Node pattern language¶
Split out of
CLAUDE.mdto 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 andLanguage-independent:matchPattern(pattern, value, ctx?, bindings?)matches a plain-objectPatterntree (headMatch/WILDCARD/EMPTY/literal/capture/any/all/not/predicate, pluslist/restfor a variadic slot's whole children array) against aChild, returning extendedBindingsornull.headMatch's slot constraints are resolved by declared slot name (mirroringAstTree's fixed-then-variadic-absorption algorithm, viaslot-cardinality.ts's canonicalslotIsVariadic), 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.WILDCARDdeliberately matches the unfilled-slot placeholder too (EMPTYexists 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 onerest()perlist()(throws otherwise — a concept only ever has one variadic slot in practice). A reference node matches structurally, not by dereferencing to its declaration (aresolved(...)operator is unbuilt). EveryPatternvariant is declared once in the union and dispatched by one exhaustiveswitch— deliberately not two hand-maintained lists (EvalVM'sHANDLERSmap vs. its separateBUILDER_NAMESarray, which can drift, is the anti-pattern this avoids). -
Phase 2 — checker integration,
src/checker.ts. A check rule's shape gained an optionalpattern(supersedingconceptwhen both are present) andpredicates(backingpredicate()terms).matchCheckDefdecides per-node whether a rule applies and with which bindings, threaded to the rule'sfnas a sixth positional argument. Only a native check function (supplied directly asfn/check—base-concept.ts'schecks(), or a language/concept's ownchecksarray in code) can name that parameter; a.lang.kdlbody-string check compiles vianew 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, malformedlist/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 —runChecksmust never abort a whole document's check run over one bad pattern.pattern/predicatesare threaded through all three places a check rule gets folded into{kind:"check",...}(base-concept.ts'sbuildValidationsFromInstance,workbench/lang-class.ts'schecksConstraintsToValidations,workbench/lang-class-inheritance.ts'snormalizeConceptRaw) so it works from every check-authoring convention alike. Not wired intoconstraint-runner.ts— a constraint matches a slot value, not a whole node, which is a different (messier) question thanmatchCheckDefanswers; deferred, not forgotten. -
Phase 3 — the projectional language,
plugins/lang-pattern/. OneBaseConceptper Phase 1 operator (PWildcard,PEmpty,PLiteralNumber/String/Bool,PCapture,PAny/PAll,PNot,PPredicate,PHeadMatch/PSlotBinding,PRest/PList), each with a realeditor()projection — seeconcepts.tsx's own file banner for the full head list and the slot-naming collision it works around (PHeadMatch's matched-head slot ishead_, nothead, since every concept instance already has its ownheadfield naming itself;this.$.head— notthis.$.head_— is the correcteditor()reference, sincethis.$is keyed by the stripped name).pattern-compile.ts'scompilePattern/compilePatternOrListare the only place that translates a tree of these nodes into the Phase 1Pattern/ListPatternshape — the concepts are an authoring/projection surface, never a second implementation of match semantics. The language ishidden = true: discovered bylang-library.tsbut excluded fromCORE_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 viagetBuiltinDef("pattern")+registerProjectLanguage— same mechanismworkbench/demo-languages.ts's_ensureDocgenLoaded()uses for the demo-tier "docgen" language. A.lang.kdl-level round-trip (given a liveLanguageto resolve slot schemas against) is tested and passes — see the persistence note below for what's still missing beyond that. There's noinspector()(matcheslang-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 aPWildcardnode and mounts a live, projectionally-editable mini-editor for it directly in the pane, via the same standaloneDocumentState+Editor+mountConceptSourceEditorViewsequencelanguage-pane-concept-source-editor.ts's concept sub-editor uses (checks-pane.tsxis itself already Solid-JSX-scoped — seetsconfig.solid.json— so it can importmountConceptSourceEditorViewdirectly, without the cross-config indirectionLanguagePaneneeds).ensurePatternLangLoaded()performs the on-demandgetBuiltinDef/registerProjectLanguageload described above, once, memoized. Apply compiles the live tree viacompilePattern; a rule with a pre-existing code-authoredpatternbut no editablepatternNode(there is no decompiler from the compiledPatternshape 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 1Patternshape 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),?nameforpredicate,{ js }forcondition,_anything,empty, numbers, strings,true/false, a barenamefor a capture of anything. Slots are always named (a positional form would need the language to know the slot order).parsePatternTextthrowsPatternTextErrorwith the position;printPatternwrites the canonical spelling (it throws for a head or slot that is not an identifier); parse and print are inverse, pinned bytests/test-pattern-text.mjs. It is a spelling, not a second matcher: the text becomes the samePatternobject. Use: a check rule'spatternmay be that text (checker.ts'smatchCheckDefparses it, cached); text that does not parse is reported once per run on the first node asked, not on every node; andworkbench.patterns.parse/.printfor 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-authoredPatternfor the pane, butprintPatternis exactly that decompiler for display), and the notation forconstraints(still not wired toconstraint-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 viapattern-compile.ts" rules above: SequencePattern(sequence(mode, items, {ordered}), conceptPSequence+PSeqItem) — an alternative tolist()as the value of a variadic slot'sheadMatchbinding (SlotListPattern = ListPattern | SequencePattern;matchHeadaccepts either wherever it required alist). Items are{pattern, min, max|null}; the element cardinality text (1,?,*,+,a..b,a..n) is parsed byparseSeqCardinality. 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).ordereditems claim consecutive runs in item order (forallOrMore, 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 barelist(), a sequence matches an empty variadic slot (the concept's declared slot list is consulted, sinceresolveSlotChildrencreates no bucket for zero children); that is required fornoneOfThese/*to mean anything. Captures inside items bind (last claimed child wins).ConditionPattern(condition(body), conceptPCondition) — a JS function body (or, with noreturn, a single expression) compiled withnew Function("node","lang","bindings","isNode","isEmpty", ...), cached by source. Deliberately the same trust model as.langcheck bodies (language-author code, full JS access) rather than a new expression language; unlikepredicate(name)it needs noctx.predicatesregistry, so it survives.lang.kdlpersistence as plain data. A body that fails to compile or throws makes the match throw (an authoring bug, like an unknown predicate) —runChecksalready converts a throwing pattern into an issue on the node.-
assertStructure(value, pattern, ctx)/explainMismatch—explainMismatchreturns{path, message}for the first reason a pattern fails, ornull; it is guaranteed to agree withmatchPattern(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 areroot+.slot/[index]steps (root.body[2].value). Granularity: element-wise insidelist/sequencewhen one child can be blamed (listindex, 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.assertStructurethrowsStructureMismatchError(.path,.reason) or returns the bindings. Exposed asModelNode.assertStructure(pattern)/matchesStructure(pattern)(src/model-api.ts; the pattern may be a plainPatternor a pattern-language node, compiled viacompilePattern) and apatternsbinding in the console scope (buildSmodelScope) so the Model Console reaches them through its generic method dispatch with no new query concept; also re-exported fromsrc/api.ts. Not built: alang-testlangAssertStructureconcept (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), andconstraint-runnerintegration (still deferred, see Phase 2). -
Persistence —
lang-schema.ts+lang-codec-encode.ts/lang-codec-decode.ts+lang-compiler.ts. A check rule'spatternKdl(persisted string) andpatternNode(its parsed form) round-trip through.lang.kdlthe same waybodydoes.conceptValidationToKdl/languageValidationToKdl(encode) and their decode counterparts calltoKdl/parseKdlagainst a standalone "pattern"Language, resolved bypattern-lang-for-codec.ts'sgetPatternLangForCodec()— memoized, never registered into the runtime registry (thisLanguageexists only for schema resolution, never to be the app's "active" pattern language). On decode,lang-compiler.ts'scompilePatternNodeIfNeededcompiles a freshly-parsedpatternNodeinto thepatternchecker.tsactually runs, mirroring its own body →fncompilation for the structural-match half of a rule; a rule that already carries a code-authoredpatterndirectly (every native check) is left untouched, and a malformedpatternNode(only possible via a hand-edited.lang.kdl) degrades the same way a brokenbodydoes — the rule'sfnreports 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:
-
A static import of the pattern plugin breaks
tsconfig.solid.json.toKdl/parseKdlneed a liveLanguageto resolveplugins/lang-pattern/'s concept slot schemas (confirmed bytests/test-lang-pattern-kdl-roundtrip.mjs— serialization itself was never the problem). Building thatLanguagevianew Language(patternDef)with a staticimport patternDef from ".../index.js"inlang-codec-encode.ts/lang-codec-decode.tsbroketsconfig.solid.json's typecheck: those codec files are reachable fromsrc/ui/checks-pane.tsx(Solid-scoped) via theworkbench/languages.tsbarrel, so the static import chain pulledconcepts.tsx— authored under the roottsconfig.json's token-JSX pragma (h/Fragment) — into the Solid JSX program too, which can't typecheck it (<Children sep={...}>doesn't satisfy Solid'sKidtype). The fix is resolving theLanguageviagetBuiltinDef("pattern")instead —lang-library.tsreaches plugin files through a template-literalimport()path (`../plugins/${name}/languages/${file}`) that TypeScript can't statically resolve, so it never enters either tsconfig's program. A plain-stringimport(), 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 usingimport()syntax. -
A static import of
lang-library.tscloses a real circular module dependency. Even after switching togetBuiltinDef, importinglang-library.tsstatically frompattern-lang-for-codec.tsstill broke — this time at runtime, not typecheck time:lang-library.tsitself importslang-codec.ts, andlang-library.ts's own top-level plugin scan (used to buildgetBuiltinDef's lookup table) reaches essentially every plugin's concept files, includingplugins/lang-core/languages/concepts-modules.concept.js, which importssrc/workbench/lang-registry.ts— which statically imports this samelang-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.tsagain, evaluated during module linking. The symptom wasplugins/lang-meta/'scoreBaseimport reading asundefinedmid-evaluation — an unrelated plugin breaking because of which side of the cycle Node's module linker reached first. The fix:pattern-lang-for-codec.tsimportslang-library.ts(andworkbench/lang-class.ts) with a dynamicimport()insidegetPatternLangForCodec(), not at module top level — deferringlang-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 dynamicimport()when the code runs, not when the importing module is linked — that's the property that breaks the cycle. -
Zod flattens a decoded
patternNode's class instance into a plain object.languageFromKdlNodeends every decode withvalidateLanguageData(...), andEvalNodeSchema(reused forpatternNode, seelang-schema.ts's doc comment) isz.object({head, children}).passthrough()— Zod always constructs a new plain object as its output, never the original input reference.parseKdlitself correctly produces a realPHeadMatch/... class instance (plugins/lang-pattern/'s concepts are realBaseConceptsubclasses), but that instance doesn't survive the Zod pass that follows it. This matters becauseBaseConcept'sChildSlotaccessors (base-concept.ts'sObject.defineProperty, non-enumerable, on the class prototype) are exactly whatpattern-compile.ts'scompilePatternreads (inst.bindings,inst.value,inst.pattern, ...) — a plain object with the samehead/childrendata has none of them, socompilePatterneither throws (inst.bindings is not iterable) or silently readsundefinedfor a scalar slot. Confirmed bytests/test-lang-pattern-persistence.mjs, which fails exactly this way without the fix. The fix, both places a decodedpatternNodereachescompilePattern: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) — inlang-compiler.ts'scompilePatternNodeIfNeeded(compiling into the checker-facingpattern) and insrc/ui/checks-pane.tsx'sloadRulesFromLang(seeding the Checks pane'sRule.patternNode, which a liveEditorthen mounts a projectional UI over — a plain object has noeditor()on its prototype either, andEditor's ownreId()only mutates.idfields in place, it doesn't reconstruct instances).cloneWithIdson 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: anyEvalNodeSchema-validated node (the original eval-AST use, not justpatternNode) 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).