Code that runs at compile time
Weaver’s compiler can run Weaver. Code marked meta runs while the
program compiles, with the same syntax, types and libraries: it computes
constants, and writes code from the program’s types. There is no
reflection at run time; what would need it is generated beforehand.
Constants
Section titled “Constants”A meta val is computed at compile time and stored in the program:
import weaver.io.print
meta fn table(n: Int): Int[] { var squares: Int[] = [] for i in 0..n { squares.push(i * i) } return squares}
meta val Squares = table(8)
fn main() { print("${Squares[7]}")}49A meta fn runs only at compile time. A function parameter marked meta
is known at compile time too, and the function is specialized for each
value; meta for unrolls a loop:
import weaver.io.print
fn power(x: Int, meta n: Int): Int { var r = 1 meta for _ in 0..n { r *= x } return r}
fn main() { print("${power(2, 10)}")}1024power(2, 10) compiles to ten multiplications, without a loop.
Generating code: quotes
Section titled “Generating code: quotes”quote { … } is a piece of code, a value that meta code builds; ${…}
inside it splices another value in. An annotation, @name, calls a meta
fn on the declaration it precedes. This one rewrites a function so that it
prints its arguments:
import weaver.io.print
meta fn trace(f: FnDecl): FnDecl = f.withBody(quote { print("→ ${${f.name}}") ${for p in f.params { quote { print(" ${${p.name}} = ${${p.expr}}") } }} ${f.body}})
@tracefn area(w: Int, h: Int): Int = w * h
fn main() { print("${area(3, 4)}")}→ area w = 3 h = 412Deriving from a type
Section titled “Deriving from a type”A meta fn receives types as values: t.fields are the fields of a record,
each with its name and type. That is how #Eq, #Show and the
derivations of the libraries are written. This one adds a describe
method to a record:
import weaver.io.print
meta fn describe(t: Type): Decls = quote { impl ${t} { fn describe(self): String { var out = ${t.name} ${for f in t.fields { quote { out = out + " ${${f.name}}=${self.${f.name}}" } }} return out } }}
@describetype Server = { host: String, port: Int }
fn main() { print(Server{host: "localhost", port: 8080}.describe())}Server host=localhost port=8080wv expand main.wft shows the code an annotation generated, and an error
in it is reported at the line of the quote that wrote it.
The libraries rely on this: #Json in weft/json writes a decoder and an
encoder from a type, #Cli in weft/cli a command line parser with its
help, #Rest in weft/rest an HTTP router and its client, all on the
registry. The
meta-programming chapter of the reference
has the whole API.