Skip to content

Checks, constraints and types

Every hook on this page takes one destructured context object (check({ node, report }: CheckContext)), the same convention as eval and generate; see Hook contexts. Four independent mechanisms annotate the AST with problems. They all produce the same shape, a Map<nodeId, [{ severity, message }]>, so the editor shows them identically as inline markers and in the Checks pane. runChecks(root, lang) (src/checker.ts) is the single entry point and merges the others in.

Mechanism Declared as Catches
Checks checks() on a concept Arbitrary per-node semantic rules, written as functions
Constraints .must(...) on the slot (or constraints()) A rule about the value in one slot
Type system typesystem() on a concept Type mismatches, from inference and overload signatures
Built-in passes engine, no authoring Unreachable code, uninitialized reads, unused assignments, invalid identifiers, link-target resolution

Severity is "error", "warning" or "info". A check or constraint returns null for no issue, or { message } to report one at the node (the severity comes from the rule). A check may instead call report(message) (report.warn(...), report.error(...) override the rule's severity) any number of times.

Rules as decorated methods

A rule can also be a method with a decorator, named by the method. This is how the Language Editor's root tabs show and add rules.

export class Pair extends Concept() {
    head = "pair";
    left = ChildSlot({ type: "expression" });
    right = ChildSlot({ type: "expression" });

    @check
    sameKind({ node, report }) {
        if (typeof node.left !== typeof node.right) report.error("the two sides differ in kind");
    }

    @infer
    type() { return "string"; }
}
Decorator Same as Tab
@check name(ctx) one entry of checks() (a CheckContext) Types, Checking rules
@infer name(ctx) typesystem().infer (one per concept) Types, Inference
@constraint name(ctx) one entry of constraints() Rules, Constraints
@intention addElse(ctx) one entry of intentions(); the label is the method name as words ("Add else") Intentions
@when("addElse") canAddElse(ctx) that intention's isApplicable (the name is a string) Intentions
@evaluate run(ctx) the concept's eval Running
@textgen text(ctx) the concept's generate Output text
@dataflow flow() the concept's dataflow Scope & flow
@scopeRules names() the concept's scope Scope & flow
@reduce toModel(...) the concept's reduce Files

Each is a root of its own in the Language Editor: a tab named by the method, added with + and deleted with ×. They work in bundled concept files and in project concept files (compiled at runtime; check, infer and constraint are in scope, so no import is needed). They harvest into the same validations as the hooks above, so the checker and the Checks pane treat them identically. Options. @check and @intention take an optional options object, and the bare form is unchanged: @check({ name: "same-types", severity: "warning" }) keeps a rule's own name (suppress markers, the Checks pane and tests match it) and severity (a rule that returns { message } is reported at that severity; report.error / report.warn keep their own), and @intention({ label: "Name theitparameter", description }) spells the Alt+Enter label that the method name cannot (intentionLabel only splits camelCase). A rule does not take pattern, predicates or concept options: those stay on checks(). A subclass keeps its parent's decorated rules and replaces one by using the same method name, marked @override (@override @check sameKind(ctx) { super.sameKind(ctx); ... }): super.name(ctx) runs the parent's rule first, so the override extends it instead of hiding it. A rule can also be declared on an interface (class ILabelled extends Interface() { @check needsLabel({ node, report }) {...} }): every concept that implements it (Concept(ILabelled)) has that rule as if it had declared it itself, and the Language Editor lists it as inherited from the interface. The interface's methods have no slots of their own, so write them with node.slot and an explicit context parameter (bare slot names need the class that declares the slots); the first interface wins when two declare the same rule, and a parent class's own rule wins over an interface's. A replacement without @override, or an @override that replaces nothing, is a designer-time problem (overrideProblems(ctor); not yet shown in the Language Editor), and inheritedRootsOf(ctor) lists the roots a class inherits. Call super with the context argument: a bare-name method has no parameter to pass on, so write the override with an explicit ctx parameter. Arguments that name another member are strings, not bare names (@when("addElse")). There is no @eval: a decorator called eval would be the global function, so the evaluation root is @evaluate. The single-hook decorators (@evaluate, @textgen, @dataflow, @scopeRules, @reduce) also make the method available under the hook's own name, so a class has one of each.

Bare names. A decorated method written with no parameter list reads its context's names directly: a @check has node, lang, nav, scopeAt, blockScopedNames, resolves, declarationOf, duplicates, match, report and its class's own slots (@check sameKind() { if (typeof left !== typeof right) report.error("the sides differ"); }); @infer has node, env, typeOf, expected, detail, tools; @constraint has value, parent, slot, lang, nav, resolves, declarationOf, duplicates; @intention has node, editor, lang, selection; its @when guard has node, lang, parent, slot, root, getTypeInfo, index, selection; @refactoring has node, model, ask, editor, lang; @migration has model, lang. Every kind that has a node (check, infer, intention, its guard, refactoring) also binds its class's own slots by name, as values to read (assigning to a bare slot name only changes the local: write through node, e.g. node.set("left", x)). A method that lists its own parameters is left as written. The names are supplied when the file is compiled, on the method's own line, so line numbers still match. Two things to know: a const or let with one of these names in the method body is a syntax error (use another name), and a slot inherited from a parent class declared in another file is read as node.slot (a parent in the same file is known, so its slots are bare names too). The Language Editor knows these names inside such a method: it does not report them as undefined, and completion offers them there (the context's names for that kind, plus the slots). A name such as reprot that is not a verb or slot of the method's kind, not a JavaScript global and not declared or imported anywhere in the file gets a warning ("nothing declares it"); the check is file-wide and name-based, so it only fires when no declaration of that name exists at all.

Refactoring parameters. In a @refactoring method, ask("How many copies", 2) is a question: the labels and literal defaults of all its ask calls are found before the method runs and put to the author in one dialog, one labelled field per question (with a single question, one text box; a host without the form dialog asks them one after another; each field has its default filled in; a number or yes/no default reads the answer as that type), and the method then runs once with the answers. Cancelling any question cancels the refactoring, so nothing is half-applied. When the method has run, the message line says what it changed (Duplicate: 3 nodes: 2 added, 1 changed); the whole refactoring is one undo step. An ask whose label is not a literal string just returns its default.

Checks

checks() returns an array of rules. The function receives a CheckContext:

checks() {
    return [
        {
            name: "variable-out-of-scope",
            severity: "error",
            check({ node, scopeAt, blockScopedNames }: CheckContext) {
                const name = node.name;
                if (typeof name !== "string" || !name) return null;
                if (!blockScopedNames.has(name)) return null;
                const scope = scopeAt(node);
                if (!scope) return null;
                if (!scope.has(name)) return { message: `"${name}" is not defined in this scope` };
                return null;
            },
        },
    ];
}

(From Symbol in plugins/lang-core/languages/concepts-symbols.concept.js.)

CheckContext (src/checker.ts) carries node; lang (active Language); nav (an AstNav factory); scopeAt(node) (the names in scope at a node, from scope analysis; undefined when the node was not recorded); resolves(ref) (true when the reference resolves to exactly one declaration) and declarationOf(ref) (that declaration node, or null), both answered by the candidate-aware resolver so a qualified name (exprˑfunction) or a same-named declaration is handled the way the editor handles it (a check and a constraint both have them; never compare a reference's name with a declaration's); duplicates(items, key?) (the groups of two or more items that share a key, in first-seen order: for (const group of duplicates(names)) report("duplicate name", group[1]); the key defaults to a primitive's value or a node's first primitive child, and an empty key never counts); blockScopedNames; match (captures from a pattern, {} otherwise) and report (report(message, target?): pass another node as target to file the issue on it, e.g. a duplicate child). Destructure only what you use: the Language Pane rewrites the header from the body when you save. check() keeps node in the context (rather than this) because the checker walks plain nodes and binding this would mean building a class instance per node per run.

A rule normally runs on nodes of the concept that declares it. Three optional gates narrow or widen that:

  • interface: "IValidIdentifier" runs on every concept that conforms to the interface, instead of one copy per implementor. It takes precedence over concept.
  • pattern runs only on nodes matching a structural shape and captures slot contents into bindings. Build patterns in the Checks pane's "+ Add structural pattern", in code, or as text in constructor notation: pattern: "Divisor(rhs: zero@0)" is the same pattern as headMatch("Divisor", { rhs: capture("zero", literal(0)) }) (a mistake in the text is reported once on the model, with its position). See Pattern language.
  • With no gate in a language-wide rule, the check runs on every node.

Some interface checks are built in, so implementing the interface is all a concept needs: IValidIdentifier, INameAllUpperCase, INameFirstCharLowerCase, INameFirstCharUpperCase (name-kind slots), and IContainerOfUniqueNames (direct INamedConcept children must have distinct names). IOptionallyNamed is INamedConcept with an optional name.

Rules saved from the Language tab are plain JavaScript compiled from a body string with positional parameters (node, lang, navFor, scopeMap, blockScopedNames, bindings); there is no separate query language for them.

Opt-in engine checks: set reportUnresolvedReferences = true on the language to flag every reference node whose name scope analysis knows nothing about. Leave it off if the language has ambient or builtin names you have not modelled in scope().

Constraints

A constraint governs one slot. It runs once per value occupying the slot, so a rule is declared once and fires for every node of that shape. A primitive offender is attributed to the parent node (a primitive has no id of its own); a nested node offender is attributed to that child. It is declared on the slot itself with .must(name, check, severity?):

stmts = ChildSlot({ type: IStatement, cardinality: "0..n" }).must("no-bare-variable-statement", bareVariableStatement, "warning");

(From Block in plugins/lang-core/languages/concepts-control-flow-blocks.concept.js; bareVariableStatement is a shared rule body in core-slot-rules.js, because every body slot of Core carries the same rule.) ConstraintContext is { value, parent, slot, lang, nav }; severity defaults to "error" and calls chain. check may also return a plain string. An absent optional (0..1) slot can arrive as undefined rather than a node; guard for it. The rule becomes the same constraint validation as before, so completion (which asks whether a candidate would violate the slot) and the Checks pane see it unchanged.

Value rules are ready made. src/constraint-rules.ts states the common ones, so every language words them alike:

steps = Prop({ type: "number", default: 1 }).must("steps-is-a-count", wholeNumber("Steps", 1));
diameter = Prop({ type: "number", default: 600 }).must("positive-diameter", positive("Outer diameter"));
currency = Prop({ type: "name" }).must("currency-is-an-iso-code", textMatching("The currency", /^[A-Z]{3}$/, "a three-letter code such as EUR"));

positive, nonNegative, wholeNumber(label, min) and textMatching pass a value that is not there yet or not of the kind they judge. A rule about a name that must be unique among siblings needs no code: implement INamedConcept on the items and IContainerOfUniqueNames on the container. Report each mistake once: when a constraint and a check would say the same thing, keep the constraint and let the check go.

A slot inherited from a base class cannot carry .must() (the declaration is in the base). Such a concept, or a rule that must be shared through interface, keeps the constraints() hook, which lists { name, slot, severity, check({ value }: ConstraintContext) } entries.

Type system

typesystem() returns a descriptor. A concept implements either overloads or infer/check, not both.

typesystem() {
    return {
        overloads: {
            variadic: true,
            signatures: [
                { params: ["number", "number"], return: "number" },
                { params: ["string", "string"], return: "string" },
            ],
        },
    };
}

(From Plus.) overloads is the declarative form for operators, and gives you both inference and the mismatch check from one signature list, resolved with the language's assignability predicate.

The two declarative shapes also have builders (src/aspects/typing.ts), which return the very same descriptor, so you write the table and not the object:

import { typing, overload } from "../../../src/aspects/typing.ts";

typesystem() {
    return typing.variadic(overload("number", "number").returns("number"), overload("string", "string").returns("string"));
}
typesystem() {
    return typing.result("any");                                  // infer() { return "any"; }
}

Three more builders cover the shapes that most hand-written rules repeat (the census is node scripts/type-rule-census.mjs; a builder exists only for a shape that occurs often):

typesystem() {
    return typing.same("expr");                                   // the node has the type of its `expr` slot (a position works too: typing.same(0))
}
typesystem() {
    // a number whose `operand` must be a number; `items` would check every item of a list slot
    return typing.result("number").expects("operand", "number");
    // ...with another severity or text: .expects("operand", "number", { severity: "warning", message: "{head} wants {expected}, not {got}" })
}
typesystem() {
    // `variable` names a variable that exists inside `expr` only (with type number); `at` is walked outside it first
    return typing.result("number").binder({ variable: "variable", type: "number", outer: ["at"], body: ["expr"] });
}

expects is also the slot's expected type: it is pushed down to the operand's inference (an empty list literal takes its element type from it) and filters the completion of an empty slot. A mismatch inside an argument says where, through {why} (default text: T: expected list<string>, got list<number> (argument 1 of list: expected string, got number)); tools.explain(got, expected) gives a hook the same path. expects never reports a value of unknown type (any) and looks through a transparent wrapper such as an option; the default text is <head>: expected T, got U. binder takes a list in variable when the body has several variables of the same type. Builders chain in any order and may be spread into an object next to hand-written hooks: { ...typing.same("expr"), check() { ... } }.

Say it when no type is computed. Every concept says what its type is. A concept with no rule still gets any (or void when it implements IStatement), but nothing then tells "no type on purpose" from "forgot". Two builders state it:

typesystem() {
    return typing.untyped("DSL value; no type model yet");   // the node is `any`; the reason says why, in a few words
}
typesystem() {
    return typing.noValue();                                 // the node produces no value: `void`
}

Both answer exactly what the fallback answered (any / void), so declaring one never changes a diagnostic; the difference is that the engine, the hover text (Unknown (no type is computed for this concept: ...)), workbench.types.describe(...) (its source is rule, declared-any, declared-void, role-void or missing, plus the reason) and workbench.types.coverage() can tell them apart. A concept implementing IStatement is covered by its role. In a hand-written object, spread it: { ...typing.untyped("check only"), check() { ... } }. A persisted language stores the same declaration as a type rule whose body is only return 'any';. The Types tab shows them as the rows no type computed because "..." and no value.

tests/test-type-coverage.mjs is a ratchet over every built-in language: a concrete concept with no rule, no declaration and no statement role fails it (UPDATE_TYPE_COVERAGE_BASELINE=1 only to tighten, never to add). For your own language, strukts check --types-coverage lists the concepts that say nothing as info findings (STRUKT-TYPE-UNDECLARED), and --strict-types makes them errors. A new concept made in the Language Editor starts with return 'any' declared; replace it as soon as the concept has a type.

Generic signatures. A type that starts with an apostrophe is a type variable: overload("list<'T>", "number").returns("'T") is the signature of an indexing operator whatever the element type is, and overload("'T", "'T").returns("list<'T>") makes a list of two values of one type (bool and number unify as number when bool is a declared subtype of number; number and string do not fit). An operand of unknown type (any) never fixes a variable and is never reported. A hook can do the same by hand with tools.unify(pattern, actual) and tools.substitute(term, bindings); a function that a walk binds with env.setFunction("first", "'T", ["list<'T>"]) is typed at every call from its arguments.

Unions, conversions, class hierarchies. Opt in per language: a typeConstructors entry with union: true makes the join of unrelated types a union<A, B> instead of any (and A fits where union<A, B> is expected); a subtypes edge with conversion: true accepts a number where a string is expected without making it a subtype; and a declares hook that returns supers: ["Animal"] makes the declared type a nominal subtype (Dog and Cat join at Animal). For flow typing, typing.narrows({ variable: "variable", to: "number", then: ["then"], otherwise: ["otherwise"] }) gives each branch the type the test established (in the other branch a union loses the members that fit); a hook uses tools.narrow / tools.exclude with tools.bind.

typing.overloads(...) / typing.variadic(...) take .severity("warning"), .message("...") and .explain("reason", "hint"). explain is the mismatch in plain words for a reader who does not know type notation, and hint is what to do about it; hosts show them next to the engine's own message (the issue's explain, see the embedding guide). Placeholders: {mix} the kinds that were given ("text and number"), {bad} the source text of the operand that does not fit, {badKind} its kind ("number") and {badType} the same with an article ("a number"), {kind} the first operand's kind and {expected} the accepted combinations. Core's +, -, * and / declare them; an overload table that gives none keeps its technical message and gets no explain. In the object form the keys are explain and hint beside signatures. The Types tab reads all of these spellings as rows (infers, overloads, same type as, expects ... : ..., binds ... in ... after ...) and writes a body back the way it found it; anything with logic (infer(...) { ... }, check, walk) stays the object. tests/test-aspect-probe-golden.mjs and tests/test-sample-diagnostics-golden.mjs are the checks for such a respelling.

For custom behaviour, write the hooks. plugins/lang-money/ infers "any" for its values and reports mismatches in check:

typesystem() {
    return {
        infer() { return "any"; },
        check({ node }: TypeCheckContext) {
            // ...resolve both operand currencies...
            if (lhsCurrency && rhsCurrency && lhsCurrency !== rhsCurrency)
                return { severity: "error", message: `Currency mismatch: cannot add ${lhsCurrency} and ${rhsCurrency}` };
            return null;
        },
    };
}
Hook Signature and role
infer ({ node, env, typeOf, expected, detail, tools }: TypeInferContext) => Type. Returns the type the node produces. env.get(name) looks up a variable (default any), env.set, env.child(). Call typeOf(child, expected?, childEnv?) to type children; childEnv types a child under a narrowed scope. expected is pushed down from the parent's expectedTypeOfSlot.
check ({ node, env, typeOf, whenConcrete, isSubtype, isAssignable, tools }: TypeCheckContext) => { severity?, message } or null. Reports a local mismatch; severity defaults to "warning". whenConcrete(child, fn) only calls fn when the child's type is known (not "any"). Prefer isAssignable(got, expected) for "A used where B is expected" and isSubtype for hierarchy.
overloads { operands?, variadic?, signatures, severity?, message?, explain?, hint? }, as above.
walk ({ node, env, walkNode, typeOf, walker }: TypeWalkHookContext). Takes over traversal of this node's subtree when you must bind names or open scopes. A child you do not pass to walkNode is never visited, so use it sparingly. walker is the engine's shared walk state (return-type stack, parameter table, class depth, tools).
expectedTypeOfSlot ({ node, slot, env }: ExpectedSlotContext) => Type or null. The type a slot should hold. Completion uses it to filter suggestions, and the type walker passes it to the child's infer as expected.
declares ({ node, tools }: TypeDeclaresContext) => { name, base?, refinement? } or null. This node declares a type (a typedef). An alias is transparent; a refinement is nominal, below its base, with the base assignable to it (the predicate is a runtime check).
denotes ({ node, denote }: TypeDenotesContext) => Type or null. This node is a type expression written as nodes; the type it denotes. denote(child) resolves a nested type node. Annotation slots holding nodes, typedef bases and tools.denote all resolve through it.

typesystem() still returns one descriptor object; the hooks inside it are the context-taking members above (a plan to split it into separate class members was not carried out, because overloads and the hooks are read together by one engine path). The hook inside the descriptor is named typeOf for the child-inference callback so it no longer shadows the hook called infer.

A Type is a structured term: a constructor plus arguments (number, list<number>, opt<number<0, 10, 2>>). A hook may return a type-name string, which is parsed for you, but everything a hook receives is a term: compare with the constants and helpers (NUMBER, isAny, isCon(t, "list")) from src/typesystem.ts, never with a string, and print with printType. The built-in names are number, bool, string, list, function, null, void and any; a language may add its own and declare a subtype hierarchy (Language#subtypes) and, per constructor, argument variance and wrapper behaviour such as options (Language#typeConstructors). tools carries the language-aware helpers — join, isSubtype, isAssignable, lift, unwrap, bind, denote, normalize. Returning nothing from infer means any. An unknown type is permissive: any never produces a mismatch. The full contract is in Type terms.

A language-wide override of another language's types goes through an overlay, as the JavaScript grammar demo does to allow string + number; see Language authoring guide.

The Type Trace pane shows the inference frames for the selected node, including detail(label, value) rows a hook records.

Intentions (quick fixes)

intentions() contributes actions to the Alt+Enter popup and the context menu:

intentions() {
    return [
        {
            name: "Convert to while",
            description: "Turn this if into a while loop",
            group: "Transform",
            isApplicable: ({ node }: IntentionApplicableContext) => node.else_ === undefined || isEmpty(node.else_),
            apply({ node, editor }: IntentionApplyContext) { editor.toggleIfWhile(node.id); },
        },
    ];
}

group picks the popup header (default "Refactor"; conventional others are "Folding", "Edit value", "Transform", "List", "Move"). isApplicable({ node, lang, parent, slot, root, getTypeInfo, index, selection }) gates the action (slot is the slot of parent holding node, index its position in a variadic slot); omit it to always offer. apply({ node, editor, lang, selection }) performs the edit through the Editor's public mutators and should finish with editor.fire(), or wrap several mutations in editor.transaction(() => ...) so undo sees one step. Details are at the head of src/editor/intentions.ts.

Range selection. When the user has selected a run of sibling nodes, both isApplicable and apply receive selection in their context, { parent, from, to, nodes }, or null when nothing is selected. An intention marked forSelection: true is offered only while a range under its own node is selected, which is how a "Wrap selection in..." action is written: it reads selection.nodes and rewrites selection.parent's children.

Alongside these, a concept can restrict where it may be placed with canBeChild({ parent, slot, lang }), canBeRoot({ lang }) and canBeAncestor({ child, lang }) (see Concepts).

Testing

Build a small tree, run runChecks(root, lang) and look up the node id in the returned map. The tests/test-checker.mjs, tests/test-constraint-runner.mjs and type-system suites show the pattern.

Type tests, in the language itself. A concept's @test roots (the Tests tab: givensnippetexpect ...) can state what the type system must say about a snippet, without running it. Write the expectation first, then the type rule:

@test("a sum of numbers is a number")
sum({ run }) { return run`1 + 2`.hasType("number"); }

@test("mixing text and numbers is reported")
mixed({ run }) { return run`1 + "a"`.hasTypeError("no overload matches"); }

@test("a well-typed snippet has no problems")
fine({ run }) { return run`"a" + "b"`.typeChecks(); }

hasType(t) compares the type the language infers for the snippet's last expression, typeChecks() passes when the type pass reports nothing (a type rule that throws counts, as the warning it is) and hasTypeError(part?) passes when it reports something, optionally with that text in the message. On the Tests tab the same three read as expect type "number", expect typechecks and expect typeerror "overload". They run with the other tests in the Tests pane and strukts test.

Spell-check core

src/spellcheck.ts checks words without depending on a dictionary library. A Dictionary is any { has(word), suggest?(word) }, so a Hunspell-compatible one such as nspell fits directly; the host loads it, lazily per language. checkSpelling(text, dict, options) returns each misspelling with its range and suggestions (identifiers are split on camelCase and snake_case; URLs, tokens with digits, short words and ALL-CAPS acronyms are skipped). findMisspellings(root, dict, shouldCheck) walks a tree and checks only the string children your shouldCheck(node, childIndex) accepts, which is where a per-slot spellcheck flag plugs in. ProjectDictionary is the case-insensitive "Add to dictionary" word list, serializable to JSON for a project sidecar, and applyReplacement backs a "Replace with" action.

In the checker. A concept that implements ISpellChecked has its string-kind slots spell-checked during runChecks; each misspelling is a warning (rule spelling) with up to three suggestions in its message, so the editor's normal squiggles and the Checks pane show it. The host turns this on by calling setSpellcheckProvider({ dictionary(lang), ignore? }) (src/spellcheck-checks.ts); with no provider, or a provider that returns no dictionary for the language, the pass does nothing. struktJS installs a provider at startup (installSpellcheck, src/spellcheck-host.ts) together with an English dictionary source. There is no per-slot flag.

Supplying a dictionary. A plugin calls registerDictionarySource({ id, locales: ["en"], load }); load() returns a Dictionary (wrap a Hunspell engine such as nspell, or use wordListDictionary(words) for a domain vocabulary). The dictionary for the active locale (default en, matched by prefix so en-GB uses an en source) loads on first use and is cached; the checks re-run when it arrives, and a failed load is not retried. Words added with "Add to dictionary" persist in local storage and are accepted everywhere.

English dictionary. src/spellcheck-en.ts registers the en source: nspell over dictionary-en (MIT / MIT AND BSD, both new dependencies). Both load through dynamic imports in load(), so they are separate chunks (about 190 KB gzipped together, mostly the word list) fetched on the first check of an ISpellChecked node and absent from the startup bundle. The .aff/.dic files are imported by relative node_modules path (?raw) because the package's exports exposes only its Node entry. Other languages: register another source for their locale. The spellcheckLocale preference (a select in Settings, also a Theia preference) picks the locale; off matches no source, so nothing is checked. It is read on every check.

Today the Changelog language's change entries implement ISpellChecked.

Intentions. With a provider installed, Alt+Enter on a node with a misspelled string slot offers a "Spelling" group: Replace "x" with "y" for each suggestion (up to five per word, three words), and Add "x" to dictionary when the provider has an addWord(word). Replace is a normal edit (one undo step); Add to dictionary changes no model content, so it re-runs the checks without an undo entry.