Skip to content

Evaluation and generation

A concept can run (eval), emit text (generate) or transform the model into another model (reduce). The three are independent; implement only what your language needs.

Evaluation

eval(context) runs when a program executes. It is dispatched on the live node, so this.someSlot reads that node's real child. The single argument is an EvalContext (src/evaluator.ts); destructure what you use. evaluate(child) recursively evaluates a child in the same environment and returns a promise.

export class MoneyAdd extends Concept(IExpression) {
    head = "moneyAdd";
    lhs = ChildSlot({ type: IExpression });
    rhs = ChildSlot({ type: IExpression });

    async eval({ evaluate, log }: EvalContext) {
        const a = await evaluate(this.lhs);
        const b = await evaluate(this.rhs);
        if (a.currency !== b.currency) {
            log("error", `Currency mismatch: cannot add ${a.currency} and ${b.currency}`);
            return { amount: NaN, currency: null };
        }
        return { amount: a.amount + b.amount, currency: a.currency };
    }
}

(From plugins/lang-money/languages/concepts.concept.js.)

Rules to know:

  • Everything is async. The input() builtin shows a modal and awaits the answer, so every eval that calls evaluate must be (or return) an async function, and must await child evaluations.
  • The context members all come from the environment shared by the whole run. vars is the current variable scope (read and write it for bindings; a nested scope is typically prototype-chained to its parent). output(text) is the sink behind print(); input(prompt); log(level, text) with level "info", "warn" or "error"; outputResult(label, value) and outputHtml(html) for structured and HTML output; call(closure, args) invokes a closure and evalIn(node, targetEnv) evaluates a subtree in another environment; lang is the active language; and model(node) gives a read-only ModelNode query (see Model API). Any mutating ModelNode call throws during evaluation because no editor is bound. env is the whole environment object, for a helper that takes one (bindLoopVar(slot, value, env)), a { ...env, vars } copy, or state a host stashed on it; prefer the named members.
  • The context is also callable: ctx(child) is evaluate(child). That keeps older eval(ev, env) concepts working next to converted ones, and is what you pass to a helper that wants "the evaluator" as a value.
  • A concept with no eval evaluates to a constant. An unknown head falls through to function-call dispatch (builtins, then closures bound in the environment).
  • A control signal such as return is implemented by throwing ReturnSignal; loops catch BreakSignal and ContinueSignal (src/meta/eval-vm.ts).

The three shapes of an eval rule

