Skip to content

Authoring concepts

A concept is a class declared with Concept(...) (src/concept-interfaces.ts), which extends BaseConcept (src/base-concept.ts). The class is both the concept's definition (harvested once into metadata) and the runtime class of every node of that concept. This page covers structure and identity; the aspects (editor, eval, checks, ...) have their own pages.

Anatomy

import { h, Fragment, Children, Text } from "../../../src/editor-jsx.ts";
import { ChildSlot } from "../../../src/base-concept.ts";
import { Concept, IExpression, IOperator, IRoot } from "../../../src/concept-interfaces.ts";
import type { EvalContext } from "../../../src/evaluator.ts";
import type { GenerateContext } from "../../../src/generator.ts";

export class Plus extends Concept(IExpression, IOperator) {
    description = "Variadic addition: numbers or string concatenation.";
    alias = "+";
    operator = { key: "+", kind: "variadic", precedence: 4 } as const;
    args = ChildSlot({ type: IExpression, cardinality: "2..n" });

    editor = this.template((self) => <Children link={self.args} sep={<Text class="op"> + </Text>} />);
    async eval({ evaluate }: EvalContext) {
        const vals = await Promise.all(this.args.map((a: any) => evaluate(a)));
        return vals.reduce((a: any, b: any) => a + b, 0);
    }
    generate({ emit }: GenerateContext) {
        return this.args.map((a: any) => emit(a)).join(" + ");
    }
}

(Abridged from plugins/lang-core/languages/concepts-operators-arithmetic.concept.js. The real concept also declares surface(), typesystem() and intentions().)

Four things carry the whole API:

  • Concept(IExpression, IOperator) names what the concept is. An interface that requires members (IOperator requires operator) makes a missing or mis-shaped member a compile error, and the same check runs again when the concept loads, so a JavaScript concept fails with a clear message too.
  • editor = this.template((self) => …) is the one place a concept's look is written. self.args is the slot's handle (identity), while this.args is the value (used in eval/generate).
  • Context objects. Every hook receives one destructurable object of named, typed members instead of positional parameters (eval({ evaluate, vars }: EvalContext), check({ node, report }: CheckContext)). See Hook contexts.
  • Data, not hooks, for declarations. The operator spec, wrapper spec and flag words are plain data members or JSX elements, so the Language Pane can read, show and persist them.

Identity and description fields

Field Meaning
head The concept's stable string identity; every node carries it. Matched by the checker, generator, persistence and most of the engine. If omitted, it is derived from the class name with the first letter lowercased; declare it whenever you want something else (the Ts* family keeps its PascalCase heads).
interfaces Concept(IExpression) / Concept(IStatement) decide which slots accept the concept and how the completion menu groups it. There is no separate category field to keep in sync.
completionGroup Optional finer completion-menu section (for example "math").
description One-line summary shown in completion and the Language tab.
shortDescription Terse (up to about six words) phrase shown inline in the completion row; the full description then shows only in the preview.
deprecated A message (what to use instead) that marks the concept deprecated: every node of it gets the warning "X is deprecated: message", and the completion menu shows it struck through and after the others of its category. Empty (the default) means not deprecated.
icon, color A single glyph and a palette colour name (red, orange, yellow, green, teal, blue, purple, pink, gray) shown beside the concept's name in the Explorer and the completion menu. Each colour is mixed with the theme's text colour, so it stays readable on every theme.
alias Short text used by completion matching, such as "+" or "elif". A single-character non-alphanumeric alias that has no operator key cannot be typed into an empty cell, and npm run lint:concepts flags it.
isAbstract Template-only concept, hidden from completion.
css, icon Concept-scoped CSS and an inline SVG for tree views. See Editors and projections.

Language names follow the plugin folder: plugins/lang-money/ is the language money (a test, tests/test-language-name-convention.mjs, pins that and lists the one exception). The name stays an explicit line in the plugin's index.ts because it is the persisted identity.

