Skip to content

Source generator: quote { … }

1 min read

Make a small source generator that turns custom quote notation into a string while your program is built. Follow its registration steps before running the app.

You need three files in one project.

dream.toml — register the generator:

[[generators]]
path = "gen.dream"

gen.dream — the generator:

module gen;

import system.codegen;

@generator
@syntax_block
public fun quote(ctx: GenContext): void {
    for (let block in ctx.syntax_blocks()) {
        ctx.replace(block, as_dream_string(block.body.trim()));
    }
}

fun as_dream_string(s: string): string {
    let escaped = s.replace("\\", "\\\\").replace("\"", "\\\"");
    return "\"" + escaped + "\"";
}

src/main.dream (or app.dream):

import system;

fun main() {
    System.println(
        quote { Hello generators }
    );
}
Hello generators
dreamer run
# in this repo:
dream run sample/generators/quote/app.dream
  • @syntax_block — Dream finds every quote { … } block; the introducer is the function name.
  • ctx.replace — swap that site for ordinary Dream source before the rest of the file is checked.

Bigger samples: html, dto. Reference: Source generators, CodeBuilder.