Skip to content

Scope and dataflow

Two analyses answer "which names are visible here?" and "what value flows where?". Both are driven by small per-concept descriptors, so the engine learns nothing about your concept names.

  • Scope analysis (src/scope.ts) computes, for each reference node, the set of names in scope. It returns Map<nodeId, Set<name>>. It powers rename, go-to-declaration, find usages, completion of names and the out-of-scope check.
  • Dataflow analysis (src/dataflow.ts) finds possibly-uninitialized reads, unreachable code after a terminator, and unused assignments (dead stores). Results are merged into runChecks as ordinary issues. See Checks, constraints and types.

What the engine needs from a language

First, say which concepts are references, blocks and declarations, using interfaces (Concept(IReference), Concept(IBlock), Concept(IDeclaration), see Language authoring guide). The scope runner treats a reference node as "record the current scope here" and a block node as "process children in order, threading introduced names forward". The scope() descriptor below covers the rest.

scope()

scope() returns a descriptor. All fields are optional:

Field Meaning
introduces(node) The name or names this node adds to the enclosing block's sequential scope. Return a string, an array (a destructuring declaration), or null.
initIndex With introduces: only children[initIndex] (the initializer) is processed with the pre-declaration scope, then the name is added. Without it, the full child processing runs first, then the name is added.
ownScopeNames(node) Names declared in this node's own inner scope (loop variables, parameters). Collected so they trigger out-of-scope checks.
process(node, scope, assignScope, helpers) Fully custom child traversal; replaces the default recursion. helpers is { processNode, collectAssignTargets }.
createsAssignBoundary true for a function or lambda, so bare-assignment target collection stops here.
isAssignTarget true for an assignment-like node: children[0]'s name is recorded as bound (Python-style bare assignment).
nameSlot This node holds no name itself (a wrapper such as a parameter or *args); its name is found by recursing into children[nameSlot].
isDestructuringPattern Marks an array or object pattern whose members each bind a name.

A declaration from Core, VarDecl:

scope() {
    return {
        introduces: (node: any) => {
            const nameNode = node.name;
            if (isNode(nameNode) && (nameNode.head === "arrayPattern" || nameNode.head === "objectPattern"))
                return nameNode.children.map((c: any) => refName(c)).filter((n: any) => !!n);
            return refName(nameNode);
        },
        initIndex: 2,
    };
}

and a bare assignment, which introduces nothing itself but binds its target:

scope() {
    return { isAssignTarget: true, initIndex: 1 };
}

(Both from plugins/lang-core/languages/concepts-symbols-defs.concept.js.) refName(node) is the helper that extracts a name from a reference node, a wrapper with nameSlot, or a bare string.

Adding introduces turns other things on

introduces also feeds the tree-wide set of block-scoped names, which gates whether the built-in variable-out-of-scope check looks at a name at all. Adding it to fix completion can start enabling that check across existing samples. Verify the samples afterwards.

dataflow()

dataflow() {
    return {
        isTerminator: false,           // acts like return/break: no code follows
        readSlots:  ["value"],         // slot names whose reference children are reads
        writeSlots: ["target"],        // slot names whose reference children are writes
        analyze(node, def, ctx) { /* custom flow logic */ },
    };
}

analyze(node, def, ctx) returns the post-state, the set of definitely-assigned names, or null for a definite terminator. ctx provides varDecls, issues, recurse(child, def), refName, gatherAssigns and addIssue(nodeId, severity, message). Symbol uses it to warn about use before initialization:

dataflow() {
    return {
        analyze(node: any, def: any, { varDecls, addIssue }: any) {
            const name = typeof node.name === "string" ? node.name : null;
            if (name && varDecls.has(name) && !def.has(name))
                addIssue(node.id, "warning", `'${name}' may be used before it is initialized`);
            return def;
        },
    };
}

