Gum variable references: Excel-like cross-instance/cross-element binding via Roslyn-parsed assignments, including lines that read a Forms-only (behavior) property. Triggers: VariableReferenceLogic, EvaluatedSyntax, ApplyVariableReferences, VariableChangedThroughReference, VariableReferences VariableListSave, a reference to a FormsProperty such as Slider.Minimum.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Gum Tool Variable References?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/vchelaru-gum-tool-variable-references)
---
name: gum-tool-variable-references
description: "Gum variable references: Excel-like cross-instance/cross-element binding via Roslyn-parsed assignments, including lines that read a Forms-only (behavior) property. Triggers: VariableReferenceLogic, EvaluatedSyntax, ApplyVariableReferences, VariableChangedThroughReference, VariableReferences VariableListSave, a reference to a FormsProperty such as Slider.Minimum."
---
# 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. A line that reads a Forms-only behavior property (a FormsProperty) is a special case: see "Two Layers in One Variable List" in **gum-forms-behaviors**.
## 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 (VariableReferenceValidator.GetFailures)
│ ├─ 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
| Class | Location | Role |
|-------|----------|------|
| `VariableReferenceLogic` | `Tools/Gum.Presentation/Plugins/InternalPlugins/VariableGrid/` | Tool-side orchestration: reaction to changes, commenting out and reporting bad lines |
| `VariableReferenceValidator` | `Tools/Gum.ProjectServices/Editing/` | Line checks (`GetFailures`) and shorthand expansion (`NormalizeLines`), shared by the tool and `gumcli edit`'s `setVariableReferences` |
| `VariableReferenceCascade` | `Tools/Gum.ProjectServices/Editing/` | The reaction after an edit: other states reading the change, elements reading this one (`ApplyToElementsReading`), and instance internals; `VariableReferenceLogic` adds saving and refresh around it |
| `EvaluatedSyntax` | `Runtimes/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.cs` | `ApplyVariableReferences` — two overloads: one for `ElementSave` (save-class, tool-time), one for `GraphicalUiElement` (runtime) |
| `MainVariableGridPlugin` | `Tools/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`. A category-state left side (`ButtonCategoryState`) is always cast to `string`, decided by what the variable is (`ElementSaveExtensions.GetReferenceCastType`), never by its category's name: a category can share its name with a loaded enum (`Orientation`, or one generated code nests in its element's class). Every caller that casts a reference result goes through that method.
`CastTo` is the single coercion point shared by three callers: state-level apply (`GetRightSideValue`/`GumExpressionService`), grid **validation** (`VariableReferenceValidator.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`. The `ElementSave` overload bakes them into the save data, which is what the tool and `ApplyAllVariableReferences` use. In a game the rows of a component are also re-evaluated live when an input changes (see **gum-runtime-variable-references**, "Live re-evaluation within a component"); only references into another element stay explicit.
### 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 `VariableReferenceValidator.DescribeRightSideFailure`, shared with the edit-time dialog. Lines reading `Index`/Absolute* are skipped: they need the live canvas.
## Validation
`VariableReferenceValidator.GetFailures` 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` (`Tools/Gum.ProjectServices/Editing/`) invoked from `VariableReferenceLogic.DoVariableReferenceReaction` and `gumcli edit`'s `setVariableReferences`, 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.
A user `VariableReferences` line that reads a Forms-behavior property (`Text = Slider.Minimum`) is a different case: see "Two Layers in One Variable List" in `gum-forms-behaviors`.
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.
**`FindAncestor<BehaviorName>()` (behavior lines only).** On an instance, `BehaviorAncestorFinder.Resolve` replaces each call with the name of the nearest ancestor instance (walking `Parent` values, slot paths by their first segment, owners in base elements) whose component chain has that behavior, so a tab can read `@FindAncestor<TabControlBehavior>().SelectedIndex`. No ancestor means the line writes nothing. It must run before `ResolveOwnerPrefix` (which then encodes a non-identifier ancestor name) and skips string literals. The fallback resolves `Other.Prop` to the other instance's component default, then its behavior's declared default. User-typed `VariableReferences` rows and the runtime do not support it. `ReapplySiblingDependentReferences` also re-runs the applier when any instance's behavior line reads `Index`, so adding, deleting or reordering tabs updates them.
**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.