Skip to content
SheetForge

Validators and edges

A domain validator adds your own rules to import validation. An edge contributor declares connections that the core reference scanner cannot see. Both are opt-in. A custom type that holds a key inside it needs both.

Add a domain validator

Core validation is fixed at four kinds: keys, references, @overlap and asset keys. A domain validator covers the rules beyond them.

Rule kindExample
Cross-columnIf type is Custom, script is required
Cross-tabChecking the meaning of a referenced record

Implement ISheetForgeValidatorPlugin and register each validator.

using SheetForge.Core.Model;
using SheetForge.Core.Plugins;
using SheetForge.Core.Validation;
 
public sealed class SkillsPlugin : ISheetForgePlugin, ISheetForgeValidatorPlugin
{
    // ... Name / RegisterEnums / RegisterCellParsers unchanged ...
 
    public void RegisterValidators(DomainValidatorRegistry validators)
    {
        validators.Register(new CustomEffectRequiresScriptValidator());
    }
}
 
public sealed class CustomEffectRequiresScriptValidator : IDomainValidator
{
    public string Name => "CustomEffectRequiresScript";
 
    public void Validate(DomainValidationContext ctx)
    {
        if (!ctx.Tables.TryGetValue("ExampleEffects", out var effects)) return;
        if (!effects.Schema.TryGetField("script", out var scriptField)) return;
        foreach (var rec in effects.Records)
        {
            if (!(rec["type"].Value is EnumValue ev) || ev.MemberName != "Custom") continue;
            var scripts = rec["script"].AsList;
            if (scripts != null && scripts.Count == 0)
                ctx.Errors.Add(new ImportError(ImportErrorCode.DomainRuleViolation,
                    new CellCoordinate("ExampleEffects", rec.RowNumber, scriptField.ColumnNumber, "script"),
                    /* what */ rec["codeName"].Value.ToString(),
                    /* why  */ "A Custom effect must specify a script to run, but 'script' is empty.",
                    /* how  */ "Put a script address in the 'script' column, or change 'type'."));
        }
    }
}

Registered validators automatically join both import validation and the authoring pre-flight.

Validator rules

Report violations into ctx.Errors as ImportErrorCode.DomainRuleViolation. Never throw. A thrown exception is caught and reported as a DomainRuleViolation error, and the other validators still run.

Fill all four elements of the error.

ElementProperty
WhereCellCoordinate
WhatActualValue
WhyExpected
HowSuggestion

The "how" is displayed verbatim as the actionable sentence.

Your validator inherits two rules of the import automatically. Validation collects everything in one run. If one error exists anywhere, the intermediate representation (the IR) is not assembled.

What the context provides

ctx gives a rule the parsed data of the run.

MemberHolds
TablesAll parsed tables
KeyIndicesKey indices
AssetKeysAsset keys. null means asset validation was skipped

Tabs from other workbooks

ctx also gives the read-only tabs of the other workbooks in the project, in ReferenceTables and ReferenceKeyIndices. When there are no other workbooks, both are empty, never null.

A rule looks a key up there the same way it does in Tables. Nothing from them enters this run's own result.

One settings asset is one workbook explains how a project holds more than one workbook.

Add an edge contributor

An edge contributor declares edges that the core reference scanner cannot see, such as a stat referenced inside a mini-grammar value.

Declare them if you build tooling over the data graph, or want the record canvas to draw your domain's connections.

public sealed class SkillsPlugin : /* ... */, ISheetForgeEdgePlugin
{
    public void RegisterEdgeContributors(EdgeContributorRegistry contributors)
    {
        contributors.Register(new ModifierStatEdgeContributor()); // effect → stat edges
    }
}

An IEdgeContributor receives a read-only cross-tab context and appends EdgeSpec items. Each item carries:

  • The from and to tab, each with a record id.
  • An optional field.
  • A payload record.
  • A label.

Contributors never emit diagnostics, because edges are material for the graph projection, not validation. See Types that build the graph.

A custom type that holds a key

RecordId@Tab is the one reference shape the Core understands. It gets four services for free:

  • Integrity checking.
  • Graph edges.
  • Nearest-match suggestions.
  • Rename propagation.

