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 everyevalthat callsevaluatemust be (or return) an async function, and mustawaitchild evaluations. - The context members all come from the environment shared by the whole run.
varsis 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 behindprint();input(prompt);log(level, text)with level"info","warn"or"error";outputResult(label, value)andoutputHtml(html)for structured and HTML output;call(closure, args)invokes a closure andevalIn(node, targetEnv)evaluates a subtree in another environment;langis the active language; andmodel(node)gives a read-onlyModelNodequery (see Model API). Any mutatingModelNodecall throws during evaluation because no editor is bound.envis 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)isevaluate(child). That keeps oldereval(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
evalevaluates to a constant. An unknown head falls through to function-call dispatch (builtins, then closures bound in the environment). - A control signal such as
returnis implemented by throwingReturnSignal; loops catchBreakSignalandContinueSignal(src/meta/eval-vm.ts).
The three shapes of an eval rule¶
Evaluator#evalUser (src/evaluator.ts) accepts, in this order:
- A native method on a
BaseConceptclass, as above. This is the preferred path. - 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 withLanguage#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. - A declarative
EvalVMtree: 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 ofsrc/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 thatDefineFunctionevaluates 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.indentis this node's own indentation string. You prepend it to each line you emit; the generator does not.nav(node)returns a chainableAstNav(.parent(),.ancestors(),.prevSibling(), ...) andmodel(node)the fluentModelNode, for the rare output that depends on tree position. Treat both as read-only.langis 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 insrc/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
generateis 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 itsgeneratehook, 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 undernotesthe 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 agenerate()hook was (the context first,thisthe concept's instance, thenlang, 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 replacesemitFilein a hook. A rule forconcept: "@root"is the rule of the root of the run, whatever its concept; in a transformation with a name other thangenerateit is the whole named output (strukts generate --export <name>), whatexportersused to be. There is no separateexporterslist any more: a named output IS a transformation with a rootfilesrule. - A root that is one output file (the
textlanguage'sTextFile) says so with theoutputFiletrait (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: trueputs 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, andself.items.each((x, t2) => t2`${x}`, { join: "\n" })isitems.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 hascopy()(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,nullleaves nothing),asProperty()(the raw scalar, a property of the output rather than a node) andnode/nodes(the raw children, for inspecting a flag); an item exposes its own concept's slots too (h.event.asProperty()).ctxis{ reduce, lang, genContext, node }. A rule is read as this form when its first parameter is namedself. A handle's value goes straight into atemplate(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 areducefunction on a rule of one of the language's transformations:{ concept: "comment", reduce(self, ctx) { return ctx.build("DocNote", self.text.asProperty()); } }(ctx.buildis the node constructor, which a function saved as text has no import for). It is persisted asreduceParams+reduceBody, shown in the Transformations section as a "model-to-model" rule, and wins over the concept's ownreduceand over the olderreductionsentries. 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 }forself.lhs.copy(),${ property self.name }forself.name.asProperty(),${ for each it in self.items: ... }forself.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.templatesistemplatesofsrc/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-levelreductionsentry is kept in the file but not run, and the$LOOP$/$IF$/$SWITCH$/$COPY_SRC$/... helpers with theirmacrosbundle no longer exist. Write the rule asreduce(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 asweaveParams+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#weavingRulescollects them (the olderweavingRulesfield 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 aspostProcessParams+postProcessBody), run once over the whole output after reduce and weave. - The generator plan (
generatorPlan, stepstransform,checkpoint,fork,serialize) is edited as rows in Language settings > Transformations, andserializeprints throughkdl,textor a named transformation. See the Generators tour sample (samples/generators-tour) for every kind of rule, a library of the project, a concept's ownreduce(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 byscripts/rule-sources.mjsinside the concept-js Vite plugin), becauseFunction#toStringis 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 byworkbench/project-generator-overlay.tsasgenerator-overlay.jsonat the project root:{ "version": 1, "languages": { "<Language#qualifiedName>": { "<transformation>": [rule, ...] } } }, a rule in its persisted form:template, orparams+bodyand the other*Params/*Bodypairs). It is data outside theLanguage: a bundled language is one global object, so nothing is changed in it.collectinsrc/transformation-rules.tsapplies 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), andruleInterceptorconsults it first on the class fallback (overlayRuleOfClass, throughsetOverlayLanguageResolver, whichlang-registry.tsregisters), never throughdefaultRuleByClass. Which overlay a generation uses:withGeneratorOverlay(scope, fn)(scope = an overlay,{ ownerId }ornullfor the bundled rules;fnmust be synchronous, restored infinally), 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 capturescurrentGeneratorOverlay()before its firstawait(generateTextdoes) and hands it to the check worker in thegeneratemessage, where it is the scope of that one generation; a generation with a function-rule overlay is sent to the worker by every caller ofgenerateText/generateTextMaybe(the Generated Code tab, Run Generator, Open Preview), while the direct callers ofrunGenerator(Rebuild Model, Verify, the plan, the Workbench API) run its function on the page thread. The worker'sevaluate,conceptTestsandrefactormessages carry it too (overlay, run withwithGeneratorOverlayExclusive, which is only safe because the worker handles one message at a time), andloadProjectFromFilesreads it. Not covered: a function rule cannot use the project'sruleImports. 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 Functionbody has no imports: weave is(srcNode, genContext, lang, nav, node)and post-process is(root, lang, node). The current node issrcNodebecausenodeis the AST constructor you need to build output. - A
reducerule may returnABANDON_INPUT(drop the input from its container) orDISMISS_TOP_RULE(copy it through as if no rule matched), both fromsrc/generator-macros.ts, which keeps only those andcreateGenContext. - A plan ends with an explicit
serializestep,{ 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 afork; a latertransformmakes an earlierserializestale. A KDL dump is written in the plan's own language; text and a transformation in the language the model is in then. - A
transformstep 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. Aforkbranch can name one too. generatorPlancomposes 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
generatetransformation hasextension: "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">(noallow-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.jsis the worked example. generateModelandgenerateProject(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'smodel.jsonmay setoutput; otherwise files go in agenerated/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.