From cd6c7c214eb67af918b199f8c9bde7095cc81bad Mon Sep 17 00:00:00 2001 From: David Driscoll Date: Fri, 4 Dec 2026 00:19:06 -0500 Subject: [PATCH 1/2] Validation: one asynchronous IValidator The synchronous IValidate is gone, with LPAD3002, its code fix and LPAD3113. IValidateAsync is now IValidator, and the class shape that declares rules is IValidatorDefinition. A validator none of whose rules waits answers ValidateAsync with a completed ValueTask, cancelled if the token already is and faulted if a rule throws. A member validated with its own validator, and the whole value of a [Mutable] view model, go through IValidator and are always awaited. The Blazor validator validates the whole model asynchronously only. Co-Authored-By: Claude Fable 5.2 --- AGENTS.md | 8 +- docs/adr/0012-launchpad-owns-validation.md | 6 +- docs/design/validation.md | 34 ++-- docs/src/content/docs/concepts/validation.md | 21 ++- .../AnalyzerReleases.Unshipped.md | 2 - src/Validation.Analyzers/Diagnostics.cs | 19 -- .../Model/FunctionReader.cs | 9 +- src/Validation.Analyzers/Model/LinkReader.cs | 2 - src/Validation.Analyzers/Model/Models.cs | 9 +- src/Validation.Analyzers/Model/Resolution.cs | 23 +-- src/Validation.Analyzers/Model/RuleReader.cs | 1 - .../Model/TargetReader.cs | 15 -- .../SynchronousValidationAnalyzer.cs | 63 ------- .../SynchronousValidationCodeFix.cs | 167 ------------------ src/Validation.Analyzers/ValidatorEmitter.cs | 88 ++++----- src/Validation.Blazor/LaunchPadValidator.cs | 13 +- src/Validation/IValidate.cs | 39 ---- src/Validation/IValidationBuilder.cs | 4 +- src/Validation/IValidator.cs | 20 +-- src/Validation/IValidatorDefinition.cs | 21 +++ src/Validation/ObjectValidator.cs | 29 +-- test/Sdk.Tests/SdkValidationTests.cs | 18 +- .../CompositionGeneratorTests.cs | 2 +- .../FunctionValidatorGeneratorTests.cs | 2 +- .../SynchronousValidationAnalyzerTests.cs | 53 ------ .../Validation.Analyzers.Tests/TestBuilder.cs | 2 +- .../ValidatorGeneratorTests.cs | 5 +- ..._Members#LaunchPadValidators.g.verified.cs | 16 +- ...le.AddressGeneratedValidator.g.verified.cs | 22 ++- ...mple.DraftGeneratedValidator.g.verified.cs | 22 ++- ...ingAddressGeneratedValidator.g.verified.cs | 2 +- ...pplicationGeneratedValidator.g.verified.cs | 2 +- ...pplicationGeneratedValidator.g.verified.cs | 22 ++- ...Assembly#LaunchPadValidators.g.verified.cs | 30 ++-- ...Sample.CarGeneratedValidator.g.verified.cs | 22 ++- ...ample.HoldGeneratedValidator.g.verified.cs | 2 +- ...ingAddressGeneratedValidator.g.verified.cs | 2 +- ...ules_Of_A_Referenced_Assembly.verified.txt | 26 +-- ...terfaces#LaunchPadValidators.g.verified.cs | 37 ++-- ...ple.CircleGeneratedValidator.g.verified.cs | 22 ++- ...e.IHasNameGeneratedValidator.g.verified.cs | 22 ++- ...le.IPricedGeneratedValidator.g.verified.cs | 22 ++- ...mple.PointGeneratedValidator.g.verified.cs | 21 ++- ...le.PolygonGeneratedValidator.g.verified.cs | 22 ++- ...mple.ShapeGeneratedValidator.g.verified.cs | 22 ++- ...ple.SquareGeneratedValidator.g.verified.cs | 22 ++- ...y_Member#LaunchPadValidators.g.verified.cs | 15 +- ...ample.BodyGeneratedValidator.g.verified.cs | 22 ++- ...ple.PlanetGeneratedValidator.g.verified.cs | 2 +- ...lanetModelGeneratedValidator.g.verified.cs | 10 +- ...ead#INamedGeneratedValidator.g.verified.cs | 22 ++- ...d#LauncherGeneratedValidator.g.verified.cs | 51 ++++-- ...ld_Report_What_It_Cannot_Read.verified.txt | 4 +- ...at_Waits#LaunchPadValidators.g.verified.cs | 14 +- ...le.BookingGeneratedValidator.g.verified.cs | 2 +- ...e.ManifestGeneratedValidator.g.verified.cs | 10 +- ...e.ScheduleGeneratedValidator.g.verified.cs | 10 +- ...Its_Type#LaunchPadValidators.g.verified.cs | 7 +- ...er_RequestGeneratedValidator.g.verified.cs | 22 ++- ...And_Make_Its_Use_Asynchronous.verified.txt | 55 ------ ...es#AccountGeneratedValidator.g.verified.cs | 22 ++- ...mple.NamedGeneratedValidator.g.verified.cs | 22 ++- ...uter_InnerGeneratedValidator.g.verified.cs | 22 ++- ...e.PositionGeneratedValidator.g.verified.cs | 21 ++- ...mple.StageGeneratedValidator.g.verified.cs | 22 ++- ..._Options#LaunchPadValidators.g.verified.cs | 12 +- ...mple.DelayGeneratedValidator.g.verified.cs | 21 ++- ...tryOptionsGeneratedValidator.g.verified.cs | 22 ++- ...e#MistakesGeneratedValidator.g.verified.cs | 22 ++- ...ample.CrewGeneratedValidator.g.verified.cs | 22 ++- ...e.LauncherGeneratedValidator.g.verified.cs | 122 ++++++++----- ...mple.StageGeneratedValidator.g.verified.cs | 21 ++- ...e.LauncherGeneratedValidator.g.verified.cs | 22 ++- .../ValidationProblemDetailsJointTests.cs | 18 +- .../LaunchPadValidatorTests.cs | 12 +- test/Validation.Tests/CompositionTests.cs | 58 +++--- .../FunctionValidatorTests.cs | 62 +++---- .../GeneratedValidatorTests.cs | 79 +++++---- test/Validation.Tests/Types/Composition.cs | 2 +- test/Validation.Tests/Types/Functions.cs | 2 +- 80 files changed, 973 insertions(+), 912 deletions(-) delete mode 100644 src/Validation.Analyzers/SynchronousValidationAnalyzer.cs delete mode 100644 src/Validation.Analyzers/SynchronousValidationCodeFix.cs delete mode 100644 src/Validation/IValidate.cs create mode 100644 src/Validation/IValidatorDefinition.cs delete mode 100644 test/Validation.Analyzers.Tests/SynchronousValidationAnalyzerTests.cs delete mode 100644 test/Validation.Analyzers.Tests/snapshots/SynchronousValidationAnalyzerTests.Should_Report_The_Synchronous_Validator_Of_An_Asynchronous_Type_And_Make_Its_Use_Asynchronous.verified.txt diff --git a/AGENTS.md b/AGENTS.md index 6dbf4edd98..c64bdf3b80 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -32,16 +32,16 @@ The conversion is done: no project references `Rocket.Surgery.Conventions` or th - Its settings are MSBuild properties (`LaunchPadPrimitivesTrim`, `...NotEmpty`, `...MaxLength`, `...ExceptionType`, `...OpenApiRepresentation`, `...GraphQLRepresentation`) in `src/Primitives/build/Rocket.Surgery.LaunchPad.Primitives.targets`. - It ships its OpenAPI, HotChocolate, EF Core and OpenTelemetry Joints as templates the same way as Hosting (`src/Primitives/build/*.cs.template`, declared in `Rocket.Surgery.LaunchPad.Primitives.Templates.targets`, which the root `Directory.Build.targets` imports too), reading the `LaunchPadPrimitives` registry its generator fills in. The EF Core value converters, the Dapper type handlers and `AddLaunchPadPrimitivesInstrumentation()` are written by the registry generator (`src/Primitives.Analyzers/Registry`) when the application references those libraries; `ConfigureDomainPrimitives()` is in the EF Core template. `test/Sdk.Tests` (`SdkPrimitivesTests`) proves them end to end. - `LaunchPad.Validation` is LaunchPad's own validation, which is replacing ZeroAlloc.Validation ([ADR-0012](docs/adr/0012-launchpad-owns-validation.md), [`docs/design/validation.md`](docs/design/validation.md), [#3374](https://github.com/RocketSurgeonsGuild/LaunchPad/issues/3374)). It depends on no other LaunchPad package. Until that work is done, ZeroAlloc.Validation is still what validates everywhere. - - `src/Validation` holds what a validator is written with and what a generated validator implements and calls. In `Rocket.Surgery.LaunchPad.Validation`: `IValidationBuilder` and `IMemberRules` (the builder a `Validate` function or an `IValidator` class declares rules on; nothing implements them, the generator reads the calls), `IValidate` and `IValidateAsync` (what an application injects), `ValidationResult`, `ValidationFailure`, `ValidationSink` and `IValidationMessageProvider`. In `.Rules`: `Rule` (the checks of the built-in rules), the rule attributes, and `MemberRulesExtensions` (the same rules on the builder). + - `src/Validation` holds what a validator is written with and what a generated validator implements and calls. In `Rocket.Surgery.LaunchPad.Validation`: `IValidationBuilder` and `IMemberRules` (the builder a `Validate` function or an `IValidatorDefinition` class declares rules on; nothing implements them, the generator reads the calls), `IValidator` (what an application injects: `ValidateAsync`, the only way to validate a whole value), `ValidationResult`, `ValidationFailure`, `ValidationSink` and `IValidationMessageProvider`. In `.Rules`: `Rule` (the checks of the built-in rules), the rule attributes, and `MemberRulesExtensions` (the same rules on the builder). - A rule is declared twice, as an attribute and as an extension method of `IMemberRules`, with the same name; both carry a `[ValidationRule]` that names the method that checks it, and that method carries the rule's code and message in a `[RuleDefaults]`. Add a rule in all three places. - `src/Validation.Analyzers` (its own package, an exception to ADR-0004 as Primitives' is) holds the generator, the analyzers (LPAD3001 and up; LPAD3101 and up for the generator) and the code fixes. `ValidatorGenerator` needs no marker: for every class, struct or record with a rule attribute on a member (LaunchPad's, or the `System.ComponentModel.DataAnnotations` ones it compiles) it writes `{Type}GeneratedValidator` beside the type (`{Type}Validator` is what an application names its class validator), with one public static rule method per member (`Ensure{Member}`) and the rule manifest (`[GeneratedValidator]`, `[GeneratedRule]`). `Model/RuleReader.cs` binds each rule's call as C# would (a speculative binding of the method the attribute's `[ValidationRule]` names), so the overload, its code and message and the placeholders' names come from the compiler. - - A **function validator** (`static void Validate(IValidationBuilder v, ...dependencies)`, in any partial type) and a **class validator** (a partial class that implements `IValidator`) are found by shape and read by `Model/FunctionReader.cs`. The body may only call the builder, and never runs: each chain becomes part of a rule method written into the type that contains it (`Validate{Type}_{Member}`, in a file that repeats the usings of the source file), and each lambda is copied as a local function of that method, so what it names resolves as it does where it was written. The generated methods name the function (`DeclaredBy = nameof(Validate)`): nothing calls a private `Validate`, and without that reference `dotnet format` deletes it as unused. `MergedModel` (in `ValidatorGenerator.cs`) puts the attributes, functions and classes of one type into its one validator, attributes first. - - A type with a rule that waits (`MustAsync`, or a member validated with the validator of such a type) gets an `IValidateAsync` and no `IValidate`; LPAD3002 is an error on `IValidate` of such a type, and its fix makes the use asynchronous. A validator that takes services, or validates a member with that member's validator, is registered scoped; the others are singletons, and only those are `IValidateOptions`. + - A **function validator** (`static void Validate(IValidationBuilder v, ...dependencies)`, in any partial type) and a **class validator** (a partial class that implements `IValidatorDefinition`) are found by shape and read by `Model/FunctionReader.cs`. The body may only call the builder, and never runs: each chain becomes part of a rule method written into the type that contains it (`Validate{Type}_{Member}`, in a file that repeats the usings of the source file), and each lambda is copied as a local function of that method, so what it names resolves as it does where it was written. The generated methods name the function (`DeclaredBy = nameof(Validate)`): nothing calls a private `Validate`, and without that reference `dotnet format` deletes it as unused. `MergedModel` (in `ValidatorGenerator.cs`) puts the attributes, functions and classes of one type into its one validator, attributes first. + - Validation is asynchronous: there is no synchronous interface. The validator of a type none of whose rules waits (no `MustAsync`, no member validated with its own validator, not a `[Mutable]` view model) answers `ValidateAsync` with a completed `ValueTask`, and only such a validator, when it is a singleton, is an `IValidateOptions` too. A validator that takes services, or validates a member with that member's validator, is registered scoped; the others are singletons. - A member is validated with its own type's validator only where it says `[ValidateNested]` (or `[ValidateWith]`); LPAD3001 warns where a type with rules has a member whose type has rules and that says neither that nor `[SkipValidation]`. The nested validator is asked of the `IServiceProvider` the validator is made with. - In a project that references the dependency injection abstractions, the generator writes `Add{AssemblyName}Validators()` (`LaunchPadValidators.g.cs`), which registers the assembly's validators and calls the same method of each referenced assembly (found by `[assembly: ValidatorAssembly]`); with Microsoft.Extensions.Options, a singleton validator of a class is an `IValidateOptions` too. - A validator holds only the rules declared for its type. Each has a public rule method for every member with rules (`Ensure{Member}`, `Ensure_Value` for the whole value; static unless it takes a service), a `ValidateDeclared` that runs them, and is an `IValidateMembers` (one member at a time, which a form field needs). These methods and their `[GeneratedRule]` are the **rule manifest** the generator reads from referenced assemblies (`Model/LinkReader.cs`); `Model/Resolution.cs` decides, once every model of the compilation is in, which other validators each one runs. - The rules of a base class or an interface stay in that type's validator, and the validator of every type that derives from it calls its `ValidateDeclared`; a type with no rules of its own still gets a validator when something it derives from has one. `[InheritFrom]` and `Include()` carry rules member by member (LPAD3112 where a member's rules can't be carried), and the validator of a `[Mutable]` view model validates the whole value as `T` and one member with `T`'s rule methods. Which members `[InheritFrom]` and `[Mutable]` write is decided in `src/Shared/GeneratedMembers.cs`, linked into both analyzer assemblies: the validation generator can't see what those generators write. - - A `Validate` function may declare rules for a type of another assembly. Its validator (`{Type}In{Assembly}GeneratedValidator`) runs the validators the referenced assemblies have for the type and then its own rules, and the registration replaces what is registered for the type with it; `[assembly: ContributedValidator]` tells the assemblies that reference this one. LPAD3113 is an error on an asynchronous rule added to a type its own assembly validates synchronously. + - A `Validate` function may declare rules for a type of another assembly. Its validator (`{Type}In{Assembly}GeneratedValidator`) runs the validators the referenced assemblies have for the type and then its own rules, and the registration replaces what is registered for the type with it; `[assembly: ContributedValidator]` tells the assemblies that reference this one. - What a transport needs is in `src/Validation` too: `ValidationFailedException` (a result with errors, which `ValidationResult.ThrowIfInvalid()` throws), `ValidationNotices` (the warnings and information of the request being handled, which a transport begins and sends with the response), `ValidationJson` (failures as JSON, written by hand), `ValidationManifest` (each validator's rules as data, which the generator writes as its `Manifest` and the registration adds) and `ObjectValidator` (validation by a type known only at run time, registered for every validated type, so a form component uses no reflection). In the manifest `each` before a rule says it is about the items of a collection and `when` that it does not always reject the value. - The integrations are packages of their own ([#3379](https://github.com/RocketSurgeonsGuild/LaunchPad/issues/3379)), each a joint that runs after its host package's and whose types live in that package's namespaces: `src/Validation.AspNetCore` (422 `ValidationFailedProblemDetails`, the `Validation-Notices` response header, and `ValidationOpenApiSchemaTransformer`, which states the rules of the manifests), `src/Validation.Grpc` (`InvalidArgument`, with the failures in the `validation-failures-bin` trailer and the notices in `validation-notices-bin`), `src/Validation.HotChocolate` (one `VALIDATION` error for each failure, and the notices as the `validationNotices` extension) and `src/Validation.Blazor` (`LaunchPadValidator`, on .NET 11's asynchronous form validation). Each turns a `ValidationFailedException` into its transport's error shape; none validates by itself. `src/Analyzers/Api/Core/SchemaRules.cs` reads LaunchPad's rule attributes as it reads ZeroAlloc.Validation's. - Not written yet: validators for generic types (LPAD3101), and validation in the mediator pipeline, which waits for the mediator switch to land ([#3379](https://github.com/RocketSurgeonsGuild/LaunchPad/issues/3379)): until then nothing throws `ValidationFailedException` but an application's own code. The `src/ZeroAlloc.*` packages, the SDK's detection of them and `[Mutable]`'s ZeroAlloc.Validation validator stay until that library is removed ([#3380](https://github.com/RocketSurgeonsGuild/LaunchPad/issues/3380)). diff --git a/docs/adr/0012-launchpad-owns-validation.md b/docs/adr/0012-launchpad-owns-validation.md index 9b216d22ef..df1dc389ce 100644 --- a/docs/adr/0012-launchpad-owns-validation.md +++ b/docs/adr/0012-launchpad-owns-validation.md @@ -5,14 +5,14 @@ The generator writes one validator per validated type at build time, and merges into it every rule the type has: - rule attributes on its members: LaunchPad's own, one for each rule, and the `System.ComponentModel.DataAnnotations` attributes the generator knows, compiled to the same checks; -- **function validators**, `static void Validate(IValidationBuilder v, ...dependencies)`, and **class validators**, partial classes that implement `IValidator` and take their dependencies in their constructor. Both are found by their shape, as Keryx finds handlers, and several for one type merge; +- **function validators**, `static void Validate(IValidationBuilder v, ...dependencies)`, and **class validators**, partial classes that implement `IValidatorDefinition` and take their dependencies in their constructor. Both are found by their shape, as Keryx finds handlers, and several for one type merge; - the rules of the type's base classes and interfaces, and the rules `[InheritFrom]` and `[Mutable]` carry over from `T`. A `Validate` body is a build-time language: it may only call the builder, the generator reads it and writes the checks, and it never runs. Nothing is interpreted at run time: no reflection, no expression trees, no rule objects. Each generated validator exposes one static **rule method** per member and a **rule manifest** that describes them. That is how rules cross assemblies with no source to read: a type that inherits from another calls its rule methods with its own values, the application's registration composes the validators several assemblies wrote for one type, and the API generators read the manifest for the OpenAPI schema. -A validator is synchronous unless one of its rules is asynchronous. An application injects `IValidate` or `IValidateAsync`; using the synchronous one for a type with an asynchronous rule is a build error with a code fix. +Validation is asynchronous. An application injects `IValidator` and awaits `ValidateAsync`; there is no synchronous interface. A validator none of whose rules waits answers with a completed `ValueTask`, so it costs no more than a synchronous call. ## Why @@ -29,6 +29,6 @@ ZeroAlloc.Validation declares rules with attributes only, so a rule that needs c ## Consequences -Replacing ZeroAlloc.Validation is a breaking change for every application that validates: the attributes move to `Rocket.Surgery.LaunchPad.Validation.Rules`, the injected type becomes `IValidate` or `IValidateAsync`, and the failures have LaunchPad's shape (path, code, message, severity and the values of the message's placeholders). The rule attributes share names with `System.ComponentModel.DataAnnotations` (`[MaxLength]`, `[EmailAddress]`), so a file imports one namespace or the other, or aliases one. +Replacing ZeroAlloc.Validation is a breaking change for every application that validates: the attributes move to `Rocket.Surgery.LaunchPad.Validation.Rules`, the injected type becomes `IValidator`, whose only method is asynchronous, and the failures have LaunchPad's shape (path, code, message, severity and the values of the message's placeholders). The rule attributes share names with `System.ComponentModel.DataAnnotations` (`[MaxLength]`, `[EmailAddress]`), so a file imports one namespace or the other, or aliases one. LaunchPad now maintains a validation library: every built-in rule, its message, and a diagnostic for everything the generator refuses to read. A type that holds a `Validate` function, and every class validator, must be `partial`, because the generated validator is written inside it to reach its private members and dependencies. The generated rule methods are public members of every library that validates, hidden from IntelliSense: changing a library's rules changes what the assemblies that inherit them call. diff --git a/docs/design/validation.md b/docs/design/validation.md index 86b9c47c80..f10cc263b3 100644 --- a/docs/design/validation.md +++ b/docs/design/validation.md @@ -30,7 +30,7 @@ Nothing is interpreted at run time: no reflection, no expression trees, no rule Items marked _(decided)_ were settled in the interview. The rest are proposals; correct any of them. -1. **Names** _(decided)_. Authoring: `IValidationBuilder`, whose `Ensure` returns an `IMemberRules`, and `IValidator` (the class shape). Consuming: `IValidate` (sync and async) and `IValidateAsync` (async only). Result: `ValidationResult` holding `ValidationFailure`s. +1. **Names** _(decided)_. Authoring: `IValidationBuilder`, whose `Ensure` returns an `IMemberRules`, and `IValidatorDefinition` (the class shape). Consuming: `IValidator`, which is asynchronous; there is no synchronous interface (see "As built"). Result: `ValidationResult` holding `ValidationFailure`s. 2. **A failure carries** _(decided)_ `Path` (`Stages[2].Thrust`), `Code` (stable, the rule's name by default, e.g. `MaxLength`), `Message`, `Severity` (`Error`, `Warning`, `Info`) and the values of the message's placeholders. Only `Error` makes a result invalid. Warnings and info travel to clients on every transport, on successful responses too: each integration defines its shape for them (problem details and GraphQL extensions, gRPC trailers). **Messages** _(decided)_: each rule has a default English template compiled in. At run time an optional `IValidationMessageProvider`, keyed by code, can replace any message (an `IStringLocalizer` adapter is the expected use), and transports send the code and placeholder values so a client can localise for itself. 3. **Merge order**: the rules of the base classes, the farthest first, then of the interfaces, then the type's own, member by member in the order the members first have a rule; for one member, its attributes, then the rules carried by `[InheritFrom]` and `Include`, then the type's functions and classes in a stable order (file path, then position). Every rule runs; a chain stops at its first failure only where `.StopOnFailure()` says so. @@ -76,7 +76,7 @@ public static partial class CreateRocket } // A class validator: dependencies in the constructor. -internal partial class RequestValidator(TimeProvider time) : IValidator +internal partial class RequestValidator(TimeProvider time) : IValidatorDefinition { public void Validate(IValidationBuilder v) => v.Ensure(x => x.ScheduledLaunchDate).GreaterThan(_ => time.GetUtcNow()); @@ -115,7 +115,7 @@ Only builder calls, as expression statements or an expression body. Lambdas may By shape, as Keryx finds handlers; there is no marker attribute. - A method named `Validate` that returns `void` and whose first parameter is `IValidationBuilder`, in any partial type. -- A partial class that implements `IValidator`. +- A partial class that implements `IValidatorDefinition`. - A type with rule attributes on its members and nothing else. Several functions and classes for the same `T` merge. A function or class for a base class or interface applies to every type that derives from or implements it. @@ -124,12 +124,12 @@ Several functions and classes for the same `T` merge. A function or class for a Each assembly generates only for the rules it declares; it never re-emits another assembly's. For each `T` an assembly has rules for: -- A sealed validator class for those rules, implementing `IValidate` when every rule is synchronous, or only `IValidateAsync` when any rule is asynchronous. `IValidate` extends `IValidateAsync`, whose `ValidateAsync` then completes synchronously. See "Synchronous use of an async validator" below. +- A sealed validator class for those rules, implementing `IValidator`. When no rule waits, its `ValidateAsync` completes synchronously. - One static **rule method** per member (and one for the whole-value rules), holding that member's checks as straight-line code. The validator calls them in merge order. - A **rule manifest**: attributes on the validator that list, per member, the rule method, the members and dependencies it reads, whether it is async, and each built-in rule's kind and arguments. - `AddLaunchPadValidators()` for the assembly, and an `IValidateOptions` adapter where the project references `Microsoft.Extensions.Options`. -**Composition at registration.** When several assemblies have rules for the same `T` (its own, a library's, the application's), the registration generated in the outermost assembly composes them: it reads the manifests of its references and registers one `IValidate` (or `IValidateAsync`, if any part is async) that runs each assembly's validator once, in reference order and then its own. A library's own `AddLaunchPadValidators()` composes what that library can see, so it works alone; the application's replaces it. +**Composition at registration.** When several assemblies have rules for the same `T` (its own, a library's, the application's), the registration generated in the outermost assembly composes them: it reads the manifests of its references and registers one `IValidator` that runs each assembly's validator once, in reference order and then its own. A library's own `AddLaunchPadValidators()` composes what that library can see, so it works alone; the application's replaces it. The manifest is what makes the rest work from metadata, with no source to read: @@ -140,13 +140,7 @@ The manifest is what makes the rest work from metadata, with no source to read: ### Synchronous use of an async validator -_(decided)_ When `T`'s validator has an async rule, any synchronous use of it is a build error from LaunchPad's analyzer, with a code fix: - -- Reported on: a call to `Validate` for `T`, and any mention of `IValidate` (a constructor or method parameter, a field, `GetService>()`). The second matters most: `IValidate` is a valid type for any `T`, so without the analyzer it would compile and fail when DI resolves it. -- The fix: `IValidate` becomes `IValidateAsync`, and `validator.Validate(x)` becomes `await validator.ValidateAsync(x, cancellationToken)`, using the `CancellationToken` in scope if there is one and making the containing method `async` (and its return type a task) if it isn't. -- The analyzer knows whether `T` is async from the rules in the compilation and from the manifests of its references. - -_(proposal)_ One case the fix can't reach: an assembly adds an async rule for a `T` whose validator in a referenced assembly is synchronous. Code already compiled against `IValidate` would break at run time, so the async rule itself is the error there, saying that `T` is validated synchronously by the assembly that declares it. +_(superseded)_ The first design had a synchronous `IValidate` beside the asynchronous interface, with a build error (LPAD3002) and a code fix where a type with an asynchronous rule was validated synchronously, and an error (LPAD3113) on an asynchronous rule added to a type its own assembly validated synchronously. Both went with the synchronous interface: see "As built". DataAnnotations: the attributes the generator knows (`[Required]`, `[StringLength]`, `[MaxLength]`, `[MinLength]`, `[Length]`, `[Range]`, `[RegularExpression]`, `[EmailAddress]`, `[Url]`, `[Phone]`, `[CreditCard]`, `[Compare]`, `[AllowedValues]`, `[DeniedValues]`, `[Base64String]`) become the same inline checks as their LaunchPad equivalents, and `ErrorMessage` becomes the message. Nothing else from DataAnnotations runs _(decided)_: a custom `ValidationAttribute`, `IValidatableObject`, `[CustomValidation]`, `[MetadataType]` and `[Range(typeof(T), string, string)]` are each a build diagnostic that points at `[Must]` or a `Validate` function. @@ -158,17 +152,17 @@ Where the code so far differs from the text above: - **The rules of a function or a class validator** are written into the type that contains it, as `Validate{Type}_{Member}` methods, in a file that repeats the usings of the file they come from. Each lambda is copied as a local function, so it reads the function's dependencies and the type's private members by the names it was written with. - **A private `Validate` function is never called**, so the compiler and formatters would take it for unused (`dotnet format` deletes it under IDE0051). The rule methods written from it name it (`DeclaredBy = nameof(Validate)`), which makes it used. - **A chain is about one member** (`x => x.Member`) or the whole value (`x => x`); a path through another member (`x => x.Engine.Name`) is an error. Rules for the members of a member go in that member's type, or in `EnsureEach` for a collection. -- **Lifetimes**: a validator that takes services, or that validates a member with the member's validator, is scoped; the others are singletons. Only a synchronous singleton is an `IValidateOptions`. +- **Lifetimes**: a validator that takes services, or that validates a member with the member's validator, is scoped; the others are singletons. Only a singleton none of whose rules waits is an `IValidateOptions`. - **`ValidateNested` in a chain** can't be under a condition. - **A validator holds only the rules declared for its type** in its assembly. Each has a rule method for every member with rules (`Ensure{Member}`, and `Ensure_Value` for the rules about the whole value), which checks that member's attributes, then the rules it carries, then calls the rule methods of the functions and classes; `ValidateDeclared` runs them all, and `Validate` runs the `ValidateDeclared` of every validator of what the type is, then its own. A rule method is static unless it takes a service, a class validator or the validator of the member. These methods, with their `[GeneratedRule]`, are the rule manifest: the generator reads them from a referenced assembly's validators, which it finds by the name of the type (`{Type}GeneratedValidator`, in the assembly that declares the type) and by `[assembly: ContributedValidator]`. -- **Base classes and interfaces.** A type's validator calls the validator of each base class and each interface that has rules, in this compilation or a referenced assembly. A type with no rules of its own gets a validator when something it derives from has one. An interface, or an abstract class, with rules has a validator too (`IValidate`). The attributes of a base class's members are read into the validator of the first type down the chain that has a validator: a base class this compilation can't write one for (a generic one, one of an assembly that doesn't run the generator) has its attributes read by each type that derives from it. +- **Base classes and interfaces.** A type's validator calls the validator of each base class and each interface that has rules, in this compilation or a referenced assembly. A type with no rules of its own gets a validator when something it derives from has one. An interface, or an abstract class, with rules has a validator too (`IValidator`). The attributes of a base class's members are read into the validator of the first type down the chain that has a validator: a base class this compilation can't write one for (a generic one, one of an assembly that doesn't run the generator) has its attributes read by each type that derives from it. - **`[InheritFrom]` and `Include()`** carry rules member by member: the rule method of a copied member calls the rule method `TOther`'s validator has for it. Where that method takes services, the validator takes `TOther`'s validator, which the registration adds; where it waits, the type is asynchronous only. A member's rules are not carried when they read the whole `TOther` (a `Must((x, value) => ...)`, a `When`), compare it with a member that was not copied, or the member's type differs: LPAD3112, a warning, says which. The generator works out which members `[InheritFrom]` copies with the code that copies them (`src/Shared/GeneratedMembers.cs`). `Include` takes the members the two types share by name and type. -- **`[Mutable]`**: the view model's validator validates the whole value as `T` (`ToImmutable()`, with the `IValidate` or `IValidateAsync` of the service provider), then the view model's own rules. `[Mutable]`'s generator still writes the ZeroAlloc.Validation validator beside it until that library goes (phase 6). +- **`[Mutable]`**: the view model's validator validates the whole value as `T` (`ToImmutable()`, with the `IValidator` of the service provider, which it awaits), then the view model's own rules. `[Mutable]`'s generator still writes the ZeroAlloc.Validation validator beside it until that library goes (phase 6). - **`IValidateMembers`** is the per-member entry point, and every generated validator is one, not only a view model's: `TryValidateMember(value, member, out result)` checks the rules of one member, from every validator of what the type is, and returns `false` when one of them waits; `ValidateMemberAsync` checks them either way. A view model checks the rules `T` and its base classes and interfaces have for the member with the view model's value, without making a `T`; a rule that reads the whole `T` is left to the validation of the whole view model. -- **Rules for a type of another assembly.** A `Validate` function may declare rules for any class, struct, record or interface the compilation can reach. For a type another assembly declares, the validator is `{Type}In{Assembly}GeneratedValidator`, in the type's namespace; it runs the validators the referenced assemblies have for the type, then its own rules, and the registration replaces what is registered for the type with it (`RemoveAll`, then add), so the rules of each assembly run once. `[assembly: ContributedValidator]` tells the assemblies that reference this one about it. An asynchronous rule added to a type whose own assembly validates it synchronously is an error (LPAD3113), as proposed above. +- **Rules for a type of another assembly.** A `Validate` function may declare rules for any class, struct, record or interface the compilation can reach. For a type another assembly declares, the validator is `{Type}In{Assembly}GeneratedValidator`, in the type's namespace; it runs the validators the referenced assemblies have for the type, then its own rules, and the registration replaces what is registered for the type with it (`RemoveAll`, then add), so the rules of each assembly run once. `[assembly: ContributedValidator]` tells the assemblies that reference this one about it. - **String rules** (`EmailAddress`, `Url`, `Matches`) are declared for `IEquatable`, and the length rules for `IEnumerable`, so the rules after them still see a `string` member as `string` and a `string?` one as `string?`. `IMemberRules` is covariant, so a rule an application declares for a base type applies to the members of derived ones. -- **The LPAD3002 fix** changes the uses in one document. Where the result must stay synchronous (a `Func`, a method that wraps the result in `Task.FromResult`) what it leaves does not compile, and says where. -- **Registration** is `Add{AssemblyName}Validators()`, public, one per assembly, and it calls the same method of each referenced assembly. Each validator is registered as the type's `IValidateAsync`, its `IValidate` if no rule waits, and its `IValidateMembers`. An `internal AddLaunchPadValidators()` in every assembly would be ambiguous in any project that sees another's internals (`InternalsVisibleTo`), which this repository's tests do. +- **One interface, asynchronous.** `IValidator` has `ValidateAsync` and nothing else; the synchronous `IValidate`, LPAD3002 and its fix, and LPAD3113 are gone. The class shape that declares rules is `IValidatorDefinition`. A validator none of whose rules waits writes `ValidateAsync` without a state machine: it returns a completed `ValueTask`, a cancelled one if the token already is, and a faulted one if a rule throws. A member validated with its own validator, and the whole value of a `[Mutable]` view model, go through the `IValidator` of the service provider, so a type that has either always awaits. `IValidateMembers.TryValidateMember` still answers at once for a member whose rules don't wait. +- **Registration** is `Add{AssemblyName}Validators()`, public, one per assembly, and it calls the same method of each referenced assembly. Each validator is registered as the type's `IValidator` and its `IValidateMembers`. An `internal AddLaunchPadValidators()` in every assembly would be ambiguous in any project that sees another's internals (`InternalsVisibleTo`), which this repository's tests do. - **Options**: there is no adapter. Each validator of a class implements `IValidateOptions` itself and is registered as one, so an options class with rules is validated wherever it is used. - **Nested validators** are asked of the `IServiceProvider` the validator is made with, when first needed, and not injected: a type can then be validated inside itself, and what is asked for is the composed validator the application registered. - **A pattern in an attribute** (`[Matches]`, `[RegularExpression]`) is an interpreted `Regex` held by the validator: the regular expression generator can't see what another generator writes. A `Validate` function can pass a `[GeneratedRegex]` member. @@ -182,7 +176,7 @@ Where the code so far differs from the text above: - **Warnings on successful responses** go through `ValidationNotices`: whatever validates a request adds what did not reject it, and the transport sends it. A transport begins the notices before the request is handled and they are ambient from there (an `AsyncLocal`), registered scoped as the ones of the request being handled: a GraphQL resolver runs in a scope of its own, and a scoped service alone would never reach the response. They travel as the `Validation-Notices` response header over HTTP (a JSON array), the `validation-notices-bin` trailer over gRPC, and the `validationNotices` extension of a GraphQL result. - **OpenAPI at run time** reads `ValidationManifest`, the rules of each validated type as data: the generator writes one as the validator's `Manifest` (with the rules of what the type derives from) and the registration adds it. `ValidationOpenApiSchemaTransformer` states the rules of a schema property from the member System.Text.Json serializes it from, whichever way the rule was declared. In the manifest a rule under a condition, a warning, and a rule about a member of a collection's item start with `when` and are left out; a rule about the items of a collection starts with `each` and goes to the `items` schema. - **OpenAPI at build time** (the API generators, `SchemaRules`) reads LaunchPad's rule attributes from the request's members, beside ZeroAlloc.Validation's until that goes. It can't read the manifest of a type in the same compilation, which another generator writes, so the rules of a `Validate` function reach the document only through the transformer above. -- **Blazor** uses the asynchronous form validation .NET 11 added: `LaunchPadValidator` validates a field that changes with `IValidateMembers`, at once when its rules are synchronous and otherwise as `EditContext.RegisterAsyncFieldValidator`, so `IsValidationPending` is the pending state and a later change cancels an earlier one; `EditContext.ValidateAsync` awaits the whole model, and `Validate` throws for a model with a rule that waits, as the form does for any asynchronous validator. The validator is found by the model's run-time type through `ObjectValidators`, which the generated registrations fill in, with no reflection. A failure of a nested member is shown on the path's field of the top model, so it is in the summary and not beside the nested input. +- **Blazor** uses the asynchronous form validation .NET 11 added: `LaunchPadValidator` validates a field that changes with `IValidateMembers`, at once when its rules are synchronous and otherwise as `EditContext.RegisterAsyncFieldValidator`, so `IsValidationPending` is the pending state and a later change cancels an earlier one; `EditContext.ValidateAsync` awaits the whole model, and the obsolete `Validate` throws, as the form does for any asynchronous validator. The validator is found by the model's run-time type through `ObjectValidators`, which the generated registrations fill in, with no reflection. A failure of a nested member is shown on the path's field of the top model, so it is in the summary and not beside the nested input. ## Tech stack @@ -246,7 +240,7 @@ Phases 2 to 4 can't run in parallel (one generator); the integrations of phase 5 - No project, sample or test references `ZeroAlloc.Validation`, `ZeroAlloc.Validation.Inject`, `ZeroAlloc.Validation.Options` or `ZeroAlloc.Mediator.Validation`, and no source mentions them. - A type with attributes, a function validator, a class validator, an interface's rules and `[InheritFrom]` from a referenced assembly gets one validator whose failures cover all five, proven by a test. -- A validator with only synchronous rules has `Validate`. For one with a `MustAsync` rule, calling `Validate` or injecting `IValidate` is a build error whose code fix produces code that compiles and awaits `ValidateAsync`, proven by analyzer and code fix tests. +- Every validator is an `IValidator`, validated with `ValidateAsync`. One with only synchronous rules completes synchronously, proven by a test. - A `[Mutable]` view model validates one field without building `T` (synchronously when the field's rules are, otherwise asynchronously), and its whole value with `T`'s rules. - Rules for one type declared in a library and in the application both run, once each, through the one validator the application registers. - Requests are validated before their handler over HTTP, gRPC and GraphQL, and each answers its transport's error shape with the failures, their codes and placeholder values; a warning reaches the client on a successful response over each; the OpenAPI document states the same lengths, ranges, patterns and required members it does today. diff --git a/docs/src/content/docs/concepts/validation.md b/docs/src/content/docs/concepts/validation.md index 9ab8bf80cb..b3403c1fe0 100644 --- a/docs/src/content/docs/concepts/validation.md +++ b/docs/src/content/docs/concepts/validation.md @@ -57,7 +57,7 @@ public static partial class CreateRocketRules The body never runs. The generator reads it at build time and writes each chain as a method of the type that contains it, so a `Validate` body may only call the builder. -**A class validator**: a partial class that implements `IValidator`, whose dependencies are its constructor's. +**A class validator**: a partial class that implements `IValidatorDefinition`, whose dependencies are its constructor's. A member is validated with its own type's validator only where you say so, with `[ValidateNested]` or `.ValidateNested()`. An analyzer warns about a member whose type has rules and that says neither that nor `[SkipValidation]`. @@ -70,24 +70,23 @@ assemblies it references. ```csharp services.AddMyAppValidators(); -public sealed class RocketService(IValidate validator) +public sealed class RocketService(IValidator validator) { - public void Create(CreateRocket request) + public async Task Create(CreateRocket request, CancellationToken cancellationToken) { - validator.Validate(request).ThrowIfInvalid(); + ( await validator.ValidateAsync(request, cancellationToken) ).ThrowIfInvalid(); // ... } } ``` -| You inject | It gives | -| --------------------- | ------------------------------------------------------------------------ | -| `IValidate` | `Validate(value)`. Only a type with no rule that waits has one. | -| `IValidateAsync` | `ValidateAsync(value, cancellationToken)`. Every validated type has one. | -| `IValidateMembers` | One member at a time, which a form does when a field changes. | +| You inject | It gives | +| --------------------- | ------------------------------------------------------------- | +| `IValidator` | `ValidateAsync(value, cancellationToken)`. | +| `IValidateMembers` | One member at a time, which a form does when a field changes. | -A type with a `MustAsync` rule is validated asynchronously only. Asking for its `IValidate` is a build error, with a fix that -makes the use asynchronous. +Validation is asynchronous, because a rule may wait (`MustAsync`). The validator of a type none of whose rules waits answers at +once, with a completed `ValueTask`. A failure carries the path of the member (`Stages[2].Thrust`), a code that stays the same whatever the message says (`MaxLength`), the message, a severity and the values of the message's placeholders. Only an error makes a result invalid: a rule declared as a diff --git a/src/Validation.Analyzers/AnalyzerReleases.Unshipped.md b/src/Validation.Analyzers/AnalyzerReleases.Unshipped.md index 39a054cf13..1ae715e249 100644 --- a/src/Validation.Analyzers/AnalyzerReleases.Unshipped.md +++ b/src/Validation.Analyzers/AnalyzerReleases.Unshipped.md @@ -6,7 +6,6 @@ Rule ID | Category | Severity | Notes --------|----------|----------|------- LPAD3001 | LaunchPad.Validation | Warning | NestedValidationAnalyzer, a member whose type has rules says neither [ValidateNested] nor [SkipValidation] -LPAD3002 | LaunchPad.Validation | Error | SynchronousValidationAnalyzer, the synchronous IValidate of a type that has an asynchronous rule LPAD3101 | LaunchPad.Validation | Error | ValidatorGenerator, a generic type can't be validated yet LPAD3102 | LaunchPad.Validation | Error | ValidatorGenerator, the type or a member with a rule can't be reached by the generated validator LPAD3103 | LaunchPad.Validation | Error | ValidatorGenerator, a rule doesn't apply to the member's type @@ -19,4 +18,3 @@ LPAD3109 | LaunchPad.Validation | Error | ValidatorGenerator, the type that cont LPAD3110 | LaunchPad.Validation | Error | ValidatorGenerator, a Validate function for a type rules can't be declared for LPAD3111 | LaunchPad.Validation | Error | ValidatorGenerator, an argument that must be a constant is not LPAD3112 | LaunchPad.Validation | Warning | ValidatorGenerator, the rules of a member [InheritFrom] or Include copies can't be checked for the type that copies it -LPAD3113 | LaunchPad.Validation | Error | ValidatorGenerator, an asynchronous rule added to a type that the assembly declaring it validates synchronously diff --git a/src/Validation.Analyzers/Diagnostics.cs b/src/Validation.Analyzers/Diagnostics.cs index 33c030df9a..90f3bf33d7 100644 --- a/src/Validation.Analyzers/Diagnostics.cs +++ b/src/Validation.Analyzers/Diagnostics.cs @@ -19,15 +19,6 @@ internal static class Diagnostics true ); - public static readonly DiagnosticDescriptor SynchronousUseOfAsyncValidator = new( - "LPAD3002", - "The type is validated asynchronously", - "'{0}' has an asynchronous rule, so it has no IValidate<{0}>: use IValidateAsync<{0}> and await ValidateAsync", - Category, - DiagnosticSeverity.Error, - true - ); - public static readonly DiagnosticDescriptor GenericType = new( "LPAD3101", "A generic type can't be validated yet", @@ -136,15 +127,6 @@ internal static class Diagnostics true ); - public static readonly DiagnosticDescriptor AsynchronousRuleForSynchronousType = new( - "LPAD3113", - "The type is validated synchronously by the assembly that declares it", - "'{0}' has an IValidate in the assembly that declares it, which code may already use: a rule added to it here can't be asynchronous", - Category, - DiagnosticSeverity.Error, - true - ); - public static DiagnosticDescriptor? Find(string id) => id switch { "LPAD3101" => GenericType, @@ -159,7 +141,6 @@ internal static class Diagnostics "LPAD3110" => TargetNotSupported, "LPAD3111" => ConstantRequired, "LPAD3112" => RulesNotCarried, - "LPAD3113" => AsynchronousRuleForSynchronousType, _ => null, }; } diff --git a/src/Validation.Analyzers/Model/FunctionReader.cs b/src/Validation.Analyzers/Model/FunctionReader.cs index 38a7fd4d73..10cdee65c7 100644 --- a/src/Validation.Analyzers/Model/FunctionReader.cs +++ b/src/Validation.Analyzers/Model/FunctionReader.cs @@ -8,7 +8,7 @@ namespace Rocket.Surgery.LaunchPad.Validation.Analyzers.Model; /// /// Reads a function validator (static void Validate(IValidationBuilder<T> v, ...)) or the Validate of a class validator -/// (an IValidator<T>), and writes the rule methods it stands for. +/// (an IValidatorDefinition<T>), and writes the rule methods it stands for. /// /// /// @@ -27,7 +27,7 @@ internal sealed class FunctionReader public static ContributorResult? Read(MethodDeclarationSyntax syntax, SemanticModel model) { - // The declaration of IValidator.Validate itself, or an abstract one, declares no rules. + // The declaration of IValidatorDefinition.Validate itself, or an abstract one, declares no rules. if (syntax.Body is null && syntax.ExpressionBody is null) return null; if (model.GetDeclaredSymbol(syntax) is not { Name: "Validate", ReturnsVoid: true, Parameters.Length: >= 1 } method) return null; if (method.Parameters[0].Type is not INamedTypeSymbol { TypeArguments: [var targetType] } builder @@ -103,7 +103,7 @@ private void Report(DiagnosticDescriptor descriptor, SyntaxNode? node, params st var isClass = !_method.IsStatic && _method.Parameters.Length == 1 && container.AllInterfaces.Any( - z => ValidationSymbols.Is(z.OriginalDefinition, ValidationSymbols.RuntimeNamespace, "IValidator") + z => ValidationSymbols.Is(z.OriginalDefinition, ValidationSymbols.RuntimeNamespace, "IValidatorDefinition") && SymbolEqualityComparer.Default.Equals(z.TypeArguments[0], targetType) ); var location = _syntax.Identifier; @@ -113,7 +113,7 @@ private void Report(DiagnosticDescriptor descriptor, SyntaxNode? node, params st DiagnosticModel.Create( Diagnostics.CallNotUnderstood, location.GetLocation(), - "Validate declares rules only as a static method that takes its dependencies as parameters, or as the Validate of a class that implements IValidator" + "Validate declares rules only as a static method that takes its dependencies as parameters, or as the Validate of a class that implements IValidatorDefinition" ) ); return null; @@ -622,7 +622,6 @@ private void ReadNested(InvocationExpressionSyntax call, IMethodSymbol symbol, s into.Nested = new( target.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), with?.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), - with is null ? TargetReader.IsKnownAsync(target, _model.Compilation) : !TargetReader.ImplementsSynchronous(with), item is not null, ValidationSymbols.CanBeNull(memberType), item is not null && ValidationSymbols.CanBeNull(item) diff --git a/src/Validation.Analyzers/Model/LinkReader.cs b/src/Validation.Analyzers/Model/LinkReader.cs index 26aebee62a..7856351c3f 100644 --- a/src/Validation.Analyzers/Model/LinkReader.cs +++ b/src/Validation.Analyzers/Model/LinkReader.cs @@ -44,7 +44,6 @@ public static LinkModel Read(INamedTypeSymbol type, Compilation compilation) mutable = new( Key(target), self.Referenced.Length > 0, - TargetReader.IsKnownAsync(target, compilation), sources.ToImmutable(), CopiedOf(MutableMembers.ViewModelProperties(target, compilation)) ); @@ -248,7 +247,6 @@ public SourceLinkModel Link(INamedTypeSymbol type) TargetReader.IsPublic(validator), declared is not null, declared is { ReturnsVoid: false }, - TargetReader.ImplementsSynchronous(validator), members.ToEquatableArray() ); } diff --git a/src/Validation.Analyzers/Model/Models.cs b/src/Validation.Analyzers/Model/Models.cs index 17561443a5..599d90611e 100644 --- a/src/Validation.Analyzers/Model/Models.cs +++ b/src/Validation.Analyzers/Model/Models.cs @@ -65,14 +65,13 @@ internal sealed record RegexModel(string Field, string Pattern, string Options); /// How a member is validated with a validator of its own. /// The type validated, as generated code names it. /// The validator named by [ValidateWith], or for the one of the type. -/// Whether the validator is known to be asynchronous only, from a referenced assembly or from the one named. /// Whether the member is a collection validated item by item. /// Whether the member can be null. /// Whether an item of the collection can be null. -internal sealed record NestedModel(string Target, string? Validator, bool IsAsync, bool IsCollection, bool CanBeNull, bool ItemCanBeNull); +internal sealed record NestedModel(string Target, string? Validator, bool IsCollection, bool CanBeNull, bool ItemCanBeNull); /// -/// The rules a Validate function or an IValidator class declares for a type, already written: the methods the generator adds +/// The rules a Validate function or an IValidatorDefinition class declares for a type, already written: the methods the generator adds /// to the type that contains the function, one for each member the rules are about. /// /// The type the rules are for. @@ -186,13 +185,11 @@ internal sealed record CopiedMemberModel(string Name, string Type); /// The type a [Mutable] view model is of. /// The type, as generated code names it. /// Whether a referenced assembly has a validator for it. -/// Whether that validator is asynchronous only. /// The type, then its base classes and interfaces: where the rules of its members are. /// The properties the view model has. internal sealed record MutableLinkModel( string Type, bool IsValidated, - bool IsKnownAsync, EquatableArray Sources, EquatableArray Members ); @@ -204,7 +201,6 @@ EquatableArray Members /// Whether it can be named in the signature of a public member. /// Whether it has rules at all. /// Whether a rule it declares waits. -/// Whether it is an IValidate: code may already depend on the type being validated synchronously. /// Its rule methods. internal sealed record SourceModel( string Target, @@ -213,7 +209,6 @@ internal sealed record SourceModel( bool IsPublic, bool HasDeclared, bool DeclaredAsync, - bool IsSynchronous, EquatableArray Members ); diff --git a/src/Validation.Analyzers/Model/Resolution.cs b/src/Validation.Analyzers/Model/Resolution.cs index 076681cafe..96e0978635 100644 --- a/src/Validation.Analyzers/Model/Resolution.cs +++ b/src/Validation.Analyzers/Model/Resolution.cs @@ -103,14 +103,11 @@ internal sealed class ResolvedMember(string name, string type) public bool IsAsync { get; set; } - /// Whether the validator the member is validated with is asynchronous only. - public bool NestedAwaited { get; set; } - /// Whether the method reads what the validator was made with, and so is not static. public bool NeedsInstance { get; set; } /// Whether a rule of the member waits, as things stand: one of its own, or one of a rule method it calls. - public bool Waits => NestedAwaited || Contributed.Any(static z => z.Member.IsAsync) || Carried.Any(static z => z.Member.IsAsync); + public bool Waits => Nested is not null || Contributed.Any(static z => z.Member.IsAsync) || Carried.Any(static z => z.Member.IsAsync); /// Whether the method reads what the validator was made with, as things stand. public bool ReadsInstance => TakesServices || Carried.Any(static z => !z.Member.IsStatic); @@ -223,7 +220,6 @@ ImmutableArray contributed resolver.Flags(all); foreach (var model in all) { - resolver.Check(model); } return ([.. all.Where(static z => z.WillEmit)], resolver.Diagnostics); @@ -381,7 +377,6 @@ private bool Settle(MergedModel model) var changed = false; foreach (var member in model.Resolved) { - if (!member.NestedAwaited && member.Nested is { } nested && IsAwaited(nested)) changed = member.NestedAwaited = true; if (member.Waits && !member.IsAsync) changed = member.IsAsync = true; if (member.ReadsInstance && !member.NeedsInstance) changed = member.NeedsInstance = true; } @@ -391,7 +386,7 @@ private bool Settle(MergedModel model) var isAsync = declaredAsync || model.Sources.Any(static z => z.DeclaredAsync) - || ( model.Mutable is { } mutable && ( model.MutableTarget?.IsAsync ?? mutable.IsKnownAsync ) ); + || model.Mutable is not null; if (isAsync && !model.IsAsync) changed = model.IsAsync = true; var instance = model.Resolved.Any(static z => z.NeedsInstance); @@ -399,20 +394,6 @@ private bool Settle(MergedModel model) return changed; } - private bool IsAwaited(NestedModel nested) => - nested.Validator is null && _byType.TryGetValue(nested.Target, out var target) && target.WillEmit ? target.IsAsync : nested.IsAsync; - - // Code compiled against the validator of the assembly that declares the type may ask for its IValidate: a rule that waits would take it away. - private void Check(MergedModel model) - { - if (!model.Target.IsForeign || !model.DeclaredAsync || model.Links is not { } links) return; - if (links.IsA.FirstOrDefault(z => z.Type == model.Target.Type) is not { } self || !self.Referenced.Any(static z => z.IsSynchronous)) return; - foreach (var contributor in model.Contributors.Where(static z => z.Members.Any(static m => m.IsAsync))) - { - Report(Analyzers.Diagnostics.AsynchronousRuleForSynchronousType, contributor.Location, model.Target.DocumentationName); - } - } - private void Report(Microsoft.CodeAnalysis.DiagnosticDescriptor descriptor, LocationModel location, params string[] arguments) => Diagnostics.Add(new(descriptor.Id, location.Path, location.Span, location.LineSpan, arguments.ToEquatableArray())); } diff --git a/src/Validation.Analyzers/Model/RuleReader.cs b/src/Validation.Analyzers/Model/RuleReader.cs index 2defbb3085..77339f0e6e 100644 --- a/src/Validation.Analyzers/Model/RuleReader.cs +++ b/src/Validation.Analyzers/Model/RuleReader.cs @@ -162,7 +162,6 @@ private void ReadNested(MemberContext context, AttributeData attribute) context.Nested = new( named.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), with?.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), - with is null ? TargetReader.IsKnownAsync(named, _model.Compilation) : !TargetReader.ImplementsSynchronous(with), item is not null, ValidationSymbols.CanBeNull(context.Type), item is not null && ValidationSymbols.CanBeNull(item) diff --git a/src/Validation.Analyzers/Model/TargetReader.cs b/src/Validation.Analyzers/Model/TargetReader.cs index 917f6952ee..af5b742624 100644 --- a/src/Validation.Analyzers/Model/TargetReader.cs +++ b/src/Validation.Analyzers/Model/TargetReader.cs @@ -106,21 +106,6 @@ public static IEnumerable InlinedMembers(INamedTypeSymbol type, Compila } } } - - /// - /// Whether a type from a referenced assembly is validated asynchronously only: its validator, found by its name, is an - /// IValidateAsync and not an IValidate. A type of this compilation is decided when its rules are merged. - /// - public static bool IsKnownAsync(INamedTypeSymbol target, Compilation compilation) - { - if (SymbolEqualityComparer.Default.Equals(target.ContainingAssembly, compilation.Assembly)) return false; - var @namespace = NamespaceOf(target); - var name = ( @namespace.Length == 0 ? "" : @namespace + "." ) + ValidatorName(target); - return target.ContainingAssembly.GetTypeByMetadataName(name) is { } validator && !ImplementsSynchronous(validator); - } - - public static bool ImplementsSynchronous(INamedTypeSymbol validator) => - validator.AllInterfaces.Any(static z => ValidationSymbols.Is(z.OriginalDefinition, ValidationSymbols.RuntimeNamespace, "IValidate")); } /// diff --git a/src/Validation.Analyzers/SynchronousValidationAnalyzer.cs b/src/Validation.Analyzers/SynchronousValidationAnalyzer.cs deleted file mode 100644 index 1cd0fed7a4..0000000000 --- a/src/Validation.Analyzers/SynchronousValidationAnalyzer.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System.Collections.Immutable; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Diagnostics; -using Rocket.Surgery.LaunchPad.Validation.Analyzers.Model; - -namespace Rocket.Surgery.LaunchPad.Validation.Analyzers; - -/// -/// LPAD3002: IValidate<T> of a type that has an asynchronous rule. Such a type has only an IValidateAsync<T>, so the -/// synchronous one would compile and then not be found when it is asked for. -/// -/// -/// Whether a type is validated asynchronously is read from its generated validator, in this compilation or in the assembly that declares -/// the type: it is an IValidateAsync and not an IValidate. -/// -[DiagnosticAnalyzer(LanguageNames.CSharp)] -public sealed class SynchronousValidationAnalyzer : DiagnosticAnalyzer -{ - /// - public override ImmutableArray SupportedDiagnostics { get; } = [Diagnostics.SynchronousUseOfAsyncValidator]; - - /// - public override void Initialize(AnalysisContext context) - { - context.EnableConcurrentExecution(); - context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); - context.RegisterSyntaxNodeAction(Analyze, SyntaxKind.GenericName); - } - - private static void Analyze(SyntaxNodeAnalysisContext context) - { - var name = (GenericNameSyntax)context.Node; - if (name.Identifier.ValueText != "IValidate") return; - if (AsynchronousTarget(context.SemanticModel.GetSymbolInfo(name, context.CancellationToken).Symbol as INamedTypeSymbol, context.Compilation) is not { } target) - { - return; - } - - context.ReportDiagnostic( - Diagnostic.Create(Diagnostics.SynchronousUseOfAsyncValidator, name.GetLocation(), target.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)) - ); - } - - /// The type an IValidate<T> is of, when that type is validated asynchronously only. - internal static INamedTypeSymbol? AsynchronousTarget(INamedTypeSymbol? type, Compilation? compilation = null) - { - if (type is not { TypeArguments: [INamedTypeSymbol target] } || !ValidationSymbols.Is(type.OriginalDefinition, ValidationSymbols.RuntimeNamespace, "IValidate")) - { - return null; - } - - var @namespace = TargetReader.NamespaceOf(target); - var prefix = @namespace.Length == 0 ? "" : @namespace + "."; - var validator = target.ContainingAssembly?.GetTypeByMetadataName(prefix + TargetReader.ValidatorName(target)); - if (validator is not null && !TargetReader.ImplementsSynchronous(validator)) return target; - - // The validator this compilation writes for a type of another assembly it adds rules to: it is the one registered for the type. - var added = compilation?.Assembly.GetTypeByMetadataName(prefix + TargetReader.ValidatorName(target, compilation.Assembly)); - return added is not null && !TargetReader.ImplementsSynchronous(added) ? target : null; - } -} diff --git a/src/Validation.Analyzers/SynchronousValidationCodeFix.cs b/src/Validation.Analyzers/SynchronousValidationCodeFix.cs deleted file mode 100644 index 92df9b9dae..0000000000 --- a/src/Validation.Analyzers/SynchronousValidationCodeFix.cs +++ /dev/null @@ -1,167 +0,0 @@ -using System.Collections.Immutable; -using System.Composition; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeActions; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Simplification; - -namespace Rocket.Surgery.LaunchPad.Validation.Analyzers; - -/// -/// Fixes LPAD3002: IValidate<T> becomes IValidateAsync<T>, and in the same document each call of its -/// Validate becomes an awaited ValidateAsync, with the cancellation token of the method it is in if that has one. The method -/// becomes asynchronous if it isn't. -/// -[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(SynchronousValidationCodeFix))] -[Shared] -public sealed class SynchronousValidationCodeFix : CodeFixProvider -{ - private const string Title = "Validate asynchronously"; - - /// - public override ImmutableArray FixableDiagnosticIds { get; } = [Diagnostics.SynchronousUseOfAsyncValidator.Id]; - - /// - public override FixAllProvider? GetFixAllProvider() => null; - - /// - public override async Task RegisterCodeFixesAsync(CodeFixContext context) - { - var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); - if (root is null) return; - foreach (var diagnostic in context.Diagnostics) - { - if (root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true) is not GenericNameSyntax name) continue; - context.RegisterCodeFix(CodeAction.Create(Title, ct => FixAsync(context.Document, name, ct), Title), diagnostic); - } - } - - private static async Task FixAsync(Document document, GenericNameSyntax name, CancellationToken cancellationToken) - { - var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); - if (root is null || model is null || model.GetSymbolInfo(name, cancellationToken).Symbol is not INamedTypeSymbol type) return document; - - // Every mention of this IValidate in the document, and every call of its Validate. - var names = new HashSet(); - var calls = new Dictionary(); - var functions = new HashSet(); - foreach (var node in root.DescendantNodes()) - { - switch (node) - { - case GenericNameSyntax { Identifier.ValueText: "IValidate" } other - when SymbolEqualityComparer.Default.Equals(model.GetSymbolInfo(other, cancellationToken).Symbol, type): - names.Add(other); - break; - case InvocationExpressionSyntax { Expression: MemberAccessExpressionSyntax { Name.Identifier.ValueText: "Validate" } } call - when model.GetSymbolInfo(call, cancellationToken).Symbol is IMethodSymbol method - && SymbolEqualityComparer.Default.Equals(method.ContainingType, type): - var function = FunctionOf(call); - calls.Add(call, function is null ? null : Token(function, model, cancellationToken)); - if (function is not null) functions.Add(function); - break; - default: - break; - } - } - - var rewritten = new Rewriter(names, calls, functions, model, cancellationToken).Visit(root); - return document.WithSyntaxRoot(rewritten); - } - - private static SyntaxNode? FunctionOf(SyntaxNode node) => - node.Ancestors().FirstOrDefault(static z => z is BaseMethodDeclarationSyntax or LocalFunctionStatementSyntax or AnonymousFunctionExpressionSyntax); - - // The cancellation token a function takes, by name. - private static string? Token(SyntaxNode function, SemanticModel model, CancellationToken cancellationToken) - { - var symbol = function is AnonymousFunctionExpressionSyntax - ? model.GetSymbolInfo(function, cancellationToken).Symbol as IMethodSymbol - : model.GetDeclaredSymbol(function, cancellationToken) as IMethodSymbol; - return symbol - ?.Parameters.FirstOrDefault(static z => z.Type is { Name: "CancellationToken", ContainingNamespace: { Name: "Threading", ContainingNamespace.Name: "System" } }) - ?.Name; - } - - private sealed class Rewriter( - HashSet names, - Dictionary calls, - HashSet functions, - SemanticModel model, - CancellationToken cancellationToken - ) : CSharpSyntaxRewriter - { - public override SyntaxNode? VisitGenericName(GenericNameSyntax node) - { - var visited = (GenericNameSyntax)base.VisitGenericName(node)!; - return names.Contains(node) ? visited.WithIdentifier(SyntaxFactory.Identifier("IValidateAsync").WithTriviaFrom(visited.Identifier)) : visited; - } - - public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node) - { - var visited = (InvocationExpressionSyntax)base.VisitInvocationExpression(node)!; - if (!calls.TryGetValue(node, out var token)) return visited; - - var access = (MemberAccessExpressionSyntax)visited.Expression; - var arguments = visited.ArgumentList; - if (token is not null) arguments = arguments.AddArguments(SyntaxFactory.Argument(SyntaxFactory.IdentifierName(token))); - ExpressionSyntax awaited = SyntaxFactory.AwaitExpression( - SyntaxFactory.Token(SyntaxKind.AwaitKeyword).WithTrailingTrivia(SyntaxFactory.Space), - visited.WithExpression(access.WithName(SyntaxFactory.IdentifierName("ValidateAsync"))).WithArgumentList(arguments).WithoutLeadingTrivia() - ); - // The result of the call is used: validator.Validate(x).IsValid. - if (node.Parent is MemberAccessExpressionSyntax or ConditionalAccessExpressionSyntax) awaited = SyntaxFactory.ParenthesizedExpression(awaited); - return awaited.WithLeadingTrivia(visited.GetLeadingTrivia()); - } - - public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node) - { - var visited = (MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!; - return !functions.Contains(node) || visited.Modifiers.Any(SyntaxKind.AsyncKeyword) - ? visited - : visited - .WithReturnType(Returns(node.ReturnType, visited.ReturnType)) - .WithModifiers(visited.Modifiers.Add(SyntaxFactory.Token(SyntaxKind.AsyncKeyword).WithTrailingTrivia(SyntaxFactory.Space))); - } - - public override SyntaxNode? VisitLocalFunctionStatement(LocalFunctionStatementSyntax node) - { - var visited = (LocalFunctionStatementSyntax)base.VisitLocalFunctionStatement(node)!; - return !functions.Contains(node) || visited.Modifiers.Any(SyntaxKind.AsyncKeyword) - ? visited - : visited - .WithReturnType(Returns(node.ReturnType, visited.ReturnType).WithoutLeadingTrivia()) - .WithModifiers(visited.Modifiers.Add(SyntaxFactory.Token(SyntaxKind.AsyncKeyword).WithLeadingTrivia(visited.ReturnType.GetLeadingTrivia()).WithTrailingTrivia(SyntaxFactory.Space))); - } - - public override SyntaxNode? VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) - { - var visited = (ParenthesizedLambdaExpressionSyntax)base.VisitParenthesizedLambdaExpression(node)!; - return !functions.Contains(node) || visited.AsyncKeyword.IsKind(SyntaxKind.AsyncKeyword) - ? visited - : visited.WithAsyncKeyword(SyntaxFactory.Token(SyntaxKind.AsyncKeyword).WithTrailingTrivia(SyntaxFactory.Space)).WithLeadingTrivia(visited.GetLeadingTrivia()); - } - - public override SyntaxNode? VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) - { - var visited = (SimpleLambdaExpressionSyntax)base.VisitSimpleLambdaExpression(node)!; - return !functions.Contains(node) || visited.AsyncKeyword.IsKind(SyntaxKind.AsyncKeyword) - ? visited - : visited.WithAsyncKeyword(SyntaxFactory.Token(SyntaxKind.AsyncKeyword).WithTrailingTrivia(SyntaxFactory.Space)).WithLeadingTrivia(visited.GetLeadingTrivia()); - } - - // void becomes Task, a task stays as it is, anything else becomes a Task of it. - private TypeSyntax Returns(TypeSyntax original, TypeSyntax visited) - { - var type = model.GetTypeInfo(original, cancellationToken).Type; - if (type is { Name: "Task" or "ValueTask", ContainingNamespace: { Name: "Tasks", ContainingNamespace.Name: "Threading" } }) return visited; - var task = type is null or { SpecialType: SpecialType.System_Void } - ? SyntaxFactory.ParseTypeName("global::System.Threading.Tasks.Task") - : SyntaxFactory.ParseTypeName("global::System.Threading.Tasks.Task<" + visited.WithoutTrivia() + ">"); - return task.WithAdditionalAnnotations(Simplifier.Annotation).WithTriviaFrom(visited); - } - } -} diff --git a/src/Validation.Analyzers/ValidatorEmitter.cs b/src/Validation.Analyzers/ValidatorEmitter.cs index eba4fa68b3..14f0d48ca4 100644 --- a/src/Validation.Analyzers/ValidatorEmitter.cs +++ b/src/Validation.Analyzers/ValidatorEmitter.cs @@ -15,8 +15,8 @@ internal static class ValidatorEmitter private const string Token = "global::System.Threading.CancellationToken"; private const string ValueTask = "global::System.Threading.Tasks.ValueTask"; - // A validator the generated one asks the service provider for: the type it is asked as, and whether it is awaited. - private sealed record NestedValidator(string Service, string Property, bool IsAsync); + // A validator the generated one asks the service provider for, and the type it is asked as. + private sealed record NestedValidator(string Service, string Property); // What the validator being written is given, and how its code names it. private sealed class Context(MergedModel model) @@ -54,10 +54,10 @@ public string Add(string type, string name) /// What a rule method of another validator is called on. public string Receiver(CarriedCall call) => call.Member.IsStatic ? call.Source.Validator : Sources[call.Source.Validator]; - public NestedValidator NestedFor(string member, NestedModel how, bool awaited) + public NestedValidator NestedFor(string member, NestedModel how) { - var service = how.Validator ?? Runtime + ( awaited ? ".IValidateAsync<" : ".IValidate<" ) + how.Target + ">"; - if (!Nested.TryGetValue(service, out var validator)) Nested.Add(service, validator = new(service, member + "Validator", awaited)); + var service = how.Validator ?? Runtime + ".IValidator<" + how.Target + ">"; + if (!Nested.TryGetValue(service, out var validator)) Nested.Add(service, validator = new(service, member + "Validator")); return validator; } } @@ -116,19 +116,15 @@ public static string Validator(MergedModel model, CompilationModel compilation) // One validator for each type validated, whichever members are of it: named after the first. foreach (var member in model.Resolved) { - if (member.Nested is { } how) context.NestedFor(member.Name, how, member.NestedAwaited); + if (member.Nested is { } how) context.NestedFor(member.Name, how); } NestedValidator? whole = null; - if (model.Mutable is { } mutable) - { - var awaited = model.MutableTarget?.IsAsync ?? mutable.IsKnownAsync; - whole = context.NestedFor("MutableTarget", new(mutable.Type, null, awaited, false, false, false), awaited); - } + if (model.Mutable is { } mutable) whole = context.NestedFor("MutableTarget", new(mutable.Type, null, false, false, false)); var nested = context.Nested; var fields = context.Fields; - var interfaces = $"{Runtime}.{( isAsync ? "IValidateAsync" : "IValidate" )}<{target.Type}>, {Runtime}.IValidateMembers<{target.Type}>" + var interfaces = $"{Runtime}.IValidator<{target.Type}>, {Runtime}.IValidateMembers<{target.Type}>" + ( options ? $", global::Microsoft.Extensions.Options.IValidateOptions<{target.Type}>" : "" ); Line("/// "); @@ -193,12 +189,38 @@ public static string Validator(MergedModel model, CompilationModel compilation) // The whole value: the rules of what the type is, then its own. Line(); - Line(" /// "); - Line( - isAsync - ? $" public async {ValueTask}<{Result}> ValidateAsync({target.Type} value, {Token} cancellationToken = default)" - : $" public {Result} Validate({target.Type} value)" - ); + if (isAsync) + { + Line(" /// "); + Line($" public async {ValueTask}<{Result}> ValidateAsync({target.Type} value, {Token} cancellationToken = default)"); + } + else + { + // None of the rules waits: the answer is there when the method returns, and a rule that throws faults the task it returns. + Line(" /// "); + Line($" public {ValueTask}<{Result}> ValidateAsync({target.Type} value, {Token} cancellationToken = default)"); + Line(" {"); + if (target.IsReferenceType) Line(" global::System.ArgumentNullException.ThrowIfNull(value);"); + Line($" if (cancellationToken.IsCancellationRequested) return {ValueTask}.FromCanceled<{Result}>(cancellationToken);"); + Line(" try"); + Line(" {"); + Line(" return new(Validate(value));"); + Line(" }"); + Line(" catch (global::System.Exception exception)"); + Line(" {"); + Line($" return {ValueTask}.FromException<{Result}>(exception);"); + Line(" }"); + Line(" }"); + Line(); + Line(" /// "); + Line(" /// Validates a value without waiting: none of the type's rules waits."); + Line(" /// "); + Line(" /// The value."); + Line(" /// The rules the value did not meet."); + Line(" " + Never); + Line($" public {Result} Validate({target.Type} value)"); + } + Line(" {"); if (target.IsReferenceType) Line(" global::System.ArgumentNullException.ThrowIfNull(value);"); Line($" var sink = new {Sink}(_messages);"); @@ -213,11 +235,7 @@ public static string Validator(MergedModel model, CompilationModel compilation) if (whole is not null) { - Line( - whole.IsAsync - ? $" sink.Add(await {whole.Property}.ValidateAsync(value.ToImmutable(), cancellationToken).ConfigureAwait(false));" - : $" sink.Add({whole.Property}.Validate(value.ToImmutable()));" - ); + Line($" sink.Add(await {whole.Property}.ValidateAsync(value.ToImmutable(), cancellationToken).ConfigureAwait(false));"); } if (model.Resolved.Count > 0) @@ -557,7 +575,7 @@ void Separate() if (member.Nested is { } how) { Separate(); - WriteNested(member.Name, how, context.NestedFor(member.Name, how, member.NestedAwaited), line); + WriteNested(member.Name, how, context.NestedFor(member.Name, how), line); } if (member.IsAsync) line(" return sink;"); @@ -567,10 +585,7 @@ void Separate() private static void WriteNested(string member, NestedModel nested, NestedValidator validator, Action line) { var name = Literal(member); - string Call(string value) => - validator.IsAsync - ? $"sink.Add(await {validator.Property}.ValidateAsync({value}, cancellationToken).ConfigureAwait(false));" - : $"sink.Add({validator.Property}.Validate({value}));"; + string Call(string value) => $"sink.Add(await {validator.Property}.ValidateAsync({value}, cancellationToken).ConfigureAwait(false));"; var present = "value"; var indent = " "; @@ -739,7 +754,7 @@ public static string Registration(IReadOnlyList models, Compilation sb.AppendLine(" {"); sb.AppendLine(" /// "); sb.AppendLine($" /// Adds the validators of {compilation.AssemblyName}, and those of the assemblies it references, each as the"); - sb.AppendLine(" /// IValidateAsync of the type it validates, as its IValidate unless one of the type's rules waits, and as its"); + sb.AppendLine(" /// IValidator of the type it validates and as its"); sb.AppendLine(" /// IValidateMembers. A validator whose rules take services is scoped; the others are singletons. Where this assembly"); sb.AppendLine(" /// adds rules to a type of another, its validator, which runs that assembly's too, replaces the one registered for the type."); sb.AppendLine(" /// "); @@ -773,8 +788,7 @@ public static string Registration(IReadOnlyList models, Compilation if (target.IsForeign) { // The validators this one runs are no longer the type's validators, nor what validates it as options. - sb.AppendLine($" {extensions}.RemoveAll<{Runtime}.IValidate<{target.Type}>>(services);"); - sb.AppendLine($" {extensions}.RemoveAll<{Runtime}.IValidateAsync<{target.Type}>>(services);"); + sb.AppendLine($" {extensions}.RemoveAll<{Runtime}.IValidator<{target.Type}>>(services);"); sb.AppendLine($" {extensions}.RemoveAll<{Runtime}.IValidateMembers<{target.Type}>>(services);"); if (compilation.HasOptions && target.IsReferenceType) { @@ -786,17 +800,9 @@ public static string Registration(IReadOnlyList models, Compilation } } - if (model.IsAsync) - { - sb.AppendLine($" {extensions}.TryAdd{lifetime}<{Runtime}.IValidateAsync<{target.Type}>, {validator}>(services);"); - } - else - { - sb.AppendLine($" {extensions}.TryAdd{lifetime}<{Runtime}.IValidate<{target.Type}>, {validator}>(services);"); - sb.AppendLine($" {extensions}.TryAdd{lifetime}<{Runtime}.IValidateAsync<{target.Type}>>(services, static provider => ({Runtime}.IValidate<{target.Type}>)provider.GetService(typeof({Runtime}.IValidate<{target.Type}>))!);"); - } + sb.AppendLine($" {extensions}.TryAdd{lifetime}<{Runtime}.IValidator<{target.Type}>, {validator}>(services);"); - sb.AppendLine($" {extensions}.TryAdd{lifetime}<{Runtime}.IValidateMembers<{target.Type}>>(services, static provider => ({Runtime}.IValidateMembers<{target.Type}>)provider.GetService(typeof({Runtime}.IValidateAsync<{target.Type}>))!);"); + sb.AppendLine($" {extensions}.TryAdd{lifetime}<{Runtime}.IValidateMembers<{target.Type}>>(services, static provider => ({Runtime}.IValidateMembers<{target.Type}>)provider.GetService(typeof({Runtime}.IValidator<{target.Type}>))!);"); sb.AppendLine($" global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, {validator}.Manifest);"); sb.AppendLine($" {extensions}.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton<{Runtime}.ObjectValidator, {Runtime}.ObjectValidator<{target.Type}>>());"); if (!model.IsAsync && compilation.HasOptions && target.IsReferenceType && !model.IsScoped) diff --git a/src/Validation.Blazor/LaunchPadValidator.cs b/src/Validation.Blazor/LaunchPadValidator.cs index 1a37c52aff..daa371a65b 100644 --- a/src/Validation.Blazor/LaunchPadValidator.cs +++ b/src/Validation.Blazor/LaunchPadValidator.cs @@ -18,9 +18,9 @@ namespace Rocket.Surgery.LaunchPad.AspNetCore.Blazor; /// of a [Mutable] type is validated this way with the rules of the type it is of, without making one. /// /// -/// The whole model is validated when the form asks. , which a form's submit uses, -/// awaits the rules that wait. can't: for a model with such a rule the form throws, as it -/// does for any asynchronous validator. +/// The whole model is validated when the form asks with , which a form's submit +/// uses. , which is obsolete, can't wait: with this validator the form throws, as it does +/// for any asynchronous validator. /// /// /// The validator is found by the model's type among those the generated Add...Validators methods registered @@ -77,13 +77,8 @@ private void OnValidationRequested(object? sender, ValidationRequestedEventArgs { var context = _editContext!; var validator = Validator(context); - if (validator.TryValidate(Services, context.Model, out var result)) - { - Report(context, result); - return; - } - // A rule of the model waits. The form awaits it in ValidateAsync, and refuses it in Validate, as it does any asynchronous validator. + // Validation is asynchronous: the form awaits it in ValidateAsync, and refuses it in Validate, as it does any asynchronous validator. e.AddAsyncValidator(cancellationToken => ValidateModel(context, validator, cancellationToken)); } diff --git a/src/Validation/IValidate.cs b/src/Validation/IValidate.cs deleted file mode 100644 index 48222313b2..0000000000 --- a/src/Validation/IValidate.cs +++ /dev/null @@ -1,39 +0,0 @@ -namespace Rocket.Surgery.LaunchPad.Validation; - -/// -/// Validates a . The generator writes one for every type that has rules; it is what an application injects and calls. -/// -/// -/// Every validated type has one. A type whose rules are all synchronous has an as well. -/// -/// The type validated. -[PublicAPI] -public interface IValidateAsync -{ - /// - /// Validates a value. - /// - /// The value. - /// A token that cancels the rules that wait. - /// The rules the value did not meet. - ValueTask ValidateAsync(T value, CancellationToken cancellationToken = default); -} - -/// -/// Validates a synchronously. Only a type with no asynchronous rule has one: asking for the -/// of a type that has an asynchronous rule is a build error. -/// -/// The type validated. -[PublicAPI] -public interface IValidate : IValidateAsync -{ - /// - /// Validates a value. - /// - /// The value. - /// The rules the value did not meet. - ValidationResult Validate(T value); - - /// - ValueTask IValidateAsync.ValidateAsync(T value, CancellationToken cancellationToken) => new(Validate(value)); -} diff --git a/src/Validation/IValidationBuilder.cs b/src/Validation/IValidationBuilder.cs index 91df25ffa0..9caf0af4ae 100644 --- a/src/Validation/IValidationBuilder.cs +++ b/src/Validation/IValidationBuilder.cs @@ -1,7 +1,7 @@ namespace Rocket.Surgery.LaunchPad.Validation; /// -/// Declares the rules of in a Validate function or an . Nothing implements it: +/// Declares the rules of in a Validate function or an . Nothing implements it: /// the generator reads the calls made on it and writes the checks they describe. /// /// The type the rules are for. @@ -150,5 +150,5 @@ public interface IMemberRules /// The validator. /// The rules of the member. IMemberRules ValidateWith() - where TValidator : IValidateAsync; + where TValidator : IValidator; } diff --git a/src/Validation/IValidator.cs b/src/Validation/IValidator.cs index ebe20bb044..cba3f8a654 100644 --- a/src/Validation/IValidator.cs +++ b/src/Validation/IValidator.cs @@ -1,21 +1,21 @@ namespace Rocket.Surgery.LaunchPad.Validation; /// -/// A class that declares rules for . Its dependencies are its constructor's parameters, and its -/// is read by the generator at build time and never called: the rules it declares are written into the generated -/// of , with every other rule the type has. +/// Validates a . The generator writes one for every type that has rules; it is what an application injects and calls. /// /// -/// The class must be . A function does the same with less: a method named -/// Validate whose first parameter is an and whose other parameters are its dependencies. +/// Validation is asynchronous, as a rule may wait (MustAsync). The validator of a type none of whose rules waits answers at +/// once, with a completed . /// -/// The type the rules are for: a type to validate, or a base class or interface whose rules apply to everything under it. +/// The type validated. [PublicAPI] -public interface IValidator +public interface IValidator { /// - /// Declares the rules. The body may only call the builder. + /// Validates a value. /// - /// The builder. - void Validate(IValidationBuilder v); + /// The value. + /// A token that cancels the rules that wait. + /// The rules the value did not meet. + ValueTask ValidateAsync(T value, CancellationToken cancellationToken = default); } diff --git a/src/Validation/IValidatorDefinition.cs b/src/Validation/IValidatorDefinition.cs new file mode 100644 index 0000000000..7cd4a42345 --- /dev/null +++ b/src/Validation/IValidatorDefinition.cs @@ -0,0 +1,21 @@ +namespace Rocket.Surgery.LaunchPad.Validation; + +/// +/// A class that declares rules for . Its dependencies are its constructor's parameters, and its +/// is read by the generator at build time and never called: the rules it declares are written into the generated +/// of , with every other rule the type has. +/// +/// +/// The class must be . A function does the same with less: a method named +/// Validate whose first parameter is an and whose other parameters are its dependencies. +/// +/// The type the rules are for: a type to validate, or a base class or interface whose rules apply to everything under it. +[PublicAPI] +public interface IValidatorDefinition +{ + /// + /// Declares the rules. The body may only call the builder. + /// + /// The builder. + void Validate(IValidationBuilder v); +} diff --git a/src/Validation/ObjectValidator.cs b/src/Validation/ObjectValidator.cs index 7a6f2714c0..ea0ef94bc5 100644 --- a/src/Validation/ObjectValidator.cs +++ b/src/Validation/ObjectValidator.cs @@ -22,15 +22,6 @@ public abstract class ObjectValidator /// The rules the value did not meet. public abstract ValueTask ValidateAsync(IServiceProvider services, object value, CancellationToken cancellationToken = default); - /// - /// Validates a value, if none of the type's rules waits. - /// - /// Where the type's validator is found. - /// The value, of . - /// The rules the value did not meet, when the method returns . - /// when the type is validated asynchronously only: validate it with . - public abstract bool TryValidate(IServiceProvider services, object value, out ValidationResult result); - /// /// Validates one member of a value, if none of its rules waits. /// @@ -54,7 +45,7 @@ public abstract class ObjectValidator /// /// The of a : it asks the services for the type's -/// and . +/// and . /// /// The type validated. [PublicAPI] @@ -65,23 +56,7 @@ public sealed class ObjectValidator : ObjectValidator /// public override ValueTask ValidateAsync(IServiceProvider services, object value, CancellationToken cancellationToken = default) => - Get>(services).ValidateAsync((T)value, cancellationToken); - - /// - public override bool TryValidate(IServiceProvider services, object value, out ValidationResult result) - { - ArgumentNullException.ThrowIfNull(services); -#pragma warning disable LPAD3002 // asked for at run time, for any T: a type with a rule that waits has none, which is the answer - if (services.GetService(typeof(IValidate)) is IValidate validator) -#pragma warning restore LPAD3002 - { - result = validator.Validate((T)value); - return true; - } - - result = default; - return false; - } + Get>(services).ValidateAsync((T)value, cancellationToken); /// public override bool TryValidateMember(IServiceProvider services, object value, string member, out ValidationResult result) => diff --git a/test/Sdk.Tests/SdkValidationTests.cs b/test/Sdk.Tests/SdkValidationTests.cs index 06f8ea27fc..6dcc2b7815 100644 --- a/test/Sdk.Tests/SdkValidationTests.cs +++ b/test/Sdk.Tests/SdkValidationTests.cs @@ -167,15 +167,15 @@ public sealed class Parcel using var services = new ServiceCollection().AddSingleton().AddappValidators().BuildServiceProvider(true); using var scope = services.CreateScope(); - Report(new Car { Wheels = 0, Plate = "", Name = "", Doors = 9, }); - Report(new Car { Name = "Mini", }); - Report(new ShippingAddress { City = "", PostCode = "10001", Recipient = "", }); - Report(new ShippingAddress { City = "Portland", PostCode = "97201", Recipient = "Ada", }); - Report(new Parcel { Weight = 0, Label = "", }); - Console.WriteLine($"Validators of Parcel: {services.GetServices>().Count()}"); - - void Report(T value) where T : notnull => - Console.WriteLine($"{typeof(T).Name}: {string.Join(", ", scope.ServiceProvider.GetRequiredService>().Validate(value).Failures.Select(z => z.Path + ":" + z.Code))}"); + await Report(new Car { Wheels = 0, Plate = "", Name = "", Doors = 9, }); + await Report(new Car { Name = "Mini", }); + await Report(new ShippingAddress { City = "", PostCode = "10001", Recipient = "", }); + await Report(new ShippingAddress { City = "Portland", PostCode = "97201", Recipient = "Ada", }); + await Report(new Parcel { Weight = 0, Label = "", }); + Console.WriteLine($"Validators of Parcel: {services.GetServices>().Count()}"); + + async System.Threading.Tasks.Task Report(T value) where T : notnull => + Console.WriteLine($"{typeof(T).Name}: {string.Join(", ", (await scope.ServiceProvider.GetRequiredService>().ValidateAsync(value)).Failures.Select(z => z.Path + ":" + z.Code))}"); public sealed class PostCodes : IPostCodes { diff --git a/test/Validation.Analyzers.Tests/CompositionGeneratorTests.cs b/test/Validation.Analyzers.Tests/CompositionGeneratorTests.cs index 0ddeea288a..ad972c7596 100644 --- a/test/Validation.Analyzers.Tests/CompositionGeneratorTests.cs +++ b/test/Validation.Analyzers.Tests/CompositionGeneratorTests.cs @@ -338,7 +338,7 @@ public static partial class Rules // The application's rules for a type the library has rules for too: its validator runs both. private static void Validate(IValidationBuilder v) => v.Ensure(x => x.Label).NotEmpty(); - // LPAD3113: the library validates Address synchronously, and code may already ask for its IValidate. + // A rule that waits, added to a type whose own rules do not. private static void Validate(IValidationBuilder
v) => v.Ensure(x => x.City).MustAsync(async (city, cancellationToken) => { await Task.Yield(); return city != "Atlantis"; }); } diff --git a/test/Validation.Analyzers.Tests/FunctionValidatorGeneratorTests.cs b/test/Validation.Analyzers.Tests/FunctionValidatorGeneratorTests.cs index e9ad859817..ad2f5eff37 100644 --- a/test/Validation.Analyzers.Tests/FunctionValidatorGeneratorTests.cs +++ b/test/Validation.Analyzers.Tests/FunctionValidatorGeneratorTests.cs @@ -109,7 +109,7 @@ internal interface ICatalog public sealed record Booking(string Serial, string? Pad); - internal sealed partial class BookingValidator(ICatalog catalog) : IValidator + internal sealed partial class BookingValidator(ICatalog catalog) : IValidatorDefinition { public void Validate(IValidationBuilder v) { diff --git a/test/Validation.Analyzers.Tests/SynchronousValidationAnalyzerTests.cs b/test/Validation.Analyzers.Tests/SynchronousValidationAnalyzerTests.cs deleted file mode 100644 index 6da37bd332..0000000000 --- a/test/Validation.Analyzers.Tests/SynchronousValidationAnalyzerTests.cs +++ /dev/null @@ -1,53 +0,0 @@ -using Rocket.Surgery.LaunchPad.Validation.Analyzers; - -namespace Validation.Analyzers.Tests; - -public class SynchronousValidationAnalyzerTests -{ - [Test] - public async Task Should_Report_The_Synchronous_Validator_Of_An_Asynchronous_Type_And_Make_Its_Use_Asynchronous() - { - var result = await TestBuilder.GenerateAndFix( - """ - using System; - using System.Threading; - using System.Threading.Tasks; - using Rocket.Surgery.LaunchPad.Validation; - using Rocket.Surgery.LaunchPad.Validation.Rules; - - namespace Sample; - - public sealed record Booking(string Serial); - - public sealed record Pad([NotEmpty] string Name); - - public static partial class Rules - { - private static void Validate(IValidationBuilder v) => v.Ensure(x => x.Serial).MustAsync((_, _) => new ValueTask(true)); - } - - public sealed class Handler(IValidate validator, IValidate pads) - { - public bool Check(Booking booking, CancellationToken cancellationToken) - { - // Pad has no asynchronous rule: this stays as it is. - if (!pads.Validate(new("LC-39A")).IsValid) return false; - return validator.Validate(booking).IsValid; - } - - public void Report(Booking booking) - { - var result = validator.Validate(booking); - Console.WriteLine(result.IsValid); - } - - public Task Already(Booking booking) => Task.FromResult(validator.Validate(booking)); - - public Func Later() => booking => validator.Validate(booking).IsValid; - } - """ - ); - - await Verify(await TestBuilder.Describe(result)).DontIgnoreEmptyCollections(); - } -} diff --git a/test/Validation.Analyzers.Tests/TestBuilder.cs b/test/Validation.Analyzers.Tests/TestBuilder.cs index ee6d70c41c..16bbf8d45c 100644 --- a/test/Validation.Analyzers.Tests/TestBuilder.cs +++ b/test/Validation.Analyzers.Tests/TestBuilder.cs @@ -27,7 +27,7 @@ public static GeneratorTestContextBuilder Create(bool services = false) .Create() .WithProjectName("Application") .WithLanguageVersion(LanguageVersion.Preview) - .AddReferences(typeof(IValidate<>).Assembly) + .AddReferences(typeof(IValidator<>).Assembly) .AddReferences(Framework); return services ? builder.AddReferences(typeof(IServiceCollection).Assembly, typeof(IValidateOptions<>).Assembly) : builder; } diff --git a/test/Validation.Analyzers.Tests/ValidatorGeneratorTests.cs b/test/Validation.Analyzers.Tests/ValidatorGeneratorTests.cs index 45dc726473..11b25d3263 100644 --- a/test/Validation.Analyzers.Tests/ValidatorGeneratorTests.cs +++ b/test/Validation.Analyzers.Tests/ValidatorGeneratorTests.cs @@ -178,9 +178,10 @@ public sealed class Launcher public Crew? Ground { get; set; } } - public sealed class StrictCrew : IValidate + public sealed class StrictCrew : IValidator { - public ValidationResult Validate(Crew value) => ValidationResult.Valid; + public System.Threading.Tasks.ValueTask ValidateAsync(Crew value, System.Threading.CancellationToken cancellationToken = default) => + new(ValidationResult.Valid); } """ ); diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#LaunchPadValidators.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#LaunchPadValidators.g.verified.cs index e06580b566..6cc4c819d2 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#LaunchPadValidators.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#LaunchPadValidators.g.verified.cs @@ -13,7 +13,7 @@ public static class ApplicationValidatorsServiceCollectionExtensions { /// /// Adds the validators of Application, and those of the assemblies it references, each as the - /// IValidateAsync of the type it validates, as its IValidate unless one of the type's rules waits, and as its + /// IValidator of the type it validates and as its /// IValidateMembers. A validator whose rules take services is scoped; the others are singletons. Where this assembly /// adds rules to a type of another, its validator, which runs that assembly's too, replaces the one registered for the type. /// @@ -22,20 +22,18 @@ public static class ApplicationValidatorsServiceCollectionExtensions public static global::Microsoft.Extensions.DependencyInjection.IServiceCollection AddApplicationValidators(this global::Microsoft.Extensions.DependencyInjection.IServiceCollection services) { global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.AddressGeneratedValidator>(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.AddressGeneratedValidator>(services); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator))!); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.AddressGeneratedValidator.Manifest); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.DraftGeneratedValidator>(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.DraftGeneratedValidator>(services); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator))!); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.DraftGeneratedValidator.Manifest); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton, global::Sample.DraftGeneratedValidator>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.ShippingAddressGeneratedValidator>(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.ShippingAddressGeneratedValidator>(services); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator))!); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.ShippingAddressGeneratedValidator.Manifest); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); return services; diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#Sample.AddressGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#Sample.AddressGeneratedValidator.g.verified.cs index e303421579..51edce74dc 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#Sample.AddressGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#Sample.AddressGeneratedValidator.g.verified.cs @@ -11,7 +11,7 @@ namespace Sample ///
[global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Address))] public sealed class AddressGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidate, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { private readonly global::Sample.IPostCodes _postCodes; private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -28,6 +28,26 @@ public AddressGeneratedValidator(global::Sample.IPostCodes postCodes, global::Ro } /// + public global::System.Threading.Tasks.ValueTask ValidateAsync(global::Sample.Address value, global::System.Threading.CancellationToken cancellationToken = default) + { + global::System.ArgumentNullException.ThrowIfNull(value); + if (cancellationToken.IsCancellationRequested) return global::System.Threading.Tasks.ValueTask.FromCanceled(cancellationToken); + try + { + return new(Validate(value)); + } + catch (global::System.Exception exception) + { + return global::System.Threading.Tasks.ValueTask.FromException(exception); + } + } + + /// + /// Validates a value without waiting: none of the type's rules waits. + /// + /// The value. + /// The rules the value did not meet. + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Address value) { global::System.ArgumentNullException.ThrowIfNull(value); diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#Sample.DraftGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#Sample.DraftGeneratedValidator.g.verified.cs index 2bf61b95f0..7cf071006b 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#Sample.DraftGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#Sample.DraftGeneratedValidator.g.verified.cs @@ -11,7 +11,7 @@ namespace Sample ///
[global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Draft))] public sealed class DraftGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidate, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers, global::Microsoft.Extensions.Options.IValidateOptions + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers, global::Microsoft.Extensions.Options.IValidateOptions { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -22,6 +22,26 @@ public sealed class DraftGeneratedValidator public DraftGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// + public global::System.Threading.Tasks.ValueTask ValidateAsync(global::Sample.Draft value, global::System.Threading.CancellationToken cancellationToken = default) + { + global::System.ArgumentNullException.ThrowIfNull(value); + if (cancellationToken.IsCancellationRequested) return global::System.Threading.Tasks.ValueTask.FromCanceled(cancellationToken); + try + { + return new(Validate(value)); + } + catch (global::System.Exception exception) + { + return global::System.Threading.Tasks.ValueTask.FromException(exception); + } + } + + /// + /// Validates a value without waiting: none of the type's rules waits. + /// + /// The value. + /// The rules the value did not meet. + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Draft value) { global::System.ArgumentNullException.ThrowIfNull(value); diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#Sample.ShippingAddressGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#Sample.ShippingAddressGeneratedValidator.g.verified.cs index 085cf39f94..769573e308 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#Sample.ShippingAddressGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Carry_The_Rules_Of_Copied_Members#Sample.ShippingAddressGeneratedValidator.g.verified.cs @@ -11,7 +11,7 @@ namespace Sample /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.ShippingAddress))] public sealed class ShippingAddressGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { private readonly global::Sample.IPostCodes _postCodes; private readonly global::Sample.AddressGeneratedValidator _addressGeneratedValidator; diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Contracts.AddressInApplicationGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Contracts.AddressInApplicationGeneratedValidator.g.verified.cs index e820724960..c0ac7b017b 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Contracts.AddressInApplicationGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Contracts.AddressInApplicationGeneratedValidator.g.verified.cs @@ -13,7 +13,7 @@ namespace Contracts /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Contracts.Address))] public sealed class AddressInApplicationGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { private readonly global::Contracts.AddressGeneratedValidator _addressGeneratedValidator; private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Contracts.ParcelInApplicationGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Contracts.ParcelInApplicationGeneratedValidator.g.verified.cs index 4901f2ba98..e00ea9c60f 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Contracts.ParcelInApplicationGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Contracts.ParcelInApplicationGeneratedValidator.g.verified.cs @@ -13,7 +13,7 @@ namespace Contracts /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Contracts.Parcel))] public sealed class ParcelInApplicationGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidate, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers, global::Microsoft.Extensions.Options.IValidateOptions + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers, global::Microsoft.Extensions.Options.IValidateOptions { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -24,6 +24,26 @@ public sealed class ParcelInApplicationGeneratedValidator public ParcelInApplicationGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// + public global::System.Threading.Tasks.ValueTask ValidateAsync(global::Contracts.Parcel value, global::System.Threading.CancellationToken cancellationToken = default) + { + global::System.ArgumentNullException.ThrowIfNull(value); + if (cancellationToken.IsCancellationRequested) return global::System.Threading.Tasks.ValueTask.FromCanceled(cancellationToken); + try + { + return new(Validate(value)); + } + catch (global::System.Exception exception) + { + return global::System.Threading.Tasks.ValueTask.FromException(exception); + } + } + + /// + /// Validates a value without waiting: none of the type's rules waits. + /// + /// The value. + /// The rules the value did not meet. + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Contracts.Parcel value) { global::System.ArgumentNullException.ThrowIfNull(value); diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#LaunchPadValidators.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#LaunchPadValidators.g.verified.cs index 1b15e145ab..a6b3be07f2 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#LaunchPadValidators.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#LaunchPadValidators.g.verified.cs @@ -13,7 +13,7 @@ public static class ApplicationValidatorsServiceCollectionExtensions { /// /// Adds the validators of Application, and those of the assemblies it references, each as the - /// IValidateAsync of the type it validates, as its IValidate unless one of the type's rules waits, and as its + /// IValidator of the type it validates and as its /// IValidateMembers. A validator whose rules take services is scoped; the others are singletons. Where this assembly /// adds rules to a type of another, its validator, which runs that assembly's too, replaces the one registered for the type. /// @@ -24,45 +24,41 @@ public static class ApplicationValidatorsServiceCollectionExtensions global::Microsoft.Extensions.DependencyInjection.ContractsValidatorsServiceCollectionExtensions.AddContractsValidators(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.RemoveAll>(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.RemoveAll>(services); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.RemoveAll>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.RemoveAll>(services); for (var i = services.Count - 1; i >= 0; i--) { if (services[i].ServiceType == typeof(global::Microsoft.Extensions.Options.IValidateOptions)) services.RemoveAt(i); } - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Contracts.AddressInApplicationGeneratedValidator>(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Contracts.AddressInApplicationGeneratedValidator>(services); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator))!); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Contracts.AddressInApplicationGeneratedValidator.Manifest); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.RemoveAll>(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.RemoveAll>(services); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.RemoveAll>(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.RemoveAll>(services); for (var i = services.Count - 1; i >= 0; i--) { if (services[i].ServiceType == typeof(global::Microsoft.Extensions.Options.IValidateOptions)) services.RemoveAt(i); } - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Contracts.ParcelInApplicationGeneratedValidator>(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Contracts.ParcelInApplicationGeneratedValidator>(services); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator))!); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Contracts.ParcelInApplicationGeneratedValidator.Manifest); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton, global::Contracts.ParcelInApplicationGeneratedValidator>()); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.CarGeneratedValidator>(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.CarGeneratedValidator>(services); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator))!); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.CarGeneratedValidator.Manifest); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton, global::Sample.CarGeneratedValidator>()); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.HoldGeneratedValidator>(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.HoldGeneratedValidator>(services); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator))!); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.HoldGeneratedValidator.Manifest); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.ShippingAddressGeneratedValidator>(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.ShippingAddressGeneratedValidator>(services); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator))!); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.ShippingAddressGeneratedValidator.Manifest); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); return services; diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Sample.CarGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Sample.CarGeneratedValidator.g.verified.cs index d135ee31e5..a74006e345 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Sample.CarGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Sample.CarGeneratedValidator.g.verified.cs @@ -11,7 +11,7 @@ namespace Sample /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Car))] public sealed class CarGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidate, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers, global::Microsoft.Extensions.Options.IValidateOptions + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers, global::Microsoft.Extensions.Options.IValidateOptions { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -22,6 +22,26 @@ public sealed class CarGeneratedValidator public CarGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// + public global::System.Threading.Tasks.ValueTask ValidateAsync(global::Sample.Car value, global::System.Threading.CancellationToken cancellationToken = default) + { + global::System.ArgumentNullException.ThrowIfNull(value); + if (cancellationToken.IsCancellationRequested) return global::System.Threading.Tasks.ValueTask.FromCanceled(cancellationToken); + try + { + return new(Validate(value)); + } + catch (global::System.Exception exception) + { + return global::System.Threading.Tasks.ValueTask.FromException(exception); + } + } + + /// + /// Validates a value without waiting: none of the type's rules waits. + /// + /// The value. + /// The rules the value did not meet. + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Car value) { global::System.ArgumentNullException.ThrowIfNull(value); diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Sample.HoldGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Sample.HoldGeneratedValidator.g.verified.cs index 715de6a5d7..db98a3abce 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Sample.HoldGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Sample.HoldGeneratedValidator.g.verified.cs @@ -11,7 +11,7 @@ namespace Sample /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Hold))] public sealed class HoldGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Sample.ShippingAddressGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Sample.ShippingAddressGeneratedValidator.g.verified.cs index 19e00f0f3b..eb877d867e 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Sample.ShippingAddressGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly#Sample.ShippingAddressGeneratedValidator.g.verified.cs @@ -11,7 +11,7 @@ namespace Sample /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.ShippingAddress))] public sealed class ShippingAddressGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { private readonly global::Contracts.AddressGeneratedValidator _addressGeneratedValidator; private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly.verified.txt b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly.verified.txt index 642b70f242..b814e7ed8e 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly.verified.txt +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Read_The_Rules_Of_A_Referenced_Assembly.verified.txt @@ -1,28 +1,6 @@ { - FinalDiagnostics: [ - { - Id: LPAD3113, - Title: The type is validated synchronously by the assembly that declares it, - Severity: Error, - WarningLevel: 0, - Location: Input0.cs: (38,24)-(38,32), - MessageFormat: '{0}' has an IValidate in the assembly that declares it, which code may already use: a rule added to it here can't be asynchronous, - Message: 'Contracts.Address' has an IValidate in the assembly that declares it, which code may already use: a rule added to it here can't be asynchronous, - Category: LaunchPad.Validation - } - ], + FinalDiagnostics: [], GeneratorDiagnostics: { - Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator: [ - { - Id: LPAD3113, - Title: The type is validated synchronously by the assembly that declares it, - Severity: Error, - WarningLevel: 0, - Location: Input0.cs: (38,24)-(38,32), - MessageFormat: '{0}' has an IValidate in the assembly that declares it, which code may already use: a rule added to it here can't be asynchronous, - Message: 'Contracts.Address' has an IValidate in the assembly that declares it, which code may already use: a rule added to it here can't be asynchronous, - Category: LaunchPad.Validation - } - ] + Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator: [] } } \ No newline at end of file diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#LaunchPadValidators.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#LaunchPadValidators.g.verified.cs index 3894af0974..81a6e8037e 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#LaunchPadValidators.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#LaunchPadValidators.g.verified.cs @@ -13,7 +13,7 @@ public static class ApplicationValidatorsServiceCollectionExtensions { /// /// Adds the validators of Application, and those of the assemblies it references, each as the - /// IValidateAsync of the type it validates, as its IValidate unless one of the type's rules waits, and as its + /// IValidator of the type it validates and as its /// IValidateMembers. A validator whose rules take services is scoped; the others are singletons. Where this assembly /// adds rules to a type of another, its validator, which runs that assembly's too, replaces the one registered for the type. /// @@ -22,45 +22,38 @@ public static class ApplicationValidatorsServiceCollectionExtensions public static global::Microsoft.Extensions.DependencyInjection.IServiceCollection AddApplicationValidators(this global::Microsoft.Extensions.DependencyInjection.IServiceCollection services) { global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.CircleGeneratedValidator>(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.CircleGeneratedValidator>(services); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator))!); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.CircleGeneratedValidator.Manifest); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton, global::Sample.CircleGeneratedValidator>()); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.IHasNameGeneratedValidator>(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.IHasNameGeneratedValidator>(services); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator))!); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.IHasNameGeneratedValidator.Manifest); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton, global::Sample.IHasNameGeneratedValidator>()); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.IPricedGeneratedValidator>(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.IPricedGeneratedValidator>(services); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator))!); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.IPricedGeneratedValidator.Manifest); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.PointGeneratedValidator>(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.PointGeneratedValidator>(services); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator))!); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.PointGeneratedValidator.Manifest); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.PolygonGeneratedValidator>(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.PolygonGeneratedValidator>(services); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator))!); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.PolygonGeneratedValidator.Manifest); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton, global::Sample.PolygonGeneratedValidator>()); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.ShapeGeneratedValidator>(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.ShapeGeneratedValidator>(services); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator))!); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.ShapeGeneratedValidator.Manifest); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton, global::Sample.ShapeGeneratedValidator>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.SquareGeneratedValidator>(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.SquareGeneratedValidator>(services); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator))!); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.SquareGeneratedValidator.Manifest); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); return services; diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.CircleGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.CircleGeneratedValidator.g.verified.cs index eb99c6e586..86572e2ec0 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.CircleGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.CircleGeneratedValidator.g.verified.cs @@ -11,7 +11,7 @@ namespace Sample /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Circle))] public sealed class CircleGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidate, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers, global::Microsoft.Extensions.Options.IValidateOptions + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers, global::Microsoft.Extensions.Options.IValidateOptions { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -22,6 +22,26 @@ public sealed class CircleGeneratedValidator public CircleGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// + public global::System.Threading.Tasks.ValueTask ValidateAsync(global::Sample.Circle value, global::System.Threading.CancellationToken cancellationToken = default) + { + global::System.ArgumentNullException.ThrowIfNull(value); + if (cancellationToken.IsCancellationRequested) return global::System.Threading.Tasks.ValueTask.FromCanceled(cancellationToken); + try + { + return new(Validate(value)); + } + catch (global::System.Exception exception) + { + return global::System.Threading.Tasks.ValueTask.FromException(exception); + } + } + + /// + /// Validates a value without waiting: none of the type's rules waits. + /// + /// The value. + /// The rules the value did not meet. + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Circle value) { global::System.ArgumentNullException.ThrowIfNull(value); diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.IHasNameGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.IHasNameGeneratedValidator.g.verified.cs index 3553049f10..440f8d43e5 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.IHasNameGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.IHasNameGeneratedValidator.g.verified.cs @@ -11,7 +11,7 @@ namespace Sample /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.IHasName))] public sealed class IHasNameGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidate, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers, global::Microsoft.Extensions.Options.IValidateOptions + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers, global::Microsoft.Extensions.Options.IValidateOptions { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -22,6 +22,26 @@ public sealed class IHasNameGeneratedValidator public IHasNameGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// + public global::System.Threading.Tasks.ValueTask ValidateAsync(global::Sample.IHasName value, global::System.Threading.CancellationToken cancellationToken = default) + { + global::System.ArgumentNullException.ThrowIfNull(value); + if (cancellationToken.IsCancellationRequested) return global::System.Threading.Tasks.ValueTask.FromCanceled(cancellationToken); + try + { + return new(Validate(value)); + } + catch (global::System.Exception exception) + { + return global::System.Threading.Tasks.ValueTask.FromException(exception); + } + } + + /// + /// Validates a value without waiting: none of the type's rules waits. + /// + /// The value. + /// The rules the value did not meet. + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.IHasName value) { global::System.ArgumentNullException.ThrowIfNull(value); diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.IPricedGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.IPricedGeneratedValidator.g.verified.cs index 928d38f60d..6a66b119c3 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.IPricedGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.IPricedGeneratedValidator.g.verified.cs @@ -11,7 +11,7 @@ namespace Sample /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.IPriced))] public sealed class IPricedGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidate, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { private readonly global::System.TimeProvider _time; private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -28,6 +28,26 @@ public IPricedGeneratedValidator(global::System.TimeProvider time, global::Rocke } /// + public global::System.Threading.Tasks.ValueTask ValidateAsync(global::Sample.IPriced value, global::System.Threading.CancellationToken cancellationToken = default) + { + global::System.ArgumentNullException.ThrowIfNull(value); + if (cancellationToken.IsCancellationRequested) return global::System.Threading.Tasks.ValueTask.FromCanceled(cancellationToken); + try + { + return new(Validate(value)); + } + catch (global::System.Exception exception) + { + return global::System.Threading.Tasks.ValueTask.FromException(exception); + } + } + + /// + /// Validates a value without waiting: none of the type's rules waits. + /// + /// The value. + /// The rules the value did not meet. + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.IPriced value) { global::System.ArgumentNullException.ThrowIfNull(value); diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.PointGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.PointGeneratedValidator.g.verified.cs index b06d3f35a2..e78f86cba5 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.PointGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.PointGeneratedValidator.g.verified.cs @@ -11,7 +11,7 @@ namespace Sample /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Point))] public sealed class PointGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidate, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { private readonly global::Sample.IPricedGeneratedValidator _iPricedGeneratedValidator; private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -28,6 +28,25 @@ public PointGeneratedValidator(global::Sample.IPricedGeneratedValidator iPricedG } /// + public global::System.Threading.Tasks.ValueTask ValidateAsync(global::Sample.Point value, global::System.Threading.CancellationToken cancellationToken = default) + { + if (cancellationToken.IsCancellationRequested) return global::System.Threading.Tasks.ValueTask.FromCanceled(cancellationToken); + try + { + return new(Validate(value)); + } + catch (global::System.Exception exception) + { + return global::System.Threading.Tasks.ValueTask.FromException(exception); + } + } + + /// + /// Validates a value without waiting: none of the type's rules waits. + /// + /// The value. + /// The rules the value did not meet. + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Point value) { var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.PolygonGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.PolygonGeneratedValidator.g.verified.cs index 2c85e73c46..bd807f348e 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.PolygonGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.PolygonGeneratedValidator.g.verified.cs @@ -11,7 +11,7 @@ namespace Sample /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Polygon))] public sealed class PolygonGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidate, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers, global::Microsoft.Extensions.Options.IValidateOptions + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers, global::Microsoft.Extensions.Options.IValidateOptions { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -22,6 +22,26 @@ public sealed class PolygonGeneratedValidator public PolygonGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// + public global::System.Threading.Tasks.ValueTask ValidateAsync(global::Sample.Polygon value, global::System.Threading.CancellationToken cancellationToken = default) + { + global::System.ArgumentNullException.ThrowIfNull(value); + if (cancellationToken.IsCancellationRequested) return global::System.Threading.Tasks.ValueTask.FromCanceled(cancellationToken); + try + { + return new(Validate(value)); + } + catch (global::System.Exception exception) + { + return global::System.Threading.Tasks.ValueTask.FromException(exception); + } + } + + /// + /// Validates a value without waiting: none of the type's rules waits. + /// + /// The value. + /// The rules the value did not meet. + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Polygon value) { global::System.ArgumentNullException.ThrowIfNull(value); diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.ShapeGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.ShapeGeneratedValidator.g.verified.cs index 7c99ace3a9..3513547e7b 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.ShapeGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.ShapeGeneratedValidator.g.verified.cs @@ -11,7 +11,7 @@ namespace Sample /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Shape))] public sealed class ShapeGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidate, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers, global::Microsoft.Extensions.Options.IValidateOptions + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers, global::Microsoft.Extensions.Options.IValidateOptions { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -22,6 +22,26 @@ public sealed class ShapeGeneratedValidator public ShapeGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// + public global::System.Threading.Tasks.ValueTask ValidateAsync(global::Sample.Shape value, global::System.Threading.CancellationToken cancellationToken = default) + { + global::System.ArgumentNullException.ThrowIfNull(value); + if (cancellationToken.IsCancellationRequested) return global::System.Threading.Tasks.ValueTask.FromCanceled(cancellationToken); + try + { + return new(Validate(value)); + } + catch (global::System.Exception exception) + { + return global::System.Threading.Tasks.ValueTask.FromException(exception); + } + } + + /// + /// Validates a value without waiting: none of the type's rules waits. + /// + /// The value. + /// The rules the value did not meet. + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Shape value) { global::System.ArgumentNullException.ThrowIfNull(value); diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.SquareGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.SquareGeneratedValidator.g.verified.cs index ab1ac52c40..26442a4302 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.SquareGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Run_The_Rules_Of_Base_Classes_And_Interfaces#Sample.SquareGeneratedValidator.g.verified.cs @@ -11,7 +11,7 @@ namespace Sample /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Square))] public sealed class SquareGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidate, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { private readonly global::Sample.IPricedGeneratedValidator _iPricedGeneratedValidator; private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -28,6 +28,26 @@ public SquareGeneratedValidator(global::Sample.IPricedGeneratedValidator iPriced } /// + public global::System.Threading.Tasks.ValueTask ValidateAsync(global::Sample.Square value, global::System.Threading.CancellationToken cancellationToken = default) + { + global::System.ArgumentNullException.ThrowIfNull(value); + if (cancellationToken.IsCancellationRequested) return global::System.Threading.Tasks.ValueTask.FromCanceled(cancellationToken); + try + { + return new(Validate(value)); + } + catch (global::System.Exception exception) + { + return global::System.Threading.Tasks.ValueTask.FromException(exception); + } + } + + /// + /// Validates a value without waiting: none of the type's rules waits. + /// + /// The value. + /// The rules the value did not meet. + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Square value) { global::System.ArgumentNullException.ThrowIfNull(value); diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#LaunchPadValidators.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#LaunchPadValidators.g.verified.cs index 9f6b83173a..f549e7ecff 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#LaunchPadValidators.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#LaunchPadValidators.g.verified.cs @@ -13,7 +13,7 @@ public static class ApplicationValidatorsServiceCollectionExtensions { /// /// Adds the validators of Application, and those of the assemblies it references, each as the - /// IValidateAsync of the type it validates, as its IValidate unless one of the type's rules waits, and as its + /// IValidator of the type it validates and as its /// IValidateMembers. A validator whose rules take services is scoped; the others are singletons. Where this assembly /// adds rules to a type of another, its validator, which runs that assembly's too, replaces the one registered for the type. /// @@ -22,18 +22,17 @@ public static class ApplicationValidatorsServiceCollectionExtensions public static global::Microsoft.Extensions.DependencyInjection.IServiceCollection AddApplicationValidators(this global::Microsoft.Extensions.DependencyInjection.IServiceCollection services) { global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.BodyGeneratedValidator>(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.BodyGeneratedValidator>(services); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator))!); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.BodyGeneratedValidator.Manifest); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton, global::Sample.BodyGeneratedValidator>()); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.PlanetGeneratedValidator>(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.PlanetGeneratedValidator>(services); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator))!); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.PlanetGeneratedValidator.Manifest); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.PlanetModelGeneratedValidator>(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.PlanetModelGeneratedValidator>(services); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator))!); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.PlanetModelGeneratedValidator.Manifest); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); return services; diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#Sample.BodyGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#Sample.BodyGeneratedValidator.g.verified.cs index 04cf4b7907..38b9e815d1 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#Sample.BodyGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#Sample.BodyGeneratedValidator.g.verified.cs @@ -11,7 +11,7 @@ namespace Sample /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Body))] public sealed class BodyGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidate, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers, global::Microsoft.Extensions.Options.IValidateOptions + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers, global::Microsoft.Extensions.Options.IValidateOptions { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -22,6 +22,26 @@ public sealed class BodyGeneratedValidator public BodyGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// + public global::System.Threading.Tasks.ValueTask ValidateAsync(global::Sample.Body value, global::System.Threading.CancellationToken cancellationToken = default) + { + global::System.ArgumentNullException.ThrowIfNull(value); + if (cancellationToken.IsCancellationRequested) return global::System.Threading.Tasks.ValueTask.FromCanceled(cancellationToken); + try + { + return new(Validate(value)); + } + catch (global::System.Exception exception) + { + return global::System.Threading.Tasks.ValueTask.FromException(exception); + } + } + + /// + /// Validates a value without waiting: none of the type's rules waits. + /// + /// The value. + /// The rules the value did not meet. + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Body value) { global::System.ArgumentNullException.ThrowIfNull(value); diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#Sample.PlanetGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#Sample.PlanetGeneratedValidator.g.verified.cs index 0c713164b2..7e5f8ea27d 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#Sample.PlanetGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#Sample.PlanetGeneratedValidator.g.verified.cs @@ -11,7 +11,7 @@ namespace Sample /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Planet))] public sealed class PlanetGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#Sample.PlanetModelGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#Sample.PlanetModelGeneratedValidator.g.verified.cs index 30bcd032e6..595bc7c49b 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#Sample.PlanetModelGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#Sample.PlanetModelGeneratedValidator.g.verified.cs @@ -11,11 +11,11 @@ namespace Sample /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.PlanetModel))] public sealed class PlanetModelGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; private readonly global::System.IServiceProvider? _services; - private global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync? _mutableTargetValidator; + private global::Rocket.Surgery.LaunchPad.Validation.IValidator? _mutableTargetValidator; /// /// Creates the validator. @@ -99,9 +99,9 @@ public bool TryValidateMember(global::Sample.PlanetModel value, string member, o new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Comment", "MaxLength(20)") ); - private global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync MutableTargetValidator => - _mutableTargetValidator ??= _services?.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync)) as global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync - ?? throw new global::System.InvalidOperationException("PlanetModelGeneratedValidator needs a Rocket.Surgery.LaunchPad.Validation.IValidateAsync, which the service provider it was given does not have."); + private global::Rocket.Surgery.LaunchPad.Validation.IValidator MutableTargetValidator => + _mutableTargetValidator ??= _services?.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator)) as global::Rocket.Surgery.LaunchPad.Validation.IValidator + ?? throw new global::System.InvalidOperationException("PlanetModelGeneratedValidator needs a Rocket.Surgery.LaunchPad.Validation.IValidator, which the service provider it was given does not have."); /// /// Checks the rules declared for itself, and no others: the validator of a type that diff --git a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read#INamedGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read#INamedGeneratedValidator.g.verified.cs index 33aca37b17..50f7d7bcc4 100644 --- a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read#INamedGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read#INamedGeneratedValidator.g.verified.cs @@ -9,7 +9,7 @@ /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::INamed))] public sealed class INamedGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidate, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -20,6 +20,26 @@ public sealed class INamedGeneratedValidator public INamedGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// + public global::System.Threading.Tasks.ValueTask ValidateAsync(global::INamed value, global::System.Threading.CancellationToken cancellationToken = default) + { + global::System.ArgumentNullException.ThrowIfNull(value); + if (cancellationToken.IsCancellationRequested) return global::System.Threading.Tasks.ValueTask.FromCanceled(cancellationToken); + try + { + return new(Validate(value)); + } + catch (global::System.Exception exception) + { + return global::System.Threading.Tasks.ValueTask.FromException(exception); + } + } + + /// + /// Validates a value without waiting: none of the type's rules waits. + /// + /// The value. + /// The rules the value did not meet. + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::INamed value) { global::System.ArgumentNullException.ThrowIfNull(value); diff --git a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read#LauncherGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read#LauncherGeneratedValidator.g.verified.cs index e04cc064eb..61a15ffa1d 100644 --- a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read#LauncherGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read#LauncherGeneratedValidator.g.verified.cs @@ -9,12 +9,12 @@ /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Launcher))] public sealed class LauncherGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidate, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { private readonly string _prefix; private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; private readonly global::System.IServiceProvider? _services; - private global::Rocket.Surgery.LaunchPad.Validation.IValidate? _engineValidator; + private global::Rocket.Surgery.LaunchPad.Validation.IValidator? _engineValidator; /// /// Creates the validator. @@ -30,12 +30,12 @@ public LauncherGeneratedValidator(string prefix, global::Rocket.Surgery.LaunchPa } /// - public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Launcher value) + public async global::System.Threading.Tasks.ValueTask ValidateAsync(global::Launcher value, global::System.Threading.CancellationToken cancellationToken = default) { global::System.ArgumentNullException.ThrowIfNull(value); var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); global::INamedGeneratedValidator.ValidateDeclared(value, ref sink); - ValidateDeclared(value, ref sink); + sink = await ValidateDeclaredAsync(value, sink, cancellationToken).ConfigureAwait(false); return sink.ToResult(); } @@ -51,8 +51,8 @@ public bool TryValidateMember(global::Launcher value, string member, out global: EnsureName(value.Name, ref sink); break; case "Engine": - EnsureEngine(value, value.Engine, ref sink); - break; + result = default; + return false; case "Count": EnsureCount(value.Count, ref sink); break; @@ -63,10 +63,25 @@ public bool TryValidateMember(global::Launcher value, string member, out global: } /// - public global::System.Threading.Tasks.ValueTask ValidateMemberAsync(global::Launcher value, string member, global::System.Threading.CancellationToken cancellationToken = default) + public async global::System.Threading.Tasks.ValueTask ValidateMemberAsync(global::Launcher value, string member, global::System.Threading.CancellationToken cancellationToken = default) { - TryValidateMember(value, member, out var result); - return new(result); + global::System.ArgumentNullException.ThrowIfNull(value); + var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); + switch (member) + { + case "Name": + global::INamedGeneratedValidator.EnsureName(((global::INamed)value).Name, ref sink); + EnsureName(value.Name, ref sink); + break; + case "Engine": + sink = await EnsureEngine(value, value.Engine, sink, cancellationToken).ConfigureAwait(false); + break; + case "Count": + EnsureCount(value.Count, ref sink); + break; + } + + return sink.ToResult(); } /// @@ -80,9 +95,9 @@ public bool TryValidateMember(global::Launcher value, string member, out global: new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Count", "GreaterThan(0)") ); - private global::Rocket.Surgery.LaunchPad.Validation.IValidate EngineValidator => - _engineValidator ??= _services?.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate)) as global::Rocket.Surgery.LaunchPad.Validation.IValidate - ?? throw new global::System.InvalidOperationException("LauncherGeneratedValidator needs a Rocket.Surgery.LaunchPad.Validation.IValidate, which the service provider it was given does not have."); + private global::Rocket.Surgery.LaunchPad.Validation.IValidator EngineValidator => + _engineValidator ??= _services?.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator)) as global::Rocket.Surgery.LaunchPad.Validation.IValidator + ?? throw new global::System.InvalidOperationException("LauncherGeneratedValidator needs a Rocket.Surgery.LaunchPad.Validation.IValidator, which the service provider it was given does not have."); /// /// Checks the rules declared for itself, and no others: the validator of a type that @@ -90,12 +105,15 @@ public bool TryValidateMember(global::Launcher value, string member, out global: /// /// The value. /// Where the failures go. + /// A token that cancels the rules that wait. + /// Where the failures went. [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] - public void ValidateDeclared(global::Launcher value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + public async global::System.Threading.Tasks.ValueTask ValidateDeclaredAsync(global::Launcher value, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink, global::System.Threading.CancellationToken cancellationToken) { EnsureName(value.Name, ref sink); - EnsureEngine(value, value.Engine, ref sink); + sink = await EnsureEngine(value, value.Engine, sink, cancellationToken).ConfigureAwait(false); EnsureCount(value.Count, ref sink); + return sink; } /// @@ -113,15 +131,16 @@ public void EnsureName(string value, ref global::Rocket.Surgery.LaunchPad.Valida /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Engine", ReadsValue = true)] [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] - public void EnsureEngine(global::Launcher instance, global::Engine value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + public async global::System.Threading.Tasks.ValueTask EnsureEngine(global::Launcher instance, global::Engine value, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink, global::System.Threading.CancellationToken cancellationToken) { if (value is { } present) { var path = sink.Enter("Engine"); - sink.Add(EngineValidator.Validate(present)); + sink.Add(await EngineValidator.ValidateAsync(present, cancellationToken).ConfigureAwait(false)); sink.Leave(path); } + return sink; } /// diff --git a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read.verified.txt b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read.verified.txt index 7dbe816739..207b0b04dd 100644 --- a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read.verified.txt +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read.verified.txt @@ -17,7 +17,7 @@ WarningLevel: 0, Location: Input0.cs: (18,17)-(18,25), MessageFormat: {0}, - Message: Validate declares rules only as a static method that takes its dependencies as parameters, or as the Validate of a class that implements IValidator, + Message: Validate declares rules only as a static method that takes its dependencies as parameters, or as the Validate of a class that implements IValidatorDefinition, Category: LaunchPad.Validation }, { @@ -140,7 +140,7 @@ WarningLevel: 0, Location: Input0.cs: (18,17)-(18,25), MessageFormat: {0}, - Message: Validate declares rules only as a static method that takes its dependencies as parameters, or as the Validate of a class that implements IValidator, + Message: Validate declares rules only as a static method that takes its dependencies as parameters, or as the Validate of a class that implements IValidatorDefinition, Category: LaunchPad.Validation }, { diff --git a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#LaunchPadValidators.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#LaunchPadValidators.g.verified.cs index 04d414f525..4b5f44a9c9 100644 --- a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#LaunchPadValidators.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#LaunchPadValidators.g.verified.cs @@ -13,7 +13,7 @@ public static class ApplicationValidatorsServiceCollectionExtensions { /// /// Adds the validators of Application, and those of the assemblies it references, each as the - /// IValidateAsync of the type it validates, as its IValidate unless one of the type's rules waits, and as its + /// IValidator of the type it validates and as its /// IValidateMembers. A validator whose rules take services is scoped; the others are singletons. Where this assembly /// adds rules to a type of another, its validator, which runs that assembly's too, replaces the one registered for the type. /// @@ -23,16 +23,16 @@ public static class ApplicationValidatorsServiceCollectionExtensions { global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton(services); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.BookingGeneratedValidator>(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.BookingGeneratedValidator>(services); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator))!); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.BookingGeneratedValidator.Manifest); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.ManifestGeneratedValidator>(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.ManifestGeneratedValidator>(services); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator))!); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.ManifestGeneratedValidator.Manifest); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.ScheduleGeneratedValidator>(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.ScheduleGeneratedValidator>(services); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator))!); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.ScheduleGeneratedValidator.Manifest); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); return services; diff --git a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.BookingGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.BookingGeneratedValidator.g.verified.cs index c4717fe7b4..ba4a37e861 100644 --- a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.BookingGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.BookingGeneratedValidator.g.verified.cs @@ -11,7 +11,7 @@ namespace Sample /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Booking))] internal sealed class BookingGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { private readonly global::Sample.BookingValidator _bookingValidator; private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; diff --git a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.ManifestGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.ManifestGeneratedValidator.g.verified.cs index 922051b719..6230f0e6ca 100644 --- a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.ManifestGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.ManifestGeneratedValidator.g.verified.cs @@ -11,11 +11,11 @@ namespace Sample /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Manifest))] public sealed class ManifestGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; private readonly global::System.IServiceProvider? _services; - private global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync? _bookingValidator; + private global::Rocket.Surgery.LaunchPad.Validation.IValidator? _bookingValidator; /// /// Creates the validator. @@ -91,9 +91,9 @@ public bool TryValidateMember(global::Sample.Manifest value, string member, out new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Others") ); - private global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync BookingValidator => - _bookingValidator ??= _services?.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync)) as global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync - ?? throw new global::System.InvalidOperationException("ManifestGeneratedValidator needs a Rocket.Surgery.LaunchPad.Validation.IValidateAsync, which the service provider it was given does not have."); + private global::Rocket.Surgery.LaunchPad.Validation.IValidator BookingValidator => + _bookingValidator ??= _services?.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator)) as global::Rocket.Surgery.LaunchPad.Validation.IValidator + ?? throw new global::System.InvalidOperationException("ManifestGeneratedValidator needs a Rocket.Surgery.LaunchPad.Validation.IValidator, which the service provider it was given does not have."); /// /// Checks the rules declared for itself, and no others: the validator of a type that diff --git a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.ScheduleGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.ScheduleGeneratedValidator.g.verified.cs index 6fb93bdc6d..935ea7cd06 100644 --- a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.ScheduleGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.ScheduleGeneratedValidator.g.verified.cs @@ -11,11 +11,11 @@ namespace Sample /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Schedule))] public sealed class ScheduleGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; private readonly global::System.IServiceProvider? _services; - private global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync? _manifestValidator; + private global::Rocket.Surgery.LaunchPad.Validation.IValidator? _manifestValidator; /// /// Creates the validator. @@ -77,9 +77,9 @@ public bool TryValidateMember(global::Sample.Schedule value, string member, out new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Manifest", "NotNull") ); - private global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync ManifestValidator => - _manifestValidator ??= _services?.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync)) as global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync - ?? throw new global::System.InvalidOperationException("ScheduleGeneratedValidator needs a Rocket.Surgery.LaunchPad.Validation.IValidateAsync, which the service provider it was given does not have."); + private global::Rocket.Surgery.LaunchPad.Validation.IValidator ManifestValidator => + _manifestValidator ??= _services?.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator)) as global::Rocket.Surgery.LaunchPad.Validation.IValidator + ?? throw new global::System.InvalidOperationException("ScheduleGeneratedValidator needs a Rocket.Surgery.LaunchPad.Validation.IValidator, which the service provider it was given does not have."); /// /// Checks the rules declared for itself, and no others: the validator of a type that diff --git a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type#LaunchPadValidators.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type#LaunchPadValidators.g.verified.cs index b79d301a55..862298b8a8 100644 --- a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type#LaunchPadValidators.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type#LaunchPadValidators.g.verified.cs @@ -13,7 +13,7 @@ public static class ApplicationValidatorsServiceCollectionExtensions { /// /// Adds the validators of Application, and those of the assemblies it references, each as the - /// IValidateAsync of the type it validates, as its IValidate unless one of the type's rules waits, and as its + /// IValidator of the type it validates and as its /// IValidateMembers. A validator whose rules take services is scoped; the others are singletons. Where this assembly /// adds rules to a type of another, its validator, which runs that assembly's too, replaces the one registered for the type. /// @@ -22,9 +22,8 @@ public static class ApplicationValidatorsServiceCollectionExtensions public static global::Microsoft.Extensions.DependencyInjection.IServiceCollection AddApplicationValidators(this global::Microsoft.Extensions.DependencyInjection.IServiceCollection services) { global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.Operations.BuildLauncher_RequestGeneratedValidator>(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.Operations.BuildLauncher_RequestGeneratedValidator>(services); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator))!); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.Operations.BuildLauncher_RequestGeneratedValidator.Manifest); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); return services; diff --git a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type#Sample.Operations.BuildLauncher_RequestGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type#Sample.Operations.BuildLauncher_RequestGeneratedValidator.g.verified.cs index 0b5d1f1a37..7ac71d2884 100644 --- a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type#Sample.Operations.BuildLauncher_RequestGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type#Sample.Operations.BuildLauncher_RequestGeneratedValidator.g.verified.cs @@ -11,7 +11,7 @@ namespace Sample.Operations /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Operations.BuildLauncher.Request))] public sealed class BuildLauncher_RequestGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidate, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { private readonly global::Sample.Services.ICatalog _catalog; private readonly global::System.TimeProvider _time; @@ -31,6 +31,26 @@ public BuildLauncher_RequestGeneratedValidator(global::Sample.Services.ICatalog } /// + public global::System.Threading.Tasks.ValueTask ValidateAsync(global::Sample.Operations.BuildLauncher.Request value, global::System.Threading.CancellationToken cancellationToken = default) + { + global::System.ArgumentNullException.ThrowIfNull(value); + if (cancellationToken.IsCancellationRequested) return global::System.Threading.Tasks.ValueTask.FromCanceled(cancellationToken); + try + { + return new(Validate(value)); + } + catch (global::System.Exception exception) + { + return global::System.Threading.Tasks.ValueTask.FromException(exception); + } + } + + /// + /// Validates a value without waiting: none of the type's rules waits. + /// + /// The value. + /// The rules the value did not meet. + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Operations.BuildLauncher.Request value) { global::System.ArgumentNullException.ThrowIfNull(value); diff --git a/test/Validation.Analyzers.Tests/snapshots/SynchronousValidationAnalyzerTests.Should_Report_The_Synchronous_Validator_Of_An_Asynchronous_Type_And_Make_Its_Use_Asynchronous.verified.txt b/test/Validation.Analyzers.Tests/snapshots/SynchronousValidationAnalyzerTests.Should_Report_The_Synchronous_Validator_Of_An_Asynchronous_Type_And_Make_Its_Use_Asynchronous.verified.txt deleted file mode 100644 index 3bf09c068c..0000000000 --- a/test/Validation.Analyzers.Tests/snapshots/SynchronousValidationAnalyzerTests.Should_Report_The_Synchronous_Validator_Of_An_Asynchronous_Type_And_Make_Its_Use_Asynchronous.verified.txt +++ /dev/null @@ -1,55 +0,0 @@ -{ - Diagnostics: [ - { - Id: LPAD3002, - Severity: Error, - Location: Input.cs: (18,28)-(18,46), - Source: IValidate, - Message: 'Booking' has an asynchronous rule, so it has no IValidate: use IValidateAsync and await ValidateAsync - } - ], - CodeFixes: [ - { - Diagnostic: Input.cs: (18,28)-(18,46), - Title: Validate asynchronously, - Text: -#nullable enable -using System; -using System.Threading; -using System.Threading.Tasks; -using Rocket.Surgery.LaunchPad.Validation; -using Rocket.Surgery.LaunchPad.Validation.Rules; - -namespace Sample; - -public sealed record Booking(string Serial); - -public sealed record Pad([NotEmpty] string Name); - -public static partial class Rules -{ - private static void Validate(IValidationBuilder v) => v.Ensure(x => x.Serial).MustAsync((_, _) => new ValueTask(true)); -} - -public sealed class Handler(IValidateAsync validator, IValidate pads) -{ - public async Task Check(Booking booking, CancellationToken cancellationToken) - { - // Pad has no asynchronous rule: this stays as it is. - if (!pads.Validate(new("LC-39A")).IsValid) return false; - return (await validator.ValidateAsync(booking, cancellationToken)).IsValid; - } - - public async Task Report(Booking booking) - { - var result = await validator.ValidateAsync(booking); - Console.WriteLine(result.IsValid); - } - - public async Task Already(Booking booking) => Task.FromResult(await validator.ValidateAsync(booking)); - - public Func Later() => async booking => (await validator.ValidateAsync(booking)).IsValid; -} - } - ] -} \ No newline at end of file diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Compile_The_DataAnnotations_Attributes#AccountGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Compile_The_DataAnnotations_Attributes#AccountGeneratedValidator.g.verified.cs index 8bf3c10245..aa0773fedb 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Compile_The_DataAnnotations_Attributes#AccountGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Compile_The_DataAnnotations_Attributes#AccountGeneratedValidator.g.verified.cs @@ -9,7 +9,7 @@ /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Account))] public sealed class AccountGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidate, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -23,6 +23,26 @@ public sealed class AccountGeneratedValidator public AccountGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// + public global::System.Threading.Tasks.ValueTask ValidateAsync(global::Account value, global::System.Threading.CancellationToken cancellationToken = default) + { + global::System.ArgumentNullException.ThrowIfNull(value); + if (cancellationToken.IsCancellationRequested) return global::System.Threading.Tasks.ValueTask.FromCanceled(cancellationToken); + try + { + return new(Validate(value)); + } + catch (global::System.Exception exception) + { + return global::System.Threading.Tasks.ValueTask.FromException(exception); + } + } + + /// + /// Validates a value without waiting: none of the type's rules waits. + /// + /// The value. + /// The rules the value did not meet. + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Account value) { global::System.ArgumentNullException.ThrowIfNull(value); diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.NamedGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.NamedGeneratedValidator.g.verified.cs index 6184700611..be730ed623 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.NamedGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.NamedGeneratedValidator.g.verified.cs @@ -11,7 +11,7 @@ namespace Sample /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Named))] public sealed class NamedGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidate, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -22,6 +22,26 @@ public sealed class NamedGeneratedValidator public NamedGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// + public global::System.Threading.Tasks.ValueTask ValidateAsync(global::Sample.Named value, global::System.Threading.CancellationToken cancellationToken = default) + { + global::System.ArgumentNullException.ThrowIfNull(value); + if (cancellationToken.IsCancellationRequested) return global::System.Threading.Tasks.ValueTask.FromCanceled(cancellationToken); + try + { + return new(Validate(value)); + } + catch (global::System.Exception exception) + { + return global::System.Threading.Tasks.ValueTask.FromException(exception); + } + } + + /// + /// Validates a value without waiting: none of the type's rules waits. + /// + /// The value. + /// The rules the value did not meet. + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Named value) { global::System.ArgumentNullException.ThrowIfNull(value); diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Outer_InnerGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Outer_InnerGeneratedValidator.g.verified.cs index 796a78868d..6aae258940 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Outer_InnerGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Outer_InnerGeneratedValidator.g.verified.cs @@ -11,7 +11,7 @@ namespace Sample /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Outer.Inner))] internal sealed class Outer_InnerGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidate, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -22,6 +22,26 @@ internal sealed class Outer_InnerGeneratedValidator public Outer_InnerGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// + public global::System.Threading.Tasks.ValueTask ValidateAsync(global::Sample.Outer.Inner value, global::System.Threading.CancellationToken cancellationToken = default) + { + global::System.ArgumentNullException.ThrowIfNull(value); + if (cancellationToken.IsCancellationRequested) return global::System.Threading.Tasks.ValueTask.FromCanceled(cancellationToken); + try + { + return new(Validate(value)); + } + catch (global::System.Exception exception) + { + return global::System.Threading.Tasks.ValueTask.FromException(exception); + } + } + + /// + /// Validates a value without waiting: none of the type's rules waits. + /// + /// The value. + /// The rules the value did not meet. + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Outer.Inner value) { global::System.ArgumentNullException.ThrowIfNull(value); diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.PositionGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.PositionGeneratedValidator.g.verified.cs index 3332287785..fa11b5b9a9 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.PositionGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.PositionGeneratedValidator.g.verified.cs @@ -11,7 +11,7 @@ namespace Sample /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Position))] public sealed class PositionGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidate, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -22,6 +22,25 @@ public sealed class PositionGeneratedValidator public PositionGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// + public global::System.Threading.Tasks.ValueTask ValidateAsync(global::Sample.Position value, global::System.Threading.CancellationToken cancellationToken = default) + { + if (cancellationToken.IsCancellationRequested) return global::System.Threading.Tasks.ValueTask.FromCanceled(cancellationToken); + try + { + return new(Validate(value)); + } + catch (global::System.Exception exception) + { + return global::System.Threading.Tasks.ValueTask.FromException(exception); + } + } + + /// + /// Validates a value without waiting: none of the type's rules waits. + /// + /// The value. + /// The rules the value did not meet. + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Position value) { var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.StageGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.StageGeneratedValidator.g.verified.cs index 1ec8571d35..67a2ced974 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.StageGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.StageGeneratedValidator.g.verified.cs @@ -11,7 +11,7 @@ namespace Sample /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Stage))] public sealed class StageGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidate, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -22,6 +22,26 @@ public sealed class StageGeneratedValidator public StageGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// + public global::System.Threading.Tasks.ValueTask ValidateAsync(global::Sample.Stage value, global::System.Threading.CancellationToken cancellationToken = default) + { + global::System.ArgumentNullException.ThrowIfNull(value); + if (cancellationToken.IsCancellationRequested) return global::System.Threading.Tasks.ValueTask.FromCanceled(cancellationToken); + try + { + return new(Validate(value)); + } + catch (global::System.Exception exception) + { + return global::System.Threading.Tasks.ValueTask.FromException(exception); + } + } + + /// + /// Validates a value without waiting: none of the type's rules waits. + /// + /// The value. + /// The rules the value did not meet. + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Stage value) { global::System.ArgumentNullException.ThrowIfNull(value); diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#LaunchPadValidators.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#LaunchPadValidators.g.verified.cs index 2463daa8e8..ead640a741 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#LaunchPadValidators.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#LaunchPadValidators.g.verified.cs @@ -13,7 +13,7 @@ public static class ApplicationValidatorsServiceCollectionExtensions { /// /// Adds the validators of Application, and those of the assemblies it references, each as the - /// IValidateAsync of the type it validates, as its IValidate unless one of the type's rules waits, and as its + /// IValidator of the type it validates and as its /// IValidateMembers. A validator whose rules take services is scoped; the others are singletons. Where this assembly /// adds rules to a type of another, its validator, which runs that assembly's too, replaces the one registered for the type. /// @@ -22,14 +22,12 @@ public static class ApplicationValidatorsServiceCollectionExtensions public static global::Microsoft.Extensions.DependencyInjection.IServiceCollection AddApplicationValidators(this global::Microsoft.Extensions.DependencyInjection.IServiceCollection services) { global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.DelayGeneratedValidator>(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.DelayGeneratedValidator>(services); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator))!); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.DelayGeneratedValidator.Manifest); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.RetryOptionsGeneratedValidator>(services); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidate)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate))!); - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync))!); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.RetryOptionsGeneratedValidator>(services); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton>(services, static provider => (global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers)provider.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator))!); global::Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton(services, global::Sample.RetryOptionsGeneratedValidator.Manifest); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton>()); global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton, global::Sample.RetryOptionsGeneratedValidator>()); diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.DelayGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.DelayGeneratedValidator.g.verified.cs index 3b3cd2881c..e2bc8777e1 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.DelayGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.DelayGeneratedValidator.g.verified.cs @@ -11,7 +11,7 @@ namespace Sample /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Delay))] internal sealed class DelayGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidate, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -22,6 +22,25 @@ internal sealed class DelayGeneratedValidator public DelayGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// + public global::System.Threading.Tasks.ValueTask ValidateAsync(global::Sample.Delay value, global::System.Threading.CancellationToken cancellationToken = default) + { + if (cancellationToken.IsCancellationRequested) return global::System.Threading.Tasks.ValueTask.FromCanceled(cancellationToken); + try + { + return new(Validate(value)); + } + catch (global::System.Exception exception) + { + return global::System.Threading.Tasks.ValueTask.FromException(exception); + } + } + + /// + /// Validates a value without waiting: none of the type's rules waits. + /// + /// The value. + /// The rules the value did not meet. + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Delay value) { var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.RetryOptionsGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.RetryOptionsGeneratedValidator.g.verified.cs index 44715159ad..80be82b5cc 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.RetryOptionsGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.RetryOptionsGeneratedValidator.g.verified.cs @@ -11,7 +11,7 @@ namespace Sample /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.RetryOptions))] public sealed class RetryOptionsGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidate, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers, global::Microsoft.Extensions.Options.IValidateOptions + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers, global::Microsoft.Extensions.Options.IValidateOptions { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -22,6 +22,26 @@ public sealed class RetryOptionsGeneratedValidator public RetryOptionsGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// + public global::System.Threading.Tasks.ValueTask ValidateAsync(global::Sample.RetryOptions value, global::System.Threading.CancellationToken cancellationToken = default) + { + global::System.ArgumentNullException.ThrowIfNull(value); + if (cancellationToken.IsCancellationRequested) return global::System.Threading.Tasks.ValueTask.FromCanceled(cancellationToken); + try + { + return new(Validate(value)); + } + catch (global::System.Exception exception) + { + return global::System.Threading.Tasks.ValueTask.FromException(exception); + } + } + + /// + /// Validates a value without waiting: none of the type's rules waits. + /// + /// The value. + /// The rules the value did not meet. + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.RetryOptions value) { global::System.ArgumentNullException.ThrowIfNull(value); diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Report_What_It_Cannot_Write#MistakesGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Report_What_It_Cannot_Write#MistakesGeneratedValidator.g.verified.cs index 65f886e6da..b5be48ee17 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Report_What_It_Cannot_Write#MistakesGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Report_What_It_Cannot_Write#MistakesGeneratedValidator.g.verified.cs @@ -9,7 +9,7 @@ /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Mistakes))] public sealed class MistakesGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidate, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -20,6 +20,26 @@ public sealed class MistakesGeneratedValidator public MistakesGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// + public global::System.Threading.Tasks.ValueTask ValidateAsync(global::Mistakes value, global::System.Threading.CancellationToken cancellationToken = default) + { + global::System.ArgumentNullException.ThrowIfNull(value); + if (cancellationToken.IsCancellationRequested) return global::System.Threading.Tasks.ValueTask.FromCanceled(cancellationToken); + try + { + return new(Validate(value)); + } + catch (global::System.Exception exception) + { + return global::System.Threading.Tasks.ValueTask.FromException(exception); + } + } + + /// + /// Validates a value without waiting: none of the type's rules waits. + /// + /// The value. + /// The rules the value did not meet. + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Mistakes value) { global::System.ArgumentNullException.ThrowIfNull(value); diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.CrewGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.CrewGeneratedValidator.g.verified.cs index b96c08fa01..326398ddc7 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.CrewGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.CrewGeneratedValidator.g.verified.cs @@ -11,7 +11,7 @@ namespace Sample /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Crew))] public sealed class CrewGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidate, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -22,6 +22,26 @@ public sealed class CrewGeneratedValidator public CrewGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// + public global::System.Threading.Tasks.ValueTask ValidateAsync(global::Sample.Crew value, global::System.Threading.CancellationToken cancellationToken = default) + { + global::System.ArgumentNullException.ThrowIfNull(value); + if (cancellationToken.IsCancellationRequested) return global::System.Threading.Tasks.ValueTask.FromCanceled(cancellationToken); + try + { + return new(Validate(value)); + } + catch (global::System.Exception exception) + { + return global::System.Threading.Tasks.ValueTask.FromException(exception); + } + } + + /// + /// Validates a value without waiting: none of the type's rules waits. + /// + /// The value. + /// The rules the value did not meet. + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Crew value) { global::System.ArgumentNullException.ThrowIfNull(value); diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.LauncherGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.LauncherGeneratedValidator.g.verified.cs index 778c425f4c..7499fd6455 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.LauncherGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.LauncherGeneratedValidator.g.verified.cs @@ -11,12 +11,12 @@ namespace Sample /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Launcher))] public sealed class LauncherGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidate, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; private readonly global::System.IServiceProvider? _services; - private global::Rocket.Surgery.LaunchPad.Validation.IValidate? _crewValidator; - private global::Rocket.Surgery.LaunchPad.Validation.IValidate? _boosterValidator; + private global::Rocket.Surgery.LaunchPad.Validation.IValidator? _crewValidator; + private global::Rocket.Surgery.LaunchPad.Validation.IValidator? _boosterValidator; private global::Sample.StrictCrew? _reserveValidator; /// @@ -31,11 +31,11 @@ public LauncherGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IV } /// - public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Launcher value) + public async global::System.Threading.Tasks.ValueTask ValidateAsync(global::Sample.Launcher value, global::System.Threading.CancellationToken cancellationToken = default) { global::System.ArgumentNullException.ThrowIfNull(value); var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); - ValidateDeclared(value, ref sink); + sink = await ValidateDeclaredAsync(value, sink, cancellationToken).ConfigureAwait(false); return sink.ToResult(); } @@ -47,23 +47,23 @@ public bool TryValidateMember(global::Sample.Launcher value, string member, out switch (member) { case "Crew": - EnsureCrew(value.Crew, ref sink); - break; + result = default; + return false; case "Booster": - EnsureBooster(value.Booster, ref sink); - break; + result = default; + return false; case "Core": - EnsureCore(value.Core, ref sink); - break; + result = default; + return false; case "Stages": - EnsureStages(value.Stages, ref sink); - break; + result = default; + return false; case "Backups": - EnsureBackups(value.Backups, ref sink); - break; + result = default; + return false; case "Reserve": - EnsureReserve(value.Reserve, ref sink); - break; + result = default; + return false; } result = sink.ToResult(); @@ -71,10 +71,33 @@ public bool TryValidateMember(global::Sample.Launcher value, string member, out } /// - public global::System.Threading.Tasks.ValueTask ValidateMemberAsync(global::Sample.Launcher value, string member, global::System.Threading.CancellationToken cancellationToken = default) + public async global::System.Threading.Tasks.ValueTask ValidateMemberAsync(global::Sample.Launcher value, string member, global::System.Threading.CancellationToken cancellationToken = default) { - TryValidateMember(value, member, out var result); - return new(result); + global::System.ArgumentNullException.ThrowIfNull(value); + var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); + switch (member) + { + case "Crew": + sink = await EnsureCrew(value.Crew, sink, cancellationToken).ConfigureAwait(false); + break; + case "Booster": + sink = await EnsureBooster(value.Booster, sink, cancellationToken).ConfigureAwait(false); + break; + case "Core": + sink = await EnsureCore(value.Core, sink, cancellationToken).ConfigureAwait(false); + break; + case "Stages": + sink = await EnsureStages(value.Stages, sink, cancellationToken).ConfigureAwait(false); + break; + case "Backups": + sink = await EnsureBackups(value.Backups, sink, cancellationToken).ConfigureAwait(false); + break; + case "Reserve": + sink = await EnsureReserve(value.Reserve, sink, cancellationToken).ConfigureAwait(false); + break; + } + + return sink.ToResult(); } /// @@ -91,13 +114,13 @@ public bool TryValidateMember(global::Sample.Launcher value, string member, out new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Reserve") ); - private global::Rocket.Surgery.LaunchPad.Validation.IValidate CrewValidator => - _crewValidator ??= _services?.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate)) as global::Rocket.Surgery.LaunchPad.Validation.IValidate - ?? throw new global::System.InvalidOperationException("LauncherGeneratedValidator needs a Rocket.Surgery.LaunchPad.Validation.IValidate, which the service provider it was given does not have."); + private global::Rocket.Surgery.LaunchPad.Validation.IValidator CrewValidator => + _crewValidator ??= _services?.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator)) as global::Rocket.Surgery.LaunchPad.Validation.IValidator + ?? throw new global::System.InvalidOperationException("LauncherGeneratedValidator needs a Rocket.Surgery.LaunchPad.Validation.IValidator, which the service provider it was given does not have."); - private global::Rocket.Surgery.LaunchPad.Validation.IValidate BoosterValidator => - _boosterValidator ??= _services?.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate)) as global::Rocket.Surgery.LaunchPad.Validation.IValidate - ?? throw new global::System.InvalidOperationException("LauncherGeneratedValidator needs a Rocket.Surgery.LaunchPad.Validation.IValidate, which the service provider it was given does not have."); + private global::Rocket.Surgery.LaunchPad.Validation.IValidator BoosterValidator => + _boosterValidator ??= _services?.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator)) as global::Rocket.Surgery.LaunchPad.Validation.IValidator + ?? throw new global::System.InvalidOperationException("LauncherGeneratedValidator needs a Rocket.Surgery.LaunchPad.Validation.IValidator, which the service provider it was given does not have."); private global::Sample.StrictCrew ReserveValidator => _reserveValidator ??= _services?.GetService(typeof(global::Sample.StrictCrew)) as global::Sample.StrictCrew @@ -109,15 +132,18 @@ public bool TryValidateMember(global::Sample.Launcher value, string member, out /// /// The value. /// Where the failures go. + /// A token that cancels the rules that wait. + /// Where the failures went. [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] - public void ValidateDeclared(global::Sample.Launcher value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + public async global::System.Threading.Tasks.ValueTask ValidateDeclaredAsync(global::Sample.Launcher value, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink, global::System.Threading.CancellationToken cancellationToken) { - EnsureCrew(value.Crew, ref sink); - EnsureBooster(value.Booster, ref sink); - EnsureCore(value.Core, ref sink); - EnsureStages(value.Stages, ref sink); - EnsureBackups(value.Backups, ref sink); - EnsureReserve(value.Reserve, ref sink); + sink = await EnsureCrew(value.Crew, sink, cancellationToken).ConfigureAwait(false); + sink = await EnsureBooster(value.Booster, sink, cancellationToken).ConfigureAwait(false); + sink = await EnsureCore(value.Core, sink, cancellationToken).ConfigureAwait(false); + sink = await EnsureStages(value.Stages, sink, cancellationToken).ConfigureAwait(false); + sink = await EnsureBackups(value.Backups, sink, cancellationToken).ConfigureAwait(false); + sink = await EnsureReserve(value.Reserve, sink, cancellationToken).ConfigureAwait(false); + return sink; } /// @@ -125,14 +151,15 @@ public void ValidateDeclared(global::Sample.Launcher value, ref global::Rocket.S /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Crew")] [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] - public void EnsureCrew(global::Sample.Crew? value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + public async global::System.Threading.Tasks.ValueTask EnsureCrew(global::Sample.Crew? value, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink, global::System.Threading.CancellationToken cancellationToken) { if (value is { } present) { var path = sink.Enter("Crew"); - sink.Add(CrewValidator.Validate(present)); + sink.Add(await CrewValidator.ValidateAsync(present, cancellationToken).ConfigureAwait(false)); sink.Leave(path); } + return sink; } /// @@ -140,7 +167,7 @@ public void EnsureCrew(global::Sample.Crew? value, ref global::Rocket.Surgery.La /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Booster", "NotNull")] [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] - public void EnsureBooster(global::Sample.Stage? value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + public async global::System.Threading.Tasks.ValueTask EnsureBooster(global::Sample.Stage? value, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink, global::System.Threading.CancellationToken cancellationToken) { if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.NotNull(value)) { @@ -150,9 +177,10 @@ public void EnsureBooster(global::Sample.Stage? value, ref global::Rocket.Surger if (value is { } present) { var path = sink.Enter("Booster"); - sink.Add(BoosterValidator.Validate(present)); + sink.Add(await BoosterValidator.ValidateAsync(present, cancellationToken).ConfigureAwait(false)); sink.Leave(path); } + return sink; } /// @@ -160,11 +188,12 @@ public void EnsureBooster(global::Sample.Stage? value, ref global::Rocket.Surger /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Core")] [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] - public void EnsureCore(global::Sample.Stage value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + public async global::System.Threading.Tasks.ValueTask EnsureCore(global::Sample.Stage value, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink, global::System.Threading.CancellationToken cancellationToken) { var path = sink.Enter("Core"); - sink.Add(BoosterValidator.Validate(value)); + sink.Add(await BoosterValidator.ValidateAsync(value, cancellationToken).ConfigureAwait(false)); sink.Leave(path); + return sink; } /// @@ -172,7 +201,7 @@ public void EnsureCore(global::Sample.Stage value, ref global::Rocket.Surgery.La /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Stages", "NotEmpty")] [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] - public void EnsureStages(global::System.Collections.Generic.IReadOnlyList? value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + public async global::System.Threading.Tasks.ValueTask EnsureStages(global::System.Collections.Generic.IReadOnlyList? value, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink, global::System.Threading.CancellationToken cancellationToken) { if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.NotEmpty(value)) { @@ -186,7 +215,7 @@ public void EnsureStages(global::System.Collections.Generic.IReadOnlyList @@ -201,7 +231,7 @@ public void EnsureStages(global::System.Collections.Generic.IReadOnlyList [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Backups")] [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] - public void EnsureBackups(global::Sample.Crew?[] value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + public async global::System.Threading.Tasks.ValueTask EnsureBackups(global::Sample.Crew?[] value, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink, global::System.Threading.CancellationToken cancellationToken) { if (value is { } present) { @@ -212,7 +242,7 @@ public void EnsureBackups(global::Sample.Crew?[] value, ref global::Rocket.Surge if (item is { } each) { var itemPath = sink.Enter(index); - sink.Add(CrewValidator.Validate(each)); + sink.Add(await CrewValidator.ValidateAsync(each, cancellationToken).ConfigureAwait(false)); sink.Leave(itemPath); } @@ -221,6 +251,7 @@ public void EnsureBackups(global::Sample.Crew?[] value, ref global::Rocket.Surge sink.Leave(path); } + return sink; } /// @@ -228,14 +259,15 @@ public void EnsureBackups(global::Sample.Crew?[] value, ref global::Rocket.Surge /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Reserve")] [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] - public void EnsureReserve(global::Sample.Crew? value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + public async global::System.Threading.Tasks.ValueTask EnsureReserve(global::Sample.Crew? value, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink, global::System.Threading.CancellationToken cancellationToken) { if (value is { } present) { var path = sink.Enter("Reserve"); - sink.Add(ReserveValidator.Validate(present)); + sink.Add(await ReserveValidator.ValidateAsync(present, cancellationToken).ConfigureAwait(false)); sink.Leave(path); } + return sink; } } } diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.StageGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.StageGeneratedValidator.g.verified.cs index 1ca442b136..9c041e27b6 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.StageGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.StageGeneratedValidator.g.verified.cs @@ -11,7 +11,7 @@ namespace Sample /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Stage))] public sealed class StageGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidate, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -22,6 +22,25 @@ public sealed class StageGeneratedValidator public StageGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// + public global::System.Threading.Tasks.ValueTask ValidateAsync(global::Sample.Stage value, global::System.Threading.CancellationToken cancellationToken = default) + { + if (cancellationToken.IsCancellationRequested) return global::System.Threading.Tasks.ValueTask.FromCanceled(cancellationToken); + try + { + return new(Validate(value)); + } + catch (global::System.Exception exception) + { + return global::System.Threading.Tasks.ValueTask.FromException(exception); + } + } + + /// + /// Validates a value without waiting: none of the type's rules waits. + /// + /// The value. + /// The rules the value did not meet. + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Stage value) { var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Write_A_Validator_For_Rule_Attributes#Sample.LauncherGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Write_A_Validator_For_Rule_Attributes#Sample.LauncherGeneratedValidator.g.verified.cs index 9e6968a076..d660205162 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Write_A_Validator_For_Rule_Attributes#Sample.LauncherGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Write_A_Validator_For_Rule_Attributes#Sample.LauncherGeneratedValidator.g.verified.cs @@ -11,7 +11,7 @@ namespace Sample /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Launcher))] public sealed class LauncherGeneratedValidator - : global::Rocket.Surgery.LaunchPad.Validation.IValidate, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -25,6 +25,26 @@ public sealed class LauncherGeneratedValidator public LauncherGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// + public global::System.Threading.Tasks.ValueTask ValidateAsync(global::Sample.Launcher value, global::System.Threading.CancellationToken cancellationToken = default) + { + global::System.ArgumentNullException.ThrowIfNull(value); + if (cancellationToken.IsCancellationRequested) return global::System.Threading.Tasks.ValueTask.FromCanceled(cancellationToken); + try + { + return new(Validate(value)); + } + catch (global::System.Exception exception) + { + return global::System.Threading.Tasks.ValueTask.FromException(exception); + } + } + + /// + /// Validates a value without waiting: none of the type's rules waits. + /// + /// The value. + /// The rules the value did not meet. + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Launcher value) { global::System.ArgumentNullException.ThrowIfNull(value); diff --git a/test/Validation.AspNetCore.Tests/ValidationProblemDetailsJointTests.cs b/test/Validation.AspNetCore.Tests/ValidationProblemDetailsJointTests.cs index 3009a461e9..8f6bc40c33 100644 --- a/test/Validation.AspNetCore.Tests/ValidationProblemDetailsJointTests.cs +++ b/test/Validation.AspNetCore.Tests/ValidationProblemDetailsJointTests.cs @@ -48,7 +48,7 @@ public async Task Maps_A_Validation_Failure_To_422_And_Keeps_The_Previous_Status var selector = await provider.GetRequiredService>().Value.StatusCodeSelector.Should().NotBeNull(); - await selector(Failures.Exception(new Probe { Name = "", })).Should().BeEqualTo(StatusCodes.Status422UnprocessableEntity); + await selector(await Failures.Exception(new Probe { Name = "", })).Should().BeEqualTo(StatusCodes.Status422UnprocessableEntity); await selector(new InvalidOperationException()).Should().BeEqualTo(StatusCodes.Status404NotFound); } @@ -72,7 +72,7 @@ public async Task Answers_A_Controller_With_The_Failures_Grouped_By_Path() { var context = new ExceptionContext(new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor()), []) { - Exception = Failures.Exception(new Probe { Name = "x", Stages = [new(0), new(5),], Crew = 12, }), + Exception = await Failures.Exception(new Probe { Name = "x", Stages = [new(0), new(5),], Crew = 12, }), }; new ValidationProblemDetailsJoint.ValidationFailedExceptionFilter().OnException(context); @@ -103,7 +103,7 @@ public async Task Writes_The_Failures_Through_The_Json_Contexts() httpContext.Response.Body = body; await new ValidationProblemDetailsJoint.ValidationFailedProblemDetailsWriter().WriteAsync( - new() { HttpContext = httpContext, Exception = Failures.Exception(new Probe { Name = "", }), ProblemDetails = new() { Instance = "/rockets", }, } + new() { HttpContext = httpContext, Exception = await Failures.Exception(new Probe { Name = "", }), ProblemDetails = new() { Instance = "/rockets", }, } ); using var document = JsonDocument.Parse(body.ToArray()); @@ -140,9 +140,9 @@ public async Task Sends_The_Warnings_Of_An_Accepted_Request_In_A_Header() await using var app = builder.Build(); app.MapGet( "/rockets/{crew:int}", - (int crew, IValidate validator, ValidationNotices notices) => + async (int crew, IValidator validator, ValidationNotices notices) => { - notices.Add(validator.Validate(new() { Crew = crew, }).ThrowIfInvalid()); + notices.Add(( await validator.ValidateAsync(new() { Crew = crew, }) ).ThrowIfInvalid()); return TypedResults.Ok(); } ); @@ -183,10 +183,10 @@ public sealed class Probe internal static class Failures { - public static ValidationFailedException Exception(Probe rocket) + public static async Task Exception(Probe rocket) { - using var services = new ServiceCollection().AddValidationAspNetCoreTestsValidators().BuildServiceProvider(true); - using var scope = services.CreateScope(); - return new(scope.ServiceProvider.GetRequiredService>().Validate(rocket)); + await using var services = new ServiceCollection().AddValidationAspNetCoreTestsValidators().BuildServiceProvider(true); + await using var scope = services.CreateAsyncScope(); + return new(await scope.ServiceProvider.GetRequiredService>().ValidateAsync(rocket)); } } diff --git a/test/Validation.Blazor.Tests/LaunchPadValidatorTests.cs b/test/Validation.Blazor.Tests/LaunchPadValidatorTests.cs index 27d7687ef0..74364207ca 100644 --- a/test/Validation.Blazor.Tests/LaunchPadValidatorTests.cs +++ b/test/Validation.Blazor.Tests/LaunchPadValidatorTests.cs @@ -27,16 +27,17 @@ public async Task Adds_The_Messages_Of_The_Model_When_The_Form_Is_Validated() await editContext.GetValidationMessages(editContext.Field(nameof(Person.Nickname))).Should().BeEquivalentTo(["Nickname must not be empty"], CollectionOrdering.Matching); } - // A model whose rules are all synchronous is validated by the synchronous Validate too. + // Validation is asynchronous, whatever the rules are: the form's obsolete synchronous Validate can't wait for it, and says so. [Test] - public async Task Validates_A_Synchronous_Model_Synchronously() + public async Task Refuses_The_Synchronous_Validation_Of_The_Form() { var editContext = new EditContext(new Person { Name = "", Nickname = "Countess", }); await using var renderer = await Render(editContext); #pragma warning disable CS0618 // the obsolete synchronous Validate is still how older forms ask - await editContext.Validate().Should().BeFalse(); + await Assert.That(editContext.Validate).Throws(); #pragma warning restore CS0618 + await ( await editContext.ValidateAsync() ).Should().BeFalse(); await editContext.GetValidationMessages().Should().BeEquivalentTo(["Name is required"], CollectionOrdering.Matching); } @@ -117,7 +118,7 @@ public async Task Shows_A_Field_As_Pending_While_Its_Rule_Waits() await editContext.GetValidationMessages(userName).Should().BeEquivalentTo(["UserName is taken"], CollectionOrdering.Matching); } - // The form's asynchronous validation awaits the rule that waits; its synchronous one can't, and says so. + // The form's asynchronous validation awaits the rule that waits. [Test] public async Task Awaits_The_Rules_That_Wait_When_The_Form_Is_Validated() { @@ -126,9 +127,6 @@ public async Task Awaits_The_Rules_That_Wait_When_The_Form_Is_Validated() var editContext = new EditContext(new Account { UserName = "taken", Email = "ada@example.com", }); await using var renderer = await Render(editContext, services => services.AddSingleton(names)); -#pragma warning disable CS0618 // the obsolete synchronous Validate is still how older forms ask - await Assert.That(editContext.Validate).Throws(); -#pragma warning restore CS0618 await ( await editContext.ValidateAsync() ).Should().BeFalse(); await editContext.GetValidationMessages().Should().BeEquivalentTo(["UserName is taken"], CollectionOrdering.Matching); } diff --git a/test/Validation.Tests/CompositionTests.cs b/test/Validation.Tests/CompositionTests.cs index 782f0d10f4..1d39666a9f 100644 --- a/test/Validation.Tests/CompositionTests.cs +++ b/test/Validation.Tests/CompositionTests.cs @@ -21,11 +21,12 @@ private static ServiceProvider Services() => .AddValidationTestsValidators() .BuildServiceProvider(true); - private static string[] Codes(T value) + private static async Task Codes(T value) { - using var services = Services(); - using var scope = services.CreateScope(); - return [.. scope.ServiceProvider.GetRequiredService>().Validate(value).Failures.Select(z => z.Path + ":" + z.Code),]; + await using var services = Services(); + await using var scope = services.CreateAsyncScope(); + var result = await scope.ServiceProvider.GetRequiredService>().ValidateAsync(value); + return [.. result.Failures.Select(z => z.Path + ":" + z.Code),]; } private static string[] MemberCodes(T value, string member) @@ -39,32 +40,32 @@ private static string[] MemberCodes(T value, string member) [Test] public async Task Should_Apply_The_Rules_Of_A_Base_Class_And_An_Interface() { - await Codes(new Square()).Should().BeEquivalentTo(Array.Empty()); - await Codes(new Square { Area = 0, Price = 0, Label = "", }).Should().BeEquivalentTo(["Area:GreaterThan", "Price:GreaterThan", "Label:NotEmpty"]); + await ( await Codes(new Square()) ).Should().BeEquivalentTo(Array.Empty()); + await ( await Codes(new Square { Area = 0, Price = 0, Label = "", }) ).Should().BeEquivalentTo(["Area:GreaterThan", "Price:GreaterThan", "Label:NotEmpty"]); } [Test] public async Task Should_Validate_A_Type_That_Only_Derives_From_One_With_Rules() { - await Codes(new Circle()).Should().BeEquivalentTo(Array.Empty()); - await Codes(new Circle { Area = -1, }).Should().BeEquivalentTo(["Area:GreaterThan"]); + await ( await Codes(new Circle()) ).Should().BeEquivalentTo(Array.Empty()); + await ( await Codes(new Circle { Area = -1, }) ).Should().BeEquivalentTo(["Area:GreaterThan"]); } [Test] public async Task Should_Validate_A_Value_As_Its_Interface() { - await Codes(new Square { Price = 0, Label = "", }).Should().BeEquivalentTo(["Price:GreaterThan"]); - await Codes(new Square { Area = 0, Label = "", }).Should().BeEquivalentTo(["Area:GreaterThan"]); + await ( await Codes(new Square { Price = 0, Label = "", }) ).Should().BeEquivalentTo(["Price:GreaterThan"]); + await ( await Codes(new Square { Area = 0, Label = "", }) ).Should().BeEquivalentTo(["Area:GreaterThan"]); } [Test] public async Task Should_Apply_The_Rules_Of_A_Base_Class_And_An_Interface_Of_Another_Assembly() { - await Codes(new Car()).Should().BeEquivalentTo(Array.Empty()); - await Codes(new Car { Wheels = 0, Plate = "nope", Name = "", Doors = 9, }) + await ( await Codes(new Car()) ).Should().BeEquivalentTo(Array.Empty()); + await ( await Codes(new Car { Wheels = 0, Plate = "nope", Name = "", Doors = 9, }) ) .Should() .BeEquivalentTo(["Wheels:GreaterThan", "Plate:Matches", "Name:NotEmpty", "Doors:InclusiveBetween"]); - await Codes(new Truck { Plate = "", }).Should().BeEquivalentTo(["Plate:NotEmpty", "Plate:Matches"]); + await ( await Codes(new Truck { Plate = "", }) ).Should().BeEquivalentTo(["Plate:NotEmpty", "Plate:Matches"]); } // Attributes, a function, a class validator, an interface's rules and [InheritFrom] from another assembly: one validator, every rule once. @@ -72,13 +73,13 @@ await Codes(new Car { Wheels = 0, Plate = "nope", Name = "", Doors = 9, }) public async Task Should_Merge_Every_Source_Of_Rules_Into_One_Validator() { // The members copied from another assembly don't bring their initializers. - await Codes(new ShippingAddress { City = "Portland", PostCode = "97201", Country = "US", }).Should().BeEquivalentTo(Array.Empty()); - await Codes( + await ( await Codes(new ShippingAddress { City = "Portland", PostCode = "97201", Country = "US", }) ).Should().BeEquivalentTo(Array.Empty()); + await ( await Codes( new ShippingAddress { Name = "", City = "", PostCode = "10001", Country = "", Phone = "", Express = true, } - ) + ) ) .Should() .BeEquivalentTo( [ @@ -98,20 +99,17 @@ public async Task Should_Carry_The_Message_And_The_Placeholders_Of_An_Inherited_ { using var services = Services(); using var scope = services.CreateScope(); - var result = scope.ServiceProvider.GetRequiredService>().Validate(new() { City = "Portland", PostCode = "123456789", }); + var result = await scope.ServiceProvider.GetRequiredService>().ValidateAsync(new() { City = "Portland", PostCode = "123456789", }); await result.Failures.Select(z => z.Message).Should().BeEquivalentTo(["PostCode must be at most 8 characters long", "PostCode is not a post code"]); await result.Failures[0].Arguments.Single(z => z.Key == "Max").Value.Should().BeEqualTo(8); } [Test] - public async Task Should_Be_Asynchronous_When_An_Inherited_Rule_Waits() + public async Task Should_Wait_For_An_Inherited_Rule() { using var services = Services(); -#pragma warning disable LPAD3002 // the point of the test: the type has no synchronous validator - await Assert.That(services.GetService>()).IsNull(); -#pragma warning restore LPAD3002 - var validator = services.GetRequiredService>(); + var validator = services.GetRequiredService>(); await ( await validator.ValidateAsync(new() { Code = "R-7", }) ).IsValid.Should().BeTrue(); var result = await validator.ValidateAsync(new() { Code = "X-1", }); @@ -121,27 +119,27 @@ public async Task Should_Be_Asynchronous_When_An_Inherited_Rule_Waits() [Test] public async Task Should_Include_The_Rules_Of_The_Members_Shared_With_Another_Type() { - await Codes(new Draft()).Should().BeEquivalentTo(Array.Empty()); - await Codes(new Draft { City = "", PostCode = "10001", }).Should().BeEquivalentTo(["City:NotEmpty", "PostCode:UnknownPostCode"]); + await ( await Codes(new Draft()) ).Should().BeEquivalentTo(Array.Empty()); + await ( await Codes(new Draft { City = "", PostCode = "10001", }) ).Should().BeEquivalentTo(["City:NotEmpty", "PostCode:UnknownPostCode"]); } // The library's rules and the application's, once each, through the one validator the application registers. [Test] public async Task Should_Compose_The_Rules_Two_Assemblies_Declare_For_One_Type() { - await Codes(new Parcel()).Should().BeEquivalentTo(Array.Empty()); - await Codes(new Parcel { Weight = 0, Label = "", }).Should().BeEquivalentTo(["Weight:GreaterThan", "Label:NotEmpty"]); - await Codes(new Parcel { Label = "this way up", }).Should().BeEquivalentTo(["Label:MaxLength"]); + await ( await Codes(new Parcel()) ).Should().BeEquivalentTo(Array.Empty()); + await ( await Codes(new Parcel { Weight = 0, Label = "", }) ).Should().BeEquivalentTo(["Weight:GreaterThan", "Label:NotEmpty"]); + await ( await Codes(new Parcel { Label = "this way up", }) ).Should().BeEquivalentTo(["Label:MaxLength"]); using var services = Services(); - await services.GetServices>().Count().Should().BeEqualTo(1); + await services.GetServices>().Count().Should().BeEqualTo(1); } [Test] public async Task Should_Validate_A_View_Model_As_The_Type_It_Makes() { - await Codes(new PlanetModel { Name = "Earth", Moons = 1, }).Should().BeEquivalentTo(Array.Empty()); - await Codes(new PlanetModel { Name = "", Moons = 200, Star = "", }) + await ( await Codes(new PlanetModel { Name = "Earth", Moons = 1, }) ).Should().BeEquivalentTo(Array.Empty()); + await ( await Codes(new PlanetModel { Name = "", Moons = 200, Star = "", }) ) .Should() .BeEquivalentTo(["Name:NotEmpty", "Moons:LessThan", "Star:StarIsNotThePlanet"]); } diff --git a/test/Validation.Tests/FunctionValidatorTests.cs b/test/Validation.Tests/FunctionValidatorTests.cs index cd80baa664..c85e109c44 100644 --- a/test/Validation.Tests/FunctionValidatorTests.cs +++ b/test/Validation.Tests/FunctionValidatorTests.cs @@ -11,24 +11,25 @@ public class FunctionValidatorTests private static ServiceProvider Services() => new ServiceCollection().AddSingleton().AddSingleton(TimeProvider.System).AddValidationTestsValidators().BuildServiceProvider(true); - private static string[] Codes(BuildLauncher.Request request) + private static async Task Codes(BuildLauncher.Request request) { - using var services = Services(); - using var scope = services.CreateScope(); - return [.. scope.ServiceProvider.GetRequiredService>().Validate(request).Failures.Select(z => z.Path + ":" + z.Code),]; + await using var services = Services(); + await using var scope = services.CreateAsyncScope(); + var result = await scope.ServiceProvider.GetRequiredService>().ValidateAsync(request); + return [.. result.Failures.Select(z => z.Path + ":" + z.Code),]; } [Test] - public async Task Should_Accept_A_Value_That_Meets_Its_Rules() => await Codes(new()).Should().BeEquivalentTo(Array.Empty()); + public async Task Should_Accept_A_Value_That_Meets_Its_Rules() => await ( await Codes(new()) ).Should().BeEquivalentTo(Array.Empty()); [Test] - public async Task Should_Merge_The_Attributes_With_The_Function() => await Codes(new() { Name = "", }).Should().BeEquivalentTo(["Name:NotEmpty", "Name:Matches"]); + public async Task Should_Merge_The_Attributes_With_The_Function() => await ( await Codes(new() { Name = "", }) ).Should().BeEquivalentTo(["Name:NotEmpty", "Name:Matches"]); [Test] public async Task Should_Stop_A_Chain_At_Its_First_Failure() { - await Codes(new() { Name = "falcon heavy", }).Should().BeEquivalentTo(["Name:TooLong"]); - await Codes(new() { Name = "falcon", }).Should().BeEquivalentTo(["Name:Matches"]); + await ( await Codes(new() { Name = "falcon heavy", }) ).Should().BeEquivalentTo(["Name:TooLong"]); + await ( await Codes(new() { Name = "falcon", }) ).Should().BeEquivalentTo(["Name:Matches"]); } [Test] @@ -36,9 +37,9 @@ public async Task Should_Use_The_Message_Code_Severity_And_Name_Of_The_Chain() { using var services = Services(); using var scope = services.CreateScope(); - var result = scope - .ServiceProvider.GetRequiredService>() - .Validate(new() { Name = "Falcon Heavy", Serial = "nope", Seats = 3, }); + var result = await scope + .ServiceProvider.GetRequiredService>() + .ValidateAsync(new() { Name = "Falcon Heavy", Serial = "nope", Seats = 3, }); await result.Failures.Length.Should().BeEqualTo(3); await result.Failures[0].Message.Should().BeEqualTo("Name is over 10"); @@ -50,46 +51,42 @@ public async Task Should_Use_The_Message_Code_Severity_And_Name_Of_The_Chain() [Test] public async Task Should_Apply_Rules_Only_Under_Their_Condition() { - await Codes(new() { Kind = LauncherKind.Crewed, }).Should().BeEquivalentTo(["Seats:NotNull"]); - await Codes(new() { Kind = LauncherKind.Crewed, Seats = 9, }).Should().BeEquivalentTo(["Seats:InclusiveBetween"]); - await Codes(new() { Kind = LauncherKind.Crewed, Seats = 4, Engines = [], }).Should().BeEquivalentTo(Array.Empty()); - await Codes(new() { Engines = [], }).Should().BeEquivalentTo(["Engines:MinLength"]); + await ( await Codes(new() { Kind = LauncherKind.Crewed, }) ).Should().BeEquivalentTo(["Seats:NotNull"]); + await ( await Codes(new() { Kind = LauncherKind.Crewed, Seats = 9, }) ).Should().BeEquivalentTo(["Seats:InclusiveBetween"]); + await ( await Codes(new() { Kind = LauncherKind.Crewed, Seats = 4, Engines = [], }) ).Should().BeEquivalentTo(Array.Empty()); + await ( await Codes(new() { Engines = [], }) ).Should().BeEquivalentTo(["Engines:MinLength"]); } [Test] public async Task Should_Compare_With_Another_Member_And_With_A_Service() { - await Codes(new() { Launched = new(2019, 1, 1), }).Should().BeEquivalentTo(["Launched:GreaterThanOrEqualTo"]); - await Codes(new() { Built = new(2999, 1, 1), }).Should().BeEquivalentTo(["Built:LessThanOrEqualTo"]); + await ( await Codes(new() { Launched = new(2019, 1, 1), }) ).Should().BeEquivalentTo(["Launched:GreaterThanOrEqualTo"]); + await ( await Codes(new() { Built = new(2999, 1, 1), }) ).Should().BeEquivalentTo(["Built:LessThanOrEqualTo"]); } [Test] public async Task Should_Call_A_Method_A_Lambda_And_A_Rule_Over_The_Whole_Value() { - await Codes(new() { Budget = 15, Spent = 20, }).Should().BeEquivalentTo(["Budget:Must", "Budget:Overspent"]); - await Codes(new() { Budget = 10, Spent = 30, }).Should().BeEquivalentTo(["Budget:Overspent", ":WayOverspent"]); + await ( await Codes(new() { Budget = 15, Spent = 20, }) ).Should().BeEquivalentTo(["Budget:Must", "Budget:Overspent"]); + await ( await Codes(new() { Budget = 10, Spent = 30, }) ).Should().BeEquivalentTo(["Budget:Overspent", ":WayOverspent"]); } [Test] public async Task Should_Validate_Each_Item_Under_Its_Index() { - await Codes(new() { Tags = ["ok", "", "too long"], }).Should().BeEquivalentTo(["Tags:MaxLength", "Tags[1]:NotEmpty", "Tags[2]:MaxLength"]); - await Codes(new() { Engines = [new("Merlin", 1), new("Unknown", 0),], }) + await ( await Codes(new() { Tags = ["ok", "", "too long"], }) ).Should().BeEquivalentTo(["Tags:MaxLength", "Tags[1]:NotEmpty", "Tags[2]:MaxLength"]); + await ( await Codes(new() { Engines = [new("Merlin", 1), new("Unknown", 0),], }) ) .Should() .BeEquivalentTo(["Engines[1].Thrust:GreaterThan", "Engines[1].Name:UnknownEngine"]); } [Test] - public async Task Should_Validate_Asynchronously_When_A_Rule_Waits() + public async Task Should_Wait_For_A_Rule_That_Waits() { using var services = Services(); using var scope = services.CreateScope(); - var validator = scope.ServiceProvider.GetRequiredService>(); + var validator = scope.ServiceProvider.GetRequiredService>(); - // LPAD3002 is what stops an application asking for it; here it is asked for to prove it isn't there. -#pragma warning disable LPAD3002 - await scope.ServiceProvider.GetService>().Should().BeNull(); -#pragma warning restore LPAD3002 await ( await validator.ValidateAsync(new("AB-1", "LC-39A")) ).IsValid.Should().BeTrue(); var taken = await validator.ValidateAsync(new("TAKEN", "LC-40")); @@ -106,7 +103,7 @@ public async Task Should_Pass_The_Cancellation_Token_To_A_Rule_That_Waits() { using var services = Services(); using var scope = services.CreateScope(); - var validator = scope.ServiceProvider.GetRequiredService>(); + var validator = scope.ServiceProvider.GetRequiredService>(); using var cancelled = new CancellationTokenSource(); await cancelled.CancelAsync(); @@ -114,17 +111,12 @@ public async Task Should_Pass_The_Cancellation_Token_To_A_Rule_That_Waits() } [Test] - public async Task Should_Be_Asynchronous_When_A_Nested_Member_Is() + public async Task Should_Wait_For_The_Rules_Of_A_Nested_Member() { using var services = Services(); using var scope = services.CreateScope(); - // LPAD3002 is what stops an application asking for it; here it is asked for to prove it isn't there. -#pragma warning disable LPAD3002 - await scope.ServiceProvider.GetService>().Should().BeNull(); -#pragma warning restore LPAD3002 - - var result = await scope.ServiceProvider.GetRequiredService>().ValidateAsync(new("", new("TAKEN", "LC-39A"))); + var result = await scope.ServiceProvider.GetRequiredService>().ValidateAsync(new("", new("TAKEN", "LC-39A"))); await result.Failures.Select(z => z.Path + ":" + z.Code).ToArray().Should().BeEquivalentTo(["Name:NotEmpty", "Booking.Serial:Taken"]); } diff --git a/test/Validation.Tests/GeneratedValidatorTests.cs b/test/Validation.Tests/GeneratedValidatorTests.cs index 202de177dd..04051abcad 100644 --- a/test/Validation.Tests/GeneratedValidatorTests.cs +++ b/test/Validation.Tests/GeneratedValidatorTests.cs @@ -16,57 +16,58 @@ private static ServiceProvider Services(Action? configure = return services.BuildServiceProvider(); } - private static string[] Codes(T value) + private static async Task Codes(T value) { - using var services = Services(); - return [.. services.GetRequiredService>().Validate(value).Failures.Select(z => z.Path + ":" + z.Code),]; + await using var services = Services(); + var result = await services.GetRequiredService>().ValidateAsync(value); + return [.. result.Failures.Select(z => z.Path + ":" + z.Code),]; } [Test] public async Task Should_Accept_A_Value_That_Meets_Its_Rules() { - await Codes(new Launcher()).Should().BeEquivalentTo(Array.Empty()); - await Codes(new Account()).Should().BeEquivalentTo(Array.Empty()); + await ( await Codes(new Launcher()) ).Should().BeEquivalentTo(Array.Empty()); + await ( await Codes(new Account()) ).Should().BeEquivalentTo(Array.Empty()); } [Test] public async Task Should_Report_Every_Rule_A_Member_Does_Not_Meet() { - await Codes(new Launcher { Name = "ab", }).Should().BeEquivalentTo(["Name:MinLength", "Name:Matches"]); - await Codes(new Launcher { Name = null, }).Should().BeEquivalentTo(["Name:NotEmpty"]); - await Codes(new Launcher { Kind = (LauncherKind)9, Engines = 0, Price = -1.234m, }) + await ( await Codes(new Launcher { Name = "ab", }) ).Should().BeEquivalentTo(["Name:MinLength", "Name:Matches"]); + await ( await Codes(new Launcher { Name = null, }) ).Should().BeEquivalentTo(["Name:NotEmpty"]); + await ( await Codes(new Launcher { Kind = (LauncherKind)9, Engines = 0, Price = -1.234m, }) ) .Should() .BeEquivalentTo(["Kind:IsInEnum", "Engines:InclusiveBetween", "Price:GreaterThanOrEqualTo", "Price:PrecisionScale"]); - await Codes(new Launcher { Tags = ["a", "b", "c"], Fins = 4, }).Should().BeEquivalentTo(["Fins:Must", "Tags:MaxLength"]); + await ( await Codes(new Launcher { Tags = ["a", "b", "c"], Fins = 4, }) ).Should().BeEquivalentTo(["Fins:Must", "Tags:MaxLength"]); } [Test] public async Task Should_Parse_A_Constant_As_The_Type_Of_The_Member() { - await Codes(new Launcher { Built = new(1999, 12, 31), }).Should().BeEquivalentTo(["Built:GreaterThanOrEqualTo"]); - await Codes(new Launcher { Built = default, }).Should().BeEquivalentTo(["Built:NotDefault", "Built:GreaterThanOrEqualTo"]); + await ( await Codes(new Launcher { Built = new(1999, 12, 31), }) ).Should().BeEquivalentTo(["Built:GreaterThanOrEqualTo"]); + await ( await Codes(new Launcher { Built = default, }) ).Should().BeEquivalentTo(["Built:NotDefault", "Built:GreaterThanOrEqualTo"]); } [Test] public async Task Should_Compare_A_Member_With_Another() { - await Codes(new Launcher { Launched = new(2019, 1, 1), }).Should().BeEquivalentTo(["Launched:GreaterThanOrEqualTo"]); - await Codes(new Launcher { Launched = new(2021, 1, 1), }).Should().BeEquivalentTo(Array.Empty()); - await Codes(new Account { Password = "a", Confirmation = "b", }).Should().BeEquivalentTo(["Confirmation:Equal"]); + await ( await Codes(new Launcher { Launched = new(2019, 1, 1), }) ).Should().BeEquivalentTo(["Launched:GreaterThanOrEqualTo"]); + await ( await Codes(new Launcher { Launched = new(2021, 1, 1), }) ).Should().BeEquivalentTo(Array.Empty()); + await ( await Codes(new Account { Password = "a", Confirmation = "b", }) ).Should().BeEquivalentTo(["Confirmation:Equal"]); } [Test] public async Task Should_Call_A_Method_Of_The_Value() { - await Codes(new Launcher { Name = "Atlas", Nickname = "Atlas V", }).Should().BeEquivalentTo(["Nickname:Must"]); - await Codes(new Launcher { Name = "Atlas", Nickname = "At", }).Should().BeEquivalentTo(Array.Empty()); + await ( await Codes(new Launcher { Name = "Atlas", Nickname = "Atlas V", }) ).Should().BeEquivalentTo(["Nickname:Must"]); + await ( await Codes(new Launcher { Name = "Atlas", Nickname = "At", }) ).Should().BeEquivalentTo(Array.Empty()); } [Test] public async Task Should_Use_The_Message_Code_And_Severity_Of_The_Attribute() { using var services = Services(); - var result = services.GetRequiredService>().Validate(new() { Name = "Falcon Heavy", Seats = 9, }); + var result = await services.GetRequiredService>().ValidateAsync(new() { Name = "Falcon Heavy", Seats = 9, }); await result.IsValid.Should().BeFalse(); await result.Failures.Length.Should().BeEqualTo(2); @@ -75,7 +76,7 @@ public async Task Should_Use_The_Message_Code_And_Severity_Of_The_Attribute() await result.Failures[1].Severity.Should().BeEqualTo(ValidationSeverity.Warning); await result.Failures[1].Message.Should().BeEqualTo("Seats must be greater than 0 and less than 8"); - var warning = services.GetRequiredService>().Validate(new() { Seats = 9, }); + var warning = await services.GetRequiredService>().ValidateAsync(new() { Seats = 9, }); await warning.IsValid.Should().BeTrue(); await warning.Failures.Length.Should().BeEqualTo(1); @@ -86,8 +87,8 @@ public async Task Should_Validate_Nested_Values_And_Items_Under_Their_Path() { var rocket = new Launcher { Crew = new("", new("", new("Ada"))), Stages = [new(1), new(0), new(-1),], }; - await Codes(rocket).Should().BeEquivalentTo(["Crew.Captain:NotEmpty", "Crew.Backup.Captain:NotEmpty", "Stages[1].Thrust:GreaterThan", "Stages[2].Thrust:GreaterThan"]); - await Codes(new Launcher { Stages = [], }).Should().BeEquivalentTo(["Stages:NotEmpty"]); + await ( await Codes(rocket) ).Should().BeEquivalentTo(["Crew.Captain:NotEmpty", "Crew.Backup.Captain:NotEmpty", "Stages[1].Thrust:GreaterThan", "Stages[2].Thrust:GreaterThan"]); + await ( await Codes(new Launcher { Stages = [], }) ).Should().BeEquivalentTo(["Stages:NotEmpty"]); } [Test] @@ -105,7 +106,7 @@ public async Task Should_Compile_The_DataAnnotations_Attributes() Roles = [], }; - await Codes(account) + await ( await Codes(account) ) .Should() .BeEquivalentTo( [ @@ -113,7 +114,7 @@ await Codes(account) "Roles:MinLength", ] ); - await Codes(new Account { UserName = " ", Share = 1, Pin = "1234", Roles = ["a", "b", "c", "d"], }) + await ( await Codes(new Account { UserName = " ", Share = 1, Pin = "1234", Roles = ["a", "b", "c", "d"], }) ) .Should() .BeEquivalentTo(["UserName:NotEmpty", "UserName:Length", "Roles:MaxLength"]); } @@ -122,27 +123,41 @@ await Codes(new Account { UserName = " ", Share = 1, Pin = "1234", Roles = ["a", public async Task Should_Fill_A_DataAnnotations_Message_By_Position() { using var services = Services(); - var result = services.GetRequiredService>().Validate(new() { UserName = "a", }); + var result = await services.GetRequiredService>().ValidateAsync(new() { UserName = "a", }); await result.Failures[0].Message.Should().BeEqualTo("UserName must have 3 to 20 characters"); } [Test] - public async Task Should_Register_The_Validator_As_Both_Interfaces() + public async Task Should_Answer_At_Once_When_No_Rule_Waits() { using var services = Services(); - var sync = services.GetRequiredService>(); - var async = services.GetRequiredService>(); + var validator = services.GetRequiredService>(); + + var pending = validator.ValidateAsync(new() { Name = "", }); + + await pending.IsCompletedSuccessfully.Should().BeTrue(); + await ( await pending ).IsInvalid.Should().BeTrue(); + await services.GetRequiredService>().Should().BeSameReferenceAs(validator); + } + + [Test] + public async Task Should_Not_Run_The_Rules_Once_Cancelled() + { + using var services = Services(); + using var cancelled = new CancellationTokenSource(); + await cancelled.CancelAsync(); + + var pending = services.GetRequiredService>().ValidateAsync(new() { Name = "", }, cancelled.Token); - await async.Should().BeSameReferenceAs(sync); - await ( await async.ValidateAsync(new() { Name = "", }) ).IsInvalid.Should().BeTrue(); + await pending.IsCanceled.Should().BeTrue(); } [Test] public async Task Should_Take_Messages_From_The_Provider_Registered() { using var services = Services(z => z.AddSingleton()); - var result = services.GetRequiredService>().Validate(new() { Name = "", }); + var result = await services.GetRequiredService>().ValidateAsync(new() { Name = "", }); await result.Failures[0].Message.Should().BeEqualTo("Name MUST NOT BE EMPTY"); } @@ -159,14 +174,14 @@ public async Task Should_Validate_Options() [Test] public async Task Should_Not_Accept_Null() => - await Assert.That(() => new LauncherGeneratedValidator().Validate(null!)).Throws(); + await Assert.That(() => new LauncherGeneratedValidator().ValidateAsync(null!).AsTask()).Throws(); [Test] public async Task Should_Say_Which_Validator_Is_Missing() { - var exception = await Assert.That(() => new LauncherGeneratedValidator().Validate(new() { Crew = new("Ada"), })).Throws(); + var exception = await Assert.That(async () => await new LauncherGeneratedValidator().ValidateAsync(new() { Crew = new("Ada"), })).Throws(); - await exception!.Message.Should().Contain("IValidate"); + await exception!.Message.Should().Contain("IValidator"); } private sealed class Shouting : IValidationMessageProvider diff --git a/test/Validation.Tests/Types/Composition.cs b/test/Validation.Tests/Types/Composition.cs index 4c6a98fc0e..c9d23b1809 100644 --- a/test/Validation.Tests/Types/Composition.cs +++ b/test/Validation.Tests/Types/Composition.cs @@ -67,7 +67,7 @@ public sealed partial class ShippingAddress : IHasName private static void Validate(IValidationBuilder v) => v.Ensure(x => x.Phone).NotEmpty(); } -internal sealed partial class ShippingAddressValidator(ICatalog catalog) : IValidator +internal sealed partial class ShippingAddressValidator(ICatalog catalog) : IValidatorDefinition { public void Validate(IValidationBuilder v) => v.Ensure(x => x).Must(x => !x.Express || catalog.IsKnown(x.Name ?? "")).WithCode("ExpressNeedsAKnownName"); diff --git a/test/Validation.Tests/Types/Functions.cs b/test/Validation.Tests/Types/Functions.cs index c925798276..8c453648bd 100644 --- a/test/Validation.Tests/Types/Functions.cs +++ b/test/Validation.Tests/Types/Functions.cs @@ -88,7 +88,7 @@ private static void Validate(IValidationBuilder v, ICatalog catalog, Ti public sealed record Booking(string Serial, string? Pad); /// A class validator: its dependencies are its constructor's. -internal sealed partial class BookingValidator(ICatalog catalog) : IValidator +internal sealed partial class BookingValidator(ICatalog catalog) : IValidatorDefinition { private readonly string _pad = "LC-39A"; From aebbcd41f1f11d02036fee376b693c8a420fcb31 Mon Sep 17 00:00:00 2001 From: David Driscoll Date: Fri, 4 Dec 2026 00:24:56 -0500 Subject: [PATCH 2/2] Validation: a validator is given the validators of its members The validator of a member validated with its own, and of the type a [Mutable] view model is of, is a constructor parameter. Where making it takes the validator being made (a type with a member of its own type, two types that validate each other) the generator finds the cycle and that validator alone is asked of an IServiceProvider when first used. Co-Authored-By: Claude Fable 5.2 --- AGENTS.md | 2 +- docs/design/validation.md | 6 +- .../Model/FunctionReader.cs | 2 + src/Validation.Analyzers/Model/LinkReader.cs | 93 ++++++++++-- src/Validation.Analyzers/Model/Models.cs | 10 +- src/Validation.Analyzers/Model/Resolution.cs | 74 ++++++++++ src/Validation.Analyzers/Model/RuleReader.cs | 2 + src/Validation.Analyzers/ValidatorEmitter.cs | 36 ++--- .../ValidatorGeneratorTests.cs | 16 +++ ...lanetModelGeneratedValidator.g.verified.cs | 15 +- ...d#LauncherGeneratedValidator.g.verified.cs | 15 +- ...e.ManifestGeneratedValidator.g.verified.cs | 17 +-- ...e.ScheduleGeneratedValidator.g.verified.cs | 15 +- ...e.LauncherGeneratedValidator.g.verified.cs | 41 +++--- ...Sample.PadGeneratedValidator.g.verified.cs | 115 +++++++++++++++ ...mple.TowerGeneratedValidator.g.verified.cs | 136 ++++++++++++++++++ .../GeneratedValidatorTests.cs | 22 ++- 17 files changed, 515 insertions(+), 102 deletions(-) create mode 100644 test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.PadGeneratedValidator.g.verified.cs create mode 100644 test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.TowerGeneratedValidator.g.verified.cs diff --git a/AGENTS.md b/AGENTS.md index c64bdf3b80..5ec0cee756 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -37,7 +37,7 @@ The conversion is done: no project references `Rocket.Surgery.Conventions` or th - `src/Validation.Analyzers` (its own package, an exception to ADR-0004 as Primitives' is) holds the generator, the analyzers (LPAD3001 and up; LPAD3101 and up for the generator) and the code fixes. `ValidatorGenerator` needs no marker: for every class, struct or record with a rule attribute on a member (LaunchPad's, or the `System.ComponentModel.DataAnnotations` ones it compiles) it writes `{Type}GeneratedValidator` beside the type (`{Type}Validator` is what an application names its class validator), with one public static rule method per member (`Ensure{Member}`) and the rule manifest (`[GeneratedValidator]`, `[GeneratedRule]`). `Model/RuleReader.cs` binds each rule's call as C# would (a speculative binding of the method the attribute's `[ValidationRule]` names), so the overload, its code and message and the placeholders' names come from the compiler. - A **function validator** (`static void Validate(IValidationBuilder v, ...dependencies)`, in any partial type) and a **class validator** (a partial class that implements `IValidatorDefinition`) are found by shape and read by `Model/FunctionReader.cs`. The body may only call the builder, and never runs: each chain becomes part of a rule method written into the type that contains it (`Validate{Type}_{Member}`, in a file that repeats the usings of the source file), and each lambda is copied as a local function of that method, so what it names resolves as it does where it was written. The generated methods name the function (`DeclaredBy = nameof(Validate)`): nothing calls a private `Validate`, and without that reference `dotnet format` deletes it as unused. `MergedModel` (in `ValidatorGenerator.cs`) puts the attributes, functions and classes of one type into its one validator, attributes first. - Validation is asynchronous: there is no synchronous interface. The validator of a type none of whose rules waits (no `MustAsync`, no member validated with its own validator, not a `[Mutable]` view model) answers `ValidateAsync` with a completed `ValueTask`, and only such a validator, when it is a singleton, is an `IValidateOptions` too. A validator that takes services, or validates a member with that member's validator, is registered scoped; the others are singletons. - - A member is validated with its own type's validator only where it says `[ValidateNested]` (or `[ValidateWith]`); LPAD3001 warns where a type with rules has a member whose type has rules and that says neither that nor `[SkipValidation]`. The nested validator is asked of the `IServiceProvider` the validator is made with. + - A member is validated with its own type's validator only where it says `[ValidateNested]` (or `[ValidateWith]`); LPAD3001 warns where a type with rules has a member whose type has rules and that says neither that nor `[SkipValidation]`. The nested validator (the `IValidator` registered for the member's type) is given to the validator's constructor; only where making it takes this validator (a type with a member of its own type, two types that validate each other, `Resolver.Cycles`) is it asked of an `IServiceProvider` when first used. - In a project that references the dependency injection abstractions, the generator writes `Add{AssemblyName}Validators()` (`LaunchPadValidators.g.cs`), which registers the assembly's validators and calls the same method of each referenced assembly (found by `[assembly: ValidatorAssembly]`); with Microsoft.Extensions.Options, a singleton validator of a class is an `IValidateOptions` too. - A validator holds only the rules declared for its type. Each has a public rule method for every member with rules (`Ensure{Member}`, `Ensure_Value` for the whole value; static unless it takes a service), a `ValidateDeclared` that runs them, and is an `IValidateMembers` (one member at a time, which a form field needs). These methods and their `[GeneratedRule]` are the **rule manifest** the generator reads from referenced assemblies (`Model/LinkReader.cs`); `Model/Resolution.cs` decides, once every model of the compilation is in, which other validators each one runs. - The rules of a base class or an interface stay in that type's validator, and the validator of every type that derives from it calls its `ValidateDeclared`; a type with no rules of its own still gets a validator when something it derives from has one. `[InheritFrom]` and `Include()` carry rules member by member (LPAD3112 where a member's rules can't be carried), and the validator of a `[Mutable]` view model validates the whole value as `T` and one member with `T`'s rule methods. Which members `[InheritFrom]` and `[Mutable]` write is decided in `src/Shared/GeneratedMembers.cs`, linked into both analyzer assemblies: the validation generator can't see what those generators write. diff --git a/docs/design/validation.md b/docs/design/validation.md index f10cc263b3..ba63049b1a 100644 --- a/docs/design/validation.md +++ b/docs/design/validation.md @@ -157,14 +157,14 @@ Where the code so far differs from the text above: - **A validator holds only the rules declared for its type** in its assembly. Each has a rule method for every member with rules (`Ensure{Member}`, and `Ensure_Value` for the rules about the whole value), which checks that member's attributes, then the rules it carries, then calls the rule methods of the functions and classes; `ValidateDeclared` runs them all, and `Validate` runs the `ValidateDeclared` of every validator of what the type is, then its own. A rule method is static unless it takes a service, a class validator or the validator of the member. These methods, with their `[GeneratedRule]`, are the rule manifest: the generator reads them from a referenced assembly's validators, which it finds by the name of the type (`{Type}GeneratedValidator`, in the assembly that declares the type) and by `[assembly: ContributedValidator]`. - **Base classes and interfaces.** A type's validator calls the validator of each base class and each interface that has rules, in this compilation or a referenced assembly. A type with no rules of its own gets a validator when something it derives from has one. An interface, or an abstract class, with rules has a validator too (`IValidator`). The attributes of a base class's members are read into the validator of the first type down the chain that has a validator: a base class this compilation can't write one for (a generic one, one of an assembly that doesn't run the generator) has its attributes read by each type that derives from it. - **`[InheritFrom]` and `Include()`** carry rules member by member: the rule method of a copied member calls the rule method `TOther`'s validator has for it. Where that method takes services, the validator takes `TOther`'s validator, which the registration adds; where it waits, the type is asynchronous only. A member's rules are not carried when they read the whole `TOther` (a `Must((x, value) => ...)`, a `When`), compare it with a member that was not copied, or the member's type differs: LPAD3112, a warning, says which. The generator works out which members `[InheritFrom]` copies with the code that copies them (`src/Shared/GeneratedMembers.cs`). `Include` takes the members the two types share by name and type. -- **`[Mutable]`**: the view model's validator validates the whole value as `T` (`ToImmutable()`, with the `IValidator` of the service provider, which it awaits), then the view model's own rules. `[Mutable]`'s generator still writes the ZeroAlloc.Validation validator beside it until that library goes (phase 6). +- **`[Mutable]`**: the view model's validator validates the whole value as `T` (`ToImmutable()`, with the `IValidator` its constructor is given, which it awaits), then the view model's own rules. `[Mutable]`'s generator still writes the ZeroAlloc.Validation validator beside it until that library goes (phase 6). - **`IValidateMembers`** is the per-member entry point, and every generated validator is one, not only a view model's: `TryValidateMember(value, member, out result)` checks the rules of one member, from every validator of what the type is, and returns `false` when one of them waits; `ValidateMemberAsync` checks them either way. A view model checks the rules `T` and its base classes and interfaces have for the member with the view model's value, without making a `T`; a rule that reads the whole `T` is left to the validation of the whole view model. - **Rules for a type of another assembly.** A `Validate` function may declare rules for any class, struct, record or interface the compilation can reach. For a type another assembly declares, the validator is `{Type}In{Assembly}GeneratedValidator`, in the type's namespace; it runs the validators the referenced assemblies have for the type, then its own rules, and the registration replaces what is registered for the type with it (`RemoveAll`, then add), so the rules of each assembly run once. `[assembly: ContributedValidator]` tells the assemblies that reference this one about it. - **String rules** (`EmailAddress`, `Url`, `Matches`) are declared for `IEquatable`, and the length rules for `IEnumerable`, so the rules after them still see a `string` member as `string` and a `string?` one as `string?`. `IMemberRules` is covariant, so a rule an application declares for a base type applies to the members of derived ones. -- **One interface, asynchronous.** `IValidator` has `ValidateAsync` and nothing else; the synchronous `IValidate`, LPAD3002 and its fix, and LPAD3113 are gone. The class shape that declares rules is `IValidatorDefinition`. A validator none of whose rules waits writes `ValidateAsync` without a state machine: it returns a completed `ValueTask`, a cancelled one if the token already is, and a faulted one if a rule throws. A member validated with its own validator, and the whole value of a `[Mutable]` view model, go through the `IValidator` of the service provider, so a type that has either always awaits. `IValidateMembers.TryValidateMember` still answers at once for a member whose rules don't wait. +- **One interface, asynchronous.** `IValidator` has `ValidateAsync` and nothing else; the synchronous `IValidate`, LPAD3002 and its fix, and LPAD3113 are gone. The class shape that declares rules is `IValidatorDefinition`. A validator none of whose rules waits writes `ValidateAsync` without a state machine: it returns a completed `ValueTask`, a cancelled one if the token already is, and a faulted one if a rule throws. A member validated with its own validator, and the whole value of a `[Mutable]` view model, go through the `IValidator` registered for the type, so a type that has either always awaits. `IValidateMembers.TryValidateMember` still answers at once for a member whose rules don't wait. - **Registration** is `Add{AssemblyName}Validators()`, public, one per assembly, and it calls the same method of each referenced assembly. Each validator is registered as the type's `IValidator` and its `IValidateMembers`. An `internal AddLaunchPadValidators()` in every assembly would be ambiguous in any project that sees another's internals (`InternalsVisibleTo`), which this repository's tests do. - **Options**: there is no adapter. Each validator of a class implements `IValidateOptions` itself and is registered as one, so an options class with rules is validated wherever it is used. -- **Nested validators** are asked of the `IServiceProvider` the validator is made with, when first needed, and not injected: a type can then be validated inside itself, and what is asked for is the composed validator the application registered. +- **Nested validators** are given to the validator's constructor, as the `IValidator` registered for the member's type, so what is given is the composed validator the application registered. A validator can't be given one that is made with it: for a type with a member of its own type, or two types that validate each other, the generator finds the cycle (through the validators of this compilation, and the constructors of those of referenced assemblies) and that validator alone is asked of an `IServiceProvider` when it is first used. The same holds for the validator of the type a `[Mutable]` view model is of, and for one that can't be named in a public constructor. - **A pattern in an attribute** (`[Matches]`, `[RegularExpression]`) is an interpreted `Regex` held by the validator: the regular expression generator can't see what another generator writes. A `Validate` function can pass a `[GeneratedRegex]` member. - **DataAnnotations** compiled so far: `[Required]`, `[StringLength]`, `[MaxLength]`, `[MinLength]`, `[Length]`, `[Range]` of numbers, `[RegularExpression]`, `[EmailAddress]`, `[Url]` and `[Compare]`. `[Phone]`, `[CreditCard]`, `[Base64String]`, `[AllowedValues]` and `[DeniedValues]` are reported (LPAD3104, a warning) until they have rules of their own. - **`[Must]`** names a method of the validated type, static or not, that takes the member's value and returns `bool`; it must be public or internal, because the validator is a class of its own. An asynchronous one is an error: declare it with `MustAsync` in a function. diff --git a/src/Validation.Analyzers/Model/FunctionReader.cs b/src/Validation.Analyzers/Model/FunctionReader.cs index 10cdee65c7..987bcc5705 100644 --- a/src/Validation.Analyzers/Model/FunctionReader.cs +++ b/src/Validation.Analyzers/Model/FunctionReader.cs @@ -622,6 +622,8 @@ private void ReadNested(InvocationExpressionSyntax call, IMethodSymbol symbol, s into.Nested = new( target.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), with?.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), + TargetReader.IsPublic(with ?? target), + ReferencedValidators.For(_model.Compilation).Reaches(target, with), item is not null, ValidationSymbols.CanBeNull(memberType), item is not null && ValidationSymbols.CanBeNull(item) diff --git a/src/Validation.Analyzers/Model/LinkReader.cs b/src/Validation.Analyzers/Model/LinkReader.cs index 7856351c3f..45be3facf6 100644 --- a/src/Validation.Analyzers/Model/LinkReader.cs +++ b/src/Validation.Analyzers/Model/LinkReader.cs @@ -44,6 +44,8 @@ public static LinkModel Read(INamedTypeSymbol type, Compilation compilation) mutable = new( Key(target), self.Referenced.Length > 0, + TargetReader.IsPublic(target), + validators.Reaches(target, null), sources.ToImmutable(), CopiedOf(MutableMembers.ViewModelProperties(target, compilation)) ); @@ -163,27 +165,93 @@ private ReferencedValidators(Compilation compilation) private static bool ReferencesRuntime(IAssemblySymbol assembly) => assembly.Modules.Any(static module => module.ReferencedAssemblies.Any(static z => z.Name == ValidationSymbols.RuntimeNamespace)); - /// A type and the validators referenced assemblies wrote for it. - public SourceLinkModel Link(INamedTypeSymbol type) + // The validators referenced assemblies have for a type: the one of the assembly that declares it, then those others contributed. + private IEnumerable ValidatorsOf(INamedTypeSymbol type) { - lock (_links) + if (_validating.Contains(type.ContainingAssembly) && !TargetReader.IsGeneric(type)) { - if (_links.TryGetValue(type, out var existing)) return existing; - var sources = new List(); - if (_validating.Contains(type.ContainingAssembly) && !TargetReader.IsGeneric(type)) + var @namespace = TargetReader.NamespaceOf(type); + var name = ( @namespace.Length == 0 ? "" : @namespace + "." ) + TargetReader.ValidatorName(type); + if (type.ContainingAssembly.GetTypeByMetadataName(name) is { } own) yield return own; + } + + if (!_contributed.TryGetValue(type, out var contributed)) yield break; + foreach (var validator in contributed) + { + yield return validator; + } + } + + /// + /// The types whose validators the validator of a member is made with, and theirs in turn, as far as the constructors of the + /// validators of referenced assemblies say: what tells a validator it can't be given one that needs it. + /// + public EquatableArray Reaches(INamedTypeSymbol target, INamedTypeSymbol? with) => ReachesFrom(with is null ? target : null, with); + + private EquatableArray ReachesFrom(INamedTypeSymbol? target, INamedTypeSymbol? validator) + { + var types = new HashSet(SymbolEqualityComparer.Default); + var validators = new HashSet(SymbolEqualityComparer.Default); + var names = new SortedSet(StringComparer.Ordinal); + if (target is not null) Type(target); + if (validator is not null) Validator(validator); + return names.ToEquatableArray(); + + void Type(INamedTypeSymbol type) + { + if (!types.Add(type)) return; + foreach (var found in ValidatorsOf(type)) { - var @namespace = TargetReader.NamespaceOf(type); - var name = ( @namespace.Length == 0 ? "" : @namespace + "." ) + TargetReader.ValidatorName(type); - if (type.ContainingAssembly.GetTypeByMetadataName(name) is { } own && Read(type, own) is { } read) sources.Add(read); + Validator(found); } + } - if (_contributed.TryGetValue(type, out var contributed)) + void Validator(INamedTypeSymbol found) + { + if (!validators.Add(found)) return; + foreach (var parameter in found.InstanceConstructors.SelectMany(static z => z.Parameters)) { - foreach (var validator in contributed) + if (parameter.Type is not INamedTypeSymbol given) continue; + if (given is { TypeArguments: [INamedTypeSymbol of] } && ValidationSymbols.Is(given.OriginalDefinition, ValidationSymbols.RuntimeNamespace, "IValidator")) + { + names.Add(LinkReader.Key(of)); + Type(of); + } + else if (Validated(given) is { } validated) { - if (Read(type, validator) is { } read) sources.Add(read); + names.Add(LinkReader.Key(validated)); + Validator(given); } } + } + } + + // The type a generated validator validates. + private static INamedTypeSymbol? Validated(INamedTypeSymbol validator) + { + foreach (var attribute in validator.GetAttributes()) + { + if (ValidationSymbols.Is(attribute.AttributeClass, ValidationSymbols.RuntimeNamespace, "GeneratedValidatorAttribute") + && attribute.ConstructorArguments is [{ Value: INamedTypeSymbol type }]) + { + return type; + } + } + + return null; + } + + /// A type and the validators referenced assemblies wrote for it. + public SourceLinkModel Link(INamedTypeSymbol type) + { + lock (_links) + { + if (_links.TryGetValue(type, out var existing)) return existing; + var sources = new List(); + foreach (var validator in ValidatorsOf(type)) + { + if (Read(type, validator) is { } read) sources.Add(read); + } var link = new SourceLinkModel(LinkReader.Key(type), sources.ToEquatableArray()); _links.Add(type, link); @@ -247,6 +315,7 @@ public SourceLinkModel Link(INamedTypeSymbol type) TargetReader.IsPublic(validator), declared is not null, declared is { ReturnsVoid: false }, + ReachesFrom(null, validator), members.ToEquatableArray() ); } diff --git a/src/Validation.Analyzers/Model/Models.cs b/src/Validation.Analyzers/Model/Models.cs index 599d90611e..9de675deb7 100644 --- a/src/Validation.Analyzers/Model/Models.cs +++ b/src/Validation.Analyzers/Model/Models.cs @@ -65,10 +65,12 @@ internal sealed record RegexModel(string Field, string Pattern, string Options); /// How a member is validated with a validator of its own. /// The type validated, as generated code names it. /// The validator named by [ValidateWith], or for the one of the type. +/// Whether the validator can be named in the signature of a public constructor. +/// The types whose validators the validator is made with, and theirs in turn, as far as referenced assemblies say. /// Whether the member is a collection validated item by item. /// Whether the member can be null. /// Whether an item of the collection can be null. -internal sealed record NestedModel(string Target, string? Validator, bool IsCollection, bool CanBeNull, bool ItemCanBeNull); +internal sealed record NestedModel(string Target, string? Validator, bool IsPublic, EquatableArray Reaches, bool IsCollection, bool CanBeNull, bool ItemCanBeNull); /// /// The rules a Validate function or an IValidatorDefinition class declares for a type, already written: the methods the generator adds @@ -185,11 +187,15 @@ internal sealed record CopiedMemberModel(string Name, string Type); /// The type a [Mutable] view model is of. /// The type, as generated code names it. /// Whether a referenced assembly has a validator for it. +/// Whether the type can be named in the signature of a public constructor. +/// The types whose validators the type's validator is made with, and theirs in turn, as far as referenced assemblies say. /// The type, then its base classes and interfaces: where the rules of its members are. /// The properties the view model has. internal sealed record MutableLinkModel( string Type, bool IsValidated, + bool IsPublic, + EquatableArray Reaches, EquatableArray Sources, EquatableArray Members ); @@ -201,6 +207,7 @@ EquatableArray Members /// Whether it can be named in the signature of a public member. /// Whether it has rules at all. /// Whether a rule it declares waits. +/// The types whose validators it is made with, and theirs in turn. /// Its rule methods. internal sealed record SourceModel( string Target, @@ -209,6 +216,7 @@ internal sealed record SourceModel( bool IsPublic, bool HasDeclared, bool DeclaredAsync, + EquatableArray Reaches, EquatableArray Members ); diff --git a/src/Validation.Analyzers/Model/Resolution.cs b/src/Validation.Analyzers/Model/Resolution.cs index 96e0978635..27429dcb61 100644 --- a/src/Validation.Analyzers/Model/Resolution.cs +++ b/src/Validation.Analyzers/Model/Resolution.cs @@ -27,6 +27,9 @@ internal sealed class MergedModel(TargetModel target) /// For the view model of a [Mutable] type: the type it is of, which its whole value is validated as. public MutableLinkModel? Mutable { get; set; } + /// Whether the validator of the type the view model is of is asked of the service provider when it is first used. + public bool MutableLazy { get; set; } + /// The type the view model is of, when this compilation has rules for it. public MergedModel? MutableTarget { get; set; } @@ -103,6 +106,12 @@ internal sealed class ResolvedMember(string name, string type) public bool IsAsync { get; set; } + /// + /// Whether the member's validator is asked of the service provider when it is first used, and not given to the constructor: making + /// it takes this validator, or it can't be named in the constructor's signature. + /// + public bool NestedLazy { get; set; } + /// Whether the method reads what the validator was made with, and so is not static. public bool NeedsInstance { get; set; } @@ -149,6 +158,7 @@ internal sealed class SourceRef public MergedModel? Local { get; } public string Target => Local?.Target.Type ?? _referenced!.Target; public string Validator => Local?.Target.ValidatorFullName ?? _referenced!.Validator; + public IEnumerable Reaches => _referenced?.Reaches ?? []; public bool IsStatic => Local is { } local ? !local.NeedsInstance : _referenced!.IsStatic; public bool IsPublic => Local?.IsPublic ?? _referenced!.IsPublic; public bool HasDeclared => Local is { } local ? local.Resolved.Count > 0 : _referenced!.HasDeclared; @@ -220,6 +230,7 @@ ImmutableArray contributed resolver.Flags(all); foreach (var model in all) { + resolver.Cycles(model); } return ([.. all.Where(static z => z.WillEmit)], resolver.Diagnostics); @@ -394,6 +405,69 @@ private bool Settle(MergedModel model) return changed; } + // A validator is given the validators of its members when it is made, unless making one of them takes this validator: two types + // that validate each other, or a type with a member of its own type. That one is asked of the service provider when it is first used. + private void Cycles(MergedModel model) + { + foreach (var member in model.Resolved) + { + if (member.Nested is not { } nested) continue; + member.NestedLazy = !nested.IsPublic || Reaches(nested.Validator is null ? [nested.Target, .. nested.Reaches] : nested.Reaches, model.Target.Type); + } + + if (model.Mutable is { } mutable) model.MutableLazy = !mutable.IsPublic || Reaches([mutable.Type, .. mutable.Reaches], model.Target.Type); + } + + private bool Reaches(IEnumerable from, string to) + { + var seen = new HashSet(StringComparer.Ordinal); + var pending = new Stack(from); + while (pending.Count > 0) + { + var type = pending.Pop(); + if (type == to) return true; + if (!seen.Add(type) || !_byType.TryGetValue(type, out var model) || !model.WillEmit) continue; + foreach (var next in Needs(model)) + { + pending.Push(next); + } + } + + return false; + } + + // The types whose validators a validator of this compilation is made with, or asks for. + private static IEnumerable Needs(MergedModel model) + { + foreach (var member in model.Resolved) + { + if (member.Nested is not { } nested) continue; + if (nested.Validator is null) yield return nested.Target; + foreach (var type in nested.Reaches) + { + yield return type; + } + } + + if (model.Mutable is { } mutable) + { + yield return mutable.Type; + foreach (var type in mutable.Reaches) + { + yield return type; + } + } + + foreach (var source in model.InstanceSources) + { + yield return source.Target; + foreach (var type in source.Reaches) + { + yield return type; + } + } + } + private void Report(Microsoft.CodeAnalysis.DiagnosticDescriptor descriptor, LocationModel location, params string[] arguments) => Diagnostics.Add(new(descriptor.Id, location.Path, location.Span, location.LineSpan, arguments.ToEquatableArray())); } diff --git a/src/Validation.Analyzers/Model/RuleReader.cs b/src/Validation.Analyzers/Model/RuleReader.cs index 77339f0e6e..3357179494 100644 --- a/src/Validation.Analyzers/Model/RuleReader.cs +++ b/src/Validation.Analyzers/Model/RuleReader.cs @@ -162,6 +162,8 @@ private void ReadNested(MemberContext context, AttributeData attribute) context.Nested = new( named.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), with?.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), + TargetReader.IsPublic(with ?? named), + ReferencedValidators.For(_model.Compilation).Reaches(named, with), item is not null, ValidationSymbols.CanBeNull(context.Type), item is not null && ValidationSymbols.CanBeNull(item) diff --git a/src/Validation.Analyzers/ValidatorEmitter.cs b/src/Validation.Analyzers/ValidatorEmitter.cs index 14f0d48ca4..c2a150a2d1 100644 --- a/src/Validation.Analyzers/ValidatorEmitter.cs +++ b/src/Validation.Analyzers/ValidatorEmitter.cs @@ -15,8 +15,9 @@ internal static class ValidatorEmitter private const string Token = "global::System.Threading.CancellationToken"; private const string ValueTask = "global::System.Threading.Tasks.ValueTask"; - // A validator the generated one asks the service provider for, and the type it is asked as. - private sealed record NestedValidator(string Service, string Property); + // The validator of a member, or of the type a view model is of: the type it is asked as, how the code names it, and the property + // that asks the service provider for it when it can't be given to the constructor. + private sealed record NestedValidator(string Service, string Access, string? Property); // What the validator being written is given, and how its code names it. private sealed class Context(MergedModel model) @@ -54,10 +55,12 @@ public string Add(string type, string name) /// What a rule method of another validator is called on. public string Receiver(CarriedCall call) => call.Member.IsStatic ? call.Source.Validator : Sources[call.Source.Validator]; - public NestedValidator NestedFor(string member, NestedModel how) + public NestedValidator NestedFor(string member, string target, string? named, bool lazy) { - var service = how.Validator ?? Runtime + ".IValidator<" + how.Target + ">"; - if (!Nested.TryGetValue(service, out var validator)) Nested.Add(service, validator = new(service, member + "Validator")); + var service = named ?? Runtime + ".IValidator<" + target + ">"; + if (Nested.TryGetValue(service, out var validator)) return validator; + validator = lazy ? new(service, member + "Validator", member + "Validator") : new(service, Add(service, Camel(member) + "Validator"), null); + Nested.Add(service, validator); return validator; } } @@ -116,13 +119,14 @@ public static string Validator(MergedModel model, CompilationModel compilation) // One validator for each type validated, whichever members are of it: named after the first. foreach (var member in model.Resolved) { - if (member.Nested is { } how) context.NestedFor(member.Name, how); + if (member.Nested is { } how) context.NestedFor(member.Name, how.Target, how.Validator, member.NestedLazy); } NestedValidator? whole = null; - if (model.Mutable is { } mutable) whole = context.NestedFor("MutableTarget", new(mutable.Type, null, false, false, false)); + if (model.Mutable is { } mutable) whole = context.NestedFor("MutableTarget", mutable.Type, null, model.MutableLazy); - var nested = context.Nested; + // Those asked of the service provider when they are first used. + var nested = context.Nested.Values.Where(static z => z.Property is not null).ToList(); var fields = context.Fields; var interfaces = $"{Runtime}.IValidator<{target.Type}>, {Runtime}.IValidateMembers<{target.Type}>" + ( options ? $", global::Microsoft.Extensions.Options.IValidateOptions<{target.Type}>" : "" ); @@ -142,9 +146,9 @@ public static string Validator(MergedModel model, CompilationModel compilation) Line($" private readonly {Runtime}.IValidationMessageProvider? _messages;"); if (nested.Count > 0) Line(" private readonly global::System.IServiceProvider? _services;"); - foreach (var validator in nested.Values) + foreach (var validator in nested) { - Line($" private {validator.Service}? _{Camel(validator.Property)};"); + Line($" private {validator.Service}? _{Camel(validator.Property!)};"); } foreach (var regex in model.Members.SelectMany(static z => z.Regexes)) @@ -164,7 +168,7 @@ public static string Validator(MergedModel model, CompilationModel compilation) } Line(" /// What replaces the rules' messages, if anything does."); - if (nested.Count > 0) Line(" /// Where the validators of the members validated with their own are found."); + if (nested.Count > 0) Line(" /// Where the validators that can't be given here, as making them takes this one, are found."); var parameters = string.Concat(fields.Select(static z => z.Type + " " + z.Parameter + ", ")) + Runtime + ".IValidationMessageProvider? messages = null" @@ -235,7 +239,7 @@ public static string Validator(MergedModel model, CompilationModel compilation) if (whole is not null) { - Line($" sink.Add(await {whole.Property}.ValidateAsync(value.ToImmutable(), cancellationToken).ConfigureAwait(false));"); + Line($" sink.Add(await {whole.Access}.ValidateAsync(value.ToImmutable(), cancellationToken).ConfigureAwait(false));"); } if (model.Resolved.Count > 0) @@ -271,9 +275,9 @@ public static string Validator(MergedModel model, CompilationModel compilation) Line(" }"); } - foreach (var validator in nested.Values) + foreach (var validator in nested) { - var field = "_" + Camel(validator.Property); + var field = "_" + Camel(validator.Property!); Line(); Line($" private {validator.Service} {validator.Property} =>"); Line($" {field} ??= _services?.GetService(typeof({validator.Service})) as {validator.Service}"); @@ -575,7 +579,7 @@ void Separate() if (member.Nested is { } how) { Separate(); - WriteNested(member.Name, how, context.NestedFor(member.Name, how), line); + WriteNested(member.Name, how, context.NestedFor(member.Name, how.Target, how.Validator, member.NestedLazy), line); } if (member.IsAsync) line(" return sink;"); @@ -585,7 +589,7 @@ void Separate() private static void WriteNested(string member, NestedModel nested, NestedValidator validator, Action line) { var name = Literal(member); - string Call(string value) => $"sink.Add(await {validator.Property}.ValidateAsync({value}, cancellationToken).ConfigureAwait(false));"; + string Call(string value) => $"sink.Add(await {validator.Access}.ValidateAsync({value}, cancellationToken).ConfigureAwait(false));"; var present = "value"; var indent = " "; diff --git a/test/Validation.Analyzers.Tests/ValidatorGeneratorTests.cs b/test/Validation.Analyzers.Tests/ValidatorGeneratorTests.cs index 11b25d3263..912f67721c 100644 --- a/test/Validation.Analyzers.Tests/ValidatorGeneratorTests.cs +++ b/test/Validation.Analyzers.Tests/ValidatorGeneratorTests.cs @@ -178,6 +178,22 @@ public sealed class Launcher public Crew? Ground { get; set; } } + // Each validates the other: neither validator can be given the other's when it is made, so each asks for it when it gets there. + public sealed class Pad + { + [ValidateNested] + public Tower? Tower { get; set; } + } + + public sealed class Tower + { + [NotEmpty] + public string? Name { get; set; } + + [ValidateNested] + public Pad? Pad { get; set; } + } + public sealed class StrictCrew : IValidator { public System.Threading.Tasks.ValueTask ValidateAsync(Crew value, System.Threading.CancellationToken cancellationToken = default) => diff --git a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#Sample.PlanetModelGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#Sample.PlanetModelGeneratedValidator.g.verified.cs index 595bc7c49b..7e6a09524b 100644 --- a/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#Sample.PlanetModelGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/CompositionGeneratorTests.Should_Validate_A_View_Model_As_Its_Type_And_Member_By_Member#Sample.PlanetModelGeneratedValidator.g.verified.cs @@ -13,19 +13,18 @@ namespace Sample public sealed class PlanetModelGeneratedValidator : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { + private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidator _mutableTargetValidator; private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; - private readonly global::System.IServiceProvider? _services; - private global::Rocket.Surgery.LaunchPad.Validation.IValidator? _mutableTargetValidator; /// /// Creates the validator. /// + /// What the rules declared for the type take. /// What replaces the rules' messages, if anything does. - /// Where the validators of the members validated with their own are found. - public PlanetModelGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null, global::System.IServiceProvider? services = null) + public PlanetModelGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidator mutableTargetValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) { + _mutableTargetValidator = mutableTargetValidator; _messages = messages; - _services = services; } /// @@ -33,7 +32,7 @@ public PlanetModelGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation { global::System.ArgumentNullException.ThrowIfNull(value); var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); - sink.Add(await MutableTargetValidator.ValidateAsync(value.ToImmutable(), cancellationToken).ConfigureAwait(false)); + sink.Add(await _mutableTargetValidator.ValidateAsync(value.ToImmutable(), cancellationToken).ConfigureAwait(false)); ValidateDeclared(value, ref sink); return sink.ToResult(); } @@ -99,10 +98,6 @@ public bool TryValidateMember(global::Sample.PlanetModel value, string member, o new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Comment", "MaxLength(20)") ); - private global::Rocket.Surgery.LaunchPad.Validation.IValidator MutableTargetValidator => - _mutableTargetValidator ??= _services?.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator)) as global::Rocket.Surgery.LaunchPad.Validation.IValidator - ?? throw new global::System.InvalidOperationException("PlanetModelGeneratedValidator needs a Rocket.Surgery.LaunchPad.Validation.IValidator, which the service provider it was given does not have."); - /// /// Checks the rules declared for itself, and no others: the validator of a type that /// derives from it calls this. diff --git a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read#LauncherGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read#LauncherGeneratedValidator.g.verified.cs index 61a15ffa1d..c1476329f2 100644 --- a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read#LauncherGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read#LauncherGeneratedValidator.g.verified.cs @@ -12,21 +12,20 @@ public sealed class LauncherGeneratedValidator : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { private readonly string _prefix; + private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidator _engineValidator; private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; - private readonly global::System.IServiceProvider? _services; - private global::Rocket.Surgery.LaunchPad.Validation.IValidator? _engineValidator; /// /// Creates the validator. /// /// What the rules declared for the type take. + /// What the rules declared for the type take. /// What replaces the rules' messages, if anything does. - /// Where the validators of the members validated with their own are found. - public LauncherGeneratedValidator(string prefix, global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null, global::System.IServiceProvider? services = null) + public LauncherGeneratedValidator(string prefix, global::Rocket.Surgery.LaunchPad.Validation.IValidator engineValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) { _prefix = prefix; + _engineValidator = engineValidator; _messages = messages; - _services = services; } /// @@ -95,10 +94,6 @@ public bool TryValidateMember(global::Launcher value, string member, out global: new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Count", "GreaterThan(0)") ); - private global::Rocket.Surgery.LaunchPad.Validation.IValidator EngineValidator => - _engineValidator ??= _services?.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator)) as global::Rocket.Surgery.LaunchPad.Validation.IValidator - ?? throw new global::System.InvalidOperationException("LauncherGeneratedValidator needs a Rocket.Surgery.LaunchPad.Validation.IValidator, which the service provider it was given does not have."); - /// /// Checks the rules declared for itself, and no others: the validator of a type that /// derives from it calls this. @@ -137,7 +132,7 @@ public void EnsureName(string value, ref global::Rocket.Surgery.LaunchPad.Valida if (value is { } present) { var path = sink.Enter("Engine"); - sink.Add(await EngineValidator.ValidateAsync(present, cancellationToken).ConfigureAwait(false)); + sink.Add(await _engineValidator.ValidateAsync(present, cancellationToken).ConfigureAwait(false)); sink.Leave(path); } return sink; diff --git a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.ManifestGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.ManifestGeneratedValidator.g.verified.cs index 6230f0e6ca..e5cff6848e 100644 --- a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.ManifestGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.ManifestGeneratedValidator.g.verified.cs @@ -13,19 +13,18 @@ namespace Sample public sealed class ManifestGeneratedValidator : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { + private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidator _bookingValidator; private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; - private readonly global::System.IServiceProvider? _services; - private global::Rocket.Surgery.LaunchPad.Validation.IValidator? _bookingValidator; /// /// Creates the validator. /// + /// What the rules declared for the type take. /// What replaces the rules' messages, if anything does. - /// Where the validators of the members validated with their own are found. - public ManifestGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null, global::System.IServiceProvider? services = null) + public ManifestGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidator bookingValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) { + _bookingValidator = bookingValidator; _messages = messages; - _services = services; } /// @@ -91,10 +90,6 @@ public bool TryValidateMember(global::Sample.Manifest value, string member, out new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Others") ); - private global::Rocket.Surgery.LaunchPad.Validation.IValidator BookingValidator => - _bookingValidator ??= _services?.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator)) as global::Rocket.Surgery.LaunchPad.Validation.IValidator - ?? throw new global::System.InvalidOperationException("ManifestGeneratedValidator needs a Rocket.Surgery.LaunchPad.Validation.IValidator, which the service provider it was given does not have."); - /// /// Checks the rules declared for itself, and no others: the validator of a type that /// derives from it calls this. @@ -135,7 +130,7 @@ public static void EnsureName(string value, ref global::Rocket.Surgery.LaunchPad if (value is { } present) { var path = sink.Enter("Booking"); - sink.Add(await BookingValidator.ValidateAsync(present, cancellationToken).ConfigureAwait(false)); + sink.Add(await _bookingValidator.ValidateAsync(present, cancellationToken).ConfigureAwait(false)); sink.Leave(path); } return sink; @@ -157,7 +152,7 @@ public static void EnsureName(string value, ref global::Rocket.Surgery.LaunchPad if (item is { } each) { var itemPath = sink.Enter(index); - sink.Add(await BookingValidator.ValidateAsync(each, cancellationToken).ConfigureAwait(false)); + sink.Add(await _bookingValidator.ValidateAsync(each, cancellationToken).ConfigureAwait(false)); sink.Leave(itemPath); } diff --git a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.ScheduleGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.ScheduleGeneratedValidator.g.verified.cs index 935ea7cd06..e07bba8c72 100644 --- a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.ScheduleGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.ScheduleGeneratedValidator.g.verified.cs @@ -13,19 +13,18 @@ namespace Sample public sealed class ScheduleGeneratedValidator : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { + private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidator _manifestValidator; private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; - private readonly global::System.IServiceProvider? _services; - private global::Rocket.Surgery.LaunchPad.Validation.IValidator? _manifestValidator; /// /// Creates the validator. /// + /// What the rules declared for the type take. /// What replaces the rules' messages, if anything does. - /// Where the validators of the members validated with their own are found. - public ScheduleGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null, global::System.IServiceProvider? services = null) + public ScheduleGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidator manifestValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) { + _manifestValidator = manifestValidator; _messages = messages; - _services = services; } /// @@ -77,10 +76,6 @@ public bool TryValidateMember(global::Sample.Schedule value, string member, out new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Manifest", "NotNull") ); - private global::Rocket.Surgery.LaunchPad.Validation.IValidator ManifestValidator => - _manifestValidator ??= _services?.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator)) as global::Rocket.Surgery.LaunchPad.Validation.IValidator - ?? throw new global::System.InvalidOperationException("ScheduleGeneratedValidator needs a Rocket.Surgery.LaunchPad.Validation.IValidator, which the service provider it was given does not have."); - /// /// Checks the rules declared for itself, and no others: the validator of a type that /// derives from it calls this. @@ -109,7 +104,7 @@ public bool TryValidateMember(global::Sample.Schedule value, string member, out if (value is { } present) { var path = sink.Enter("Manifest"); - sink.Add(await ManifestValidator.ValidateAsync(present, cancellationToken).ConfigureAwait(false)); + sink.Add(await _manifestValidator.ValidateAsync(present, cancellationToken).ConfigureAwait(false)); sink.Leave(path); } return sink; diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.LauncherGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.LauncherGeneratedValidator.g.verified.cs index 7499fd6455..97498e6c1d 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.LauncherGeneratedValidator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.LauncherGeneratedValidator.g.verified.cs @@ -13,21 +13,24 @@ namespace Sample public sealed class LauncherGeneratedValidator : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers { + private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidator _crewValidator; + private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidator _boosterValidator; + private readonly global::Sample.StrictCrew _reserveValidator; private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; - private readonly global::System.IServiceProvider? _services; - private global::Rocket.Surgery.LaunchPad.Validation.IValidator? _crewValidator; - private global::Rocket.Surgery.LaunchPad.Validation.IValidator? _boosterValidator; - private global::Sample.StrictCrew? _reserveValidator; /// /// Creates the validator. /// + /// What the rules declared for the type take. + /// What the rules declared for the type take. + /// What the rules declared for the type take. /// What replaces the rules' messages, if anything does. - /// Where the validators of the members validated with their own are found. - public LauncherGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null, global::System.IServiceProvider? services = null) + public LauncherGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidator crewValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidator boosterValidator, global::Sample.StrictCrew reserveValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) { + _crewValidator = crewValidator; + _boosterValidator = boosterValidator; + _reserveValidator = reserveValidator; _messages = messages; - _services = services; } /// @@ -114,18 +117,6 @@ public bool TryValidateMember(global::Sample.Launcher value, string member, out new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Reserve") ); - private global::Rocket.Surgery.LaunchPad.Validation.IValidator CrewValidator => - _crewValidator ??= _services?.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator)) as global::Rocket.Surgery.LaunchPad.Validation.IValidator - ?? throw new global::System.InvalidOperationException("LauncherGeneratedValidator needs a Rocket.Surgery.LaunchPad.Validation.IValidator, which the service provider it was given does not have."); - - private global::Rocket.Surgery.LaunchPad.Validation.IValidator BoosterValidator => - _boosterValidator ??= _services?.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator)) as global::Rocket.Surgery.LaunchPad.Validation.IValidator - ?? throw new global::System.InvalidOperationException("LauncherGeneratedValidator needs a Rocket.Surgery.LaunchPad.Validation.IValidator, which the service provider it was given does not have."); - - private global::Sample.StrictCrew ReserveValidator => - _reserveValidator ??= _services?.GetService(typeof(global::Sample.StrictCrew)) as global::Sample.StrictCrew - ?? throw new global::System.InvalidOperationException("LauncherGeneratedValidator needs a Sample.StrictCrew, which the service provider it was given does not have."); - /// /// Checks the rules declared for itself, and no others: the validator of a type that /// derives from it calls this. @@ -156,7 +147,7 @@ public bool TryValidateMember(global::Sample.Launcher value, string member, out if (value is { } present) { var path = sink.Enter("Crew"); - sink.Add(await CrewValidator.ValidateAsync(present, cancellationToken).ConfigureAwait(false)); + sink.Add(await _crewValidator.ValidateAsync(present, cancellationToken).ConfigureAwait(false)); sink.Leave(path); } return sink; @@ -177,7 +168,7 @@ public bool TryValidateMember(global::Sample.Launcher value, string member, out if (value is { } present) { var path = sink.Enter("Booster"); - sink.Add(await BoosterValidator.ValidateAsync(present, cancellationToken).ConfigureAwait(false)); + sink.Add(await _boosterValidator.ValidateAsync(present, cancellationToken).ConfigureAwait(false)); sink.Leave(path); } return sink; @@ -191,7 +182,7 @@ public bool TryValidateMember(global::Sample.Launcher value, string member, out public async global::System.Threading.Tasks.ValueTask EnsureCore(global::Sample.Stage value, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink, global::System.Threading.CancellationToken cancellationToken) { var path = sink.Enter("Core"); - sink.Add(await BoosterValidator.ValidateAsync(value, cancellationToken).ConfigureAwait(false)); + sink.Add(await _boosterValidator.ValidateAsync(value, cancellationToken).ConfigureAwait(false)); sink.Leave(path); return sink; } @@ -215,7 +206,7 @@ public bool TryValidateMember(global::Sample.Launcher value, string member, out foreach (var item in present) { var itemPath = sink.Enter(index); - sink.Add(await BoosterValidator.ValidateAsync(item, cancellationToken).ConfigureAwait(false)); + sink.Add(await _boosterValidator.ValidateAsync(item, cancellationToken).ConfigureAwait(false)); sink.Leave(itemPath); index++; @@ -242,7 +233,7 @@ public bool TryValidateMember(global::Sample.Launcher value, string member, out if (item is { } each) { var itemPath = sink.Enter(index); - sink.Add(await CrewValidator.ValidateAsync(each, cancellationToken).ConfigureAwait(false)); + sink.Add(await _crewValidator.ValidateAsync(each, cancellationToken).ConfigureAwait(false)); sink.Leave(itemPath); } @@ -264,7 +255,7 @@ public bool TryValidateMember(global::Sample.Launcher value, string member, out if (value is { } present) { var path = sink.Enter("Reserve"); - sink.Add(await ReserveValidator.ValidateAsync(present, cancellationToken).ConfigureAwait(false)); + sink.Add(await _reserveValidator.ValidateAsync(present, cancellationToken).ConfigureAwait(false)); sink.Leave(path); } return sink; diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.PadGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.PadGeneratedValidator.g.verified.cs new file mode 100644 index 0000000000..05b692dba7 --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.PadGeneratedValidator.g.verified.cs @@ -0,0 +1,115 @@ +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.PadGeneratedValidator.g.cs +// +#nullable enable +#pragma warning disable CS1998 // a member whose rules all turned out to be synchronous + +namespace Sample +{ + /// + /// Validates a : every rule declared for it, by the attributes of its members and by the + /// functions and classes that validate it, and the rules of what it derives from. + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Pad))] + public sealed class PadGeneratedValidator + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers + { + private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; + private readonly global::System.IServiceProvider? _services; + private global::Rocket.Surgery.LaunchPad.Validation.IValidator? _towerValidator; + + /// + /// Creates the validator. + /// + /// What replaces the rules' messages, if anything does. + /// Where the validators that can't be given here, as making them takes this one, are found. + public PadGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null, global::System.IServiceProvider? services = null) + { + _messages = messages; + _services = services; + } + + /// + public async global::System.Threading.Tasks.ValueTask ValidateAsync(global::Sample.Pad value, global::System.Threading.CancellationToken cancellationToken = default) + { + global::System.ArgumentNullException.ThrowIfNull(value); + var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); + sink = await ValidateDeclaredAsync(value, sink, cancellationToken).ConfigureAwait(false); + return sink.ToResult(); + } + + /// + public bool TryValidateMember(global::Sample.Pad value, string member, out global::Rocket.Surgery.LaunchPad.Validation.ValidationResult result) + { + global::System.ArgumentNullException.ThrowIfNull(value); + var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); + switch (member) + { + case "Tower": + result = default; + return false; + } + + result = sink.ToResult(); + return true; + } + + /// + public async global::System.Threading.Tasks.ValueTask ValidateMemberAsync(global::Sample.Pad value, string member, global::System.Threading.CancellationToken cancellationToken = default) + { + global::System.ArgumentNullException.ThrowIfNull(value); + var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); + switch (member) + { + case "Tower": + sink = await EnsureTower(value.Tower, sink, cancellationToken).ConfigureAwait(false); + break; + } + + return sink.ToResult(); + } + + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.Pad), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Tower") + ); + + private global::Rocket.Surgery.LaunchPad.Validation.IValidator TowerValidator => + _towerValidator ??= _services?.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator)) as global::Rocket.Surgery.LaunchPad.Validation.IValidator + ?? throw new global::System.InvalidOperationException("PadGeneratedValidator needs a Rocket.Surgery.LaunchPad.Validation.IValidator, which the service provider it was given does not have."); + + /// + /// Checks the rules declared for itself, and no others: the validator of a type that + /// derives from it calls this. + /// + /// The value. + /// Where the failures go. + /// A token that cancels the rules that wait. + /// Where the failures went. + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public async global::System.Threading.Tasks.ValueTask ValidateDeclaredAsync(global::Sample.Pad value, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink, global::System.Threading.CancellationToken cancellationToken) + { + sink = await EnsureTower(value.Tower, sink, cancellationToken).ConfigureAwait(false); + return sink; + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Tower")] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public async global::System.Threading.Tasks.ValueTask EnsureTower(global::Sample.Tower? value, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink, global::System.Threading.CancellationToken cancellationToken) + { + if (value is { } present) + { + var path = sink.Enter("Tower"); + sink.Add(await TowerValidator.ValidateAsync(present, cancellationToken).ConfigureAwait(false)); + sink.Leave(path); + } + return sink; + } + } +} diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.TowerGeneratedValidator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.TowerGeneratedValidator.g.verified.cs new file mode 100644 index 0000000000..858e029649 --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.TowerGeneratedValidator.g.verified.cs @@ -0,0 +1,136 @@ +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.TowerGeneratedValidator.g.cs +// +#nullable enable +#pragma warning disable CS1998 // a member whose rules all turned out to be synchronous + +namespace Sample +{ + /// + /// Validates a : every rule declared for it, by the attributes of its members and by the + /// functions and classes that validate it, and the rules of what it derives from. + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Tower))] + public sealed class TowerGeneratedValidator + : global::Rocket.Surgery.LaunchPad.Validation.IValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidateMembers + { + private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; + private readonly global::System.IServiceProvider? _services; + private global::Rocket.Surgery.LaunchPad.Validation.IValidator? _padValidator; + + /// + /// Creates the validator. + /// + /// What replaces the rules' messages, if anything does. + /// Where the validators that can't be given here, as making them takes this one, are found. + public TowerGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null, global::System.IServiceProvider? services = null) + { + _messages = messages; + _services = services; + } + + /// + public async global::System.Threading.Tasks.ValueTask ValidateAsync(global::Sample.Tower value, global::System.Threading.CancellationToken cancellationToken = default) + { + global::System.ArgumentNullException.ThrowIfNull(value); + var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); + sink = await ValidateDeclaredAsync(value, sink, cancellationToken).ConfigureAwait(false); + return sink.ToResult(); + } + + /// + public bool TryValidateMember(global::Sample.Tower value, string member, out global::Rocket.Surgery.LaunchPad.Validation.ValidationResult result) + { + global::System.ArgumentNullException.ThrowIfNull(value); + var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); + switch (member) + { + case "Name": + EnsureName(value.Name, ref sink); + break; + case "Pad": + result = default; + return false; + } + + result = sink.ToResult(); + return true; + } + + /// + public async global::System.Threading.Tasks.ValueTask ValidateMemberAsync(global::Sample.Tower value, string member, global::System.Threading.CancellationToken cancellationToken = default) + { + global::System.ArgumentNullException.ThrowIfNull(value); + var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); + switch (member) + { + case "Name": + EnsureName(value.Name, ref sink); + break; + case "Pad": + sink = await EnsurePad(value.Pad, sink, cancellationToken).ConfigureAwait(false); + break; + } + + return sink.ToResult(); + } + + /// + /// The rules of each member, as data. + /// + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static global::Rocket.Surgery.LaunchPad.Validation.ValidationManifest Manifest { get; } = new( + typeof(global::Sample.Tower), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Name", "NotEmpty"), + new global::Rocket.Surgery.LaunchPad.Validation.ValidatedMember("Pad") + ); + + private global::Rocket.Surgery.LaunchPad.Validation.IValidator PadValidator => + _padValidator ??= _services?.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidator)) as global::Rocket.Surgery.LaunchPad.Validation.IValidator + ?? throw new global::System.InvalidOperationException("TowerGeneratedValidator needs a Rocket.Surgery.LaunchPad.Validation.IValidator, which the service provider it was given does not have."); + + /// + /// Checks the rules declared for itself, and no others: the validator of a type that + /// derives from it calls this. + /// + /// The value. + /// Where the failures go. + /// A token that cancels the rules that wait. + /// Where the failures went. + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public async global::System.Threading.Tasks.ValueTask ValidateDeclaredAsync(global::Sample.Tower value, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink, global::System.Threading.CancellationToken cancellationToken) + { + EnsureName(value.Name, ref sink); + sink = await EnsurePad(value.Pad, sink, cancellationToken).ConfigureAwait(false); + return sink; + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Name", "NotEmpty")] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void EnsureName(string? value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.NotEmpty(value)) + { + sink.Add("Name", "NotEmpty", "{Name} must not be empty", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Name"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value)); + } + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Pad")] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public async global::System.Threading.Tasks.ValueTask EnsurePad(global::Sample.Pad? value, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink, global::System.Threading.CancellationToken cancellationToken) + { + if (value is { } present) + { + var path = sink.Enter("Pad"); + sink.Add(await PadValidator.ValidateAsync(present, cancellationToken).ConfigureAwait(false)); + sink.Leave(path); + } + return sink; + } + } +} diff --git a/test/Validation.Tests/GeneratedValidatorTests.cs b/test/Validation.Tests/GeneratedValidatorTests.cs index 04051abcad..32007e8c95 100644 --- a/test/Validation.Tests/GeneratedValidatorTests.cs +++ b/test/Validation.Tests/GeneratedValidatorTests.cs @@ -173,13 +173,29 @@ public async Task Should_Validate_Options() } [Test] - public async Task Should_Not_Accept_Null() => - await Assert.That(() => new LauncherGeneratedValidator().ValidateAsync(null!).AsTask()).Throws(); + public async Task Should_Not_Accept_Null() + { + using var services = Services(); + using var scope = services.CreateScope(); + var validator = scope.ServiceProvider.GetRequiredService>(); + + await Assert.That(() => validator.ValidateAsync(null!).AsTask()).Throws(); + } + + // The validators of a validator's members are given to its constructor. + [Test] + public async Task Should_Be_Made_With_The_Validators_Of_Its_Members() + { + var parameters = typeof(LauncherGeneratedValidator).GetConstructors().Single().GetParameters().Select(z => z.ParameterType); + + await parameters.Should().BeEquivalentTo([typeof(IValidator), typeof(IValidator), typeof(IValidationMessageProvider)]); + } + // A type with a member of its own type can't be given its own validator: it asks the service provider for it when it gets there. [Test] public async Task Should_Say_Which_Validator_Is_Missing() { - var exception = await Assert.That(async () => await new LauncherGeneratedValidator().ValidateAsync(new() { Crew = new("Ada"), })).Throws(); + var exception = await Assert.That(async () => await new CrewGeneratedValidator().ValidateAsync(new("Ada", new("Grace")))).Throws(); await exception!.Message.Should().Contain("IValidator"); }