Slots

Slots are class fields assigned from three helpers. At construction the field is replaced by an accessor over the node's children, so this.args reads the real child (or an array for a variadic slot).

Helper Declares
ChildSlot({ type, cardinality, default, ... }) A nested child node. type is the slot kind (a string, or an interface value such as IExpression), default "expression".
Prop({ type, cardinality, default, multiline, placeholder }) A persisted scalar (not a nested node). type is a value kind such as "name", "string", "number", "boolean"; default "string". placeholder makes it optional text: while the value is empty ("" or unfilled) the cell draws that word (e.g. "none") dimmed and clicking it lets you type.
Ref({ target, cardinality }) The name of another declaration, resolved in scope rather than embedded. target defaults to "symbol".

The same slots can be written positionally, which reads better when there is little to say:

Positional Same as
child(IExpression) ChildSlot({ type: IExpression })
optional(IStatement) ChildSlot({ type: IStatement, cardinality: "0..1" })
children(IExpression, "2..n") ChildSlot({ type: IExpression, cardinality: "2..n" }) (default cardinality "0..n")
prop("name", { default: "" }) Prop({ type: "name", default: "" })
ref("symbol") Ref({ target: "symbol" })

The Language Pane's Declaration card edits ChildSlot/Prop/Ref option objects in place; it lists a positional slot too but sends you to the Code view to change it.

  • Cardinality is "1" (default), "0..1" (optional), "0..n", "1..n" or a range such as "2..n". A variadic slot consumes the rest of children, so it must be the last slot of the concept.
  • A trailing underscore in a field name is stripped from the slot name (else_ is the slot else), which is how a slot can be named after a JavaScript keyword.
  • Slot kinds. "expression" and "statement" are engine kinds (a statement slot also accepts expressions). Any other type names either a category or a concept-typed row such as Core's withItem, tryHandler, case or params. A plugin that owns such a kind registers it with registerClosedSlotKinds(...) (src/slot-kinds.ts), which controls whether the slot accepts only listed categories, whether empty rows are blank lines, and whether Enter inserts rows.
  • Editing behavior of a child slot is stated by the editor that draws it, not by the slot: <Child link={self.body} body /> marks a statement slot as a construct's own statement list (so a second statement promotes it to the language's block concept); <Children link={self.items} items /> marks an expression-variadic slot as a literal's item list so Enter adds an item rather than climbing to the enclosing statement. The old blockBody, collectionItems and separator slot options are ignored (with a one-time warning). See Enter / Shift+Enter insertion.
  • An unfilled slot can be the __Empty__ placeholder node, and an absent optional (0..1) slot can read as undefined, depending on how the node was built. Guard for both: isEmpty() from src/ast.ts, plus a plain undefined test.

Constraints on a slot: .must()

A rule about what a slot may hold is declared where the slot is:

rhs = ChildSlot({ type: IExpression }).must("no-literal-zero-divisor", ({ value }: ConstraintContext) =>
    value === 0 ? { message: "Division by zero: the divisor is the literal 0" } : null);
msg = Prop({ type: "name" }).must("not-todo", ({ value }) => value === "todo" && "resolve the todo", "warning");

.must(name, check, severity = "error") chains. check receives a ConstraintContext ({ value, parent, slot, lang, nav }) and returns a message (a string or { message }) for a violation and nothing otherwise. It becomes the same constraint validation the old constraints() hook produced, so completion (violatesSlot), the Checks pane and the Language Pane see it unchanged. A slot inherited from a base class cannot carry .must() (the declaration sits in the base); such a concept keeps the constraints() hook, whose check takes the same ConstraintContext.

Inheritance

Use ordinary JavaScript extends to share methods, and pass the base class to Concept(...) ahead of the interfaces:

class StatementBlock extends Concept(IStatement) {      // not exported: never registered as a concept
    declare stmts: any[];
    async eval({ evaluate }: EvalContext) { /* ... */ }
}

