Skip to content

Writing a generator as a model

Audience: language authors · ~8 min read · Prerequisites: Generators, Open Preview and multi-file generation

What it is

A language's generator can be written as a model of the Generator language: rules say when something applies, templates say what is written, and macros mark the parts of a template that vary. Because it is a model, it is edited like one: concepts, templates and labels are picked from completion lists.

Open the Generators tour sample and its model Invoicing to Core. Choose Run > Execute > Run Generator Model to generate from every model of the language the generator names.

Run > Execute > Trace Generator Model runs the same generation and opens By example: the input model on the left (each node with the rules that wrote for it), the output lines in the middle, coloured by rule, and on the right why a line looks as it does. Click an input node to light its lines; click a line to see its rule and template.

Generator models are the rules of a language

A generator model that generates from one of the project's languages is that language's generation rules: Run Generator, the multi-file generation and strukts generate use them, and the language file is not changed. A generator whose transformation has the same name as one the language stores (generate, for the text Run Generator writes) replaces it. A generator that writes code asks for the folder's trust; without it the generator is left out.

A language that still keeps its rules as data (the old Transformations section; Language settings > Generation does not mark it "From a generator model.") is moved with Tools > Typechecker > Convert Transformations to Generator Models…. Each transformation becomes a model in the project's generators folder, and its data leaves the language file. A function, files, reduce, weave or post-process rule, with its imports, becomes a code rule that carries the code unchanged. A transformation with a part a model cannot say yet stays as it is; the Messages say which.

A generator is spread over roots. Its main page holds the mapping configuration and links to the other roots; a rule and its template each have a root. Links are grouped by the stage a rule runs in. List | Table shows the rules as a read-only table to filter and group; a click on a row shows its fields below; Enter or Open goes to its root. A link opens that root in its own tab, and each root links back. + Add makes a root for the item you pick and opens it. Coverage ↗, or Run > Execute > Show Generator Coverage, opens a filterable table of the source language's concepts, their rules and, after a trace, how often each applied. Alt+Enter on a macro offers Remove macro (what it wraps stays); on selected lines, Surround with a loop or if macro; on pieces of a line, an optional or exactly-one macro.

The parts

