From 3fc37e2749b86b85e9efa4652985235cfaeaac2e Mon Sep 17 00:00:00 2001 From: David Driscoll Date: Thu, 3 Dec 2026 17:37:35 -0500 Subject: [PATCH 1/8] Add LaunchPad.Validation: runtime package and attribute-rule generator LaunchPad owns validation (#3374). This is the first two parts (#3375, #3376): the decision and design, the runtime package, and the generator for rules declared with attributes. ZeroAlloc.Validation is still what validates everywhere else. - ADR-0012 and docs/design/validation.md. - src/Validation: the builder a Validate function or an IValidator class declares rules on, IValidate and IValidateAsync, the result types, the message formatter and provider, the built-in rules, their attributes and the rule manifest attributes. - src/Validation.Analyzers: ValidatorGenerator writes a validator, with a rule method per member, for every type whose members carry LaunchPad rule attributes or the DataAnnotations attributes it compiles, and the method that registers an assembly's validators. LPAD3001 and its fixes for nested validation; LPAD3101 to LPAD3106 for what it refuses. - test/Validation.Tests and test/Validation.Analyzers.Tests. Co-Authored-By: Claude Fable 5.2 --- AGENTS.md | 8 + LaunchPad.slnx | 4 + Readme.md | 7 + docs/adr/0012-launchpad-owns-validation.md | 34 ++ docs/design/validation.md | 239 ++++++++ .../AnalyzerReleases.Unshipped.md | 14 + src/Validation.Analyzers/Diagnostics.cs | 86 +++ .../Model/EquatableArray.cs | 41 ++ src/Validation.Analyzers/Model/Models.cs | 75 +++ src/Validation.Analyzers/Model/RuleReader.cs | 517 ++++++++++++++++++ .../Model/ValidationSymbols.cs | 133 +++++ .../NestedValidationAnalyzer.cs | 55 ++ .../NestedValidationCodeFix.cs | 82 +++ ...gery.LaunchPad.Validation.Analyzers.csproj | 48 ++ .../ValidatorGenerator.cs | 385 +++++++++++++ src/Validation/GeneratedValidatorAttribute.cs | 72 +++ src/Validation/IValidate.cs | 39 ++ src/Validation/IValidationBuilder.cs | 154 ++++++ src/Validation/IValidationMessageProvider.cs | 16 + src/Validation/IValidator.cs | 21 + ...Rocket.Surgery.LaunchPad.Validation.csproj | 30 + src/Validation/Rules/MemberRulesExtensions.cs | 339 ++++++++++++ src/Validation/Rules/Rule.cs | 235 ++++++++ src/Validation/Rules/RuleAttributes.cs | 370 +++++++++++++ .../Rules/ValidationRuleAttribute.cs | 49 ++ src/Validation/ValidationFailure.cs | 31 ++ src/Validation/ValidationMessage.cs | 90 +++ src/Validation/ValidationResult.cs | 73 +++ src/Validation/ValidationSeverity.cs | 23 + src/Validation/ValidationSink.cs | 132 +++++ .../ModuleInitializer.cs | 21 + .../NestedValidationAnalyzerTests.cs | 55 ++ .../Validation.Analyzers.Tests/TestBuilder.cs | 119 ++++ .../Validation.Analyzers.Tests.csproj | 25 + .../ValidatorGeneratorTests.cs | 307 +++++++++++ ...ules_And_Offer_Both_Decisions.verified.txt | 392 +++++++++++++ ...Attributes#Account.Validator.g.verified.cs | 200 +++++++ ...he_DataAnnotations_Attributes.verified.txt | 6 + ...Class#Sample.Named.Validator.g.verified.cs | 44 ++ ...Sample.Outer_Inner.Validator.g.verified.cs | 44 ++ ...ss#Sample.Position.Validator.g.verified.cs | 57 ++ ...Class#Sample.Stage.Validator.g.verified.cs | 58 ++ ...Parameter_And_Of_A_Base_Class.verified.txt | 6 + ..._Options#LaunchPadValidators.g.verified.cs | 30 + ...tions#Sample.Delay.Validator.g.verified.cs | 43 ++ ...ample.RetryOptions.Validator.g.verified.cs | 58 ++ ...lidators_And_Validate_Options.verified.txt | 6 + ...not_Write#Mistakes.Validator.g.verified.cs | 41 ++ ...d_Report_What_It_Cannot_Write.verified.txt | 288 ++++++++++ ...dators#Sample.Crew.Validator.g.verified.cs | 44 ++ ...rs#Sample.Launcher.Validator.g.verified.cs | 148 +++++ ...ators#Sample.Stage.Validator.g.verified.cs | 43 ++ ...Members_With_Their_Validators.verified.txt | 6 + ...es#Sample.Launcher.Validator.g.verified.cs | 175 ++++++ ...Validator_For_Rule_Attributes.verified.txt | 6 + ...hing_For_A_Type_With_No_Rules.verified.txt | 6 + test/Validation.Tests/BuilderTests.cs | 62 +++ .../GeneratedValidatorTests.cs | 176 ++++++ test/Validation.Tests/RuleTests.cs | 166 ++++++ test/Validation.Tests/Types/Models.cs | 113 ++++ test/Validation.Tests/Validation.Tests.csproj | 18 + test/Validation.Tests/ValidationSinkTests.cs | 121 ++++ 62 files changed, 6286 insertions(+) create mode 100644 docs/adr/0012-launchpad-owns-validation.md create mode 100644 docs/design/validation.md create mode 100644 src/Validation.Analyzers/AnalyzerReleases.Unshipped.md create mode 100644 src/Validation.Analyzers/Diagnostics.cs create mode 100644 src/Validation.Analyzers/Model/EquatableArray.cs create mode 100644 src/Validation.Analyzers/Model/Models.cs create mode 100644 src/Validation.Analyzers/Model/RuleReader.cs create mode 100644 src/Validation.Analyzers/Model/ValidationSymbols.cs create mode 100644 src/Validation.Analyzers/NestedValidationAnalyzer.cs create mode 100644 src/Validation.Analyzers/NestedValidationCodeFix.cs create mode 100644 src/Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.csproj create mode 100644 src/Validation.Analyzers/ValidatorGenerator.cs create mode 100644 src/Validation/GeneratedValidatorAttribute.cs create mode 100644 src/Validation/IValidate.cs create mode 100644 src/Validation/IValidationBuilder.cs create mode 100644 src/Validation/IValidationMessageProvider.cs create mode 100644 src/Validation/IValidator.cs create mode 100644 src/Validation/Rocket.Surgery.LaunchPad.Validation.csproj create mode 100644 src/Validation/Rules/MemberRulesExtensions.cs create mode 100644 src/Validation/Rules/Rule.cs create mode 100644 src/Validation/Rules/RuleAttributes.cs create mode 100644 src/Validation/Rules/ValidationRuleAttribute.cs create mode 100644 src/Validation/ValidationFailure.cs create mode 100644 src/Validation/ValidationMessage.cs create mode 100644 src/Validation/ValidationResult.cs create mode 100644 src/Validation/ValidationSeverity.cs create mode 100644 src/Validation/ValidationSink.cs create mode 100644 test/Validation.Analyzers.Tests/ModuleInitializer.cs create mode 100644 test/Validation.Analyzers.Tests/NestedValidationAnalyzerTests.cs create mode 100644 test/Validation.Analyzers.Tests/TestBuilder.cs create mode 100644 test/Validation.Analyzers.Tests/Validation.Analyzers.Tests.csproj create mode 100644 test/Validation.Analyzers.Tests/ValidatorGeneratorTests.cs create mode 100644 test/Validation.Analyzers.Tests/snapshots/NestedValidationAnalyzerTests.Should_Report_A_Member_Whose_Type_Has_Rules_And_Offer_Both_Decisions.verified.txt create mode 100644 test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Compile_The_DataAnnotations_Attributes#Account.Validator.g.verified.cs create mode 100644 test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Compile_The_DataAnnotations_Attributes.verified.txt create mode 100644 test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Named.Validator.g.verified.cs create mode 100644 test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Outer_Inner.Validator.g.verified.cs create mode 100644 test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Position.Validator.g.verified.cs create mode 100644 test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Stage.Validator.g.verified.cs create mode 100644 test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class.verified.txt create mode 100644 test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#LaunchPadValidators.g.verified.cs create mode 100644 test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.Delay.Validator.g.verified.cs create mode 100644 test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.RetryOptions.Validator.g.verified.cs create mode 100644 test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options.verified.txt create mode 100644 test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Report_What_It_Cannot_Write#Mistakes.Validator.g.verified.cs create mode 100644 test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Report_What_It_Cannot_Write.verified.txt create mode 100644 test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.Crew.Validator.g.verified.cs create mode 100644 test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.Launcher.Validator.g.verified.cs create mode 100644 test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.Stage.Validator.g.verified.cs create mode 100644 test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators.verified.txt create mode 100644 test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Write_A_Validator_For_Rule_Attributes#Sample.Launcher.Validator.g.verified.cs create mode 100644 test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Write_A_Validator_For_Rule_Attributes.verified.txt create mode 100644 test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Write_Nothing_For_A_Type_With_No_Rules.verified.txt create mode 100644 test/Validation.Tests/BuilderTests.cs create mode 100644 test/Validation.Tests/GeneratedValidatorTests.cs create mode 100644 test/Validation.Tests/RuleTests.cs create mode 100644 test/Validation.Tests/Types/Models.cs create mode 100644 test/Validation.Tests/Validation.Tests.csproj create mode 100644 test/Validation.Tests/ValidationSinkTests.cs diff --git a/AGENTS.md b/AGENTS.md index 93328bd0507..622179ee696 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -31,6 +31,14 @@ The conversion is done: no project references `Rocket.Surgery.Conventions` or th - `src/Primitives.Analyzers` (its own package, an exception to ADR-0004) holds every generator, analyzer (LPAD2001 and up; LPAD2101 and up for the generator) and code fix, except LPAD2024, which LaunchPad's own analyzer (`src/Analyzers/Primitives`) reports in an application that uses domain primitives through a library without referencing Primitives, as Primitives' analyzers don't run there. The attributes are not compiled into any assembly: the generator writes `Sources/PrimitiveAttributes.cs` into every project that references Primitives, `internal`, `[Conditional("CodeGeneration")]` and `[Embedded]`, as a C# 15 closed hierarchy (`PrimitiveAttribute` for the kinds, `PrimitiveRuleAttribute` for the rules). A domain primitive in a referenced assembly is found by `IDomainPrimitive` (a value object by `IValueObject`), never by its attributes. The NodaTime members of `DatePrimitiveKind` are behind `#if LAUNCHPAD_PRIMITIVES_NODATIME`, which the package's targets define when the project references NodaTime. - 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). + - 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}Validator` beside the type, an `IValidate` 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 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, each validator of a class is an `IValidateOptions` too. + - Not written yet: function and class validators (the builder is not read), asynchronous rules, the rules of base classes, interfaces, `[InheritFrom]` and `[Mutable]`, and validators for generic types (LPAD3101). + - `test/Validation.Tests` runs the generator as an application does and proves what the validators do; `test/Validation.Analyzers.Tests` has the snapshots of what the generator writes and reports. - `src/Sdks/LaunchPad` is the **LaunchPad SDK** (`Rocket.Surgery.LaunchPad.Sdk`), an MSBuild SDK an application applies with an `` element in each project (`#:sdk` in a file-based app) or once in its `Directory.Build.props`. It chains `Joinery.Dovetail.Sdk` (the version `Directory.Packages.props` pins for it) and adds LaunchPad packages from what Dovetail's host detection finds and from the project's direct `PackageReference`s; `LaunchPadEnable=false` opts out. Every LaunchPad SDK also chains the **Chirograph** SDK (OpenAPI clients from `OpenApiClient` items) through `src/Sdks/LaunchPad/Sdk/Rocket.Surgery.LaunchPad.Chirograph.targets`, after the project body, unless the project applies Chirograph itself or sets `LaunchPadEnableChirograph=false`; the repository's own test projects apply `` directly, at the version `global.json` pins, which must equal the `Chirograph` `PackageVersion`. The versions are written into `Sdk/Packages.props` when the SDK is packed. `src/Sdks/Console` is the **console SDK** (`Rocket.Surgery.LaunchPad.Sdk.Console`): the same SDK for ConsoleAppFramework applications, chaining `Joinery.Dovetail.Sdk.Console`. `src/Sdks/{Web,Worker,Razor,BlazorWebAssembly,WebAssembly,WindowsDesktop}` are the **mirrors** (`Rocket.Surgery.LaunchPad.Sdk.Web`, ...): each is the Microsoft SDK of the same name with LaunchPad, chains Dovetail's mirror (`Joinery.Dovetail.Sdk.Web`, ...) and then applies `src/Sdks/Mirror/Rocket.Surgery.LaunchPad.Mirror.props`, which skips LaunchPad when a `Directory.Build.props` already applied it. Every SDK but `Rocket.Surgery.LaunchPad.Sdk` packs the shared files of `src/Sdks/LaunchPad/Sdk` beside its own `Sdk.props`/`Sdk.targets`; `src/Sdks/Directory.Build.props`/`.targets` hold the package settings and generate each `Sdk/Packages.props` from `LaunchPadChainedSdk`. `test/Sdk.Tests` packs it and builds throwaway applications against it, and `sample/Sample.Sdk` consumes it from packed packages (`dotnet msbuild build/pack.proj` there first). Like an application outside the repository, that sample and the throwaway projects of the tests stand outside central package management and name their own versions. - An operation that can fail responds with a **union response** instead of throwing ([`docs/design/union-types.md`](docs/design/union-types.md), [ADR-0005](docs/adr/0005-portable-unions-shaped-like-csharp-unions.md), [ADR-0010](docs/adr/0010-net11-only-and-native-unions.md), [ADR-0006](docs/adr/0006-union-responses-over-every-transport.md)); the generated servers answer each error case in their transport's error shape. Unions are native C# 15 unions (`public union Result(RocketModel, NotFound);`), or hand-written custom unions; LaunchPad has no union generator and no polyfill ([ADR-0010](docs/adr/0010-net11-only-and-native-unions.md)). The standard error cases (`Problem`, `NotFound` and the rest) are in Foundation. Generators detect a union by name (`UnionAttribute` or `IUnion`), take its cases from its public one-parameter constructors (implicitly declared ones included) and read it through `Value`. - Every test project runs on TUnit with Microsoft.Testing.Platform, as moved by tickets [#3050](https://github.com/RocketSurgeonsGuild/LaunchPad/issues/3050) and [#3051](https://github.com/RocketSurgeonsGuild/LaunchPad/issues/3051); `test/Directory.Build.targets` adds the TUnit, Verify.TUnit, TUnit.Mocks and TUnit.Assertions.Should packages to each of them, and there is no xunit, FakeItEasy or Shouldly anywhere. Tests assert with the Should syntax (`await x.Should().BeEqualTo(y)`), falling back to `Assert.That` only where it has no equivalent, and mock with TUnit.Mocks. A test that resolves services from a populated service collection derives from `ContainerTest` (`test/Shared/ContainerTest.cs`, linked into the projects that use it). The same file gives every test project `Joinery.Dovetail` and Specular, so a test gets the joints and the Specular scan results of the projects it references. Shared test code (the web app fixtures and fake time) lives in the non-packable `test/TestSupport` project. A test creates scopes directly with `CreateScope()` / `CreateAsyncScope()`. diff --git a/LaunchPad.slnx b/LaunchPad.slnx index 9269ce13aa4..9ccc47b0e16 100644 --- a/LaunchPad.slnx +++ b/LaunchPad.slnx @@ -91,6 +91,8 @@ + + @@ -145,6 +147,8 @@ + + diff --git a/Readme.md b/Readme.md index 6644236ea74..07d8ef48c10 100644 --- a/Readme.md +++ b/Readme.md @@ -90,6 +90,13 @@ lists what the SDK adds for each technology. | [Rocket.Surgery.LaunchPad.Primitives][nuget-primitives] | [![nuget-primitives-badge]][nuget-primitives] | Domain primitives, strong IDs, smart enums and value objects, with OpenAPI, HotChocolate, EF Core and OpenTelemetry joints as templates | | Rocket.Surgery.LaunchPad.Primitives.Analyzers | not published yet | The domain primitive generator, analyzers and code fixes Primitives depends on; a port of dotnet-domain-primitives (MIT) | +### Validation + +| Package | NuGet | What it does | +| ----------------------------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Rocket.Surgery.LaunchPad.Validation | not published yet | LaunchPad's own validation, in progress ([#3374](https://github.com/RocketSurgeonsGuild/LaunchPad/issues/3374)): rule attributes and `System.ComponentModel.DataAnnotations` compiled into one generated validator per type | +| Rocket.Surgery.LaunchPad.Validation.Analyzers | not published yet | The validator generator, analyzers and code fixes Validation depends on | + ## Contributing `mise install` installs the toolchain, `mise run build` builds, tests and packs, and `hk check` lints. diff --git a/docs/adr/0012-launchpad-owns-validation.md b/docs/adr/0012-launchpad-owns-validation.md new file mode 100644 index 00000000000..9b216d22efe --- /dev/null +++ b/docs/adr/0012-launchpad-owns-validation.md @@ -0,0 +1,34 @@ +# LaunchPad owns validation + +`Rocket.Surgery.LaunchPad.Validation` is LaunchPad's own validation: a runtime package and a source generator in an analyzer package of its own (`Rocket.Surgery.LaunchPad.Validation.Analyzers`), in place of ZeroAlloc.Validation. It is optional and depends on no other LaunchPad package, as Primitives is ([ADR-0008](0008-primitives-is-an-independent-strong-types-package.md)); its analyzer package is the same exception to [ADR-0004](0004-one-generator-assembly.md). The design is in [`docs/design/validation.md`](../design/validation.md), and the work is tracked by [#3374](https://github.com/RocketSurgeonsGuild/LaunchPad/issues/3374). + +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; +- 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. + +## Why + +ZeroAlloc.Validation declares rules with attributes only, so a rule that needs code (one that reads two members, applies under a condition or asks a service) has nowhere to go but a `[Must]` method. Its generator can't see what LaunchPad's `[Mutable]` and `[InheritFrom]` generators write, so the types they complete go unvalidated or are validated by delegation. And LaunchPad controls neither what it emits (the failure type, the paths, the codes, the registration) nor its vocabulary, which is not the one OpenAPI, Blazor and EF Core tooling already read. + +## Considered Options + +- **Keep ZeroAlloc.Validation and add function validators beside it.** Rejected: two validators per type with two failure types, and the composition with `[Mutable]` and `[InheritFrom]` stays unsolved. +- **[ValiCraft](https://github.com/hquinn/ValiCraft)** (MIT), whose generator rewrites a fluent `DefineRules` method the way this one rewrites `Validate`. Rejected as a dependency for the same reason as ZeroAlloc.Validation: its generator knows nothing of attributes, of LaunchPad's generators or of rules that cross assemblies. Its approach is the model for the function validators. +- **FluentValidation.** Rejected: it builds expression trees and compiles them at run time, which is what LaunchPad 2.0 left behind. +- **A `Validate` body that runs**, over a builder that takes values instead of lambdas. Rejected: the rules would not be known at build time, so they could not be carried over to another type, described to OpenAPI or split by member for a Blazor field. +- **The generator in LaunchPad's one analyzer assembly** ([ADR-0004](0004-one-generator-assembly.md)), where it could share the `[Mutable]` and `[InheritFrom]` models directly. Rejected: Validation would then need Foundation's analyzer, and it is meant to be usable without the rest of LaunchPad. The models are shared as linked source instead. +- **Integrations as templates**, as Primitives ships its Joints. Rejected: the gRPC interceptor, the HotChocolate error filter and the Blazor component are more than wiring. They stay integration packages ([ADR-0002](0002-package-per-integration.md)), renamed from `Rocket.Surgery.LaunchPad.ZeroAlloc.*` to `Rocket.Surgery.LaunchPad.Validation.*`. + +## 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. + +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 new file mode 100644 index 00000000000..2c6815e30af --- /dev/null +++ b/docs/design/validation.md @@ -0,0 +1,239 @@ +# Spec: LaunchPad validation + +Status: in progress, tracked by [#3374](https://github.com/RocketSurgeonsGuild/LaunchPad/issues/3374). The runtime package (`src/Validation`) exists, and the generator (`src/Validation.Analyzers`) writes validators from attribute rules; function and class validators, and everything under "What the manifest makes work", are not built yet. "As built" at the end lists where the code differs from this document. The decision is [ADR-0012](../adr/0012-launchpad-owns-validation.md). + +## Objective + +LaunchPad owns validation. A new package, `Rocket.Surgery.LaunchPad.Validation`, with its own analyzer package, writes one validator per validated type at build time. It replaces ZeroAlloc.Validation everywhere in this repository. + +Why: ZeroAlloc.Validation is attribute-only, its generator can't compose with `[Mutable]` and `[InheritFrom]`, and LaunchPad controls neither its output nor its vocabulary. + +The rules of a type come from several places, and the generator merges all of them into one generated validator: + +1. LaunchPad rule attributes on the type's members (a full set, one per fluent rule). +2. `System.ComponentModel.DataAnnotations` attributes, compiled to inline checks. +3. Function validators: `static void Validate(IValidationBuilder v, ...dependencies)`. +4. Class validators: a class with constructor-injected dependencies that implements `Validate(IValidationBuilder v)`. +5. The rules of `T`'s base classes and interfaces. +6. The rules carried over by `[InheritFrom]` and `[Mutable]`. + +Nothing is interpreted at run time: no reflection, no expression trees, no rule objects. The `Validate` bodies are a build-time DSL; the generator reads them and they never execute. + +### Out of scope + +- FluentValidation API compatibility, or a migration shim from it. +- A runtime rule engine, or rules defined at run time. +- Arbitrary C# statements in a `Validate` body. +- A separate repository. + +## Decisions and assumptions + +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. +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**: attributes, then base class and interface rules, then inherited (`[InheritFrom]`) rules, then the type's own functions and classes in a stable order (assembly, then file path, then position). Every rule runs; a chain stops at its first failure only where `.StopOnFailure()` says so. +4. **Nested values are validated where asked** _(decided)_: `[ValidateNested]` on the member, or `.ValidateWith()` in a chain, validates it with its type's validator (a collection item by item) and prefixes its failures with the member's path. An analyzer warns on every member whose type has rules and that is marked neither `[ValidateNested]` nor `[SkipValidation]`, with a fix for each. +5. **Containing types are partial.** The generator writes the validator inside the type that declares the function or class, so the rewritten rules can reach its private members and the captured dependencies. A non-partial container is a build error. +6. **Dependencies** of every function and class that contributes to `T` become constructor parameters of the generated validator, resolved from DI. A `CancellationToken` parameter is the call's token, not a dependency. Dependencies travel with carried rules _(decided)_: a type that inherits a rule that needs a service takes that service too, and one that inherits an async rule is async-only. +7. **Attribute name overlap** _(decided)_. LaunchPad's `[MaxLength]`, `[MinLength]`, `[Range]`, `[EmailAddress]` and others share names with DataAnnotations (and `[MaxLength]`, `[Regex]`, `[Trim]` with Primitives' rule attributes, which are `internal` and generated into each project). The LaunchPad attributes live in `Rocket.Surgery.LaunchPad.Validation.Rules`, a namespace of their own that a file imports deliberately, and an analyzer reports the ambiguous case with a fix. A member typed as a domain primitive is valid by construction; its Primitives rules are not repeated. +8. **Integrations stay packages** _(decided)_, renamed from `Rocket.Surgery.LaunchPad.ZeroAlloc.*` to `Rocket.Surgery.LaunchPad.Validation.{AspNetCore,Blazor,Grpc,HotChocolate}` ([ADR-0002](../adr/0002-package-per-integration.md)). +9. **Diagnostics** are `LPAD3001` and up (analyzers) and `LPAD3101` and up (generator). + +## Authoring + +```csharp +using Rocket.Surgery.LaunchPad.Validation; +using Rocket.Surgery.LaunchPad.Validation.Rules; + +public static partial class CreateRocket +{ + public readonly partial record struct Request + { + [NotEmpty, MinLength(10), MaxLength(30)] + public string SerialNumber { get; init; } + + [IsInEnum] + public RocketType Type { get; init; } + + public ImmutableArray Stages { get; init; } + public Crew? Crew { get; init; } + } + + // A function validator: the builder first, then whatever it needs injected. + private static void Validate(IValidationBuilder v, IRocketCatalog catalog) + { + v.Ensure(x => x.Crew).NotNull().When(x => x.Type == RocketType.Crewed); + + v.EnsureEach(x => x.Stages, stage => stage.Ensure(x => x.Thrust).GreaterThan(0)); + + v.Ensure(x => x.SerialNumber) + .MustAsync((serial, ct) => catalog.IsFree(serial, ct)) + .WithCode("SerialNumberTaken") + .WithMessage("{Name} '{Value}' is already in use"); + } +} + +// A class validator: dependencies in the constructor. +internal partial class RequestValidator(TimeProvider time) : IValidator +{ + public void Validate(IValidationBuilder v) => + v.Ensure(x => x.ScheduledLaunchDate).GreaterThan(_ => time.GetUtcNow()); +} + +// Rules for everything that implements an interface, or derives from a base class. +internal static partial class AuditRules +{ + private static void Validate(IValidationBuilder v) => v.Ensure(x => x.OwnerId).NotDefault(); +} +``` + +### The builder vocabulary + +| Call | Meaning | +| ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `v.Ensure(x => x.Member)` | Starts a chain of rules for one member. `v.Ensure(x => x)` starts one for the whole value (cross-member rules). | +| `v.EnsureEach(x => x.Items, item => ...)` | Rules for each item of a collection; the callback gets a builder of the item type. Simple items take rules directly: `v.EnsureEach(x => x.Tags).NotEmpty()`. | +| `.NotNull()`, `.NotEmpty()`, `.NotDefault()`, `.MaxLength(n)`, `.GreaterThan(...)`, ... | Built-in rules. Each has an attribute of the same name. A comparison takes a constant or a lambda over the model. | +| `.Must(predicate)`, `.MustAsync(predicate)` | A custom rule: a lambda or a method group, over the member's value or over `(model, value)`. | +| `.When(x => ...)`, `.Unless(x => ...)` | The chain's rules so far apply only under the condition. | +| `v.When(x => ..., v => { ... })` | A group of chains under one condition. | +| `.WithMessage(template)`, `.WithCode(code)`, `.WithSeverity(severity)`, `.WithName(name)` | Change the preceding rule's failure. Templates take `{Name}`, `{Value}` and the rule's own placeholders, with format specifiers. | +| `.StopOnFailure()` | The chain stops at its first failing rule. | +| `.ValidateNested()`, `.ValidateWith()` | Validates the member with the validator of its type, or with a named one. | +| `v.Include()` | Applies the rules of another type whose members `T` shares by name and type. | + +A rule is checked by a static method that returns `bool` (the built-in ones are on `Rule`) and carries its code and message in a `[RuleDefaults]`. The extension method of `IMemberRules` that declares it, and the attribute of the same name, each carry a `[ValidationRule(typeof(Rule), nameof(Rule.MaxLength))]` that names it; the generator writes a call to the method, with the member's value and then the arguments. That is how an application or library adds to the vocabulary: its own method, extension method and attribute (derived from `RuleAttribute`). + +### What a `Validate` body may contain + +Only builder calls, as expression statements or an expression body. Lambdas may read the model, the member's value, the function's parameters and the class's fields, and may call any method. Anything else (locals, `if`, loops, `await` outside a `MustAsync` lambda) is a build error that names the statement. + +### Discovery + +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 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. + +## What is generated + +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. +- 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. + +The manifest is what makes the rest work from metadata, with no source to read: + +- **`[InheritFrom]`**: the inheriting type's validator calls `TSource`'s rule methods for each copied member with its own values, in the same assembly or from a reference. A rule that reads an excluded member is dropped with a warning. The inheriting type's own attributes, functions and classes add to them. +- **Base classes and interfaces**: the same, for the members they declare. +- **`[Mutable]`**: the view model's validator validates the whole value as `TTarget` (as today, through `ToImmutable()`), and adds a per-member entry point that calls `TTarget`'s rule methods for one member, which is what a Blazor field needs. A member with only synchronous rules validates synchronously; one with async rules validates asynchronously and the Blazor integration shows the field as pending until it finishes. Submit awaits the whole validator. No rule is skipped. The generator recognises `[Mutable]` and `[InheritFrom]` by name and derives their members with the same code LaunchPad's analyzer uses (`src/Shared`, linked into both). +- **OpenAPI**: the API generators read the built-in rules' kinds and arguments from the manifest instead of ZeroAlloc's attributes (`src/Analyzers/Api/Core/SchemaRules.cs`). + +### 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. + +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. + +## As built + +Where the code so far differs from the text above: + +- **Registration** is `Add{AssemblyName}Validators()`, public, one per assembly, and it calls the same method of each referenced assembly. 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. +- **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 until function validators arrive. +- **Generic types** with rules are an error (LPAD3101) for now. +- **LPAD3001** looks only at types that have rules themselves: a type with no rules and a member whose type has them is not reported. + +## Tech stack + +- .NET 11, C# 15, `$(LaunchPadTargetFrameworks)`; the analyzer package targets `netstandard2.0`. +- Roslyn incremental generators; the generated code and the manifest are the only contract between assemblies. +- No dependency on any other LaunchPad package. `Microsoft.Extensions.DependencyInjection.Abstractions` only. +- Tests on TUnit with Verify snapshots, as everywhere else. + +## Commands + +``` +Build: mise run build +Test: dotnet run --project test/Validation.Tests + dotnet run --project test/Validation.Analyzers.Tests +Format: hk fix +Check: hk check +``` + +## Project structure + +``` +src/Validation/ runtime: builder and validator interfaces, result types, rule attributes, built-in rule methods +src/Validation/build/ MSBuild properties and Joint templates +src/Validation.Analyzers/ generator, analyzers, code fixes (an exception to ADR-0004, as Primitives is) +src/Shared/ the [Mutable] and [InheritFrom] member models, linked into both analyzer assemblies +src/Validation.{AspNetCore,Blazor,Grpc,HotChocolate}/ the integrations, replacing src/ZeroAlloc.* +test/Validation.Tests/ behaviour of generated validators +test/Validation.Analyzers.Tests/ generator snapshots and diagnostics +docs/adr/0012-launchpad-owns-validation.md +``` + +## Testing strategy + +- **Generator snapshots** (Verify) for each rule source alone and merged: attributes, DataAnnotations, function, class, base class, interface, `[InheritFrom]` (same assembly and referenced), `[Mutable]`. +- **Behaviour tests** that run the generated validators: every built-in rule's pass and fail cases, paths for nested values and collections, conditions, messages and placeholders, severity, sync and async entry points. +- **Diagnostics tests** for each `LPAD3xxx`, with the code fix where there is one. +- **End to end** in `test/Sdk.Tests`: a packed package, a throwaway application, and a referenced library whose rules are inherited across the assembly boundary. +- **AOT**: one of the samples `build/Samples.cs` publishes with native AOT validates a request, with no trim or AOT warnings from the package. +- The existing `test/ZeroAlloc.*.Tests` and sample tests are ported, not rewritten: they are the regression suite for the integrations. + +## Plan + +Each phase is one or more sub-issues of a new epic; later phases depend on earlier ones. + +1. **ADR-0012 and the runtime package**: interfaces, result types, rule attributes, built-in rule methods. No generator. +2. **Generator, attributes only**: validators, rule methods, manifest and registration for LaunchPad attributes and DataAnnotations; nested values and collections. +3. **Function and class validators**: the DSL, dependencies, sync and async, the body diagnostics. +4. **Composition**: base classes and interfaces, `[InheritFrom]`, `[Mutable]` (moving the validator out of `MutableGenerator`), across assemblies. +5. **Integrations**: mediator pipeline on Keryx, ASP.NET Core problem details and OpenAPI, gRPC, HotChocolate, Blazor, options. The API generators read the manifest. +6. **Port and remove**: samples, `LaunchPadHealthCheckOptions`, the SDK's detection targets, docs site, `AGENTS.md`, `GLOSSARY.md`, the readme; ZeroAlloc.Validation and its packages leave `Directory.Packages.props`. + +Phases 2 to 4 can't run in parallel (one generator); the integrations of phase 5 can, once phase 4's manifest is stable. The mediator part of phase 5 waits for the Keryx switch to land. + +## Boundaries + +- **Always**: generated code only, no reflection or expression trees; every rule has an attribute and a fluent form with the same name; a new diagnostic for every construct the generator refuses; update `AGENTS.md` and the glossary in the pull request that makes them untrue. +- **Ask first**: adding, renaming or removing a package (each needs its ticket); a dependency beyond `Microsoft.Extensions.DependencyInjection.Abstractions`; touching mediator code while the Keryx switch is in flight; changing `[Mutable]` or `[InheritFrom]` behaviour beyond validation. +- **Never**: a runtime fallback that interprets rules; a `Version` in a `.csproj`; editing `plans/dovetail-migration.md`. + +## Success criteria + +- 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. +- 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. +- Options classes are validated at startup with no reflection. +- An application replaces a built-in rule's message through `IValidationMessageProvider` without changing a rule. +- A native AOT sample publishes with no warnings from validation and rejects an invalid request. +- `mise run build` passes on CI. + +## Open questions + +None from the interview. Still unreviewed among the assumptions: the merge order (3), partial containing types (5) and the diagnostic ID ranges (9). diff --git a/src/Validation.Analyzers/AnalyzerReleases.Unshipped.md b/src/Validation.Analyzers/AnalyzerReleases.Unshipped.md new file mode 100644 index 00000000000..cba2892e3c5 --- /dev/null +++ b/src/Validation.Analyzers/AnalyzerReleases.Unshipped.md @@ -0,0 +1,14 @@ +; Unshipped analyzer release +; + +### New Rules + +Rule ID | Category | Severity | Notes +--------|----------|----------|------- +LPAD3001 | LaunchPad.Validation | Warning | NestedValidationAnalyzer, a member whose type has rules says neither [ValidateNested] nor [SkipValidation] +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 +LPAD3104 | LaunchPad.Validation | Warning | ValidatorGenerator, a System.ComponentModel.DataAnnotations attribute the generator doesn't compile +LPAD3105 | LaunchPad.Validation | Error | ValidatorGenerator, a rule's argument is not valid +LPAD3106 | LaunchPad.Validation | Error | ValidatorGenerator, [ValidateNested] on a member whose type can't be validated diff --git a/src/Validation.Analyzers/Diagnostics.cs b/src/Validation.Analyzers/Diagnostics.cs new file mode 100644 index 00000000000..0443f1e896e --- /dev/null +++ b/src/Validation.Analyzers/Diagnostics.cs @@ -0,0 +1,86 @@ +using Microsoft.CodeAnalysis; + +namespace Rocket.Surgery.LaunchPad.Validation.Analyzers; + +/// +/// The diagnostics of LaunchPad's validation: LPAD3001 and up are what the analyzers report, LPAD3101 and up are what the generator can't +/// write a validator for. +/// +internal static class Diagnostics +{ + public const string Category = "LaunchPad.Validation"; + + public static readonly DiagnosticDescriptor NestedValidationNotDecided = new( + "LPAD3001", + "A member whose type has rules is not validated", + "'{0}' is a {1}, which has rules, but they are not applied here: add [ValidateNested] to validate it, or [SkipValidation] to say it is deliberate", + Category, + DiagnosticSeverity.Warning, + true + ); + + public static readonly DiagnosticDescriptor GenericType = new( + "LPAD3101", + "A generic type can't be validated yet", + "'{0}' has rules, but it is generic or inside a generic type, which the generator doesn't write a validator for yet", + Category, + DiagnosticSeverity.Error, + true + ); + + public static readonly DiagnosticDescriptor NotAccessible = new( + "LPAD3102", + "The generated validator can't reach it", + "{0} must be public or internal for its rules to be checked: the generated validator is a class of its own", + Category, + DiagnosticSeverity.Error, + true + ); + + public static readonly DiagnosticDescriptor RuleDoesNotApply = new( + "LPAD3103", + "The rule doesn't apply to the member", + "[{0}] can't be checked on '{1}', which is of type {2}: {3}", + Category, + DiagnosticSeverity.Error, + true + ); + + public static readonly DiagnosticDescriptor UnsupportedDataAnnotation = new( + "LPAD3104", + "The attribute is not compiled into the validator", + "[{0}] on '{1}' is not checked by the generated validator: {2}", + Category, + DiagnosticSeverity.Warning, + true + ); + + public static readonly DiagnosticDescriptor InvalidArgument = new( + "LPAD3105", + "The rule's argument is not valid", + "[{0}] on '{1}': {2}", + Category, + DiagnosticSeverity.Error, + true + ); + + public static readonly DiagnosticDescriptor NestedNotValidatable = new( + "LPAD3106", + "The member can't be validated with a validator", + "'{0}' is marked for nested validation, but {1}", + Category, + DiagnosticSeverity.Error, + true + ); + + public static DiagnosticDescriptor? Find(string id) => id switch + { + "LPAD3101" => GenericType, + "LPAD3102" => NotAccessible, + "LPAD3103" => RuleDoesNotApply, + "LPAD3104" => UnsupportedDataAnnotation, + "LPAD3105" => InvalidArgument, + "LPAD3106" => NestedNotValidatable, + _ => null, + }; +} diff --git a/src/Validation.Analyzers/Model/EquatableArray.cs b/src/Validation.Analyzers/Model/EquatableArray.cs new file mode 100644 index 00000000000..41ccbca9285 --- /dev/null +++ b/src/Validation.Analyzers/Model/EquatableArray.cs @@ -0,0 +1,41 @@ +using System.Collections; +using System.Collections.Immutable; + +namespace Rocket.Surgery.LaunchPad.Validation.Analyzers.Model; + +/// +/// An immutable array compared by its items, so a model that holds one stays cacheable in an incremental generator. +/// +internal readonly struct EquatableArray(ImmutableArray items) : IEquatable>, IEnumerable + where T : IEquatable +{ + public static EquatableArray Empty { get; } = new([]); + + public ImmutableArray Items => items.IsDefault ? [] : items; + public int Length => Items.Length; + public T this[int index] => Items[index]; + + public bool Equals(EquatableArray other) => Items.AsSpan().SequenceEqual(other.Items.AsSpan()); + public override bool Equals(object? obj) => obj is EquatableArray other && Equals(other); + + public override int GetHashCode() + { + var hash = 17; + foreach (var item in Items) + { + hash = unchecked(( hash * 31 ) + ( item?.GetHashCode() ?? 0 )); + } + + return hash; + } + + public IEnumerator GetEnumerator() => ( (IEnumerable)Items ).GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + public static implicit operator EquatableArray(ImmutableArray items) => new(items); +} + +internal static class EquatableArray +{ + public static EquatableArray ToEquatableArray(this IEnumerable items) where T : IEquatable => new([.. items]); +} diff --git a/src/Validation.Analyzers/Model/Models.cs b/src/Validation.Analyzers/Model/Models.cs new file mode 100644 index 00000000000..2c828e7aaec --- /dev/null +++ b/src/Validation.Analyzers/Model/Models.cs @@ -0,0 +1,75 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Text; + +namespace Rocket.Surgery.LaunchPad.Validation.Analyzers.Model; + +/// A type that has rules, and everything the generator writes its validator from. It holds no symbols, so the generator can cache it. +internal sealed record ValidatedTypeModel( + string Namespace, + string ValidatorName, + string Type, + string DocumentationName, + string HintName, + bool IsPublic, + bool IsReferenceType, + EquatableArray Members +) +{ + /// The validator's name with its namespace, as generated code refers to it. + public string ValidatorFullName => Namespace.Length == 0 ? "global::" + ValidatorName : "global::" + Namespace + "." + ValidatorName; +} + +/// What the syntax provider makes of a type declaration: the model, if the type has rules the generator can write, and what it reports. +internal sealed record ValidatedTypeResult(ValidatedTypeModel? Model, EquatableArray Diagnostics); + +/// A member with rules, or one validated with a validator of its own. +internal sealed record MemberModel( + string Name, + string Type, + bool ReadsValue, + EquatableArray Reads, + EquatableArray Rules, + EquatableArray Regexes, + NestedModel? Nested +); + +/// Another member a rule reads: the one a comparison is made with. +internal sealed record ReadModel(string Name, string Parameter, string Type); + +/// One rule of a member, ready to write. +/// The expression that is when the value meets the rule. +/// The code of its failures. +/// The message template of its failures. +/// The ValidationSeverity member's name. +/// The message's placeholders after {Name} and {Value}. +/// The rule as the manifest states it: MaxLength(30). +internal sealed record RuleModel(string Check, string Code, string Message, string Severity, EquatableArray Arguments, string Manifest); + +/// A placeholder of a rule's message and the expression of its value. +internal sealed record ArgumentModel(string Name, string Expression); + +/// A regular expression a rule matches against, held in a field of the validator. +internal sealed record RegexModel(string Field, string Pattern, string Options); + +/// How a member is validated with a validator of its own. +/// The type the validator is asked of the service provider as. +/// 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 Service, bool IsCollection, bool CanBeNull, bool ItemCanBeNull); + +/// A diagnostic without its symbols: the descriptor's id, where it is, and its arguments. +internal sealed record DiagnosticModel(string Id, string? Path, TextSpan Span, LinePositionSpan LineSpan, EquatableArray Arguments) +{ + public static DiagnosticModel Create(DiagnosticDescriptor descriptor, Location? location, params string[] arguments) => new( + descriptor.Id, + location?.SourceTree?.FilePath, + location?.SourceSpan ?? default, + location?.GetLineSpan().Span ?? default, + arguments.ToEquatableArray() + ); + + public Diagnostic? ToDiagnostic() => Diagnostics.Find(Id) is { } descriptor + ? Diagnostic.Create(descriptor, Path is null ? Location.None : Location.Create(Path, Span, LineSpan), [.. Arguments.Items]) + : null; +} diff --git a/src/Validation.Analyzers/Model/RuleReader.cs b/src/Validation.Analyzers/Model/RuleReader.cs new file mode 100644 index 00000000000..c2e6ccbadf6 --- /dev/null +++ b/src/Validation.Analyzers/Model/RuleReader.cs @@ -0,0 +1,517 @@ +using System.Globalization; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; + +namespace Rocket.Surgery.LaunchPad.Validation.Analyzers.Model; + +/// +/// Reads the rules the attributes of a type's members declare: LaunchPad's rule attributes, and the +/// System.ComponentModel.DataAnnotations attributes the generator compiles. +/// +/// +/// Which method checks a rule is decided by C#: the reader binds the call the generator will write (the method the attribute's +/// [ValidationRule] names, with the member's value and the attribute's arguments) and takes the overload the compiler picks, its +/// code and message, and the names of its parameters for the message's placeholders. +/// +internal sealed class RuleReader +{ + private const string Rule = "global::" + ValidationSymbols.RulesNamespace + ".Rule"; + private const string Regex = "global::System.Text.RegularExpressions.Regex"; + private const string Invariant = "global::System.Globalization.CultureInfo.InvariantCulture"; + + public static ValidatedTypeResult Read(INamedTypeSymbol type, SemanticModel model, int position) + { + var reader = new RuleReader(type, model, position); + var members = new List(); + foreach (var member in ValidationSymbols.Members(type)) + { + var attributes = ValidationSymbols.AttributesOf(member).Where(static z => ValidationSymbols.IsRelevant(z.AttributeClass)).ToList(); + if (attributes.Count == 0) continue; + if (reader.ReadMember(member, attributes) is { } read) members.Add(read); + } + + if (members.Count == 0) return new(null, reader._diagnostics.ToEquatableArray()); + + var location = type.Locations.FirstOrDefault(); + var containers = new List(); + for (var current = type; current is not null; current = current.ContainingType) + { + containers.Insert(0, current); + } + + if (containers.Any(static z => z.IsGenericType)) + { + reader.Report(Diagnostics.GenericType, location, type.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); + return new(null, reader._diagnostics.ToEquatableArray()); + } + + if (containers.Any(static z => z.DeclaredAccessibility is not ( Accessibility.Public or Accessibility.Internal ) || z.IsFileLocal)) + { + reader.Report(Diagnostics.NotAccessible, location, "'" + type.Name + "' and the types that contain it"); + return new(null, reader._diagnostics.ToEquatableArray()); + } + + var @namespace = type.ContainingNamespace is { IsGlobalNamespace: false } ns ? ns.ToDisplayString() : ""; + var name = string.Join("_", containers.Select(static z => z.Name)); + return new( + new( + @namespace, + name + "Validator", + type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), + type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat).Replace("global::", "").Replace('<', '{').Replace('>', '}'), + ( @namespace.Length == 0 ? name : @namespace + "." + name ) + ".Validator.g.cs", + containers.All(static z => z.DeclaredAccessibility == Accessibility.Public), + type.IsReferenceType, + members.ToEquatableArray() + ), + reader._diagnostics.ToEquatableArray() + ); + } + + private readonly INamedTypeSymbol _type; + private readonly SemanticModel _model; + private readonly int _position; + private readonly List _diagnostics = []; + internal static readonly string[] first = ["value",]; + + private RuleReader(INamedTypeSymbol type, SemanticModel model, int position) + { + _type = type; + _model = model; + _position = position; + } + + // What is gathered for one member while its attributes are read. + private sealed class MemberContext(ISymbol member, ITypeSymbol type) + { + public ISymbol Member { get; } = member; + public ITypeSymbol Type { get; } = type; + public string TypeName { get; } = type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + public List Rules { get; } = []; + public List Reads { get; } = []; + public List Regexes { get; } = []; + public bool ReadsValue { get; set; } + public NestedModel? Nested { get; set; } + } + + // An argument of a rule: what the generated call passes, what stands in for it when the call is bound, and how the manifest states it. + private readonly record struct Argument(string Expression, string Binding, string Manifest) + { + public static Argument Constant(string expression, string? manifest = null) => new(expression, expression, manifest ?? expression); + } + + private void Report(DiagnosticDescriptor descriptor, Location? location, params string[] arguments) => + _diagnostics.Add(DiagnosticModel.Create(descriptor, location, arguments)); + + private static Location? LocationOf(AttributeData attribute) => attribute.ApplicationSyntaxReference?.GetSyntax().GetLocation(); + + private static string NameOf(AttributeData attribute) => + attribute.AttributeClass is { } type ? type.Name.EndsWith("Attribute", StringComparison.Ordinal) ? type.Name[..^9] : type.Name : "?"; + + private MemberModel? ReadMember(ISymbol member, List attributes) + { + var accessible = member.DeclaredAccessibility is Accessibility.Public or Accessibility.Internal + && ( member is not IPropertySymbol { GetMethod: { } getter } || getter.DeclaredAccessibility is Accessibility.Public or Accessibility.Internal ); + if (!accessible) + { + Report(Diagnostics.NotAccessible, member.Locations.FirstOrDefault(), "'" + member.Name + "'"); + return null; + } + + var context = new MemberContext(member, ValidationSymbols.TypeOf(member)); + foreach (var attribute in attributes) + { + var type = attribute.AttributeClass!; + if (ValidationSymbols.IsValidateNested(type) || ValidationSymbols.IsValidateWith(type)) + { + ReadNested(context, attribute); + } + else if (ValidationSymbols.IsRuleAttribute(type)) + { + ReadRule(context, attribute); + } + else + { + ReadDataAnnotation(context, attribute); + } + } + + return context.Rules.Count == 0 && context.Nested is null + ? null + : new( + member.Name, + context.Type.ToDisplayString(ValidationSymbols.Annotated), + context.ReadsValue, + context.Reads.ToEquatableArray(), + context.Rules.ToEquatableArray(), + context.Regexes.ToEquatableArray(), + context.Nested + ); + } + + private void ReadNested(MemberContext context, AttributeData attribute) + { + var item = ValidationSymbols.ItemType(context.Type); + var target = ValidationSymbols.Underlying(item ?? context.Type); + if (target is not INamedTypeSymbol { SpecialType: SpecialType.None, TypeKind: TypeKind.Class or TypeKind.Struct or TypeKind.Interface }) + { + Report( + Diagnostics.NestedNotValidatable, + LocationOf(attribute), + context.Member.Name, + "its type, " + target.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat) + ", is not one a validator is written for" + ); + return; + } + + var service = ValidationSymbols.IsValidateWith(attribute.AttributeClass) + ? attribute.AttributeClass!.TypeArguments[0].ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) + : "global::" + ValidationSymbols.RuntimeNamespace + ".IValidate<" + target.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) + ">"; + context.Nested = new(service, item is not null, ValidationSymbols.CanBeNull(context.Type), item is not null && ValidationSymbols.CanBeNull(item)); + } + + private void ReadRule(MemberContext context, AttributeData attribute) + { + var type = attribute.AttributeClass!; + if (ValidationSymbols.Is(type, ValidationSymbols.RulesNamespace, "MustAttribute")) + { + ReadMust(context, attribute); + return; + } + + if (ValidationSymbols.Is(type, ValidationSymbols.RulesNamespace, "MatchesAttribute")) + { + if (attribute.ConstructorArguments is not [{ Value: string pattern }]) return; + var options = Named(attribute, "Options") is { Value: int value } ? value : 0; + AddRule(context, attribute, Rule, "Matches", [AddRegex(context, pattern, options)]); + return; + } + + if (RuleMethod(type) is not var (container, method)) + { + Report(Diagnostics.InvalidArgument, LocationOf(attribute), NameOf(attribute), context.Member.Name, "the attribute has no [ValidationRule] that names the method that checks it"); + return; + } + + var arguments = new List(); + if (ValidationSymbols.Inherits(type, ValidationSymbols.RulesNamespace, "ComparisonRuleAttribute")) + { + if (Named(attribute, "Member") is { Value: string other }) + { + if (ReadOther(context, attribute, other) is not { } read) return; + arguments.Add(read); + } + else if (attribute.ConstructorArguments is [var constant]) + { + if (Convert(context, attribute, constant) is not { } converted) return; + arguments.Add(converted); + } + else + { + Report(Diagnostics.InvalidArgument, LocationOf(attribute), NameOf(attribute), context.Member.Name, "it needs a value, or the name of another member in Member"); + return; + } + } + else + { + var parameters = attribute.AttributeConstructor?.Parameters ?? []; + for (var i = 0; i < attribute.ConstructorArguments.Length; i++) + { + var constant = attribute.ConstructorArguments[i]; + if (i < parameters.Length && parameters[i].Type.SpecialType == SpecialType.System_Object) + { + if (Convert(context, attribute, constant) is not { } converted) return; + arguments.Add(converted); + } + else + { + arguments.Add(Argument.Constant(constant.ToCSharpString())); + } + } + } + + AddRule(context, attribute, container, method, arguments); + } + + private void ReadMust(MemberContext context, AttributeData attribute) + { + if (attribute.ConstructorArguments is not [{ Value: string name }]) return; + var candidates = new List(); + for (var current = _type; current is not null; current = current.BaseType) + { + candidates.AddRange(current.GetMembers(name).OfType().Where(static z => z.Parameters.Length == 1)); + } + + var conversions = _model.Compilation; + var method = candidates.FirstOrDefault(z => z.ReturnType.SpecialType == SpecialType.System_Boolean + && conversions.ClassifyConversion(context.Type, z.Parameters[0].Type) is { IsImplicit: true }); + if (method is null) + { + var reason = candidates.Any(static z => z.ReturnType.Name is "ValueTask" or "Task") + ? "'" + name + "' is asynchronous, which an attribute can't declare yet: declare the rule with MustAsync in a Validate function" + : "'" + _type.Name + "' has no method '" + name + "' that takes the member's value and returns bool"; + Report(Diagnostics.InvalidArgument, LocationOf(attribute), NameOf(attribute), context.Member.Name, reason); + return; + } + + if (method.DeclaredAccessibility is not ( Accessibility.Public or Accessibility.Internal )) + { + Report(Diagnostics.NotAccessible, LocationOf(attribute), "'" + name + "'"); + return; + } + + string check; + if (method.IsStatic) + { + check = method.ContainingType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) + "." + method.Name + "(value)"; + } + else + { + context.ReadsValue = true; + check = "instance." + method.Name + "(value)"; + } + + context.Rules.Add(Finish(attribute, new(check, "Must", "{Name} is not valid", "Error", EquatableArray.Empty, "Must(" + name + ")"), [])); + } + + private void ReadDataAnnotation(MemberContext context, AttributeData attribute) + { + var arguments = attribute.ConstructorArguments; + switch (attribute.AttributeClass!.Name) + { + case "RequiredAttribute": + var allowEmpty = Named(attribute, "AllowEmptyStrings") is { Value: true }; + AddRule(context, attribute, Rule, context.Type.SpecialType == SpecialType.System_String && !allowEmpty ? "NotEmpty" : "NotNull", []); + break; + case "StringLengthAttribute" when arguments is [{ Value: int longest }]: + if (Named(attribute, "MinimumLength") is { Value: int and > 0 and var shortest }) + { + AddRule(context, attribute, Rule, "Length", [Number(shortest), Number(longest)]); + } + else + { + AddRule(context, attribute, Rule, "MaxLength", [Number(longest)]); + } + + break; + case "MaxLengthAttribute": + // No length, or -1, is "the most the database allows": nothing to check. + if (arguments is [{ Value: int and >= 0 and var most }]) AddRule(context, attribute, Rule, "MaxLength", [Number(most)]); + break; + case "MinLengthAttribute" when arguments is [{ Value: int least }]: + AddRule(context, attribute, Rule, "MinLength", [Number(least)]); + break; + case "LengthAttribute" when arguments is [{ Value: int from }, { Value: int to }]: + AddRule(context, attribute, Rule, "Length", [Number(from), Number(to)]); + break; + case "RangeAttribute" when arguments is [var low, var high]: + if (Convert(context, attribute, low) is not { } lower || Convert(context, attribute, high) is not { } upper) break; + var minimumIsExclusive = Named(attribute, "MinimumIsExclusive") is { Value: true }; + var maximumIsExclusive = Named(attribute, "MaximumIsExclusive") is { Value: true }; + if (minimumIsExclusive == maximumIsExclusive) + { + AddRule(context, attribute, Rule, minimumIsExclusive ? "ExclusiveBetween" : "InclusiveBetween", [lower, upper]); + } + else + { + AddRule(context, attribute, Rule, minimumIsExclusive ? "GreaterThan" : "GreaterThanOrEqualTo", [lower]); + AddRule(context, attribute, Rule, maximumIsExclusive ? "LessThan" : "LessThanOrEqualTo", [upper]); + } + + break; + case "RangeAttribute": + Unsupported(context, attribute, "a range of a type and two strings is converted through reflection; use [InclusiveBetween], which parses its strings at build time"); + break; + case "RegularExpressionAttribute" when arguments is [{ Value: string pattern }]: + // The attribute matches the whole value. + AddRule(context, attribute, Rule, "Matches", [AddRegex(context, "^(?:" + pattern + ")$", 0)]); + break; + case "EmailAddressAttribute": + AddRule(context, attribute, Rule, "EmailAddress", []); + break; + case "UrlAttribute": + AddRule(context, attribute, Rule, "Url", []); + break; + case "CompareAttribute" when arguments is [{ Value: string other }]: + if (ReadOther(context, attribute, other) is { } read) AddRule(context, attribute, Rule, "Equal", [read]); + break; + default: + Unsupported(context, attribute, "use a LaunchPad rule attribute, or [Must] with a method of the type"); + break; + } + } + + private void Unsupported(MemberContext context, AttributeData attribute, string reason) => + Report(Diagnostics.UnsupportedDataAnnotation, LocationOf(attribute), NameOf(attribute), context.Member.Name, reason); + + private static Argument Number(int value) => Argument.Constant(value.ToString(CultureInfo.InvariantCulture)); + + private static TypedConstant? Named(AttributeData attribute, string name) + { + foreach (var argument in attribute.NamedArguments) + { + if (argument.Key == name) return argument.Value; + } + + return null; + } + + private static (string Container, string Method)? RuleMethod(INamedTypeSymbol attribute) + { + for (var current = attribute; current is not null; current = current.BaseType) + { + foreach (var candidate in current.GetAttributes()) + { + if (ValidationSymbols.Is(candidate.AttributeClass, ValidationSymbols.RulesNamespace, "ValidationRuleAttribute") + && candidate.ConstructorArguments is [{ Value: INamedTypeSymbol container }, { Value: string method }]) + { + return (container.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), method); + } + } + } + + return null; + } + + private Argument AddRegex(MemberContext context, string pattern, int options) + { + var field = context.Member.Name + "Pattern" + ( context.Regexes.Count == 0 ? "" : context.Regexes.Count.ToString(CultureInfo.InvariantCulture) ); + context.Regexes.Add( + new(field, SymbolDisplay.FormatLiteral(pattern, true), "(global::System.Text.RegularExpressions.RegexOptions)" + options.ToString(CultureInfo.InvariantCulture)) + ); + return new(field, "default(" + Regex + ")", SymbolDisplay.FormatLiteral(pattern, true)); + } + + private Argument? ReadOther(MemberContext context, AttributeData attribute, string name) + { + if (ValidationSymbols.Members(_type).FirstOrDefault(z => z.Name == name) is not { } other || other.Name == context.Member.Name) + { + Report(Diagnostics.InvalidArgument, LocationOf(attribute), NameOf(attribute), context.Member.Name, "'" + _type.Name + "' has no other member '" + name + "' to compare it with"); + return null; + } + + var type = ValidationSymbols.TypeOf(other); + var parameter = "other" + other.Name; + if (context.Reads.All(z => z.Name != other.Name)) context.Reads.Add(new(other.Name, parameter, type.ToDisplayString(ValidationSymbols.Annotated))); + return new(parameter, "default(" + type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) + ")", other.Name); + } + + // A constant an attribute takes as an object, as the member's type: a string is parsed, a number is converted. + private Argument? Convert(MemberContext context, AttributeData attribute, TypedConstant constant) + { + var target = ValidationSymbols.Underlying(context.Type); + var targetName = target.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + if (constant.IsNull || constant.Kind == TypedConstantKind.Array) + { + Report(Diagnostics.InvalidArgument, LocationOf(attribute), NameOf(attribute), context.Member.Name, "it is compared with one value, which can't be null"); + return null; + } + + var literal = constant.ToCSharpString(); + if (constant.Value is string text && target.SpecialType is not ( SpecialType.System_String or SpecialType.System_Object )) + { + var parses = target + .GetMembers("Parse") + .OfType() + .Any(static z => z is { IsStatic: true, Parameters: [{ Type.SpecialType: SpecialType.System_String }, { Type.Name: "IFormatProvider" }] }); + if (!parses) + { + Report( + Diagnostics.InvalidArgument, + LocationOf(attribute), + NameOf(attribute), + context.Member.Name, + literal + " can't be read as a " + target.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat) + ", which has no Parse(string, IFormatProvider)" + ); + return null; + } + + _ = text; + return new(targetName + ".Parse(" + literal + ", " + Invariant + ")", "default(" + targetName + ")", literal); + } + + if (constant.Kind == TypedConstantKind.Enum && constant.Type is { } enumType) + { + var value = System.Convert.ToString(constant.Value, CultureInfo.InvariantCulture); + return Argument.Constant("(" + enumType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) + ")(" + value + ")", literal); + } + + return IsNumber(target.SpecialType) && constant.Type is { } constantType && IsNumber(constantType.SpecialType) + ? Argument.Constant("(" + targetName + ")(" + literal + ")", literal) + : Argument.Constant(literal); + } + + private static bool IsNumber(SpecialType type) => type is >= SpecialType.System_SByte and <= SpecialType.System_Double; + + private void AddRule(MemberContext context, AttributeData attribute, string container, string method, IReadOnlyList arguments) + { + var binding = container + "." + method + "(" + string.Join(", ", new[] { "default(" + context.TypeName + ")", }.Concat(arguments.Select(static z => z.Binding))) + ")"; + var info = _model.GetSpeculativeSymbolInfo(_position, SyntaxFactory.ParseExpression(binding), SpeculativeBindingOption.BindAsExpression); + if (info.Symbol is not IMethodSymbol bound || bound.ReturnType.SpecialType != SpecialType.System_Boolean) + { + var reason = info.Symbol is IMethodSymbol + ? method + " is not a method that returns bool" + : "no " + container.Replace("global::", "") + "." + method + " takes that type" + + ( arguments.Count == 0 ? "" : " with " + string.Join(", ", arguments.Select(static z => z.Manifest)) ); + Report( + Diagnostics.RuleDoesNotApply, + LocationOf(attribute), + NameOf(attribute), + context.Member.Name, + context.Type.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat), + reason + ); + return; + } + + var code = method; + var message = "{Name} is not valid"; + foreach (var candidate in bound.OriginalDefinition.GetAttributes()) + { + if (ValidationSymbols.Is(candidate.AttributeClass, ValidationSymbols.RulesNamespace, "RuleDefaultsAttribute") + && candidate.ConstructorArguments is [{ Value: string defaultCode }, { Value: string defaultMessage }]) + { + code = defaultCode; + message = defaultMessage; + } + } + + var placeholders = new List(); + for (var i = 0; i < arguments.Count && i + 1 < bound.Parameters.Length; i++) + { + var name = bound.Parameters[i + 1].Name; + // A pattern is not something a message shows. + if (arguments[i].Binding == "default(" + Regex + ")") continue; + placeholders.Add(new(char.ToUpperInvariant(name[0]) + name[1..], arguments[i].Expression)); + } + + var check = container + "." + method + "(" + string.Join(", ", first.Concat(arguments.Select(static z => z.Expression))) + ")"; + var manifest = arguments.Count == 0 ? code : code + "(" + string.Join(", ", arguments.Select(static z => z.Manifest)) + ")"; + context.Rules.Add(Finish(attribute, new(check, code, message, "Error", placeholders.ToEquatableArray(), manifest), placeholders)); + } + + // The code, message and severity the attribute gives the rule in place of its own. + private static RuleModel Finish(AttributeData attribute, RuleModel rule, IReadOnlyList placeholders) + { + if (Named(attribute, "Code") is { Value: string code }) rule = rule with { Code = code, }; + if (Named(attribute, "Message") is { Value: string message }) rule = rule with { Message = message, }; + if (Named(attribute, "Severity") is { Value: int severity }) + { + rule = rule with { Severity = severity switch { 1 => "Warning", 2 => "Info", _ => "Error", }, }; + } + + // A DataAnnotations message numbers its placeholders: the member's name, then the attribute's arguments. + if (Named(attribute, "ErrorMessage") is { Value: string errorMessage }) + { + errorMessage = errorMessage.Replace("{0}", "{Name}"); + for (var i = 0; i < placeholders.Count; i++) + { + errorMessage = errorMessage.Replace("{" + ( i + 1 ).ToString(CultureInfo.InvariantCulture) + "}", "{" + placeholders[i].Name + "}"); + } + + rule = rule with { Message = errorMessage, }; + } + + return rule; + } +} diff --git a/src/Validation.Analyzers/Model/ValidationSymbols.cs b/src/Validation.Analyzers/Model/ValidationSymbols.cs new file mode 100644 index 00000000000..c923d07252f --- /dev/null +++ b/src/Validation.Analyzers/Model/ValidationSymbols.cs @@ -0,0 +1,133 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +namespace Rocket.Surgery.LaunchPad.Validation.Analyzers.Model; + +/// +/// What the generator and the analyzers both ask of a symbol: which attributes are rules, which members a type is validated by, whether a +/// type has rules at all. +/// +internal static class ValidationSymbols +{ + public const string RuntimeNamespace = "Rocket.Surgery.LaunchPad.Validation"; + public const string RulesNamespace = RuntimeNamespace + ".Rules"; + public const string DataAnnotationsNamespace = "System.ComponentModel.DataAnnotations"; + + /// A type as generated code names it, with the ? of a nullable reference type. + public static readonly SymbolDisplayFormat Annotated = + SymbolDisplayFormat.FullyQualifiedFormat.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier); + + public static bool IsRuleAttribute(INamedTypeSymbol? attribute) => Inherits(attribute, RulesNamespace, "RuleAttribute"); + + public static bool IsDataAnnotation(INamedTypeSymbol? attribute) => Inherits(attribute, DataAnnotationsNamespace, "ValidationAttribute"); + + public static bool IsValidateNested(INamedTypeSymbol? attribute) => Is(attribute, RulesNamespace, "ValidateNestedAttribute"); + + public static bool IsValidateWith(INamedTypeSymbol? attribute) => Is(attribute?.OriginalDefinition, RulesNamespace, "ValidateWithAttribute"); + + public static bool IsSkipValidation(INamedTypeSymbol? attribute) => Is(attribute, RulesNamespace, "SkipValidationAttribute"); + + /// Whether the attribute says how the member's own type is validated here. + public static bool DecidesNestedValidation(INamedTypeSymbol? attribute) => + IsValidateNested(attribute) || IsValidateWith(attribute) || IsSkipValidation(attribute); + + /// Whether the attribute is one the generator reads. + public static bool IsRelevant(INamedTypeSymbol? attribute) => + IsRuleAttribute(attribute) || IsDataAnnotation(attribute) || IsValidateNested(attribute) || IsValidateWith(attribute); + + public static bool Is(INamedTypeSymbol? type, string @namespace, string name) => + type is not null && type.Name == name && type.ContainingNamespace?.ToDisplayString() == @namespace; + + public static bool Inherits(INamedTypeSymbol? type, string @namespace, string name) + { + for (var current = type; current is not null; current = current.BaseType) + { + if (Is(current, @namespace, name)) return true; + } + + return false; + } + + /// The instance properties and fields a type is validated by, its own first and then those of its base classes. + public static IEnumerable Members(INamedTypeSymbol type) + { + var seen = new HashSet(StringComparer.Ordinal); + for (var current = type; current is { SpecialType: not SpecialType.System_Object }; current = current.BaseType) + { + foreach (var member in current.GetMembers()) + { + var candidate = member switch + { + IPropertySymbol { IsStatic: false, IsIndexer: false, GetMethod: not null, Name: not "EqualityContract" } => true, + IFieldSymbol { IsStatic: false, IsConst: false, IsImplicitlyDeclared: false } => true, + _ => false, + }; + if (candidate && seen.Add(member.Name)) yield return member; + } + } + } + + public static ITypeSymbol TypeOf(ISymbol member) => member switch + { + IPropertySymbol property => property.Type, + IFieldSymbol field => field.Type, + IParameterSymbol parameter => parameter.Type, + _ => throw new ArgumentOutOfRangeException(nameof(member)), + }; + + /// + /// The attributes of a member, with those of the primary constructor parameter it comes from: on a record, an attribute with no target + /// goes to the parameter. + /// + public static IEnumerable AttributesOf(ISymbol member) + { + foreach (var attribute in member.GetAttributes()) + { + yield return attribute; + } + + if (member is not IPropertySymbol property || PrimaryParameter(property) is not { } parameter) yield break; + foreach (var attribute in parameter.GetAttributes()) + { + yield return attribute; + } + } + + public static IParameterSymbol? PrimaryParameter(IPropertySymbol property) + { + foreach (var constructor in property.ContainingType.InstanceConstructors) + { + if (constructor.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() is not TypeDeclarationSyntax) continue; + foreach (var parameter in constructor.Parameters) + { + if (parameter.Name == property.Name && SymbolEqualityComparer.Default.Equals(parameter.Type, property.Type)) return parameter; + } + } + + return null; + } + + /// Whether a type has rules: a member of it carries one, or is validated with a validator of its own. + public static bool HasRules(ITypeSymbol? type) => + type is INamedTypeSymbol { SpecialType: SpecialType.None, TypeKind: TypeKind.Class or TypeKind.Struct } named + && Members(named).Any(static member => AttributesOf(member).Any(static attribute => IsRelevant(attribute.AttributeClass))); + + /// The type without the ? of a nullable value type. + public static ITypeSymbol Underlying(ITypeSymbol type) => + type is INamedTypeSymbol { OriginalDefinition.SpecialType: SpecialType.System_Nullable_T, TypeArguments: [var argument] } ? argument : type; + + /// The type of the items of a collection, or for anything that isn't one (a string is not). + public static ITypeSymbol? ItemType(ITypeSymbol type) + { + if (type.SpecialType == SpecialType.System_String) return null; + if (type is IArrayTypeSymbol array) return array.ElementType; + foreach (var candidate in type is INamedTypeSymbol { TypeKind: TypeKind.Interface } self ? type.AllInterfaces.Insert(0, self) : type.AllInterfaces) + { + if (candidate.OriginalDefinition.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T) return candidate.TypeArguments[0]; + } + + return null; + } + + public static bool CanBeNull(ITypeSymbol type) => type.IsReferenceType || type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T; +} diff --git a/src/Validation.Analyzers/NestedValidationAnalyzer.cs b/src/Validation.Analyzers/NestedValidationAnalyzer.cs new file mode 100644 index 00000000000..dc60bdca913 --- /dev/null +++ b/src/Validation.Analyzers/NestedValidationAnalyzer.cs @@ -0,0 +1,55 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using Rocket.Surgery.LaunchPad.Validation.Analyzers.Model; + +namespace Rocket.Surgery.LaunchPad.Validation.Analyzers; + +/// +/// LPAD3001: in a type that has rules, a member whose own type has rules (or a collection of one) and that says neither +/// [ValidateNested] nor [SkipValidation]. Nested validation is asked for, never assumed, so the member's rules would silently +/// not be applied. +/// +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public sealed class NestedValidationAnalyzer : DiagnosticAnalyzer +{ + /// + public override ImmutableArray SupportedDiagnostics { get; } = [Diagnostics.NestedValidationNotDecided]; + + /// + public override void Initialize(AnalysisContext context) + { + context.EnableConcurrentExecution(); + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + context.RegisterSymbolAction(Analyze, SymbolKind.NamedType); + } + + private static void Analyze(SymbolAnalysisContext context) + { + var type = (INamedTypeSymbol)context.Symbol; + if (type.TypeKind is not ( TypeKind.Class or TypeKind.Struct ) || !ValidationSymbols.HasRules(type)) return; + + foreach (var member in ValidationSymbols.Members(type)) + { + // Only what the type declares: what it inherits is reported on the type that declares it. + if (!SymbolEqualityComparer.Default.Equals(member.ContainingType, type)) continue; + if (ValidationSymbols.AttributesOf(member).Any(static z => ValidationSymbols.DecidesNestedValidation(z.AttributeClass))) continue; + + var memberType = ValidationSymbols.TypeOf(member); + var target = ValidationSymbols.Underlying(ValidationSymbols.ItemType(memberType) ?? memberType); + if (!ValidationSymbols.HasRules(target)) continue; + + var location = member is IPropertySymbol property && ValidationSymbols.PrimaryParameter(property) is { } parameter + ? parameter.Locations.FirstOrDefault() + : member.Locations.FirstOrDefault(); + context.ReportDiagnostic( + Diagnostic.Create( + Diagnostics.NestedValidationNotDecided, + location, + member.Name, + ( ValidationSymbols.ItemType(memberType) is null ? "" : "collection of " ) + target.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat) + ) + ); + } + } +} diff --git a/src/Validation.Analyzers/NestedValidationCodeFix.cs b/src/Validation.Analyzers/NestedValidationCodeFix.cs new file mode 100644 index 00000000000..8fd3d533375 --- /dev/null +++ b/src/Validation.Analyzers/NestedValidationCodeFix.cs @@ -0,0 +1,82 @@ +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; +using Rocket.Surgery.LaunchPad.Validation.Analyzers.Model; + +namespace Rocket.Surgery.LaunchPad.Validation.Analyzers; + +/// +/// Fixes LPAD3001 either way: [ValidateNested] to validate the member with its type's validator, or [SkipValidation] to say +/// that leaving it out is deliberate. +/// +[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(NestedValidationCodeFix))] +[Shared] +public sealed class NestedValidationCodeFix : CodeFixProvider +{ + /// + public override ImmutableArray FixableDiagnosticIds { get; } = [Diagnostics.NestedValidationNotDecided.Id]; + + /// + public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; + + /// + 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) + { + var node = root.FindToken(diagnostic.Location.SourceSpan.Start).Parent; + SyntaxNode? target = node?.FirstAncestorOrSelf(); + target ??= node?.FirstAncestorOrSelf(static z => z is PropertyDeclarationSyntax or FieldDeclarationSyntax); + if (target is null) continue; + foreach (var attribute in new[] { "ValidateNested", "SkipValidation", }) + { + var title = "Add [" + attribute + "]"; + context.RegisterCodeFix(CodeAction.Create(title, ct => AddAsync(context.Document, target, attribute, ct), title), diagnostic); + } + } + } + + private static async Task AddAsync(Document document, SyntaxNode target, string attribute, CancellationToken cancellationToken) + { + var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + if (root is null) return document; + + // The full name, which the simplifier shortens where the namespace is imported. + var name = SyntaxFactory.ParseName("global::" + ValidationSymbols.RulesNamespace + "." + attribute).WithAdditionalAnnotations(Simplifier.Annotation); + var list = SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory.Attribute(name))); + SyntaxNode updated; + switch (target) + { + case ParameterSyntax parameter: + updated = parameter + .WithoutLeadingTrivia() + .WithAttributeLists(parameter.AttributeLists.Add(list.WithTrailingTrivia(SyntaxFactory.Space))) + .WithLeadingTrivia(parameter.GetLeadingTrivia()); + break; + case MemberDeclarationSyntax member: + var leading = member.GetLeadingTrivia(); + var indentation = leading.Count > 0 && leading[^1].IsKind(SyntaxKind.WhitespaceTrivia) + ? SyntaxFactory.TriviaList(leading[^1]) + : SyntaxFactory.TriviaList(); + var endOfLine = root.DescendantTrivia().FirstOrDefault(static z => z.IsKind(SyntaxKind.EndOfLineTrivia)) is { RawKind: not 0 } found + ? found + : SyntaxFactory.LineFeed; + // The attribute goes last, on a line of its own: the member's comments and other attributes stay above it. + updated = member.AttributeLists.Count > 0 + ? member.WithAttributeLists(member.AttributeLists.Add(list.WithLeadingTrivia(indentation).WithTrailingTrivia(endOfLine))) + : member.WithLeadingTrivia(indentation).WithAttributeLists(SyntaxFactory.SingletonList(list.WithLeadingTrivia(leading).WithTrailingTrivia(endOfLine))); + break; + default: + return document; + } + + return document.WithSyntaxRoot(root.ReplaceNode(target, updated)); + } +} diff --git a/src/Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.csproj b/src/Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.csproj new file mode 100644 index 00000000000..c1e41959d30 --- /dev/null +++ b/src/Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.csproj @@ -0,0 +1,48 @@ + + + + netstandard2.0 + true + true + true + Rocket.Surgery.LaunchPad.Validation.Analyzers + The generator, analyzers and code fixes of Rocket.Surgery.LaunchPad.Validation. + $(PackageTags);source-generator;roslyn;analyzers;validation + + $(NoWarn);RS1038 + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Validation.Analyzers/ValidatorGenerator.cs b/src/Validation.Analyzers/ValidatorGenerator.cs new file mode 100644 index 00000000000..481ea3192ab --- /dev/null +++ b/src/Validation.Analyzers/ValidatorGenerator.cs @@ -0,0 +1,385 @@ +using System.Collections.Immutable; +using System.Text; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Rocket.Surgery.LaunchPad.Validation.Analyzers.Model; + +namespace Rocket.Surgery.LaunchPad.Validation.Analyzers; + +/// +/// Writes a validator for every type whose members carry rule attributes (LaunchPad's, and the +/// System.ComponentModel.DataAnnotations ones it compiles), and the method that registers the assembly's validators. +/// +/// +/// A type needs no marker: the generator looks at every class, struct and record that has an attribute on a member. The validator is a +/// class of its own beside the type, named after it, with one static rule method per member. +/// +[Generator] +public sealed class ValidatorGenerator : IIncrementalGenerator +{ + /// + public void Initialize(IncrementalGeneratorInitializationContext context) + { + var types = context + .SyntaxProvider.CreateSyntaxProvider(static (node, _) => IsCandidate(node), static (syntax, _) => Read(syntax)) + .Where(static z => z is not null) + .Select(static (z, _) => z!); + + var environment = context.CompilationProvider.Select(static (compilation, _) => CompilationModel.Read(compilation)); + + context.RegisterSourceOutput( + types.Combine(environment), + static (output, pair) => + { + var (result, compilation) = pair; + foreach (var diagnostic in result.Diagnostics) + { + if (diagnostic.ToDiagnostic() is { } reported) output.ReportDiagnostic(reported); + } + + if (result.Model is { } model) output.AddSource(model.HintName, ValidatorEmitter.Validator(model, compilation)); + } + ); + + context.RegisterSourceOutput( + types.Where(static z => z.Model is not null).Select(static (z, _) => z.Model!).Collect().Combine(environment), + static (output, pair) => + { + var (models, compilation) = pair; + if (!compilation.HasServiceCollection || ( models.IsEmpty && compilation.Registrations.Length == 0 )) return; + output.AddSource("LaunchPadValidators.g.cs", ValidatorEmitter.Registration(models, compilation)); + } + ); + } + + private static bool IsCandidate(SyntaxNode node) => + node is TypeDeclarationSyntax type and ( ClassDeclarationSyntax or StructDeclarationSyntax or RecordDeclarationSyntax ) && HasMemberAttributes(type); + + private static bool HasMemberAttributes(TypeDeclarationSyntax type) + { + if (type.ParameterList is { } parameters && parameters.Parameters.Any(static z => z.AttributeLists.Count > 0)) return true; + foreach (var member in type.Members) + { + if (member is PropertyDeclarationSyntax or FieldDeclarationSyntax && member.AttributeLists.Count > 0) return true; + } + + return false; + } + + private static ValidatedTypeResult? Read(GeneratorSyntaxContext context) + { + var declaration = (TypeDeclarationSyntax)context.Node; + if (context.SemanticModel.GetDeclaredSymbol(declaration) is not INamedTypeSymbol type) return null; + + // A partial type is read once, from the first of its declarations that could have rules. + var first = type.DeclaringSyntaxReferences.Select(static z => z.GetSyntax()).OfType().FirstOrDefault(HasMemberAttributes); + if (first != declaration) return null; + + var result = RuleReader.Read(type, context.SemanticModel, declaration.Identifier.SpanStart); + return result.Model is null && result.Diagnostics.Length == 0 ? null : result; + } +} + +/// What the generated code depends on in the compilation: the libraries it can use, and the validators its references registered. +internal sealed record CompilationModel(string AssemblyName, bool HasServiceCollection, bool HasOptions, EquatableArray Registrations) +{ + public static CompilationModel Read(Compilation compilation) + { + var registrations = ImmutableArray.CreateBuilder(); + foreach (var assembly in compilation.SourceModule.ReferencedAssemblySymbols) + { + foreach (var attribute in assembly.GetAttributes()) + { + if (ValidationSymbols.Is(attribute.AttributeClass, ValidationSymbols.RuntimeNamespace, "ValidatorAssemblyAttribute") + && attribute.ConstructorArguments is [{ Value: INamedTypeSymbol type }, { Value: string method }] + && compilation.IsSymbolAccessibleWithin(type, compilation.Assembly)) + { + registrations.Add(type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) + "." + method); + } + } + } + + registrations.Sort(StringComparer.Ordinal); + return new( + compilation.AssemblyName ?? "Assembly", + compilation.GetTypeByMetadataName("Microsoft.Extensions.DependencyInjection.IServiceCollection") is not null + && compilation.GetTypeByMetadataName("Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions") is not null, + compilation.GetTypeByMetadataName("Microsoft.Extensions.Options.IValidateOptions`1") is not null, + registrations.ToImmutable() + ); + } +} + +/// Writes the validators and their registration. +internal static class ValidatorEmitter +{ + private const string Runtime = "global::" + ValidationSymbols.RuntimeNamespace; + private const string Sink = Runtime + ".ValidationSink"; + private const string Never = "[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]"; + + public static string Validator(ValidatedTypeModel model, CompilationModel compilation) + { + var options = compilation.HasOptions && model.IsReferenceType; + var nested = model.Members.Where(static z => z.Nested is not null).ToList(); + var sb = new StringBuilder(); + sb.AppendLine("// "); + sb.AppendLine("#nullable enable"); + sb.AppendLine(); + var indent = ""; + if (model.Namespace.Length > 0) + { + sb.Append("namespace ").AppendLine(model.Namespace); + sb.AppendLine("{"); + indent = " "; + } + + void Line(string text = "") => _ = text.Length == 0 ? sb.AppendLine() : sb.Append(indent).AppendLine(text); + + Line("/// "); + Line($"/// Validates a : the rules its members carry as attributes."); + Line("/// "); + Line($"[{Runtime}.GeneratedValidator(typeof({model.Type}))]"); + Line($"{( model.IsPublic ? "public" : "internal" )} sealed partial class {model.ValidatorName}"); + Line($" : {Runtime}.IValidate<{model.Type}>{( options ? $", global::Microsoft.Extensions.Options.IValidateOptions<{model.Type}>" : "" )}"); + Line("{"); + Line($" private readonly {Runtime}.IValidationMessageProvider? _messages;"); + if (nested.Count > 0) Line(" private readonly global::System.IServiceProvider? _services;"); + // One validator for each type validated, whichever members are of it: named after the first. + var validators = new Dictionary(StringComparer.Ordinal); + foreach (var member in nested) + { + if (validators.ContainsKey(member.Nested!.Service)) continue; + validators.Add(member.Nested.Service, member.Name + "Validator"); + Line($" private {member.Nested.Service}? _{Camel(member.Name)}Validator;"); + } + + foreach (var regex in model.Members.SelectMany(static z => z.Regexes)) + { + Line(); + Line($" private static readonly global::System.Text.RegularExpressions.Regex {regex.Field} ="); + Line($" new({regex.Pattern}, {regex.Options} | global::System.Text.RegularExpressions.RegexOptions.CultureInvariant, global::System.TimeSpan.FromSeconds(2));"); + } + + Line(); + Line(" /// "); + Line(" /// Creates the validator."); + Line(" /// "); + 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."); + Line($" public {model.ValidatorName}({Runtime}.IValidationMessageProvider? messages = null, global::System.IServiceProvider? services = null)"); + Line(" {"); + Line(" _messages = messages;"); + Line(" _services = services;"); + Line(" }"); + } + else + { + Line($" public {model.ValidatorName}({Runtime}.IValidationMessageProvider? messages = null) => _messages = messages;"); + } + + Line(); + Line(" /// "); + Line($" public {Runtime}.ValidationResult Validate({model.Type} value)"); + Line(" {"); + if (model.IsReferenceType) Line(" global::System.ArgumentNullException.ThrowIfNull(value);"); + Line($" var sink = new {Sink}(_messages);"); + foreach (var member in model.Members) + { + if (member.Rules.Length > 0) + { + var arguments = ( member.ReadsValue ? "value, " : "" ) + "value." + member.Name + string.Concat(member.Reads.Select(static z => ", value." + z.Name)); + Line($" Ensure{member.Name}({arguments}, ref sink);"); + } + + if (member.Nested is { } how) WriteNested(member, how, validators[how.Service], Line); + } + + Line(" return sink.ToResult();"); + Line(" }"); + + if (options) + { + Line(); + Line(" /// "); + Line($" global::Microsoft.Extensions.Options.ValidateOptionsResult global::Microsoft.Extensions.Options.IValidateOptions<{model.Type}>.Validate(string? name, {model.Type} options)"); + Line(" {"); + Line(" var result = Validate(options);"); + Line(" if (result.IsValid) return global::Microsoft.Extensions.Options.ValidateOptionsResult.Success;"); + Line(" var failures = new global::System.Collections.Generic.List();"); + Line(" foreach (var failure in result.Errors)"); + Line(" {"); + Line(" failures.Add(failure.Path.Length == 0 ? failure.Message : failure.Path + \": \" + failure.Message);"); + Line(" }"); + Line(); + Line(" return global::Microsoft.Extensions.Options.ValidateOptionsResult.Fail(failures);"); + Line(" }"); + } + + foreach (var validator in validators) + { + var field = "_" + Camel(validator.Value); + Line(); + Line($" private {validator.Key} {validator.Value} =>"); + Line($" {field} ??= _services?.GetService(typeof({validator.Key})) as {validator.Key}"); + Line($" ?? throw new global::System.InvalidOperationException(\"{model.ValidatorName} needs a {Escape(validator.Key.Replace("global::", ""))}, which the service provider it was given does not have.\");"); + } + + foreach (var member in model.Members.Where(static z => z.Rules.Length > 0)) + { + WriteRuleMethod(model, member, Line); + } + + Line("}"); + if (model.Namespace.Length > 0) sb.AppendLine("}"); + return sb.ToString(); + } + + private static void WriteNested(MemberModel member, NestedModel nested, string validator, Action line) + { + var local = Camel(member.Name); + var name = Literal(member.Name); + line(""); + if (nested.CanBeNull) line($" if (value.{member.Name} is {{ }} {local})"); + line(" {"); + if (!nested.CanBeNull) line($" var {local} = value.{member.Name};"); + line($" var path = sink.Enter({name});"); + if (nested.IsCollection) + { + line(" var index = 0;"); + line($" foreach (var item in {local})"); + line(" {"); + if (nested.ItemCanBeNull) + { + line(" if (item is { } present)"); + line(" {"); + line(" var itemPath = sink.Enter(index);"); + line($" sink.Add({validator}.Validate(present));"); + line(" sink.Leave(itemPath);"); + line(" }"); + } + else + { + line(" var itemPath = sink.Enter(index);"); + line($" sink.Add({validator}.Validate(item));"); + line(" sink.Leave(itemPath);"); + } + + line(""); + line(" index++;"); + line(" }"); + line(""); + } + else + { + line($" sink.Add({validator}.Validate({local}));"); + } + + line(" sink.Leave(path);"); + line(" }"); + line(""); + } + + private static void WriteRuleMethod(ValidatedTypeModel model, MemberModel member, Action line) + { + var name = Literal(member.Name); + var manifest = string.Concat(member.Rules.Select(static z => ", " + Literal(z.Manifest))); + var reads = member.Reads.Length == 0 ? "" : ", Reads = new[] { " + string.Join(", ", member.Reads.Select(static z => Literal(z.Name))) + " }"; + var parameters = ( member.ReadsValue ? model.Type + " instance, " : "" ) + + member.Type + " value" + + string.Concat(member.Reads.Select(static z => ", " + z.Type + " " + z.Parameter)); + + line(""); + line(" /// "); + line($" /// The rules of ."); + line(" /// "); + line($" [{Runtime}.GeneratedRule({name}{manifest}{reads}{( member.ReadsValue ? ", ReadsValue = true" : "" )})]"); + line(" " + Never); + line($" public static void Ensure{member.Name}({parameters}, ref {Sink} sink)"); + line(" {"); + var first = true; + foreach (var rule in member.Rules) + { + if (!first) line(""); + first = false; + var arguments = string.Concat(rule.Arguments.Select(static z => $", {Sink}.Argument({Literal(z.Name)}, {z.Expression})")); + line($" if (!{rule.Check})"); + line(" {"); + line($" sink.Add({name}, {Literal(rule.Code)}, {Literal(rule.Message)}, {Runtime}.ValidationSeverity.{rule.Severity}, {Sink}.Argument(\"Name\", {name}), {Sink}.Argument(\"Value\", value){arguments});"); + line(" }"); + } + + line(" }"); + } + + public static string Registration(ImmutableArray models, CompilationModel compilation) + { + const string extensions = "global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions"; + const string services = "global::Microsoft.Extensions.DependencyInjection.IServiceCollection"; + var name = Identifier(compilation.AssemblyName); + var @class = name + "ValidatorsServiceCollectionExtensions"; + var method = "Add" + name + "Validators"; + var sb = new StringBuilder(); + sb.AppendLine("// "); + sb.AppendLine("#nullable enable"); + sb.AppendLine(); + sb.AppendLine($"[assembly: {Runtime}.ValidatorAssembly(typeof(global::Microsoft.Extensions.DependencyInjection.{@class}), \"{method}\")]"); + sb.AppendLine(); + sb.AppendLine("namespace Microsoft.Extensions.DependencyInjection"); + sb.AppendLine("{"); + sb.AppendLine(" /// "); + sb.AppendLine($" /// Registers the validators of {compilation.AssemblyName}."); + sb.AppendLine(" /// "); + sb.AppendLine($" public static class {@class}"); + sb.AppendLine(" {"); + sb.AppendLine(" /// "); + sb.AppendLine($" /// Adds the validators of {compilation.AssemblyName}, and those of the assemblies it references, each as the"); + sb.AppendLine(" /// IValidate and IValidateAsync of the type it validates."); + sb.AppendLine(" /// "); + sb.AppendLine(" /// The services."); + sb.AppendLine(" /// The services."); + sb.AppendLine($" public static {services} {method}(this {services} services)"); + sb.AppendLine(" {"); + foreach (var registration in compilation.Registrations) + { + sb.AppendLine($" {registration}(services);"); + } + + foreach (var model in models.OrderBy(static z => z.ValidatorFullName, StringComparer.Ordinal)) + { + var validator = model.ValidatorFullName; + sb.AppendLine($" {extensions}.TryAddSingleton<{Runtime}.IValidate<{model.Type}>, {validator}>(services);"); + sb.AppendLine($" {extensions}.TryAddSingleton<{Runtime}.IValidateAsync<{model.Type}>>(services, static provider => ({Runtime}.IValidate<{model.Type}>)provider.GetService(typeof({Runtime}.IValidate<{model.Type}>))!);"); + if (compilation.HasOptions && model.IsReferenceType) + { + sb.AppendLine($" {extensions}.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton, {validator}>());"); + } + } + + sb.AppendLine(" return services;"); + sb.AppendLine(" }"); + sb.AppendLine(" }"); + sb.AppendLine("}"); + return sb.ToString(); + } + + private static string Literal(string value) => SymbolDisplay.FormatLiteral(value, true); + + private static string Escape(string value) => value.Replace("\\", "\\\\").Replace("\"", "\\\""); + + private static string Camel(string name) => char.ToLowerInvariant(name[0]) + name[1..]; + + private static string Identifier(string assemblyName) + { + var builder = new StringBuilder(assemblyName.Length); + foreach (var character in assemblyName) + { + if (char.IsLetterOrDigit(character) || character == '_') builder.Append(character); + } + + if (builder.Length == 0 || char.IsDigit(builder[0])) builder.Insert(0, '_'); + return builder.ToString(); + } +} diff --git a/src/Validation/GeneratedValidatorAttribute.cs b/src/Validation/GeneratedValidatorAttribute.cs new file mode 100644 index 00000000000..0bdaec95fb9 --- /dev/null +++ b/src/Validation/GeneratedValidatorAttribute.cs @@ -0,0 +1,72 @@ +using System.ComponentModel; + +namespace Rocket.Surgery.LaunchPad.Validation; + +/// +/// On a validator the generator wrote: the type it validates. With the of its rule methods it is the +/// rule manifest, which the generator reads from referenced assemblies in place of their source. +/// +/// The type validated. +[PublicAPI] +[EditorBrowsable(EditorBrowsableState.Never)] +[AttributeUsage(AttributeTargets.Class, Inherited = false)] +public sealed class GeneratedValidatorAttribute(Type type) : Attribute +{ + /// + /// The type validated. + /// + public Type Type { get; } = type; +} + +/// +/// On a rule method the generator wrote: the member whose rules it checks, and the rules. The method takes the member's value, then the +/// values of the members named by , then the . +/// +/// The member's name. +/// The rules, each as its name and its constant arguments: MaxLength(30). +[PublicAPI] +[EditorBrowsable(EditorBrowsableState.Never)] +[AttributeUsage(AttributeTargets.Method, Inherited = false)] +public sealed class GeneratedRuleAttribute(string member, params string[] rules) : Attribute +{ + /// + /// The member's name. + /// + public string Member { get; } = member; + + /// + /// The rules. + /// + public IReadOnlyList Rules { get; } = rules; + + /// + /// The other members of the value the rules read, in the order the method takes them. + /// + public string[] Reads { get; init; } = []; + + /// + /// Whether the method takes the whole value first: a rule that calls a method of the value needs it. + /// + public bool ReadsValue { get; init; } +} + +/// +/// On an assembly the generator wrote validators into: the class that registers them, which the assemblies that reference this one call. +/// +/// The class with the method that registers the assembly's validators. +/// The method's name. +[PublicAPI] +[EditorBrowsable(EditorBrowsableState.Never)] +[AttributeUsage(AttributeTargets.Assembly)] +public sealed class ValidatorAssemblyAttribute(Type registration, string method) : Attribute +{ + /// + /// The class with the method that registers the assembly's validators. + /// + public Type Registration { get; } = registration; + + /// + /// The method's name. + /// + public string Method { get; } = method; +} diff --git a/src/Validation/IValidate.cs b/src/Validation/IValidate.cs new file mode 100644 index 00000000000..48222313b26 --- /dev/null +++ b/src/Validation/IValidate.cs @@ -0,0 +1,39 @@ +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 new file mode 100644 index 00000000000..48a8385cb6c --- /dev/null +++ b/src/Validation/IValidationBuilder.cs @@ -0,0 +1,154 @@ +namespace Rocket.Surgery.LaunchPad.Validation; + +/// +/// 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. +[PublicAPI] +public interface IValidationBuilder +{ + /// + /// Starts the rules of one member, or of the whole value with x => x. + /// + /// The member: x => x.Name. + /// The member's type. + /// The rules of the member. + IMemberRules Ensure(Func member); + + /// + /// Starts the rules of each item of a collection. + /// + /// The collection: x => x.Tags. + /// The items' type. + /// The rules of each item. + IMemberRules EnsureEach(Func?> items); + + /// + /// Declares the rules of each item of a collection, member by member. + /// + /// The collection: x => x.Stages. + /// The rules of an item. + /// The items' type. + void EnsureEach(Func?> items, Action> rules); + + /// + /// Declares rules that apply only when a condition holds. + /// + /// The condition. + /// The rules. + void When(Func condition, Action> rules); + + /// + /// Declares rules that apply only when a condition does not hold. + /// + /// The condition. + /// The rules. + void Unless(Func condition, Action> rules); + + /// + /// Applies the rules of another type to the members shares with it by name and type. + /// + /// The type whose rules to apply. + void Include(); +} + +/// +/// The rules of one member of , in the order they are declared. The built-in rules are extension methods +/// (), and an application adds its own with . +/// +/// The type the rules are for. +/// The member's type. +[PublicAPI] +public interface IMemberRules +{ + /// + /// A rule of the application's own, over the member's value. + /// + /// What must hold: a lambda or a method. + /// The rules of the member. + IMemberRules Must(Func predicate); + + /// + /// A rule of the application's own, over the whole value and the member's value. + /// + /// What must hold: a lambda or a method. + /// The rules of the member. + IMemberRules Must(Func predicate); + + /// + /// An asynchronous rule of the application's own, over the member's value. A type with one is validated asynchronously only. + /// + /// What must hold: a lambda or a method. + /// The rules of the member. + IMemberRules MustAsync(Func> predicate); + + /// + /// An asynchronous rule of the application's own, over the whole value and the member's value. + /// + /// What must hold: a lambda or a method. + /// The rules of the member. + IMemberRules MustAsync(Func> predicate); + + /// + /// The rules declared so far for the member apply only when a condition holds. + /// + /// The condition. + /// The rules of the member. + IMemberRules When(Func condition); + + /// + /// The rules declared so far for the member apply only when a condition does not hold. + /// + /// The condition. + /// The rules of the member. + IMemberRules Unless(Func condition); + + /// + /// The message of the rule before, with {Name}, {Value} and the rule's own placeholders. + /// + /// The message template, a constant. + /// The rules of the member. + IMemberRules WithMessage(string template); + + /// + /// The code of the rule before. + /// + /// The code, a constant. + /// The rules of the member. + IMemberRules WithCode(string code); + + /// + /// The severity of the rule before. + /// + /// The severity, a constant. + /// The rules of the member. + IMemberRules WithSeverity(ValidationSeverity severity); + + /// + /// What the messages of the member's rules call it, in place of its name. + /// + /// The name, a constant. + /// The rules of the member. + IMemberRules WithName(string name); + + /// + /// The member's rules stop at the first one that fails. + /// + /// The rules of the member. + IMemberRules StopOnFailure(); + + /// + /// Validates the member with the validator of its own type, and puts its failures under the member. + /// + /// The rules of the member. + IMemberRules ValidateNested(); + + /// + /// Validates the member with a validator named here. + /// + /// The validator. + /// The rules of the member. + IMemberRules ValidateWith() + where TValidator : IValidateAsync; +} diff --git a/src/Validation/IValidationMessageProvider.cs b/src/Validation/IValidationMessageProvider.cs new file mode 100644 index 00000000000..6a344bbfb94 --- /dev/null +++ b/src/Validation/IValidationMessageProvider.cs @@ -0,0 +1,16 @@ +namespace Rocket.Surgery.LaunchPad.Validation; + +/// +/// Replaces the messages of rules, by code: an application registers one to reword or translate them without changing a rule. +/// +[PublicAPI] +public interface IValidationMessageProvider +{ + /// + /// The message template to use for a rule, or to keep the rule's own. + /// + /// The rule's code. + /// The rule's own template, with its placeholders ({Name}, {Value}, {Max}, ...). + /// A template with the same placeholders, or . + string? GetTemplate(string code, string defaultTemplate); +} diff --git a/src/Validation/IValidator.cs b/src/Validation/IValidator.cs new file mode 100644 index 00000000000..ebe20bb044c --- /dev/null +++ b/src/Validation/IValidator.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 IValidator +{ + /// + /// Declares the rules. The body may only call the builder. + /// + /// The builder. + void Validate(IValidationBuilder v); +} diff --git a/src/Validation/Rocket.Surgery.LaunchPad.Validation.csproj b/src/Validation/Rocket.Surgery.LaunchPad.Validation.csproj new file mode 100644 index 00000000000..f73e5750879 --- /dev/null +++ b/src/Validation/Rocket.Surgery.LaunchPad.Validation.csproj @@ -0,0 +1,30 @@ + + + + $(LaunchPadTargetFrameworks) + Validation written ahead of time: rules declared with attributes, System.ComponentModel.DataAnnotations and fluent Validate functions are merged into one generated validator per type, with no reflection and no expression trees. + $(PackageTags);validation;validator;source-generator;aot;data-annotations + true + + + + + + + + + + + + + diff --git a/src/Validation/Rules/MemberRulesExtensions.cs b/src/Validation/Rules/MemberRulesExtensions.cs new file mode 100644 index 00000000000..94c32155e26 --- /dev/null +++ b/src/Validation/Rules/MemberRulesExtensions.cs @@ -0,0 +1,339 @@ +using System.Collections; +using System.Text.RegularExpressions; + +namespace Rocket.Surgery.LaunchPad.Validation.Rules; + +/// +/// The built-in rules of a member, as a Validate function declares them. They are never run: the generator reads each call and +/// writes a call to the method its names. +/// +[PublicAPI] +[SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "The generator reads the arguments.")] +public static class MemberRulesExtensions +{ + /// The member must not be . + /// The rules of the member. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.NotNull))] + public static IMemberRules NotNull(this IMemberRules rules) => rules; + + /// The member must be . + /// The rules of the member. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.Null))] + public static IMemberRules Null(this IMemberRules rules) => rules; + + /// The member must not be , the default of its type, white space or a collection with no items. + /// The rules of the member. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.NotEmpty))] + public static IMemberRules NotEmpty(this IMemberRules rules) => rules; + + /// The member must be , the default of its type, white space or a collection with no items. + /// The rules of the member. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.Empty))] + public static IMemberRules Empty(this IMemberRules rules) => rules; + + /// The member must not be the default of its type. + /// The rules of the member. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.NotDefault))] + public static IMemberRules NotDefault(this IMemberRules rules) => rules; + + /// The member must have the shape of an email address. + /// The rules of the member. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.EmailAddress))] + public static IMemberRules EmailAddress(this IMemberRules rules) => rules; + + /// The member must be an absolute http or https URL. + /// The rules of the member. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.Url))] + public static IMemberRules Url(this IMemberRules rules) => rules; + + /// The string must have at least this many characters. + /// The rules of the member. + /// The length. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.MinLength))] + public static IMemberRules MinLength(this IMemberRules rules, int min) => rules; + + /// The collection must have at least this many items. + /// The rules of the member. + /// The length. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.MinLength))] + public static IMemberRules MinLength(this IMemberRules rules, int min) + where TMember : IEnumerable? => rules; + + /// The string must have at most this many characters. + /// The rules of the member. + /// The length. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.MaxLength))] + public static IMemberRules MaxLength(this IMemberRules rules, int max) => rules; + + /// The collection must have at most this many items. + /// The rules of the member. + /// The length. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.MaxLength))] + public static IMemberRules MaxLength(this IMemberRules rules, int max) + where TMember : IEnumerable? => rules; + + /// The string must have a number of characters between two bounds. + /// The rules of the member. + /// The least it may have. + /// The most it may have. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.Length))] + public static IMemberRules Length(this IMemberRules rules, int min, int max) => rules; + + /// The collection must have a number of items between two bounds. + /// The rules of the member. + /// The least it may have. + /// The most it may have. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.Length))] + public static IMemberRules Length(this IMemberRules rules, int min, int max) + where TMember : IEnumerable? => rules; + + /// The string must match a regular expression. + /// The rules of the member. + /// The pattern, a constant. + /// The pattern's options, a constant. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.Matches))] + public static IMemberRules Matches(this IMemberRules rules, [StringSyntax(StringSyntaxAttribute.Regex)] string pattern, RegexOptions options = RegexOptions.None) => rules; + + /// The string must match a regular expression. + /// The rules of the member. + /// The regular expression: a property or method the regular expression generator writes. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.Matches))] + public static IMemberRules Matches(this IMemberRules rules, Regex pattern) => rules; + + /// The member must equal a value. + /// The rules of the member. + /// The value to compare with. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.Equal))] + public static IMemberRules Equal(this IMemberRules rules, TMember other) => rules; + + /// The member must equal another value of the value being validated. + /// The rules of the member. + /// The value to compare with, from the value being validated. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.Equal))] + public static IMemberRules Equal(this IMemberRules rules, Func other) => rules; + + /// The member must not equal a value. + /// The rules of the member. + /// The value to compare with. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.NotEqual))] + public static IMemberRules NotEqual(this IMemberRules rules, TMember other) => rules; + + /// The member must not equal another value of the value being validated. + /// The rules of the member. + /// The value to compare with, from the value being validated. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.NotEqual))] + public static IMemberRules NotEqual(this IMemberRules rules, Func other) => rules; + + /// The member must be greater than a value. + /// The rules of the member. + /// The value to compare with. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.GreaterThan))] + public static IMemberRules GreaterThan(this IMemberRules rules, TMember other) + where TMember : IComparable? => rules; + + /// The member must be greater than another value of the value being validated. + /// The rules of the member. + /// The value to compare with, from the value being validated. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.GreaterThan))] + public static IMemberRules GreaterThan(this IMemberRules rules, Func other) + where TMember : IComparable? => rules; + + /// The member must be greater than a value, when it has one. + /// The rules of the member. + /// The value to compare with. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.GreaterThan))] + public static IMemberRules GreaterThan(this IMemberRules rules, TMember other) + where TMember : struct, IComparable => rules; + + /// The member must be greater than another value of the value being validated, when it has one. + /// The rules of the member. + /// The value to compare with, from the value being validated. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.GreaterThan))] + public static IMemberRules GreaterThan(this IMemberRules rules, Func other) + where TMember : struct, IComparable => rules; + + /// The member must be greater than or equal to a value. + /// The rules of the member. + /// The value to compare with. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.GreaterThanOrEqualTo))] + public static IMemberRules GreaterThanOrEqualTo(this IMemberRules rules, TMember other) + where TMember : IComparable? => rules; + + /// The member must be greater than or equal to another value of the value being validated. + /// The rules of the member. + /// The value to compare with, from the value being validated. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.GreaterThanOrEqualTo))] + public static IMemberRules GreaterThanOrEqualTo(this IMemberRules rules, Func other) + where TMember : IComparable? => rules; + + /// The member must be greater than or equal to a value, when it has one. + /// The rules of the member. + /// The value to compare with. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.GreaterThanOrEqualTo))] + public static IMemberRules GreaterThanOrEqualTo(this IMemberRules rules, TMember other) + where TMember : struct, IComparable => rules; + + /// The member must be greater than or equal to another value of the value being validated, when it has one. + /// The rules of the member. + /// The value to compare with, from the value being validated. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.GreaterThanOrEqualTo))] + public static IMemberRules GreaterThanOrEqualTo(this IMemberRules rules, Func other) + where TMember : struct, IComparable => rules; + + /// The member must be less than a value. + /// The rules of the member. + /// The value to compare with. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.LessThan))] + public static IMemberRules LessThan(this IMemberRules rules, TMember other) + where TMember : IComparable? => rules; + + /// The member must be less than another value of the value being validated. + /// The rules of the member. + /// The value to compare with, from the value being validated. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.LessThan))] + public static IMemberRules LessThan(this IMemberRules rules, Func other) + where TMember : IComparable? => rules; + + /// The member must be less than a value, when it has one. + /// The rules of the member. + /// The value to compare with. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.LessThan))] + public static IMemberRules LessThan(this IMemberRules rules, TMember other) + where TMember : struct, IComparable => rules; + + /// The member must be less than another value of the value being validated, when it has one. + /// The rules of the member. + /// The value to compare with, from the value being validated. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.LessThan))] + public static IMemberRules LessThan(this IMemberRules rules, Func other) + where TMember : struct, IComparable => rules; + + /// The member must be less than or equal to a value. + /// The rules of the member. + /// The value to compare with. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.LessThanOrEqualTo))] + public static IMemberRules LessThanOrEqualTo(this IMemberRules rules, TMember other) + where TMember : IComparable? => rules; + + /// The member must be less than or equal to another value of the value being validated. + /// The rules of the member. + /// The value to compare with, from the value being validated. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.LessThanOrEqualTo))] + public static IMemberRules LessThanOrEqualTo(this IMemberRules rules, Func other) + where TMember : IComparable? => rules; + + /// The member must be less than or equal to a value, when it has one. + /// The rules of the member. + /// The value to compare with. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.LessThanOrEqualTo))] + public static IMemberRules LessThanOrEqualTo(this IMemberRules rules, TMember other) + where TMember : struct, IComparable => rules; + + /// The member must be less than or equal to another value of the value being validated, when it has one. + /// The rules of the member. + /// The value to compare with, from the value being validated. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.LessThanOrEqualTo))] + public static IMemberRules LessThanOrEqualTo(this IMemberRules rules, Func other) + where TMember : struct, IComparable => rules; + + /// The member must be between two values, either of which it may equal. + /// The rules of the member. + /// The lower bound. + /// The upper bound. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.InclusiveBetween))] + public static IMemberRules InclusiveBetween(this IMemberRules rules, TMember min, TMember max) + where TMember : IComparable? => rules; + + /// The member must be between two values, either of which it may equal, when it has one. + /// The rules of the member. + /// The lower bound. + /// The upper bound. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.InclusiveBetween))] + public static IMemberRules InclusiveBetween(this IMemberRules rules, TMember min, TMember max) + where TMember : struct, IComparable => rules; + + /// The member must be between two values, neither of which it may equal. + /// The rules of the member. + /// The lower bound. + /// The upper bound. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.ExclusiveBetween))] + public static IMemberRules ExclusiveBetween(this IMemberRules rules, TMember min, TMember max) + where TMember : IComparable? => rules; + + /// The member must be between two values, neither of which it may equal, when it has one. + /// The rules of the member. + /// The lower bound. + /// The upper bound. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.ExclusiveBetween))] + public static IMemberRules ExclusiveBetween(this IMemberRules rules, TMember min, TMember max) + where TMember : struct, IComparable => rules; + + /// The member must be a value its enumeration names. + /// The rules of the member. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.IsInEnum))] + public static IMemberRules IsInEnum(this IMemberRules rules) + where TMember : struct, Enum => rules; + + /// The member must be a value its enumeration names, when it has one. + /// The rules of the member. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.IsInEnum))] + public static IMemberRules IsInEnum(this IMemberRules rules) + where TMember : struct, Enum => rules; + + /// The number must fit a precision and a scale. + /// The rules of the member. + /// The most digits it may have. + /// The most of them that may follow the decimal point. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.PrecisionScale))] + public static IMemberRules PrecisionScale(this IMemberRules rules, int precision, int scale) => rules; + + /// The number must fit a precision and a scale, when there is one. + /// The rules of the member. + /// The most digits it may have. + /// The most of them that may follow the decimal point. + /// The rules of the member. + [ValidationRule(typeof(Rule), nameof(Rule.PrecisionScale))] + public static IMemberRules PrecisionScale(this IMemberRules rules, int precision, int scale) => rules; +} diff --git a/src/Validation/Rules/Rule.cs b/src/Validation/Rules/Rule.cs new file mode 100644 index 00000000000..a7f9c70e0b9 --- /dev/null +++ b/src/Validation/Rules/Rule.cs @@ -0,0 +1,235 @@ +using System.Collections; +using System.Text.RegularExpressions; + +namespace Rocket.Surgery.LaunchPad.Validation.Rules; + +/// +/// The checks of the built-in rules. The generated validators call them; each returns whether the value meets the rule. +/// +/// +/// Except for , and , a rule has nothing to say about a +/// value that is : it passes, and whether the value may be null is a rule of its own. +/// +[PublicAPI] +public static class Rule +{ + /// The value is not . + [RuleDefaults("NotNull", "{Name} is required")] + public static bool NotNull(T value) => value is not null; + + /// The value is . + [RuleDefaults("Null", "{Name} must not be set")] + public static bool Null(T value) => value is null; + + /// The string is not , empty or white space. + [RuleDefaults("NotEmpty", "{Name} must not be empty")] + public static bool NotEmpty(string? value) => !string.IsNullOrWhiteSpace(value); + + /// The value is not , not the default of its type, and not a collection with no items. + [RuleDefaults("NotEmpty", "{Name} must not be empty")] + public static bool NotEmpty(T value) => value switch + { + null => false, + string text => !string.IsNullOrWhiteSpace(text), + IEnumerable e => Count(e, 1) > 0, + _ => !EqualityComparer.Default.Equals(value, default!), + }; + + /// The string is , empty or white space. + [RuleDefaults("Empty", "{Name} must be empty")] + public static bool Empty(string? value) => string.IsNullOrWhiteSpace(value); + + /// The value is , the default of its type, or a collection with no items. + [RuleDefaults("Empty", "{Name} must be empty")] + public static bool Empty(T value) => !NotEmpty(value); + + /// The value is not the default of its type: an id that was never assigned, a date that was never set. + [RuleDefaults("NotDefault", "{Name} must be set")] + public static bool NotDefault(T value) => !EqualityComparer.Default.Equals(value, default!); + + /// The string has at least characters. + [RuleDefaults("MinLength", "{Name} must be at least {Min} characters long")] + public static bool MinLength(string? value, int min) => value is null || value.Length >= min; + + /// The collection has at least items. + [RuleDefaults("MinLength", "{Name} must have at least {Min} items")] + public static bool MinLength(T value, int min) + where T : IEnumerable? => value is null || Count(value, min) >= min; + + /// The string has at most characters. + [RuleDefaults("MaxLength", "{Name} must be at most {Max} characters long")] + public static bool MaxLength(string? value, int max) => value is null || value.Length <= max; + + /// The collection has at most items. + [RuleDefaults("MaxLength", "{Name} must have at most {Max} items")] + public static bool MaxLength(T value, int max) + where T : IEnumerable? => value is null || Count(value, max + 1) <= max; + + /// The string has between and characters. + [RuleDefaults("Length", "{Name} must be between {Min} and {Max} characters long")] + public static bool Length(string? value, int min, int max) => value is null || ( value.Length >= min && value.Length <= max ); + + /// The collection has between and items. + [RuleDefaults("Length", "{Name} must have between {Min} and {Max} items")] + public static bool Length(T value, int min, int max) + where T : IEnumerable? => value is null || Count(value, max + 1) is var count && count >= min && count <= max; + + /// The value equals . + [RuleDefaults("Equal", "{Name} must be equal to {Other}")] + public static bool Equal(T value, T other) => value is null || EqualityComparer.Default.Equals(value, other); + + /// The value does not equal . + [RuleDefaults("NotEqual", "{Name} must not be equal to {Other}")] + public static bool NotEqual(T value, T other) => value is null || !EqualityComparer.Default.Equals(value, other); + + /// The value is greater than . + [RuleDefaults("GreaterThan", "{Name} must be greater than {Other}")] + public static bool GreaterThan(T value, T other) + where T : IComparable? => value is null || value.CompareTo(other) > 0; + + /// + [RuleDefaults("GreaterThan", "{Name} must be greater than {Other}")] + public static bool GreaterThan(T? value, T other) + where T : struct, IComparable => value is not { } actual || actual.CompareTo(other) > 0; + + /// The value is greater than or equal to . + [RuleDefaults("GreaterThanOrEqualTo", "{Name} must be greater than or equal to {Other}")] + public static bool GreaterThanOrEqualTo(T value, T other) + where T : IComparable? => value is null || value.CompareTo(other) >= 0; + + /// + [RuleDefaults("GreaterThanOrEqualTo", "{Name} must be greater than or equal to {Other}")] + public static bool GreaterThanOrEqualTo(T? value, T other) + where T : struct, IComparable => value is not { } actual || actual.CompareTo(other) >= 0; + + /// The value is less than . + [RuleDefaults("LessThan", "{Name} must be less than {Other}")] + public static bool LessThan(T value, T other) + where T : IComparable? => value is null || value.CompareTo(other) < 0; + + /// + [RuleDefaults("LessThan", "{Name} must be less than {Other}")] + public static bool LessThan(T? value, T other) + where T : struct, IComparable => value is not { } actual || actual.CompareTo(other) < 0; + + /// The value is less than or equal to . + [RuleDefaults("LessThanOrEqualTo", "{Name} must be less than or equal to {Other}")] + public static bool LessThanOrEqualTo(T value, T other) + where T : IComparable? => value is null || value.CompareTo(other) <= 0; + + /// + [RuleDefaults("LessThanOrEqualTo", "{Name} must be less than or equal to {Other}")] + public static bool LessThanOrEqualTo(T? value, T other) + where T : struct, IComparable => value is not { } actual || actual.CompareTo(other) <= 0; + + /// The value is between and , either of which it may equal. + [RuleDefaults("InclusiveBetween", "{Name} must be between {Min} and {Max}")] + public static bool InclusiveBetween(T value, T min, T max) + where T : IComparable? => value is null || ( value.CompareTo(min) >= 0 && value.CompareTo(max) <= 0 ); + + /// + [RuleDefaults("InclusiveBetween", "{Name} must be between {Min} and {Max}")] + public static bool InclusiveBetween(T? value, T min, T max) + where T : struct, IComparable => value is not { } actual || ( actual.CompareTo(min) >= 0 && actual.CompareTo(max) <= 0 ); + + /// The value is between and , neither of which it may equal. + [RuleDefaults("ExclusiveBetween", "{Name} must be greater than {Min} and less than {Max}")] + public static bool ExclusiveBetween(T value, T min, T max) + where T : IComparable? => value is null || ( value.CompareTo(min) > 0 && value.CompareTo(max) < 0 ); + + /// + [RuleDefaults("ExclusiveBetween", "{Name} must be greater than {Min} and less than {Max}")] + public static bool ExclusiveBetween(T? value, T min, T max) + where T : struct, IComparable => value is not { } actual || ( actual.CompareTo(min) > 0 && actual.CompareTo(max) < 0 ); + + /// The string matches a regular expression. + [RuleDefaults("Matches", "{Name} is not in the expected format")] + public static bool Matches(string? value, Regex pattern) + { + ArgumentNullException.ThrowIfNull(pattern); + return value is null || pattern.IsMatch(value); + } + + /// The string has the shape of an email address: one @, with something on both sides of it. + [RuleDefaults("EmailAddress", "{Name} is not a valid email address")] + public static bool EmailAddress(string? value) + { + if (value is null) return true; + var at = value.IndexOf('@'); + return at > 0 && at < value.Length - 1 && at == value.LastIndexOf('@') && !value.AsSpan().ContainsAny(' ', '\r', '\n'); + } + + /// The string is an absolute http or https URL. + [RuleDefaults("Url", "{Name} is not a valid URL")] + public static bool Url(string? value) => + value is null || ( Uri.TryCreate(value, UriKind.Absolute, out var uri) && ( uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps ) ); + + /// The value is one the enumeration names. + [RuleDefaults("IsInEnum", "{Name} has a value that is not allowed")] + public static bool IsInEnum(T value) + where T : struct, Enum => Enum.IsDefined(value); + + /// + [RuleDefaults("IsInEnum", "{Name} has a value that is not allowed")] + public static bool IsInEnum(T? value) + where T : struct, Enum => value is not { } actual || Enum.IsDefined(actual); + + /// + /// The number has at most digits, at most of them after the decimal point. + /// Trailing zeros count as they are written. + /// + [RuleDefaults("PrecisionScale", "{Name} must have at most {Precision} digits, {Scale} of them decimals")] + public static bool PrecisionScale(decimal value, int precision, int scale) + { + Span bits = stackalloc int[4]; + decimal.GetBits(value, bits); + var unscaled = ( new System.Numerics.BigInteger((uint)bits[2]) << 64 ) | ( (ulong)(uint)bits[1] << 32 ) | (uint)bits[0]; + var actualScale = value.Scale; + var digits = unscaled.IsZero ? 0 : unscaled.ToString(System.Globalization.CultureInfo.InvariantCulture).Length; + var integerDigits = Math.Max(digits - actualScale, 0); + return actualScale <= scale && integerDigits <= precision - scale; + } + + /// + [RuleDefaults("PrecisionScale", "{Name} must have at most {Precision} digits, {Scale} of them decimals")] + public static bool PrecisionScale(decimal? value, int precision, int scale) => value is not { } actual || PrecisionScale(actual, precision, scale); + + // The number of items, counted no further than the limit: a rule never needs to know how far past its bound a sequence goes. + private static int Count(IEnumerable value, int limit) + { + switch (value) + { + case string text: + return text.Length; + case ICollection collection: + try + { + return collection.Count; + } + catch (InvalidOperationException) + { + // A default ImmutableArray has no count. + return 0; + } + + default: + break; + } + + var count = 0; + var enumerator = value.GetEnumerator(); + try + { + while (count < limit && enumerator.MoveNext()) + { + count++; + } + } + finally + { + ( enumerator as IDisposable )?.Dispose(); + } + + return count; + } +} diff --git a/src/Validation/Rules/RuleAttributes.cs b/src/Validation/Rules/RuleAttributes.cs new file mode 100644 index 00000000000..81edb5c992a --- /dev/null +++ b/src/Validation/Rules/RuleAttributes.cs @@ -0,0 +1,370 @@ +namespace Rocket.Surgery.LaunchPad.Validation.Rules; + +/// +/// The base of the attributes that put a rule on a member. Each has the name of the rule a Validate function declares with +/// , and checks the same thing. An application's own derive from it and carry a +/// . +/// +[PublicAPI] +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = true)] +public abstract class RuleAttribute : Attribute +{ + /// + /// The message template of the rule's failures, in place of the rule's own. + /// + public string? Message { get; init; } + + /// + /// The code of the rule's failures, in place of the rule's own. + /// + public string? Code { get; init; } + + /// + /// How serious the rule's failures are. + /// + public ValidationSeverity Severity { get; init; } +} + +/// +/// The base of the rules that compare the member with a constant, or with another member of the same value. +/// +[PublicAPI] +public abstract class ComparisonRuleAttribute : RuleAttribute +{ + /// + /// Compares with another member. + /// + protected ComparisonRuleAttribute() { } + + /// + /// Compares with a constant. + /// + /// The constant. A string is parsed as the member's type where that isn't a string: a date, a decimal. + protected ComparisonRuleAttribute(object value) => Value = value; + + /// + /// The constant the member is compared with. + /// + public object? Value { get; } + + /// + /// The name of the member this one is compared with, in place of a constant. + /// + public string? Member { get; init; } +} + +/// +/// The member must not be . +/// +[PublicAPI] +[ValidationRule(typeof(Rule), nameof(Rule.NotNull))] +public sealed class NotNullAttribute : RuleAttribute; + +/// +/// The member must be . +/// +[PublicAPI] +[ValidationRule(typeof(Rule), nameof(Rule.Null))] +public sealed class NullAttribute : RuleAttribute; + +/// +/// The member must not be , the default of its type, a string of white space or a collection with no items. +/// +[PublicAPI] +[ValidationRule(typeof(Rule), nameof(Rule.NotEmpty))] +public sealed class NotEmptyAttribute : RuleAttribute; + +/// +/// The member must be , the default of its type, a string of white space or a collection with no items. +/// +[PublicAPI] +[ValidationRule(typeof(Rule), nameof(Rule.Empty))] +public sealed class EmptyAttribute : RuleAttribute; + +/// +/// The member must not be the default of its type. +/// +[PublicAPI] +[ValidationRule(typeof(Rule), nameof(Rule.NotDefault))] +public sealed class NotDefaultAttribute : RuleAttribute; + +/// +/// The member must have the shape of an email address. +/// +[PublicAPI] +[ValidationRule(typeof(Rule), nameof(Rule.EmailAddress))] +public sealed class EmailAddressAttribute : RuleAttribute; + +/// +/// The member must be an absolute http or https URL. +/// +[PublicAPI] +[ValidationRule(typeof(Rule), nameof(Rule.Url))] +public sealed class UrlAttribute : RuleAttribute; + +/// +/// The member must be a value its enumeration names. +/// +[PublicAPI] +[ValidationRule(typeof(Rule), nameof(Rule.IsInEnum))] +public sealed class IsInEnumAttribute : RuleAttribute; + +/// +/// The member must equal a constant, or another member. +/// +[PublicAPI] +[ValidationRule(typeof(Rule), nameof(Rule.Equal))] +public sealed class EqualAttribute : ComparisonRuleAttribute +{ + /// + /// Compares with the member named by . + /// + public EqualAttribute() { } + + /// + public EqualAttribute(object value) : base(value) { } +} + +/// +/// The member must not equal a constant, or another member. +/// +[PublicAPI] +[ValidationRule(typeof(Rule), nameof(Rule.NotEqual))] +public sealed class NotEqualAttribute : ComparisonRuleAttribute +{ + /// + /// Compares with the member named by . + /// + public NotEqualAttribute() { } + + /// + public NotEqualAttribute(object value) : base(value) { } +} + +/// +/// The member must be greater than a constant, or another member. +/// +[PublicAPI] +[ValidationRule(typeof(Rule), nameof(Rule.GreaterThan))] +public sealed class GreaterThanAttribute : ComparisonRuleAttribute +{ + /// + /// Compares with the member named by . + /// + public GreaterThanAttribute() { } + + /// + public GreaterThanAttribute(object value) : base(value) { } +} + +/// +/// The member must be greater than or equal to a constant, or another member. +/// +[PublicAPI] +[ValidationRule(typeof(Rule), nameof(Rule.GreaterThanOrEqualTo))] +public sealed class GreaterThanOrEqualToAttribute : ComparisonRuleAttribute +{ + /// + /// Compares with the member named by . + /// + public GreaterThanOrEqualToAttribute() { } + + /// + public GreaterThanOrEqualToAttribute(object value) : base(value) { } +} + +/// +/// The member must be less than a constant, or another member. +/// +[PublicAPI] +[ValidationRule(typeof(Rule), nameof(Rule.LessThan))] +public sealed class LessThanAttribute : ComparisonRuleAttribute +{ + /// + /// Compares with the member named by . + /// + public LessThanAttribute() { } + + /// + public LessThanAttribute(object value) : base(value) { } +} + +/// +/// The member must be less than or equal to a constant, or another member. +/// +[PublicAPI] +[ValidationRule(typeof(Rule), nameof(Rule.LessThanOrEqualTo))] +public sealed class LessThanOrEqualToAttribute : ComparisonRuleAttribute +{ + /// + /// Compares with the member named by . + /// + public LessThanOrEqualToAttribute() { } + + /// + public LessThanOrEqualToAttribute(object value) : base(value) { } +} + +/// +/// The member, a string or a collection, must have at least this many characters or items. +/// +/// The length. +[PublicAPI] +[ValidationRule(typeof(Rule), nameof(Rule.MinLength))] +public sealed class MinLengthAttribute(int min) : RuleAttribute +{ + /// + /// The length. + /// + public int Min { get; } = min; +} + +/// +/// The member, a string or a collection, must have at most this many characters or items. +/// +/// The length. +[PublicAPI] +[ValidationRule(typeof(Rule), nameof(Rule.MaxLength))] +public sealed class MaxLengthAttribute(int max) : RuleAttribute +{ + /// + /// The length. + /// + public int Max { get; } = max; +} + +/// +/// The member, a string or a collection, must have a number of characters or items between two bounds. +/// +/// The least it may have. +/// The most it may have. +[PublicAPI] +[ValidationRule(typeof(Rule), nameof(Rule.Length))] +public sealed class LengthAttribute(int min, int max) : RuleAttribute +{ + /// + /// The least it may have. + /// + public int Min { get; } = min; + + /// + /// The most it may have. + /// + public int Max { get; } = max; +} + +/// +/// The member must be between two constants, either of which it may equal. +/// +/// The lower bound. A string is parsed as the member's type where that isn't a string. +/// The upper bound. +[PublicAPI] +[ValidationRule(typeof(Rule), nameof(Rule.InclusiveBetween))] +public sealed class InclusiveBetweenAttribute(object min, object max) : RuleAttribute +{ + /// + /// The lower bound. + /// + public object Min { get; } = min; + + /// + /// The upper bound. + /// + public object Max { get; } = max; +} + +/// +/// The member must be between two constants, neither of which it may equal. +/// +/// The lower bound. A string is parsed as the member's type where that isn't a string. +/// The upper bound. +[PublicAPI] +[ValidationRule(typeof(Rule), nameof(Rule.ExclusiveBetween))] +public sealed class ExclusiveBetweenAttribute(object min, object max) : RuleAttribute +{ + /// + /// The lower bound. + /// + public object Min { get; } = min; + + /// + /// The upper bound. + /// + public object Max { get; } = max; +} + +/// +/// The member, a string, must match a regular expression. +/// +/// The pattern. The validator holds it as a , interpreted: a pattern in an attribute is out of the regular expression generator's reach. +[PublicAPI] +[ValidationRule(typeof(Rule), nameof(Rule.Matches))] +public sealed class MatchesAttribute([StringSyntax(StringSyntaxAttribute.Regex)] string pattern) + : RuleAttribute +{ + /// + /// The pattern. + /// + public string Pattern { get; } = pattern; + + /// + /// The pattern's options. + /// + public System.Text.RegularExpressions.RegexOptions Options { get; init; } +} + +/// +/// The member, a decimal, must fit a precision and a scale. +/// +/// The most digits it may have. +/// The most of them that may follow the decimal point. +[PublicAPI] +[ValidationRule(typeof(Rule), nameof(Rule.PrecisionScale))] +public sealed class PrecisionScaleAttribute(int precision, int scale) : RuleAttribute +{ + /// + /// The most digits it may have. + /// + public int Precision { get; } = precision; + + /// + /// The most of them that may follow the decimal point. + /// + public int Scale { get; } = scale; +} + +/// +/// The member must pass a method of the type that declares it: one that takes the member's value, or the whole value and the member's, and +/// returns , or a ValueTask<bool> for an asynchronous rule. +/// +/// The method's name: nameof(IsAssigned). +[PublicAPI] +public sealed class MustAttribute(string method) : RuleAttribute +{ + /// + /// The method's name. + /// + public string Method { get; } = method; +} + +/// +/// The member is validated with the validator of its own type (a collection item by item), and its failures are put under the member. +/// +[PublicAPI] +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)] +public sealed class ValidateNestedAttribute : Attribute; + +/// +/// The member is validated with a validator named here, in place of the one of its own type. +/// +/// The validator. +[PublicAPI] +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)] +public sealed class ValidateWithAttribute : Attribute; + +/// +/// The member's type has rules, and they are deliberately not applied here. +/// +[PublicAPI] +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)] +public sealed class SkipValidationAttribute : Attribute; diff --git a/src/Validation/Rules/ValidationRuleAttribute.cs b/src/Validation/Rules/ValidationRuleAttribute.cs new file mode 100644 index 00000000000..78e0b9ed034 --- /dev/null +++ b/src/Validation/Rules/ValidationRuleAttribute.cs @@ -0,0 +1,49 @@ +namespace Rocket.Surgery.LaunchPad.Validation.Rules; + +/// +/// Says which method checks a rule. It goes on the two ways a rule is declared: the extension method of +/// a Validate function calls, and the attribute a member carries. The generator writes a call +/// to the method, with the member's value first and then the arguments of the extension method or of the attribute's constructor, in order. +/// +/// +/// This is how an application adds a rule of its own: a method that returns (or a +/// ValueTask<bool>, for an asynchronous rule) with a , and an extension method, an attribute or +/// both pointing at it. +/// +/// The type that declares the method. +/// The method's name. Its overloads are chosen as C# chooses them, from the member's type and the arguments. +[PublicAPI] +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = false)] +public sealed class ValidationRuleAttribute(Type type, string method) : Attribute +{ + /// + /// The type that declares the method. + /// + public Type Type { get; } = type; + + /// + /// The method's name. + /// + public string Method { get; } = method; +} + +/// +/// The code and message of a rule, on the method that checks it. The message's placeholders are {Name}, {Value} and the +/// method's parameters after the value, with a capital: a max parameter is {Max}. +/// +/// The code of the rule's failures. +/// The message template of the rule's failures. +[PublicAPI] +[AttributeUsage(AttributeTargets.Method, Inherited = false)] +public sealed class RuleDefaultsAttribute(string code, string message) : Attribute +{ + /// + /// The code of the rule's failures. + /// + public string Code { get; } = code; + + /// + /// The message template of the rule's failures. + /// + public string Message { get; } = message; +} diff --git a/src/Validation/ValidationFailure.cs b/src/Validation/ValidationFailure.cs new file mode 100644 index 00000000000..3d40b8d9615 --- /dev/null +++ b/src/Validation/ValidationFailure.cs @@ -0,0 +1,31 @@ +using System.Collections.Immutable; + +namespace Rocket.Surgery.LaunchPad.Validation; + +/// +/// One rule a value did not meet. +/// +/// The member the rule is about, from the validated value: Stages[2].Thrust. Empty for a rule about the whole value. +/// The rule's code, which stays the same whatever the message says: MaxLength. +/// The message, with its placeholders filled in. +/// How serious the failure is. +/// The values of the message's placeholders, by name, for a caller that writes the message itself. +[PublicAPI] +public sealed record ValidationFailure( + string Path, + string Code, + string Message, + ValidationSeverity Severity, + ImmutableArray> Arguments +) +{ + /// + /// Creates a failure with no placeholder values. + /// + /// The member the rule is about. + /// The rule's code. + /// The message. + /// How serious the failure is. + public ValidationFailure(string path, string code, string message, ValidationSeverity severity = ValidationSeverity.Error) + : this(path, code, message, severity, []) { } +} diff --git a/src/Validation/ValidationMessage.cs b/src/Validation/ValidationMessage.cs new file mode 100644 index 00000000000..66db27cd52d --- /dev/null +++ b/src/Validation/ValidationMessage.cs @@ -0,0 +1,90 @@ +using System.Globalization; +using System.Text; + +namespace Rocket.Surgery.LaunchPad.Validation; + +/// +/// Fills in the placeholders of a message template: {Name}, {Value} and a rule's own, each with an optional format +/// ({Value:C}). {{ and }} are literal braces, and a placeholder with no value is left as it is written. +/// +[PublicAPI] +public static class ValidationMessage +{ + /// + /// Fills in a template. + /// + /// The template. + /// The values of the placeholders, by name. + /// The message. + public static string Format(string template, ReadOnlySpan> arguments) + { + ArgumentNullException.ThrowIfNull(template); + if (!template.Contains('{') && !template.Contains('}')) return template; + + var builder = new StringBuilder(template.Length + 16); + var span = template.AsSpan(); + var index = 0; + while (index < span.Length) + { + var current = span[index]; + if (current is '{' or '}' && index + 1 < span.Length && span[index + 1] == current) + { + builder.Append(current); + index += 2; + continue; + } + + var close = current == '{' ? span[index..].IndexOf('}') : -1; + if (close < 0) + { + builder.Append(current); + index++; + continue; + } + + var placeholder = span.Slice(index + 1, close - 1); + var colon = placeholder.IndexOf(':'); + var name = colon < 0 ? placeholder : placeholder[..colon]; + if (TryFind(arguments, name, out var value)) + { + Append(builder, value, colon < 0 ? default : placeholder[( colon + 1 )..]); + } + else + { + builder.Append(span.Slice(index, close + 1)); + } + + index += close + 1; + } + + return builder.ToString(); + } + + private static bool TryFind(ReadOnlySpan> arguments, ReadOnlySpan name, out object? value) + { + foreach (var argument in arguments) + { + if (!name.Equals(argument.Key, StringComparison.Ordinal)) continue; + value = argument.Value; + return true; + } + + value = null; + return false; + } + + private static void Append(StringBuilder builder, object? value, ReadOnlySpan format) + { + switch (value) + { + case null: + break; + case IFormattable formattable: + builder.Append(formattable.ToString(format.IsEmpty ? null : format.ToString(), CultureInfo.CurrentCulture)); + break; + default: + builder.Append(value); + break; + } + } +} diff --git a/src/Validation/ValidationResult.cs b/src/Validation/ValidationResult.cs new file mode 100644 index 00000000000..22707e3aa61 --- /dev/null +++ b/src/Validation/ValidationResult.cs @@ -0,0 +1,73 @@ +using System.Collections.Immutable; + +namespace Rocket.Surgery.LaunchPad.Validation; + +/// +/// What validating a value found: every rule it did not meet. A result with no is valid, whatever +/// warnings and information it carries. +/// +[PublicAPI] +public readonly record struct ValidationResult +{ + + /// + /// Creates a result from the failures found. + /// + /// The failures. + public ValidationResult(ImmutableArray failures) + { + Failures = failures; + var valid = true; + if (!failures.IsDefaultOrEmpty) + { + foreach (var failure in failures) + { + if (failure.Severity != ValidationSeverity.Error) continue; + valid = false; + break; + } + } + + IsInvalid = !valid; + } + + /// + /// A result with no failures. + /// + public static ValidationResult Valid => default; + + /// + /// Every failure, of any severity, in the order the rules ran. + /// + public ImmutableArray Failures => field.IsDefault ? [] : field; + + /// + /// Whether no failure is an . + /// + public bool IsValid => !IsInvalid; + + /// + /// Whether any failure is an . + /// + public bool IsInvalid { get; } + + /// + /// The failures that are errors. + /// + public IEnumerable Errors => Failures.Where(static z => z.Severity == ValidationSeverity.Error); + + /// + public bool Equals(ValidationResult other) => Failures.SequenceEqual(other.Failures); + + /// + public override int GetHashCode() + { + var hash = new HashCode(); + foreach (var failure in Failures) + { + hash.Add(failure); + } + + return hash.ToHashCode(); + } +} diff --git a/src/Validation/ValidationSeverity.cs b/src/Validation/ValidationSeverity.cs new file mode 100644 index 00000000000..d573d5bc230 --- /dev/null +++ b/src/Validation/ValidationSeverity.cs @@ -0,0 +1,23 @@ +namespace Rocket.Surgery.LaunchPad.Validation; + +/// +/// How serious a is. Only makes a value invalid. +/// +[PublicAPI] +public enum ValidationSeverity +{ + /// + /// The value is invalid. + /// + Error = 0, + + /// + /// The value is valid, and the caller should be told something about it. + /// + Warning = 1, + + /// + /// The value is valid, and there is something to say about it. + /// + Info = 2, +} diff --git a/src/Validation/ValidationSink.cs b/src/Validation/ValidationSink.cs new file mode 100644 index 00000000000..fcf5bcd28dd --- /dev/null +++ b/src/Validation/ValidationSink.cs @@ -0,0 +1,132 @@ +using System.Collections.Immutable; +using System.ComponentModel; +using System.Globalization; + +namespace Rocket.Surgery.LaunchPad.Validation; + +/// +/// Collects the failures of one validation. The generated validators and their rule methods write to it; an application has no use for it +/// unless it writes a validator by hand. +/// +/// +/// A mutable struct: pass it by . +/// +/// +/// Creates a sink. +/// +/// What replaces the rules' messages, if anything does. +[PublicAPI] +[EditorBrowsable(EditorBrowsableState.Advanced)] +public struct ValidationSink(IValidationMessageProvider? messages = null) +{ + private readonly IValidationMessageProvider? _messages = messages; + private ImmutableArray.Builder? _failures; + + /// + /// The path of the value being validated, which every failure's path starts with. Empty at the root. + /// + public string Path { readonly get => field ?? string.Empty; private set; } + + /// + /// Whether an error has been added. + /// + public bool HasErrors { get; private set; } + + /// + /// The number of failures added so far, of any severity. A chain that stops at its first failure compares it before and after a rule. + /// + public readonly int Count => _failures?.Count ?? 0; + + /// + /// The value of a message's placeholder. + /// + /// The placeholder's name. + /// Its value. + /// The pair takes. + public static KeyValuePair Argument(string name, object? value) => new(name, value); + + /// + /// Moves into a member of the value being validated, so the failures added from here on are under it. + /// + /// The member's name. + /// The path to give back to . + public string Enter(string member) + { + var previous = Path; + Path = Combine(previous, member); + return previous; + } + + /// + /// Moves into an item of the collection being validated. + /// + /// The item's position. + /// The path to give back to . + public string Enter(int index) + { + var previous = Path; + Path = string.Concat(previous, "[", index.ToString(CultureInfo.InvariantCulture), "]"); + return previous; + } + + /// + /// Moves back to where was called. + /// + /// What returned. + public void Leave(string previous) => Path = previous; + + /// + /// Adds a failure. + /// + /// The member the rule is about, or empty for the value itself. + /// The rule's code. + /// The message template. + /// How serious the failure is. + /// The values of the template's placeholders. + public void Add( + string member, + string code, + string template, + ValidationSeverity severity, + params ReadOnlySpan> arguments + ) + { + var message = ValidationMessage.Format(_messages?.GetTemplate(code, template) ?? template, arguments); + Add(new ValidationFailure(Combine(Path, member), code, message, severity, [.. arguments])); + } + + /// + /// Adds a failure that is already made. Its path is taken as it is. + /// + /// The failure. + public void Add(ValidationFailure failure) + { + ArgumentNullException.ThrowIfNull(failure); + ( _failures ??= ImmutableArray.CreateBuilder() ).Add(failure); + HasErrors |= failure.Severity == ValidationSeverity.Error; + } + + /// + /// Adds the failures of another validation, each under the current path. + /// + /// The result of validating the value at the current path. + public void Add(ValidationResult result) + { + foreach (var failure in result.Failures) + { + Add(failure with { Path = Combine(Path, failure.Path) }); + } + } + + /// + /// The result of the validation. + /// + /// Every failure added. + public readonly ValidationResult ToResult() => _failures is null ? ValidationResult.Valid : new(_failures.ToImmutable()); + + private static string Combine(string prefix, string member) => + prefix.Length == 0 ? member + : member.Length == 0 ? prefix + : member[0] == '[' ? string.Concat(prefix, member) + : string.Concat(prefix, ".", member); +} diff --git a/test/Validation.Analyzers.Tests/ModuleInitializer.cs b/test/Validation.Analyzers.Tests/ModuleInitializer.cs new file mode 100644 index 00000000000..154697b16f9 --- /dev/null +++ b/test/Validation.Analyzers.Tests/ModuleInitializer.cs @@ -0,0 +1,21 @@ +using System.Runtime.CompilerServices; + +using DiffEngine; + +using Microsoft.CodeAnalysis; + +using Rocket.Surgery.Extensions.Testing.SourceGenerators; + +namespace Validation.Analyzers.Tests; + +public static class ModuleInitializer +{ + [ModuleInitializer] + public static void Init() + { + VerifyGeneratorTextContext.Initialize(DiagnosticSeverity.Warning, Customizers.Empty); + DiffRunner.Disabled = true; + VerifierSettings.UseTextDiffFormat(TextDiffFormat.Compact); + DerivePathInfo((sourceFile, _, type, method) => new(Path.Combine(Path.GetDirectoryName(sourceFile)!, "snapshots"), type.Name, method.Name)); + } +} diff --git a/test/Validation.Analyzers.Tests/NestedValidationAnalyzerTests.cs b/test/Validation.Analyzers.Tests/NestedValidationAnalyzerTests.cs new file mode 100644 index 00000000000..02cc97c0e40 --- /dev/null +++ b/test/Validation.Analyzers.Tests/NestedValidationAnalyzerTests.cs @@ -0,0 +1,55 @@ +using Rocket.Surgery.LaunchPad.Validation.Analyzers; + +namespace Validation.Analyzers.Tests; + +public class NestedValidationAnalyzerTests +{ + [Test] + public async Task Should_Report_A_Member_Whose_Type_Has_Rules_And_Offer_Both_Decisions() + { + var result = await TestBuilder.Fix( + """ + using System.Collections.Generic; + using Rocket.Surgery.LaunchPad.Validation.Rules; + + namespace Sample; + + public sealed record Crew([NotEmpty] string Captain); + + public readonly record struct Stage([GreaterThan(0d)] double Thrust); + + public sealed class Launcher + { + [NotEmpty] + public string? Name { get; set; } + + /// The crew. + public Crew? Crew { get; set; } + + [NotEmpty] + public IReadOnlyList? Stages { get; set; } + + public Stage? Booster; + + [ValidateNested] + public Crew? Decided { get; set; } + + [SkipValidation] + public Crew? Skipped { get; set; } + + public string? Plain { get; set; } + } + + public sealed record Mission([NotEmpty] string Name, Crew Crew); + + // Has no rules of its own: nothing here is validated, so nothing is reported. + public sealed class Hangar + { + public Crew? Crew { get; set; } + } + """ + ); + + await Verify(await TestBuilder.Describe(result)).DontIgnoreEmptyCollections(); + } +} diff --git a/test/Validation.Analyzers.Tests/TestBuilder.cs b/test/Validation.Analyzers.Tests/TestBuilder.cs new file mode 100644 index 00000000000..f25d58134c2 --- /dev/null +++ b/test/Validation.Analyzers.Tests/TestBuilder.cs @@ -0,0 +1,119 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; + +using Rocket.Surgery.Extensions.Testing.SourceGenerators; +using Rocket.Surgery.LaunchPad.Validation; +using Rocket.Surgery.LaunchPad.Validation.Analyzers; + +namespace Validation.Analyzers.Tests; + +/// +/// The compilations the tests run the generator and the analyzers on: an application that references Validation, and with +/// services the dependency injection abstractions and Microsoft.Extensions.Options, which the registration and the options +/// validation are written for. +/// +internal static class TestBuilder +{ + public const string RegistrationFile = "LaunchPadValidators.g.cs"; + + public static GeneratorTestContextBuilder Create(bool services = false) + { + var builder = GeneratorTestContextBuilder + .Create() + .WithProjectName("Application") + .WithLanguageVersion(LanguageVersion.Preview) + .AddReferences(typeof(IValidate<>).Assembly) + .AddReferences(Framework); + return services ? builder.AddReferences(typeof(IServiceCollection).Assembly, typeof(IValidateOptions<>).Assembly) : builder; + } + + /// The assemblies of the shared framework, as an application compiles against them. + public static IReadOnlyCollection Framework { get; } = + [ + .. ( (string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")! ) + .Split(Path.PathSeparator) + .Where(static z => Path.GetFileName(z) is { } name && ( name.StartsWith("System.", StringComparison.Ordinal) || name is "netstandard.dll" or "mscorlib.dll" )) + .Where(static z => Path.GetDirectoryName(z) == Path.GetDirectoryName(typeof(object).Assembly.Location)), + ]; + + /// Runs the generator on . + public static Task Generate(string source, bool services = false) => + Create(services) + .WithGenerator() + .AddSources("#nullable enable\n" + source) + .Build() + .GenerateAsync(TestContext.Current!.Execution.CancellationToken); + + /// Runs on , and on what it reports. + public static Task Fix(string source) + where TAnalyzer : DiagnosticAnalyzer, new() + where TFix : CodeFixProvider, new() => + Create() + .AddSource("Input.cs", "#nullable enable\n" + source) + .WithAnalyzer() + .WithCodeFix() + .Build() + .GenerateAsync(TestContext.Current!.Execution.CancellationToken); + + /// Checks that what the generator wrote compiles without an error or a warning. + public static async Task ShouldCompileCleanly(this GeneratorTestResults result) + { + var problems = result.FinalCompilation + .GetDiagnostics() + .Where(static z => z.Severity >= DiagnosticSeverity.Warning) + // assembly version unification, which the .NET SDK leaves out of every build too (NoWarn) + .Where(static z => z.Id is not ( "CS1701" or "CS1702" )) + .Select(static z => z.ToString()) + .ToArray(); + await Assert.That(problems).IsEmpty(); + } + + /// + /// What a snapshot shows of an analyzer run: the LPAD diagnostics it reported, in source order, and each fix offered on them with the + /// source as that fix alone leaves it. + /// + public static async Task Describe(GeneratorTestResults results) + { + var reported = results + .AnalyzerResults.Values.SelectMany(static z => z.Diagnostics) + .Where(static z => z.Id.StartsWith("LPAD", StringComparison.Ordinal) || z.Id == "AD0001") + .GroupBy(static z => (z.Id, z.Location.SourceSpan)) + .Select(static z => z.First()) + .OrderBy(static z => z.Location.SourceSpan.Start) + .Select( + static z => new + { + z.Id, + z.Severity, + Location = z.Location.GetLineSpan().ToString(), + Source = z.Location.SourceTree?.GetText().ToString(z.Location.SourceSpan), + Message = z.GetMessage(System.Globalization.CultureInfo.InvariantCulture), + } + ) + .ToArray(); + + var fixes = new List(); + var seen = new HashSet<(string, Microsoft.CodeAnalysis.Text.TextSpan)>(); + foreach (var resolved in results.CodeFixResults.Values.SelectMany(static z => z.ResolvedFixes)) + { + if (!seen.Add((resolved.Diagnostic.Id, resolved.Diagnostic.Location.SourceSpan))) continue; + foreach (var action in resolved.CodeActions) + { + foreach (var operation in await action.CodeAction.GetOperationsAsync(CancellationToken.None)) + { + if (operation is not ApplyChangesOperation apply) continue; + var text = await apply.ChangedSolution.GetDocument(action.TargetDocument.Id)!.GetTextAsync(); + fixes.Add(new { Diagnostic = resolved.Diagnostic.Location.GetLineSpan().ToString(), action.CodeAction.Title, Text = text.ToString(), }); + break; + } + } + } + + return new { Diagnostics = reported, CodeFixes = fixes, }; + } +} diff --git a/test/Validation.Analyzers.Tests/Validation.Analyzers.Tests.csproj b/test/Validation.Analyzers.Tests/Validation.Analyzers.Tests.csproj new file mode 100644 index 00000000000..b7160244390 --- /dev/null +++ b/test/Validation.Analyzers.Tests/Validation.Analyzers.Tests.csproj @@ -0,0 +1,25 @@ + + + + $(LaunchPadTargetFrameworks) + false + + + + + + + + + + + + + + + + + + + + diff --git a/test/Validation.Analyzers.Tests/ValidatorGeneratorTests.cs b/test/Validation.Analyzers.Tests/ValidatorGeneratorTests.cs new file mode 100644 index 00000000000..45dc7264732 --- /dev/null +++ b/test/Validation.Analyzers.Tests/ValidatorGeneratorTests.cs @@ -0,0 +1,307 @@ +namespace Validation.Analyzers.Tests; + +public class ValidatorGeneratorTests +{ + [Test] + public async Task Should_Write_A_Validator_For_Rule_Attributes() + { + var result = await TestBuilder.Generate( + """ + using System; + using Rocket.Surgery.LaunchPad.Validation; + using Rocket.Surgery.LaunchPad.Validation.Rules; + + namespace Sample; + + public enum Fuel { Kerosene, Methane } + + public sealed record Launcher + { + [NotEmpty, MinLength(3), MaxLength(30, Message = "{Name} is too long", Code = "TooLong")] + [Matches("^[A-Z]", Options = System.Text.RegularExpressions.RegexOptions.IgnoreCase)] + public string? Name { get; init; } + + [IsInEnum] + public Fuel Fuel { get; init; } + + [InclusiveBetween(1, 33), NotEqual(13, Severity = ValidationSeverity.Warning)] + public int Engines { get; init; } + + [GreaterThanOrEqualTo(0), PrecisionScale(8, 2)] + public decimal? Price { get; init; } + + [NotDefault, GreaterThan("2000-01-01")] + public DateOnly Built { get; init; } + + [GreaterThanOrEqualTo(Member = nameof(Built))] + public DateOnly? Launched { get; init; } + + [Must(nameof(IsOdd))] + public int Fins { get; init; } + + [Must(nameof(IsShort))] + public string? Nickname { get; init; } + + public string? NotValidated { get; init; } + + public static bool IsOdd(int value) => value % 2 == 1; + internal bool IsShort(string? value) => value is null || value.Length < 5; + } + """ + ); + + await result.ShouldCompileCleanly(); + await Verify(result); + } + + [Test] + public async Task Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class() + { + var result = await TestBuilder.Generate( + """ + using Rocket.Surgery.LaunchPad.Validation.Rules; + + namespace Sample; + + public abstract class Named + { + [NotEmpty] + public string? Name { get; set; } + } + + public sealed class Stage : Named + { + [GreaterThan(0d)] + public double Thrust; + } + + public readonly record struct Position([InclusiveBetween(-90d, 90d)] double Latitude, [property: InclusiveBetween(-180d, 180d)] double Longitude); + + internal static class Outer + { + internal sealed record Inner([MaxLength(3)] int[] Values); + } + """ + ); + + await result.ShouldCompileCleanly(); + await Verify(result); + } + + [Test] + public async Task Should_Compile_The_DataAnnotations_Attributes() + { + var result = await TestBuilder.Generate( + """ + using System.ComponentModel.DataAnnotations; + + public sealed class Account + { + [Required, StringLength(20, MinimumLength = 3, ErrorMessage = "{0} must have {1} to {2} characters")] + public string? UserName { get; set; } + + [Required(AllowEmptyStrings = true), StringLength(100)] + public string? Notes { get; set; } + + [Required] + public int? Age { get; set; } + + [EmailAddress, Url] + public string? Contact { get; set; } + + [Range(18, 120)] + public int Years { get; set; } + + [Range(0d, 1d, MinimumIsExclusive = true)] + public double Share { get; set; } + + [Range(0, 10, MinimumIsExclusive = true, MaximumIsExclusive = true)] + public decimal Score { get; set; } + + [RegularExpression("[0-9]{4}")] + public string? Pin { get; set; } + + [MinLength(1), MaxLength(3), Length(1, 3)] + public string[]? Roles { get; set; } + + [MaxLength] + public string? Unbounded { get; set; } + + public string? Password { get; set; } + + [Compare(nameof(Password))] + public string? Confirmation { get; set; } + } + """ + ); + + await result.ShouldCompileCleanly(); + await Verify(result); + } + + [Test] + public async Task Should_Validate_Nested_Members_With_Their_Validators() + { + var result = await TestBuilder.Generate( + """ + using System.Collections.Generic; + using Rocket.Surgery.LaunchPad.Validation; + using Rocket.Surgery.LaunchPad.Validation.Rules; + + namespace Sample; + + public sealed record Crew([NotEmpty] string Captain); + + public readonly record struct Stage([GreaterThan(0d)] double Thrust); + + public sealed class Launcher + { + [ValidateNested] + public Crew? Crew { get; set; } + + [NotNull, ValidateNested] + public Stage? Booster { get; set; } + + [ValidateNested] + public Stage Core { get; set; } + + [NotEmpty, ValidateNested] + public IReadOnlyList? Stages { get; set; } + + [ValidateNested] + public Crew?[] Backups { get; set; } = []; + + [ValidateWith] + public Crew? Reserve { get; set; } + + [SkipValidation] + public Crew? Ground { get; set; } + } + + public sealed class StrictCrew : IValidate + { + public ValidationResult Validate(Crew value) => ValidationResult.Valid; + } + """ + ); + + await result.ShouldCompileCleanly(); + await Verify(result); + } + + [Test] + public async Task Should_Register_The_Validators_And_Validate_Options() + { + var result = await TestBuilder.Generate( + """ + using Rocket.Surgery.LaunchPad.Validation.Rules; + + namespace Sample + { + public sealed class RetryOptions + { + [InclusiveBetween(1, 10)] + public int Attempts { get; set; } + } + + internal readonly record struct Delay([GreaterThan(0)] int Milliseconds); + } + """, + true + ); + + await result.ShouldCompileCleanly(); + await Verify(result); + } + + [Test] + public async Task Should_Write_Nothing_For_A_Type_With_No_Rules() + { + var result = await TestBuilder.Generate( + """ + using System.Text.Json.Serialization; + + public sealed class Plain + { + [JsonPropertyName("name")] + public string? Name { get; set; } + } + """, + true + ); + + await result.ShouldCompileCleanly(); + await Verify(result); + } + + [Test] + public async Task Should_Report_What_It_Cannot_Write() + { + var result = await TestBuilder.Generate( + """ + using System; + using System.ComponentModel.DataAnnotations; + using Rules = Rocket.Surgery.LaunchPad.Validation.Rules; + + public sealed class Generic + { + [Rules.NotEmpty] + public string? Name { get; set; } + } + + public static class Outer + { + private sealed class Hidden + { + [Rules.NotEmpty] + public string? Name { get; set; } + } + } + + public sealed class Mistakes + { + [Rules.NotEmpty] + private string? Secret { get; set; } + + [Rules.EmailAddress] + public int NotAString { get; set; } + + [Rules.GreaterThan("soon")] + public Uri? NotParsable { get; set; } + + [Rules.GreaterThan] + public int NoValue { get; set; } + + [Rules.LessThan(Member = "Missing")] + public int NoSuchMember { get; set; } + + [Rules.Must("Missing")] + public int NoSuchMethod { get; set; } + + [Rules.Must(nameof(IsFree))] + public string? Asynchronous { get; set; } + + [Rules.Must(nameof(IsPrivate))] + public string? PrivateMethod { get; set; } + + [Rules.ValidateNested] + public int NotNested { get; set; } + + [Phone, CreditCard] + public string? Phone { get; set; } + + [Range(typeof(DateTime), "2000-01-01", "2100-01-01")] + public DateTime Reflected { get; set; } + + [Rules.NotEmpty] + public string? Fine { get; set; } + + public System.Threading.Tasks.ValueTask IsFree(string? value) => new(true); + private bool IsPrivate(string? value) => true; + } + """ + ); + + await Verify(result); + } +} diff --git a/test/Validation.Analyzers.Tests/snapshots/NestedValidationAnalyzerTests.Should_Report_A_Member_Whose_Type_Has_Rules_And_Offer_Both_Decisions.verified.txt b/test/Validation.Analyzers.Tests/snapshots/NestedValidationAnalyzerTests.Should_Report_A_Member_Whose_Type_Has_Rules_And_Offer_Both_Decisions.verified.txt new file mode 100644 index 00000000000..dd3c8740ec3 --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/NestedValidationAnalyzerTests.Should_Report_A_Member_Whose_Type_Has_Rules_And_Offer_Both_Decisions.verified.txt @@ -0,0 +1,392 @@ +{ + Diagnostics: [ + { + Id: LPAD3001, + Severity: Warning, + Location: Input.cs: (16,17)-(16,21), + Source: Crew, + Message: 'Crew' is a Crew?, which has rules, but they are not applied here: add [ValidateNested] to validate it, or [SkipValidation] to say it is deliberate + }, + { + Id: LPAD3001, + Severity: Warning, + Location: Input.cs: (19,33)-(19,39), + Source: Stages, + Message: 'Stages' is a collection of Stage, which has rules, but they are not applied here: add [ValidateNested] to validate it, or [SkipValidation] to say it is deliberate + }, + { + Id: LPAD3001, + Severity: Warning, + Location: Input.cs: (21,18)-(21,25), + Source: Booster, + Message: 'Booster' is a Stage, which has rules, but they are not applied here: add [ValidateNested] to validate it, or [SkipValidation] to say it is deliberate + }, + { + Id: LPAD3001, + Severity: Warning, + Location: Input.cs: (32,58)-(32,62), + Source: Crew, + Message: 'Crew' is a Crew, which has rules, but they are not applied here: add [ValidateNested] to validate it, or [SkipValidation] to say it is deliberate + } + ], + CodeFixes: [ + { + Diagnostic: Input.cs: (16,17)-(16,21), + Title: Add [SkipValidation], + Text: +#nullable enable +using System.Collections.Generic; +using Rocket.Surgery.LaunchPad.Validation.Rules; + +namespace Sample; + +public sealed record Crew([NotEmpty] string Captain); + +public readonly record struct Stage([GreaterThan(0d)] double Thrust); + +public sealed class Launcher +{ + [NotEmpty] + public string? Name { get; set; } + + /// The crew. + [SkipValidation] + public Crew? Crew { get; set; } + + [NotEmpty] + public IReadOnlyList? Stages { get; set; } + + public Stage? Booster; + + [ValidateNested] + public Crew? Decided { get; set; } + + [SkipValidation] + public Crew? Skipped { get; set; } + + public string? Plain { get; set; } +} + +public sealed record Mission([NotEmpty] string Name, Crew Crew); + +// Has no rules of its own: nothing here is validated, so nothing is reported. +public sealed class Hangar +{ + public Crew? Crew { get; set; } +} + }, + { + Diagnostic: Input.cs: (16,17)-(16,21), + Title: Add [ValidateNested], + Text: +#nullable enable +using System.Collections.Generic; +using Rocket.Surgery.LaunchPad.Validation.Rules; + +namespace Sample; + +public sealed record Crew([NotEmpty] string Captain); + +public readonly record struct Stage([GreaterThan(0d)] double Thrust); + +public sealed class Launcher +{ + [NotEmpty] + public string? Name { get; set; } + + /// The crew. + [ValidateNested] + public Crew? Crew { get; set; } + + [NotEmpty] + public IReadOnlyList? Stages { get; set; } + + public Stage? Booster; + + [ValidateNested] + public Crew? Decided { get; set; } + + [SkipValidation] + public Crew? Skipped { get; set; } + + public string? Plain { get; set; } +} + +public sealed record Mission([NotEmpty] string Name, Crew Crew); + +// Has no rules of its own: nothing here is validated, so nothing is reported. +public sealed class Hangar +{ + public Crew? Crew { get; set; } +} + }, + { + Diagnostic: Input.cs: (19,33)-(19,39), + Title: Add [SkipValidation], + Text: +#nullable enable +using System.Collections.Generic; +using Rocket.Surgery.LaunchPad.Validation.Rules; + +namespace Sample; + +public sealed record Crew([NotEmpty] string Captain); + +public readonly record struct Stage([GreaterThan(0d)] double Thrust); + +public sealed class Launcher +{ + [NotEmpty] + public string? Name { get; set; } + + /// The crew. + public Crew? Crew { get; set; } + + [NotEmpty] + [SkipValidation] + public IReadOnlyList? Stages { get; set; } + + public Stage? Booster; + + [ValidateNested] + public Crew? Decided { get; set; } + + [SkipValidation] + public Crew? Skipped { get; set; } + + public string? Plain { get; set; } +} + +public sealed record Mission([NotEmpty] string Name, Crew Crew); + +// Has no rules of its own: nothing here is validated, so nothing is reported. +public sealed class Hangar +{ + public Crew? Crew { get; set; } +} + }, + { + Diagnostic: Input.cs: (19,33)-(19,39), + Title: Add [ValidateNested], + Text: +#nullable enable +using System.Collections.Generic; +using Rocket.Surgery.LaunchPad.Validation.Rules; + +namespace Sample; + +public sealed record Crew([NotEmpty] string Captain); + +public readonly record struct Stage([GreaterThan(0d)] double Thrust); + +public sealed class Launcher +{ + [NotEmpty] + public string? Name { get; set; } + + /// The crew. + public Crew? Crew { get; set; } + + [NotEmpty] + [ValidateNested] + public IReadOnlyList? Stages { get; set; } + + public Stage? Booster; + + [ValidateNested] + public Crew? Decided { get; set; } + + [SkipValidation] + public Crew? Skipped { get; set; } + + public string? Plain { get; set; } +} + +public sealed record Mission([NotEmpty] string Name, Crew Crew); + +// Has no rules of its own: nothing here is validated, so nothing is reported. +public sealed class Hangar +{ + public Crew? Crew { get; set; } +} + }, + { + Diagnostic: Input.cs: (21,18)-(21,25), + Title: Add [SkipValidation], + Text: +#nullable enable +using System.Collections.Generic; +using Rocket.Surgery.LaunchPad.Validation.Rules; + +namespace Sample; + +public sealed record Crew([NotEmpty] string Captain); + +public readonly record struct Stage([GreaterThan(0d)] double Thrust); + +public sealed class Launcher +{ + [NotEmpty] + public string? Name { get; set; } + + /// The crew. + public Crew? Crew { get; set; } + + [NotEmpty] + public IReadOnlyList? Stages { get; set; } + + [SkipValidation] + public Stage? Booster; + + [ValidateNested] + public Crew? Decided { get; set; } + + [SkipValidation] + public Crew? Skipped { get; set; } + + public string? Plain { get; set; } +} + +public sealed record Mission([NotEmpty] string Name, Crew Crew); + +// Has no rules of its own: nothing here is validated, so nothing is reported. +public sealed class Hangar +{ + public Crew? Crew { get; set; } +} + }, + { + Diagnostic: Input.cs: (21,18)-(21,25), + Title: Add [ValidateNested], + Text: +#nullable enable +using System.Collections.Generic; +using Rocket.Surgery.LaunchPad.Validation.Rules; + +namespace Sample; + +public sealed record Crew([NotEmpty] string Captain); + +public readonly record struct Stage([GreaterThan(0d)] double Thrust); + +public sealed class Launcher +{ + [NotEmpty] + public string? Name { get; set; } + + /// The crew. + public Crew? Crew { get; set; } + + [NotEmpty] + public IReadOnlyList? Stages { get; set; } + + [ValidateNested] + public Stage? Booster; + + [ValidateNested] + public Crew? Decided { get; set; } + + [SkipValidation] + public Crew? Skipped { get; set; } + + public string? Plain { get; set; } +} + +public sealed record Mission([NotEmpty] string Name, Crew Crew); + +// Has no rules of its own: nothing here is validated, so nothing is reported. +public sealed class Hangar +{ + public Crew? Crew { get; set; } +} + }, + { + Diagnostic: Input.cs: (32,58)-(32,62), + Title: Add [SkipValidation], + Text: +#nullable enable +using System.Collections.Generic; +using Rocket.Surgery.LaunchPad.Validation.Rules; + +namespace Sample; + +public sealed record Crew([NotEmpty] string Captain); + +public readonly record struct Stage([GreaterThan(0d)] double Thrust); + +public sealed class Launcher +{ + [NotEmpty] + public string? Name { get; set; } + + /// The crew. + public Crew? Crew { get; set; } + + [NotEmpty] + public IReadOnlyList? Stages { get; set; } + + public Stage? Booster; + + [ValidateNested] + public Crew? Decided { get; set; } + + [SkipValidation] + public Crew? Skipped { get; set; } + + public string? Plain { get; set; } +} + +public sealed record Mission([NotEmpty] string Name, [SkipValidation] Crew Crew); + +// Has no rules of its own: nothing here is validated, so nothing is reported. +public sealed class Hangar +{ + public Crew? Crew { get; set; } +} + }, + { + Diagnostic: Input.cs: (32,58)-(32,62), + Title: Add [ValidateNested], + Text: +#nullable enable +using System.Collections.Generic; +using Rocket.Surgery.LaunchPad.Validation.Rules; + +namespace Sample; + +public sealed record Crew([NotEmpty] string Captain); + +public readonly record struct Stage([GreaterThan(0d)] double Thrust); + +public sealed class Launcher +{ + [NotEmpty] + public string? Name { get; set; } + + /// The crew. + public Crew? Crew { get; set; } + + [NotEmpty] + public IReadOnlyList? Stages { get; set; } + + public Stage? Booster; + + [ValidateNested] + public Crew? Decided { get; set; } + + [SkipValidation] + public Crew? Skipped { get; set; } + + public string? Plain { get; set; } +} + +public sealed record Mission([NotEmpty] string Name, [ValidateNested] Crew Crew); + +// Has no rules of its own: nothing here is validated, so nothing is reported. +public sealed class Hangar +{ + public Crew? Crew { get; set; } +} + } + ] +} \ No newline at end of file diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Compile_The_DataAnnotations_Attributes#Account.Validator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Compile_The_DataAnnotations_Attributes#Account.Validator.g.verified.cs new file mode 100644 index 00000000000..2db38f3feca --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Compile_The_DataAnnotations_Attributes#Account.Validator.g.verified.cs @@ -0,0 +1,200 @@ +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Account.Validator.g.cs +// +#nullable enable + +/// +/// Validates a : the rules its members carry as attributes. +/// +[global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Account))] +public sealed partial class AccountValidator + : global::Rocket.Surgery.LaunchPad.Validation.IValidate +{ + private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; + + private static readonly global::System.Text.RegularExpressions.Regex PinPattern = + new("^(?:[0-9]{4})$", (global::System.Text.RegularExpressions.RegexOptions)0 | global::System.Text.RegularExpressions.RegexOptions.CultureInvariant, global::System.TimeSpan.FromSeconds(2)); + + /// + /// Creates the validator. + /// + /// What replaces the rules' messages, if anything does. + public AccountValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; + + /// + public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Account value) + { + global::System.ArgumentNullException.ThrowIfNull(value); + var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); + EnsureUserName(value.UserName, ref sink); + EnsureNotes(value.Notes, ref sink); + EnsureAge(value.Age, ref sink); + EnsureContact(value.Contact, ref sink); + EnsureYears(value.Years, ref sink); + EnsureShare(value.Share, ref sink); + EnsureScore(value.Score, ref sink); + EnsurePin(value.Pin, ref sink); + EnsureRoles(value.Roles, ref sink); + EnsureConfirmation(value.Confirmation, value.Password, ref sink); + return sink.ToResult(); + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("UserName", "NotEmpty", "Length(3, 20)")] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void EnsureUserName(string? value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.NotEmpty(value)) + { + sink.Add("UserName", "NotEmpty", "{Name} must not be empty", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "UserName"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value)); + } + + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.Length(value, 3, 20)) + { + sink.Add("UserName", "Length", "{Name} must have {Min} to {Max} characters", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "UserName"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Min", 3), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Max", 20)); + } + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Notes", "NotNull", "MaxLength(100)")] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void EnsureNotes(string? value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.NotNull(value)) + { + sink.Add("Notes", "NotNull", "{Name} is required", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Notes"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value)); + } + + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.MaxLength(value, 100)) + { + sink.Add("Notes", "MaxLength", "{Name} must be at most {Max} characters long", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Notes"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Max", 100)); + } + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Age", "NotNull")] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void EnsureAge(int? value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.NotNull(value)) + { + sink.Add("Age", "NotNull", "{Name} is required", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Age"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value)); + } + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Contact", "EmailAddress", "Url")] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void EnsureContact(string? value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.EmailAddress(value)) + { + sink.Add("Contact", "EmailAddress", "{Name} is not a valid email address", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Contact"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value)); + } + + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.Url(value)) + { + sink.Add("Contact", "Url", "{Name} is not a valid URL", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Contact"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value)); + } + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Years", "InclusiveBetween(18, 120)")] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void EnsureYears(int value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.InclusiveBetween(value, (int)(18), (int)(120))) + { + sink.Add("Years", "InclusiveBetween", "{Name} must be between {Min} and {Max}", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Years"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Min", (int)(18)), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Max", (int)(120))); + } + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Share", "GreaterThan(0)", "LessThanOrEqualTo(1)")] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void EnsureShare(double value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.GreaterThan(value, (double)(0))) + { + sink.Add("Share", "GreaterThan", "{Name} must be greater than {Other}", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Share"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Other", (double)(0))); + } + + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.LessThanOrEqualTo(value, (double)(1))) + { + sink.Add("Share", "LessThanOrEqualTo", "{Name} must be less than or equal to {Other}", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Share"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Other", (double)(1))); + } + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Score", "ExclusiveBetween(0, 10)")] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void EnsureScore(decimal value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.ExclusiveBetween(value, (decimal)(0), (decimal)(10))) + { + sink.Add("Score", "ExclusiveBetween", "{Name} must be greater than {Min} and less than {Max}", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Score"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Min", (decimal)(0)), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Max", (decimal)(10))); + } + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Pin", "Matches(\"^(?:[0-9]{4})$\")")] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void EnsurePin(string? value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.Matches(value, PinPattern)) + { + sink.Add("Pin", "Matches", "{Name} is not in the expected format", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Pin"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value)); + } + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Roles", "MinLength(1)", "MaxLength(3)", "Length(1, 3)")] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void EnsureRoles(string[]? value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.MinLength(value, 1)) + { + sink.Add("Roles", "MinLength", "{Name} must have at least {Min} items", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Roles"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Min", 1)); + } + + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.MaxLength(value, 3)) + { + sink.Add("Roles", "MaxLength", "{Name} must have at most {Max} items", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Roles"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Max", 3)); + } + + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.Length(value, 1, 3)) + { + sink.Add("Roles", "Length", "{Name} must have between {Min} and {Max} items", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Roles"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Min", 1), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Max", 3)); + } + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Confirmation", "Equal(Password)", Reads = new[] { "Password" })] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void EnsureConfirmation(string? value, string? otherPassword, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.Equal(value, otherPassword)) + { + sink.Add("Confirmation", "Equal", "{Name} must be equal to {Other}", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Confirmation"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Other", otherPassword)); + } + } +} diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Compile_The_DataAnnotations_Attributes.verified.txt b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Compile_The_DataAnnotations_Attributes.verified.txt new file mode 100644 index 00000000000..b814e7ed8ef --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Compile_The_DataAnnotations_Attributes.verified.txt @@ -0,0 +1,6 @@ +{ + FinalDiagnostics: [], + GeneratorDiagnostics: { + Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator: [] + } +} \ No newline at end of file diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Named.Validator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Named.Validator.g.verified.cs new file mode 100644 index 00000000000..45f4e394b93 --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Named.Validator.g.verified.cs @@ -0,0 +1,44 @@ +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.Named.Validator.g.cs +// +#nullable enable + +namespace Sample +{ + /// + /// Validates a : the rules its members carry as attributes. + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Named))] + public sealed partial class NamedValidator + : global::Rocket.Surgery.LaunchPad.Validation.IValidate + { + private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; + + /// + /// Creates the validator. + /// + /// What replaces the rules' messages, if anything does. + public NamedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; + + /// + public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Named value) + { + global::System.ArgumentNullException.ThrowIfNull(value); + var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); + EnsureName(value.Name, ref sink); + return sink.ToResult(); + } + + /// + /// 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)); + } + } + } +} diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Outer_Inner.Validator.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_Inner.Validator.g.verified.cs new file mode 100644 index 00000000000..11eb69902ca --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Outer_Inner.Validator.g.verified.cs @@ -0,0 +1,44 @@ +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.Outer_Inner.Validator.g.cs +// +#nullable enable + +namespace Sample +{ + /// + /// Validates a : the rules its members carry as attributes. + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Outer.Inner))] + internal sealed partial class Outer_InnerValidator + : global::Rocket.Surgery.LaunchPad.Validation.IValidate + { + private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; + + /// + /// Creates the validator. + /// + /// What replaces the rules' messages, if anything does. + public Outer_InnerValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; + + /// + public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Outer.Inner value) + { + global::System.ArgumentNullException.ThrowIfNull(value); + var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); + EnsureValues(value.Values, ref sink); + return sink.ToResult(); + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Values", "MaxLength(3)")] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void EnsureValues(int[] value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.MaxLength(value, 3)) + { + sink.Add("Values", "MaxLength", "{Name} must have at most {Max} items", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Values"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Max", 3)); + } + } + } +} diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Position.Validator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Position.Validator.g.verified.cs new file mode 100644 index 00000000000..1e9989eea3d --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Position.Validator.g.verified.cs @@ -0,0 +1,57 @@ +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.Position.Validator.g.cs +// +#nullable enable + +namespace Sample +{ + /// + /// Validates a : the rules its members carry as attributes. + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Position))] + public sealed partial class PositionValidator + : global::Rocket.Surgery.LaunchPad.Validation.IValidate + { + private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; + + /// + /// Creates the validator. + /// + /// What replaces the rules' messages, if anything does. + public PositionValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; + + /// + public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Position value) + { + var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); + EnsureLatitude(value.Latitude, ref sink); + EnsureLongitude(value.Longitude, ref sink); + return sink.ToResult(); + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Latitude", "InclusiveBetween(-90, 90)")] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void EnsureLatitude(double value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.InclusiveBetween(value, (double)(-90), (double)(90))) + { + sink.Add("Latitude", "InclusiveBetween", "{Name} must be between {Min} and {Max}", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Latitude"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Min", (double)(-90)), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Max", (double)(90))); + } + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Longitude", "InclusiveBetween(-180, 180)")] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void EnsureLongitude(double value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.InclusiveBetween(value, (double)(-180), (double)(180))) + { + sink.Add("Longitude", "InclusiveBetween", "{Name} must be between {Min} and {Max}", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Longitude"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Min", (double)(-180)), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Max", (double)(180))); + } + } + } +} diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Stage.Validator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Stage.Validator.g.verified.cs new file mode 100644 index 00000000000..1863ef7ae84 --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Stage.Validator.g.verified.cs @@ -0,0 +1,58 @@ +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.Stage.Validator.g.cs +// +#nullable enable + +namespace Sample +{ + /// + /// Validates a : the rules its members carry as attributes. + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Stage))] + public sealed partial class StageValidator + : global::Rocket.Surgery.LaunchPad.Validation.IValidate + { + private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; + + /// + /// Creates the validator. + /// + /// What replaces the rules' messages, if anything does. + public StageValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; + + /// + public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Stage value) + { + global::System.ArgumentNullException.ThrowIfNull(value); + var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); + EnsureThrust(value.Thrust, ref sink); + EnsureName(value.Name, ref sink); + return sink.ToResult(); + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Thrust", "GreaterThan(0)")] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void EnsureThrust(double value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.GreaterThan(value, (double)(0))) + { + sink.Add("Thrust", "GreaterThan", "{Name} must be greater than {Other}", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Thrust"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Other", (double)(0))); + } + } + + /// + /// 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)); + } + } + } +} diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class.verified.txt b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class.verified.txt new file mode 100644 index 00000000000..b814e7ed8ef --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class.verified.txt @@ -0,0 +1,6 @@ +{ + FinalDiagnostics: [], + GeneratorDiagnostics: { + Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator: [] + } +} \ No newline at end of file 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 new file mode 100644 index 00000000000..2ba80880c2a --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#LaunchPadValidators.g.verified.cs @@ -0,0 +1,30 @@ +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/LaunchPadValidators.g.cs +// +#nullable enable + +[assembly: global::Rocket.Surgery.LaunchPad.Validation.ValidatorAssembly(typeof(global::Microsoft.Extensions.DependencyInjection.ApplicationValidatorsServiceCollectionExtensions), "AddApplicationValidators")] + +namespace Microsoft.Extensions.DependencyInjection +{ + /// + /// Registers the validators of Application. + /// + public static class ApplicationValidatorsServiceCollectionExtensions + { + /// + /// Adds the validators of Application, and those of the assemblies it references, each as the + /// IValidate and IValidateAsync of the type it validates. + /// + /// The services. + /// The services. + public static global::Microsoft.Extensions.DependencyInjection.IServiceCollection AddApplicationValidators(this global::Microsoft.Extensions.DependencyInjection.IServiceCollection services) + { + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.DelayValidator>(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, global::Sample.RetryOptionsValidator>(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.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton, global::Sample.RetryOptionsValidator>()); + return services; + } + } +} diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.Delay.Validator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.Delay.Validator.g.verified.cs new file mode 100644 index 00000000000..d1588849e70 --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.Delay.Validator.g.verified.cs @@ -0,0 +1,43 @@ +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.Delay.Validator.g.cs +// +#nullable enable + +namespace Sample +{ + /// + /// Validates a : the rules its members carry as attributes. + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Delay))] + internal sealed partial class DelayValidator + : global::Rocket.Surgery.LaunchPad.Validation.IValidate + { + private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; + + /// + /// Creates the validator. + /// + /// What replaces the rules' messages, if anything does. + public DelayValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; + + /// + public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Delay value) + { + var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); + EnsureMilliseconds(value.Milliseconds, ref sink); + return sink.ToResult(); + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Milliseconds", "GreaterThan(0)")] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void EnsureMilliseconds(int value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.GreaterThan(value, (int)(0))) + { + sink.Add("Milliseconds", "GreaterThan", "{Name} must be greater than {Other}", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Milliseconds"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Other", (int)(0))); + } + } + } +} diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.RetryOptions.Validator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.RetryOptions.Validator.g.verified.cs new file mode 100644 index 00000000000..acde6a49a73 --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.RetryOptions.Validator.g.verified.cs @@ -0,0 +1,58 @@ +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.RetryOptions.Validator.g.cs +// +#nullable enable + +namespace Sample +{ + /// + /// Validates a : the rules its members carry as attributes. + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.RetryOptions))] + public sealed partial class RetryOptionsValidator + : global::Rocket.Surgery.LaunchPad.Validation.IValidate, global::Microsoft.Extensions.Options.IValidateOptions + { + private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; + + /// + /// Creates the validator. + /// + /// What replaces the rules' messages, if anything does. + public RetryOptionsValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; + + /// + public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.RetryOptions value) + { + global::System.ArgumentNullException.ThrowIfNull(value); + var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); + EnsureAttempts(value.Attempts, ref sink); + return sink.ToResult(); + } + + /// + global::Microsoft.Extensions.Options.ValidateOptionsResult global::Microsoft.Extensions.Options.IValidateOptions.Validate(string? name, global::Sample.RetryOptions options) + { + var result = Validate(options); + if (result.IsValid) return global::Microsoft.Extensions.Options.ValidateOptionsResult.Success; + var failures = new global::System.Collections.Generic.List(); + foreach (var failure in result.Errors) + { + failures.Add(failure.Path.Length == 0 ? failure.Message : failure.Path + ": " + failure.Message); + } + + return global::Microsoft.Extensions.Options.ValidateOptionsResult.Fail(failures); + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Attempts", "InclusiveBetween(1, 10)")] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void EnsureAttempts(int value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.InclusiveBetween(value, (int)(1), (int)(10))) + { + sink.Add("Attempts", "InclusiveBetween", "{Name} must be between {Min} and {Max}", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Attempts"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Min", (int)(1)), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Max", (int)(10))); + } + } + } +} diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options.verified.txt b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options.verified.txt new file mode 100644 index 00000000000..b814e7ed8ef --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options.verified.txt @@ -0,0 +1,6 @@ +{ + FinalDiagnostics: [], + GeneratorDiagnostics: { + Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator: [] + } +} \ No newline at end of file diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Report_What_It_Cannot_Write#Mistakes.Validator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Report_What_It_Cannot_Write#Mistakes.Validator.g.verified.cs new file mode 100644 index 00000000000..92a7bd80596 --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Report_What_It_Cannot_Write#Mistakes.Validator.g.verified.cs @@ -0,0 +1,41 @@ +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Mistakes.Validator.g.cs +// +#nullable enable + +/// +/// Validates a : the rules its members carry as attributes. +/// +[global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Mistakes))] +public sealed partial class MistakesValidator + : global::Rocket.Surgery.LaunchPad.Validation.IValidate +{ + private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; + + /// + /// Creates the validator. + /// + /// What replaces the rules' messages, if anything does. + public MistakesValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; + + /// + public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Mistakes value) + { + global::System.ArgumentNullException.ThrowIfNull(value); + var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); + EnsureFine(value.Fine, ref sink); + return sink.ToResult(); + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Fine", "NotEmpty")] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void EnsureFine(string? value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.NotEmpty(value)) + { + sink.Add("Fine", "NotEmpty", "{Name} must not be empty", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Fine"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value)); + } + } +} diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Report_What_It_Cannot_Write.verified.txt b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Report_What_It_Cannot_Write.verified.txt new file mode 100644 index 00000000000..36d319ae806 --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Report_What_It_Cannot_Write.verified.txt @@ -0,0 +1,288 @@ +{ + FinalDiagnostics: [ + { + Id: LPAD3102, + Title: The generated validator can't reach it, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (13,25)-(13,31), + MessageFormat: {0} must be public or internal for its rules to be checked: the generated validator is a class of its own, + Message: 'Hidden' and the types that contain it must be public or internal for its rules to be checked: the generated validator is a class of its own, + Category: LaunchPad.Validation + }, + { + Id: LPAD3102, + Title: The generated validator can't reach it, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (23,20)-(23,26), + MessageFormat: {0} must be public or internal for its rules to be checked: the generated validator is a class of its own, + Message: 'Secret' must be public or internal for its rules to be checked: the generated validator is a class of its own, + Category: LaunchPad.Validation + }, + { + Id: LPAD3103, + Title: The rule doesn't apply to the member, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (25,5)-(25,23), + MessageFormat: [{0}] can't be checked on '{1}', which is of type {2}: {3}, + Message: [EmailAddress] can't be checked on 'NotAString', which is of type int: no Rocket.Surgery.LaunchPad.Validation.Rules.Rule.EmailAddress takes that type, + Category: LaunchPad.Validation + }, + { + Id: LPAD3105, + Title: The rule's argument is not valid, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (28,5)-(28,30), + MessageFormat: [{0}] on '{1}': {2}, + Message: [GreaterThan] on 'NotParsable': "soon" can't be read as a Uri?, which has no Parse(string, IFormatProvider), + Category: LaunchPad.Validation + }, + { + Id: LPAD3105, + Title: The rule's argument is not valid, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (31,5)-(31,22), + MessageFormat: [{0}] on '{1}': {2}, + Message: [GreaterThan] on 'NoValue': it needs a value, or the name of another member in Member, + Category: LaunchPad.Validation + }, + { + Id: LPAD3105, + Title: The rule's argument is not valid, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (34,5)-(34,39), + MessageFormat: [{0}] on '{1}': {2}, + Message: [LessThan] on 'NoSuchMember': 'Mistakes' has no other member 'Missing' to compare it with, + Category: LaunchPad.Validation + }, + { + Id: LPAD3105, + Title: The rule's argument is not valid, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (37,5)-(37,26), + MessageFormat: [{0}] on '{1}': {2}, + Message: [Must] on 'NoSuchMethod': 'Mistakes' has no method 'Missing' that takes the member's value and returns bool, + Category: LaunchPad.Validation + }, + { + Id: LPAD3105, + Title: The rule's argument is not valid, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (40,5)-(40,31), + MessageFormat: [{0}] on '{1}': {2}, + Message: [Must] on 'Asynchronous': 'IsFree' is asynchronous, which an attribute can't declare yet: declare the rule with MustAsync in a Validate function, + Category: LaunchPad.Validation + }, + { + Id: LPAD3102, + Title: The generated validator can't reach it, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (43,5)-(43,34), + MessageFormat: {0} must be public or internal for its rules to be checked: the generated validator is a class of its own, + Message: 'IsPrivate' must be public or internal for its rules to be checked: the generated validator is a class of its own, + Category: LaunchPad.Validation + }, + { + Id: LPAD3106, + Title: The member can't be validated with a validator, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (46,5)-(46,25), + MessageFormat: '{0}' is marked for nested validation, but {1}, + Message: 'NotNested' is marked for nested validation, but its type, int, is not one a validator is written for, + Category: LaunchPad.Validation + }, + { + Id: LPAD3104, + Title: The attribute is not compiled into the validator, + Severity: Warning, + WarningLevel: 1, + Location: Input0.cs: (49,12)-(49,22), + MessageFormat: [{0}] on '{1}' is not checked by the generated validator: {2}, + Message: [CreditCard] on 'Phone' is not checked by the generated validator: use a LaunchPad rule attribute, or [Must] with a method of the type, + Category: LaunchPad.Validation + }, + { + Id: LPAD3104, + Title: The attribute is not compiled into the validator, + Severity: Warning, + WarningLevel: 1, + Location: Input0.cs: (49,5)-(49,10), + MessageFormat: [{0}] on '{1}' is not checked by the generated validator: {2}, + Message: [Phone] on 'Phone' is not checked by the generated validator: use a LaunchPad rule attribute, or [Must] with a method of the type, + Category: LaunchPad.Validation + }, + { + Id: LPAD3101, + Title: A generic type can't be validated yet, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (5,20)-(5,27), + MessageFormat: '{0}' has rules, but it is generic or inside a generic type, which the generator doesn't write a validator for yet, + Message: 'Generic' has rules, but it is generic or inside a generic type, which the generator doesn't write a validator for yet, + Category: LaunchPad.Validation + }, + { + Id: LPAD3104, + Title: The attribute is not compiled into the validator, + Severity: Warning, + WarningLevel: 1, + Location: Input0.cs: (52,5)-(52,56), + MessageFormat: [{0}] on '{1}' is not checked by the generated validator: {2}, + Message: [Range] on 'Reflected' is not checked by the generated validator: a range of a type and two strings is converted through reflection; use [InclusiveBetween], which parses its strings at build time, + Category: LaunchPad.Validation + } + ], + GeneratorDiagnostics: { + Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator: [ + { + Id: LPAD3102, + Title: The generated validator can't reach it, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (13,25)-(13,31), + MessageFormat: {0} must be public or internal for its rules to be checked: the generated validator is a class of its own, + Message: 'Hidden' and the types that contain it must be public or internal for its rules to be checked: the generated validator is a class of its own, + Category: LaunchPad.Validation + }, + { + Id: LPAD3102, + Title: The generated validator can't reach it, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (23,20)-(23,26), + MessageFormat: {0} must be public or internal for its rules to be checked: the generated validator is a class of its own, + Message: 'Secret' must be public or internal for its rules to be checked: the generated validator is a class of its own, + Category: LaunchPad.Validation + }, + { + Id: LPAD3103, + Title: The rule doesn't apply to the member, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (25,5)-(25,23), + MessageFormat: [{0}] can't be checked on '{1}', which is of type {2}: {3}, + Message: [EmailAddress] can't be checked on 'NotAString', which is of type int: no Rocket.Surgery.LaunchPad.Validation.Rules.Rule.EmailAddress takes that type, + Category: LaunchPad.Validation + }, + { + Id: LPAD3105, + Title: The rule's argument is not valid, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (28,5)-(28,30), + MessageFormat: [{0}] on '{1}': {2}, + Message: [GreaterThan] on 'NotParsable': "soon" can't be read as a Uri?, which has no Parse(string, IFormatProvider), + Category: LaunchPad.Validation + }, + { + Id: LPAD3105, + Title: The rule's argument is not valid, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (31,5)-(31,22), + MessageFormat: [{0}] on '{1}': {2}, + Message: [GreaterThan] on 'NoValue': it needs a value, or the name of another member in Member, + Category: LaunchPad.Validation + }, + { + Id: LPAD3105, + Title: The rule's argument is not valid, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (34,5)-(34,39), + MessageFormat: [{0}] on '{1}': {2}, + Message: [LessThan] on 'NoSuchMember': 'Mistakes' has no other member 'Missing' to compare it with, + Category: LaunchPad.Validation + }, + { + Id: LPAD3105, + Title: The rule's argument is not valid, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (37,5)-(37,26), + MessageFormat: [{0}] on '{1}': {2}, + Message: [Must] on 'NoSuchMethod': 'Mistakes' has no method 'Missing' that takes the member's value and returns bool, + Category: LaunchPad.Validation + }, + { + Id: LPAD3105, + Title: The rule's argument is not valid, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (40,5)-(40,31), + MessageFormat: [{0}] on '{1}': {2}, + Message: [Must] on 'Asynchronous': 'IsFree' is asynchronous, which an attribute can't declare yet: declare the rule with MustAsync in a Validate function, + Category: LaunchPad.Validation + }, + { + Id: LPAD3102, + Title: The generated validator can't reach it, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (43,5)-(43,34), + MessageFormat: {0} must be public or internal for its rules to be checked: the generated validator is a class of its own, + Message: 'IsPrivate' must be public or internal for its rules to be checked: the generated validator is a class of its own, + Category: LaunchPad.Validation + }, + { + Id: LPAD3106, + Title: The member can't be validated with a validator, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (46,5)-(46,25), + MessageFormat: '{0}' is marked for nested validation, but {1}, + Message: 'NotNested' is marked for nested validation, but its type, int, is not one a validator is written for, + Category: LaunchPad.Validation + }, + { + Id: LPAD3104, + Title: The attribute is not compiled into the validator, + Severity: Warning, + WarningLevel: 1, + Location: Input0.cs: (49,12)-(49,22), + MessageFormat: [{0}] on '{1}' is not checked by the generated validator: {2}, + Message: [CreditCard] on 'Phone' is not checked by the generated validator: use a LaunchPad rule attribute, or [Must] with a method of the type, + Category: LaunchPad.Validation + }, + { + Id: LPAD3104, + Title: The attribute is not compiled into the validator, + Severity: Warning, + WarningLevel: 1, + Location: Input0.cs: (49,5)-(49,10), + MessageFormat: [{0}] on '{1}' is not checked by the generated validator: {2}, + Message: [Phone] on 'Phone' is not checked by the generated validator: use a LaunchPad rule attribute, or [Must] with a method of the type, + Category: LaunchPad.Validation + }, + { + Id: LPAD3101, + Title: A generic type can't be validated yet, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (5,20)-(5,27), + MessageFormat: '{0}' has rules, but it is generic or inside a generic type, which the generator doesn't write a validator for yet, + Message: 'Generic' has rules, but it is generic or inside a generic type, which the generator doesn't write a validator for yet, + Category: LaunchPad.Validation + }, + { + Id: LPAD3104, + Title: The attribute is not compiled into the validator, + Severity: Warning, + WarningLevel: 1, + Location: Input0.cs: (52,5)-(52,56), + MessageFormat: [{0}] on '{1}' is not checked by the generated validator: {2}, + Message: [Range] on 'Reflected' is not checked by the generated validator: a range of a type and two strings is converted through reflection; use [InclusiveBetween], which parses its strings at build time, + Category: LaunchPad.Validation + } + ] + } +} \ No newline at end of file diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.Crew.Validator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.Crew.Validator.g.verified.cs new file mode 100644 index 00000000000..0b6d143928c --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.Crew.Validator.g.verified.cs @@ -0,0 +1,44 @@ +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.Crew.Validator.g.cs +// +#nullable enable + +namespace Sample +{ + /// + /// Validates a : the rules its members carry as attributes. + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Crew))] + public sealed partial class CrewValidator + : global::Rocket.Surgery.LaunchPad.Validation.IValidate + { + private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; + + /// + /// Creates the validator. + /// + /// What replaces the rules' messages, if anything does. + public CrewValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; + + /// + public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Crew value) + { + global::System.ArgumentNullException.ThrowIfNull(value); + var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); + EnsureCaptain(value.Captain, ref sink); + return sink.ToResult(); + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Captain", "NotEmpty")] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void EnsureCaptain(string value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.NotEmpty(value)) + { + sink.Add("Captain", "NotEmpty", "{Name} must not be empty", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Captain"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value)); + } + } + } +} diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.Launcher.Validator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.Launcher.Validator.g.verified.cs new file mode 100644 index 00000000000..d93de18acb5 --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.Launcher.Validator.g.verified.cs @@ -0,0 +1,148 @@ +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.Launcher.Validator.g.cs +// +#nullable enable + +namespace Sample +{ + /// + /// Validates a : the rules its members carry as attributes. + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Launcher))] + public sealed partial class LauncherValidator + : global::Rocket.Surgery.LaunchPad.Validation.IValidate + { + 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::Sample.StrictCrew? _reserveValidator; + + /// + /// Creates the validator. + /// + /// What replaces the rules' messages, if anything does. + /// Where the validators of the members validated with their own are found. + public LauncherValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null, global::System.IServiceProvider? services = null) + { + _messages = messages; + _services = services; + } + + /// + public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Launcher value) + { + global::System.ArgumentNullException.ThrowIfNull(value); + var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); + + if (value.Crew is { } crew) + { + var path = sink.Enter("Crew"); + sink.Add(CrewValidator.Validate(crew)); + sink.Leave(path); + } + + EnsureBooster(value.Booster, ref sink); + + if (value.Booster is { } booster) + { + var path = sink.Enter("Booster"); + sink.Add(BoosterValidator.Validate(booster)); + sink.Leave(path); + } + + + { + var core = value.Core; + var path = sink.Enter("Core"); + sink.Add(BoosterValidator.Validate(core)); + sink.Leave(path); + } + + EnsureStages(value.Stages, ref sink); + + if (value.Stages is { } stages) + { + var path = sink.Enter("Stages"); + var index = 0; + foreach (var item in stages) + { + var itemPath = sink.Enter(index); + sink.Add(BoosterValidator.Validate(item)); + sink.Leave(itemPath); + + index++; + } + + sink.Leave(path); + } + + + if (value.Backups is { } backups) + { + var path = sink.Enter("Backups"); + var index = 0; + foreach (var item in backups) + { + if (item is { } present) + { + var itemPath = sink.Enter(index); + sink.Add(CrewValidator.Validate(present)); + sink.Leave(itemPath); + } + + index++; + } + + sink.Leave(path); + } + + + if (value.Reserve is { } reserve) + { + var path = sink.Enter("Reserve"); + sink.Add(ReserveValidator.Validate(reserve)); + sink.Leave(path); + } + + return sink.ToResult(); + } + + 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("LauncherValidator needs a Rocket.Surgery.LaunchPad.Validation.IValidate, 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("LauncherValidator needs a Rocket.Surgery.LaunchPad.Validation.IValidate, 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("LauncherValidator needs a Sample.StrictCrew, which the service provider it was given does not have."); + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Booster", "NotNull")] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void EnsureBooster(global::Sample.Stage? value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.NotNull(value)) + { + sink.Add("Booster", "NotNull", "{Name} is required", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Booster"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value)); + } + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Stages", "NotEmpty")] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void EnsureStages(global::System.Collections.Generic.IReadOnlyList? value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.NotEmpty(value)) + { + sink.Add("Stages", "NotEmpty", "{Name} must not be empty", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Stages"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value)); + } + } + } +} diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.Stage.Validator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.Stage.Validator.g.verified.cs new file mode 100644 index 00000000000..753293e0a36 --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.Stage.Validator.g.verified.cs @@ -0,0 +1,43 @@ +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.Stage.Validator.g.cs +// +#nullable enable + +namespace Sample +{ + /// + /// Validates a : the rules its members carry as attributes. + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Stage))] + public sealed partial class StageValidator + : global::Rocket.Surgery.LaunchPad.Validation.IValidate + { + private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; + + /// + /// Creates the validator. + /// + /// What replaces the rules' messages, if anything does. + public StageValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; + + /// + public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Stage value) + { + var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); + EnsureThrust(value.Thrust, ref sink); + return sink.ToResult(); + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Thrust", "GreaterThan(0)")] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void EnsureThrust(double value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.GreaterThan(value, (double)(0))) + { + sink.Add("Thrust", "GreaterThan", "{Name} must be greater than {Other}", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Thrust"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Other", (double)(0))); + } + } + } +} diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators.verified.txt b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators.verified.txt new file mode 100644 index 00000000000..b814e7ed8ef --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators.verified.txt @@ -0,0 +1,6 @@ +{ + FinalDiagnostics: [], + GeneratorDiagnostics: { + Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator: [] + } +} \ No newline at end of file diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Write_A_Validator_For_Rule_Attributes#Sample.Launcher.Validator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Write_A_Validator_For_Rule_Attributes#Sample.Launcher.Validator.g.verified.cs new file mode 100644 index 00000000000..eb2e77f5904 --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Write_A_Validator_For_Rule_Attributes#Sample.Launcher.Validator.g.verified.cs @@ -0,0 +1,175 @@ +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.Launcher.Validator.g.cs +// +#nullable enable + +namespace Sample +{ + /// + /// Validates a : the rules its members carry as attributes. + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Launcher))] + public sealed partial class LauncherValidator + : global::Rocket.Surgery.LaunchPad.Validation.IValidate + { + private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; + + private static readonly global::System.Text.RegularExpressions.Regex NamePattern = + new("^[A-Z]", (global::System.Text.RegularExpressions.RegexOptions)1 | global::System.Text.RegularExpressions.RegexOptions.CultureInvariant, global::System.TimeSpan.FromSeconds(2)); + + /// + /// Creates the validator. + /// + /// What replaces the rules' messages, if anything does. + public LauncherValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; + + /// + public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Launcher value) + { + global::System.ArgumentNullException.ThrowIfNull(value); + var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); + EnsureName(value.Name, ref sink); + EnsureFuel(value.Fuel, ref sink); + EnsureEngines(value.Engines, ref sink); + EnsurePrice(value.Price, ref sink); + EnsureBuilt(value.Built, ref sink); + EnsureLaunched(value.Launched, value.Built, ref sink); + EnsureFins(value.Fins, ref sink); + EnsureNickname(value, value.Nickname, ref sink); + return sink.ToResult(); + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Name", "NotEmpty", "MinLength(3)", "MaxLength(30)", "Matches(\"^[A-Z]\")")] + [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)); + } + + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.MinLength(value, 3)) + { + sink.Add("Name", "MinLength", "{Name} must be at least {Min} characters long", 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), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Min", 3)); + } + + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.MaxLength(value, 30)) + { + sink.Add("Name", "TooLong", "{Name} is too long", 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), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Max", 30)); + } + + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.Matches(value, NamePattern)) + { + sink.Add("Name", "Matches", "{Name} is not in the expected format", 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("Fuel", "IsInEnum")] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void EnsureFuel(global::Sample.Fuel value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.IsInEnum(value)) + { + sink.Add("Fuel", "IsInEnum", "{Name} has a value that is not allowed", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Fuel"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value)); + } + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Engines", "InclusiveBetween(1, 33)", "NotEqual(13)")] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void EnsureEngines(int value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.InclusiveBetween(value, (int)(1), (int)(33))) + { + sink.Add("Engines", "InclusiveBetween", "{Name} must be between {Min} and {Max}", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Engines"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Min", (int)(1)), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Max", (int)(33))); + } + + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.NotEqual(value, (int)(13))) + { + sink.Add("Engines", "NotEqual", "{Name} must not be equal to {Other}", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Warning, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Engines"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Other", (int)(13))); + } + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Price", "GreaterThanOrEqualTo(0)", "PrecisionScale(8, 2)")] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void EnsurePrice(decimal? value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.GreaterThanOrEqualTo(value, (decimal)(0))) + { + sink.Add("Price", "GreaterThanOrEqualTo", "{Name} must be greater than or equal to {Other}", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Price"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Other", (decimal)(0))); + } + + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.PrecisionScale(value, 8, 2)) + { + sink.Add("Price", "PrecisionScale", "{Name} must have at most {Precision} digits, {Scale} of them decimals", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Price"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Precision", 8), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Scale", 2)); + } + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Built", "NotDefault", "GreaterThan(\"2000-01-01\")")] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void EnsureBuilt(global::System.DateOnly value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.NotDefault(value)) + { + sink.Add("Built", "NotDefault", "{Name} must be set", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Built"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value)); + } + + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.GreaterThan(value, global::System.DateOnly.Parse("2000-01-01", global::System.Globalization.CultureInfo.InvariantCulture))) + { + sink.Add("Built", "GreaterThan", "{Name} must be greater than {Other}", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Built"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Other", global::System.DateOnly.Parse("2000-01-01", global::System.Globalization.CultureInfo.InvariantCulture))); + } + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Launched", "GreaterThanOrEqualTo(Built)", Reads = new[] { "Built" })] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void EnsureLaunched(global::System.DateOnly? value, global::System.DateOnly otherBuilt, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.GreaterThanOrEqualTo(value, otherBuilt)) + { + sink.Add("Launched", "GreaterThanOrEqualTo", "{Name} must be greater than or equal to {Other}", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Launched"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Other", otherBuilt)); + } + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Fins", "Must(IsOdd)")] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void EnsureFins(int value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + { + if (!global::Sample.Launcher.IsOdd(value)) + { + sink.Add("Fins", "Must", "{Name} is not valid", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Fins"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value)); + } + } + + /// + /// The rules of . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Nickname", "Must(IsShort)", ReadsValue = true)] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void EnsureNickname(global::Sample.Launcher instance, string? value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink sink) + { + if (!instance.IsShort(value)) + { + sink.Add("Nickname", "Must", "{Name} is not valid", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Nickname"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", value)); + } + } + } +} diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Write_A_Validator_For_Rule_Attributes.verified.txt b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Write_A_Validator_For_Rule_Attributes.verified.txt new file mode 100644 index 00000000000..b814e7ed8ef --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Write_A_Validator_For_Rule_Attributes.verified.txt @@ -0,0 +1,6 @@ +{ + FinalDiagnostics: [], + GeneratorDiagnostics: { + Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator: [] + } +} \ No newline at end of file diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Write_Nothing_For_A_Type_With_No_Rules.verified.txt b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Write_Nothing_For_A_Type_With_No_Rules.verified.txt new file mode 100644 index 00000000000..b814e7ed8ef --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Write_Nothing_For_A_Type_With_No_Rules.verified.txt @@ -0,0 +1,6 @@ +{ + FinalDiagnostics: [], + GeneratorDiagnostics: { + Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator: [] + } +} \ No newline at end of file diff --git a/test/Validation.Tests/BuilderTests.cs b/test/Validation.Tests/BuilderTests.cs new file mode 100644 index 00000000000..16fed3a5b6a --- /dev/null +++ b/test/Validation.Tests/BuilderTests.cs @@ -0,0 +1,62 @@ +using Rocket.Surgery.LaunchPad.Validation; +using Rocket.Surgery.LaunchPad.Validation.Rules; + +namespace Validation.Tests; + +/// +/// The builder is only ever read by the generator, so what there is to prove here is that the rules a validator declares compile against +/// the member types they are meant for. +/// +public class BuilderTests +{ + private enum Kind + { + Cargo, + Crewed, + } + + private sealed record Stage(double Thrust, string? Name); + + private sealed record Rocket( + string Name, + string? Nickname, + Kind Kind, + Kind? Backup, + int Engines, + int? Seats, + decimal Price, + DateOnly Built, + DateOnly? Launched, + IReadOnlyList Stages, + string[] Tags, + Stage? Booster + ); + + private static void Validate(IValidationBuilder v, TimeProvider time) + { + v.Ensure(x => x.Name).NotEmpty().MinLength(3).MaxLength(30).Matches("^[A-Z]").WithMessage("{Name} must start with a capital").WithCode("Capital"); + v.Ensure(x => x.Nickname).Length(1, 10).NotEqual(x => x.Name).WithSeverity(ValidationSeverity.Warning); + v.Ensure(x => x.Kind).IsInEnum(); + v.Ensure(x => x.Backup).IsInEnum().NotEqual(x => x.Kind); + v.Ensure(x => x.Engines).GreaterThan(0).LessThanOrEqualTo(33).StopOnFailure(); + v.Ensure(x => x.Seats).NotNull().InclusiveBetween(1, 7).When(x => x.Kind == Kind.Crewed); + v.Ensure(x => x.Price).PrecisionScale(12, 2).GreaterThanOrEqualTo(0m); + v.Ensure(x => x.Built).NotDefault().LessThan(_ => DateOnly.FromDateTime(time.GetUtcNow().UtcDateTime)); + v.Ensure(x => x.Launched).GreaterThanOrEqualTo(x => x.Built).Unless(x => x.Launched is null); + v.Ensure(x => x.Stages).NotEmpty().MaxLength(4); + v.EnsureEach(x => x.Stages, stage => stage.Ensure(x => x.Thrust).ExclusiveBetween(0, 10_000)); + v.EnsureEach(x => x.Tags).NotEmpty().MaxLength(20); + v.Ensure(x => x.Booster).ValidateNested().WithName("First stage"); + v.Ensure(x => x).Must(x => x.Engines >= x.Stages.Count).MustAsync((_, _) => ValueTask.FromResult(true)); + v.When(x => x.Kind == Kind.Cargo, cargo => cargo.Ensure(x => x.Seats).Null()); + v.Unless(x => x.Kind == Kind.Cargo, crewed => crewed.Ensure(x => x.Name).Must((rocket, name) => name != rocket.Nickname)); + } + + [Test] + public async Task Should_Declare_Rules_For_Every_Kind_Of_Member() + { + Action, TimeProvider> validate = Validate; + + await validate.Should().NotBeNull(); + } +} diff --git a/test/Validation.Tests/GeneratedValidatorTests.cs b/test/Validation.Tests/GeneratedValidatorTests.cs new file mode 100644 index 00000000000..bcc183f06f2 --- /dev/null +++ b/test/Validation.Tests/GeneratedValidatorTests.cs @@ -0,0 +1,176 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; + +using Rocket.Surgery.LaunchPad.Validation; + +using Validation.Tests.Types; + +namespace Validation.Tests; + +public class GeneratedValidatorTests +{ + private static ServiceProvider Services(Action? configure = null) + { + var services = new ServiceCollection().AddValidationTestsValidators(); + configure?.Invoke(services); + return services.BuildServiceProvider(); + } + + private static string[] Codes(T value) + { + using var services = Services(); + return [.. services.GetRequiredService>().Validate(value).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()); + } + + [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, }) + .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"]); + } + + [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"]); + } + + [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"]); + } + + [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()); + } + + [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, }); + + await result.IsValid.Should().BeFalse(); + await result.Failures.Length.Should().BeEqualTo(2); + await result.Failures[0].Code.Should().BeEqualTo("TooLong"); + await result.Failures[0].Message.Should().BeEqualTo("Name is longer than 10: Falcon Heavy"); + 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, }); + + await warning.IsValid.Should().BeTrue(); + await warning.Failures.Length.Should().BeEqualTo(1); + } + + [Test] + 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"]); + } + + [Test] + public async Task Should_Compile_The_DataAnnotations_Attributes() + { + var account = new Account + { + UserName = "a", + Notes = null, + Email = "nope", + Site = "nope", + Age = 17, + Share = 0, + Pin = "12345", + Roles = [], + }; + + await Codes(account) + .Should() + .BeEquivalentTo( + [ + "UserName:Length", "Notes:NotNull", "Email:EmailAddress", "Site:Url", "Age:InclusiveBetween", "Share:GreaterThan", "Pin:Matches", + "Roles:MinLength", + ] + ); + await Codes(new Account { UserName = " ", Share = 1, Pin = "1234", Roles = ["a", "b", "c", "d"], }) + .Should() + .BeEquivalentTo(["UserName:NotEmpty", "UserName:Length", "Roles:MaxLength"]); + } + + [Test] + public async Task Should_Fill_A_DataAnnotations_Message_By_Position() + { + using var services = Services(); + var result = services.GetRequiredService>().Validate(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() + { + using var services = Services(); + var sync = services.GetRequiredService>(); + var async = services.GetRequiredService>(); + + await async.Should().BeSameReferenceAs(sync); + await ( await async.ValidateAsync(new() { Name = "", }) ).IsInvalid.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 = "", }); + + await result.Failures[0].Message.Should().BeEqualTo("Name MUST NOT BE EMPTY"); + } + + [Test] + public async Task Should_Validate_Options() + { + using var services = Services(z => z.AddOptions().Configure(o => o.Attempts = 11)); + + var exception = await Assert.That(() => services.GetRequiredService>().Value).Throws(); + + await exception!.Failures.Should().BeEquivalentTo(["Attempts: Attempts must be between 1 and 10", "Endpoint: Endpoint must not be empty"]); + } + + [Test] + public async Task Should_Not_Accept_Null() => + await Assert.That(() => new LauncherValidator().Validate(null!)).Throws(); + + [Test] + public async Task Should_Say_Which_Validator_Is_Missing() + { + var exception = await Assert.That(() => new LauncherValidator().Validate(new() { Crew = new("Ada"), })).Throws(); + + await exception!.Message.Should().Contain("IValidate"); + } + + private sealed class Shouting : IValidationMessageProvider + { + public string? GetTemplate(string code, string defaultTemplate) => defaultTemplate.Replace("{Name}", "{NAME}").ToUpperInvariant().Replace("{NAME}", "{Name}"); + } +} diff --git a/test/Validation.Tests/RuleTests.cs b/test/Validation.Tests/RuleTests.cs new file mode 100644 index 00000000000..ca58ff30b10 --- /dev/null +++ b/test/Validation.Tests/RuleTests.cs @@ -0,0 +1,166 @@ +using System.Collections.Immutable; +using System.Text.RegularExpressions; + +using Rocket.Surgery.LaunchPad.Validation.Rules; + +namespace Validation.Tests; + +public partial class RuleTests +{ + private enum Fuel + { + Kerosene = 1, + Methane = 2, + } + + [GeneratedRegex("^[A-Z]{2}-[0-9]+$")] + private static partial Regex SerialNumber { get; } + + [Test] + public async Task Should_Leave_Null_To_NotNull() + { + await Rule.NotNull(null).Should().BeFalse(); + await Rule.NotNull("a").Should().BeTrue(); + await Rule.Null(null).Should().BeTrue(); + await Rule.Null(1).Should().BeFalse(); + + await Rule.MinLength(null, 3).Should().BeTrue(); + await Rule.MaxLength((int[]?)null, 3).Should().BeTrue(); + await Rule.GreaterThan(null, 3).Should().BeTrue(); + await Rule.GreaterThan(null, "a").Should().BeTrue(); + await Rule.Matches(null, SerialNumber).Should().BeTrue(); + await Rule.EmailAddress(null).Should().BeTrue(); + await Rule.Url(null).Should().BeTrue(); + await Rule.IsInEnum((Fuel?)null).Should().BeTrue(); + await Rule.PrecisionScale(null, 4, 2).Should().BeTrue(); + } + + [Test] + public async Task Should_Know_What_Is_Empty() + { + await Rule.NotEmpty(null).Should().BeFalse(); + await Rule.NotEmpty(" ").Should().BeFalse(); + await Rule.NotEmpty("a").Should().BeTrue(); + await Rule.NotEmpty(Guid.Empty).Should().BeFalse(); + await Rule.NotEmpty(Guid.NewGuid()).Should().BeTrue(); + await Rule.NotEmpty(0).Should().BeFalse(); + await Rule.NotEmpty((int?)null).Should().BeFalse(); + await Rule.NotEmpty(Array.Empty()).Should().BeFalse(); + await Rule.NotEmpty(new List { 1, }).Should().BeTrue(); + await Rule.NotEmpty(default(ImmutableArray)).Should().BeFalse(); + await Rule.NotEmpty(ImmutableArray.Create(1)).Should().BeTrue(); + await Rule.NotEmpty(Enumerable.Range(0, 0)).Should().BeFalse(); + await Rule.NotEmpty((object)" ").Should().BeFalse(); + + await Rule.Empty("").Should().BeTrue(); + await Rule.Empty("a").Should().BeFalse(); + await Rule.Empty(Array.Empty()).Should().BeTrue(); + + await Rule.NotDefault(Guid.Empty).Should().BeFalse(); + await Rule.NotDefault(default(DateOnly)).Should().BeFalse(); + await Rule.NotDefault(new DateOnly(2026, 1, 1)).Should().BeTrue(); + } + + [Test] + public async Task Should_Measure_Strings_And_Collections() + { + await Rule.MinLength("ab", 3).Should().BeFalse(); + await Rule.MinLength("abc", 3).Should().BeTrue(); + await Rule.MaxLength("abcd", 3).Should().BeFalse(); + await Rule.MaxLength("abc", 3).Should().BeTrue(); + await Rule.Length("ab", 3, 5).Should().BeFalse(); + await Rule.Length("abcdef", 3, 5).Should().BeFalse(); + await Rule.Length("abcd", 3, 5).Should().BeTrue(); + + await Rule.MinLength(new List { 1, 2, }, 3).Should().BeFalse(); + await Rule.MaxLength(new List { 1, 2, 3, 4, }, 3).Should().BeFalse(); + await Rule.MaxLength(ImmutableArray.Create(1, 2, 3), 3).Should().BeTrue(); + await Rule.Length(Enumerable.Range(0, 4), 3, 5).Should().BeTrue(); + await Rule.Length(Enumerable.Range(0, 6), 3, 5).Should().BeFalse(); + } + + [Test] + public async Task Should_Not_Enumerate_Past_The_Bound() + { + await Rule.MaxLength(Forever(), 3).Should().BeFalse(); + await Rule.MinLength(Forever(), 3).Should().BeTrue(); + + static IEnumerable Forever() + { + while (true) + { + yield return 1; + } + } + } + + [Test] + public async Task Should_Compare() + { + await Rule.Equal(1, 1).Should().BeTrue(); + await Rule.Equal("a", "b").Should().BeFalse(); + await Rule.NotEqual(1, 1).Should().BeFalse(); + + await Rule.GreaterThan(2, 1).Should().BeTrue(); + await Rule.GreaterThan(1, 1).Should().BeFalse(); + await Rule.GreaterThan((int?)1, 1).Should().BeFalse(); + await Rule.GreaterThanOrEqualTo(1, 1).Should().BeTrue(); + await Rule.GreaterThanOrEqualTo((decimal?)0.5m, 1m).Should().BeFalse(); + await Rule.LessThan(1, 1).Should().BeFalse(); + await Rule.LessThan(new DateOnly(2026, 1, 1), new DateOnly(2026, 1, 2)).Should().BeTrue(); + await Rule.LessThanOrEqualTo("b", "a").Should().BeFalse(); + await Rule.LessThanOrEqualTo((long?)1, 1).Should().BeTrue(); + + await Rule.InclusiveBetween(1, 1, 5).Should().BeTrue(); + await Rule.InclusiveBetween(5, 1, 5).Should().BeTrue(); + await Rule.InclusiveBetween((int?)6, 1, 5).Should().BeFalse(); + await Rule.ExclusiveBetween(1, 1, 5).Should().BeFalse(); + await Rule.ExclusiveBetween(3, 1, 5).Should().BeTrue(); + await Rule.ExclusiveBetween((int?)5, 1, 5).Should().BeFalse(); + } + + [Test] + [Arguments("ada@example.com", true)] + [Arguments("ada", false)] + [Arguments("@example.com", false)] + [Arguments("ada@", false)] + [Arguments("ada@@example.com", false)] + [Arguments("ada lovelace@example.com", false)] + public async Task Should_Recognise_An_Email_Address(string value, bool valid) => await Rule.EmailAddress(value).Should().BeEqualTo(valid); + + [Test] + [Arguments("https://example.com/a?b=c", true)] + [Arguments("http://localhost:5000", true)] + [Arguments("ftp://example.com", false)] + [Arguments("/relative", false)] + [Arguments("example.com", false)] + public async Task Should_Recognise_A_Url(string value, bool valid) => await Rule.Url(value).Should().BeEqualTo(valid); + + [Test] + public async Task Should_Match_A_Pattern() + { + await Rule.Matches("AB-123", SerialNumber).Should().BeTrue(); + await Rule.Matches("ab-123", SerialNumber).Should().BeFalse(); + } + + [Test] + public async Task Should_Know_The_Values_Of_An_Enumeration() + { + await Rule.IsInEnum(Fuel.Methane).Should().BeTrue(); + await Rule.IsInEnum((Fuel)7).Should().BeFalse(); + await Rule.IsInEnum((Fuel?)0).Should().BeFalse(); + } + + [Test] + [Arguments("12.34", 4, 2, true)] + [Arguments("123.4", 4, 2, false)] + [Arguments("1.234", 4, 2, false)] + [Arguments("0.12", 2, 2, true)] + [Arguments("-99.99", 4, 2, true)] + [Arguments("100", 4, 2, false)] + [Arguments("0", 4, 2, true)] + [Arguments("79228162514264337593543950335", 29, 0, true)] + [Arguments("79228162514264337593543950335", 28, 0, false)] + public async Task Should_Check_Precision_And_Scale(string value, int precision, int scale, bool valid) => + await Rule.PrecisionScale(decimal.Parse(value, System.Globalization.CultureInfo.InvariantCulture), precision, scale).Should().BeEqualTo(valid); +} diff --git a/test/Validation.Tests/Types/Models.cs b/test/Validation.Tests/Types/Models.cs new file mode 100644 index 00000000000..42f1db5169f --- /dev/null +++ b/test/Validation.Tests/Types/Models.cs @@ -0,0 +1,113 @@ +using System.Collections.Immutable; + +using Rocket.Surgery.LaunchPad.Validation; +using Rocket.Surgery.LaunchPad.Validation.Rules; + +using DataAnnotations = System.ComponentModel.DataAnnotations; + +namespace Validation.Tests.Types; + +public enum LauncherKind +{ + Cargo = 1, + Crewed = 2, +} + +/// A type validated by LaunchPad's rule attributes: every shape of rule an attribute declares. +public sealed record Launcher +{ + [NotEmpty] + [MinLength(3)] + [MaxLength(10, Message = "{Name} is longer than {Max}: {Value}", Code = "TooLong")] + [Matches("^[A-Z]")] + public string? Name { get; init; } = "Falcon"; + + [IsInEnum] + public LauncherKind Kind { get; init; } = LauncherKind.Cargo; + + [InclusiveBetween(1, 33)] + public int Engines { get; init; } = 9; + + [GreaterThanOrEqualTo(0)] + [PrecisionScale(8, 2)] + public decimal Price { get; init; } = 100m; + + [NotDefault] + [GreaterThanOrEqualTo("2000-01-01")] + public DateOnly Built { get; init; } = new(2020, 1, 1); + + [GreaterThanOrEqualTo(Member = nameof(Built))] + public DateOnly? Launched { get; init; } + + [ExclusiveBetween(0, 8, Severity = ValidationSeverity.Warning)] + public int? Seats { get; init; } + + [Must(nameof(IsOdd))] + public int Fins { get; init; } = 3; + + [Must(nameof(IsShort))] + public string? Nickname { get; init; } + + [MaxLength(2)] + public ImmutableArray Tags { get; init; } = []; + + [ValidateNested] + public Crew? Crew { get; init; } + + [NotEmpty] + [ValidateNested] + public IReadOnlyList Stages { get; init; } = [new(1),]; + + public static bool IsOdd(int value) => value % 2 == 1; + + internal bool IsShort(string? value) => value is null || value.Length < ( Name?.Length ?? 0 ); +} + +public readonly record struct Stage([property: GreaterThan(0d)] double Thrust); + +public sealed record Crew([NotEmpty] string Captain, [property: ValidateNested] Crew? Backup = null); + +/// A type validated by the System.ComponentModel.DataAnnotations attributes the generator compiles. +public sealed class Account +{ + [DataAnnotations.Required] + [DataAnnotations.StringLength(20, MinimumLength = 3, ErrorMessage = "{0} must have {1} to {2} characters")] + public string? UserName { get; set; } = "ada"; + + [DataAnnotations.Required(AllowEmptyStrings = true)] + public string? Notes { get; set; } = ""; + + [DataAnnotations.EmailAddress] + public string? Email { get; set; } + + [DataAnnotations.Url] + public string? Site { get; set; } + + [DataAnnotations.Range(18, 120)] + public int Age { get; set; } = 30; + + [DataAnnotations.Range(0d, 1d, MinimumIsExclusive = true)] + public double Share { get; set; } = 0.5; + + [DataAnnotations.RegularExpression("[0-9]{4}")] + public string? Pin { get; set; } + + [DataAnnotations.MinLength(1)] + [DataAnnotations.MaxLength(3)] + public string[]? Roles { get; set; } + + public string? Password { get; set; } + + [DataAnnotations.Compare(nameof(Password))] + public string? Confirmation { get; set; } +} + +/// An options class: validated when the options are made. +internal sealed class RetryOptions +{ + [InclusiveBetween(1, 10)] + public int Attempts { get; set; } = 3; + + [NotEmpty] + public string? Endpoint { get; set; } +} diff --git a/test/Validation.Tests/Validation.Tests.csproj b/test/Validation.Tests/Validation.Tests.csproj new file mode 100644 index 00000000000..0eba831123a --- /dev/null +++ b/test/Validation.Tests/Validation.Tests.csproj @@ -0,0 +1,18 @@ + + + + $(LaunchPadTargetFrameworks) + false + + + + + + + + + diff --git a/test/Validation.Tests/ValidationSinkTests.cs b/test/Validation.Tests/ValidationSinkTests.cs new file mode 100644 index 00000000000..822b4fb130f --- /dev/null +++ b/test/Validation.Tests/ValidationSinkTests.cs @@ -0,0 +1,121 @@ +using System.Globalization; + +using Rocket.Surgery.LaunchPad.Validation; + +using ValidationResult = Rocket.Surgery.LaunchPad.Validation.ValidationResult; + +namespace Validation.Tests; + +public class ValidationSinkTests +{ + private static KeyValuePair Argument(string name, object? value) => new(name, value); + + [Test] + public async Task Should_Be_Valid_With_No_Failures() + { + var result = new ValidationSink().ToResult(); + + await result.IsValid.Should().BeTrue(); + await result.Failures.Length.Should().BeEqualTo(0); + await default(ValidationResult).Failures.Length.Should().BeEqualTo(0); + await ValidationResult.Valid.IsValid.Should().BeTrue(); + } + + [Test] + public async Task Should_Fill_In_The_Message() + { + var sink = new ValidationSink(); + sink.Add("Name", "MaxLength", "{Name} must be at most {Max} characters long", ValidationSeverity.Error, Argument("Name", "Name"), Argument("Max", 30)); + var failure = sink.ToResult().Failures[0]; + + await failure.Path.Should().BeEqualTo("Name"); + await failure.Code.Should().BeEqualTo("MaxLength"); + await failure.Message.Should().BeEqualTo("Name must be at most 30 characters long"); + await failure.Arguments[1].Value.Should().BeEqualTo(30); + } + + [Test] + public async Task Should_Put_Failures_Under_The_Member_And_Item_Entered() + { + var sink = new ValidationSink(); + var root = sink.Enter("Stages"); + var stages = sink.Enter(2); + sink.Add("Thrust", "GreaterThan", "{Name} must be greater than {Other}", ValidationSeverity.Error); + sink.Add("", "NotNull", "required", ValidationSeverity.Error); + sink.Leave(stages); + sink.Leave(root); + sink.Add("", "Must", "whole value", ValidationSeverity.Error); + + var paths = sink.ToResult().Failures.Select(z => z.Path).ToArray(); + + await paths.Should().BeEquivalentTo(["Stages[2].Thrust", "Stages[2]", ""]); + } + + [Test] + public async Task Should_Put_A_Nested_Result_Under_The_Current_Path() + { + var nested = new ValidationSink(); + nested.Add("Name", "NotEmpty", "{Name} must not be empty", ValidationSeverity.Error); + + var sink = new ValidationSink(); + var root = sink.Enter("Crew"); + sink.Add(nested.ToResult()); + sink.Leave(root); + + await sink.ToResult().Failures[0].Path.Should().BeEqualTo("Crew.Name"); + } + + [Test] + public async Task Should_Be_Invalid_Only_For_Errors() + { + var sink = new ValidationSink(); + sink.Add("Name", "Short", "short", ValidationSeverity.Warning); + sink.Add("Name", "Note", "note", ValidationSeverity.Info); + + await sink.HasErrors.Should().BeFalse(); + await sink.Count.Should().BeEqualTo(2); + await sink.ToResult().IsValid.Should().BeTrue(); + await sink.ToResult().Failures.Length.Should().BeEqualTo(2); + + sink.Add("Name", "NotEmpty", "empty", ValidationSeverity.Error); + + await sink.HasErrors.Should().BeTrue(); + await sink.ToResult().IsInvalid.Should().BeTrue(); + await sink.ToResult().Errors.Count().Should().BeEqualTo(1); + } + + [Test] + public async Task Should_Take_Its_Messages_From_The_Provider() + { + var sink = new ValidationSink(new Dutch()); + sink.Add("Name", "MaxLength", "{Name} must be at most {Max} characters long", ValidationSeverity.Error, Argument("Name", "Naam"), Argument("Max", 30)); + sink.Add("Name", "NotEmpty", "{Name} must not be empty", ValidationSeverity.Error, Argument("Name", "Naam")); + + var messages = sink.ToResult().Failures.Select(z => z.Message).ToArray(); + + await messages.Should().BeEquivalentTo(["Naam mag hooguit 30 tekens lang zijn", "Naam must not be empty"]); + } + + [Test] + public async Task Should_Format_Placeholders() + { + var culture = CultureInfo.CurrentCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; + try + { + await ValidationMessage.Format("no placeholders", []).Should().BeEqualTo("no placeholders"); + await ValidationMessage.Format("{Value:0.00} of {Max}", [Argument("Value", 1.5m), Argument("Max", 3)]).Should().BeEqualTo("1.50 of 3"); + await ValidationMessage.Format("{{literal}} {Value}", [Argument("Value", null)]).Should().BeEqualTo("{literal} "); + await ValidationMessage.Format("{Unknown} and {unclosed", []).Should().BeEqualTo("{Unknown} and {unclosed"); + } + finally + { + CultureInfo.CurrentCulture = culture; + } + } + + private sealed class Dutch : IValidationMessageProvider + { + public string? GetTemplate(string code, string defaultTemplate) => code == "MaxLength" ? "{Name} mag hooguit {Max} tekens lang zijn" : null; + } +} From 55452164898dede7b474f801d23eb755f459279a Mon Sep 17 00:00:00 2001 From: David Driscoll Date: Thu, 3 Dec 2026 17:56:11 -0500 Subject: [PATCH 2/8] Validation: function and class validators, and asynchronous rules The third part of LaunchPad's validation (#3377). - 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. Their bodies are read at build time and never run: each chain becomes part of a rule method written into the type that contains it, and each lambda a local function of that method. - The attributes, functions and classes of one type merge into its one validator, now named {Type}GeneratedValidator. - A rule that waits (MustAsync, or a member validated with the validator of such a type) makes the type's validator an IValidateAsync only. LPAD3002 is an error on IValidate of such a type, with a fix. - A validator that takes services or asks for nested validators is registered scoped. - The generated rule methods name the Validate they were read from, so a private one nobody calls is not removed as unused. - String rules keep the member's own nullability; IMemberRules is covariant in the member's type. - LPAD3107 to LPAD3111 for what the generator can't read in a body. Co-Authored-By: Claude Fable 5.2 --- AGENTS.md | 8 +- docs/design/validation.md | 12 +- .../AnalyzerReleases.Unshipped.md | 6 + src/Validation.Analyzers/Diagnostics.cs | 59 ++ .../Model/FunctionReader.cs | 795 ++++++++++++++++++ src/Validation.Analyzers/Model/Models.cs | 75 +- src/Validation.Analyzers/Model/RuleReader.cs | 73 +- .../Model/TargetReader.cs | 124 +++ .../SynchronousValidationAnalyzer.cs | 54 ++ .../SynchronousValidationCodeFix.cs | 164 ++++ .../ValidatorGenerator.cs | 441 ++++++++-- src/Validation/GeneratedValidatorAttribute.cs | 6 + src/Validation/IValidationBuilder.cs | 4 +- src/Validation/Rules/MemberRulesExtensions.cs | 40 +- .../FunctionValidatorGeneratorTests.cs | 201 +++++ .../SynchronousValidationAnalyzerTests.cs | 53 ++ .../Validation.Analyzers.Tests/TestBuilder.cs | 14 + ...Read#Bodies.ValidateLauncher.g.verified.cs | 40 + ...d#LauncherGeneratedValidator.g.verified.cs | 52 ++ ...ld_Report_What_It_Cannot_Read.verified.txt | 288 +++++++ ...at_Waits#LaunchPadValidators.g.verified.cs | 30 + ...le.BookingGeneratedValidator.g.verified.cs | 39 + ...ingValidator.ValidateBooking.g.verified.cs | 59 ++ ...e.ManifestGeneratedValidator.g.verified.cs | 84 ++ ...e.ScheduleGeneratedValidator.g.verified.cs | 52 ++ ....Scheduling.ValidateSchedule.g.verified.cs | 29 + ...Scheduling.ValidateSchedule1.g.verified.cs | 30 + ..._Class_With_A_Rule_That_Waits.verified.txt | 6 + ...Its_Type#LaunchPadValidators.g.verified.cs | 28 + ...alidateBuildLauncher_Request.g.verified.cs | 237 ++++++ ...er_RequestGeneratedValidator.g.verified.cs | 63 ++ ...s_Of_A_Function_Into_Its_Type.verified.txt | 6 + ...And_Make_Its_Use_Asynchronous.verified.txt | 55 ++ ...s#AccountGeneratedValidator.g.verified.cs} | 9 +- ...ple.NamedGeneratedValidator.g.verified.cs} | 9 +- ...ter_InnerGeneratedValidator.g.verified.cs} | 9 +- ....PositionGeneratedValidator.g.verified.cs} | 9 +- ...ple.StageGeneratedValidator.g.verified.cs} | 9 +- ..._Options#LaunchPadValidators.g.verified.cs | 9 +- ...ple.DelayGeneratedValidator.g.verified.cs} | 9 +- ...ryOptionsGeneratedValidator.g.verified.cs} | 9 +- ...#MistakesGeneratedValidator.g.verified.cs} | 9 +- ...mple.CrewGeneratedValidator.g.verified.cs} | 9 +- ....LauncherGeneratedValidator.g.verified.cs} | 39 +- ...ple.StageGeneratedValidator.g.verified.cs} | 9 +- ....LauncherGeneratedValidator.g.verified.cs} | 9 +- test/Validation.Tests/BuilderTests.cs | 62 -- .../FunctionValidatorTests.cs | 131 +++ .../GeneratedValidatorTests.cs | 4 +- test/Validation.Tests/Types/Functions.cs | 100 +++ 50 files changed, 3390 insertions(+), 281 deletions(-) create mode 100644 src/Validation.Analyzers/Model/FunctionReader.cs create mode 100644 src/Validation.Analyzers/Model/TargetReader.cs create mode 100644 src/Validation.Analyzers/SynchronousValidationAnalyzer.cs create mode 100644 src/Validation.Analyzers/SynchronousValidationCodeFix.cs create mode 100644 test/Validation.Analyzers.Tests/FunctionValidatorGeneratorTests.cs create mode 100644 test/Validation.Analyzers.Tests/SynchronousValidationAnalyzerTests.cs create mode 100644 test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read#Bodies.ValidateLauncher.g.verified.cs create mode 100644 test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read#LauncherGeneratedValidator.g.verified.cs create mode 100644 test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read.verified.txt create mode 100644 test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#LaunchPadValidators.g.verified.cs create mode 100644 test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.BookingGeneratedValidator.g.verified.cs create mode 100644 test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.BookingValidator.ValidateBooking.g.verified.cs create mode 100644 test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.ManifestGeneratedValidator.g.verified.cs create mode 100644 test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.ScheduleGeneratedValidator.g.verified.cs create mode 100644 test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.Scheduling.ValidateSchedule.g.verified.cs create mode 100644 test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.Scheduling.ValidateSchedule1.g.verified.cs create mode 100644 test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits.verified.txt create mode 100644 test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type#LaunchPadValidators.g.verified.cs create mode 100644 test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type#Sample.Operations.BuildLauncher.ValidateBuildLauncher_Request.g.verified.cs create mode 100644 test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type#Sample.Operations.BuildLauncher_RequestGeneratedValidator.g.verified.cs create mode 100644 test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type.verified.txt create mode 100644 test/Validation.Analyzers.Tests/snapshots/SynchronousValidationAnalyzerTests.Should_Report_The_Synchronous_Validator_Of_An_Asynchronous_Type_And_Make_Its_Use_Asynchronous.verified.txt rename test/Validation.Analyzers.Tests/snapshots/{ValidatorGeneratorTests.Should_Compile_The_DataAnnotations_Attributes#Account.Validator.g.verified.cs => ValidatorGeneratorTests.Should_Compile_The_DataAnnotations_Attributes#AccountGeneratedValidator.g.verified.cs} (97%) rename test/Validation.Analyzers.Tests/snapshots/{ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Named.Validator.g.verified.cs => ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.NamedGeneratedValidator.g.verified.cs} (82%) rename test/Validation.Analyzers.Tests/snapshots/{ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Outer_Inner.Validator.g.verified.cs => ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Outer_InnerGeneratedValidator.g.verified.cs} (83%) rename test/Validation.Analyzers.Tests/snapshots/{ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Position.Validator.g.verified.cs => ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.PositionGeneratedValidator.g.verified.cs} (89%) rename test/Validation.Analyzers.Tests/snapshots/{ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Stage.Validator.g.verified.cs => ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.StageGeneratedValidator.g.verified.cs} (88%) rename test/Validation.Analyzers.Tests/snapshots/{ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.Delay.Validator.g.verified.cs => ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.DelayGeneratedValidator.g.verified.cs} (83%) rename test/Validation.Analyzers.Tests/snapshots/{ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.RetryOptions.Validator.g.verified.cs => ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.RetryOptionsGeneratedValidator.g.verified.cs} (87%) rename test/Validation.Analyzers.Tests/snapshots/{ValidatorGeneratorTests.Should_Report_What_It_Cannot_Write#Mistakes.Validator.g.verified.cs => ValidatorGeneratorTests.Should_Report_What_It_Cannot_Write#MistakesGeneratedValidator.g.verified.cs} (82%) rename test/Validation.Analyzers.Tests/snapshots/{ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.Crew.Validator.g.verified.cs => ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.CrewGeneratedValidator.g.verified.cs} (83%) rename test/Validation.Analyzers.Tests/snapshots/{ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.Launcher.Validator.g.verified.cs => ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.LauncherGeneratedValidator.g.verified.cs} (79%) rename test/Validation.Analyzers.Tests/snapshots/{ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.Stage.Validator.g.verified.cs => ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.StageGeneratedValidator.g.verified.cs} (83%) rename test/Validation.Analyzers.Tests/snapshots/{ValidatorGeneratorTests.Should_Write_A_Validator_For_Rule_Attributes#Sample.Launcher.Validator.g.verified.cs => ValidatorGeneratorTests.Should_Write_A_Validator_For_Rule_Attributes#Sample.LauncherGeneratedValidator.g.verified.cs} (96%) delete mode 100644 test/Validation.Tests/BuilderTests.cs create mode 100644 test/Validation.Tests/FunctionValidatorTests.cs create mode 100644 test/Validation.Tests/Types/Functions.cs diff --git a/AGENTS.md b/AGENTS.md index 622179ee696..a4c217d1e85 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,10 +34,12 @@ The conversion is done: no project references `Rocket.Surgery.Conventions` or th - `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). - 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}Validator` beside the type, an `IValidate` 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. + - `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 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, each validator of a class is an `IValidateOptions` too. - - Not written yet: function and class validators (the builder is not read), asynchronous rules, the rules of base classes, interfaces, `[InheritFrom]` and `[Mutable]`, and validators for generic types (LPAD3101). + - 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. + - Not written yet ([#3378](https://github.com/RocketSurgeonsGuild/LaunchPad/issues/3378)): rules declared for a base class, an interface or a type of another assembly (LPAD3110), `Include`, the rules `[InheritFrom]` and `[Mutable]` carry over, and validators for generic types (LPAD3101). - `test/Validation.Tests` runs the generator as an application does and proves what the validators do; `test/Validation.Analyzers.Tests` has the snapshots of what the generator writes and reports. - `src/Sdks/LaunchPad` is the **LaunchPad SDK** (`Rocket.Surgery.LaunchPad.Sdk`), an MSBuild SDK an application applies with an `` element in each project (`#:sdk` in a file-based app) or once in its `Directory.Build.props`. It chains `Joinery.Dovetail.Sdk` (the version `Directory.Packages.props` pins for it) and adds LaunchPad packages from what Dovetail's host detection finds and from the project's direct `PackageReference`s; `LaunchPadEnable=false` opts out. Every LaunchPad SDK also chains the **Chirograph** SDK (OpenAPI clients from `OpenApiClient` items) through `src/Sdks/LaunchPad/Sdk/Rocket.Surgery.LaunchPad.Chirograph.targets`, after the project body, unless the project applies Chirograph itself or sets `LaunchPadEnableChirograph=false`; the repository's own test projects apply `` directly, at the version `global.json` pins, which must equal the `Chirograph` `PackageVersion`. The versions are written into `Sdk/Packages.props` when the SDK is packed. `src/Sdks/Console` is the **console SDK** (`Rocket.Surgery.LaunchPad.Sdk.Console`): the same SDK for ConsoleAppFramework applications, chaining `Joinery.Dovetail.Sdk.Console`. `src/Sdks/{Web,Worker,Razor,BlazorWebAssembly,WebAssembly,WindowsDesktop}` are the **mirrors** (`Rocket.Surgery.LaunchPad.Sdk.Web`, ...): each is the Microsoft SDK of the same name with LaunchPad, chains Dovetail's mirror (`Joinery.Dovetail.Sdk.Web`, ...) and then applies `src/Sdks/Mirror/Rocket.Surgery.LaunchPad.Mirror.props`, which skips LaunchPad when a `Directory.Build.props` already applied it. Every SDK but `Rocket.Surgery.LaunchPad.Sdk` packs the shared files of `src/Sdks/LaunchPad/Sdk` beside its own `Sdk.props`/`Sdk.targets`; `src/Sdks/Directory.Build.props`/`.targets` hold the package settings and generate each `Sdk/Packages.props` from `LaunchPadChainedSdk`. `test/Sdk.Tests` packs it and builds throwaway applications against it, and `sample/Sample.Sdk` consumes it from packed packages (`dotnet msbuild build/pack.proj` there first). Like an application outside the repository, that sample and the throwaway projects of the tests stand outside central package management and name their own versions. - An operation that can fail responds with a **union response** instead of throwing ([`docs/design/union-types.md`](docs/design/union-types.md), [ADR-0005](docs/adr/0005-portable-unions-shaped-like-csharp-unions.md), [ADR-0010](docs/adr/0010-net11-only-and-native-unions.md), [ADR-0006](docs/adr/0006-union-responses-over-every-transport.md)); the generated servers answer each error case in their transport's error shape. Unions are native C# 15 unions (`public union Result(RocketModel, NotFound);`), or hand-written custom unions; LaunchPad has no union generator and no polyfill ([ADR-0010](docs/adr/0010-net11-only-and-native-unions.md)). The standard error cases (`Problem`, `NotFound` and the rest) are in Foundation. Generators detect a union by name (`UnionAttribute` or `IUnion`), take its cases from its public one-parameter constructors (implicitly declared ones included) and read it through `Value`. diff --git a/docs/design/validation.md b/docs/design/validation.md index 2c6815e30af..f758a56f2ad 100644 --- a/docs/design/validation.md +++ b/docs/design/validation.md @@ -1,6 +1,6 @@ # Spec: LaunchPad validation -Status: in progress, tracked by [#3374](https://github.com/RocketSurgeonsGuild/LaunchPad/issues/3374). The runtime package (`src/Validation`) exists, and the generator (`src/Validation.Analyzers`) writes validators from attribute rules; function and class validators, and everything under "What the manifest makes work", are not built yet. "As built" at the end lists where the code differs from this document. The decision is [ADR-0012](../adr/0012-launchpad-owns-validation.md). +Status: in progress, tracked by [#3374](https://github.com/RocketSurgeonsGuild/LaunchPad/issues/3374). The runtime package (`src/Validation`) exists, and the generator (`src/Validation.Analyzers`) writes validators from attribute rules, function validators and class validators; base classes, interfaces, `[InheritFrom]`, `[Mutable]`, composition across assemblies and the integrations are not built yet. "As built" at the end lists where the code differs from this document. The decision is [ADR-0012](../adr/0012-launchpad-owns-validation.md). ## Objective @@ -154,12 +154,20 @@ DataAnnotations: the attributes the generator knows (`[Required]`, `[StringLengt Where the code so far differs from the text above: +- **The generated validator** is `{Type}GeneratedValidator`, a class of its own beside the type: `{Type}Validator` is the name an application gives its class validator. +- **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`. +- **Rules can be declared** only for a class, struct or record of the same assembly so far (LPAD3110); `Include` is an error; `ValidateNested` in a chain can't be under a condition. +- **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. 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. - **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 until function validators arrive. +- **`[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. - **Generic types** with rules are an error (LPAD3101) for now. - **LPAD3001** looks only at types that have rules themselves: a type with no rules and a member whose type has them is not reported. diff --git a/src/Validation.Analyzers/AnalyzerReleases.Unshipped.md b/src/Validation.Analyzers/AnalyzerReleases.Unshipped.md index cba2892e3c5..6ebdf27db09 100644 --- a/src/Validation.Analyzers/AnalyzerReleases.Unshipped.md +++ b/src/Validation.Analyzers/AnalyzerReleases.Unshipped.md @@ -6,9 +6,15 @@ 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, 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 LPAD3104 | LaunchPad.Validation | Warning | ValidatorGenerator, a System.ComponentModel.DataAnnotations attribute the generator doesn't compile LPAD3105 | LaunchPad.Validation | Error | ValidatorGenerator, a rule's argument is not valid LPAD3106 | LaunchPad.Validation | Error | ValidatorGenerator, [ValidateNested] on a member whose type can't be validated +LPAD3107 | LaunchPad.Validation | Error | ValidatorGenerator, a statement in a Validate body that is not a call on the builder +LPAD3108 | LaunchPad.Validation | Error | ValidatorGenerator, a call on the builder the generator can't read +LPAD3109 | LaunchPad.Validation | Error | ValidatorGenerator, the type that contains a Validate function, or a class validator, is not partial +LPAD3110 | LaunchPad.Validation | Error | ValidatorGenerator, a Validate function for a type rules can't be declared for yet +LPAD3111 | LaunchPad.Validation | Error | ValidatorGenerator, an argument that must be a constant is not diff --git a/src/Validation.Analyzers/Diagnostics.cs b/src/Validation.Analyzers/Diagnostics.cs index 0443f1e896e..435c7ac379e 100644 --- a/src/Validation.Analyzers/Diagnostics.cs +++ b/src/Validation.Analyzers/Diagnostics.cs @@ -19,6 +19,15 @@ 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", @@ -73,6 +82,51 @@ internal static class Diagnostics true ); + public static readonly DiagnosticDescriptor StatementNotAllowed = new( + "LPAD3107", + "A Validate body may only call the builder", + "This is not a call on '{0}': a Validate body is read at build time and never runs, so it can only declare rules", + Category, + DiagnosticSeverity.Error, + true + ); + + public static readonly DiagnosticDescriptor CallNotUnderstood = new( + "LPAD3108", + "The generator can't read this rule", + "{0}", + Category, + DiagnosticSeverity.Error, + true + ); + + public static readonly DiagnosticDescriptor MustBePartial = new( + "LPAD3109", + "The type that declares rules must be partial", + "'{0}' must be partial, and public or internal, and not generic: the rules its Validate declares are written into it", + Category, + DiagnosticSeverity.Error, + true + ); + + public static readonly DiagnosticDescriptor TargetNotSupported = new( + "LPAD3110", + "Rules can't be declared for this type yet", + "Validate declares rules for '{0}', {1}", + Category, + DiagnosticSeverity.Error, + true + ); + + public static readonly DiagnosticDescriptor ConstantRequired = new( + "LPAD3111", + "The argument must be a constant", + "{0} takes a constant: the generator writes it into the validator", + Category, + DiagnosticSeverity.Error, + true + ); + public static DiagnosticDescriptor? Find(string id) => id switch { "LPAD3101" => GenericType, @@ -81,6 +135,11 @@ internal static class Diagnostics "LPAD3104" => UnsupportedDataAnnotation, "LPAD3105" => InvalidArgument, "LPAD3106" => NestedNotValidatable, + "LPAD3107" => StatementNotAllowed, + "LPAD3108" => CallNotUnderstood, + "LPAD3109" => MustBePartial, + "LPAD3110" => TargetNotSupported, + "LPAD3111" => ConstantRequired, _ => null, }; } diff --git a/src/Validation.Analyzers/Model/FunctionReader.cs b/src/Validation.Analyzers/Model/FunctionReader.cs new file mode 100644 index 00000000000..167e46c7eed --- /dev/null +++ b/src/Validation.Analyzers/Model/FunctionReader.cs @@ -0,0 +1,795 @@ +using System.Globalization; +using System.Text; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +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. +/// +/// +/// +/// The body is a list of calls on the builder. Each chain is about one member (or the whole value), and becomes part of that member's +/// rule method. The method is written into the type that contains the function, so what the lambdas name resolves as it does where +/// they are written: each lambda is copied as a local function, with its own parameters, and called with the value being validated. +/// +/// +/// The names the generated method uses start with two underscores, so they can't meet the names a lambda uses. +/// +/// +internal sealed class FunctionReader +{ + private const string Runtime = "global::" + ValidationSymbols.RuntimeNamespace; + private const string Sink = "__sink"; + + public static ContributorResult? Read(MethodDeclarationSyntax syntax, SemanticModel model) + { + // The declaration of IValidator.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 + || !ValidationSymbols.Is(builder.OriginalDefinition, ValidationSymbols.RuntimeNamespace, "IValidationBuilder")) + { + return null; + } + + var reader = new FunctionReader(syntax, model, method); + var result = reader.Read(targetType); + return new(result, reader._diagnostics.ToEquatableArray()); + } + + private readonly MethodDeclarationSyntax _syntax; + private readonly SemanticModel _model; + private readonly IMethodSymbol _method; + private readonly List _diagnostics = []; + private readonly List _members = []; + private readonly List _fields = []; + private string _prefix = ""; + private int _locals; + + private FunctionReader(MethodDeclarationSyntax syntax, SemanticModel model, IMethodSymbol method) + { + _syntax = syntax; + _model = model; + _method = method; + } + + // The rule method of one member, as it is written. + private sealed class MemberBuilder(string member, string type, string method) + { + public string Member { get; } = member; + public string Type { get; } = type; + public string Method { get; } = method; + public StringBuilder Body { get; } = new(); + public List Manifest { get; } = []; + public bool IsAsync { get; set; } + public bool ReadsValue { get; set; } + public NestedModel? Nested { get; set; } + public int Functions { get; set; } + } + + // A condition a group of rules is under: v.When(x => ..., v => { ... }). + private sealed record Condition(ExpressionSyntax Expression, bool Negate, string Instance); + + // Where a statement is read: the builder's name, the value its lambdas are about, and, inside EnsureEach, the method being written. + private sealed record Scope(string Builder, string Instance, ITypeSymbol Model, IReadOnlyList Conditions, MemberBuilder? Into, string Indent); + + // One rule of a chain, before the chain is written. + private sealed class RuleBuilder + { + public string Check { get; set; } = ""; + public bool IsAsync { get; set; } + public string Code { get; set; } = ""; + public string Message { get; set; } = ""; + public string Severity { get; set; } = "Error"; + public List<(string Name, string Expression)> Placeholders { get; } = []; + public List Conditions { get; } = []; + } + + private void Report(DiagnosticDescriptor descriptor, SyntaxNode? node, params string[] arguments) => + _diagnostics.Add(DiagnosticModel.Create(descriptor, node?.GetLocation(), arguments)); + + private void NotUnderstood(SyntaxNode node, string reason) => Report(Diagnostics.CallNotUnderstood, node, reason); + + private ContributorModel? Read(ITypeSymbol targetType) + { + var container = _method.ContainingType; + var isClass = !_method.IsStatic + && _method.Parameters.Length == 1 + && container.AllInterfaces.Any( + z => ValidationSymbols.Is(z.OriginalDefinition, ValidationSymbols.RuntimeNamespace, "IValidator") + && SymbolEqualityComparer.Default.Equals(z.TypeArguments[0], targetType) + ); + var location = _syntax.Identifier; + if (!isClass && !_method.IsStatic) + { + _diagnostics.Add( + 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" + ) + ); + return null; + } + + var containers = TargetReader.Containers(container); + var partial = containers.All( + static z => z.DeclaringSyntaxReferences.Any(static r => r.GetSyntax() is TypeDeclarationSyntax t && t.Modifiers.Any(SyntaxKind.PartialKeyword)) + ); + if (!partial || TargetReader.IsGeneric(container) || !TargetReader.IsReachable(container) || ( isClass && container.TypeKind != TypeKind.Class )) + { + _diagnostics.Add(DiagnosticModel.Create(Diagnostics.MustBePartial, location.GetLocation(), container.Name)); + return null; + } + + var targetName = targetType.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat); + if (targetType is not INamedTypeSymbol { TypeKind: TypeKind.Class or TypeKind.Struct } target) + { + _diagnostics.Add( + DiagnosticModel.Create(Diagnostics.TargetNotSupported, location.GetLocation(), targetName, "which is not a class, a struct or a record: the rules of interfaces are not written yet") + ); + return null; + } + + if (!SymbolEqualityComparer.Default.Equals(target.ContainingAssembly, _model.Compilation.Assembly)) + { + _diagnostics.Add( + DiagnosticModel.Create(Diagnostics.TargetNotSupported, location.GetLocation(), targetName, "which another assembly declares: rules for the types of other assemblies are not written yet") + ); + return null; + } + + if (TargetReader.IsGeneric(target)) + { + _diagnostics.Add(DiagnosticModel.Create(Diagnostics.GenericType, location.GetLocation(), targetName)); + return null; + } + + if (!TargetReader.IsReachable(target)) + { + _diagnostics.Add(DiagnosticModel.Create(Diagnostics.NotAccessible, location.GetLocation(), "'" + target.Name + "' and the types that contain it")); + return null; + } + + // Two Validate functions of one container for the same type: the second one's methods are numbered. + var siblings = container + .GetMembers("Validate") + .OfType() + .Where(z => z.Parameters.Length > 0 && SymbolEqualityComparer.Default.Equals(z.Parameters[0].Type, _method.Parameters[0].Type)) + .ToList(); + var ordinal = siblings.FindIndex(z => SymbolEqualityComparer.Default.Equals(z, _method)); + var targetIdentifier = string.Join("_", TargetReader.Containers(target).Select(static z => z.Name)); + _prefix = "Validate" + targetIdentifier + ( ordinal > 0 ? ordinal.ToString(CultureInfo.InvariantCulture) : "" ); + + var scope = new Scope(_method.Parameters[0].Name, "__instance", target, [], null, ""); + if (_syntax.ExpressionBody is { } expressionBody) + { + ReadStatement(expressionBody.Expression, scope); + } + else if (_syntax.Body is { } body) + { + ReadStatements(body.Statements, scope); + } + + if (_members.Count == 0) return null; + + var tree = _syntax.SyntaxTree; + var namespaces = _syntax.Ancestors().OfType().Reverse().ToList(); + var containerName = string.Join(".", containers.Select(static z => z.Name)); + var @namespace = TargetReader.NamespaceOf(container); + return new( + TargetReader.Read(target), + container.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), + isClass, + containers.All(static z => z.DeclaredAccessibility == Accessibility.Public), + ( @namespace.Length == 0 ? "" : @namespace + "." ) + containerName + "." + _prefix + ".g.cs", + tree.FilePath + ":" + _syntax.SpanStart.ToString("D10", CultureInfo.InvariantCulture), + ( (CompilationUnitSyntax)tree.GetRoot() ).Usings.Where(static z => z.GlobalKeyword.IsKind(SyntaxKind.None)).Select(static z => z.ToString()).ToEquatableArray(), + @namespace, + namespaces.SelectMany(static z => z.Usings).Select(static z => z.ToString()).ToEquatableArray(), + containers.Select(Declaration).ToEquatableArray(), + _method + .Parameters.Skip(1) + .Select( + static z => new DependencyModel( + z.Type.ToDisplayString(ValidationSymbols.Annotated), + z.Name, + z.Type is { Name: "CancellationToken", ContainingNamespace: { Name: "Threading", ContainingNamespace.Name: "System" } }, + TargetReader.IsPublic(z.Type) + ) + ) + .ToEquatableArray(), + _members + .Select( + static z => new ContributedMemberModel(z.Member, z.Type, z.Method, z.IsAsync, z.ReadsValue, z.Body.ToString(), z.Manifest.ToEquatableArray(), z.Nested) + ) + .ToEquatableArray(), + _fields.ToEquatableArray() + ); + } + + private static string Declaration(INamedTypeSymbol type) + { + var keyword = type switch + { + { IsRecord: true, TypeKind: TypeKind.Struct } => "record struct", + { IsRecord: true } => "record", + { TypeKind: TypeKind.Struct } => "struct", + { TypeKind: TypeKind.Interface } => "interface", + _ => "class", + }; + return "partial " + keyword + " " + type.Name; + } + + private void ReadStatements(IEnumerable statements, Scope scope) + { + foreach (var statement in statements) + { + if (statement is ExpressionStatementSyntax expression) + { + ReadStatement(expression.Expression, scope); + } + else + { + Report(Diagnostics.StatementNotAllowed, statement, scope.Builder); + } + } + } + + private void ReadStatement(ExpressionSyntax expression, Scope scope) + { + var calls = new List(); + var current = expression; + while (current is InvocationExpressionSyntax { Expression: MemberAccessExpressionSyntax access, } invocation) + { + calls.Insert(0, invocation); + current = access.Expression; + } + + if (calls.Count == 0 || current is not IdentifierNameSyntax root || root.Identifier.ValueText != scope.Builder) + { + Report(Diagnostics.StatementNotAllowed, expression, scope.Builder); + return; + } + + var first = calls[0]; + var name = NameOf(first); + var arguments = first.ArgumentList.Arguments; + switch (name) + { + case "Ensure" when arguments.Count == 1: + if (ReadSelector(arguments[0].Expression) is var (member, type)) ReadChain(member, type, [.. calls.Skip(1)], scope, false); + break; + case "EnsureEach" when arguments.Count == 1: + if (ReadSelector(arguments[0].Expression) is var (items, itemsType)) ReadChain(items, itemsType, [.. calls.Skip(1)], scope, true); + break; + case "EnsureEach" when arguments.Count == 2 && calls.Count == 1: + ReadEach(arguments[0].Expression, arguments[1].Expression, scope); + break; + case "When" or "Unless" when arguments.Count == 2 && calls.Count == 1: + if (arguments[1].Expression is not LambdaExpressionSyntax group || ParameterNames(group) is not [var groupBuilder]) + { + NotUnderstood(arguments[1].Expression, "The rules of " + name + " are declared in a lambda that takes the builder"); + break; + } + + var conditions = scope.Conditions.Append(new(arguments[0].Expression, name == "Unless", scope.Instance)).ToList(); + ReadBody(group, scope with { Builder = groupBuilder, Conditions = conditions, }); + break; + case "Include": + NotUnderstood(first, "Include is not written yet: it comes with the rules of base classes and of other types"); + break; + default: + NotUnderstood(first, "'" + name + "' is not something the builder declares rules with here"); + break; + } + } + + private void ReadBody(LambdaExpressionSyntax lambda, Scope scope) + { + if (lambda.Body is BlockSyntax block) + { + ReadStatements(block.Statements, scope); + } + else if (lambda.Body is ExpressionSyntax expression) + { + ReadStatement(expression, scope); + } + } + + private static string NameOf(InvocationExpressionSyntax invocation) => ( (MemberAccessExpressionSyntax)invocation.Expression ).Name.Identifier.ValueText; + + private static List? ParameterNames(LambdaExpressionSyntax lambda) => lambda switch + { + SimpleLambdaExpressionSyntax simple => [simple.Parameter.Identifier.ValueText], + ParenthesizedLambdaExpressionSyntax parenthesized => [.. parenthesized.ParameterList.Parameters.Select(static z => z.Identifier.ValueText)], + _ => null, + }; + + // x => x.Member, or x => x for the whole value. + private (string Member, ITypeSymbol Type)? ReadSelector(ExpressionSyntax expression) + { + if (expression is LambdaExpressionSyntax { Body: ExpressionSyntax body, } lambda && ParameterNames(lambda) is [var parameter]) + { + if (body is IdentifierNameSyntax self && self.Identifier.ValueText == parameter && _model.GetTypeInfo(self).Type is { } whole) return ("", whole); + if (body is MemberAccessExpressionSyntax { Expression: IdentifierNameSyntax of, } access && of.Identifier.ValueText == parameter) + { + switch (_model.GetSymbolInfo(access).Symbol) + { + case IPropertySymbol property: + return (property.Name, property.Type); + case IFieldSymbol field: + return (field.Name, field.Type); + default: + break; + } + } + } + + NotUnderstood(expression, "A rule is about one member, chosen with x => x.Member, or about the whole value, with x => x"); + return null; + } + + private MemberBuilder MemberFor(string member, ITypeSymbol type) + { + if (_members.FirstOrDefault(z => z.Member == member) is { } existing) return existing; + var builder = new MemberBuilder(member, type.ToDisplayString(ValidationSymbols.Annotated), member.Length == 0 ? _prefix : _prefix + "_" + member); + if (member.Length == 0) builder.ReadsValue = true; + _members.Add(builder); + return builder; + } + + // A lambda becomes a local function of the rule method, called with the arguments; anything else (a method, a delegate) is called as it is. + private string Invoke(MemberBuilder into, List functions, ExpressionSyntax expression, params string[] arguments) + { + if (arguments.Any(static z => z.StartsWith("__instance", StringComparison.Ordinal))) into.ReadsValue = true; + var list = string.Join(", ", arguments); + if (expression is not LambdaExpressionSyntax lambda || _model.GetSymbolInfo(lambda).Symbol is not IMethodSymbol symbol) + { + var text = expression.ToString(); + return ( expression is IdentifierNameSyntax or MemberAccessExpressionSyntax or GenericNameSyntax ? text : "(" + text + ")" ) + "(" + list + ")"; + } + + var name = "__rule" + into.Functions.ToString(CultureInfo.InvariantCulture); + into.Functions++; + var names = ParameterNames(lambda) ?? []; + var parameters = new List(); + for (var i = 0; i < symbol.Parameters.Length; i++) + { + var parameter = i < names.Count && names[i] != "_" ? names[i] : "__discard" + i.ToString(CultureInfo.InvariantCulture); + parameters.Add(symbol.Parameters[i].Type.ToDisplayString(ValidationSymbols.Annotated) + " " + parameter); + } + + var body = lambda.Body is BlockSyntax block ? "\n" + block : " => " + lambda.Body + ";"; + functions.Add( + ( lambda.AsyncKeyword.IsKind(SyntaxKind.AsyncKeyword) ? "async " : "" ) + + symbol.ReturnType.ToDisplayString(ValidationSymbols.Annotated) + + " " + + name + + "(" + + string.Join(", ", parameters) + + ")" + + body + ); + return name + "(" + list + ")"; + } + + private void ReadEach(ExpressionSyntax selector, ExpressionSyntax rules, Scope scope) + { + if (ReadSelector(selector) is not var (member, type)) return; + if (ValidationSymbols.ItemType(type) is not { } item || rules is not LambdaExpressionSyntax lambda || ParameterNames(lambda) is not [var itemBuilder]) + { + NotUnderstood(rules, "EnsureEach takes a collection, and the rules of an item in a lambda that takes the item's builder"); + return; + } + + var into = scope.Into ?? MemberFor(member, type); + var value = ValueOf(member, scope); + var n = Local(); + var indent = scope.Indent; + var present = "__present" + n; + WriteLoopStart(into, indent, value, member, n); + Line(into, indent + " if (__item" + n + " is { } " + present + ")"); + Line(into, indent + " {"); + ReadBody(lambda, new(itemBuilder, present, item, scope.Conditions, into, indent + " ")); + Line(into, indent + " }"); + WriteLoopEnd(into, indent, n); + into.Manifest.Add("EnsureEach"); + } + + private string Local() + { + _locals++; + return _locals.ToString(CultureInfo.InvariantCulture); + } + + private static string ValueOf(string member, Scope scope) => + scope.Into is null ? member.Length == 0 ? "__instance" : "__value" : member.Length == 0 ? scope.Instance : scope.Instance + "." + member; + + private static void Line(MemberBuilder into, string text) => into.Body.Append(text).Append('\n'); + + private static void WriteLoopStart(MemberBuilder into, string indent, string value, string member, string n) + { + Line(into, indent + "if (" + value + " is { } __items" + n + ")"); + Line(into, indent + "{"); + Line(into, indent + " var __path" + n + " = " + Sink + ".Enter(" + Literal(member) + ");"); + Line(into, indent + " var __index" + n + " = 0;"); + Line(into, indent + " foreach (var __item" + n + " in __items" + n + ")"); + Line(into, indent + " {"); + Line(into, indent + " var __itemPath" + n + " = " + Sink + ".Enter(__index" + n + ");"); + } + + private static void WriteLoopEnd(MemberBuilder into, string indent, string n) + { + Line(into, indent + " " + Sink + ".Leave(__itemPath" + n + ");"); + Line(into, indent + " __index" + n + "++;"); + Line(into, indent + " }"); + Line(into, indent + ""); + Line(into, indent + " " + Sink + ".Leave(__path" + n + ");"); + Line(into, indent + "}"); + Line(into, ""); + } + + private static string Literal(string value) => SymbolDisplay.FormatLiteral(value, true); + + private void ReadChain(string member, ITypeSymbol memberType, List calls, Scope scope, bool each) + { + // The compiler has already said so: EnsureEach takes a collection. + if (each && ValidationSymbols.ItemType(memberType) is null) return; + + var into = scope.Into ?? MemberFor(member, memberType); + var functions = new List(); + var rules = new List(); + var displayName = member; + var stop = false; + var n = each ? Local() : ""; + var value = each ? "__item" + n : ValueOf(member, scope); + + foreach (var call in calls) + { + var name = NameOf(call); + var arguments = call.ArgumentList.Arguments; + if (_model.GetSymbolInfo(call).Symbol is not IMethodSymbol symbol) + { + NotUnderstood(call, "'" + name + "' doesn't resolve to a rule"); + continue; + } + + if (ValidationSymbols.Is(symbol.ContainingType.OriginalDefinition, ValidationSymbols.RuntimeNamespace, "IMemberRules")) + { + switch (name) + { + case "Must" or "MustAsync" when arguments.Count == 1 && symbol.Parameters[0].Type is INamedTypeSymbol predicate: + var isAsync = name == "MustAsync"; + var takesModel = predicate.TypeArguments.Length == ( isAsync ? 4 : 3 ); + var passed = new List(); + if (takesModel) passed.Add(scope.Instance); + passed.Add(value); + if (isAsync) passed.Add("__cancellationToken"); + var invoked = Invoke(into, functions, arguments[0].Expression, [.. passed]); + rules.Add( + new() + { + Check = isAsync ? "await " + invoked + ".ConfigureAwait(false)" : invoked, + IsAsync = isAsync, + Code = "Must", + Message = "{Name} is not valid", + } + ); + if (isAsync) into.IsAsync = true; + into.Manifest.Add(name); + break; + case "When" or "Unless" when arguments.Count == 1: + var condition = ( name == "Unless" ? "!" : "" ) + Invoke(into, functions, arguments[0].Expression, scope.Instance); + foreach (var rule in rules) + { + rule.Conditions.Add(condition); + } + + if (into.Nested is not null && scope.Into is null) NotUnderstood(call, "A member validated with ValidateNested can't be under a condition yet"); + break; + case "WithMessage" or "WithCode" when arguments.Count == 1: + if (Constant(arguments[0].Expression, name) is not { } text) break; + if (rules.Count == 0) + { + NotUnderstood(call, name + " changes the rule before it, and there is none"); + break; + } + + if (name == "WithMessage") + { + rules[^1].Message = text; + } + else + { + rules[^1].Code = text; + } + + break; + case "WithSeverity" when arguments.Count == 1: + if (_model.GetConstantValue(arguments[0].Expression) is not { HasValue: true, Value: int severity }) + { + Report(Diagnostics.ConstantRequired, arguments[0].Expression, name); + break; + } + + if (rules.Count == 0) + { + NotUnderstood(call, name + " changes the rule before it, and there is none"); + break; + } + + rules[^1].Severity = severity == 1 ? "Warning" : severity == 2 ? "Info" : "Error"; + break; + case "WithName" when arguments.Count == 1: + if (Constant(arguments[0].Expression, name) is { } display) displayName = display; + break; + case "StopOnFailure": + stop = true; + break; + case "ValidateNested" or "ValidateWith": + ReadNested(call, symbol, member, memberType, into, scope, each); + break; + default: + NotUnderstood(call, "'" + name + "' is not read by the generator"); + break; + } + + continue; + } + + var definition = symbol.ReducedFrom ?? symbol; + if (RuleMethod(definition) is not var (container, method)) + { + NotUnderstood(call, "'" + name + "' is not a rule: the extension method that declares one carries a [ValidationRule]"); + continue; + } + + ReadRule(call, symbol, container, method, into, functions, rules, scope, value); + } + + Write(into, scope, member, displayName, each ? "" : member, value, functions, rules, stop, each, n, each ? ValueOf(member, scope) : ""); + } + + private string? Constant(ExpressionSyntax expression, string method) + { + if (_model.GetConstantValue(expression) is { HasValue: true, Value: string text }) return text; + Report(Diagnostics.ConstantRequired, expression, method); + return null; + } + + private static (string Container, string Method)? RuleMethod(IMethodSymbol extension) + { + foreach (var attribute in extension.GetAttributes()) + { + if (ValidationSymbols.Is(attribute.AttributeClass, ValidationSymbols.RulesNamespace, "ValidationRuleAttribute") + && attribute.ConstructorArguments is [{ Value: INamedTypeSymbol container }, { Value: string method }]) + { + return (container.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), method); + } + } + + return null; + } + + private void ReadNested(InvocationExpressionSyntax call, IMethodSymbol symbol, string member, ITypeSymbol memberType, MemberBuilder into, Scope scope, bool each) + { + if (scope.Into is not null || each || member.Length == 0) + { + NotUnderstood(call, "ValidateNested is declared on a member of the type itself, with Ensure(x => x.Member): it validates a collection item by item"); + return; + } + + var item = ValidationSymbols.ItemType(memberType); + if (ValidationSymbols.Underlying(item ?? memberType) is not INamedTypeSymbol { SpecialType: SpecialType.None, TypeKind: TypeKind.Class or TypeKind.Struct or TypeKind.Interface } target) + { + Report(Diagnostics.NestedNotValidatable, call, member, "its type is not one a validator is written for"); + return; + } + + var with = symbol.Name == "ValidateWith" ? symbol.TypeArguments[0] as INamedTypeSymbol : null; + 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) + ); + } + + private void ReadRule( + InvocationExpressionSyntax call, + IMethodSymbol symbol, + string container, + string method, + MemberBuilder into, + List functions, + List rules, + Scope scope, + string value + ) + { + var arguments = call.ArgumentList.Arguments; + var valueType = symbol.ReceiverType is INamedTypeSymbol { TypeArguments: [_, var receiver] } + ? receiver.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) + : "object"; + var expressions = new List(); + var bindings = new List { "default(" + valueType + ")", }; + var shown = new List(); + var manifest = new List(); + + // A pattern written as a string is held as a Regex by the type the rules are written into. + var isPattern = method == "Matches" + && container == "global::" + ValidationSymbols.RulesNamespace + ".Rule" + && symbol.Parameters is [{ Type.SpecialType: SpecialType.System_String }, ..]; + if (isPattern) + { + if (Constant(arguments[0].Expression, "Matches") is not { } pattern) return; + var options = 0; + if (arguments.Count > 1) + { + if (_model.GetConstantValue(arguments[1].Expression) is not { HasValue: true, Value: int given }) + { + Report(Diagnostics.ConstantRequired, arguments[1].Expression, "Matches"); + return; + } + + options = given; + } + + var field = into.Method + "Pattern" + _fields.Count.ToString(CultureInfo.InvariantCulture); + _fields.Add( + "private static readonly global::System.Text.RegularExpressions.Regex " + + field + + " = new(" + + Literal(pattern) + + ", (global::System.Text.RegularExpressions.RegexOptions)" + + options.ToString(CultureInfo.InvariantCulture) + + " | global::System.Text.RegularExpressions.RegexOptions.CultureInvariant, global::System.TimeSpan.FromSeconds(2));" + ); + expressions.Add(field); + bindings.Add("default(global::System.Text.RegularExpressions.Regex)"); + shown.Add(false); + manifest.Add(Literal(pattern)); + } + else + { + for (var i = 0; i < arguments.Count && i < symbol.Parameters.Length; i++) + { + var parameter = symbol.Parameters[i].Type; + var expression = arguments[i].Expression; + if (parameter is INamedTypeSymbol { TypeKind: TypeKind.Delegate, DelegateInvokeMethod.ReturnType: var returned }) + { + expressions.Add(Invoke(into, functions, expression, scope.Instance)); + bindings.Add("default(" + returned.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) + ")"); + } + else + { + expressions.Add(expression.ToString()); + bindings.Add("default(" + parameter.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) + ")"); + } + + shown.Add(parameter is not INamedTypeSymbol { Name: "Regex" }); + manifest.Add(expression.ToString()); + } + } + + var bound = RuleBinder.Bind(_model, _syntax.SpanStart, container, method, bindings, out _); + if (bound is null) + { + NotUnderstood(call, "no " + container.Replace("global::", "") + "." + method + " checks a value of that type with those arguments"); + return; + } + + var check = container + "." + method + "(" + string.Join(", ", new[] { value, }.Concat(expressions)) + ")"; + var rule = new RuleBuilder + { + Check = bound.IsAsync ? "await " + check + ".ConfigureAwait(false)" : check, + IsAsync = bound.IsAsync, + Code = bound.Code, + Message = bound.Message, + }; + for (var i = 0; i < expressions.Count && i < bound.Placeholders.Count; i++) + { + if (shown[i]) rule.Placeholders.Add((bound.Placeholders[i], expressions[i])); + } + + if (bound.IsAsync) into.IsAsync = true; + rules.Add(rule); + into.Manifest.Add(manifest.Count == 0 ? bound.Code : bound.Code + "(" + string.Join(", ", manifest) + ")"); + } + + private void Write( + MemberBuilder into, + Scope scope, + string member, + string displayName, + string path, + string value, + List functions, + List rules, + bool stop, + bool each, + string n, + string collection + ) + { + if (rules.Count == 0) return; + + // The conditions of the groups the chain is in: each is a local function of this chain. + var grouped = scope.Conditions.Select(z => ( z.Negate ? "!" : "" ) + Invoke(into, functions, z.Expression, z.Instance)).ToList(); + var indent = scope.Indent; + if (each) + { + WriteLoopStart(into, indent, collection, member, n); + indent += " "; + } + + Line(into, indent + "{"); + if (stop) Line(into, indent + " var __start = " + Sink + ".Count;"); + foreach (var function in functions) + { + var lines = function.Split('\n'); + Line(into, indent + " " + lines[0]); + for (var i = 1; i < lines.Length; i++) + { + Line(into, lines[i].TrimEnd('\r')); + } + } + + foreach (var rule in rules) + { + var conditions = new List(); + if (stop) conditions.Add(Sink + ".Count == __start"); + conditions.AddRange(grouped); + conditions.AddRange(rule.Conditions); + conditions.Add(rule.IsAsync ? "!( " + rule.Check + " )" : "!" + rule.Check); + var arguments = string.Concat(rule.Placeholders.Select(static z => ", " + Runtime + ".ValidationSink.Argument(" + Literal(z.Name) + ", " + z.Expression + ")")); + Line(into, indent + " if (" + string.Join(" && ", conditions) + ")"); + Line(into, indent + " {"); + Line( + into, + indent + + " " + + Sink + + ".Add(" + + Literal(path) + + ", " + + Literal(rule.Code) + + ", " + + Literal(rule.Message) + + ", " + + Runtime + + ".ValidationSeverity." + + rule.Severity + + ", " + + Runtime + + ".ValidationSink.Argument(\"Name\", " + + Literal(displayName) + + "), " + + Runtime + + ".ValidationSink.Argument(\"Value\", " + + value + + ")" + + arguments + + ");" + ); + Line(into, indent + " }"); + } + + Line(into, indent + "}"); + if (each) + { + WriteLoopEnd(into, scope.Indent, n); + } + else + { + Line(into, ""); + } + } +} diff --git a/src/Validation.Analyzers/Model/Models.cs b/src/Validation.Analyzers/Model/Models.cs index 2c828e7aaec..d0cf2626970 100644 --- a/src/Validation.Analyzers/Model/Models.cs +++ b/src/Validation.Analyzers/Model/Models.cs @@ -3,22 +3,24 @@ namespace Rocket.Surgery.LaunchPad.Validation.Analyzers.Model; -/// A type that has rules, and everything the generator writes its validator from. It holds no symbols, so the generator can cache it. -internal sealed record ValidatedTypeModel( +/// A type that is validated, as the generated code names it and its validator. +internal sealed record TargetModel( string Namespace, string ValidatorName, string Type, string DocumentationName, string HintName, bool IsPublic, - bool IsReferenceType, - EquatableArray Members + bool IsReferenceType ) { /// The validator's name with its namespace, as generated code refers to it. public string ValidatorFullName => Namespace.Length == 0 ? "global::" + ValidatorName : "global::" + Namespace + "." + ValidatorName; } +/// A type whose members carry rule attributes. It holds no symbols, so the generator can cache it. +internal sealed record ValidatedTypeModel(TargetModel Target, EquatableArray Members); + /// What the syntax provider makes of a type declaration: the model, if the type has rules the generator can write, and what it reports. internal sealed record ValidatedTypeResult(ValidatedTypeModel? Model, EquatableArray Diagnostics); @@ -52,11 +54,72 @@ internal sealed record ArgumentModel(string Name, string Expression); internal sealed record RegexModel(string Field, string Pattern, string Options); /// How a member is validated with a validator of its own. -/// The type the validator is asked of the service provider as. +/// 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 Service, bool IsCollection, bool CanBeNull, bool ItemCanBeNull); +internal sealed record NestedModel(string Target, string? Validator, bool IsAsync, 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 +/// to the type that contains the function, one for each member the rules are about. +/// +/// The type the rules are for. +/// The type that contains the function, or the class validator, as generated code names it. +/// Whether it is a class validator, whose methods are called on an instance of it. +/// Whether the container, and so its rule methods, can be seen from other assemblies. +/// The name of the file the methods are written to. +/// Where the declaration is, which orders the contributors of one type. +/// The using directives of the file, which the copied lambdas are read with. +/// The namespace of the container. +/// The using directives inside the namespace. +/// The declarations to reopen, outermost first: partial class Name. +/// The function's parameters after the builder. +/// The rule methods. +/// The fields the methods use: the regular expressions of patterns. +internal sealed record ContributorModel( + TargetModel Target, + string Container, + bool IsClass, + bool IsPublic, + string HintName, + string Order, + EquatableArray Usings, + string Namespace, + EquatableArray NamespaceUsings, + EquatableArray Containers, + EquatableArray Dependencies, + EquatableArray Members, + EquatableArray Fields +); + +/// What the syntax provider makes of a Validate method. +internal sealed record ContributorResult(ContributorModel? Model, EquatableArray Diagnostics); + +/// A parameter of a Validate function after the builder: a service, or the cancellation token. +internal sealed record DependencyModel(string Type, string Name, bool IsCancellationToken, bool IsPublic); + +/// A rule method written from a function or a class validator. +/// The member the rules are about, or empty for the whole value. +/// The member's type. +/// The method's name. +/// Whether a rule waits, so the method is asynchronous. +/// Whether the method takes the whole value as well as the member's. +/// The method's body, indented from its braces. +/// The rules as the manifest states them. +/// How the member is validated with a validator of its own, if the rules say so. +internal sealed record ContributedMemberModel( + string Member, + string Type, + string Method, + bool IsAsync, + bool ReadsValue, + string Body, + EquatableArray Manifest, + NestedModel? Nested +); /// A diagnostic without its symbols: the descriptor's id, where it is, and its arguments. internal sealed record DiagnosticModel(string Id, string? Path, TextSpan Span, LinePositionSpan LineSpan, EquatableArray Arguments) diff --git a/src/Validation.Analyzers/Model/RuleReader.cs b/src/Validation.Analyzers/Model/RuleReader.cs index c2e6ccbadf6..878dd496842 100644 --- a/src/Validation.Analyzers/Model/RuleReader.cs +++ b/src/Validation.Analyzers/Model/RuleReader.cs @@ -33,39 +33,19 @@ public static ValidatedTypeResult Read(INamedTypeSymbol type, SemanticModel mode if (members.Count == 0) return new(null, reader._diagnostics.ToEquatableArray()); var location = type.Locations.FirstOrDefault(); - var containers = new List(); - for (var current = type; current is not null; current = current.ContainingType) - { - containers.Insert(0, current); - } - - if (containers.Any(static z => z.IsGenericType)) + if (TargetReader.IsGeneric(type)) { reader.Report(Diagnostics.GenericType, location, type.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); return new(null, reader._diagnostics.ToEquatableArray()); } - if (containers.Any(static z => z.DeclaredAccessibility is not ( Accessibility.Public or Accessibility.Internal ) || z.IsFileLocal)) + if (!TargetReader.IsReachable(type)) { reader.Report(Diagnostics.NotAccessible, location, "'" + type.Name + "' and the types that contain it"); return new(null, reader._diagnostics.ToEquatableArray()); } - var @namespace = type.ContainingNamespace is { IsGlobalNamespace: false } ns ? ns.ToDisplayString() : ""; - var name = string.Join("_", containers.Select(static z => z.Name)); - return new( - new( - @namespace, - name + "Validator", - type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), - type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat).Replace("global::", "").Replace('<', '{').Replace('>', '}'), - ( @namespace.Length == 0 ? name : @namespace + "." + name ) + ".Validator.g.cs", - containers.All(static z => z.DeclaredAccessibility == Accessibility.Public), - type.IsReferenceType, - members.ToEquatableArray() - ), - reader._diagnostics.ToEquatableArray() - ); + return new(new(TargetReader.Read(type), members.ToEquatableArray()), reader._diagnostics.ToEquatableArray()); } private readonly INamedTypeSymbol _type; @@ -164,10 +144,16 @@ private void ReadNested(MemberContext context, AttributeData attribute) return; } - var service = ValidationSymbols.IsValidateWith(attribute.AttributeClass) - ? attribute.AttributeClass!.TypeArguments[0].ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) - : "global::" + ValidationSymbols.RuntimeNamespace + ".IValidate<" + target.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat) + ">"; - context.Nested = new(service, item is not null, ValidationSymbols.CanBeNull(context.Type), item is not null && ValidationSymbols.CanBeNull(item)); + var named = (INamedTypeSymbol)target; + var with = ValidationSymbols.IsValidateWith(attribute.AttributeClass) ? attribute.AttributeClass!.TypeArguments[0] as INamedTypeSymbol : null; + 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) + ); } private void ReadRule(MemberContext context, AttributeData attribute) @@ -445,11 +431,17 @@ private Argument AddRegex(MemberContext context, string pattern, int options) private void AddRule(MemberContext context, AttributeData attribute, string container, string method, IReadOnlyList arguments) { - var binding = container + "." + method + "(" + string.Join(", ", new[] { "default(" + context.TypeName + ")", }.Concat(arguments.Select(static z => z.Binding))) + ")"; - var info = _model.GetSpeculativeSymbolInfo(_position, SyntaxFactory.ParseExpression(binding), SpeculativeBindingOption.BindAsExpression); - if (info.Symbol is not IMethodSymbol bound || bound.ReturnType.SpecialType != SpecialType.System_Boolean) + var bound = RuleBinder.Bind( + _model, + _position, + container, + method, + new[] { "default(" + context.TypeName + ")", }.Concat(arguments.Select(static z => z.Binding)), + out var found + ); + if (bound is null) { - var reason = info.Symbol is IMethodSymbol + var reason = found ? method + " is not a method that returns bool" : "no " + container.Replace("global::", "") + "." + method + " takes that type" + ( arguments.Count == 0 ? "" : " with " + string.Join(", ", arguments.Select(static z => z.Manifest)) ); @@ -464,25 +456,14 @@ private void AddRule(MemberContext context, AttributeData attribute, string cont return; } - var code = method; - var message = "{Name} is not valid"; - foreach (var candidate in bound.OriginalDefinition.GetAttributes()) - { - if (ValidationSymbols.Is(candidate.AttributeClass, ValidationSymbols.RulesNamespace, "RuleDefaultsAttribute") - && candidate.ConstructorArguments is [{ Value: string defaultCode }, { Value: string defaultMessage }]) - { - code = defaultCode; - message = defaultMessage; - } - } - + var code = bound.Code; + var message = bound.Message; var placeholders = new List(); - for (var i = 0; i < arguments.Count && i + 1 < bound.Parameters.Length; i++) + for (var i = 0; i < arguments.Count && i < bound.Placeholders.Count; i++) { - var name = bound.Parameters[i + 1].Name; // A pattern is not something a message shows. if (arguments[i].Binding == "default(" + Regex + ")") continue; - placeholders.Add(new(char.ToUpperInvariant(name[0]) + name[1..], arguments[i].Expression)); + placeholders.Add(new(bound.Placeholders[i], arguments[i].Expression)); } var check = container + "." + method + "(" + string.Join(", ", first.Concat(arguments.Select(static z => z.Expression))) + ")"; diff --git a/src/Validation.Analyzers/Model/TargetReader.cs b/src/Validation.Analyzers/Model/TargetReader.cs new file mode 100644 index 00000000000..d08bd39d5ef --- /dev/null +++ b/src/Validation.Analyzers/Model/TargetReader.cs @@ -0,0 +1,124 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; + +namespace Rocket.Surgery.LaunchPad.Validation.Analyzers.Model; + +/// Names a validated type and its validator, and says why a validator can't be written for it. +internal static class TargetReader +{ + /// The types a type is declared in, outermost first, and the type itself last. + public static List Containers(INamedTypeSymbol type) + { + var containers = new List(); + for (var current = type; current is not null; current = current.ContainingType) + { + containers.Insert(0, current); + } + + return containers; + } + + public static bool IsReachable(INamedTypeSymbol type) => + Containers(type).All(static z => z.DeclaredAccessibility is Accessibility.Public or Accessibility.Internal && !z.IsFileLocal); + + /// Whether a type can be named in the signature of a public member. + public static bool IsPublic(ITypeSymbol type) => type switch + { + IArrayTypeSymbol array => IsPublic(array.ElementType), + INamedTypeSymbol named => Containers(named).All(static z => z.DeclaredAccessibility == Accessibility.Public) && named.TypeArguments.All(IsPublic), + _ => true, + }; + + public static bool IsGeneric(INamedTypeSymbol type) => Containers(type).Any(static z => z.IsGenericType); + + /// + /// The name of a type's validator, without its namespace. Not {Type}Validator: that is what an application calls its class + /// validator. + /// + public static string ValidatorName(INamedTypeSymbol type) => string.Join("_", Containers(type).Select(static z => z.Name)) + "GeneratedValidator"; + + public static string NamespaceOf(INamedTypeSymbol type) => type.ContainingNamespace is { IsGlobalNamespace: false } ns ? ns.ToDisplayString() : ""; + + /// The model of a type that is public or internal and not generic; the caller reports the others. + public static TargetModel Read(INamedTypeSymbol type) + { + var @namespace = NamespaceOf(type); + var name = ValidatorName(type); + var fullName = type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + return new( + @namespace, + name, + fullName, + fullName.Replace("global::", "").Replace('<', '{').Replace('>', '}'), + ( @namespace.Length == 0 ? name : @namespace + "." + name ) + ".g.cs", + Containers(type).All(static z => z.DeclaredAccessibility == Accessibility.Public), + type.IsReferenceType + ); + } + + /// + /// 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")); +} + +/// +/// Decides which method checks a rule the way C# does: it binds the call the generator will write and takes the overload the compiler +/// picks, with its code, its message and the names of its parameters, which are the message's placeholders. +/// +internal static class RuleBinder +{ + public sealed record Bound(string Code, string Message, IReadOnlyList Placeholders, bool IsAsync); + + /// + /// + /// + /// The semantic model of the tree the rule is declared in. + /// A position in that tree. + /// The type that declares the method, as generated code names it. + /// The method's name. + /// An expression of the type of each argument, the value first: default(string). + /// Whether a method was found at all: one that doesn't return is found and not bound. + public static Bound? Bind(SemanticModel model, int position, string container, string method, IEnumerable arguments, out bool found) + { + var call = container + "." + method + "(" + string.Join(", ", arguments) + ")"; + var info = model.GetSpeculativeSymbolInfo(position, SyntaxFactory.ParseExpression(call), SpeculativeBindingOption.BindAsExpression); + found = info.Symbol is IMethodSymbol; + if (info.Symbol is not IMethodSymbol bound) return null; + var returns = bound.ReturnType; + var isBool = returns.SpecialType == SpecialType.System_Boolean + || returns is INamedTypeSymbol { Name: "ValueTask" or "Task", TypeArguments: [{ SpecialType: SpecialType.System_Boolean }] }; + if (!isBool) return null; + + var code = method; + var message = "{Name} is not valid"; + foreach (var candidate in bound.OriginalDefinition.GetAttributes()) + { + if (ValidationSymbols.Is(candidate.AttributeClass, ValidationSymbols.RulesNamespace, "RuleDefaultsAttribute") + && candidate.ConstructorArguments is [{ Value: string defaultCode }, { Value: string defaultMessage }]) + { + code = defaultCode; + message = defaultMessage; + } + } + + var placeholders = new List(); + for (var i = 1; i < bound.Parameters.Length; i++) + { + var name = bound.Parameters[i].Name; + placeholders.Add(char.ToUpperInvariant(name[0]) + name[1..]); + } + + return new(code, message, placeholders, returns.SpecialType != SpecialType.System_Boolean); + } +} diff --git a/src/Validation.Analyzers/SynchronousValidationAnalyzer.cs b/src/Validation.Analyzers/SynchronousValidationAnalyzer.cs new file mode 100644 index 00000000000..a90830b58fb --- /dev/null +++ b/src/Validation.Analyzers/SynchronousValidationAnalyzer.cs @@ -0,0 +1,54 @@ +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) 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) + { + if (type is not { TypeArguments: [INamedTypeSymbol target] } || !ValidationSymbols.Is(type.OriginalDefinition, ValidationSymbols.RuntimeNamespace, "IValidate")) + { + return null; + } + + var @namespace = TargetReader.NamespaceOf(target); + var validator = target.ContainingAssembly?.GetTypeByMetadataName(( @namespace.Length == 0 ? "" : @namespace + "." ) + TargetReader.ValidatorName(target)); + return validator is not null && !TargetReader.ImplementsSynchronous(validator) ? target : null; + } +} diff --git a/src/Validation.Analyzers/SynchronousValidationCodeFix.cs b/src/Validation.Analyzers/SynchronousValidationCodeFix.cs new file mode 100644 index 00000000000..0699dfa833a --- /dev/null +++ b/src/Validation.Analyzers/SynchronousValidationCodeFix.cs @@ -0,0 +1,164 @@ +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 = call.Ancestors().FirstOrDefault(static z => z is BaseMethodDeclarationSyntax or LocalFunctionStatementSyntax or AnonymousFunctionExpressionSyntax); + 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); + } + + // 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/ValidatorGenerator.cs b/src/Validation.Analyzers/ValidatorGenerator.cs index 481ea3192ab..17cf222da58 100644 --- a/src/Validation.Analyzers/ValidatorGenerator.cs +++ b/src/Validation.Analyzers/ValidatorGenerator.cs @@ -26,29 +26,61 @@ public void Initialize(IncrementalGeneratorInitializationContext context) .Where(static z => z is not null) .Select(static (z, _) => z!); + // A function validator, or the Validate of a class validator: a method named Validate whose first parameter is the builder. + var contributors = context + .SyntaxProvider.CreateSyntaxProvider( + static (node, _) => node is MethodDeclarationSyntax { Identifier.ValueText: "Validate", ParameterList.Parameters.Count: >= 1, }, + static (syntax, _) => FunctionReader.Read((MethodDeclarationSyntax)syntax.Node, syntax.SemanticModel) + ) + .Where(static z => z is not null) + .Select(static (z, _) => z!); + var environment = context.CompilationProvider.Select(static (compilation, _) => CompilationModel.Read(compilation)); context.RegisterSourceOutput( - types.Combine(environment), - static (output, pair) => + types, + static (output, result) => { - var (result, compilation) = pair; foreach (var diagnostic in result.Diagnostics) { if (diagnostic.ToDiagnostic() is { } reported) output.ReportDiagnostic(reported); } + } + ); - if (result.Model is { } model) output.AddSource(model.HintName, ValidatorEmitter.Validator(model, compilation)); + // The rule methods of a function or a class validator, written into the type that contains it. + context.RegisterSourceOutput( + contributors, + static (output, result) => + { + foreach (var diagnostic in result.Diagnostics) + { + if (diagnostic.ToDiagnostic() is { } reported) output.ReportDiagnostic(reported); + } + + if (result.Model is { } model) output.AddSource(model.HintName, ValidatorEmitter.Contributor(model)); } ); + // One validator for each type, from everything that declares rules for it, and the method that registers them all. context.RegisterSourceOutput( - types.Where(static z => z.Model is not null).Select(static (z, _) => z.Model!).Collect().Combine(environment), + types + .Where(static z => z.Model is not null) + .Select(static (z, _) => z.Model!) + .Collect() + .Combine(contributors.Where(static z => z.Model is not null).Select(static (z, _) => z.Model!).Collect()) + .Combine(environment), static (output, pair) => { - var (models, compilation) = pair; - if (!compilation.HasServiceCollection || ( models.IsEmpty && compilation.Registrations.Length == 0 )) return; - output.AddSource("LaunchPadValidators.g.cs", ValidatorEmitter.Registration(models, compilation)); + var ((attributed, contributed), compilation) = pair; + var merged = MergedModel.Merge(attributed, contributed); + foreach (var model in merged) + { + output.AddSource(model.Target.HintName, ValidatorEmitter.Validator(model, compilation)); + } + + if (!compilation.HasServiceCollection || ( merged.Count == 0 && compilation.Registrations.Length == 0 )) return; + output.AddSource("LaunchPadValidators.g.cs", ValidatorEmitter.Registration(merged, compilation)); } ); } @@ -111,47 +143,173 @@ public static CompilationModel Read(Compilation compilation) } } -/// Writes the validators and their registration. +/// Everything that declares rules for one type: the attributes of its members, and the functions and classes that validate it. +internal sealed class MergedModel(TargetModel target) +{ + public TargetModel Target { get; } = target; + public IReadOnlyList Members { get; private set; } = []; + public List Contributors { get; } = []; + + /// Whether a rule waits, here or in a member validated with its own validator: the type is then validated asynchronously only. + public bool IsAsync { get; private set; } + + /// + /// Whether the validator takes services, or asks the service provider for the validators of its members: it then can't outlive them, and + /// is registered scoped. + /// + public bool HasDependencies => Contributors.Any(static z => z.IsClass || z.Dependencies.Any(static d => !d.IsCancellationToken)) || Nested.Any(); + + /// Whether the validator can be public: the type is, and so is everything its constructor takes. + public bool IsPublic => Target.IsPublic && Contributors.All(static z => z.IsClass ? z.IsPublic : z.Dependencies.All(static d => d.IsPublic)); + + public IEnumerable Nested => + Members.Where(static z => z.Nested is not null).Select(static z => z.Nested!) + .Concat(Contributors.SelectMany(static z => z.Members).Where(static z => z.Nested is not null).Select(static z => z.Nested!)); + + public static IReadOnlyList Merge(ImmutableArray attributed, ImmutableArray contributed) + { + var byType = new Dictionary(StringComparer.Ordinal); + MergedModel For(TargetModel target) + { + if (!byType.TryGetValue(target.Type, out var merged)) byType.Add(target.Type, merged = new(target)); + return merged; + } + + foreach (var model in attributed) + { + For(model.Target).Members = model.Members.Items; + } + + foreach (var model in contributed.OrderBy(static z => z.Order, StringComparer.Ordinal)) + { + For(model.Target).Contributors.Add(model); + } + + foreach (var merged in byType.Values) + { + merged.IsAsync = merged.Contributors.Any(static z => z.Members.Any(static m => m.IsAsync)) || merged.Nested.Any(static z => z.IsAsync); + } + + // A type that validates a member with the validator of an asynchronous type is asynchronous too. + for (var changed = true; changed;) + { + changed = false; + foreach (var merged in byType.Values) + { + if (merged.IsAsync) continue; + if (!merged.Nested.Any(z => z.Validator is null && byType.TryGetValue(z.Target, out var nested) && nested.IsAsync)) continue; + merged.IsAsync = true; + changed = true; + } + } + + return [.. byType.Values.OrderBy(static z => z.Target.ValidatorFullName, StringComparer.Ordinal)]; + } +} + +/// Writes the validators, the rule methods of functions and classes, and the registration. internal static class ValidatorEmitter { private const string Runtime = "global::" + ValidationSymbols.RuntimeNamespace; private const string Sink = Runtime + ".ValidationSink"; private const string Never = "[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]"; + private const string Token = "global::System.Threading.CancellationToken"; + + // 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); - public static string Validator(ValidatedTypeModel model, CompilationModel compilation) + public static string Validator(MergedModel model, CompilationModel compilation) { - var options = compilation.HasOptions && model.IsReferenceType; - var nested = model.Members.Where(static z => z.Nested is not null).ToList(); + var target = model.Target; + var isAsync = model.IsAsync; + var options = compilation.HasOptions && target.IsReferenceType && !isAsync && !model.HasDependencies; var sb = new StringBuilder(); sb.AppendLine("// "); sb.AppendLine("#nullable enable"); sb.AppendLine(); var indent = ""; - if (model.Namespace.Length > 0) + if (target.Namespace.Length > 0) { - sb.Append("namespace ").AppendLine(model.Namespace); + sb.Append("namespace ").AppendLine(target.Namespace); sb.AppendLine("{"); indent = " "; } void Line(string text = "") => _ = text.Length == 0 ? sb.AppendLine() : sb.Append(indent).AppendLine(text); + // What the validator is given: the services its functions take, each once, and its class validators. + var fields = new List<(string Type, string Field, string Parameter)>(); + var dependencyFields = new Dictionary(StringComparer.Ordinal); + var classFields = new Dictionary(StringComparer.Ordinal); + string Unique(string name) + { + var candidate = name; + for (var i = 1; fields.Any(z => z.Parameter == candidate) || candidate is "messages" or "services" or "value"; i++) + { + candidate = name + i.ToString(System.Globalization.CultureInfo.InvariantCulture); + } + + return candidate; + } + + foreach (var contributor in model.Contributors) + { + if (contributor.IsClass) + { + if (classFields.ContainsKey(contributor.Container)) continue; + var name = Unique(Camel(contributor.Container[( contributor.Container.LastIndexOf('.') + 1 )..].Replace("global::", ""))); + classFields.Add(contributor.Container, "_" + name); + fields.Add((contributor.Container, "_" + name, name)); + continue; + } + + foreach (var dependency in contributor.Dependencies) + { + if (dependency.IsCancellationToken || dependencyFields.ContainsKey(dependency.Type)) continue; + var name = Unique(dependency.Name); + dependencyFields.Add(dependency.Type, "_" + name); + fields.Add((dependency.Type, "_" + name, name)); + } + } + + // One validator for each type validated, whichever members are of it: named after the first. + var nested = new Dictionary(StringComparer.Ordinal); + NestedValidator NestedFor(string member, NestedModel how) + { + var awaited = how.Validator is null ? isAsync : how.IsAsync; + 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)); + return validator; + } + + foreach (var member in model.Members) + { + if (member.Nested is { } how) NestedFor(member.Name, how); + } + + foreach (var member in model.Contributors.SelectMany(static z => z.Members)) + { + if (member.Nested is { } how) NestedFor(member.Member, how); + } + Line("/// "); - Line($"/// Validates a : the rules its members carry as attributes."); + Line($"/// Validates a : every rule declared for it, by the attributes of its members and by the"); + Line("/// functions and classes that validate it."); Line("/// "); - Line($"[{Runtime}.GeneratedValidator(typeof({model.Type}))]"); - Line($"{( model.IsPublic ? "public" : "internal" )} sealed partial class {model.ValidatorName}"); - Line($" : {Runtime}.IValidate<{model.Type}>{( options ? $", global::Microsoft.Extensions.Options.IValidateOptions<{model.Type}>" : "" )}"); + Line($"[{Runtime}.GeneratedValidator(typeof({target.Type}))]"); + Line($"{( model.IsPublic ? "public" : "internal" )} sealed class {target.ValidatorName}"); + Line($" : {Runtime}.{( isAsync ? "IValidateAsync" : "IValidate" )}<{target.Type}>{( options ? $", global::Microsoft.Extensions.Options.IValidateOptions<{target.Type}>" : "" )}"); Line("{"); + foreach (var field in fields) + { + Line($" private readonly {field.Type} {field.Field};"); + } + Line($" private readonly {Runtime}.IValidationMessageProvider? _messages;"); if (nested.Count > 0) Line(" private readonly global::System.IServiceProvider? _services;"); - // One validator for each type validated, whichever members are of it: named after the first. - var validators = new Dictionary(StringComparer.Ordinal); - foreach (var member in nested) + foreach (var validator in nested.Values) { - if (validators.ContainsKey(member.Nested!.Service)) continue; - validators.Add(member.Nested.Service, member.Name + "Validator"); - Line($" private {member.Nested.Service}? _{Camel(member.Name)}Validator;"); + Line($" private {validator.Service}? _{Camel(validator.Property)};"); } foreach (var regex in model.Members.SelectMany(static z => z.Regexes)) @@ -165,26 +323,44 @@ public static string Validator(ValidatedTypeModel model, CompilationModel compil Line(" /// "); Line(" /// Creates the validator."); Line(" /// "); + foreach (var field in fields) + { + Line($" /// What the rules declared for the type take."); + } + Line(" /// What replaces the rules' messages, if anything does."); - if (nested.Count > 0) + if (nested.Count > 0) Line(" /// Where the validators of the members validated with their own are found."); + var parameters = string.Concat(fields.Select(static z => z.Type + " " + z.Parameter + ", ")) + + Runtime + + ".IValidationMessageProvider? messages = null" + + ( nested.Count > 0 ? ", global::System.IServiceProvider? services = null" : "" ); + if (fields.Count == 0 && nested.Count == 0) { - Line(" /// Where the validators of the members validated with their own are found."); - Line($" public {model.ValidatorName}({Runtime}.IValidationMessageProvider? messages = null, global::System.IServiceProvider? services = null)"); - Line(" {"); - Line(" _messages = messages;"); - Line(" _services = services;"); - Line(" }"); + Line($" public {target.ValidatorName}({parameters}) => _messages = messages;"); } else { - Line($" public {model.ValidatorName}({Runtime}.IValidationMessageProvider? messages = null) => _messages = messages;"); + Line($" public {target.ValidatorName}({parameters})"); + Line(" {"); + foreach (var field in fields) + { + Line($" {field.Field} = {field.Parameter};"); + } + + Line(" _messages = messages;"); + if (nested.Count > 0) Line(" _services = services;"); + Line(" }"); } Line(); Line(" /// "); - Line($" public {Runtime}.ValidationResult Validate({model.Type} value)"); + Line( + isAsync + ? $" public async global::System.Threading.Tasks.ValueTask<{Runtime}.ValidationResult> ValidateAsync({target.Type} value, {Token} cancellationToken = default)" + : $" public {Runtime}.ValidationResult Validate({target.Type} value)" + ); Line(" {"); - if (model.IsReferenceType) Line(" global::System.ArgumentNullException.ThrowIfNull(value);"); + if (target.IsReferenceType) Line(" global::System.ArgumentNullException.ThrowIfNull(value);"); Line($" var sink = new {Sink}(_messages);"); foreach (var member in model.Members) { @@ -194,7 +370,34 @@ public static string Validator(ValidatedTypeModel model, CompilationModel compil Line($" Ensure{member.Name}({arguments}, ref sink);"); } - if (member.Nested is { } how) WriteNested(member, how, validators[how.Service], Line); + if (member.Nested is { } how) WriteNested(member.Name, how, NestedFor(member.Name, how), Line); + } + + foreach (var contributor in model.Contributors) + { + var on = contributor.IsClass ? classFields[contributor.Container] : contributor.Container; + foreach (var member in contributor.Members) + { + if (member.Body.Length > 0) + { + var arguments = new List(); + if (member.ReadsValue) arguments.Add("value"); + if (member.Member.Length > 0) arguments.Add("value." + member.Member); + foreach (var dependency in contributor.Dependencies) + { + arguments.Add(dependency.IsCancellationToken ? isAsync ? "cancellationToken" : "default" : dependencyFields[dependency.Type]); + } + + var list = string.Join(", ", arguments); + Line( + member.IsAsync + ? $" sink = await {on}.{member.Method}({list}, sink, cancellationToken).ConfigureAwait(false);" + : $" {on}.{member.Method}({list}, ref sink);" + ); + } + + if (member.Nested is { } how) WriteNested(member.Member, how, NestedFor(member.Member, how), Line); + } } Line(" return sink.ToResult();"); @@ -204,7 +407,7 @@ public static string Validator(ValidatedTypeModel model, CompilationModel compil { Line(); Line(" /// "); - Line($" global::Microsoft.Extensions.Options.ValidateOptionsResult global::Microsoft.Extensions.Options.IValidateOptions<{model.Type}>.Validate(string? name, {model.Type} options)"); + Line($" global::Microsoft.Extensions.Options.ValidateOptionsResult global::Microsoft.Extensions.Options.IValidateOptions<{target.Type}>.Validate(string? name, {target.Type} options)"); Line(" {"); Line(" var result = Validate(options);"); Line(" if (result.IsValid) return global::Microsoft.Extensions.Options.ValidateOptionsResult.Success;"); @@ -218,33 +421,38 @@ public static string Validator(ValidatedTypeModel model, CompilationModel compil Line(" }"); } - foreach (var validator in validators) + foreach (var validator in nested.Values) { - var field = "_" + Camel(validator.Value); + var field = "_" + Camel(validator.Property); Line(); - Line($" private {validator.Key} {validator.Value} =>"); - Line($" {field} ??= _services?.GetService(typeof({validator.Key})) as {validator.Key}"); - Line($" ?? throw new global::System.InvalidOperationException(\"{model.ValidatorName} needs a {Escape(validator.Key.Replace("global::", ""))}, which the service provider it was given does not have.\");"); + Line($" private {validator.Service} {validator.Property} =>"); + Line($" {field} ??= _services?.GetService(typeof({validator.Service})) as {validator.Service}"); + Line($" ?? throw new global::System.InvalidOperationException(\"{target.ValidatorName} needs a {Escape(validator.Service.Replace("global::", ""))}, which the service provider it was given does not have.\");"); } foreach (var member in model.Members.Where(static z => z.Rules.Length > 0)) { - WriteRuleMethod(model, member, Line); + WriteRuleMethod(target, member, Line); } Line("}"); - if (model.Namespace.Length > 0) sb.AppendLine("}"); + if (target.Namespace.Length > 0) sb.AppendLine("}"); return sb.ToString(); } - private static void WriteNested(MemberModel member, NestedModel nested, string validator, Action line) + private static void WriteNested(string member, NestedModel nested, NestedValidator validator, Action line) { - var local = Camel(member.Name); - var name = Literal(member.Name); + var local = "__" + Camel(member); + 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}));"; + line(""); - if (nested.CanBeNull) line($" if (value.{member.Name} is {{ }} {local})"); + if (nested.CanBeNull) line($" if (value.{member} is {{ }} {local})"); line(" {"); - if (!nested.CanBeNull) line($" var {local} = value.{member.Name};"); + if (!nested.CanBeNull) line($" var {local} = value.{member};"); line($" var path = sink.Enter({name});"); if (nested.IsCollection) { @@ -256,14 +464,14 @@ private static void WriteNested(MemberModel member, NestedModel nested, string v line(" if (item is { } present)"); line(" {"); line(" var itemPath = sink.Enter(index);"); - line($" sink.Add({validator}.Validate(present));"); + line(" " + Call("present")); line(" sink.Leave(itemPath);"); line(" }"); } else { line(" var itemPath = sink.Enter(index);"); - line($" sink.Add({validator}.Validate(item));"); + line(" " + Call("item")); line(" sink.Leave(itemPath);"); } @@ -274,7 +482,7 @@ private static void WriteNested(MemberModel member, NestedModel nested, string v } else { - line($" sink.Add({validator}.Validate({local}));"); + line(" " + Call(local)); } line(" sink.Leave(path);"); @@ -282,18 +490,18 @@ private static void WriteNested(MemberModel member, NestedModel nested, string v line(""); } - private static void WriteRuleMethod(ValidatedTypeModel model, MemberModel member, Action line) + private static void WriteRuleMethod(TargetModel target, MemberModel member, Action line) { var name = Literal(member.Name); var manifest = string.Concat(member.Rules.Select(static z => ", " + Literal(z.Manifest))); var reads = member.Reads.Length == 0 ? "" : ", Reads = new[] { " + string.Join(", ", member.Reads.Select(static z => Literal(z.Name))) + " }"; - var parameters = ( member.ReadsValue ? model.Type + " instance, " : "" ) + var parameters = ( member.ReadsValue ? target.Type + " instance, " : "" ) + member.Type + " value" + string.Concat(member.Reads.Select(static z => ", " + z.Type + " " + z.Parameter)); line(""); line(" /// "); - line($" /// The rules of ."); + line($" /// The rules of ."); line(" /// "); line($" [{Runtime}.GeneratedRule({name}{manifest}{reads}{( member.ReadsValue ? ", ReadsValue = true" : "" )})]"); line(" " + Never); @@ -314,7 +522,102 @@ private static void WriteRuleMethod(ValidatedTypeModel model, MemberModel member line(" }"); } - public static string Registration(ImmutableArray models, CompilationModel compilation) + /// The rule methods of a function or a class validator, in the type that contains it, read with the usings of its file. + public static string Contributor(ContributorModel model) + { + var sb = new StringBuilder(); + sb.AppendLine("// "); + // The lambdas are copied from a file that may not have nullable reference types on: their annotations are read, their warnings are not repeated. + sb.AppendLine("#nullable enable annotations"); + sb.AppendLine("#pragma warning disable CS1998 // an asynchronous rule method whose rules all turned out to be synchronous"); + foreach (var @using in model.Usings) + { + sb.AppendLine(@using); + } + + sb.AppendLine(); + var indent = ""; + if (model.Namespace.Length > 0) + { + sb.Append("namespace ").AppendLine(model.Namespace); + sb.AppendLine("{"); + indent = " "; + foreach (var @using in model.NamespaceUsings) + { + sb.Append(indent).AppendLine(@using); + } + } + + foreach (var container in model.Containers) + { + sb.Append(indent).AppendLine(container); + sb.Append(indent).AppendLine("{"); + indent += " "; + } + + void Line(string text = "") => _ = text.Length == 0 ? sb.AppendLine() : sb.Append(indent).AppendLine(text); + + foreach (var field in model.Fields) + { + Line(field); + Line(); + } + + var accessibility = model.IsPublic && model.Target.IsPublic ? "public" : "internal"; + var @static = model.IsClass ? "" : "static "; + var dependencies = string.Concat(model.Dependencies.Select(static z => z.Type + " " + z.Name + ", ")); + var first = true; + foreach (var member in model.Members.Where(static z => z.Body.Length > 0)) + { + if (!first) Line(); + first = false; + var manifest = string.Concat(member.Manifest.Select(static z => ", " + Literal(z))); + var parameters = ( member.ReadsValue ? model.Target.Type + " __instance, " : "" ) + + ( member.Member.Length > 0 ? member.Type + " __value, " : "" ) + + dependencies; + Line("/// "); + Line( + member.Member.Length > 0 + ? $"/// The rules Validate declares for ." + : $"/// The rules Validate declares for a as a whole." + ); + Line("/// "); + Line($"[{Runtime}.GeneratedRule({Literal(member.Member)}{manifest}{( member.ReadsValue ? ", ReadsValue = true" : "" )}, DeclaredBy = nameof(Validate))]"); + Line(Never); + Line( + member.IsAsync + ? $"{accessibility} {@static}async global::System.Threading.Tasks.ValueTask<{Sink}> {member.Method}({parameters}{Sink} __sink, {Token} __cancellationToken)" + : $"{accessibility} {@static}void {member.Method}({parameters}ref {Sink} __sink)" + ); + Line("{"); + foreach (var line in member.Body.TrimEnd('\n').Split('\n')) + { + // A line of a copied lambda keeps the indentation it was written with. + if (line.Length == 0) + { + sb.AppendLine(); + } + else + { + sb.Append(indent).Append(" ").AppendLine(line); + } + } + + if (member.IsAsync) Line(" return __sink;"); + Line("}"); + } + + for (var i = 0; i < model.Containers.Length; i++) + { + indent = indent[..^4]; + sb.Append(indent).AppendLine("}"); + } + + if (model.Namespace.Length > 0) sb.AppendLine("}"); + return sb.ToString(); + } + + public static string Registration(IReadOnlyList models, CompilationModel compilation) { const string extensions = "global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions"; const string services = "global::Microsoft.Extensions.DependencyInjection.IServiceCollection"; @@ -336,7 +639,8 @@ public static string Registration(ImmutableArray models, Com sb.AppendLine(" {"); sb.AppendLine(" /// "); sb.AppendLine($" /// Adds the validators of {compilation.AssemblyName}, and those of the assemblies it references, each as the"); - sb.AppendLine(" /// IValidate and IValidateAsync of the type it validates."); + sb.AppendLine(" /// IValidateAsync of the type it validates, and as its IValidate unless one of the type's rules waits. A"); + sb.AppendLine(" /// validator whose rules take services is scoped; the others are singletons."); sb.AppendLine(" /// "); sb.AppendLine(" /// The services."); sb.AppendLine(" /// The services."); @@ -347,14 +651,27 @@ public static string Registration(ImmutableArray models, Com sb.AppendLine($" {registration}(services);"); } - foreach (var model in models.OrderBy(static z => z.ValidatorFullName, StringComparer.Ordinal)) + foreach (var model in models) { - var validator = model.ValidatorFullName; - sb.AppendLine($" {extensions}.TryAddSingleton<{Runtime}.IValidate<{model.Type}>, {validator}>(services);"); - sb.AppendLine($" {extensions}.TryAddSingleton<{Runtime}.IValidateAsync<{model.Type}>>(services, static provider => ({Runtime}.IValidate<{model.Type}>)provider.GetService(typeof({Runtime}.IValidate<{model.Type}>))!);"); - if (compilation.HasOptions && model.IsReferenceType) + var target = model.Target; + var validator = target.ValidatorFullName; + var lifetime = model.HasDependencies ? "Scoped" : "Singleton"; + foreach (var container in model.Contributors.Where(static z => z.IsClass).Select(static z => z.Container).Distinct(StringComparer.Ordinal)) + { + sb.AppendLine($" {extensions}.TryAddScoped<{container}>(services);"); + } + + if (model.IsAsync) + { + sb.AppendLine($" {extensions}.TryAdd{lifetime}<{Runtime}.IValidateAsync<{target.Type}>, {validator}>(services);"); + continue; + } + + 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}>))!);"); + if (compilation.HasOptions && target.IsReferenceType && !model.HasDependencies) { - sb.AppendLine($" {extensions}.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton, {validator}>());"); + sb.AppendLine($" {extensions}.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton, {validator}>());"); } } diff --git a/src/Validation/GeneratedValidatorAttribute.cs b/src/Validation/GeneratedValidatorAttribute.cs index 0bdaec95fb9..d0531e5e19b 100644 --- a/src/Validation/GeneratedValidatorAttribute.cs +++ b/src/Validation/GeneratedValidatorAttribute.cs @@ -44,6 +44,12 @@ public sealed class GeneratedRuleAttribute(string member, params string[] rules) /// public string[] Reads { get; init; } = []; + /// + /// The name of the function or class validator method the rules were read from. Its value says little; that the generated code + /// names the method is what tells the compiler, and a formatter, that a private Validate nobody calls is used. + /// + public string? DeclaredBy { get; init; } + /// /// Whether the method takes the whole value first: a rule that calls a method of the value needs it. /// diff --git a/src/Validation/IValidationBuilder.cs b/src/Validation/IValidationBuilder.cs index 48a8385cb6c..91df25ffa05 100644 --- a/src/Validation/IValidationBuilder.cs +++ b/src/Validation/IValidationBuilder.cs @@ -58,9 +58,9 @@ public interface IValidationBuilder /// (), and an application adds its own with . /// /// The type the rules are for. -/// The member's type. +/// The member's type. A rule declared for a type applies to the members of every type that converts to it. [PublicAPI] -public interface IMemberRules +public interface IMemberRules { /// /// A rule of the application's own, over the member's value. diff --git a/src/Validation/Rules/MemberRulesExtensions.cs b/src/Validation/Rules/MemberRulesExtensions.cs index 94c32155e26..0077babbd8a 100644 --- a/src/Validation/Rules/MemberRulesExtensions.cs +++ b/src/Validation/Rules/MemberRulesExtensions.cs @@ -45,22 +45,17 @@ public static class MemberRulesExtensions /// The rules of the member. /// The rules of the member. [ValidationRule(typeof(Rule), nameof(Rule.EmailAddress))] - public static IMemberRules EmailAddress(this IMemberRules rules) => rules; + public static IMemberRules EmailAddress(this IMemberRules rules) + where TMember : IEquatable? => rules; /// The member must be an absolute http or https URL. /// The rules of the member. /// The rules of the member. [ValidationRule(typeof(Rule), nameof(Rule.Url))] - public static IMemberRules Url(this IMemberRules rules) => rules; + public static IMemberRules Url(this IMemberRules rules) + where TMember : IEquatable? => rules; - /// The string must have at least this many characters. - /// The rules of the member. - /// The length. - /// The rules of the member. - [ValidationRule(typeof(Rule), nameof(Rule.MinLength))] - public static IMemberRules MinLength(this IMemberRules rules, int min) => rules; - - /// The collection must have at least this many items. + /// The string or collection must have at least this many characters or items. /// The rules of the member. /// The length. /// The rules of the member. @@ -68,14 +63,7 @@ public static class MemberRulesExtensions public static IMemberRules MinLength(this IMemberRules rules, int min) where TMember : IEnumerable? => rules; - /// The string must have at most this many characters. - /// The rules of the member. - /// The length. - /// The rules of the member. - [ValidationRule(typeof(Rule), nameof(Rule.MaxLength))] - public static IMemberRules MaxLength(this IMemberRules rules, int max) => rules; - - /// The collection must have at most this many items. + /// The string or collection must have at most this many characters or items. /// The rules of the member. /// The length. /// The rules of the member. @@ -83,15 +71,7 @@ public static IMemberRules MinLength(this IMemberRules MaxLength(this IMemberRules rules, int max) where TMember : IEnumerable? => rules; - /// The string must have a number of characters between two bounds. - /// The rules of the member. - /// The least it may have. - /// The most it may have. - /// The rules of the member. - [ValidationRule(typeof(Rule), nameof(Rule.Length))] - public static IMemberRules Length(this IMemberRules rules, int min, int max) => rules; - - /// The collection must have a number of items between two bounds. + /// The string or collection must have a number of characters or items between two bounds. /// The rules of the member. /// The least it may have. /// The most it may have. @@ -106,14 +86,16 @@ public static IMemberRules Length(this IMemberRulesThe pattern's options, a constant. /// The rules of the member. [ValidationRule(typeof(Rule), nameof(Rule.Matches))] - public static IMemberRules Matches(this IMemberRules rules, [StringSyntax(StringSyntaxAttribute.Regex)] string pattern, RegexOptions options = RegexOptions.None) => rules; + public static IMemberRules Matches(this IMemberRules rules, [StringSyntax(StringSyntaxAttribute.Regex)] string pattern, RegexOptions options = RegexOptions.None) + where TMember : IEquatable? => rules; /// The string must match a regular expression. /// The rules of the member. /// The regular expression: a property or method the regular expression generator writes. /// The rules of the member. [ValidationRule(typeof(Rule), nameof(Rule.Matches))] - public static IMemberRules Matches(this IMemberRules rules, Regex pattern) => rules; + public static IMemberRules Matches(this IMemberRules rules, Regex pattern) + where TMember : IEquatable? => rules; /// The member must equal a value. /// The rules of the member. diff --git a/test/Validation.Analyzers.Tests/FunctionValidatorGeneratorTests.cs b/test/Validation.Analyzers.Tests/FunctionValidatorGeneratorTests.cs new file mode 100644 index 00000000000..e9ad8598176 --- /dev/null +++ b/test/Validation.Analyzers.Tests/FunctionValidatorGeneratorTests.cs @@ -0,0 +1,201 @@ +namespace Validation.Analyzers.Tests; + +public class FunctionValidatorGeneratorTests +{ + [Test] + public async Task Should_Write_The_Rules_Of_A_Function_Into_Its_Type() + { + var result = await TestBuilder.Generate( + """ + using System; + using System.Collections.Generic; + using System.Text.RegularExpressions; + using Rocket.Surgery.LaunchPad.Validation; + using Rocket.Surgery.LaunchPad.Validation.Rules; + + namespace Sample.Operations + { + using Sample.Services; + + public enum Kind { Cargo, Crewed } + + public sealed record Engine(string Name, double Thrust); + + public static partial class BuildLauncher + { + public sealed record Request + { + [NotEmpty] + public string Name { get; init; } = ""; + public string? Serial { get; init; } + public Kind Kind { get; init; } + public int? Seats { get; init; } + public DateOnly Built { get; init; } + public DateOnly? Launched { get; init; } + public IReadOnlyList Engines { get; init; } = []; + public string[] Tags { get; init; } = []; + public int Budget { get; init; } + public int Spent { get; init; } + } + + private static readonly Regex SerialPattern = new("^[A-Z]{2}-[0-9]+$"); + + private static bool IsRound(int value) => value % 10 == 0; + + private static void Validate(IValidationBuilder v, ICatalog catalog, TimeProvider time) + { + v.Ensure(x => x.Name).MaxLength(10).WithMessage("{Name} is over {Max}").WithCode("TooLong").Matches("^[A-Z]", RegexOptions.IgnoreCase).StopOnFailure(); + v.Ensure(x => x.Serial).NotNull().Matches(SerialPattern).WithSeverity(ValidationSeverity.Warning); + v.Ensure(x => x.Seats).NotNull().InclusiveBetween(1, 7).When(x => x.Kind == Kind.Crewed); + v.Ensure(x => x.Seats).Null().Unless(x => x.Kind == Kind.Crewed).WithName("Seat count"); + v.Ensure(x => x.Built).LessThanOrEqualTo(_ => DateOnly.FromDateTime(time.GetUtcNow().UtcDateTime)); + v.Ensure(x => x.Launched).GreaterThanOrEqualTo(x => x.Built); + v.Ensure(x => x.Budget).Must(IsRound).Must((request, budget) => budget >= request.Spent).WithCode("Overspent"); + v.EnsureEach(x => x.Tags).NotEmpty().MaxLength(5); + v.EnsureEach( + x => x.Engines, + engine => + { + engine.Ensure(x => x.Thrust).GreaterThan(0); + engine.Ensure(x => x.Name).Must(name => + { + return catalog.IsKnown(name); + }); + } + ); + v.When( + x => x.Kind == Kind.Cargo, + cargo => + { + cargo.Ensure(x => x.Engines).MinLength(1); + cargo.Ensure(x => x).Must(x => x.Spent <= x.Budget * 2).WithCode("WayOverspent"); + } + ); + } + } + } + + namespace Sample.Services + { + public interface ICatalog + { + bool IsKnown(string name); + } + } + """, + true + ); + + await result.ShouldCompileCleanly(); + await Verify(result); + } + + [Test] + public async Task Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits() + { + var result = await TestBuilder.Generate( + """ + using System.Threading; + using System.Threading.Tasks; + using Rocket.Surgery.LaunchPad.Validation; + using Rocket.Surgery.LaunchPad.Validation.Rules; + + namespace Sample; + + internal interface ICatalog + { + ValueTask IsFree(string serial, CancellationToken cancellationToken); + } + + public sealed record Booking(string Serial, string? Pad); + + internal sealed partial class BookingValidator(ICatalog catalog) : IValidator + { + public void Validate(IValidationBuilder v) + { + v.Ensure(x => x.Serial).NotEmpty().MustAsync(catalog.IsFree).WithCode("Taken").StopOnFailure(); + v.Ensure(x => x.Serial).MustAsync(async (serial, ct) => await catalog.IsFree(serial, ct)).When(x => x.Pad is not null); + v.Ensure(x => x.Pad).NotEmpty(); + } + } + + // Validated by attributes, and asynchronous because a member of it is. + public sealed record Manifest([NotEmpty] string Name, [ValidateNested] Booking Booking, [ValidateNested] Booking[] Others); + + public sealed class Schedule + { + public Manifest? Manifest { get; set; } + } + + public static partial class Scheduling + { + // Two functions for one type merge; this one takes the cancellation token. + private static void Validate(IValidationBuilder v) => v.Ensure(x => x.Manifest).NotNull().ValidateNested(); + + private static void Validate(IValidationBuilder v, CancellationToken cancellationToken) => + v.Ensure(x => x).Must(_ => !cancellationToken.IsCancellationRequested); + } + """, + true + ); + + await result.ShouldCompileCleanly(); + await Verify(result); + } + + [Test] + public async Task Should_Report_What_It_Cannot_Read() + { + var result = await TestBuilder.Generate( + """ + using System.Collections.Generic; + using Rocket.Surgery.LaunchPad.Validation; + using Rocket.Surgery.LaunchPad.Validation.Rules; + + public interface INamed { string Name { get; } } + + public sealed record Engine(string Name); + + public sealed record Launcher(string Name, Engine Engine, int Count) : INamed; + + public static class NotPartial + { + private static void Validate(IValidationBuilder v) => v.Ensure(x => x.Name).NotEmpty(); + } + + public partial class Instance + { + private void Validate(IValidationBuilder v) => v.Ensure(x => x.Name).NotEmpty(); + } + + public static partial class Targets + { + private static void Validate(IValidationBuilder v) => v.Ensure(x => x.Name).NotEmpty(); + private static void Validate(IValidationBuilder> v) => v.Ensure(x => x.Count).GreaterThan(0); + } + + public static partial class Bodies + { + private static void Validate(IValidationBuilder v, string prefix) + { + var limit = 3; + if (limit > 2) v.Ensure(x => x.Name).NotEmpty(); + System.Console.WriteLine("never runs"); + v.Ensure(x => x.Engine.Name).NotEmpty(); + v.Ensure(x => x.Name).WithMessage("no rule before it"); + v.Ensure(x => x.Name).NotEmpty().WithMessage(prefix + " is required"); + v.Ensure(x => x.Name).Matches(prefix); + v.Ensure(x => x.Name).Trimmed(); + v.Ensure(x => x.Engine).ValidateNested().When(x => x.Count > 0); + v.Include(); + v.Ensure(x => x.Count).GreaterThan(0); + } + + private static IMemberRules Trimmed(this IMemberRules rules) => rules; + } + """ + ); + + await Verify(result); + } +} diff --git a/test/Validation.Analyzers.Tests/SynchronousValidationAnalyzerTests.cs b/test/Validation.Analyzers.Tests/SynchronousValidationAnalyzerTests.cs new file mode 100644 index 00000000000..6da37bd332a --- /dev/null +++ b/test/Validation.Analyzers.Tests/SynchronousValidationAnalyzerTests.cs @@ -0,0 +1,53 @@ +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 f25d58134c2..20501f0eeda 100644 --- a/test/Validation.Analyzers.Tests/TestBuilder.cs +++ b/test/Validation.Analyzers.Tests/TestBuilder.cs @@ -60,6 +60,20 @@ public static Task Fix(string source) .Build() .GenerateAsync(TestContext.Current!.Execution.CancellationToken); + /// + /// Runs the generator, then on what it wrote and on what that reports. + /// + public static Task GenerateAndFix(string source) + where TAnalyzer : DiagnosticAnalyzer, new() + where TFix : CodeFixProvider, new() => + Create(true) + .WithGenerator() + .AddSource("Input.cs", "#nullable enable\n" + source) + .WithAnalyzer() + .WithCodeFix() + .Build() + .GenerateAsync(TestContext.Current!.Execution.CancellationToken); + /// Checks that what the generator wrote compiles without an error or a warning. public static async Task ShouldCompileCleanly(this GeneratorTestResults result) { diff --git a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read#Bodies.ValidateLauncher.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read#Bodies.ValidateLauncher.g.verified.cs new file mode 100644 index 00000000000..f11426c208a --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read#Bodies.ValidateLauncher.g.verified.cs @@ -0,0 +1,40 @@ +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Bodies.ValidateLauncher.g.cs +// +#nullable enable annotations +#pragma warning disable CS1998 // an asynchronous rule method whose rules all turned out to be synchronous +using System.Collections.Generic; +using Rocket.Surgery.LaunchPad.Validation; +using Rocket.Surgery.LaunchPad.Validation.Rules; + +partial class Bodies +{ + /// + /// The rules Validate declares for . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Name", "NotEmpty", DeclaredBy = nameof(Validate))] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void ValidateLauncher_Name(string __value, string prefix, 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 Validate declares for . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Count", "GreaterThan(0)", DeclaredBy = nameof(Validate))] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void ValidateLauncher_Count(int __value, string prefix, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink __sink) + { + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.GreaterThan(__value, 0)) + { + __sink.Add("Count", "GreaterThan", "{Name} must be greater than {Other}", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Count"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", __value), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Other", 0)); + } + } + } +} 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 new file mode 100644 index 00000000000..e4443c4cee3 --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read#LauncherGeneratedValidator.g.verified.cs @@ -0,0 +1,52 @@ +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/LauncherGeneratedValidator.g.cs +// +#nullable enable + +/// +/// Validates a : every rule declared for it, by the attributes of its members and by the +/// functions and classes that validate it. +/// +[global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Launcher))] +public sealed class LauncherGeneratedValidator + : global::Rocket.Surgery.LaunchPad.Validation.IValidate +{ + 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; + + /// + /// 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 LauncherGeneratedValidator(string prefix, global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null, global::System.IServiceProvider? services = null) + { + _prefix = prefix; + _messages = messages; + _services = services; + } + + /// + public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Launcher value) + { + global::System.ArgumentNullException.ThrowIfNull(value); + var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); + global::Bodies.ValidateLauncher_Name(value.Name, _prefix, ref sink); + + if (value.Engine is { } __engine) + { + var path = sink.Enter("Engine"); + sink.Add(EngineValidator.Validate(__engine)); + sink.Leave(path); + } + + global::Bodies.ValidateLauncher_Count(value.Count, _prefix, ref sink); + return sink.ToResult(); + } + + 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."); +} 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 new file mode 100644 index 00000000000..7b4e73ebc17 --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Report_What_It_Cannot_Read.verified.txt @@ -0,0 +1,288 @@ +{ + FinalDiagnostics: [ + { + Id: LPAD3109, + Title: The type that declares rules must be partial, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (13,24)-(13,32), + MessageFormat: '{0}' must be partial, and public or internal, and not generic: the rules its Validate declares are written into it, + Message: 'NotPartial' must be partial, and public or internal, and not generic: the rules its Validate declares are written into it, + Category: LaunchPad.Validation + }, + { + Id: LPAD3108, + Title: The generator can't read this rule, + Severity: Error, + 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, + Category: LaunchPad.Validation + }, + { + Id: LPAD3110, + Title: Rules can't be declared for this type yet, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (23,24)-(23,32), + MessageFormat: Validate declares rules for '{0}', {1}, + Message: Validate declares rules for 'INamed', which is not a class, a struct or a record: the rules of interfaces are not written yet, + Category: LaunchPad.Validation + }, + { + Id: LPAD3110, + Title: Rules can't be declared for this type yet, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (24,24)-(24,32), + MessageFormat: Validate declares rules for '{0}', {1}, + Message: Validate declares rules for 'List', which another assembly declares: rules for the types of other assemblies are not written yet, + Category: LaunchPad.Validation + }, + { + Id: LPAD3107, + Title: A Validate body may only call the builder, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (31,8)-(31,22), + MessageFormat: This is not a call on '{0}': a Validate body is read at build time and never runs, so it can only declare rules, + Message: This is not a call on 'v': a Validate body is read at build time and never runs, so it can only declare rules, + Category: LaunchPad.Validation + }, + { + Id: LPAD3107, + Title: A Validate body may only call the builder, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (32,8)-(32,56), + MessageFormat: This is not a call on '{0}': a Validate body is read at build time and never runs, so it can only declare rules, + Message: This is not a call on 'v': a Validate body is read at build time and never runs, so it can only declare rules, + Category: LaunchPad.Validation + }, + { + Id: LPAD3107, + Title: A Validate body may only call the builder, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (33,8)-(33,46), + MessageFormat: This is not a call on '{0}': a Validate body is read at build time and never runs, so it can only declare rules, + Message: This is not a call on 'v': a Validate body is read at build time and never runs, so it can only declare rules, + Category: LaunchPad.Validation + }, + { + Id: LPAD3108, + Title: The generator can't read this rule, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (34,17)-(34,35), + MessageFormat: {0}, + Message: A rule is about one member, chosen with x => x.Member, or about the whole value, with x => x, + Category: LaunchPad.Validation + }, + { + Id: LPAD3108, + Title: The generator can't read this rule, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (35,8)-(35,62), + MessageFormat: {0}, + Message: WithMessage changes the rule before it, and there is none, + Category: LaunchPad.Validation + }, + { + Id: LPAD3111, + Title: The argument must be a constant, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (36,53)-(36,76), + MessageFormat: {0} takes a constant: the generator writes it into the validator, + Message: WithMessage takes a constant: the generator writes it into the validator, + Category: LaunchPad.Validation + }, + { + Id: LPAD3111, + Title: The argument must be a constant, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (37,38)-(37,44), + MessageFormat: {0} takes a constant: the generator writes it into the validator, + Message: Matches takes a constant: the generator writes it into the validator, + Category: LaunchPad.Validation + }, + { + Id: LPAD3108, + Title: The generator can't read this rule, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (38,8)-(38,39), + MessageFormat: {0}, + Message: 'Trimmed' is not a rule: the extension method that declares one carries a [ValidationRule], + Category: LaunchPad.Validation + }, + { + Id: LPAD3108, + Title: The generator can't read this rule, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (39,8)-(39,71), + MessageFormat: {0}, + Message: A member validated with ValidateNested can't be under a condition yet, + Category: LaunchPad.Validation + }, + { + Id: LPAD3108, + Title: The generator can't read this rule, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (40,8)-(40,27), + MessageFormat: {0}, + Message: Include is not written yet: it comes with the rules of base classes and of other types, + Category: LaunchPad.Validation + } + ], + GeneratorDiagnostics: { + Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator: [ + { + Id: LPAD3109, + Title: The type that declares rules must be partial, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (13,24)-(13,32), + MessageFormat: '{0}' must be partial, and public or internal, and not generic: the rules its Validate declares are written into it, + Message: 'NotPartial' must be partial, and public or internal, and not generic: the rules its Validate declares are written into it, + Category: LaunchPad.Validation + }, + { + Id: LPAD3108, + Title: The generator can't read this rule, + Severity: Error, + 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, + Category: LaunchPad.Validation + }, + { + Id: LPAD3110, + Title: Rules can't be declared for this type yet, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (23,24)-(23,32), + MessageFormat: Validate declares rules for '{0}', {1}, + Message: Validate declares rules for 'INamed', which is not a class, a struct or a record: the rules of interfaces are not written yet, + Category: LaunchPad.Validation + }, + { + Id: LPAD3110, + Title: Rules can't be declared for this type yet, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (24,24)-(24,32), + MessageFormat: Validate declares rules for '{0}', {1}, + Message: Validate declares rules for 'List', which another assembly declares: rules for the types of other assemblies are not written yet, + Category: LaunchPad.Validation + }, + { + Id: LPAD3107, + Title: A Validate body may only call the builder, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (31,8)-(31,22), + MessageFormat: This is not a call on '{0}': a Validate body is read at build time and never runs, so it can only declare rules, + Message: This is not a call on 'v': a Validate body is read at build time and never runs, so it can only declare rules, + Category: LaunchPad.Validation + }, + { + Id: LPAD3107, + Title: A Validate body may only call the builder, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (32,8)-(32,56), + MessageFormat: This is not a call on '{0}': a Validate body is read at build time and never runs, so it can only declare rules, + Message: This is not a call on 'v': a Validate body is read at build time and never runs, so it can only declare rules, + Category: LaunchPad.Validation + }, + { + Id: LPAD3107, + Title: A Validate body may only call the builder, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (33,8)-(33,46), + MessageFormat: This is not a call on '{0}': a Validate body is read at build time and never runs, so it can only declare rules, + Message: This is not a call on 'v': a Validate body is read at build time and never runs, so it can only declare rules, + Category: LaunchPad.Validation + }, + { + Id: LPAD3108, + Title: The generator can't read this rule, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (34,17)-(34,35), + MessageFormat: {0}, + Message: A rule is about one member, chosen with x => x.Member, or about the whole value, with x => x, + Category: LaunchPad.Validation + }, + { + Id: LPAD3108, + Title: The generator can't read this rule, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (35,8)-(35,62), + MessageFormat: {0}, + Message: WithMessage changes the rule before it, and there is none, + Category: LaunchPad.Validation + }, + { + Id: LPAD3111, + Title: The argument must be a constant, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (36,53)-(36,76), + MessageFormat: {0} takes a constant: the generator writes it into the validator, + Message: WithMessage takes a constant: the generator writes it into the validator, + Category: LaunchPad.Validation + }, + { + Id: LPAD3111, + Title: The argument must be a constant, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (37,38)-(37,44), + MessageFormat: {0} takes a constant: the generator writes it into the validator, + Message: Matches takes a constant: the generator writes it into the validator, + Category: LaunchPad.Validation + }, + { + Id: LPAD3108, + Title: The generator can't read this rule, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (38,8)-(38,39), + MessageFormat: {0}, + Message: 'Trimmed' is not a rule: the extension method that declares one carries a [ValidationRule], + Category: LaunchPad.Validation + }, + { + Id: LPAD3108, + Title: The generator can't read this rule, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (39,8)-(39,71), + MessageFormat: {0}, + Message: A member validated with ValidateNested can't be under a condition yet, + Category: LaunchPad.Validation + }, + { + Id: LPAD3108, + Title: The generator can't read this rule, + Severity: Error, + WarningLevel: 0, + Location: Input0.cs: (40,8)-(40,27), + MessageFormat: {0}, + Message: Include is not written yet: it comes with the rules of base classes and of other types, + Category: LaunchPad.Validation + } + ] + } +} \ No newline at end of file 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 new file mode 100644 index 00000000000..db0977ebf8b --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#LaunchPadValidators.g.verified.cs @@ -0,0 +1,30 @@ +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/LaunchPadValidators.g.cs +// +#nullable enable + +[assembly: global::Rocket.Surgery.LaunchPad.Validation.ValidatorAssembly(typeof(global::Microsoft.Extensions.DependencyInjection.ApplicationValidatorsServiceCollectionExtensions), "AddApplicationValidators")] + +namespace Microsoft.Extensions.DependencyInjection +{ + /// + /// Registers the validators of Application. + /// + 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, and as its IValidate unless one of the type's rules waits. A + /// validator whose rules take services is scoped; the others are singletons. + /// + /// The services. + /// The services. + public static global::Microsoft.Extensions.DependencyInjection.IServiceCollection AddApplicationValidators(this global::Microsoft.Extensions.DependencyInjection.IServiceCollection 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, global::Sample.ManifestGeneratedValidator>(services); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddScoped, global::Sample.ScheduleGeneratedValidator>(services); + 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 new file mode 100644 index 00000000000..f87e4b3c0ce --- /dev/null +++ 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 @@ -0,0 +1,39 @@ +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.BookingGeneratedValidator.g.cs +// +#nullable enable + +namespace Sample +{ + /// + /// Validates a : every rule declared for it, by the attributes of its members and by the + /// functions and classes that validate it. + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Booking))] + internal sealed class BookingGeneratedValidator + : global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync + { + private readonly global::Sample.BookingValidator _bookingValidator; + private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; + + /// + /// Creates the validator. + /// + /// What the rules declared for the type take. + /// What replaces the rules' messages, if anything does. + public BookingGeneratedValidator(global::Sample.BookingValidator bookingValidator, global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) + { + _bookingValidator = bookingValidator; + _messages = messages; + } + + /// + public async global::System.Threading.Tasks.ValueTask ValidateAsync(global::Sample.Booking value, global::System.Threading.CancellationToken cancellationToken = default) + { + global::System.ArgumentNullException.ThrowIfNull(value); + var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); + sink = await _bookingValidator.ValidateBooking_Serial(value, value.Serial, sink, cancellationToken).ConfigureAwait(false); + _bookingValidator.ValidateBooking_Pad(value.Pad, ref sink); + return sink.ToResult(); + } + } +} diff --git a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.BookingValidator.ValidateBooking.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.BookingValidator.ValidateBooking.g.verified.cs new file mode 100644 index 00000000000..ca5cd5f166a --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.BookingValidator.ValidateBooking.g.verified.cs @@ -0,0 +1,59 @@ +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.BookingValidator.ValidateBooking.g.cs +// +#nullable enable annotations +#pragma warning disable CS1998 // an asynchronous rule method whose rules all turned out to be synchronous +using System.Threading; +using System.Threading.Tasks; +using Rocket.Surgery.LaunchPad.Validation; +using Rocket.Surgery.LaunchPad.Validation.Rules; + +namespace Sample +{ + partial class BookingValidator + { + /// + /// The rules Validate declares for . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Serial", "NotEmpty", "MustAsync", "MustAsync", ReadsValue = true, DeclaredBy = nameof(Validate))] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + internal async global::System.Threading.Tasks.ValueTask ValidateBooking_Serial(global::Sample.Booking __instance, string __value, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink __sink, global::System.Threading.CancellationToken __cancellationToken) + { + { + var __start = __sink.Count; + if (__sink.Count == __start && !global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.NotEmpty(__value)) + { + __sink.Add("Serial", "NotEmpty", "{Name} must not be empty", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Serial"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", __value)); + } + if (__sink.Count == __start && !( await catalog.IsFree(__value, __cancellationToken).ConfigureAwait(false) )) + { + __sink.Add("Serial", "Taken", "{Name} is not valid", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Serial"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", __value)); + } + } + + { + async global::System.Threading.Tasks.ValueTask __rule0(string serial, global::System.Threading.CancellationToken ct) => await catalog.IsFree(serial, ct); + bool __rule1(global::Sample.Booking x) => x.Pad is not null; + if (__rule1(__instance) && !( await __rule0(__value, __cancellationToken).ConfigureAwait(false) )) + { + __sink.Add("Serial", "Must", "{Name} is not valid", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Serial"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", __value)); + } + } + return __sink; + } + + /// + /// The rules Validate declares for . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Pad", "NotEmpty", DeclaredBy = nameof(Validate))] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + internal void ValidateBooking_Pad(string? __value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink __sink) + { + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.NotEmpty(__value)) + { + __sink.Add("Pad", "NotEmpty", "{Name} must not be empty", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Pad"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", __value)); + } + } + } + } +} 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 new file mode 100644 index 00000000000..52ade42b645 --- /dev/null +++ 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 @@ -0,0 +1,84 @@ +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.ManifestGeneratedValidator.g.cs +// +#nullable enable + +namespace Sample +{ + /// + /// Validates a : every rule declared for it, by the attributes of its members and by the + /// functions and classes that validate it. + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Manifest))] + public sealed class ManifestGeneratedValidator + : global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync + { + private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; + private readonly global::System.IServiceProvider? _services; + private global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync? _bookingValidator; + + /// + /// Creates the validator. + /// + /// 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) + { + _messages = messages; + _services = services; + } + + /// + public async global::System.Threading.Tasks.ValueTask ValidateAsync(global::Sample.Manifest value, global::System.Threading.CancellationToken cancellationToken = default) + { + global::System.ArgumentNullException.ThrowIfNull(value); + var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); + EnsureName(value.Name, ref sink); + + if (value.Booking is { } __booking) + { + var path = sink.Enter("Booking"); + sink.Add(await BookingValidator.ValidateAsync(__booking, cancellationToken).ConfigureAwait(false)); + sink.Leave(path); + } + + + if (value.Others is { } __others) + { + var path = sink.Enter("Others"); + var index = 0; + foreach (var item in __others) + { + if (item is { } present) + { + var itemPath = sink.Enter(index); + sink.Add(await BookingValidator.ValidateAsync(present, cancellationToken).ConfigureAwait(false)); + sink.Leave(itemPath); + } + + index++; + } + + sink.Leave(path); + } + + return sink.ToResult(); + } + + 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."); + + /// + /// 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)); + } + } + } +} 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 new file mode 100644 index 00000000000..ac8d89835d9 --- /dev/null +++ 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 @@ -0,0 +1,52 @@ +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.ScheduleGeneratedValidator.g.cs +// +#nullable enable + +namespace Sample +{ + /// + /// Validates a : every rule declared for it, by the attributes of its members and by the + /// functions and classes that validate it. + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Schedule))] + public sealed class ScheduleGeneratedValidator + : global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync + { + private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; + private readonly global::System.IServiceProvider? _services; + private global::Rocket.Surgery.LaunchPad.Validation.IValidateAsync? _manifestValidator; + + /// + /// Creates the validator. + /// + /// 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) + { + _messages = messages; + _services = services; + } + + /// + public async global::System.Threading.Tasks.ValueTask ValidateAsync(global::Sample.Schedule value, global::System.Threading.CancellationToken cancellationToken = default) + { + global::System.ArgumentNullException.ThrowIfNull(value); + var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); + global::Sample.Scheduling.ValidateSchedule_Manifest(value.Manifest, ref sink); + + if (value.Manifest is { } __manifest) + { + var path = sink.Enter("Manifest"); + sink.Add(await ManifestValidator.ValidateAsync(__manifest, cancellationToken).ConfigureAwait(false)); + sink.Leave(path); + } + + global::Sample.Scheduling.ValidateSchedule1(value, cancellationToken, ref sink); + return sink.ToResult(); + } + + 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."); + } +} diff --git a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.Scheduling.ValidateSchedule.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.Scheduling.ValidateSchedule.g.verified.cs new file mode 100644 index 00000000000..20e44bb599e --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.Scheduling.ValidateSchedule.g.verified.cs @@ -0,0 +1,29 @@ +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.Scheduling.ValidateSchedule.g.cs +// +#nullable enable annotations +#pragma warning disable CS1998 // an asynchronous rule method whose rules all turned out to be synchronous +using System.Threading; +using System.Threading.Tasks; +using Rocket.Surgery.LaunchPad.Validation; +using Rocket.Surgery.LaunchPad.Validation.Rules; + +namespace Sample +{ + partial class Scheduling + { + /// + /// The rules Validate declares for . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Manifest", "NotNull", DeclaredBy = nameof(Validate))] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void ValidateSchedule_Manifest(global::Sample.Manifest? __value, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink __sink) + { + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.NotNull(__value)) + { + __sink.Add("Manifest", "NotNull", "{Name} is required", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Manifest"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", __value)); + } + } + } + } +} diff --git a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.Scheduling.ValidateSchedule1.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.Scheduling.ValidateSchedule1.g.verified.cs new file mode 100644 index 00000000000..5a9d2033cf4 --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits#Sample.Scheduling.ValidateSchedule1.g.verified.cs @@ -0,0 +1,30 @@ +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.Scheduling.ValidateSchedule1.g.cs +// +#nullable enable annotations +#pragma warning disable CS1998 // an asynchronous rule method whose rules all turned out to be synchronous +using System.Threading; +using System.Threading.Tasks; +using Rocket.Surgery.LaunchPad.Validation; +using Rocket.Surgery.LaunchPad.Validation.Rules; + +namespace Sample +{ + partial class Scheduling + { + /// + /// The rules Validate declares for a as a whole. + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("", "Must", ReadsValue = true, DeclaredBy = nameof(Validate))] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void ValidateSchedule1(global::Sample.Schedule __instance, global::System.Threading.CancellationToken cancellationToken, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink __sink) + { + { + bool __rule0(global::Sample.Schedule __discard0) => !cancellationToken.IsCancellationRequested; + if (!__rule0(__instance)) + { + __sink.Add("", "Must", "{Name} is not valid", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", ""), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", __instance)); + } + } + } + } +} diff --git a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits.verified.txt b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits.verified.txt new file mode 100644 index 00000000000..b814e7ed8ef --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_An_Asynchronous_Validator_For_A_Class_With_A_Rule_That_Waits.verified.txt @@ -0,0 +1,6 @@ +{ + FinalDiagnostics: [], + GeneratorDiagnostics: { + Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator: [] + } +} \ No newline at end of file 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 new file mode 100644 index 00000000000..192ea7ffa5b --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type#LaunchPadValidators.g.verified.cs @@ -0,0 +1,28 @@ +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/LaunchPadValidators.g.cs +// +#nullable enable + +[assembly: global::Rocket.Surgery.LaunchPad.Validation.ValidatorAssembly(typeof(global::Microsoft.Extensions.DependencyInjection.ApplicationValidatorsServiceCollectionExtensions), "AddApplicationValidators")] + +namespace Microsoft.Extensions.DependencyInjection +{ + /// + /// Registers the validators of Application. + /// + 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, and as its IValidate unless one of the type's rules waits. A + /// validator whose rules take services is scoped; the others are singletons. + /// + /// The services. + /// The services. + public static global::Microsoft.Extensions.DependencyInjection.IServiceCollection AddApplicationValidators(this global::Microsoft.Extensions.DependencyInjection.IServiceCollection 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))!); + return services; + } + } +} diff --git a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type#Sample.Operations.BuildLauncher.ValidateBuildLauncher_Request.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type#Sample.Operations.BuildLauncher.ValidateBuildLauncher_Request.g.verified.cs new file mode 100644 index 00000000000..edeba608507 --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type#Sample.Operations.BuildLauncher.ValidateBuildLauncher_Request.g.verified.cs @@ -0,0 +1,237 @@ +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.Operations.BuildLauncher.ValidateBuildLauncher_Request.g.cs +// +#nullable enable annotations +#pragma warning disable CS1998 // an asynchronous rule method whose rules all turned out to be synchronous +using System; +using System.Collections.Generic; +using System.Text.RegularExpressions; +using Rocket.Surgery.LaunchPad.Validation; +using Rocket.Surgery.LaunchPad.Validation.Rules; + +namespace Sample.Operations +{ + using Sample.Services; + partial class BuildLauncher + { + private static readonly global::System.Text.RegularExpressions.Regex ValidateBuildLauncher_Request_NamePattern0 = new("^[A-Z]", (global::System.Text.RegularExpressions.RegexOptions)1 | global::System.Text.RegularExpressions.RegexOptions.CultureInvariant, global::System.TimeSpan.FromSeconds(2)); + + /// + /// The rules Validate declares for . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Name", "MaxLength(10)", "Matches(\"^[A-Z]\")", DeclaredBy = nameof(Validate))] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void ValidateBuildLauncher_Request_Name(string __value, global::Sample.Services.ICatalog catalog, global::System.TimeProvider time, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink __sink) + { + { + var __start = __sink.Count; + if (__sink.Count == __start && !global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.MaxLength(__value, 10)) + { + __sink.Add("Name", "TooLong", "{Name} is over {Max}", 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), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Max", 10)); + } + if (__sink.Count == __start && !global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.Matches(__value, ValidateBuildLauncher_Request_NamePattern0)) + { + __sink.Add("Name", "Matches", "{Name} is not in the expected format", 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 Validate declares for . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Serial", "NotNull", "Matches(SerialPattern)", DeclaredBy = nameof(Validate))] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void ValidateBuildLauncher_Request_Serial(string? __value, global::Sample.Services.ICatalog catalog, global::System.TimeProvider time, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink __sink) + { + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.NotNull(__value)) + { + __sink.Add("Serial", "NotNull", "{Name} is required", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Serial"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", __value)); + } + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.Matches(__value, SerialPattern)) + { + __sink.Add("Serial", "Matches", "{Name} is not in the expected format", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Warning, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Serial"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", __value)); + } + } + } + + /// + /// The rules Validate declares for . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Seats", "NotNull", "InclusiveBetween(1, 7)", "Null", ReadsValue = true, DeclaredBy = nameof(Validate))] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void ValidateBuildLauncher_Request_Seats(global::Sample.Operations.BuildLauncher.Request __instance, int? __value, global::Sample.Services.ICatalog catalog, global::System.TimeProvider time, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink __sink) + { + { + bool __rule0(global::Sample.Operations.BuildLauncher.Request x) => x.Kind == Kind.Crewed; + if (__rule0(__instance) && !global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.NotNull(__value)) + { + __sink.Add("Seats", "NotNull", "{Name} is required", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Seats"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", __value)); + } + if (__rule0(__instance) && !global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.InclusiveBetween(__value, 1, 7)) + { + __sink.Add("Seats", "InclusiveBetween", "{Name} must be between {Min} and {Max}", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Seats"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", __value), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Min", 1), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Max", 7)); + } + } + + { + bool __rule1(global::Sample.Operations.BuildLauncher.Request x) => x.Kind == Kind.Crewed; + if (!__rule1(__instance) && !global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.Null(__value)) + { + __sink.Add("Seats", "Null", "{Name} must not be set", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Seat count"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", __value)); + } + } + } + + /// + /// The rules Validate declares for . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Built", "LessThanOrEqualTo(_ => DateOnly.FromDateTime(time.GetUtcNow().UtcDateTime))", ReadsValue = true, DeclaredBy = nameof(Validate))] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void ValidateBuildLauncher_Request_Built(global::Sample.Operations.BuildLauncher.Request __instance, global::System.DateOnly __value, global::Sample.Services.ICatalog catalog, global::System.TimeProvider time, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink __sink) + { + { + global::System.DateOnly __rule0(global::Sample.Operations.BuildLauncher.Request __discard0) => DateOnly.FromDateTime(time.GetUtcNow().UtcDateTime); + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.LessThanOrEqualTo(__value, __rule0(__instance))) + { + __sink.Add("Built", "LessThanOrEqualTo", "{Name} must be less than or equal to {Other}", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Built"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", __value), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Other", __rule0(__instance))); + } + } + } + + /// + /// The rules Validate declares for . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Launched", "GreaterThanOrEqualTo(x => x.Built)", ReadsValue = true, DeclaredBy = nameof(Validate))] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void ValidateBuildLauncher_Request_Launched(global::Sample.Operations.BuildLauncher.Request __instance, global::System.DateOnly? __value, global::Sample.Services.ICatalog catalog, global::System.TimeProvider time, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink __sink) + { + { + global::System.DateOnly __rule0(global::Sample.Operations.BuildLauncher.Request x) => x.Built; + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.GreaterThanOrEqualTo(__value, __rule0(__instance))) + { + __sink.Add("Launched", "GreaterThanOrEqualTo", "{Name} must be greater than or equal to {Other}", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Launched"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", __value), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Other", __rule0(__instance))); + } + } + } + + /// + /// The rules Validate declares for . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Budget", "Must", "Must", ReadsValue = true, DeclaredBy = nameof(Validate))] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void ValidateBuildLauncher_Request_Budget(global::Sample.Operations.BuildLauncher.Request __instance, int __value, global::Sample.Services.ICatalog catalog, global::System.TimeProvider time, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink __sink) + { + { + bool __rule0(global::Sample.Operations.BuildLauncher.Request request, int budget) => budget >= request.Spent; + if (!IsRound(__value)) + { + __sink.Add("Budget", "Must", "{Name} is not valid", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Budget"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", __value)); + } + if (!__rule0(__instance, __value)) + { + __sink.Add("Budget", "Overspent", "{Name} is not valid", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Budget"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", __value)); + } + } + } + + /// + /// The rules Validate declares for . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Tags", "NotEmpty", "MaxLength(5)", DeclaredBy = nameof(Validate))] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void ValidateBuildLauncher_Request_Tags(string[] __value, global::Sample.Services.ICatalog catalog, global::System.TimeProvider time, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink __sink) + { + if (__value is { } __items1) + { + var __path1 = __sink.Enter("Tags"); + var __index1 = 0; + foreach (var __item1 in __items1) + { + var __itemPath1 = __sink.Enter(__index1); + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.NotEmpty(__item1)) + { + __sink.Add("", "NotEmpty", "{Name} must not be empty", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Tags"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", __item1)); + } + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.MaxLength(__item1, 5)) + { + __sink.Add("", "MaxLength", "{Name} must be at most {Max} characters long", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Tags"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", __item1), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Max", 5)); + } + } + __sink.Leave(__itemPath1); + __index1++; + } + + __sink.Leave(__path1); + } + } + + /// + /// The rules Validate declares for . + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("Engines", "GreaterThan(0)", "Must", "EnsureEach", "MinLength(1)", ReadsValue = true, DeclaredBy = nameof(Validate))] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void ValidateBuildLauncher_Request_Engines(global::Sample.Operations.BuildLauncher.Request __instance, global::System.Collections.Generic.IReadOnlyList __value, global::Sample.Services.ICatalog catalog, global::System.TimeProvider time, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink __sink) + { + if (__value is { } __items2) + { + var __path2 = __sink.Enter("Engines"); + var __index2 = 0; + foreach (var __item2 in __items2) + { + var __itemPath2 = __sink.Enter(__index2); + if (__item2 is { } __present2) + { + { + if (!global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.GreaterThan(__present2.Thrust, 0)) + { + __sink.Add("Thrust", "GreaterThan", "{Name} must be greater than {Other}", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Thrust"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", __present2.Thrust), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Other", 0)); + } + } + + { + bool __rule0(string name) + { + return catalog.IsKnown(name); + } + if (!__rule0(__present2.Name)) + { + __sink.Add("Name", "Must", "{Name} is not valid", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Name"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", __present2.Name)); + } + } + + } + __sink.Leave(__itemPath2); + __index2++; + } + + __sink.Leave(__path2); + } + + { + bool __rule1(global::Sample.Operations.BuildLauncher.Request x) => x.Kind == Kind.Cargo; + if (__rule1(__instance) && !global::Rocket.Surgery.LaunchPad.Validation.Rules.Rule.MinLength(__value, 1)) + { + __sink.Add("Engines", "MinLength", "{Name} must have at least {Min} items", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", "Engines"), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", __value), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Min", 1)); + } + } + } + + /// + /// The rules Validate declares for a as a whole. + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedRule("", "Must", ReadsValue = true, DeclaredBy = nameof(Validate))] + [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] + public static void ValidateBuildLauncher_Request(global::Sample.Operations.BuildLauncher.Request __instance, global::Sample.Services.ICatalog catalog, global::System.TimeProvider time, ref global::Rocket.Surgery.LaunchPad.Validation.ValidationSink __sink) + { + { + bool __rule0(global::Sample.Operations.BuildLauncher.Request x) => x.Spent <= x.Budget * 2; + bool __rule1(global::Sample.Operations.BuildLauncher.Request x) => x.Kind == Kind.Cargo; + if (__rule1(__instance) && !__rule0(__instance)) + { + __sink.Add("", "WayOverspent", "{Name} is not valid", global::Rocket.Surgery.LaunchPad.Validation.ValidationSeverity.Error, global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Name", ""), global::Rocket.Surgery.LaunchPad.Validation.ValidationSink.Argument("Value", __instance)); + } + } + } + } +} 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 new file mode 100644 index 00000000000..a1d78cebb16 --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type#Sample.Operations.BuildLauncher_RequestGeneratedValidator.g.verified.cs @@ -0,0 +1,63 @@ +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.Operations.BuildLauncher_RequestGeneratedValidator.g.cs +// +#nullable enable + +namespace Sample.Operations +{ + /// + /// Validates a : every rule declared for it, by the attributes of its members and by the + /// functions and classes that validate it. + /// + [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Operations.BuildLauncher.Request))] + public sealed class BuildLauncher_RequestGeneratedValidator + : global::Rocket.Surgery.LaunchPad.Validation.IValidate + { + private readonly global::Sample.Services.ICatalog _catalog; + private readonly global::System.TimeProvider _time; + private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; + + /// + /// 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. + public BuildLauncher_RequestGeneratedValidator(global::Sample.Services.ICatalog catalog, global::System.TimeProvider time, global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) + { + _catalog = catalog; + _time = time; + _messages = messages; + } + + /// + public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Operations.BuildLauncher.Request value) + { + global::System.ArgumentNullException.ThrowIfNull(value); + var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); + EnsureName(value.Name, ref sink); + global::Sample.Operations.BuildLauncher.ValidateBuildLauncher_Request_Name(value.Name, _catalog, _time, ref sink); + global::Sample.Operations.BuildLauncher.ValidateBuildLauncher_Request_Serial(value.Serial, _catalog, _time, ref sink); + global::Sample.Operations.BuildLauncher.ValidateBuildLauncher_Request_Seats(value, value.Seats, _catalog, _time, ref sink); + global::Sample.Operations.BuildLauncher.ValidateBuildLauncher_Request_Built(value, value.Built, _catalog, _time, ref sink); + global::Sample.Operations.BuildLauncher.ValidateBuildLauncher_Request_Launched(value, value.Launched, _catalog, _time, ref sink); + global::Sample.Operations.BuildLauncher.ValidateBuildLauncher_Request_Budget(value, value.Budget, _catalog, _time, ref sink); + global::Sample.Operations.BuildLauncher.ValidateBuildLauncher_Request_Tags(value.Tags, _catalog, _time, ref sink); + global::Sample.Operations.BuildLauncher.ValidateBuildLauncher_Request_Engines(value, value.Engines, _catalog, _time, ref sink); + global::Sample.Operations.BuildLauncher.ValidateBuildLauncher_Request(value, _catalog, _time, ref sink); + return sink.ToResult(); + } + + /// + /// 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)); + } + } + } +} diff --git a/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type.verified.txt b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type.verified.txt new file mode 100644 index 00000000000..b814e7ed8ef --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/FunctionValidatorGeneratorTests.Should_Write_The_Rules_Of_A_Function_Into_Its_Type.verified.txt @@ -0,0 +1,6 @@ +{ + FinalDiagnostics: [], + GeneratorDiagnostics: { + Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator: [] + } +} \ No newline at end of file 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 new file mode 100644 index 00000000000..3bf09c068cf --- /dev/null +++ b/test/Validation.Analyzers.Tests/snapshots/SynchronousValidationAnalyzerTests.Should_Report_The_Synchronous_Validator_Of_An_Asynchronous_Type_And_Make_Its_Use_Asynchronous.verified.txt @@ -0,0 +1,55 @@ +{ + 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#Account.Validator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Compile_The_DataAnnotations_Attributes#AccountGeneratedValidator.g.verified.cs similarity index 97% rename from test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Compile_The_DataAnnotations_Attributes#Account.Validator.g.verified.cs rename to test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Compile_The_DataAnnotations_Attributes#AccountGeneratedValidator.g.verified.cs index 2db38f3feca..a33e0d970ff 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Compile_The_DataAnnotations_Attributes#Account.Validator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Compile_The_DataAnnotations_Attributes#AccountGeneratedValidator.g.verified.cs @@ -1,12 +1,13 @@ -//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Account.Validator.g.cs +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/AccountGeneratedValidator.g.cs // #nullable enable /// -/// Validates a : the rules its members carry as attributes. +/// Validates a : every rule declared for it, by the attributes of its members and by the +/// functions and classes that validate it. /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Account))] -public sealed partial class AccountValidator +public sealed class AccountGeneratedValidator : global::Rocket.Surgery.LaunchPad.Validation.IValidate { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -18,7 +19,7 @@ public sealed partial class AccountValidator /// Creates the validator. /// /// What replaces the rules' messages, if anything does. - public AccountValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; + public AccountGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Account value) diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Named.Validator.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 similarity index 82% rename from test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Named.Validator.g.verified.cs rename to 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 45f4e394b93..72fd6b03213 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Named.Validator.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 @@ -1,14 +1,15 @@ -//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.Named.Validator.g.cs +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.NamedGeneratedValidator.g.cs // #nullable enable namespace Sample { /// - /// Validates a : the rules its members carry as attributes. + /// Validates a : every rule declared for it, by the attributes of its members and by the + /// functions and classes that validate it. /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Named))] - public sealed partial class NamedValidator + public sealed class NamedGeneratedValidator : global::Rocket.Surgery.LaunchPad.Validation.IValidate { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -17,7 +18,7 @@ public sealed partial class NamedValidator /// Creates the validator. /// /// What replaces the rules' messages, if anything does. - public NamedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; + public NamedGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Named 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_Inner.Validator.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 similarity index 83% rename from test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Outer_Inner.Validator.g.verified.cs rename to 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 11eb69902ca..63f1c3428c4 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Outer_Inner.Validator.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 @@ -1,14 +1,15 @@ -//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.Outer_Inner.Validator.g.cs +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.Outer_InnerGeneratedValidator.g.cs // #nullable enable namespace Sample { /// - /// Validates a : the rules its members carry as attributes. + /// Validates a : every rule declared for it, by the attributes of its members and by the + /// functions and classes that validate it. /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Outer.Inner))] - internal sealed partial class Outer_InnerValidator + internal sealed class Outer_InnerGeneratedValidator : global::Rocket.Surgery.LaunchPad.Validation.IValidate { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -17,7 +18,7 @@ internal sealed partial class Outer_InnerValidator /// Creates the validator. /// /// What replaces the rules' messages, if anything does. - public Outer_InnerValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; + public Outer_InnerGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Outer.Inner value) diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Position.Validator.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 similarity index 89% rename from test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Position.Validator.g.verified.cs rename to 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 1e9989eea3d..57ac36db981 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Position.Validator.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 @@ -1,14 +1,15 @@ -//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.Position.Validator.g.cs +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.PositionGeneratedValidator.g.cs // #nullable enable namespace Sample { /// - /// Validates a : the rules its members carry as attributes. + /// Validates a : every rule declared for it, by the attributes of its members and by the + /// functions and classes that validate it. /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Position))] - public sealed partial class PositionValidator + public sealed class PositionGeneratedValidator : global::Rocket.Surgery.LaunchPad.Validation.IValidate { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -17,7 +18,7 @@ public sealed partial class PositionValidator /// Creates the validator. /// /// What replaces the rules' messages, if anything does. - public PositionValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; + public PositionGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Position value) diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Stage.Validator.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 similarity index 88% rename from test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Stage.Validator.g.verified.cs rename to 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 1863ef7ae84..dce984dfb23 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Read_The_Attributes_Of_A_Record_Parameter_And_Of_A_Base_Class#Sample.Stage.Validator.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 @@ -1,14 +1,15 @@ -//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.Stage.Validator.g.cs +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.StageGeneratedValidator.g.cs // #nullable enable namespace Sample { /// - /// Validates a : the rules its members carry as attributes. + /// Validates a : every rule declared for it, by the attributes of its members and by the + /// functions and classes that validate it. /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Stage))] - public sealed partial class StageValidator + public sealed class StageGeneratedValidator : global::Rocket.Surgery.LaunchPad.Validation.IValidate { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -17,7 +18,7 @@ public sealed partial class StageValidator /// Creates the validator. /// /// What replaces the rules' messages, if anything does. - public StageValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; + public StageGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Stage 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 2ba80880c2a..f92325e49ff 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,17 +13,18 @@ public static class ApplicationValidatorsServiceCollectionExtensions { /// /// Adds the validators of Application, and those of the assemblies it references, each as the - /// IValidate and IValidateAsync of the type it validates. + /// IValidateAsync of the type it validates, and as its IValidate unless one of the type's rules waits. A + /// validator whose rules take services is scoped; the others are singletons. /// /// The services. /// The services. public static global::Microsoft.Extensions.DependencyInjection.IServiceCollection AddApplicationValidators(this global::Microsoft.Extensions.DependencyInjection.IServiceCollection services) { - global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddSingleton, global::Sample.DelayValidator>(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, global::Sample.RetryOptionsValidator>(services); + 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.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton, global::Sample.RetryOptionsValidator>()); + global::Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAddEnumerable(services, global::Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton, global::Sample.RetryOptionsGeneratedValidator>()); return services; } } diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.Delay.Validator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.DelayGeneratedValidator.g.verified.cs similarity index 83% rename from test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.Delay.Validator.g.verified.cs rename to test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.DelayGeneratedValidator.g.verified.cs index d1588849e70..008020f8ff3 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.Delay.Validator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.DelayGeneratedValidator.g.verified.cs @@ -1,14 +1,15 @@ -//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.Delay.Validator.g.cs +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.DelayGeneratedValidator.g.cs // #nullable enable namespace Sample { /// - /// Validates a : the rules its members carry as attributes. + /// Validates a : every rule declared for it, by the attributes of its members and by the + /// functions and classes that validate it. /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Delay))] - internal sealed partial class DelayValidator + internal sealed class DelayGeneratedValidator : global::Rocket.Surgery.LaunchPad.Validation.IValidate { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -17,7 +18,7 @@ internal sealed partial class DelayValidator /// Creates the validator. /// /// What replaces the rules' messages, if anything does. - public DelayValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; + public DelayGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Delay value) diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.RetryOptions.Validator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.RetryOptionsGeneratedValidator.g.verified.cs similarity index 87% rename from test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.RetryOptions.Validator.g.verified.cs rename to test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.RetryOptionsGeneratedValidator.g.verified.cs index acde6a49a73..ef411ba1954 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.RetryOptions.Validator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Register_The_Validators_And_Validate_Options#Sample.RetryOptionsGeneratedValidator.g.verified.cs @@ -1,14 +1,15 @@ -//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.RetryOptions.Validator.g.cs +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.RetryOptionsGeneratedValidator.g.cs // #nullable enable namespace Sample { /// - /// Validates a : the rules its members carry as attributes. + /// Validates a : every rule declared for it, by the attributes of its members and by the + /// functions and classes that validate it. /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.RetryOptions))] - public sealed partial class RetryOptionsValidator + public sealed class RetryOptionsGeneratedValidator : global::Rocket.Surgery.LaunchPad.Validation.IValidate, global::Microsoft.Extensions.Options.IValidateOptions { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -17,7 +18,7 @@ public sealed partial class RetryOptionsValidator /// Creates the validator. /// /// What replaces the rules' messages, if anything does. - public RetryOptionsValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; + public RetryOptionsGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.RetryOptions value) diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Report_What_It_Cannot_Write#Mistakes.Validator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Report_What_It_Cannot_Write#MistakesGeneratedValidator.g.verified.cs similarity index 82% rename from test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Report_What_It_Cannot_Write#Mistakes.Validator.g.verified.cs rename to test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Report_What_It_Cannot_Write#MistakesGeneratedValidator.g.verified.cs index 92a7bd80596..366a88882a5 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Report_What_It_Cannot_Write#Mistakes.Validator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Report_What_It_Cannot_Write#MistakesGeneratedValidator.g.verified.cs @@ -1,12 +1,13 @@ -//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Mistakes.Validator.g.cs +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/MistakesGeneratedValidator.g.cs // #nullable enable /// -/// Validates a : the rules its members carry as attributes. +/// Validates a : every rule declared for it, by the attributes of its members and by the +/// functions and classes that validate it. /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Mistakes))] -public sealed partial class MistakesValidator +public sealed class MistakesGeneratedValidator : global::Rocket.Surgery.LaunchPad.Validation.IValidate { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -15,7 +16,7 @@ public sealed partial class MistakesValidator /// Creates the validator. /// /// What replaces the rules' messages, if anything does. - public MistakesValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; + public MistakesGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Mistakes value) diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.Crew.Validator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.CrewGeneratedValidator.g.verified.cs similarity index 83% rename from test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.Crew.Validator.g.verified.cs rename to test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.CrewGeneratedValidator.g.verified.cs index 0b6d143928c..d08badf5b7f 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.Crew.Validator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.CrewGeneratedValidator.g.verified.cs @@ -1,14 +1,15 @@ -//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.Crew.Validator.g.cs +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.CrewGeneratedValidator.g.cs // #nullable enable namespace Sample { /// - /// Validates a : the rules its members carry as attributes. + /// Validates a : every rule declared for it, by the attributes of its members and by the + /// functions and classes that validate it. /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Crew))] - public sealed partial class CrewValidator + public sealed class CrewGeneratedValidator : global::Rocket.Surgery.LaunchPad.Validation.IValidate { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -17,7 +18,7 @@ public sealed partial class CrewValidator /// Creates the validator. /// /// What replaces the rules' messages, if anything does. - public CrewValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; + public CrewGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Crew value) diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.Launcher.Validator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.LauncherGeneratedValidator.g.verified.cs similarity index 79% rename from test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.Launcher.Validator.g.verified.cs rename to test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.LauncherGeneratedValidator.g.verified.cs index d93de18acb5..c96f3c483f1 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.Launcher.Validator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.LauncherGeneratedValidator.g.verified.cs @@ -1,14 +1,15 @@ -//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.Launcher.Validator.g.cs +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.LauncherGeneratedValidator.g.cs // #nullable enable namespace Sample { /// - /// Validates a : the rules its members carry as attributes. + /// Validates a : every rule declared for it, by the attributes of its members and by the + /// functions and classes that validate it. /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Launcher))] - public sealed partial class LauncherValidator + public sealed class LauncherGeneratedValidator : global::Rocket.Surgery.LaunchPad.Validation.IValidate { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -22,7 +23,7 @@ public sealed partial class LauncherValidator /// /// What replaces the rules' messages, if anything does. /// Where the validators of the members validated with their own are found. - public LauncherValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null, global::System.IServiceProvider? services = null) + public LauncherGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null, global::System.IServiceProvider? services = null) { _messages = messages; _services = services; @@ -34,37 +35,37 @@ public LauncherValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidation global::System.ArgumentNullException.ThrowIfNull(value); var sink = new global::Rocket.Surgery.LaunchPad.Validation.ValidationSink(_messages); - if (value.Crew is { } crew) + if (value.Crew is { } __crew) { var path = sink.Enter("Crew"); - sink.Add(CrewValidator.Validate(crew)); + sink.Add(CrewValidator.Validate(__crew)); sink.Leave(path); } EnsureBooster(value.Booster, ref sink); - if (value.Booster is { } booster) + if (value.Booster is { } __booster) { var path = sink.Enter("Booster"); - sink.Add(BoosterValidator.Validate(booster)); + sink.Add(BoosterValidator.Validate(__booster)); sink.Leave(path); } { - var core = value.Core; + var __core = value.Core; var path = sink.Enter("Core"); - sink.Add(BoosterValidator.Validate(core)); + sink.Add(BoosterValidator.Validate(__core)); sink.Leave(path); } EnsureStages(value.Stages, ref sink); - if (value.Stages is { } stages) + if (value.Stages is { } __stages) { var path = sink.Enter("Stages"); var index = 0; - foreach (var item in stages) + foreach (var item in __stages) { var itemPath = sink.Enter(index); sink.Add(BoosterValidator.Validate(item)); @@ -77,11 +78,11 @@ public LauncherValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidation } - if (value.Backups is { } backups) + if (value.Backups is { } __backups) { var path = sink.Enter("Backups"); var index = 0; - foreach (var item in backups) + foreach (var item in __backups) { if (item is { } present) { @@ -97,10 +98,10 @@ public LauncherValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidation } - if (value.Reserve is { } reserve) + if (value.Reserve is { } __reserve) { var path = sink.Enter("Reserve"); - sink.Add(ReserveValidator.Validate(reserve)); + sink.Add(ReserveValidator.Validate(__reserve)); sink.Leave(path); } @@ -109,15 +110,15 @@ public LauncherValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidation 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("LauncherValidator needs a Rocket.Surgery.LaunchPad.Validation.IValidate, which the service provider it was given does not have."); + ?? 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.IValidate BoosterValidator => _boosterValidator ??= _services?.GetService(typeof(global::Rocket.Surgery.LaunchPad.Validation.IValidate)) as global::Rocket.Surgery.LaunchPad.Validation.IValidate - ?? throw new global::System.InvalidOperationException("LauncherValidator needs a Rocket.Surgery.LaunchPad.Validation.IValidate, which the service provider it was given does not have."); + ?? 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::Sample.StrictCrew ReserveValidator => _reserveValidator ??= _services?.GetService(typeof(global::Sample.StrictCrew)) as global::Sample.StrictCrew - ?? throw new global::System.InvalidOperationException("LauncherValidator needs a Sample.StrictCrew, which the service provider it was given does not have."); + ?? throw new global::System.InvalidOperationException("LauncherGeneratedValidator needs a Sample.StrictCrew, which the service provider it was given does not have."); /// /// The rules of . diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.Stage.Validator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.StageGeneratedValidator.g.verified.cs similarity index 83% rename from test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.Stage.Validator.g.verified.cs rename to test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.StageGeneratedValidator.g.verified.cs index 753293e0a36..569bbda5848 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.Stage.Validator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Validate_Nested_Members_With_Their_Validators#Sample.StageGeneratedValidator.g.verified.cs @@ -1,14 +1,15 @@ -//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.Stage.Validator.g.cs +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.StageGeneratedValidator.g.cs // #nullable enable namespace Sample { /// - /// Validates a : the rules its members carry as attributes. + /// Validates a : every rule declared for it, by the attributes of its members and by the + /// functions and classes that validate it. /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Stage))] - public sealed partial class StageValidator + public sealed class StageGeneratedValidator : global::Rocket.Surgery.LaunchPad.Validation.IValidate { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -17,7 +18,7 @@ public sealed partial class StageValidator /// Creates the validator. /// /// What replaces the rules' messages, if anything does. - public StageValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; + public StageGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Stage value) diff --git a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Write_A_Validator_For_Rule_Attributes#Sample.Launcher.Validator.g.verified.cs b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Write_A_Validator_For_Rule_Attributes#Sample.LauncherGeneratedValidator.g.verified.cs similarity index 96% rename from test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Write_A_Validator_For_Rule_Attributes#Sample.Launcher.Validator.g.verified.cs rename to test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Write_A_Validator_For_Rule_Attributes#Sample.LauncherGeneratedValidator.g.verified.cs index eb2e77f5904..9375ec65c55 100644 --- a/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Write_A_Validator_For_Rule_Attributes#Sample.Launcher.Validator.g.verified.cs +++ b/test/Validation.Analyzers.Tests/snapshots/ValidatorGeneratorTests.Should_Write_A_Validator_For_Rule_Attributes#Sample.LauncherGeneratedValidator.g.verified.cs @@ -1,14 +1,15 @@ -//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.Launcher.Validator.g.cs +//HintName: Rocket.Surgery.LaunchPad.Validation.Analyzers/Rocket.Surgery.LaunchPad.Validation.Analyzers.ValidatorGenerator/Sample.LauncherGeneratedValidator.g.cs // #nullable enable namespace Sample { /// - /// Validates a : the rules its members carry as attributes. + /// Validates a : every rule declared for it, by the attributes of its members and by the + /// functions and classes that validate it. /// [global::Rocket.Surgery.LaunchPad.Validation.GeneratedValidator(typeof(global::Sample.Launcher))] - public sealed partial class LauncherValidator + public sealed class LauncherGeneratedValidator : global::Rocket.Surgery.LaunchPad.Validation.IValidate { private readonly global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? _messages; @@ -20,7 +21,7 @@ public sealed partial class LauncherValidator /// Creates the validator. /// /// What replaces the rules' messages, if anything does. - public LauncherValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; + public LauncherGeneratedValidator(global::Rocket.Surgery.LaunchPad.Validation.IValidationMessageProvider? messages = null) => _messages = messages; /// public global::Rocket.Surgery.LaunchPad.Validation.ValidationResult Validate(global::Sample.Launcher value) diff --git a/test/Validation.Tests/BuilderTests.cs b/test/Validation.Tests/BuilderTests.cs deleted file mode 100644 index 16fed3a5b6a..00000000000 --- a/test/Validation.Tests/BuilderTests.cs +++ /dev/null @@ -1,62 +0,0 @@ -using Rocket.Surgery.LaunchPad.Validation; -using Rocket.Surgery.LaunchPad.Validation.Rules; - -namespace Validation.Tests; - -/// -/// The builder is only ever read by the generator, so what there is to prove here is that the rules a validator declares compile against -/// the member types they are meant for. -/// -public class BuilderTests -{ - private enum Kind - { - Cargo, - Crewed, - } - - private sealed record Stage(double Thrust, string? Name); - - private sealed record Rocket( - string Name, - string? Nickname, - Kind Kind, - Kind? Backup, - int Engines, - int? Seats, - decimal Price, - DateOnly Built, - DateOnly? Launched, - IReadOnlyList Stages, - string[] Tags, - Stage? Booster - ); - - private static void Validate(IValidationBuilder v, TimeProvider time) - { - v.Ensure(x => x.Name).NotEmpty().MinLength(3).MaxLength(30).Matches("^[A-Z]").WithMessage("{Name} must start with a capital").WithCode("Capital"); - v.Ensure(x => x.Nickname).Length(1, 10).NotEqual(x => x.Name).WithSeverity(ValidationSeverity.Warning); - v.Ensure(x => x.Kind).IsInEnum(); - v.Ensure(x => x.Backup).IsInEnum().NotEqual(x => x.Kind); - v.Ensure(x => x.Engines).GreaterThan(0).LessThanOrEqualTo(33).StopOnFailure(); - v.Ensure(x => x.Seats).NotNull().InclusiveBetween(1, 7).When(x => x.Kind == Kind.Crewed); - v.Ensure(x => x.Price).PrecisionScale(12, 2).GreaterThanOrEqualTo(0m); - v.Ensure(x => x.Built).NotDefault().LessThan(_ => DateOnly.FromDateTime(time.GetUtcNow().UtcDateTime)); - v.Ensure(x => x.Launched).GreaterThanOrEqualTo(x => x.Built).Unless(x => x.Launched is null); - v.Ensure(x => x.Stages).NotEmpty().MaxLength(4); - v.EnsureEach(x => x.Stages, stage => stage.Ensure(x => x.Thrust).ExclusiveBetween(0, 10_000)); - v.EnsureEach(x => x.Tags).NotEmpty().MaxLength(20); - v.Ensure(x => x.Booster).ValidateNested().WithName("First stage"); - v.Ensure(x => x).Must(x => x.Engines >= x.Stages.Count).MustAsync((_, _) => ValueTask.FromResult(true)); - v.When(x => x.Kind == Kind.Cargo, cargo => cargo.Ensure(x => x.Seats).Null()); - v.Unless(x => x.Kind == Kind.Cargo, crewed => crewed.Ensure(x => x.Name).Must((rocket, name) => name != rocket.Nickname)); - } - - [Test] - public async Task Should_Declare_Rules_For_Every_Kind_Of_Member() - { - Action, TimeProvider> validate = Validate; - - await validate.Should().NotBeNull(); - } -} diff --git a/test/Validation.Tests/FunctionValidatorTests.cs b/test/Validation.Tests/FunctionValidatorTests.cs new file mode 100644 index 00000000000..cd80baa664c --- /dev/null +++ b/test/Validation.Tests/FunctionValidatorTests.cs @@ -0,0 +1,131 @@ +using Microsoft.Extensions.DependencyInjection; + +using Rocket.Surgery.LaunchPad.Validation; + +using Validation.Tests.Types; + +namespace Validation.Tests; + +public class FunctionValidatorTests +{ + private static ServiceProvider Services() => + new ServiceCollection().AddSingleton().AddSingleton(TimeProvider.System).AddValidationTestsValidators().BuildServiceProvider(true); + + private static string[] 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),]; + } + + [Test] + public async Task Should_Accept_A_Value_That_Meets_Its_Rules() => 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"]); + + [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"]); + } + + [Test] + 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, }); + + await result.Failures.Length.Should().BeEqualTo(3); + await result.Failures[0].Message.Should().BeEqualTo("Name is over 10"); + await result.Failures[1].Severity.Should().BeEqualTo(ValidationSeverity.Warning); + await result.Failures[2].Message.Should().BeEqualTo("Seat count must not be set"); + await result.Failures[2].Path.Should().BeEqualTo("Seats"); + } + + [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"]); + } + + [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"]); + } + + [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"]); + } + + [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),], }) + .Should() + .BeEquivalentTo(["Engines[1].Thrust:GreaterThan", "Engines[1].Name:UnknownEngine"]); + } + + [Test] + public async Task Should_Validate_Asynchronously_When_A_Rule_Waits() + { + using var services = Services(); + using var scope = services.CreateScope(); + 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")); + + await taken.Failures.Select(z => z.Path + ":" + z.Code).ToArray().Should().BeEquivalentTo(["Serial:Taken", "Pad:Equal"]); + + var empty = await validator.ValidateAsync(new("", "LC-39A")); + + await empty.Failures.Select(z => z.Path + ":" + z.Code).ToArray().Should().BeEquivalentTo(["Serial:NotEmpty"]); + } + + [Test] + 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>(); + using var cancelled = new CancellationTokenSource(); + await cancelled.CancelAsync(); + + await Assert.That(async () => await validator.ValidateAsync(new("AB-1", null), cancelled.Token)).Throws(); + } + + [Test] + public async Task Should_Be_Asynchronous_When_A_Nested_Member_Is() + { + 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"))); + + 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 bcc183f06f2..202de177dd0 100644 --- a/test/Validation.Tests/GeneratedValidatorTests.cs +++ b/test/Validation.Tests/GeneratedValidatorTests.cs @@ -159,12 +159,12 @@ public async Task Should_Validate_Options() [Test] public async Task Should_Not_Accept_Null() => - await Assert.That(() => new LauncherValidator().Validate(null!)).Throws(); + await Assert.That(() => new LauncherGeneratedValidator().Validate(null!)).Throws(); [Test] public async Task Should_Say_Which_Validator_Is_Missing() { - var exception = await Assert.That(() => new LauncherValidator().Validate(new() { Crew = new("Ada"), })).Throws(); + var exception = await Assert.That(() => new LauncherGeneratedValidator().Validate(new() { Crew = new("Ada"), })).Throws(); await exception!.Message.Should().Contain("IValidate"); } diff --git a/test/Validation.Tests/Types/Functions.cs b/test/Validation.Tests/Types/Functions.cs new file mode 100644 index 00000000000..e5056f1573e --- /dev/null +++ b/test/Validation.Tests/Types/Functions.cs @@ -0,0 +1,100 @@ +using System.Text.RegularExpressions; + +using Rocket.Surgery.LaunchPad.Validation; +using Rocket.Surgery.LaunchPad.Validation.Rules; + +namespace Validation.Tests.Types; + +public interface ICatalog +{ + bool IsKnown(string name); + ValueTask IsFree(string serial, CancellationToken cancellationToken); +} + +public sealed class Catalog : ICatalog +{ + public bool IsKnown(string name) => name is "Merlin" or "Raptor"; + + public async ValueTask IsFree(string serial, CancellationToken cancellationToken) + { + await Task.Yield(); + cancellationToken.ThrowIfCancellationRequested(); + return serial != "TAKEN"; + } +} + +public sealed record Engine(string Name, double Thrust); + +/// An operation in the shape the samples use: the request and the function that validates it in one static class. +public static partial class BuildLauncher +{ + public sealed record Request + { + [NotEmpty] + public string Name { get; init; } = "Falcon"; + + public string? Serial { get; init; } = "AB-1"; + public LauncherKind Kind { get; init; } = LauncherKind.Cargo; + public int? Seats { get; init; } + public DateOnly Built { get; init; } = new(2020, 1, 1); + public DateOnly? Launched { get; init; } + public IReadOnlyList Engines { get; init; } = [new("Merlin", 100),]; + public string[] Tags { get; init; } = []; + public int Budget { get; init; } = 10; + public int Spent { get; init; } + } + + [GeneratedRegex("^[A-Z]{2}-[0-9]+$")] + private static partial Regex SerialPattern { get; } + + private const int MostTags = 2; + + private static bool IsRound(int value) => value % 10 == 0; + + // A function validator: the builder, then what it needs. + private static void Validate(IValidationBuilder v, ICatalog catalog, TimeProvider time) + { + v.Ensure(x => x.Name).MaxLength(10).WithMessage("{Name} is over {Max}").WithCode("TooLong").Matches("^[A-Z]").StopOnFailure(); + v.Ensure(x => x.Serial).NotNull().Matches(SerialPattern).WithSeverity(ValidationSeverity.Warning); + v.Ensure(x => x.Seats).NotNull().InclusiveBetween(1, 7).When(x => x.Kind == LauncherKind.Crewed); + v.Ensure(x => x.Seats).Null().Unless(x => x.Kind == LauncherKind.Crewed).WithName("Seat count"); + v.Ensure(x => x.Built).LessThanOrEqualTo(_ => DateOnly.FromDateTime(time.GetUtcNow().UtcDateTime)); + v.Ensure(x => x.Launched).GreaterThanOrEqualTo(x => x.Built); + v.Ensure(x => x.Budget).Must(IsRound).Must((request, budget) => budget >= request.Spent).WithCode("Overspent"); + v.Ensure(x => x.Tags).MaxLength(MostTags); + v.EnsureEach(x => x.Tags).NotEmpty().MaxLength(5); + v.EnsureEach( + x => x.Engines, + engine => + { + engine.Ensure(x => x.Thrust).GreaterThan(0); + engine.Ensure(x => x.Name).Must(name => catalog.IsKnown(name)).WithCode("UnknownEngine"); + } + ); + v.When( + x => x.Kind == LauncherKind.Cargo, + cargo => + { + cargo.Ensure(x => x.Engines).MinLength(1); + cargo.Ensure(x => x).Must(x => x.Spent <= x.Budget * 2).WithCode("WayOverspent"); + } + ); + } +} + +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 +{ + private readonly string _pad = "LC-39A"; + + public void Validate(IValidationBuilder v) + { + v.Ensure(x => x.Serial).NotEmpty().MustAsync(catalog.IsFree).WithCode("Taken").StopOnFailure(); + v.Ensure(x => x.Pad).Equal(_pad); + } +} + +/// Validated by attributes only, but a member of it is validated asynchronously, so it is too. +public sealed record Manifest([NotEmpty] string Name, [ValidateNested] Booking Booking); From 5069f725deda2fa4d06af0285b97ebadd9fb2935 Mon Sep 17 00:00:00 2001 From: David Driscoll Date: Thu, 3 Dec 2026 17:59:09 -0500 Subject: [PATCH 3/8] Validation: build clean in Release CI builds in Release, where the repository's analyzers are errors: no LINQ or string concatenation inside a loop in the generator (ZA0601, ZA0201), a summary the formatter had emptied (RCS1138), and a reference to Microsoft.Extensions.Options the test projects already get from the framework (NU1510). Co-Authored-By: Claude Fable 5.2 --- .../Model/FunctionReader.cs | 5 ++- src/Validation.Analyzers/Model/RuleReader.cs | 7 ++- .../Model/TargetReader.cs | 2 +- .../Model/ValidationSymbols.cs | 6 +++ .../NestedValidationAnalyzer.cs | 2 +- .../SynchronousValidationCodeFix.cs | 5 ++- .../ValidatorGenerator.cs | 44 +++++++++++++------ .../Validation.Analyzers.Tests.csproj | 1 - test/Validation.Tests/Validation.Tests.csproj | 1 - 9 files changed, 51 insertions(+), 22 deletions(-) diff --git a/src/Validation.Analyzers/Model/FunctionReader.cs b/src/Validation.Analyzers/Model/FunctionReader.cs index 167e46c7eed..a769fcb2036 100644 --- a/src/Validation.Analyzers/Model/FunctionReader.cs +++ b/src/Validation.Analyzers/Model/FunctionReader.cs @@ -704,6 +704,9 @@ string value into.Manifest.Add(manifest.Count == 0 ? bound.Code : bound.Code + "(" + string.Join(", ", manifest) + ")"); } + private static string Arguments(RuleBuilder rule) => + string.Concat(rule.Placeholders.Select(static z => ", " + Runtime + ".ValidationSink.Argument(" + Literal(z.Name) + ", " + z.Expression + ")")); + private void Write( MemberBuilder into, Scope scope, @@ -749,7 +752,7 @@ string collection conditions.AddRange(grouped); conditions.AddRange(rule.Conditions); conditions.Add(rule.IsAsync ? "!( " + rule.Check + " )" : "!" + rule.Check); - var arguments = string.Concat(rule.Placeholders.Select(static z => ", " + Runtime + ".ValidationSink.Argument(" + Literal(z.Name) + ", " + z.Expression + ")")); + var arguments = Arguments(rule); Line(into, indent + " if (" + string.Join(" && ", conditions) + ")"); Line(into, indent + " {"); Line( diff --git a/src/Validation.Analyzers/Model/RuleReader.cs b/src/Validation.Analyzers/Model/RuleReader.cs index 878dd496842..af4c0f6b266 100644 --- a/src/Validation.Analyzers/Model/RuleReader.cs +++ b/src/Validation.Analyzers/Model/RuleReader.cs @@ -25,7 +25,7 @@ public static ValidatedTypeResult Read(INamedTypeSymbol type, SemanticModel mode var members = new List(); foreach (var member in ValidationSymbols.Members(type)) { - var attributes = ValidationSymbols.AttributesOf(member).Where(static z => ValidationSymbols.IsRelevant(z.AttributeClass)).ToList(); + var attributes = ValidationSymbols.RelevantAttributesOf(member); if (attributes.Count == 0) continue; if (reader.ReadMember(member, attributes) is { } read) members.Add(read); } @@ -225,7 +225,7 @@ private void ReadMust(MemberContext context, AttributeData attribute) var candidates = new List(); for (var current = _type; current is not null; current = current.BaseType) { - candidates.AddRange(current.GetMembers(name).OfType().Where(static z => z.Parameters.Length == 1)); + AddPredicates(candidates, current, name); } var conversions = _model.Compilation; @@ -260,6 +260,9 @@ private void ReadMust(MemberContext context, AttributeData attribute) context.Rules.Add(Finish(attribute, new(check, "Must", "{Name} is not valid", "Error", EquatableArray.Empty, "Must(" + name + ")"), [])); } + private static void AddPredicates(List candidates, INamedTypeSymbol type, string name) => + candidates.AddRange(type.GetMembers(name).OfType().Where(static z => z.Parameters.Length == 1)); + private void ReadDataAnnotation(MemberContext context, AttributeData attribute) { var arguments = attribute.ConstructorArguments; diff --git a/src/Validation.Analyzers/Model/TargetReader.cs b/src/Validation.Analyzers/Model/TargetReader.cs index d08bd39d5ef..d39bd38c390 100644 --- a/src/Validation.Analyzers/Model/TargetReader.cs +++ b/src/Validation.Analyzers/Model/TargetReader.cs @@ -81,7 +81,7 @@ internal static class RuleBinder public sealed record Bound(string Code, string Message, IReadOnlyList Placeholders, bool IsAsync); /// - /// + /// Binds the call of a rule's method, and returns what the compiler picked, or when nothing checks those types. /// /// The semantic model of the tree the rule is declared in. /// A position in that tree. diff --git a/src/Validation.Analyzers/Model/ValidationSymbols.cs b/src/Validation.Analyzers/Model/ValidationSymbols.cs index c923d07252f..41aa9ea65c2 100644 --- a/src/Validation.Analyzers/Model/ValidationSymbols.cs +++ b/src/Validation.Analyzers/Model/ValidationSymbols.cs @@ -93,6 +93,12 @@ public static IEnumerable AttributesOf(ISymbol member) } } + /// The attributes of a member that the generator reads. + public static List RelevantAttributesOf(ISymbol member) => [.. AttributesOf(member).Where(static z => IsRelevant(z.AttributeClass))]; + + /// Whether a member says how its own type is validated: [ValidateNested], [ValidateWith] or [SkipValidation]. + public static bool DecidesNestedValidation(ISymbol member) => AttributesOf(member).Any(static z => DecidesNestedValidation(z.AttributeClass)); + public static IParameterSymbol? PrimaryParameter(IPropertySymbol property) { foreach (var constructor in property.ContainingType.InstanceConstructors) diff --git a/src/Validation.Analyzers/NestedValidationAnalyzer.cs b/src/Validation.Analyzers/NestedValidationAnalyzer.cs index dc60bdca913..c2cde5d462e 100644 --- a/src/Validation.Analyzers/NestedValidationAnalyzer.cs +++ b/src/Validation.Analyzers/NestedValidationAnalyzer.cs @@ -33,7 +33,7 @@ private static void Analyze(SymbolAnalysisContext context) { // Only what the type declares: what it inherits is reported on the type that declares it. if (!SymbolEqualityComparer.Default.Equals(member.ContainingType, type)) continue; - if (ValidationSymbols.AttributesOf(member).Any(static z => ValidationSymbols.DecidesNestedValidation(z.AttributeClass))) continue; + if (ValidationSymbols.DecidesNestedValidation(member)) continue; var memberType = ValidationSymbols.TypeOf(member); var target = ValidationSymbols.Underlying(ValidationSymbols.ItemType(memberType) ?? memberType); diff --git a/src/Validation.Analyzers/SynchronousValidationCodeFix.cs b/src/Validation.Analyzers/SynchronousValidationCodeFix.cs index 0699dfa833a..92df9b9daeb 100644 --- a/src/Validation.Analyzers/SynchronousValidationCodeFix.cs +++ b/src/Validation.Analyzers/SynchronousValidationCodeFix.cs @@ -59,7 +59,7 @@ when SymbolEqualityComparer.Default.Equals(model.GetSymbolInfo(other, cancellati 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 = call.Ancestors().FirstOrDefault(static z => z is BaseMethodDeclarationSyntax or LocalFunctionStatementSyntax or AnonymousFunctionExpressionSyntax); + var function = FunctionOf(call); calls.Add(call, function is null ? null : Token(function, model, cancellationToken)); if (function is not null) functions.Add(function); break; @@ -72,6 +72,9 @@ when model.GetSymbolInfo(call, cancellationToken).Symbol is IMethodSymbol method 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) { diff --git a/src/Validation.Analyzers/ValidatorGenerator.cs b/src/Validation.Analyzers/ValidatorGenerator.cs index 17cf222da58..30875f2cf65 100644 --- a/src/Validation.Analyzers/ValidatorGenerator.cs +++ b/src/Validation.Analyzers/ValidatorGenerator.cs @@ -162,6 +162,13 @@ internal sealed class MergedModel(TargetModel target) /// Whether the validator can be public: the type is, and so is everything its constructor takes. public bool IsPublic => Target.IsPublic && Contributors.All(static z => z.IsClass ? z.IsPublic : z.Dependencies.All(static d => d.IsPublic)); + private bool HasRuleThatWaits => Contributors.Any(static z => z.Members.Any(static m => m.IsAsync)) || Nested.Any(static z => z.IsAsync); + + private bool HasAsyncMember(Dictionary byType) => + Nested.Any(z => z.Validator is null && byType.TryGetValue(z.Target, out var nested) && nested.IsAsync); + + public IEnumerable ClassValidators => Contributors.Where(static z => z.IsClass).Select(static z => z.Container).Distinct(StringComparer.Ordinal); + public IEnumerable Nested => Members.Where(static z => z.Nested is not null).Select(static z => z.Nested!) .Concat(Contributors.SelectMany(static z => z.Members).Where(static z => z.Nested is not null).Select(static z => z.Nested!)); @@ -187,7 +194,7 @@ MergedModel For(TargetModel target) foreach (var merged in byType.Values) { - merged.IsAsync = merged.Contributors.Any(static z => z.Members.Any(static m => m.IsAsync)) || merged.Nested.Any(static z => z.IsAsync); + merged.IsAsync = merged.HasRuleThatWaits; } // A type that validates a member with the validator of an asynchronous type is asynchronous too. @@ -197,7 +204,7 @@ MergedModel For(TargetModel target) foreach (var merged in byType.Values) { if (merged.IsAsync) continue; - if (!merged.Nested.Any(z => z.Validator is null && byType.TryGetValue(z.Target, out var nested) && nested.IsAsync)) continue; + if (!merged.HasAsyncMember(byType)) continue; merged.IsAsync = true; changed = true; } @@ -241,14 +248,16 @@ public static string Validator(MergedModel model, CompilationModel compilation) var fields = new List<(string Type, string Field, string Parameter)>(); var dependencyFields = new Dictionary(StringComparer.Ordinal); var classFields = new Dictionary(StringComparer.Ordinal); + var taken = new HashSet(StringComparer.Ordinal) { "messages", "services", "value", }; string Unique(string name) { var candidate = name; - for (var i = 1; fields.Any(z => z.Parameter == candidate) || candidate is "messages" or "services" or "value"; i++) + for (var i = 1; taken.Contains(candidate); i++) { candidate = name + i.ToString(System.Globalization.CultureInfo.InvariantCulture); } + taken.Add(candidate); return candidate; } @@ -366,7 +375,7 @@ NestedValidator NestedFor(string member, NestedModel how) { if (member.Rules.Length > 0) { - var arguments = ( member.ReadsValue ? "value, " : "" ) + "value." + member.Name + string.Concat(member.Reads.Select(static z => ", value." + z.Name)); + var arguments = ( member.ReadsValue ? "value, " : "" ) + "value." + member.Name + Reads(member); Line($" Ensure{member.Name}({arguments}, ref sink);"); } @@ -512,7 +521,7 @@ private static void WriteRuleMethod(TargetModel target, MemberModel member, Acti { if (!first) line(""); first = false; - var arguments = string.Concat(rule.Arguments.Select(static z => $", {Sink}.Argument({Literal(z.Name)}, {z.Expression})")); + var arguments = Arguments(rule); line($" if (!{rule.Check})"); line(" {"); line($" sink.Add({name}, {Literal(rule.Code)}, {Literal(rule.Message)}, {Runtime}.ValidationSeverity.{rule.Severity}, {Sink}.Argument(\"Name\", {name}), {Sink}.Argument(\"Value\", value){arguments});"); @@ -548,13 +557,15 @@ public static string Contributor(ContributorModel model) } } - foreach (var container in model.Containers) + for (var i = 0; i < model.Containers.Length; i++) { - sb.Append(indent).AppendLine(container); - sb.Append(indent).AppendLine("{"); - indent += " "; + var nesting = indent + new string(' ', i * 4); + sb.Append(nesting).AppendLine(model.Containers[i]); + sb.Append(nesting).AppendLine("{"); } + indent += new string(' ', model.Containers.Length * 4); + void Line(string text = "") => _ = text.Length == 0 ? sb.AppendLine() : sb.Append(indent).AppendLine(text); foreach (var field in model.Fields) @@ -571,7 +582,7 @@ public static string Contributor(ContributorModel model) { if (!first) Line(); first = false; - var manifest = string.Concat(member.Manifest.Select(static z => ", " + Literal(z))); + var manifest = Manifest(member); var parameters = ( member.ReadsValue ? model.Target.Type + " __instance, " : "" ) + ( member.Member.Length > 0 ? member.Type + " __value, " : "" ) + dependencies; @@ -607,10 +618,9 @@ public static string Contributor(ContributorModel model) Line("}"); } - for (var i = 0; i < model.Containers.Length; i++) + for (var i = model.Containers.Length - 1; i >= 0; i--) { - indent = indent[..^4]; - sb.Append(indent).AppendLine("}"); + sb.Append(indent, 0, indent.Length - ( ( model.Containers.Length - i ) * 4 )).AppendLine("}"); } if (model.Namespace.Length > 0) sb.AppendLine("}"); @@ -656,7 +666,7 @@ public static string Registration(IReadOnlyList models, Compilation var target = model.Target; var validator = target.ValidatorFullName; var lifetime = model.HasDependencies ? "Scoped" : "Singleton"; - foreach (var container in model.Contributors.Where(static z => z.IsClass).Select(static z => z.Container).Distinct(StringComparer.Ordinal)) + foreach (var container in model.ClassValidators) { sb.AppendLine($" {extensions}.TryAddScoped<{container}>(services);"); } @@ -684,6 +694,12 @@ public static string Registration(IReadOnlyList models, Compilation private static string Literal(string value) => SymbolDisplay.FormatLiteral(value, true); + private static string Reads(MemberModel member) => string.Concat(member.Reads.Select(static z => ", value." + z.Name)); + + private static string Arguments(RuleModel rule) => string.Concat(rule.Arguments.Select(static z => $", {Sink}.Argument({Literal(z.Name)}, {z.Expression})")); + + private static string Manifest(ContributedMemberModel member) => string.Concat(member.Manifest.Select(static z => ", " + Literal(z))); + private static string Escape(string value) => value.Replace("\\", "\\\\").Replace("\"", "\\\""); private static string Camel(string name) => char.ToLowerInvariant(name[0]) + name[1..]; diff --git a/test/Validation.Analyzers.Tests/Validation.Analyzers.Tests.csproj b/test/Validation.Analyzers.Tests/Validation.Analyzers.Tests.csproj index b7160244390..33079191c39 100644 --- a/test/Validation.Analyzers.Tests/Validation.Analyzers.Tests.csproj +++ b/test/Validation.Analyzers.Tests/Validation.Analyzers.Tests.csproj @@ -16,7 +16,6 @@ - diff --git a/test/Validation.Tests/Validation.Tests.csproj b/test/Validation.Tests/Validation.Tests.csproj index 0eba831123a..e76826f380f 100644 --- a/test/Validation.Tests/Validation.Tests.csproj +++ b/test/Validation.Tests/Validation.Tests.csproj @@ -13,6 +13,5 @@ ReferenceOutputAssembly="false" /> - From 0c5edb0bd7f969eaa7618c68a5b8b0de0590c01a Mon Sep 17 00:00:00 2001 From: David Driscoll Date: Thu, 3 Dec 2026 18:00:18 -0500 Subject: [PATCH 4/8] Validation: no angle brackets in the analyzer release notes Codacy's Markdown check reads IValidate in the notes column as an HTML element. Co-Authored-By: Claude Fable 5.2 --- src/Validation.Analyzers/AnalyzerReleases.Unshipped.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Validation.Analyzers/AnalyzerReleases.Unshipped.md b/src/Validation.Analyzers/AnalyzerReleases.Unshipped.md index 6ebdf27db09..271b722fd0d 100644 --- a/src/Validation.Analyzers/AnalyzerReleases.Unshipped.md +++ b/src/Validation.Analyzers/AnalyzerReleases.Unshipped.md @@ -6,7 +6,7 @@ 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, IValidate of a type that has an asynchronous rule +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 From 2c163b517e1bdc0db4be7db92c08465887d53542 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:04:04 +0000 Subject: [PATCH 5/8] Automatically linting code --- test/Validation.Tests/Types/Functions.cs | 30 ------------------------ 1 file changed, 30 deletions(-) diff --git a/test/Validation.Tests/Types/Functions.cs b/test/Validation.Tests/Types/Functions.cs index e5056f1573e..11bb69b85b1 100644 --- a/test/Validation.Tests/Types/Functions.cs +++ b/test/Validation.Tests/Types/Functions.cs @@ -50,36 +50,6 @@ public sealed record Request private const int MostTags = 2; private static bool IsRound(int value) => value % 10 == 0; - - // A function validator: the builder, then what it needs. - private static void Validate(IValidationBuilder v, ICatalog catalog, TimeProvider time) - { - v.Ensure(x => x.Name).MaxLength(10).WithMessage("{Name} is over {Max}").WithCode("TooLong").Matches("^[A-Z]").StopOnFailure(); - v.Ensure(x => x.Serial).NotNull().Matches(SerialPattern).WithSeverity(ValidationSeverity.Warning); - v.Ensure(x => x.Seats).NotNull().InclusiveBetween(1, 7).When(x => x.Kind == LauncherKind.Crewed); - v.Ensure(x => x.Seats).Null().Unless(x => x.Kind == LauncherKind.Crewed).WithName("Seat count"); - v.Ensure(x => x.Built).LessThanOrEqualTo(_ => DateOnly.FromDateTime(time.GetUtcNow().UtcDateTime)); - v.Ensure(x => x.Launched).GreaterThanOrEqualTo(x => x.Built); - v.Ensure(x => x.Budget).Must(IsRound).Must((request, budget) => budget >= request.Spent).WithCode("Overspent"); - v.Ensure(x => x.Tags).MaxLength(MostTags); - v.EnsureEach(x => x.Tags).NotEmpty().MaxLength(5); - v.EnsureEach( - x => x.Engines, - engine => - { - engine.Ensure(x => x.Thrust).GreaterThan(0); - engine.Ensure(x => x.Name).Must(name => catalog.IsKnown(name)).WithCode("UnknownEngine"); - } - ); - v.When( - x => x.Kind == LauncherKind.Cargo, - cargo => - { - cargo.Ensure(x => x.Engines).MinLength(1); - cargo.Ensure(x => x).Must(x => x.Spent <= x.Budget * 2).WithCode("WayOverspent"); - } - ); - } } public sealed record Booking(string Serial, string? Pad); From 60b7b6dbdbbe3c0b7e8a3f16a541da57b80d0edb Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:07:55 +0000 Subject: [PATCH 6/8] Automatically linting code (attempt 2/3) --- test/Validation.Tests/Types/Functions.cs | 7 ------- 1 file changed, 7 deletions(-) diff --git a/test/Validation.Tests/Types/Functions.cs b/test/Validation.Tests/Types/Functions.cs index 11bb69b85b1..af6b058b6f4 100644 --- a/test/Validation.Tests/Types/Functions.cs +++ b/test/Validation.Tests/Types/Functions.cs @@ -43,13 +43,6 @@ public sealed record Request public int Budget { get; init; } = 10; public int Spent { get; init; } } - - [GeneratedRegex("^[A-Z]{2}-[0-9]+$")] - private static partial Regex SerialPattern { get; } - - private const int MostTags = 2; - - private static bool IsRound(int value) => value % 10 == 0; } public sealed record Booking(string Serial, string? Pad); From 10add77d4d0302e2c99fee45c11567aa1febfb9c Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:11:25 +0000 Subject: [PATCH 7/8] Automatically linting code (attempt 3/3) --- test/Validation.Tests/Types/Functions.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/test/Validation.Tests/Types/Functions.cs b/test/Validation.Tests/Types/Functions.cs index af6b058b6f4..382d5ae686b 100644 --- a/test/Validation.Tests/Types/Functions.cs +++ b/test/Validation.Tests/Types/Functions.cs @@ -1,5 +1,3 @@ -using System.Text.RegularExpressions; - using Rocket.Surgery.LaunchPad.Validation; using Rocket.Surgery.LaunchPad.Validation.Rules; From 94959fab3ec904e70b54facab75064ae5822f81d Mon Sep 17 00:00:00 2001 From: David Driscoll Date: Thu, 3 Dec 2026 18:30:19 -0500 Subject: [PATCH 8/8] Validation tests: keep the function validator through the lint job The lint job formats without building the validation generator, so the private Validate that only generated code names looked unused: the bot deleted it, and then what only it used, in three commits. Restore it and suppress IDE0051 on it. Co-Authored-By: Claude Fable 5.2 --- test/Validation.Tests/Types/Functions.cs | 42 ++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/test/Validation.Tests/Types/Functions.cs b/test/Validation.Tests/Types/Functions.cs index 382d5ae686b..c9257982764 100644 --- a/test/Validation.Tests/Types/Functions.cs +++ b/test/Validation.Tests/Types/Functions.cs @@ -1,3 +1,5 @@ +using System.Text.RegularExpressions; + using Rocket.Surgery.LaunchPad.Validation; using Rocket.Surgery.LaunchPad.Validation.Rules; @@ -41,6 +43,46 @@ public sealed record Request public int Budget { get; init; } = 10; public int Spent { get; init; } } + + [GeneratedRegex("^[A-Z]{2}-[0-9]+$")] + private static partial Regex SerialPattern { get; } + + private const int MostTags = 2; + + private static bool IsRound(int value) => value % 10 == 0; + + // A function validator: the builder, then what it needs. + // Nothing calls it. In a build the rule methods the generator writes name it, so it is used; the lint job formats without building the + // generator, sees an unused private method, and deletes it and then what only it used. + [SuppressMessage("CodeQuality", "IDE0051:Remove unused private members", Justification = "Read by the validation generator.")] + private static void Validate(IValidationBuilder v, ICatalog catalog, TimeProvider time) + { + v.Ensure(x => x.Name).MaxLength(10).WithMessage("{Name} is over {Max}").WithCode("TooLong").Matches("^[A-Z]").StopOnFailure(); + v.Ensure(x => x.Serial).NotNull().Matches(SerialPattern).WithSeverity(ValidationSeverity.Warning); + v.Ensure(x => x.Seats).NotNull().InclusiveBetween(1, 7).When(x => x.Kind == LauncherKind.Crewed); + v.Ensure(x => x.Seats).Null().Unless(x => x.Kind == LauncherKind.Crewed).WithName("Seat count"); + v.Ensure(x => x.Built).LessThanOrEqualTo(_ => DateOnly.FromDateTime(time.GetUtcNow().UtcDateTime)); + v.Ensure(x => x.Launched).GreaterThanOrEqualTo(x => x.Built); + v.Ensure(x => x.Budget).Must(IsRound).Must((request, budget) => budget >= request.Spent).WithCode("Overspent"); + v.Ensure(x => x.Tags).MaxLength(MostTags); + v.EnsureEach(x => x.Tags).NotEmpty().MaxLength(5); + v.EnsureEach( + x => x.Engines, + engine => + { + engine.Ensure(x => x.Thrust).GreaterThan(0); + engine.Ensure(x => x.Name).Must(name => catalog.IsKnown(name)).WithCode("UnknownEngine"); + } + ); + v.When( + x => x.Kind == LauncherKind.Cargo, + cargo => + { + cargo.Ensure(x => x.Engines).MinLength(1); + cargo.Ensure(x => x).Must(x => x.Spent <= x.Budget * 2).WithCode("WayOverspent"); + } + ); + } } public sealed record Booking(string Serial, string? Pad);