A block threads def through its statements with recurse, stopping when a statement returns null (Block in plugins/lang-core/languages/concepts-control-flow-blocks.concept.js). Control-flow concepts additionally declare branch, loop and try shapes. A language with no scope() or dataflow() descriptors gets no analysis for those concepts; a language-less run falls back to a registered "shape floor" (registerDataflowShapeFloor), which Core registers and the engine otherwise leaves empty.

Builders for the common shapes

Three shapes repeat so often that they have a one-line spelling. A builder returns the same descriptor the hand-written body returned, so nothing else changes: the engine, the tabs and a saved language all see the ordinary introduces / analyze object.

import { scoping } from "../../../src/aspects/scoping.ts";
import { flowing } from "../../../src/aspects/flowing.ts";

// the node introduces the name its slot refers to (a symbol / name reference)
scope(self) { return scoping.declares(self.name); }

// ...or the plain text its slot holds ({ allowEmpty: true } keeps an empty string)
scope(self) { return scoping.declaresText(self.name_); }

// a loop: each `before` slot is analysed with the incoming def, the body on a fork of it,
// and the names `binds` introduces are assigned inside the body
dataflow(self) { return flowing.loop({ body: self.body, before: [self.start, self.end], binds: self.var_ }); }

self is the slot-handle map (the same one editor = this.template((self) => ...) receives), passed when the concept is harvested. A slot is named by its field name (self.var_, self.else_), and a name the concept does not have is an error when the concept loads (no such slot on this concept), not a silent undefined later. A builder is only for the exact shape; a scope with a process hook, a loop that does anything beyond the shape, or an if stays an ordinary scope() / dataflow() body. Use node.children[i] or the accessor in a hand-written body as before.

Authoring without code

You can express the common cases as data, in the Language tab:

  • Flat fields: scopeIntroducesSlot, scopeInitSlot, scopeCreatesAssignBoundary, scopeIsAssignTarget, dataflowReadSlots, dataflowWriteSlots (see ConceptSchema in src/lang-schema.ts).
  • Free-form bodies: scopeBody and dataflowBody hold arbitrary JavaScript compiled from a string.
  • A projectional descriptor, scopeNode/dataflowNode, built from the plugins/lang-scopeflow/ concepts. It covers name extraction and four dataflow fields, and is described in Scopeflow language.

Precedence when several are present on a persisted concept: scopeBody wins, then the flat fields, then the projectional scopeNode (see mergeInheritance in src/workbench/lang-class-inheritance.ts).

Reference slots

A Ref slot stores the name of a declaration. Three optional hooks control how it resolves and what it offers:

Hook Role
referenceScopes() { [slotName]: (node, lang, ctx) => Node[] or Set<Node> or null }. The explicit set of valid target declarations. ctx is { root, models }, where models holds sibling model files for cross-file resolution.
linkTargets() { [slotName]: (targetNode, refNode, parentNode, slotName, lang) => string or { message, severity } or null }. Validates a resolved reference against the declaration it points to. Runs only after referenceScopes resolved a candidate.
stringCandidates() { [slotName]: (node, lang, ctx) => string[] or null }. Candidate strings for a plain string property slot; a pick is written into the slot as-is.

plugins/lang-entities/ shows the pattern: a property reference whose valid targets are only entity-property declarations across every model in the project.

referenceScopes() {
    const target = (_node: any, _lang: any, ctx: any) => {
        const out: any[] = [];
        const walk = (n: any) => { /* collect entityProperty nodes */ };
        const roots = ctx.models?.length ? ctx.models.map((m: any) => m.ast) : [ctx.root];
        for (const r of roots) walk(r);
        return out;
    };
    target.byId = true;       // resolve by node id rather than by name
    return { target };
}

Concept-typed completion falls out of this for free. A reference slot with no provider falls back to name matching and offers poor candidates. A candidate declaration also needs a name that scope analysis can read, via introduces or isAssignTarget, or it is silently dropped from the list.

Testing

tests/test-cross-file-scope.mjs and the scope and dataflow suites show how to build a tree and call the analysis functions directly. Verify completion and rename in the editor too. See Testing.