Standard Library
namespace meta
The compile-time view of a program that rules and macros read.
since 0.1.0-alpha.1linuxwindowswasm
Overview
When a rule matches a class, it can look at that class through these types: its name, its base types, its fields and methods, their types and parameters, and the attributes written on them. Rules use this to generate code such as serializers, validators and database mappings. Every type is given as plain text, spelled the way the source wrote it, and attributes are exposed by name together with their argument values. These types exist for rules and macros to read while the compiler expands them; ordinary program code has no use for them.
Examples
attribute Describe { }
rule describe {
match @Describe(d) on class C
inject `string describe() =>
$C.name + " has " + [ $for f in C.fields : $f.name + ":" + $f.type ].joinToString(", ");` at member of C
}
@Describe
class Point {
int x;
int y;
string label;
}
console.writeln(Point().describe());
Point has x:int, y:int, label:string
Types
- Attr — An attribute written on a field or method, with the values of its arguments.
- AttrArg — One argument of an attribute, with a slot for every primitive form.
- Class — A class that a rule has matched, as a rule sees it.
- Field — A field of a class, as a rule sees it.
- Method — A method of a class, as a rule sees it.
- Param — One parameter of a method, as a rule sees it.
Functions
parseExpr
parseExpr(string source) -> AstParse a string of source text into a single expression fragment.
This is for procedural macros, which compute a piece of code as text and return it to be compiled in place of the macro call. It runs only while the compiler expands the macro. A source string that does not parse is a compile error that shows the fragment.
Parameters
- source
- The text of one expression.
Returns
The parsed expression, as an opaque Ast.
Throws
RuntimeException- when called while the program runs instead of while it is compiled.
Examples
macro countChars(string payload) comptime {
var parts = ["0"];
for (int i in 1..payload.length()) parts = parts.add("+ 1");
return meta::parseExpr(parts.joinToString(" "));
}
int n = countChars!(`four`);
console.writeln(n);
4
See also: parseStmts
parseStmts
parseStmts(string source) -> AstParse a string of source text into a list of statements.
Like parseExpr it works only while the compiler expands code. A procedural expression
macro must return an expression, so a statement fragment returned from one is a compile
error. Calling this function in a running program throws.
Parameters
- source
- The text of the statements.
Returns
The parsed statements, as an opaque Ast.
Throws
RuntimeException- always, when called while the program runs instead of while it is compiled.
Examples
try {
meta::parseStmts("int x = 1;");
} catch (RuntimeException e) {
console.writeln(e.message);
}
meta::parseStmts() is compile-time-only
See also: parseExpr