Skip to content

feat: expression, value-computer and unbound columns (#378) - #514

Open
michaelstonis wants to merge 4 commits into
mainfrom
feat/378-unbound-expression-columns
Open

michaelstonis wants to merge 4 commits into
mainfrom
feat/378-unbound-expression-columns

Conversation

@michaelstonis

Copy link
Copy Markdown
Contributor

Part of #378.

Changes

Columns can now show values the item does not have as a property, declared in XAML: an expression over the item's properties, a reusable value computer, or per-row unbound storage kept by the column.

<core:KumikoColumn Header="Total" Key="Total" Expression="Quantity * UnitPrice" ColumnType="Numeric" Format="C" />
<core:KumikoColumn Header="Age" Key="Age" ValueComputer="{StaticResource AgeFromBirthDate}" />
<core:KumikoColumn Header="Note" Key="Note" IsUnbound="True" />

Expression engine (Core, KumikoUI.Core.Data.Expressions, internal). A hand-written tokenizer and precedence-climbing parser build a tree of nodes that is evaluated by walking it. There is no System.Linq.Expressions, no Reflection.Emit and no other runtime code generation. Property paths resolve through KumikoAccessorRegistry.GetPath once per item type (an immutable, volatile cache per node, so one tree is evaluated from several threads at once).

  • Syntax: property paths (Address.City, or [Address.City] for keyword names), int/long/decimal/double literals (invariant), single- or double-quoted strings with escapes, true/false/null, parentheses.
  • Operators: unary - + ! not, * / %, + -, < <= > >=, == = != <>, && and, || or, ??, ?:.
  • Numbers use the same promotion as summaries (KumikoComparer.TryGetNumber): exact decimal when both operands are integral or decimal, falling back to double on overflow, and double when either operand is floating-point.
  • Arithmetic with null gives null. + concatenates when either side is text (invariant formatting). Dates subtract to a TimeSpan and take a TimeSpan added or subtracted. Comparisons always give a Boolean. Logic treats null as false.
  • Parse errors throw KumikoExpressionException (Position, Expression, Reason) when the expression is assigned, so a XAML typo fails at page load. Nesting depth and token count are bounded, so a hostile expression cannot overflow the stack.
  • Evaluation errors (unknown property, type mismatch, division by zero) are never thrown. The cell reads as null and the error is reported.
  • No method calls or aggregates in this version.

Columns. KumikoColumn gets Expression, ValueComputer (IKumikoValueComputer: Compute, plus optional default-implemented CanSetValue/TrySetValue) and IsUnbound. Unbound storage is a ConditionalWeakTable<object, StrongBox<object?>> per column, keyed by item reference and safe to read from a background build. GetUnboundValue, SetUnboundValue, HasUnboundValue and ClearUnboundValues give access from code. SetUnboundValue refreshes the grid: cells, sort, filter, grouping and summaries. Value-type items are refused, and unbound values are not part of KumikoLayoutState.

  • Read precedence: ValueAccessor > ValueComputer > Expression > unbound storage > PropertyName.
  • Write precedence: ValueSetter > the computer's write-back (falls back to unbound storage when the column is also unbound) > unbound storage > PropertyName.
  • An expression column without a setter or write-back is read-only (no editor opens, SetCellValue returns false).
  • Unbound edits convert by the replaced value's type or ColumnType and raise CellValueChanged.

One read path. The column exposes one internal EffectiveAccessor delegate, rebuilt only when a value setting changes, so caches can compare it by reference. KumikoSource.ReadColumnValue, ItemReader (sort, filter, grouping, summaries, search, background builds), CellTextCache, clipboard and export (KumikoExportColumn) all read through it.

Change tracking.

  • Cell-text, row-height and search invalidation ask the column (ValueDependsOn). An expression depends only on the paths it reads (and their parents). An unbound column depends on its own value changes, reported under its name. A computer depends on any property, like ValueAccessor.
  • A sort, filter or grouping by an expression is reapplied when a referenced property changes and not otherwise. Group and table summaries of an expression or unbound column update the same way.

Naming. Group and summary descriptions find a column by PropertyName, else by Key for a column without a property. The column menu's Group by uses the same name. Key is documented as required for unbound columns, and a warning is traced when one has none.

Event. KumikoSource.UnboundValueRequested (KumikoUnboundValueEventArgs: Column, Item, Error, settable Value, HasValue) is raised for two cases:

  • An expression or computer failed for an item. Error says why, and the handler may supply a value. With no handler, the error is traced once per column and message.
  • An unbound cell has no value yet. Error is null, and a supplied value is stored.

During background builds it is raised on the worker thread (documented).

Public API added (Core PublicAPI.Unshipped.txt):

  • IKumikoValueComputer (Compute, CanSetValue, TrySetValue)
  • KumikoExpressionException (ctor, Expression, Position, Reason)
  • KumikoColumn.Expression, ValueComputer, IsUnbound, GetUnboundValue, SetUnboundValue, HasUnboundValue, ClearUnboundValues
  • KumikoSource.UnboundValueRequested
  • KumikoUnboundValueEventArgs (ctor, Column, Item, Error, Value, HasValue)

KumikoColumn became partial (no API change). No MAUI or Uno API changes: columns are Core objects in host XAML, and both hosts pass them through as is.

Samples.

  • MainPage (MAUI) and BasicGridPage (Uno) each add three columns:
    • a "Monthly" expression column (Salary / 12)
    • a "Tenure" column using a shared TenureYearsComputer page resource (samples/Shared/TenureYearsComputer.cs)
    • a "Note" unbound column
  • Both sample Employee types implement a small shared IHasHireDate interface.

Other changes.

  • bench/KumikoUI.Benchmarks/ExpressionColumnBenchmarks.cs sorts 100,000 rows by an expression, a lambda accessor and a bound property.
  • eng/AotSmoke checks expression and unbound columns: decimal arithmetic, the conditional, concatenation, sort, group and summary.
  • Docs: README "Computed and unbound columns" section (plus notes in the sorting and Native AOT sections), docs/RENDERING.md (cache invalidation), docs/EXPORT.md, and a CHANGELOG entry.

One small change outside Core models. In KumikoInputController.ColumnMenu.cs the Group by / Ungroup item now names the column by ValueName (PropertyName, else Key) instead of PropertyName, so computed columns can be grouped from the menu. Nothing else in the input controller changed, and the renderer, its drawing and layout code, and the hit tester are untouched.

Acceptance criteria

  • Expression, ValueComputer and IsUnbound columns work from XAML on MAUI and Uno, with the documented precedence. MAUI is covered by a runtime-XAML host test (KumikoDataGridComputedColumnsTests, with a StaticResource computer) and by the XamlC-compiled sample. Uno is covered by BasicGridPage, which declares all three column kinds and builds through the Uno XAML generator; the Uno test project cannot load XAML at runtime, so there is no Uno runtime test. Precedence is covered by ValueSources_FollowTheDocumentedPrecedence.
  • Expression columns sort, filter, group, summarize and copy like bound columns, including in background rebuilds. Search and CSV export are covered too, and a background build is compared with a synchronous one (sorted, filtered, grouped and summarized by expression and unbound columns).
  • Unbound values are editable, survive sort, filter and regroup, and are readable and writable from code.
  • Expression cells refresh when a referenced property changes and not when an unrelated one does. Cache hits are proven by counting getter reads. The sort, grouping and summaries follow the same rule.
  • Expression parsing and evaluation are Native AOT safe (checked by eng/AotSmoke). New AotSmoke checks were added, and the published binary runs with no IL2xxx/IL3xxx warnings.
  • Behavior tests in tests/KumikoUI.Core.Tests: 55 parser/evaluation tests in Data/ColumnExpressionTests.cs and 36 tests in ComputedColumnTests.cs. They cover precedence, literals, nulls, types, dates, parse-error positions, depth limits, thread safety, invalidation, unbound storage, editing, background builds, layout state, and errors reported rather than thrown.
  • MainPage (MAUI) and BasicGridPage (Uno) samples show a computed and an unbound column, plus a value-computer column.
  • XML docs on every new public member; PublicAPI.Unshipped.txt updated. eng/update-public-api.sh Core emptied the file on this machine because dotnet format reported no fixes, so the file was restored and the 28 RS0016 symbols from the build were added and sorted by hand. The build is clean.
  • README "Columns" section updated; CHANGELOG entry under Unreleased.
  • No allocations added to the per-frame render path. The cell-text cache still serves frames. The accessor is a field read, and the dependency checks loop over arrays without allocating. Expressions are evaluated only on a cache miss.

Verification

  • dotnet build src/KumikoUI.Core, src/KumikoUI.SkiaSharp, src/KumikoUI.Export.Excel: succeeded, 0 warnings.

  • dotnet build src/KumikoUI.Maui -f net10.0-maccatalyst, dotnet build src/KumikoUI.Uno -f net10.0-desktop: succeeded.

  • dotnet test tests/KumikoUI.Core.Tests: 4452 passed, 5 skipped, 0 failed.

  • dotnet test tests/KumikoUI.Maui.Tests: 450 passed.

  • dotnet test tests/KumikoUI.Uno.Tests: 321 passed.

  • dotnet test tests/KumikoUI.SkiaSharp.Tests: 42 passed.

  • dotnet test tests/KumikoUI.Export.Excel.Tests: 122 passed.

  • dotnet test tests/KumikoUI.SourceGenerators.Tests: 10 passed.

  • dotnet build samples/SampleApp.Uno/SampleApp.Uno.csproj -f net10.0-desktop: succeeded.

  • dotnet build samples/SampleApp.Maui/SampleApp.Maui.csproj -f net10.0-maccatalyst -c Release (as CI builds it): succeeded. The Debug build fails restore with NU1605 from the DevFlow package pin on this machine, which this change does not affect.

  • dotnet run --project eng/DocsSnippets -c Release, then dotnet build tests/KumikoUI.Docs.Snippets.Uno -f net10.0-desktop -c Release and dotnet build tests/KumikoUI.Docs.Snippets.Maui -f net10.0-maccatalyst -c Release: succeeded.

  • dotnet publish eng/AotSmoke -c Release -r osx-arm64: no trim or AOT warnings, and the binary prints "AOT smoke OK". This machine's .NET install needed LIBRARY_PATH pointing at OpenSSL and Brotli to link.

  • dotnet run -c Release --project bench/KumikoUI.Benchmarks -- --filter '*ExpressionColumn*' --job short, sorting 100,000 rows:

    Sort by Mean Allocated
    Bound property 29.2 ms 4.2 MB
    ValueAccessor lambda 28.0 ms 4.2 MB
    Expression Quantity * UnitPrice 50.6 ms 9.5 MB (boxed operands)

Held for Foundations

Grouping a computed column from the built-in column menu (Group by / Ungroup) is not included: the menu items are built in KumikoInputController.ColumnMenu.cs, which stays untouched until #446/#448 land. Grouping a computed column from code (GroupDescription with the column's Key) works.

or TokenKind.And or TokenKind.Or or TokenKind.Not) || segment.Bracketed)
throw Error("Expected a property name after '.'", segment);
_index++;
path += "." + segment.Text;

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

2 participants