Your own notation may swallow a key, as in attack:add:10, stat.hp>50 or fire@0.4. The Core then sees one opaque string, so those four services stop at your notation.

Three pieces put three of the services back. Write them as a set. A notation with only one of the three can import without errors while the keys inside it stay unchecked or unseen. The table shows what is lost without each piece.

The three pieces

PieceContractWhat it restoresWithout it
1. IntegrityIDomainValidatorA missing key inside your notation is reported, with the coordinate and an actionable sentenceA typo imports cleanly and fails at runtime
2. VisibilityIEdgeContributorThe buried link becomes a real edgeThe connection exists in the data and nowhere on screen
3. The "how"TextSuggestion.FindNearest inside piece 1A suggestion in the sentence shape of the built-in reference errorsA correct diagnosis with no way to act on it

Piece 1 is a domain validator. Piece 2 is an edge contributor.

With piece 2, the canvas draws the edge, the Used by count in the node inspector includes it, and the reference index indexes it.

Piece 3 produces a sentence such as "Unknown stat 'atack'. Did you mean 'attack'?".

Validate and suggest together

Pieces 1 and 3 go in the same class. The suggestion belongs in the validator, because it is the only one of the three that produces a sentence a person reads.

// Piece 1 + 3 together — the validator is where the suggestion belongs, because it is the
// only one of the three that produces a sentence a person reads.
using SheetForge.Core.Model;
using SheetForge.Core.Validation;
 
public sealed class ModifierStatExistsValidator : IDomainValidator
{
    public string Name => "ModifierStatExists";
 
    public void Validate(DomainValidationContext ctx)
    {
        if (!ctx.KeyIndices.TryGetValue("Stats", out var stats)) return;   // no target tab: nothing to check
        if (!ctx.Tables.TryGetValue("Effects", out var effects)) return;
        if (!effects.Schema.TryGetField("modifier", out var field)) return;
 
        foreach (var rec in effects.Records)
            foreach (string statKey in StatKeysIn(rec["modifier"]))       // your notation's own split
            {
                if (stats.Contains(statKey)) continue;
                string near = TextSuggestion.FindNearest(statKey, stats.Keys);   // piece 3
                ctx.Errors.Add(new ImportError(ImportErrorCode.DomainRuleViolation,
                    new CellCoordinate("Effects", rec.RowNumber, field.ColumnNumber, "modifier"),
                    /* what */ statKey,
                    /* why  */ "This modifier points at a stat that does not exist in 'Stats'.",
                    /* how  */ near != null
                        ? "Did you mean '" + near + "'? Fix the stat name in the modifier value."
                        : "Add that record to 'Stats', or correct the stat name."));
            }
    }
}

Share one splitter

Reuse one splitter for the notation. The parser, the validator and the edge contributor must agree on where a key starts and ends. If each keeps a private copy of that split, the three copies drift apart.

A wrapper type gets this for free, because TrySplit is the shared splitter.

Rename propagation

The fourth service, rename propagation, needs one more thing. Renaming a record rewrites referring cells only where the Core can find the key in the text. The Core can find it in:

  • A RecordId@Tab field.
  • A list of them.
  • A wrapper whose TrySplit exposes the key as an element.

The Core cannot guess at your grammar's substring boundaries on its own. There are two ways to handle that.

ChoiceWhat you doResult
Tell it howImplement IReferencingCellTypeOne opt-in replaces this whole three-piece recipe and restores all four services at once
Accept the boundaryNothing morePiece 1 reports the now-dangling key on the next import, with the coordinate and the suggestion

Reference parity describes IReferencingCellType.

If you accept the boundary, a rename does not rewrite the key inside your notation. The break is reported, not silent.

When the recipe still applies

The three-piece recipe is still the right answer when the column has no @target, because there is no single tab the key lives in.

In the bundled sample, List<Modifier> names no target, so the Core cannot know where attack should resolve. ModifierStatEdgeContributor opens those edges by hand.

Give the column a target, as in List<Modifier@Stats>, and Reference parity takes over.

Next steps