Evaluator#evalUser (src/evaluator.ts) accepts, in this order:

  1. A native method on a BaseConcept class, as above. This is the preferred path.
  2. A slot-thunk function eval(...slotThunks, ev, env) (positional, as compiled from a Language Pane body) on a plain-data concept (one added at runtime with Language#setConcept, or authored in the Language tab): one zero-argument async thunk per declared slot, in slot order. A variadic slot's thunk resolves to an array and carries .nodes, the raw children.
  3. A declarative EvalVM tree: a small AST whose heads are VM opcodes (Const, EvalChild "slot", EvalChildren, Var, SetVar, Seq, If, While, For, Foreach, Eq, Lt, And, Or, AddAll, DefineFunction, ...), which is what the Language tab's Eval section edits. The full handler vocabulary is in the head comment of src/meta/eval-vm.ts. These opcode heads are not any language's concepts, so such trees are always persisted in the schema-less KDL form. Note that DefineFunction evaluates its body eagerly when given a raw rule tree, so read its doc comment before using it.

Running a program from code

const ev = new Evaluator(lang, { output: (s) => lines.push(s) });
await ev.evaluate(ast);              // pass a previous `vars` object to persist bindings across runs

EvaluatorOptions supplies output, input, log, outputResult, outputHtml and a cancellation token. In the IDE, the Run command does this against the open root.

Host execution

A language can declare supportsHostExecution and a hostExecutorId (Core uses "python") so the IDE can run the generated or saved text with a real interpreter on the host instead of the in-process evaluator. See core.devkit.json in plugins/lang-core/ for the fields, and Security and privacy for what that implies.

Text generation

generate(context) returns the text for one node. runGenerator(root, lang) calls it over the tree; the IDE's Run Generator command shows the result. The argument is a GenerateContext (src/generator.ts).

generate({ emit, indent }: GenerateContext) {
    return `${indent}print(${emit(this.value)})`;
}
  • emit(child) generates a child at this node's indentation; emit(child, deeper) passes a different indentation string for a nested block. inline(child) generates a child with no indentation at all, for a sub-expression in the middle of a line.
  • indent is this node's own indentation string. You prepend it to each line you emit; the generator does not.
  • nav(node) returns a chainable AstNav (.parent(), .ancestors(), .prevSibling(), ...) and model(node) the fluent ModelNode, for the rare output that depends on tree position. Treat both as read-only. lang is the active language.
  • The context is callable too (ctx(child, indent)), so a helper that takes "the generator" as a value gets the whole context: generate(ctx: GenerateContext) { return genIfChain(ctx, this.cond, ctx.indent); }.
  • A language can also hold generator rules as data (generators: [{ concept, body }]), compiled from a body string with positional parameters (gen, lang, indent, nav, model). The persisted shapes are in src/lang-schema.ts.

Text rules as data: transformations

A language can also hold text rules as plain data, in transformations: [{ name, target: "text", extension, rules: [{ concept, template }] }] (a template is { strings, holes }, built once with compileTemplate((self, t) => t`${self.name} = ${self.value}`) from src/text-output/template-ir.ts; each, opt and plain values are the other holes). The layout is the text language's: a block template (first line blank) is dedented, a multi-line value is indented to its hole, an absent optional part leaves no blank line.

  • The transformation named generate is the language's default: every normal generation (Run Generator, strukts generate, verify) renders a node that has a rule with the rule and every other node with its generate hook, so a language can move one concept at a time. A rule that fails is reported like a hook that throws.
  • Any other name is run alone with strukts generate --project <p> --export <name>, which writes <root>.<extension> and lists under notes the concepts it had no rule for.
  • A rule reading a slot its concept does not have fails with the slots there are.
  • A rule can be code instead of a template: { concept, fn({ emit, indent }) { ... } } is called exactly as a generate() hook was (the context first, this the concept's instance, then lang, indent, nav, model), so a hook moves in verbatim. It is saved as its parameter list and body and compiled when the language loads; a language that ships in the repository keeps the real function (its module imports and helpers), and the source wins over a saved copy.
  • A rule can write files: files(node, lang) returns the file text or a list of { path, content } (paths stay inside the output folder). It replaces emitFile in a hook. A rule for concept: "@root" is the rule of the root of the run, whatever its concept; in a transformation with a name other than generate it is the whole named output (strukts generate --export <name>), what exporters used to be. There is no separate exporters list any more: a named output IS a transformation with a root files rule.
  • A root that is one output file (the text language's TextFile) says so with the outputFile trait (traits() { return { outputFile: { pathSlot: "path" } }; }); a model of such roots is written as those files.
  • A rule is byte-for-byte what the hook it replaced printed. indented: true puts the caller's indentation before the first line (the hook began with ${indent}), ${self.child.indented()} renders a child at the caller's indentation instead of at column 0 (emit(child)'s default), x.indented(" ") adds a literal to it, and self.items.each((x, t2) => t2`${x}`, { join: "\n" }) is items.map(emit).join("\n"). A rule applies to the concept of the language that declares it, so two languages using one head for different concepts do not mix.

Model-to-model: reduce, weave, postProcess

For a real compiler-style transformation, runGeneratorPipeline(root, lang) runs: root mapping and reduction (one recursive pass), then weaving rules, then a single whole-tree postProcess hook. Output is a new AST, not text.

  • reduce(self, ctx) is the preferred spelling: self.<slot> is a handle of that slot (a misspelled slot throws, naming the concept's slots). A handle is callable and has copy() (the slot reduced: one node, or an array for a list slot), each(fn) / weave(fn) (for a list slot, fn(item, index) for every child; an array result is spliced in, null leaves nothing), asProperty() (the raw scalar, a property of the output rather than a node) and node/nodes (the raw children, for inspecting a flag); an item exposes its own concept's slots too (h.event.asProperty()). ctx is { reduce, lang, genContext, node }. A rule is read as this form when its first parameter is named self. A handle's value goes straight into a template(lang) hole (src/model-template.ts), so a lowering is written in the target's own text: reduce(self) { return templates.core`add(${self.lhs.copy()}, ${self.rhs.copy()})`; } (templates.<language> looks the language up by name when the template runs; the template is parsed by that language's own parser, so it has the tree a saved and re-read model has).
  • A language-level reduction (a rule for a concept the language does not own, such as the Doc Extractor's rule for Core's comment) is a reduce function on a rule of one of the language's transformations: { concept: "comment", reduce(self, ctx) { return ctx.build("DocNote", self.text.asProperty()); } } (ctx.build is the node constructor, which a function saved as text has no import for). It is persisted as reduceParams + reduceBody, shown in the Transformations section as a "model-to-model" rule, and wins over the concept's own reduce and over the older reductions entries. The slots of a concept the language does not define are read from the class registry.
  • The template view. A model-to-model rule whose function is return ctx.templates.<language>...; (the template is the whole returned value) has a Code | Template switch in Language settings > Transformations. Template shows it as a projectional editor of the TARGET language (<language> is the one the template is written in): the template's text is parsed with each ${...} hole replaced by a placeholder, and every placeholder becomes a macro chip: ${ copy self.lhs } for self.lhs.copy(), ${ property self.name } for self.name.asProperty(), ${ for each it in self.items: ... } for self.items.each((it) => ctx.templates.<language>...) (its body is itself a template of target nodes), and ${ code } for any other expression, ${ only if <condition>: ... } for <condition> ? ctx.templates.<language>...: null (the body is a template of target nodes; the condition is code, and a conditional with any other else stays a code hole). A chip's source, item and condition are drawn as bare text, not as quoted strings. Editing the tree writes the text back and applies it; an unedited template is never rewritten. A template that cannot be a tree (a hole inside a name, text that does not read as the target language) stays code and the view says why. ctx.templates is templates of src/model-template.ts. Quick fixes: Alt+Enter on a node of the template offers Repeat for each… and Only if…, which wrap the node (or, on a bare expression, the statement it stands for) in the chip after asking for the list slot or the condition; the file root is never wrapped, and a language without the chips never sees them (traits().wrapIntention.anyNode, src/editor/intentions.ts).
  • The older spellings are gone (round 39, decided with the user): reduce(...slotThunks, reduce, lang, genContext, node) on a concept is reported once and the node copied through, a language-level reductions entry is kept in the file but not run, and the $LOOP$/$IF$/$SWITCH$/$COPY_SRC$/... helpers with their macros bundle no longer exist. Write the rule as reduce(self, ctx) (above) or as a model-to-model rule of a transformation; the language settings' Health section lists what still uses an old form.
  • A weaving rule is a rule of a transformation ({ concept, weave(srcNode, genContext, lang, nav, node) {...} }, persisted as weaveParams + weaveBody), keyed by source concept; it injects fragments that do not map from a single node, after reduction. A concept may have a reduce rule and a weave rule in one transformation. Language#weavingRules collects them (the older weavingRules field of a language, written as text, is folded into the model-to-model transformation when the language loads). A transformation also has one post-process (postProcess(root, lang, node) {...}, persisted as postProcessParams + postProcessBody), run once over the whole output after reduce and weave.
  • The generator plan (generatorPlan, steps transform, checkpoint, fork, serialize) is edited as rows in Language settings > Transformations, and serialize prints through kdl, text or a named transformation. See the Generators tour sample (samples/generators-tour) for every kind of rule, a library of the project, a concept's own reduce(self, ctx), a weave rule, a post-process and a plan.
  • A bundled rule's source. A bundled function rule carries its source as written beside it (__src, attached by scripts/rule-sources.mjs inside the concept-js Vite plugin), because Function#toString is the built code (minified in a production bundle); the rule cards show that text. The same step lists, per function, the names its body uses that belong to the plugin's own module (__src.free, e.g. { fn: ["genOperand"] }; absent when there are none): a compiled body runs in the global scope, so "Customize this rule" (src/workbench/customize-rule.ts) copies a bundled function rule into a project language only when that list is empty (about 64% of the bundled function rules).
  • Per-project generator overlay (src/generator-overlay.ts, saved by workbench/project-generator-overlay.ts as generator-overlay.json at the project root: { "version": 1, "languages": { "<Language#qualifiedName>": { "<transformation>": [rule, ...] } } }, a rule in its persisted form: template, or params + body and the other *Params/*Body pairs). It is data outside the Language: a bundled language is one global object, so nothing is changed in it. collect in src/transformation-rules.ts applies the overlay per language at that language's place in the import walk (applyOverlay: the overlay's rule replaces that language's rule for the same concept, so a derived language's own rule still beats an overlay of the language it imports), and ruleInterceptor consults it first on the class fallback (overlayRuleOfClass, through setOverlayLanguageResolver, which lang-registry.ts registers), never through defaultRuleByClass. Which overlay a generation uses: withGeneratorOverlay(scope, fn) (scope = an overlay, { ownerId } or null for the bundled rules; fn must be synchronous, restored in finally), else the default owner provider the app registers (src/index.tsx: the active document's project) and the CLI registers per loaded project (tools/strukts-cli/lib/project.mjs). An async caller captures currentGeneratorOverlay() before its first await (generateText does) and hands it to the check worker in the generate message, where it is the scope of that one generation; a generation with a function-rule overlay is sent to the worker by every caller of generateText/generateTextMaybe (the Generated Code tab, Run Generator, Open Preview), while the direct callers of runGenerator (Rebuild Model, Verify, the plan, the Workbench API) run its function on the page thread. The worker's evaluate, conceptTests and refactor messages carry it too (overlay, run with withGeneratorOverlayExclusive, which is only safe because the worker handles one message at a time), and loadProjectFromFiles reads it. Not covered: a function rule cannot use the project's ruleImports.
  • genContext.label(name, inputNode, outputNode) and .get(name, inputNode) look up the output an earlier rule produced for an input node. One context is threaded through a whole run.
  • Body-string weave and post-process rules use a different calling convention, because a new Function body has no imports: weave is (srcNode, genContext, lang, nav, node) and post-process is (root, lang, node). The current node is srcNode because node is the AST constructor you need to build output.
  • A reduce rule may return ABANDON_INPUT (drop the input from its container) or DISMISS_TOP_RULE (copy it through as if no rule matched), both from src/generator-macros.ts, which keeps only those and createGenContext.
  • A plan ends with an explicit serialize step, { kind: "serialize", as: "kdl" | "text", transformation?: "<name>" }, which says how the model it ends in becomes output: a KDL dump (the default, and what a plan without the step gets), the language's generated text, or the output of a named transformation (its files headed by their path). It may also end a fork; a later transform makes an earlier serialize stale. A KDL dump is written in the plan's own language; text and a transformation in the language the model is in then.
  • A transform step may name one transformation, { kind: "transform", target, transformation?: "<name>" }: only that model-to-model transformation's reduce rules, weave rules and post-process run (runGeneratorStep(root, lang, genContext, name)). A step with no name runs every model-to-model rule and the first post-process. A name the language does not have, or one that only writes text, is an error naming the language and the transformation. A fork branch can name one too.
  • generatorPlan composes steps (transform, checkpoint, fork, serialize) across a language and its imports (src/generator-plan.ts).

Full detail is in Generator.

Previews and writing files

  • A language whose default generate transformation has extension: "html" says its generator output is a self-contained HTML and JavaScript document, not source text. Open Preview then runs it in a sandboxed <iframe sandbox="allow-scripts"> (no allow-same-origin). Escape every dynamic string you embed: re-escape < inside <script> literals (JSON stringification does not), and entity-escape text placed as HTML. plugins/lang-robot/languages/preview-runtime.js is the worked example.
  • generateModel and generateProject (src/generator-multi-file.ts) run the generator over every root of a model or every model of a project and write files. A model's model.json may set output; otherwise files go in a generated/ folder inside the model's folder. The Rebuild variants delete that folder first.

Testing your rules

Build a small AST with node(...) or parseSurface, run Evaluator#evaluate or runGenerator, and assert on the output. tests/test-evaluator.mjs and tests/test-generator.mjs show the pattern. The sample smoke tests in npm test also evaluate every bundled sample, so a broken eval in a plugin shows up there. See Testing.

Paste as template

templateToGeneratorBody(text, options?) (src/generator-template.ts) turns a block of example output into the body of a text generator. In the pasted text, {{slot}} becomes a hole filled with gen(this.slot, indent) (the compiled form of emit), and a pair of lines {{#each slot}} / {{/each}} repeats the lines between them once per element, with {{.}} as the element. Indentation is analysed once: the unit (a tab, or the smallest space step) is detected, and every line is emitted as the caller's indent plus its depth in units, so the generated text nests correctly inside another generator. Pin the unit, the line ending or the trailing newline with the indentUnit, eol and trailingNewline options. Unbalanced {{#each}} markers throw. Compile the result with compileGenerator.

In the Language Pane, a concept's Generate section has a Paste as template… button under the code box. It opens a text area: paste the example output, mark the parts that vary with {{slot}} and {{#each slot}} / {{/each}}, and press Create generator from template. The generated body replaces the concept's generate body (the box above shows it, and you can edit it further like any other body). A template with an unclosed {{#each}} reports the error and changes nothing.