Language authoring guide¶
This is the entry point for defining languages on struktJS. It explains the model, shows the smallest real language, and points to a page per aspect.
The model: language, concept, node¶
- A language (
Language,src/workbench/lang-class.ts) is a named set of concepts plus checks, constraints, generators and rules. It can import other languages and look up their concepts. - A concept is a node type, identified by its
headstring. It declares its slots, how it is projected in the editor, how it evaluates, what it generates, and what it checks. - A node is an instance of a concept in a model:
{ id, head, children }, with children matching the slots by position.
A concept bundles these aspects, each optional:
| Aspect | Hook | Page |
|---|---|---|
| Structure | ChildSlot, Ref, Prop fields (or child(), children(), optional(), ref(), prop()), .must() constraints |
Concepts |
| Editor and inspector | editor = this.template(...), inspector, notations, css |
Editors and projections |
| Interpreter | eval({ evaluate, vars, ... }: EvalContext) |
Evaluation and generation |
| Code generator | generate({ emit, indent, ... }: GenerateContext), reduce(...) |
Evaluation and generation |
| Validation | checks(), slot .must(), typesystem(), intentions() |
Checks, constraints and types |
| Names and flow | scope(), dataflow(), referenceScopes() |
Scope and dataflow |
| Persistence | surface() per grammar |
Persistence grammars |
Three ways to author¶
- A concept class in a plugin. A
.tsxfile whose classes extendConcept(...), inplugins/<name>/languages/. This is how every built-in language is written, and the path this guide assumes. See Plugins and devkits. - The Language tab. The in-app Language Pane edits concepts visually (structure, editor tokens, eval rules,
checks, generators) and saves the language as a
.lang.jsfile. Rule bodies written there are plain JavaScript compiled from strings. The persisted data shapes are the Zod schemas insrc/lang-schema.ts, which is the best single reference for what a persisted concept can carry..lang.kdlfiles are no longer read. - A hot-reloaded dev-plugin. A single
.ts/.tsxfile outside the repo that the running backend recompiles on change. See Plugins and devkits.
Class-authored concepts and Language Pane concepts end up as the same runtime data; a class-authored concept is both the definition and the class every node of that concept is an instance of.
The smallest language¶
plugins/lang-simplest/ is the floor example: one concept, one string property, one editor rule, one generator
rule.
import { h, Fragment, Child, Text } from "../../../src/editor-jsx.ts";
import { Prop } from "../../../src/base-concept.ts";
import { Concept, IRoot, IStatement } from "../../../src/concept-interfaces.ts";
import type { EvalContext } from "../../../src/evaluator.ts";
import type { GenerateContext } from "../../../src/generator.ts";
export class Simplest extends Concept(IStatement, IRoot) {
head = "simplest";
description = "The smallest possible language definition — one concept, one string property.";
text = Prop({ type: "string" });
editor = this.template((self) => <><Text class="kw">simplest </Text><Child link={self.text} /></>);
eval({ output }: EvalContext) {
output(this.text);
return null;
}
generate({ indent }: GenerateContext) {
return `${indent}print(${JSON.stringify(this.text)})`;
}
}
And the plugin's index.ts turns the module's exported classes into a language:
import { conceptsFromModule } from "../../../src/base-concept.ts";
import "../../lang-python/grammar/ts-parser.ts"; // its model files are Python-syntax text
import * as concepts from "./concepts.tsx";
export default {
name: "simplest",
namespace: "simplest",
displayName: "The Simplest Language",
description: "Minimal one-concept, one-property language definition.",
concepts: conceptsFromModule(concepts),
};
A model for it is just source text in the grammar the language persists with, here the universal call syntax:
simplest("hello")
For a language with expressions, a root with statements and a type check, read plugins/lang-money/ next: a file
root, a literal, a binary operator with a currency-mismatch type check, and a print statement, in about 250 lines.
What the engine asks of a language¶
The engine never looks for concepts by Core's names. A language says what its concepts mean through fields and
platform interfaces, and general code asks the Language:
| Meaning | How a concept declares it | How the engine asks |
|---|---|---|
| The model's own root node | IRoot (in Concept(...)) |
lang.fileRootHead() |
| A statement-list container | Concept(IBlock, …) |
lang.isBlock(head), lang.blockHead() |
| A variable reference | Concept(IReference, …) |
lang.isReference(head) |
| A declaration that introduces a name | Concept(IDeclaration, …) |
lang.isDeclaration(head) |
| Identifier validity of name slots | Concept(IValidIdentifier, …) |
built-in checker rule |
Has a name slot used for labels |
Concept(INamedConcept, …) |
node presentation |
| Run button in the gutter | gutterRun = true |
lang.hasGutterRun(head) |
The old roles concept array no longer carries any well-known role: no engine code reads it. It remains a free-form
list of custom tags you can attach and query with conceptsWithRole, hasRole and headForRole. Interface
conformance is transitive across extends and across interfaces that extend interfaces, and the interface list is
inherited, so a subclass of a block-like concept is a block too. If no concept in a language implements an interface,
that feature is simply absent; the engine does not guess at Python names. Full account:
Languages, plugins & devkits.
Other hooks the editor reads (operator keys, side-transformations, placement guards, traits()) are covered in
Concepts and Editors and projections.
Language-level features¶
Language imports¶
A language imports others with _importNames (resolved when the language registers). Imported concepts appear in
completion and are usable by the interpreter, but they are not listed in the importing language's own concept list in
the Language tab. Concept lookup is first-match-wins across the language's own concepts and then its imports in
declared order. Two concepts sharing a head, alias or operator key shadow each other silently, so a collision
scan runs in tests; see the "Ambiguous concept keys" section of Languages, plugins & devkits.
Aspect overlays: customizing a foreign concept¶
An importing language can change how one imported concept looks, generates, type-checks or flows, without forking the
language it comes from. Overlays affect only what getConcept() returns on the importing language; getRawConcept()
and the source language are never changed.
const overlay = new Language({ name: "overlay", concepts: [] });
overlay.importedLanguages = [coreLanguage];
overlay.setEditorOverlay("plus", [{ kind: "text", text: "[PLUS]" }]);
overlay.getConcept("plus").editor; // the overridden [PLUS] editor
coreLanguage.getConcept("plus").editor; // unchanged
setEditorOverlay(head, tokensOrFn)replaces the concept's editor; calling it again for the same head replaces the previous overlay. It takes a static token array or a(node) => tokensfunction for a per-node dynamic overlay. Either way it fully replaces the editor rather than merging with it.addEditorExtensionis the priority-ranked variant. Its optional fifth argumentwhen(node)gates the extension per node: nodes it rejects fall through to the next extension, the overlay, or the concept's own editor. Put<NextEditor/>in the extension's tokens to render that next editor in place, so an extension can decorate a base concept instead of forking it, e.g.lang.addEditorExtension("Assign", () => <><Text class="badge">!</Text><NextEditor/></>, 10, "flag", n => n.flagged). A gated extension has no node-free snapshot: completion labels and wrap triggers still read the base editor.- There is no generator overlay (
addGeneratorOverlayis gone). To write a concept of an imported language differently, give your language a rule for that concept in itsgeneratetransformation: a rule of the language itself beats the imported language's rule (plugins/lang-entitieswrites Core'scommentas a docstring this way). setTypesystemOverlay(head, { infer, check, overloads, walk })andsetDataflowOverlay(head, { analyze })do the same for those aspects.clearOverlays(head)removes all overlays for that head.
A real use is plugins/lang-jsgrammar/, whose onActivate(lang) calls lang.setTypesystemOverlay("plus", ...) to
accept JavaScript's string/number mixing. Overlays belong in onActivate, which runs after imports resolve.
Interface concepts¶
An abstract concept named I… is a structural contract that declares required slots. Any concept listing it among its
interfaces must have a slot of the same name for each one, otherwise the Language tab reports an error.
Interface concepts have no editor and are hidden from completion. In Core, iBinaryOp declares lhs and rhs, and
the abstract binary-operator base implements it. The platform interfaces IReference, IDeclaration, IBlock,
INamedConcept, IValidIdentifier and IEmpty (src/platform-interfaces.ts) are built into the engine and resolve
under every language without registration.
Notations¶
notations() returns alternate { name, editor } layouts for the same node. When a concept has at least one, a small
badge on the node cycles through them, and the choice is stored per node. A notation can be limited to particular
persistence grammars with grammars: [...]: Core's comment has a /* ... */ notation offered only under the
JavaScript grammar, because it has no valid Python surface form.
Migrations¶
When a language changes shape, apply a batch of structural operations to it, and to saved models. In the Explorer,
right-click a language and choose Migrate.... Operations are a JSON array using these op values
(OPERATION_TYPES in src/migrations.ts): renameConcept, renameSlot, addSlot, removeSlot, retypeSlot, renameLanguage,
setCategory, setDescription, transform.
[
{ "op": "renameConcept", "from": "OldName", "to": "NewName" },
{ "op": "renameSlot", "concept": "NewName", "from": "value", "to": "expr" }
]
Because nodes are positional, only renameConcept, addSlot, removeSlot and retypeSlot change existing model
ASTs; the others are metadata-only.
retypeSlot ({ "op": "retypeSlot", "concept": "Price", "slotName": "amount", "kind": "number" }) changes a property slot's kind
(string, name, code, number, boolean) and converts each saved value where it reads faithfully as the new kind ("12" to 12,
"true" to true). A value that does not convert leaves that slot empty; the Migrate… preview counts those values before you apply.
Scripted steps. When a migration has to look at a value (cents to euros, splitting a literal into value and unit),
use transform: { "op": "transform", "concept": "Price", "description": "cents to euros", "body": "return api.make('Price', [node.children[0] / 100]);" }.
body is the body of function (node, api). It runs once per node of each saved model, children before parents, on
nodes whose head is concept (every node when omitted), after the step's structural operations have been applied to
that model. Return a node or a string, number or boolean to replace the node, or nothing to keep it. api offers
isNode(x), make(head, children) and empty(). A transform changes saved models only, never the language itself, and
a script that throws or returns something else fails the load of that model with the step's description in the
message instead of producing a half-migrated tree. The script lives in the language's .lang.js, so it is covered by
the same workspace-trust prompt and is not sandboxed.
In the Migrate dialog, the Scripted step section builds this line for you (concept, description and a multi-line
body, JSON-escaped) and appends it to the operation list, so scripted and structural steps can share one migration.
To apply a language's history to a project's files on disk, outside the IDE, use strukts migrate
(CLI).
In a bundled plugin. A plugin language declares version: 2 and migrations: [{ toVersion: 2, operations: [...] }] in its descriptor
(languages/index.ts); plugins/lang-devices/ is the worked example (bare mm/gsm numbers to typed quantities, shipped with a sample root
still saved by v1). Write each scripted step to be idempotent, and remember that a bare number read from a saved file is a Literal node
around the number (api.isNode(x) && x.head === 'Literal'), not a number.
Newer files are refused. A model whose # langversion: is higher than the installed language's version is not
opened (the project load reports "saved with language X vN, but vM is installed"); nothing is rewritten.
Reference slots¶
A slot declared with Ref({ target: "symbol" }) stores the name of another declaration rather than a nested subtree.
Pair it with referenceScopes() to restrict valid targets; see Scope and dataflow.
Where to go next¶
Concepts, then Editors and projections, then whichever of evaluation, checks, scope or persistence your language needs. Package it with Plugins and devkits. The generated API reference documents every signature.