agentleFS
vchelaruvchelaru/Gum/.claude/skills/gum-tool-variable-references/SKILL.md

gum-tool-variable-references

Skill655 starsChanged 2 months agoMITView on GitHub

Gum variable references — Excel-like cross-instance/cross-element binding via Roslyn-parsed assignments. Triggers: VariableReferenceLogic, EvaluatedSyntax, ApplyVariableReferences, VariableChangedThroughReference, VariableReferences VariableListSave.

The file

We split this skill into the rules it gives an agent

2 rules. About 0 are common, 0 are distinctive, and 2 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈0

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    When designing fixes in this area, the question is almost always "did ApplyVariableReferences run on the state that owns the reference?" — …

    line 110
  2. Very specific:

    When a variable changes, DoVariableReferenceReaction finds all elements that reference the changed element via …

    line 118

≈ “Common” is an estimate: at least 1 in 5 of the 364,980 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Variable References

Variable references are Gum's system for keeping variables in sync across instances and elements, like cell references in a spreadsheet. A user writes X = SomeOtherObject.X and the left side stays updated whenever the right side changes.

Storage

Variable references are stored as a VariableListSave<string> on a StateSave, with Name set to "VariableReferences" (or "InstanceName.VariableReferences" for instance-scoped references). Each string entry is one assignment line.

Syntax

LeftProperty = RightSide
  • Left side: An unqualified property name on the owning instance/element (e.g. X, FontSize, Red).
  • Scoping (the two sides differ): On an instance's row, the left side is the instance's variable (X = writes Instance.X). A bare right-side name resolves against the containing element, so X = X assigns the containing component's X to the instance's X. Naming another instance needs Other.X. Runtime-computed names such as AbsoluteWidth follow the same rule (bare means the containing element). The Variables grid never rewrites a bare right-side name to the instance; it only adds a missing left side (ModifyLines, AddImpliedLeftSide). See ApplyVariableReferencesOnSpecificOwner in ElementSaveExtensions.GumRuntime.cs.
  • Owner prefix @: @Index on an instance row means "the instance that owns this row" and survives copy/paste, unlike Item1.Index. ElementSaveExtensions.ResolveOwnerPrefix rewrites it to Owner.Index (or drops it on an element row) before every evaluation, so EvaluatedSyntax never sees @. A new place that evaluates or validates a right side must call it first. The expression is parsed as C#, so an owner name that is not an identifier (gum-logo-256) is written as gum_x002D_logo_x002D_256; any code that reads a name back out of the rewritten text must pass it through ElementSaveExtensions.DecodeOwnerName.
  • Right side: A variable path, which can be:
    • Local: OtherInstance.X (same element)
    • Cross-element: Components/MyComp.InstanceName.Width (slash-separated element path)
    • Expressions: OtherInstance.Width + 10, OtherInstance.Width * 2, Index % 4 (modulo by zero evaluates to null, like /), !OtherInstance.Visible
    • Conditional/comparison/logical operators: ternary cond ? a : b, ==, !=, <, >, <=, >=, &&, ||, !
    • Gum's own function set (GumCommon/Runtime/ExpressionFunctions.cs, the single table of names, arities and implementations): Sin Cos Tan Sqrt Abs Floor Ceiling Round Min Max Clamp. Plain names only, no Math. prefix (Math.Max is rejected with a hint), trig takes degrees to match Rotation. These are Gum semantics that look like C#, not .NET methods; to add one, add it to that table. Name-only scanners (HeadlessErrorChecker) read ExpressionFunctions.Names. Code that walks right-side identifiers (qualifying, dependency reads) must skip EvaluatedSyntax.IsFunctionName, or Sin(X) becomes Inst.Sin(X). GetFunctionCallProblem supplies the validation message for unknown functions or wrong argument counts.
    • Category-state LHS: <CategoryName>State = "StateName" assigns the categorical state by name
    • Literals: X = 42
  • Row splitting: a row splits at its first = only (Split(equalsArray, 2, ...)), because the right side may hold ==, !=, <= or >=. Any new row parser must pass the count of 2, or X = A == B ? 1 : 2 silently evaluates to nothing. Equality between numbers of different types (Width == 50, float against int) compares by value (EvaluatedSyntax.AreEqual).
  • Comments: Lines starting with // are skipped. Invalid lines are auto-commented on validation failure.
  • Shorthand: Writing just OtherInstance.X (no left side) auto-expands to X = OtherInstance.X.
  • Composite names (Color, CornerRadius): a line like Color = OtherInstance.FillColor is stored collapsed and expanded into per-channel lines (Red = OtherInstance.FillRed, ...) at apply and validate time by ElementSaveExtensions.ExpandCompositeReferenceLine. Any code reading raw VariableReferences line text must expand through that method first: there is no Color variable, so matching the collapsed left side against real variable names silently never hits.