export class MoneyFile extends Concept(StatementBlock, IBlock, IRoot) {
    head = "moneyFile";
    name = Prop({ type: "name", default: "" });
    stmts = ChildSlot({ type: IStatement, cardinality: "0..n" });
}

Because JavaScript runs a base class's field initializers before a subclass's, a base-declared variadic slot would land before the subclass's own slots and be truncated. Declare slots in the concrete class and share only methods in the base (this is the reason for the pattern above in plugins/lang-money/). A base class that is not exported is automatically not registered: conceptsFromModule picks up only exported BaseConcept subclasses.

The separate parent field (extends: "ParentHead" in persisted .lang.js data and the Language tab) is language-level metadata inheritance within one language, resolved by mergeInheritance (src/workbench/lang-class-inheritance.ts). The effective slots are the parent's followed by the concept's own. The concept's own editor, inspector, css, icon, notations, reduce and the like win when set and otherwise fall back to the parent's; intentions, computed, actions, validations and the interface list are merged; eval always comes from the concept itself. Class-authored concepts normally use JavaScript extends instead.

Interfaces

An interface is a value declared once (src/concept-interfaces.ts for the platform ones; plugins/<name>/languages/interfaces.ts for a plugin's own):

export abstract class ICell extends Interface() {}                                              // a marker; the head is the class name
export abstract class IOperator extends Interface<{ operator: OperatorSpec }>({ requires: ["operator"] }) {}

Naming it as a value (not a string in a list) makes a typo a compile error and gives go-to-definition. A slot's type accepts the same value, so ChildSlot({ type: ICell }) and Concept(ICell) refer to one thing. The Declaration card in the Language Pane edits the list in the Concept(...) header.

Interface Gives the concept
IExpression, IStatement Which slots accept it and how completion groups it.
IBlock Statement-list container.
IReference, IDeclaration Holds a variable name / introduces a name.
IOperator Typing behaviour as an operator; requires operator = { key, kind, precedence, … }. See below.
IWrapper A wrap whose delimiters the editor draws itself; requires wrapper = { slot, left, right }.
ISplittable An operator key typed in the middle of its text splits it into two literals.

Other flags stay plain members:

Declaration Effect
IRoot in Concept(...) This is a model's own root concept (IDefaultRoot marks the one a new model starts from). The old isFileRoot = true flag is migrated on load.
gutterRun = true A Run button in the line-number gutter on the concept's first line. Unset means the file root only; false opts out.
isDefault() returning true The canonical bare-identifier concept: what typing a letter into an empty cell builds.
isParamsContainer = true The canonical parameter-list container.
importModuleSlot, importNameSlot Name which slots hold an import's module and member, so completion can recognize import context without naming heads.
traits() Free-form engine-understood roles (chain, newReference, extractVariable, surroundShortcut, docComment, and others); the registry is in Language-agnostic core.

See Language authoring guide for how the engine consults these.

Typing behavior: operators and side-transformations

When a user types a key at the end of a filled cell, the editor can wrap the current node in your concept. An operator concept implements IOperator and declares one data member:

operator = { key: "-", kind: "binary", precedence: 4, assoc: "left" } as const;
Field Meaning
key The key that triggers it, for example "+". Optional: a word operator is reached through its alias.
kind "binary", "unary" or "variadic".
precedence Number controlling where the wrap lands.
assoc "left" makes a chain of equal-precedence operators nest to the left; see Editors.
upgradeOnEquals, upgradeOnRepeat Swap to another head when = is typed on an empty right-hand side, or the same key is repeated (Times to Power).
reshapeOnEquals Reshape into another head holding a given value (class-only, not persisted).

Other typing members:

Member Meaning
operatorKeys + operatorValueSlot Multi-operator form for one head covering many operators through a property; use instead of an operator spec, not alongside. Class-only.
wrapTrigger, wrapContext A trigger that no token renders literally (a ternary's "?"), disambiguated by context. Can instead be set as props on a <Text> token.
canSurround Opts into the "surround with" intention, offered only where the concept is legal in the selection's slot. If the concept's last slot is variadic and accepts the selected nodes, they go there (fixed slots before it stay empty: a table's row group); otherwise the wrapper takes the statement shape (empty first slot, the selection as body block: if/while). The entry reads "Surround with alias(…)"; a concept whose alias does not describe what it renders sets traits().surroundLabel (the row group uses when <guard>).

Placement guards restrict where a concept may appear. They take context objects and return false to forbid:

canBeChild({ parent, slot, lang }: CanBeChildContext) { return parent?.head !== "params"; }
canBeRoot({ lang }: CanBeRootContext) { … }
canBeAncestor({ child, lang }: CanBeAncestorContext) { … }

They are read from the harvested concept, so they must not depend on this.

Hook contexts

Each hook receives one object, so a hook names exactly what it uses and nothing is positional. Annotate the parameter with the context type (TypeScript cannot infer a destructured parameter of a subclass member); the Language Pane keeps the destructured names in step with what the body uses when you save.

Hook Context type Members
eval EvalContext (src/evaluator.ts) evaluate(child), call(closure, args), vars, output, input, log, outputResult, outputHtml, modelImports, evalIn, model, lang, and env (the whole environment, for a helper that takes one)
generate GenerateContext (src/generator.ts) emit(child), inline(child), indent, nav, model, lang. The context is also callable (ctx(child, indent)), for a helper that takes the generator as a value
checks()[].check CheckContext (src/checker.ts) node, lang, nav, scopeAt(node), blockScopedNames, match (pattern captures), report
slot .must / constraints()[].check ConstraintContext (src/hook-contexts.ts) value, parent, slot, lang, nav
canBeChild / canBeRoot / canBeAncestor CanBeChildContext / CanBeRootContext / CanBeAncestorContext parent, slot, lang / lang / child, lang
intention isApplicable / apply IntentionApplicableContext / IntentionApplyContext node, lang, parent, slot, root, getTypeInfo, index, selection / node, editor, lang, selection
typesystem() infer / check / walk / expectedTypeOfSlot / declares / denotes TypeInferContext, TypeCheckContext, TypeWalkHookContext, ExpectedSlotContext, TypeDeclaresContext, TypeDenotesContext see Checks and types

A hook written the old positional way still runs (each hook kind is bridged where the concept is harvested), and a rule authored in the Language Pane as a body string keeps its positional compiled parameters; only a hook whose first parameter is an object-destructuring pattern is treated as written against a context.

Registering concepts

A plugin's index.ts builds the language from the module:

import { conceptsFromModule } from "../../../src/base-concept.ts";
import * as concepts from "./concepts.tsx";
export default { name: "money", namespace: "money", displayName: "Money", description: "...",
                 concepts: conceptsFromModule(concepts) };

conceptsFromModule collects every exported BaseConcept subclass. When some exports are helpers or abstract bases, list the concepts explicitly with conceptMetaFromClass instead (Core's concepts-*.concept.js files do this). Metadata is harvested once from a throwaway instance, so do not rely on per-node state in code that runs at harvest time, and note that a newly added concept field must be threaded through conceptMetaFromClass, normalizeConceptRaw and RuntimeConceptData or it reads undefined at runtime. Two concepts sharing a head, alias or operator key shadow each other with no priority system.

Hooks reference

Every hook is optional. All are listed with full contracts in the API reference under BaseConcept.

editor, inspector, notations(), computed(), actions() (projection); eval(), generate(), reduce(), surface() (execution and persistence); checks(), typesystem(), intentions() and slot .must() (validation); scope(), dataflow(), referenceScopes(), linkTargets(), stringCandidates() (names and references); diagramActions() (diagram toolbars); canBeChild, canBeRoot, canBeAncestor (placement); traits().