Skip to content

feat: validate commits against DataAnnotations attributes through generated validators (#352) - #503

Open
michaelstonis wants to merge 3 commits into
mainfrom
feat/352-annotation-validation
Open

michaelstonis wants to merge 3 commits into
mainfrom
feat/352-annotation-validation

Conversation

@michaelstonis

Copy link
Copy Markdown
Contributor

Closes #352.

Changes

Cell edits can now be checked against the System.ComponentModel.DataAnnotations validation attributes models already declare, without reflection under Native AOT and full trimming.

Edit pipeline (src/KumikoUI.Core/Editing)

  • New KumikoAnnotationValidation enum (Off, the default, or On) and EditSession.AnnotationValidation.
  • CommitEdit and ToggleBooleanCell gain a step after CellValidator and before the write. The column's path is resolved through KumikoColumn.ResolvePath, and the validator of its last segment runs on the object that declares that segment. A refused value is never written, so nothing has to be written back, unlike ValidateItem. The result is a normal error CellValidationResult merged with MoreSevere, and it is shown and reported like any other error (CurrentValidation, ValidationFailed, and from there the existing screen reader announcement). Columns with a ValueSetter are skipped. A validator that throws (a misconfigured attribute) is traced and does not block the edit.
  • The check lives in EditSession.CheckAnnotations, an internal static method, so paste (Clipboard: paste tab-separated text from Excel into the grid with Ctrl/Cmd+V #350) and form editing (Editing: add a form edit mode that edits or adds a record in a host-native form built from the columns #364) can run the same rules.

Data layer (src/KumikoUI.Core/Data)

  • IKumikoPropertyValidator with Validate(object item, object? value, KumikoStrings strings), which returns null when the value is valid.
  • KumikoAnnotationValidator, which runs a list of ValidationAttributes through GetValidationResult. It builds the ValidationContext with the (object, string displayName, IServiceProvider?, IDictionary?) constructor, which is the only one not marked RequiresUnreferencedCode on .NET 10 (checked against the runtime). [Required] runs first. The display name is read lazily, so a [Display(ResourceType)] name follows the current culture. Null entries are skipped.
  • KumikoPropertyAccessor.Validator and a new five-argument constructor that takes the validator. An accessor built with that constructor is authoritative: passing null means "no rules". An accessor built with the existing four-argument constructor, which includes reflection and hand-written accessors, falls back to ReflectionValidatorFactory (GetCustomAttributes), but only when IsReflectionPropertyAccessSupported is true. When it is false, the attributes are ignored and a warning is traced once per type. Resolved validators are cached in KumikoAccessorRegistry and cleared with its other caches.
  • KumikoValuePath.TryGetLastSegment, an internal helper.

Source generator

  • ValidatorEmitter: for every accessor property that has validation attributes, the generator now emits a KumikoAnnotationValidator. It constructs each attribute with its constructor arguments and named arguments (primitives, strings, chars, enums, typeof, arrays and params arrays, NaN and infinity). It inherits the attributes of overridden members, and an override's own attribute of the same type replaces the inherited one. The display name comes from [Display(Name)], as a literal or as a resource read through the same Text() helper that the column metadata from Columns: auto-generate columns from the item type, with DataAnnotations and an AOT-safe source-generator path #315 uses.
  • An attribute whose constructor or named-argument setter is marked RequiresUnreferencedCode ([MaxLength], [MinLength], [Length], [Compare], [Range(typeof(...), ...)]) is emitted behind KumikoAccessorRegistry.IsReflectionPropertyAccessSupported. That property is a FeatureGuard for RequiresUnreferencedCode, so the generated code adds no IL warning and the trimmer removes the branch. The generator reports this as new diagnostic KUMIKO004 (Info).
  • An attribute that generated code cannot construct (an inaccessible attribute type or argument type, an error argument, or a RequiresDynamicCode constructor) is left out and reported as new diagnostic KUMIKO003 (Warning). Both diagnostics are listed in AnalyzerReleases.Unshipped.md.
  • Generated accessors always use the five-argument constructor, passing null when a property has no rules.

Hosts: AnnotationValidation is a bindable property on MAUI and a dependency property on Uno, defaulting to Off and forwarded to EditSession. The ValidationFailed docs on both hosts mention it.

Samples: the shared Auto Columns models gain [Required], [StringLength], [Range], [RegularExpression] and a custom [PaidWhenDelivered] rule. The Auto Columns pages of both sample apps set AnnotationValidation="On" and show the last refused edit in a status line.

Docs: there is a new README section "Validation attributes" under Validation. The README also gains a row in the host property table, notes in Native AOT and Trimming (including KUMIKO003 and KUMIKO004), a row for the Auto Columns page in samples/README.md, and a CHANGELOG entry under Unreleased, Added.

Public API added (all in PublicAPI.Unshipped.txt):

  • Core: IKumikoPropertyValidator, KumikoAnnotationValidator (constructor, MemberName, DisplayName, Attributes, Validate), KumikoPropertyAccessor.Validator, the five-argument KumikoPropertyAccessor constructor, KumikoAnnotationValidation (Off, On), EditSession.AnnotationValidation.
  • MAUI and Uno: KumikoDataGrid.AnnotationValidation and AnnotationValidationProperty.

Open question from the issue (an assembly-level switch to opt out of emitting validators): not added. Validators are emitted only for properties that carry validation attributes, and they cost one object per such property at module load.

Acceptance criteria

  • With AnnotationValidation = On, [Required], [Range], [StringLength], [RegularExpression] and a custom ValidationAttribute refuse invalid commits and Boolean toggles before the item is written, with the attribute's message. Covered by AnnotationValidationTests; a setter counter proves no write happened.
  • With Off (the default) behavior is unchanged. Tests cover both the commit and the toggle, and the existing suites pass.
  • Generator tests in tests/KumikoUI.SourceGenerators.Tests cover emitted validators, including named arguments and [Display(Name)] (literal and resource), enum, typeof, params, char and double arguments, override inheritance, the guarded unreferenced-code attribute (KUMIKO004) and the inaccessible attribute (KUMIKO003). One test emits the compilation, loads it and runs the generated validators.
  • Reflection fallback works only when reflection access is supported; otherwise one trace warning. Tested in the reflection-switch collection.
  • eng/AotSmoke publishes with no new IL warnings and validates an annotated model: [Required], [StringLength], [RegularExpression], [Range] with [Display(Name)], a custom attribute on a Boolean toggle, and a [MaxLength] property. That last one checks that the guarded branch adds no warning and is not checked under AOT. Applying [MaxLength] warns IL2026 at the attribute itself, in app code and independent of KumikoUI, so the smoke model suppresses that one with a justification.
  • Behavior tests in tests/KumikoUI.Core.Tests/Editing (AnnotationValidationTests.cs, 17 tests).
  • Works on MAUI and Uno; sample page shows annotated models on both sample apps (the Auto Columns page). Both hosts build, there is a MAUI mapping test, and both sample apps build. The pages were not run interactively.
  • XML docs on every new public member; PublicAPI.Unshipped.txt updated. eng/update-public-api.sh could not rewrite the files on this machine (dotnet format failed to load the workspace and emptied the Core file), so the lines were added by hand from the RS0016 output. The diff contains additions only.
  • README validation section and CHANGELOG entry under Unreleased.
  • Validation errors are announced to screen readers as today. A refusal goes through ValidationFailed, which the hosts already announce, and nothing changed there.
  • No allocations added to the per-frame render path. The work runs only on commit and toggle.

Verification

  • dotnet build src/KumikoUI.Core: succeeded, 0 warnings. -c Release also succeeded.
  • dotnet build src/KumikoUI.SourceGenerators: succeeded.
  • dotnet build src/KumikoUI.Maui -f net10.0-maccatalyst: succeeded, 0 warnings.
  • dotnet build src/KumikoUI.Uno -f net10.0-desktop: succeeded. The only warnings are the existing Uno0001 warnings in files this change does not touch.
  • dotnet test tests/KumikoUI.Core.Tests: 4378 passed, 5 skipped.
  • dotnet test tests/KumikoUI.SourceGenerators.Tests: 14 passed.
  • dotnet test tests/KumikoUI.SkiaSharp.Tests: 42 passed.
  • dotnet test tests/KumikoUI.Maui.Tests: 450 passed.
  • dotnet test tests/KumikoUI.Uno.Tests: 321 passed.
  • dotnet publish eng/AotSmoke -c Release -r osx-arm64: no IL warnings. Running the binary printed AOT smoke OK: 51 visible rows, 8+ distinct colors in the frame. and exited 0. On this machine the native link needed LIBRARY_PATH pointing at Homebrew's OpenSSL, an environment issue unrelated to this change.
  • dotnet build samples/SampleApp.Maui -f net10.0-maccatalyst -c Release: succeeded, with existing XamlC warnings only. The Debug build fails restore with NU1605 from the DevFlow package override, which this change does not touch.
  • dotnet build samples/SampleApp.Uno -f net10.0-desktop: succeeded.
  • dotnet run --project eng/DocsSnippets -c Release, then building tests/KumikoUI.Docs.Snippets.Maui and tests/KumikoUI.Docs.Snippets.Uno: succeeded.
  • dotnet run --project eng/DocsIdentifiers -c Release: 0 problems.
  • eng/TypeNameCheck on KumikoUI.Core.dll: no public type name collides.

[Fact]
public void Validators_AreEmittedFromValidationAttributes_AndCompileCleanly()
{
var (output, diagnostics, run) = Generate(ValidatedModels);
var context = new System.Runtime.Loader.AssemblyLoadContext("validators", isCollectible: true);
try
{
var assembly = context.LoadFromStream(new MemoryStream(stream.ToArray()));
Comment on lines +67 to +72
foreach (var attribute in _attributes)
{
var result = attribute.GetValidationResult(value, context);
if (result != ValidationResult.Success)
return CellValidationResult.Error(result?.ErrorMessage is { Length: > 0 } message ? message : strings.EnterValidValue);
}
Comment on lines +36 to +62
foreach (var attribute in p.GetAttributes())
{
if (attribute.AttributeClass is not { } attributeClass || !IsValidationAttribute(attributeClass)) continue;
string className = attributeClass.ToDisplayString(TypeFormat);
if (seen.Contains(className)) continue;
declaredHere.Add(className);

string where = $"[{ShortName(attributeClass)}] on '{property.ContainingType.Name}.{property.Name}'";
var location = attribute.ApplicationSyntaxReference is { } reference
? DiagnosticLocation.From(Location.Create(reference.SyntaxTree, reference.Span))
: null;

if (Construct(attribute, attributeClass, out bool requiresUnreferencedCode) is not { } expression)
{
diagnostics.Add(new DiagnosticInfo(Diagnostics.ValidationAttributeNotEmitted, location, where));
continue;
}

if (requiresUnreferencedCode)
{
// KumikoAccessorRegistry.IsReflectionPropertyAccessSupported is a feature guard for
// RequiresUnreferencedCode: the trimmer removes this branch under Native AOT and full trimming.
expression = $"global::KumikoUI.Core.Data.KumikoAccessorRegistry.IsReflectionPropertyAccessSupported ? {expression} : null";
diagnostics.Add(new DiagnosticInfo(Diagnostics.ValidationAttributeNeedsReflection, location, where));
}
attributes.Add(expression);
}
Comment on lines +159 to +164
foreach (var item in constant.Values)
{
string? value = Constant(item, elementType);
if (value == null) return null;
items.Add(value);
}

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.

Editing: validate commits against DataAnnotations attributes, trim-safe through the source generator

2 participants