Roslyn Parsing

The syntax is parsed as C# via Roslyn. Slashes in element paths are converted to global:: qualified names before parsing (Components/Foo becomes global::Components.Foo) and converted back after. The EvaluatedSyntax class handles conversion (ConvertToCSharpSyntax / ConvertToSlashSyntax) and recursive evaluation of the right-side expression tree.

Architecture

SetVariableLogic (variable change entry point)
  ├─ calls VariableReferenceLogic.DoVariableReferenceReaction()
  │    ├─ Validates lines (GetIndividualFailures)
  │    ├─ ElementSaveExtensions.ApplyVariableReferences() — writes hard values to StateSave
  │    ├─ Finds all elements that reference this element (via ObjectFinder.GetElementReferencesToThis)
  │    ├─ Applies references on those elements too (cascade)
  │    └─ DoVariableReferenceReactionOnInstanceVariableSet() — deep propagation for tunneled vars
  └─ calls VariableReferenceLogic.ReactIfChangedMemberIsVariableReference()
       └─ ModifyLines() — auto-expansion and qualification of newly entered references

Key Classes

ClassLocationRole
VariableReferenceLogicTools/Gum.Presentation/Plugins/InternalPlugins/VariableGrid/Tool-side orchestration: validation, reaction to changes, line expansion
EvaluatedSyntaxRuntimes/GumExpressions/Roslyn-based expression parser/evaluator (shared Gum.Expressions package); resolves right-side values via RecursiveVariableFinder, or via a live GraphicalUiElement for Absolute* identifiers (see below)
ElementSaveExtensions (partial)GumRuntime/ElementSaveExtensions.GumRuntime.csApplyVariableReferences — two overloads: one for ElementSave (save-class, tool-time), one for GraphicalUiElement (runtime)
MainVariableGridPluginTools/Gum.Presentation/Plugins/InternalPlugins/VariableGrid/Calls GumExpressionService.Initialize() so the tool uses Roslyn evaluation

Two Apply Paths

ApplyVariableReferences has two overloads:

  1. ElementSave overload (tool-time): Iterates VariableListSave entries, evaluates right sides, writes hard values into the StateSave via SetValue. Fires VariableChangedThroughReference delegate when a value actually changes, which routes through PluginManager.VariableSetThroughReference: plugins that subscribe to PluginBase.VariableSetThroughReference get that event (codegen and errors defer non-selected elements to once per commit), every other plugin gets a plain VariableSet (font generation, etc.).
  2. GraphicalUiElement overload (runtime): Similar iteration but calls referenceOwner.SetProperty(left, value) on the runtime object. Used for wireframe preview in the tool and at game runtime.

Right-Side Evaluation

GetRightSideValue resolves the right side of an assignment:

  • In the tool: CustomEvaluateExpression is set by MainVariableGridPlugin to use EvaluatedSyntax (Roslyn parsing with full expression support).
  • At runtime (no tool): Falls back to RecursiveVariableFinder with simple dot-path lookup — no expression support, just direct variable resolution.

