Repository navigation
feat: validate commits against DataAnnotations attributes through generated validators (#352) - #503
Open
michaelstonis wants to merge 3 commits into
Open
michaelstonis wants to merge 3 commits into
michaelstonis wants to merge 3 commits into
Conversation
| [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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #352.
Changes
Cell edits can now be checked against the
System.ComponentModel.DataAnnotationsvalidation attributes models already declare, without reflection under Native AOT and full trimming.Edit pipeline (
src/KumikoUI.Core/Editing)KumikoAnnotationValidationenum (Off, the default, orOn) andEditSession.AnnotationValidation.CommitEditandToggleBooleanCellgain a step afterCellValidatorand before the write. The column's path is resolved throughKumikoColumn.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, unlikeValidateItem. The result is a normal errorCellValidationResultmerged withMoreSevere, and it is shown and reported like any other error (CurrentValidation,ValidationFailed, and from there the existing screen reader announcement). Columns with aValueSetterare skipped. A validator that throws (a misconfigured attribute) is traced and does not block the edit.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)IKumikoPropertyValidatorwithValidate(object item, object? value, KumikoStrings strings), which returns null when the value is valid.KumikoAnnotationValidator, which runs a list ofValidationAttributes throughGetValidationResult. It builds theValidationContextwith the(object, string displayName, IServiceProvider?, IDictionary?)constructor, which is the only one not markedRequiresUnreferencedCodeon .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.Validatorand 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 toReflectionValidatorFactory(GetCustomAttributes), but only whenIsReflectionPropertyAccessSupportedis true. When it is false, the attributes are ignored and a warning is traced once per type. Resolved validators are cached inKumikoAccessorRegistryand 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 aKumikoAnnotationValidator. 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 sameText()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.RequiresUnreferencedCode([MaxLength],[MinLength],[Length],[Compare],[Range(typeof(...), ...)]) is emitted behindKumikoAccessorRegistry.IsReflectionPropertyAccessSupported. That property is aFeatureGuardforRequiresUnreferencedCode, so the generated code adds no IL warning and the trimmer removes the branch. The generator reports this as new diagnosticKUMIKO004(Info).RequiresDynamicCodeconstructor) is left out and reported as new diagnosticKUMIKO003(Warning). Both diagnostics are listed inAnalyzerReleases.Unshipped.md.nullwhen a property has no rules.Hosts:
AnnotationValidationis a bindable property on MAUI and a dependency property on Uno, defaulting toOffand forwarded toEditSession. TheValidationFaileddocs 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 setAnnotationValidation="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
KUMIKO003andKUMIKO004), a row for the Auto Columns page insamples/README.md, and a CHANGELOG entry under Unreleased, Added.Public API added (all in
PublicAPI.Unshipped.txt):IKumikoPropertyValidator,KumikoAnnotationValidator(constructor,MemberName,DisplayName,Attributes,Validate),KumikoPropertyAccessor.Validator, the five-argumentKumikoPropertyAccessorconstructor,KumikoAnnotationValidation(Off,On),EditSession.AnnotationValidation.KumikoDataGrid.AnnotationValidationandAnnotationValidationProperty.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
AnnotationValidation = On,[Required],[Range],[StringLength],[RegularExpression]and a customValidationAttributerefuse invalid commits and Boolean toggles before the item is written, with the attribute's message. Covered byAnnotationValidationTests; a setter counter proves no write happened.Off(the default) behavior is unchanged. Tests cover both the commit and the toggle, and the existing suites pass.tests/KumikoUI.SourceGenerators.Testscover 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.eng/AotSmokepublishes 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.tests/KumikoUI.Core.Tests/Editing(AnnotationValidationTests.cs, 17 tests).PublicAPI.Unshipped.txtupdated.eng/update-public-api.shcould not rewrite the files on this machine (dotnet formatfailed 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.ValidationFailed, which the hosts already announce, and nothing changed there.Verification
dotnet build src/KumikoUI.Core: succeeded, 0 warnings.-c Releasealso 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 printedAOT smoke OK: 51 visible rows, 8+ distinct colors in the frame.and exited 0. On this machine the native link neededLIBRARY_PATHpointing 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 buildingtests/KumikoUI.Docs.Snippets.Mauiandtests/KumikoUI.Docs.Snippets.Uno: succeeded.dotnet run --project eng/DocsIdentifiers -c Release: 0 problems.eng/TypeNameCheckonKumikoUI.Core.dll: no public type name collides.