Skip to content

Node pattern language

Split out of CLAUDE.md to keep that file's per-session load light. Linked from there — read this when you're actually touching this subsystem.

A structural pattern-matching facility for the AST — matches a node by shape (concept head, slot contents, literals, captures, combinators), not only by concept name — built in four phases, each independently useful and each landing in its own commit. There is no single Language-like class tying these together; read the four subsections below in order, since each depends on the previous one.

  • Phase 1 — the matcher, src/pattern-match.ts. Headless and Language-independent: matchPattern(pattern, value, ctx?, bindings?) matches a plain-object Pattern tree (headMatch/WILDCARD/EMPTY/literal/capture/any/all/not/predicate, plus list/rest for a variadic slot's whole children array) against a Child, returning extended Bindings or null. headMatch's slot constraints are resolved by declared slot name (mirroring AstTree's fixed-then-variadic-absorption algorithm, via slot-cardinality.ts's canonical slotIsVariadic), never by position — a positional-only matcher would be a second, divergent model of "what's in slot X" from what the checker/constraint runner already use. WILDCARD deliberately matches the unfilled-slot placeholder too (EMPTY exists for "unfilled specifically"; not(EMPTY) for "filled, don't care what") — the alternative (treating an in-progress edit as a special non-match everywhere) would make checks silently stop firing on trees mid-edit. At most one rest() per list() (throws otherwise — a concept only ever has one variadic slot in practice). A reference node matches structurally, not by dereferencing to its declaration (a resolved(...) operator is unbuilt). Every Pattern variant is declared once in the union and dispatched by one exhaustive switch — deliberately not two hand-maintained lists (EvalVM's HANDLERS map vs. its separate BUILDER_NAMES array, which can drift, is the anti-pattern this avoids).

  • Phase 2 — checker integration, src/checker.ts. A check rule's shape gained an optional pattern (superseding concept when both are present) and predicates (backing predicate() terms). matchCheckDef decides per-node whether a rule applies and with which bindings, threaded to the rule's fn as a sixth positional argument. Only a native check function (supplied directly as fn/check — base-concept.ts's checks(), or a language/concept's own checks array in code) can name that parameter; a .lang.kdl body-string check compiles via new Function("node", "lang", body) with a formal parameter list fixed to exactly those two names at compile time, regardless of what the body text itself suggests, so it can't read bindings by name. A pattern that throws (unknown predicate, malformed list/rest, a slot pattern whose list-ness disagrees with the concept's declared cardinality) is caught and reported as an issue on the node it choked on — runChecks must never abort a whole document's check run over one bad pattern. pattern/predicates are threaded through all three places a check rule gets folded into {kind:"check",...} (base-concept.ts's buildValidationsFromInstance, workbench/lang-class.ts's checksConstraintsToValidations, workbench/lang-class-inheritance.ts's normalizeConceptRaw) so it works from every check-authoring convention alike. Not wired into constraint-runner.ts — a constraint matches a slot value, not a whole node, which is a different (messier) question than matchCheckDef answers; deferred, not forgotten.

  • Phase 3 — the projectional language, plugins/lang-pattern/. One BaseConcept per Phase 1 operator (PWildcard, PEmpty, PLiteralNumber/String/Bool, PCapture, PAny/PAll, PNot, PPredicate, PHeadMatch/PSlotBinding, PRest/PList), each with a real editor() projection — see concepts.tsx's own file banner for the full head list and the slot-naming collision it works around (PHeadMatch's matched-head slot is head_, not head, since every concept instance already has its own head field naming itself; this.$.head — not this.$.head_ — is the correct editor() reference, since this.$ is keyed by the stripped name). pattern-compile.ts's compilePattern/compilePatternOrList are the only place that translates a tree of these nodes into the Phase 1 Pattern/ListPattern shape — the concepts are an authoring/projection surface, never a second implementation of match semantics. The language is hidden = true: discovered by lang-library.ts but excluded from CORE_LANG_NAMES/DEMO_LANG_NAMES/BUILTIN_LANGUAGE_EXTENSIONS (never boot-loaded, never shown in the language picker), while still loadable on demand by explicit name via getBuiltinDef("pattern") + registerProjectLanguage — same mechanism workbench/demo-languages.ts's _ensureDocgenLoaded() uses for the demo-tier "docgen" language. A .lang.kdl-level round-trip (given a live Language to resolve slot schemas against) is tested and passes — see the persistence note below for what's still missing beyond that. There's no inspector() (matches lang-formula's own precedent of skipping it).

  • Phase 4 — inline authoring, src/ui/checks-pane.tsx. A check-kind rule's editor gained "+ Add structural pattern": seeds a PWildcard node and mounts a live, projectionally-editable mini-editor for it directly in the pane, via the same standalone DocumentState + Editor + mountConceptSourceEditorView sequence language-pane-concept-source-editor.ts's concept sub-editor uses (checks-pane.tsx is itself already Solid-JSX-scoped — see tsconfig.solid.json — so it can import mountConceptSourceEditorView directly, without the cross-config indirection LanguagePane needs). ensurePatternLangLoaded() performs the on-demand getBuiltinDef/registerProjectLanguage load described above, once, memoized. Apply compiles the live tree via compilePattern; a rule with a pre-existing code-authored pattern but no editable patternNode (there is no decompiler from the compiled Pattern shape back to an editable node tree) is passed through untouched rather than silently dropped, and shown as a read-only note instead of offering "+ Add" (which would otherwise clobber it). Not wired into the Constraints pane — see Phase 2's note.

  • Constructor notation — src/pattern-text.ts (2026-11-04). A text spelling of the Phase 1 Pattern shape for authors who would rather write the pattern than nest builder calls: Plus(left: _, right: 0), a@Assign(target: t, value: Literal()), Call(args: [first, ...rest]), Block(body: allOrMore[Return(), _*]), with ! / & / | (tightest to loosest), ?name for predicate, { js } for condition, _ anything, empty, numbers, strings, true/false, a bare name for a capture of anything. Slots are always named (a positional form would need the language to know the slot order). parsePatternText throws PatternTextError with the position; printPattern writes the canonical spelling (it throws for a head or slot that is not an identifier); parse and print are inverse, pinned by tests/test-pattern-text.mjs. It is a spelling, not a second matcher: the text becomes the same Pattern object. Use: a check rule's pattern may be that text (checker.ts's matchCheckDef parses it, cached); text that does not parse is reported once per run on the first node asked, not on every node; and workbench.patterns.parse / .print for scripts and the Model Console. Not built: a Checks-pane / Language Editor view of a rule's pattern as this text (the pane still edits the node tree; there is no decompiler from a code-authored Pattern for the pane, but printPattern is exactly that decompiler for display), and the notation for constraints (still not wired to constraint-runner).

  • Structure Check extension — sequences, conditions, assertStructure (src/pattern-match.ts, plugins/lang-pattern/). Ported from MPS-extensions' structure check. Three additions, all following the "one union, one dispatch, compile via pattern-compile.ts" rules above:

  • SequencePattern (sequence(mode, items, {ordered}), concept PSequence + PSeqItem) — an alternative to list() as the value of a variadic slot's headMatch binding (SlotListPattern = ListPattern | SequencePattern; matchHead accepts either wherever it required a list). Items are {pattern, min, max|null}; the element cardinality text (1, ?, *, +, a..b, a..n) is parsed by parseSeqCardinality. Modes: exactly (every child claimed, every min met), allOrMore (mins met, unclaimed children allowed), allOrLess (every child claimed, mins treated as 0), noneOfThese (no child matches any item). ordered items claim consecutive runs in item order (for allOrMore, as a subsequence with free extras); unordered items may claim children in any arrangement. Matching is a backtracking search that memoizes failed states (success never depends on accumulated bindings), so it is polynomial for the ordered case and bounded by the distinct (position, per-item counts) states for the unordered one — a very wide unordered sequence over hundreds of children is the known worst case. Unlike a bare list(), a sequence matches an empty variadic slot (the concept's declared slot list is consulted, since resolveSlotChildren creates no bucket for zero children); that is required for noneOfThese/* to mean anything. Captures inside items bind (last claimed child wins).
  • ConditionPattern (condition(body), concept PCondition) — a JS function body (or, with no return, a single expression) compiled with new Function("node","lang","bindings","isNode","isEmpty", ...), cached by source. Deliberately the same trust model as .lang check bodies (language-author code, full JS access) rather than a new expression language; unlike predicate(name) it needs no ctx.predicates registry, so it survives .lang.kdl persistence as plain data. A body that fails to compile or throws makes the match throw (an authoring bug, like an unknown predicate) — runChecks already converts a throwing pattern into an issue on the node.
  • assertStructure(value, pattern, ctx) / explainMismatch — explainMismatch returns {path, message} for the first reason a pattern fails, or null; it is guaranteed to agree with matchPattern (a generic message at the current path is the fallback when no finer reason is found, and a test checks agreement over a pattern/value matrix). Paths are root + .slot / [index] steps (root.body[2].value). Granularity: element-wise inside list/sequence when one child can be blamed (list index, the suffix index mapped to the real index, noneOfThese's forbidden child, a sequence child claimed by no item), the slot path itself for count/cardinality/arrangement failures. assertStructure throws StructureMismatchError (.path, .reason) or returns the bindings. Exposed as ModelNode.assertStructure(pattern)/matchesStructure(pattern) (src/model-api.ts; the pattern may be a plain Pattern or a pattern-language node, compiled via compilePattern) and a patterns binding in the console scope (buildSmodelScope) so the Model Console reaches them through its generic method dispatch with no new query concept; also re-exported from src/api.ts. Not built: a lang-testlang AssertStructure concept (it would need the pattern language embedded in the test language and a way to resolve the language-under-test's slot schemas — more invasive than the API surface), and constraint-runner integration (still deferred, see Phase 2).

  • Persistence — lang-schema.ts + lang-codec-encode.ts/lang-codec-decode.ts + lang-compiler.ts. A check rule's patternKdl (persisted string) and patternNode (its parsed form) round-trip through .lang.kdl the same way body does. conceptValidationToKdl/languageValidationToKdl (encode) and their decode counterparts call toKdl/parseKdl against a standalone "pattern" Language, resolved by pattern-lang-for-codec.ts's getPatternLangForCodec() — memoized, never registered into the runtime registry (this Language exists only for schema resolution, never to be the app's "active" pattern language). On decode, lang-compiler.ts's compilePatternNodeIfNeeded compiles a freshly-parsed patternNode into the pattern checker.ts actually runs, mirroring its own body → fn compilation for the structural-match half of a rule; a rule that already carries a code-authored pattern directly (every native check) is left untouched, and a malformed patternNode (only possible via a hand-edited .lang.kdl) degrades the same way a broken body does — the rule's fn reports the compile error instead of throwing later during a checker run.

Getting here took two false starts worth recording, since both failure modes are easy to reintroduce:

  1. A static import of the pattern plugin breaks tsconfig.solid.json. toKdl/parseKdl need a live Language to resolve plugins/lang-pattern/'s concept slot schemas (confirmed by tests/test-lang-pattern-kdl-roundtrip.mjs — serialization itself was never the problem). Building that Language via new Language(patternDef) with a static import patternDef from ".../index.js" in lang-codec-encode.ts/lang-codec-decode.ts broke tsconfig.solid.json's typecheck: those codec files are reachable from src/ui/checks-pane.tsx (Solid-scoped) via the workbench/languages.ts barrel, so the static import chain pulled concepts.tsx — authored under the root tsconfig.json's token-JSX pragma (h/Fragment) — into the Solid JSX program too, which can't typecheck it (<Children sep={...}> doesn't satisfy Solid's Kid type). The fix is resolving the Language via getBuiltinDef("pattern") instead — lang-library.ts reaches plugin files through a template-literal import() path (`../plugins/${name}/languages/${file}`) that TypeScript can't statically resolve, so it never enters either tsconfig's program. A plain-string import(), static or dynamic, does not get this treatment — TypeScript resolves and checks it exactly like a static import — so this dodge depends specifically on the path being computed at runtime, not just on using import() syntax.

  2. A static import of lang-library.ts closes a real circular module dependency. Even after switching to getBuiltinDef, importing lang-library.ts statically from pattern-lang-for-codec.ts still broke — this time at runtime, not typecheck time: lang-library.ts itself imports lang-codec.ts, and lang-library.ts's own top-level plugin scan (used to build getBuiltinDef's lookup table) reaches essentially every plugin's concept files, including plugins/lang-core/languages/concepts-modules.concept.js, which imports src/workbench/lang-registry.ts — which statically imports this same lang-codec.ts. That closes the cycle: lang-codec-decode.ts → pattern-lang-for-codec.ts → lang-library.ts → (plugin scan) → lang-core → lang-registry.ts → lang-codec.ts again, evaluated during module linking. The symptom was plugins/lang-meta/'s coreBase import reading as undefined mid-evaluation — an unrelated plugin breaking because of which side of the cycle Node's module linker reached first. The fix: pattern-lang-for-codec.ts imports lang-library.ts (and workbench/lang-class.ts) with a dynamic import() inside getPatternLangForCodec(), not at module top level — deferring lang-library.ts's evaluation to the first time the function is actually called, by which point every module in that cycle has long since finished its own top-level evaluation. This is orthogonal to point 1: TypeScript still resolves and checks the plain-string dynamic import the same as a static one (so it doesn't reopen the tsconfig.solid.json problem), but Node only evaluates a dynamic import() when the code runs, not when the importing module is linked — that's the property that breaks the cycle.

  3. Zod flattens a decoded patternNode's class instance into a plain object. languageFromKdlNode ends every decode with validateLanguageData(...), and EvalNodeSchema (reused for patternNode, see lang-schema.ts's doc comment) is z.object({head, children}).passthrough() — Zod always constructs a new plain object as its output, never the original input reference. parseKdl itself correctly produces a real PHeadMatch/... class instance (plugins/lang-pattern/'s concepts are real BaseConcept subclasses), but that instance doesn't survive the Zod pass that follows it. This matters because BaseConcept's ChildSlot accessors (base-concept.ts's Object.defineProperty, non-enumerable, on the class prototype) are exactly what pattern-compile.ts's compilePattern reads (inst.bindings, inst.value, inst.pattern, ...) — a plain object with the same head/children data has none of them, so compilePattern either throws (inst.bindings is not iterable) or silently reads undefined for a scalar slot. Confirmed by tests/test-lang-pattern-persistence.mjs, which fails exactly this way without the fix. The fix, both places a decoded patternNode reaches compilePattern: cloneWithIds(patternNode) first — ast.ts's existing "preserve ids, rebuild real instances via the concept-factory registry" primitive (already used for undo/redo history and collab rehydration) — in lang-compiler.ts's compilePatternNodeIfNeeded (compiling into the checker-facing pattern) and in src/ui/checks-pane.tsx's loadRulesFromLang (seeding the Checks pane's Rule.patternNode, which a live Editor then mounts a projectional UI over — a plain object has no editor() on its prototype either, and Editor's own reId() only mutates .id fields in place, it doesn't reconstruct instances). cloneWithIds on an already-real instance (anything authored live in the pane, never touching Zod) is a harmless no-op-equivalent clone, so both call sites apply it unconditionally rather than branching on provenance. This generalizes past patterns: any EvalNodeSchema-validated node (the original eval-AST use, not just patternNode) loses its class prototype the same way if one is ever a real concept-class instance rather than a plain opcode tree.

The KDL codec itself (languageToKdlText/languageFromKdlText and the lower-level *KdlNode functions in lang-codec.ts/lang-codec-encode.ts/lang-codec-decode.ts) is async as a consequence of point 1 — every caller across lang-registry.ts, workbench/project.ts, lang-library.ts, and editor-view-mount-language-actions.ts awaits it now. lang-registry.ts's saveLanguages() is fire-and-forget on both the hosted and non-hosted branches (previously "synchronous in browser" — that contract no longer holds; a caller that needs to know persistence actually finished should call saveLanguageAsync directly and await it). The encode side (patternKdlProp in lang-codec-encode.ts) does not need the same cloneWithIds treatment — toKdl's schema-driven serialization reads slot contents through the concept's declared schema against children directly, not through class-instance accessors, so it works the same whether handed a real instance or a Zod-flattened plain object (confirmed by test-lang-pattern-persistence.mjs's save → load → save stability assertion).