Resolving Absolute* Identifiers (AbsoluteX/Y/Left/Top/Right/Bottom/Width/Height)

These exist only as computed properties on an already-laid-out GraphicalUiElement — never as authored StateSave data — so RecursiveVariableFinder can never resolve them. EvaluatedSyntax takes an optional liveRoot (a GraphicalUiElement) threaded all the way from the top of the apply chain; when the right side's final identifier is one of these names, it resolves against liveRoot.GetGraphicalUiElementByName(...) instead of falling through to state lookup. liveRoot is scoped to one element (mirrors how instance names are scoped), so a cross-element (Components/Foo...) reference never attempts this resolution.

Both apply paths supply liveRoot when a live tree is available: the tool passes IWireframeObjectManager.GetRepresentation(parentElement) (null when nothing is currently rendered for that element); the runtime passes the top-level GraphicalUiElement already being applied against. Validation (AddFailureForLine) needs the same liveRoot as the apply call, or a valid Absolute* reference gets auto-commented out before it's ever applied.

Resolving Index (position among siblings)

Index / Instance.Index (TryResolveSiblingIndex in EvaluatedSyntax) reads the live tree when there is one, and otherwise the element's own instance order and Parent values (GetSiblingIndexFromData), so it resolves with nothing displayed, unlike Absolute*. An authored variable named Index is tried first and wins, so a component can define its own. Siblings are the instances sharing a Parent; in the live tree an instance with no Parent counts only other parentless instances, because the containing element's ContainedElements list is flat. EvaluatedSyntax.IsLiveLayoutName marks Index and Absolute* as read-only for validation, and HeadlessErrorChecker.RuntimeComputedVariableNames keeps GUM0009 quiet; a new live-layout name needs all three places.

Index goes stale when instances move, so VariableReferenceLogic.ReapplySiblingDependentReferences re-evaluates every state with a row matching \bIndex\b. VariableGridPluginBase calls it on InstanceAdd (a paste is an add), InstanceDelete, InstanceReordered and a Parent change. A row that only reads @Height needs none of this. Tests/Gum.Avalonia.Tests/EndToEnd/VariableReferenceRulerScenarioTests.cs drives the whole path (typed rows, copy, reorder, delete, undo).

global::Localization.CurrentLanguage

Reserved identifier resolving the current language index — see the gum-runtime-variable-references skill for the resolution mechanism. Tool preview works because a language change (ProjectPropertiesChangeLogic, pinned by ProjectPropertiesChangeLogicTests) and every property change already trigger a full wireframe rebuild (WireframeObjectManager.RefreshAll(forceLayout: true, ...)), which re-applies variable references; MainEditorTabPlugin.StartUp() wires CustomSetPropertyOnRenderable.LocalizationService to the DI ILocalizationService singleton so that re-apply sees the tool's actual current language.

Left-Side Type Coercion

Before the evaluated right side is written, it is coerced to the left variable's declared type via EvaluatedSyntax.CastTo(desiredType) (desiredType resolved from the existing state variable, else ObjectFinder.GetRootVariable). CastTo handles numeric widening/narrowing, ToString for string targets, and enum targets — a string (e.g. a ternary result "LeftToRightStack") is parsed via Enum.Parse, an int via Enum.ToObject. The boxed enum is required: typed consumers like GraphicalUiElement's ChildrenLayout setter and int-on-disk serialization reject a raw string. The enum CLR type is resolved by a cached reflection scan (EvaluatedSyntax.ResolveEnumType), overridable via the static EvaluatedSyntax.TypeResolver.

CastTo is the single coercion point shared by three callers: state-level apply (GetRightSideValue/GumExpressionService), grid validation (VariableReferenceLogic.AddFailureForLine, so a valid enum reference is not auto-commented), and the behavior tool-only applier (BehaviorToolOnlyReferencesApplier). The behavior applier evaluates the RHS directly rather than via GetRightSideValue, so it resolves the left type and calls CastTo itself — without that an enum-typed behavior reference would store a raw string.

