A context bundles macros, constants, words, and other declarations into an isolated namespace. It is the primary mechanism for creating domain-specific languages (DSLs) in Zith.
A context is activated with use, either scoped to a block or globally (one active per category at a time).
use SQL QueryBlock {
SELECT * FROM users WHERE id = :id
}
use SQL; // global activation — replaces previous context
Macros and words should ideally live inside a context block. Activating them globally is possible but discouraged — similar to using namespace std; in C++.
// Preferred
use SQL QueryBlock {
// SQL words and macros active only here
}
// Discouraged
use SQL; // pollutes the rest of the file
context WebApp {
// Macros scoped to this context
macro @getParam(name) { request.params[name] }
// Constants
const VERSION = "1.0";
// Custom keywords
macro @async { /* async handling */ }
}
// Activate in a block
use WebApp {
let version = VERSION;
let param = @getParam("name");
}
// Outside, WebApp syntax is not available
All named blocks in Zith may receive a context. Contexts can be nested:
use Web {
use Database {
// Both Web and Database syntax available
}
}
Tag macros let you define XML/HTML-like syntax inside a context. They expand at compile time into function calls.
context HTML {
tag macro div(content) { "<div>" + content + "</div>" }
tag macro span(content) { "<span>" + content + "</span>" }
tag macro a(href: string, content) {
"<a href=\\"" + href + "\\">" + content + "</a>"
}
}
use HTML { <div> <span>Hello</span> <a href="/">Home</a> </div> }
// Expands at compile time to:
// "<div><span>Hello</span><a href=\"/\">Home</a></div>"
Tag macros are pure compile-time expansions — no runtime parsing, no injection vulnerabilities. The arguments are type-checked Zith expressions.
See also: Spec: Contexts
Related: Macros | Type System