Gum tool variable references

From vchelaru/Gum · View interactive version

Gum tool variable references is an AI agent skill from the GitHub repository vchelaru/Gum. 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 Variable

How to use this skill

Skill file

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

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.).
  1. 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:

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:

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:

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

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.