Author-Time Materialization Is The Model

When the tool resolves a VariableReferences row — interactive edit, Make Default, the handful of ElementCommands paths — ApplyVariableReferences writes the evaluated right-hand-side as a hard scalar into the same StateSave's Variables. The references row and the materialized scalar are both persisted to disk. Lookup never re-evaluates the reference: scalar resolution finds the materialized value directly.

This is the load-bearing fact for reasoning about VariableReferences. A few consequences fall out of it:

  • Files written by paths that bypass ApplyVariableReferences are inconsistent. AI-authored XML, hand edits, programmatic creation, and "delete the scalars to force a reapply" workflows all leave a state with a VariableReferences row but no materialized scalars. The Variables tab / scalar lookup then falls through to the default state instead of the reference's resolved value. Gum currently has no load-time repair for this; the only fix is to retrigger a path that runs ApplyVariableReferences (e.g. re-edit and re-save the reference).
  • References are snapshots, not live bindings. Once materialized, the scalar is what every reader sees. If the right-hand side changes elsewhere, the snapshot stays stale until propagation runs again. The cascade in DoVariableReferenceReaction (described above) is what keeps snapshots fresh when authoring; nothing keeps them fresh on its own.
  • Precedence is decided at author time, not at lookup time. The materialized scalar lives in state.Variables like any other authored value, so the normal "most specific wins" scalar walk decides who wins between a state-reference and a more-local explicit override. There is no separate evaluation pass that re-asserts the reference.
  • Inheritance interacts naturally. Materialization happens on the element that authors the reference. Derived components and instances find the materialized scalar via the existing recursive state walk; they do not need their own copy. (The walk going up the instance type's BaseType chain was previously broken in StateSaveExtensionMethods.cs — see fix history on fix/variable-references-inheritance-display.)

When designing fixes in this area, the question is almost always "did ApplyVariableReferences run on the state that owns the reference?" — not "should the lookup do something smarter when it walks past a VariableReferences row?"

Hard Values — Runtime Implications

Variable references write hard values into the StateSave. This means at game runtime (where ApplyVariableReferences on the GraphicalUiElement runs once at load time), the referenced values are already baked into the save data. References are not dynamically re-evaluated at game runtime when the source value changes — they are a tool-time binding mechanism. The runtime ApplyVariableReferences(GraphicalUiElement) overload exists primarily for the tool's wireframe preview.

Cross-Element References and Cascading

When a variable changes, DoVariableReferenceReaction finds all elements that reference the changed element via ObjectFinder.GetElementReferencesToThis (filtered to ReferenceType.VariableReference). It then applies variable references on those elements too, creating a cascade. Modified elements are auto-saved.

A typed edit also re-reads the rows of the element's other states (Highlighted, Disabled) that read the changed variables, through the same row selection undo uses (FindRowsToApply), so a typed edit, an undo and a redo leave a categorized state's followers the same. A row in a loop is not evaluated.

Deep Propagation

DoVariableReferenceReactionOnInstanceVariableSet handles a subtler case: when an instance's base element has variable references internally, and the changed variable tunnels through. It walks the reference graph to find which inner-instance variables need updating and writes the values directly into the container's state.

Circular References

Rows in a loop are skipped by the canvas and by ApplyVariableReferences and keep their stored values, so repeated applies change nothing. GUM0013 in HeadlessErrorChecker names the loop on each element holding a row in it (Errors tab, gumcli check), including loops across two elements' default states.

Row Note for a Reference With No Value

A valid right side can have no value right now (100 / Y with Y = 0); the left variable keeps its last value. VariableReferenceStatusLogic.GetNote computes a "Not updating: ..." line from current values, and ElementSaveDisplayer appends it under "Set by" (no Errors-tab entry; it would flicker while Y is dragged). Reason wording comes from VariableReferenceLogic.DescribeRightSideFailure, shared with the edit-time dialog. Lines reading Index/Absolute* are skipped: they need the live canvas.

Validation

GetIndividualFailures checks each line for:

  • Parseable assignment syntax
  • Forbidden left-side names (Name, BaseType, DefaultChildContainer)
  • Left-side variable existence
  • Right-side evaluability
  • Type compatibility (with casting support for numeric types)
  • Root variable matching for unit/alignment types (prevents mixing XUnits with YUnits, etc.)

Invalid lines are auto-commented with // prefix and a message is shown to the user.

Behavior-Sourced Tool-Only References

A separate variable-reference flavor lives on BehaviorSave.ToolOnlyVariableReferences (a List<string>, not a VariableListSave). Used by Forms property promotion (#2637 v2): a behavior declares e.g. ButtonCategoryState = IsEnabled ? "Enabled" : "Disabled" so the design-time wireframe reflects authored FormsProperty values. Strictly tool-only — applied by BehaviorToolOnlyReferencesApplier invoked from VariableReferenceLogic.DoVariableReferenceReaction immediately after the state-level apply. The runtime never traverses this list; the wrapped Forms control's setter (e.g. FrameworkElement.IsEnabled → UpdateState()) owns the visual at runtime, so applying the reference there would double-write. See gum-forms-behaviors for the property-promotion pipeline.

The applier passes a fallback resolver into EvaluatedSyntax.FromSyntaxNode so identifiers not authored on state fall back to the behavior's FormsProperty.Value declarations (mirrors WPF DependencyProperty default values). Plumbed through RecursiveVariableFinder.Fallback — any caller that needs the same "default-when-state-empty" shape can use it.

Precedence between a clicked state and Forms values. Viewing the component itself, a state clicked in the States tab wins over what a Forms property derives (IsEnabled to ButtonCategoryState), because the user is authoring how that state looks; WireframeObjectManager.GetStateForReferences (via SelectedStateReferenceMerger) makes the selected state's values and rows beat the default state's reference rows. Viewing an instance of that component (inside a screen or another component), the instance's Forms values win over visual state values: the applier writes the derived category state into the containing element's default state and removes an authored one that disagrees. The merger only ever sees the containing element's rows, so the component-view rule cannot reach an instance's Forms variables. On an instance, WireframeObjectManager.ApplySelectedStateAfterCreation also reapplies the derived value (BehaviorToolOnlyReferencesApplier.GetInstanceValuesToReassert) after a non-default container state when an authored Forms value feeds it. Tests/Gum.Presentation.Tests/StateSelectionCanvasPrecedenceTests.Instance.cs pins both views.

Evaluating "defaults-only" (footgun): To ask "what would this resolve to with nothing authored?", do not pass an empty StateSave to FromSyntaxNode — RecursiveVariableFinder resolves by name through ParentContainer, so an empty state owned by a real element still leaks that element's authored values (routes to its DefaultState). Call EvaluatedSyntax.FromSyntaxNodeUsingDefaultsOnly(node, fallback) instead; it owns the state with a throwaway empty element so every identifier falls through to the fallback. The applier uses this for the "skip if equal to resting wireframe" check (issue #3082).

Known Gaps

  • Font generation: CollectRequiredFonts (in HeadlessFontGenerationService) and RecursiveVariableFinder do not resolve variable references. If a font property (Font, FontSize, etc.) is set via a variable reference, the font file may not be generated for that value. The tool-time path works because VariableChangedThroughReference fires PluginManager.VariableSet, but headless/CLI font generation could miss these. (See issue #2414)
  • Runtime support: The Roslyn expression evaluator has been extracted into Runtimes/GumExpressions/ (Gum.Expressions NuGet). Games can opt in to expression support and use ApplyAllVariableReferences to propagate changes at runtime. See the gum-runtime-variable-references skill for details.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.