Part What it is
Mapping configuration Names the language generated from and the one written (core, or text).
Template in a rule Alt+Enter on a rule > Write template in rule: the rule keeps its own copy of the template it names, shown under the rule line and saved as with genReduction(…):. Move template out reverses it; an indented text template stays shared.
Label A name for the output a rule made, so another rule can find it (genContext.getOutput("invoice_fn", node)).
Root mapping rule An input root of a concept becomes the root a template describes. Optionally keeps the input root.
Reduction rule While the input is copied, a node of a concept (where a condition holds) becomes what a template describes. Without a matching rule the node is copied as it is.
Weaving rule For each node of a concept, inserts a template into an output node the rule finds, before a trailing return.
Conditional root rule Once per run, when a condition on the input model holds (model.nodes(model/concept.invoice).length > 0), the output of a root template is added after what the run wrote. It has no input node, so the template is plain code. Not for a text target.
Abandon root rule Nodes of a concept (and its subconcepts) are not carried on into the output. Not for a text target.
Drop attribute rule An attribute (a node that wraps another to decorate it) is not written; the node it wraps is. Not for a text target.
Pattern rule Like a reduction, for nodes that look like an example written as the concept's own call: surcharge("#label", 0). A #name matches anything and is available to the template as the name name; _ matches anything; any other value must be equal, or compare: ">5", ">=5", "<5", "<=5", "!=5", a range "1..10", a choice "Rush|Late" (a leading = keeps the rest as plain text).
Templates Root and external templates hold code of the target language. A text template holds lines of text.
Macros Wrappers inside a template: LOOP, IF, SWITCH (cases and a default; the first case that matches writes, and a switch can be defined once, applied by name and extended), COPY_SRC (copy a node, reduced by the rules), PROP (a value as a literal), NAME (a text as a name), RENAME (every name in the wrapped code that reads an example, such as a def name or an assignment target, is written from a text), REF (a reference to the output made for another node, possibly in another model).
Code rule A rule written as code: a function or files rule that writes text, a reduce or weave rule, or the imports the code uses. The code is kept as it is.
Section A titled group of items. It only groups.
Script Core statements that run before (pre, on the input) or after (post, on the output) the generation, with model.nodes(model/concept.invoice) and model.set(node, model/concept.invoice/customer, value). The names are references: type model and / (also after a variable that holds the model) to start one, or type model/concept. and the name (the concepts are listed at once, Ctrl+Space lists them again, and after the concept's name its slots, of the language the mapping configuration reads). A reference is saved exactly like that (model/concept.invoiceLine/price), checked against the same language (an unknown name is an error on the reference, with the closest names), and runs as model.resolve("slot", "invoiceLine/price"). A name written as text, such as model.nodes("invoiceLine"), is refused. In a loop over model.nodes(model/concept.invoiceLine) a misspelt slot on the loop's variable (line.prise) is an error with the nearest slots; over an unfiltered model.nodes() a slot read says to filter first, and Alt+Enter on that error offers Fix: Filter by "invoiceLine" (one entry for each concept that has the slot), which adds the concept to the nodes() call, or Fix: Only when it is "invoiceLine", which puts the loop's statements under if line.is(model/concept.invoiceLine):. The same reads are checked on a list kept in a variable, on one item taken with first(), last() or [i], directly on the call (model.nodes(model/concept.invoiceLine)[0].prise), and on a list a def hands back with one plain return (a function that reads its own parameters or yields is not followed).
Plan Steps that run one after another: transform, checkpoint, fork, serialize. A parameter is an on/off switch with a default, or a choice written a|b|c (the first is the default); a step's when is name for a switch and name=value for a choice. A transform step's passes (a whole number, the most passes, or stable) runs its rules again over what they made until a pass changes nothing; By example lists each pass.

Expressions

Conditions, macro values and script bodies are ordinary Core code. In a rule or template, node is the input node (node.price > 0), genContext is the generation context and model the input model. These operators lower: + - * / % < > <= >= == != and or not. Anything else (//, **) is an error that names it, rather than code that would quietly mean something else. A script also knows the variables it assigns, if/else, for, while and lambdas; not try, def or class.

Two kinds of target

  • Code target (core). A template is code of the target language with macros. The macros are drawn around what they wrap, and the whole template is saved as text. After Run Generator Model or Trace Generator Model, every rule card shows how often it applied in that run (a rule that never applied says so), and a checkpoint step lists the generator's mapping labels. For a generator with a plan, By example also shows a strip of the plan's steps with the nodes before and after each and the time it took. A transform step opens to a diff of what it changed (the model's lines before and after). Select a macro and the Inspector says what it does and lists every macro, with the ones that are not built and why. The include macro writes the code of another external template where it stands (it takes no arguments, and templates that include each other are an error that names the cycle); the call macro does the same for a template with parameters: the template declares them with param lines and reads them as param.name, and the call gives each one an argument (an expression read for the current node), and a missing, unknown or doubled argument is an error that names it; the call site macro hands another node of the input to the code it wraps, so a call inside reads that node as node; an include or call of a template that does not exist is reported while you edit; the var macro names a read-only value (var line: a name and an expression read for the current node) that the code after it in the template reads as var.name, and a name defined twice or read before it is defined is an error; the label macro stores the first node its body makes under a mapping label, for the current input node, so a weaving rule or a reference finds it with genContext.getOutput(label, node) (a label the generator does not declare is a warning); the map source macro is a call site and a label in one: the wrapped code is generated for another node and the first node it makes is stored under a label for that node; the weave macro is a loop in its pull-style spelling and writes what a loop writes (weaving rules stay rules); the insert macro writes the node an expression computes, such as genContext.getOutput(label, node); the copy list macro copies every node of a list, like a loop over the list that copies each node. The lowered rules are code, so a project of your own is asked for trust, as for a project language; a shipped sample is already trusted.
  • Text target (text). A text template is lines of text with property, copy, loop and optional-part macros (an optional part, only if, is written only when a slot holds something, such as if cond after a comprehension, with an otherwise part such as set() for an empty set; only if exactly one in writes a one-item tuple's trailing comma; lines writes a text one line at a time behind a comment marker; a copy can use another concept's rule). It lowers to data, so nothing runs and nothing asks. A concept it does not cover is written by the language's own text rule; Messages lists which.

Macros in a text template are resolved while the model is lowered, so nothing runs: a value they take must be a slot of the node (node.customer) or a text, and a computed value is refused with a message that says what is allowed.

Macro What it writes in a text template
include, call The rows of another text template; a call binds its parameters to a slot or a text
var Names a slot or a text for the rows after it; writes nothing
call site The rows it wraps, with node moved to another slot of the input
rename The wrapped text with every whole word that reads the example replaced by the value
weave, insert A loop over a slot; the node a slot holds, written where the macro stands
label, map source Keep the text their body writes for a node; genInsert(genContext.getOutput("label", node.slot)) writes it again, after the rule that kept it ran
if, switch, switch use Their rows when a condition holds. A condition tests that a slot holds something (node.cond), compares a slot with a text, a number or True/False (node.quantity > 1), and joins those with and, or, not

A text target cannot use rule conditions, weaving rules, patterns, scripts that run after the generation, or a plan.

What the editor checks

The Problems view reports a rule that applies a missing template (an error), a template no rule applies, a rule for a concept the loaded source language lacks, and a rule an earlier rule makes unreachable (warnings).

Limits

  • Coverage needs the source language loaded.
  • A REF is filled in after every model is generated, so the order of the models does not matter; a label with no output for the node is an error. Its target is a reference slot of the input node: one that holds a node id, or one that holds a name, which the source language's own candidates for the slot resolve across every model (the tour's seeInvoice("Acme Ltd")). A name no node answers to is an error that says the name. In a generator with a plan it is written into the final model, checkpoints, forks and before a serialize step, and only for an output of the same model; generation is not parallel.
  • A plan parameter is a switch or a choice; free text is not a parameter, because nothing could read it.
  • NAME works where a name is used as an expression; for a declared name (def, an assignment target) wrap the code in RENAME.
  • After Run Generator Model over several models, the Theia IDE opens one Generated tab for each model, titled with its label; elsewhere the text is one tab with a header for each model.

From the command line

strukts generate-model --project-dir <dir> runs every generator model of a project over the models it generates from: the text is in the JSON, or, under --output <dir>, one file for each model it generated from. --generator <model> picks one, --param audit=on answers a plan switch, --param detail=full a choice. A generator that lowers to code needs --trust-project-code.