Repository navigation
Add MEV analyzers - #67993
Add MEV analyzers#67993
Conversation
4f60a59 to
afcb90e
Compare
606d200 to
c277059
Compare
c277059 to
defb55b
Compare
There was a problem hiding this comment.
Pull request overview
Adds a new ValidationsDiagnosticAnalyzer (ASP0031–ASP0034) intended to warn when the validation source generator would otherwise silently skip validation due to accessibility/graph issues, plus new generator test coverage and diagnostic documentation updates.
Changes:
- Introduces
ValidationsDiagnosticAnalyzerwith four new diagnostics (ASP0031–ASP0034) and release-tracking files. - Adds analyzer-focused test infrastructure and new tests validating diagnostic behavior.
- Updates the public diagnostics list to include the new ASP0031–ASP0034 warnings.
Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/ValidationsGeneratorTestBase.cs | Refactors metadata reference setup and adds helper to run the analyzer and collect diagnostics. |
| src/Validation/test/Microsoft.Extensions.Validation.GeneratorTests/ValidationsGenerator.Analyzer.cs | Adds analyzer unit tests validating ASP0031/33/34 scenarios. |
| src/Validation/gen/Microsoft.Extensions.Validation.ValidationsGenerator.csproj | Adds analyzer release tracking files as AdditionalFiles. |
| src/Validation/gen/Analyzers/ValidationsDiagnosticAnalyzer.cs | Implements the new MEV/validation diagnostics analyzer (ASP0031–ASP0034). |
| src/Validation/gen/AnalyzerReleases.Unshipped.md | Declares the new unshipped analyzer rules for release tracking. |
| src/Validation/gen/AnalyzerReleases.Shipped.md | Initializes shipped analyzer releases tracking file. |
| docs/list-of-diagnostics.md | Documents the new ASP0031–ASP0034 diagnostics. |
639b91e to
05f3d9e
Compare
f03bbe9 to
5c3e45c
Compare
5c3e45c to
24f994e
Compare
2aae6f7 to
4155328
Compare
| || property.IsStatic | ||
| || property.IsWriteOnly | ||
| || property.GetMethod is null | ||
| || property.GetMethod.DeclaredAccessibility is not Accessibility.Public |
There was a problem hiding this comment.
ASP0035 currently cannot fire for a non-public property, so the rule is effectively dead code.
Accessors without an explicit modifier inherit the property's declared accessibility, so for internal TheChild Child { get; } Roslyn reports GetMethod.DeclaredAccessibility == Internal. This line therefore makes ShouldSkipProperty return true for every non-public property, and AnalyzeType calls it and continues before it ever reaches IsPropertyIgnoredDueToAccessibility.
The other branch of that check (public property whose type is inaccessible) is largely unreachable too, because C# rejects it with CS0053 (inconsistent accessibility).
Evidence from the last completed CI run on this branch: ASP0035 does not appear once in the test log (no AD0001 either), while ASP0033/ASP0034/ASP0036 do. ReportsNonPublicProperty_WhoseTypeIsValidatable, ReportsInaccessibleProperty_ViaEndpointParameter and ReportsNonPublicProperty_OnRecordType are all asserting a diagnostic that is never produced.
Suggested fix: split the helper, so the analyzer does not inherit the accessibility gate it is trying to diagnose.
// Shape-based skips only; shared by generator and analyzer.
internal static bool ShouldSkipPropertyShape(...)
=> property.IsImplicitlyDeclared
|| property.IsIndexer
|| property.IsStatic
|| property.IsWriteOnly
|| property.GetMethod is null
|| property.IsEqualityContract(wellKnownTypes)
|| property.IsSkippedValidationProperty(skipValidationAttributeSymbol)
|| property.IsJsonIgnoredProperty(jsonIgnoreAttributeSymbol);
// Generator keeps the accessibility gate on top.
internal static bool ShouldSkipProperty(...)
=> ShouldSkipPropertyShape(...)
|| property.GetMethod!.DeclaredAccessibility is not Accessibility.Public;Once fixed, a test for public string X { private get; set; } would be worth adding, since that is the one shape where property and getter accessibility genuinely differ.
Minor, same method: the comment above is truncated mid-sentence ("properties without a public getter, and .").
Generated by Copilot, reviewed by @oroztocil.
| DiagnosticSeverity.Warning, | ||
| isEnabledByDefault: true, | ||
| description: null, | ||
| helpLinkUri: GetHelpLinkUri("ASP0035")); |
There was a problem hiding this comment.
ASP0035 is reported from the compilation-end action but is missing WellKnownDiagnosticTags.CompilationEnd.
ASP0034 and ASP0037 carry the tag; ASP0035 does not, yet it is reported from RegisterCompilationEndAction via the endpoint-parameter loop (AnalyzeType call further down). Roslyn may drop or stale it in live analysis.
On the question you raised in the other thread about using two descriptors with the same ID where only one is tagged: I would avoid that shape. Roslyn partly determines "is this a compilation-end analyzer" at analyzer granularity by scanning SupportedDiagnostics for the tag, and duplicate IDs in SupportedDiagnostics make effective-severity resolution and release tracking (RS2000/RS2001) ambiguous. Two cleaner options:
- (a) Two distinct IDs - keep ASP0035 for the
[ValidatableType]path (untagged, live in the IDE) and allocate a new ID for the endpoint-parameter path (taggedCompilationEnd). Sidesteps the tooling ambiguity and is self-documenting inlist-of-diagnostics.md. - (b) One tagged descriptor with all ASP0035 reporting moved into the compilation-end action. Simplest, at the cost of the live-editing experience you are trying to preserve.
(a) seems preferable. Worth settling this after the dead-code issue flagged on ShouldSkipProperty, since that changes what the attribute-path descriptor can actually report.
Generated by Copilot, reviewed by @oroztocil.
| { | ||
| if (!addValidationFound && validatableTypeAttributeFound) | ||
| { | ||
| context.ReportDiagnostic(Diagnostic.Create(ValidatableTypeIsUsedWithoutAddValidation, Location.None)); |
There was a problem hiding this comment.
ASP0037 is reported at Location.None, and the message misdirects library authors.
Location.None means the diagnostic cannot be navigated to, does not surface in the editor, and cannot be suppressed with #pragma warning disable. Consider collecting the [ValidatableType] attribute syntax locations in the operation action and reporting at one of them (and including the type name in the message, since today there is no indication of which type triggered it).
Separately, the message says the attribute has no effect "if there is no 'AddValidation' call in your application entry-point". For the common class-library case that is misleading: because the generator emits a file-scoped interceptor bound to call sites in its own compilation, a library needs AddValidation() in that project (typically inside its own public registration method), not in the app's entry point. A library author reading the current text is likely to conclude the warning does not apply to them.
Something like: "'[ValidatableType]' on type '{0}' has no effect because this project does not call 'AddValidation'. The generated resolver only covers types in the project containing the 'AddValidation' call, so add it here (for example, in a public service-registration method)."
To be clear, the rule itself is correct - I had initially misread this as a false positive for libraries and was wrong.
Generated by Copilot, reviewed by @oroztocil.
| => property.DeclaredAccessibility != Accessibility.Public || | ||
| IsInaccessibleFromGeneratedCode(property.Type.UnwrapType()); | ||
|
|
||
| private static bool IsInaccessibleFromGeneratedCode(ITypeSymbol type) |
There was a problem hiding this comment.
Accessibility check does not walk the containing type chain.
DeclaredAccessibility and IsFileLocal are both properties of the type itself, so a public type nested inside a file or private container reads as accessible. Verified against Roslyn:
FileOuter declAcc=Internal isFileLocal=True
FileOuter+NestedPublic declAcc=Public isFileLocal=False
PrivateHost+PrivOuter declAcc=Private isFileLocal=False
PrivateHost+PrivOuter+NestedPublic declAcc=Public isFileLocal=False
So file class Outer { public class Inner { } } is missed by the analyzer. Worth noting the generator has the identical gap in TryExtractValidatableType, so in that case it will emit typeof(global::Outer.Inner) into a separate file and produce CS0122 in the generated code. Computing effective accessibility by walking ContainingType would fix analyzer and generator together.
Generated by Copilot, reviewed by @oroztocil.
|
|
||
| if (IsPropertyIgnoredDueToAccessibility(property) && | ||
| (ValidationsGenerator.HasValidationAttributes(property, wellKnownTypes) || | ||
| TypeHasValidation(property.Type, wellKnownTypes))) |
There was a problem hiding this comment.
TypeHasValidation receives the raw property type while the accessibility check above unwraps it.
IsPropertyIgnoredDueToAccessibility uses property.Type.UnwrapType(), but this call passes property.Type directly. As a result internal List<Child> Items where Child has [Required] is missed: List<Child> itself has no validation attributes, does not implement IValidatableObject, and none of its own members are annotated, so TypeHasValidation returns false.
property.Type.UnwrapType() here would make the two checks consistent.
Generated by Copilot, reviewed by @oroztocil.
| var skipValidationAttribute = wellKnownTypes.Get(WellKnownTypeData.WellKnownType.Microsoft_Extensions_Validation_SkipValidationAttribute); | ||
| var jsonIgnoreAttributeSymbol = wellKnownTypes.Get(WellKnownTypeData.WellKnownType.System_Text_Json_Serialization_JsonIgnoreAttribute); | ||
|
|
||
| var topLevelValidatableTypes = new ConcurrentDictionary<ITypeSymbol, byte>(SymbolEqualityComparer.Default); |
There was a problem hiding this comment.
Compilation-start mutable state gates whether a per-operation diagnostic is reported.
topLevelValidatableTypes is scoped to the CompilationStart closure, but AnalyzeType's TryAdd guard decides whether ASP0035 is reported at all, and ASP0035/ASP0033 are reported from a per-operation action. In IDE live analysis the scope is reused across document analyses, so whether a type's properties get analyzed depends on which document was analyzed first: a type added during one document's analysis is skipped on the next. The usual symptom is squiggles that appear, vanish on edit, and do not come back.
The robust shape is to accumulate in the operation actions and report everything from the compilation-end action. This largely folds into whichever option you pick for the ASP0035 descriptor split.
Generated by Copilot, reviewed by @oroztocil.
There was a problem hiding this comment.
I'm not sure I'm following or seeing what the bug here is.
| new CSharpCompilationOptions(OutputKind.ConsoleApplication)); | ||
|
|
||
| var compilationWithAnalyzers = compilation.WithAnalyzers([new ValidationsDiagnosticAnalyzer(), new ValidatableTypeInGeneratedCodeDiagnosticAnalyzer()]); | ||
| var diagnostics = await compilationWithAnalyzers.GetAllDiagnosticsAsync(); |
There was a problem hiding this comment.
The test helper suppresses compiler diagnostics rather than separating them, so assertions stay coupled to unrelated compiler output.
GetAllDiagnosticsAsync() returns compiler diagnostics as well as analyzer ones, and filtering only Hidden still leaves every Info/Warning/Error in the collection. That is why #nullable enable had to be added across ~12 test sources and a synthetic Main added to ReportsForUseInGeneratedCode - and any future test source with an unrelated compiler warning will break the assertions again.
Separating the two concerns keeps the analyzer assertions stable and still gives the compiler-clean guarantee:
Assert.DoesNotContain(compilation.GetDiagnostics(), d => d.Severity == DiagnosticSeverity.Error);
var analyzerDiagnostics = await compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync();
Assert.DoesNotContain(analyzerDiagnostics, d => d.Id == "AD0001");
return [.. analyzerDiagnostics.OrderBy(d => d.Id).ThenBy(d => d.Location.SourceSpan.Start)];The explicit AD0001 assertion is worth keeping - it is the one real benefit GetAllDiagnosticsAsync was providing, and without it an analyzer crash would silently look like "no diagnostics" and make the negative tests pass vacuously.
Also worth making OutputKind a parameter (hardcoded to ConsoleApplication above), which is the cleaner fix for the generated-code test than adding an entry point to it.
Generated by Copilot, reviewed by @oroztocil.
There was a problem hiding this comment.
It's fine. Catching the additional errors helped making the test better actually.
| ## Analyzer Warnings | ||
|
|
||
| ### ASP (`ASP0000-ASP0032`) | ||
| ### ASP (`ASP0000-ASP0036`) |
There was a problem hiding this comment.
Heading range is out of date and bracket escaping is inconsistent.
The heading says ASP0000-ASP0036, but the table below now goes up to ASP0037.
Also, in the rows added below: ASP0033 uses \[ValidatableType\] (both brackets escaped) while ASP0036 and ASP0037 use \[ValidatableType] (closing bracket unescaped). Worth making these consistent.
Generated by Copilot, reviewed by @oroztocil.
There was a problem hiding this comment.
Both are valid escaping for markdown AFAIK.
Fixed the range.
| var diagnostics = await GetAnalyzerDiagnosticsAsync(source, additionalReferences: [externalReference]); | ||
| Assert.Empty(diagnostics); | ||
| } | ||
| } |
There was a problem hiding this comment.
A few test gaps worth closing before this ships.
- ASP0035's genuinely reachable shape -
public string X { private get; set; }. Relevant once theShouldSkipPropertyissue is resolved; today all ASP0035 tests cover a shape the analyzer cannot report. - Public type nested in a
file/private container - e.g.file class Outer { public class Inner { } }, which is currently missed by the accessibility check. - Restore the deleted dedup test (
ReportsSingleDiagnostic_WhenTypeReachedByValidatableTypeAndEndpointParameter). It was the only coverage fortopLevelValidatableTypes, which is now untested. - Record primary constructor parameters -
ReportsNonPublicProperty_OnRecordTypeonly covers a plain property. The generator has a separate code path for primary-constructor parameters that the analyzer does not model at all. - ASP0037 in a class library - two cases: it does fire with
[ValidatableType]and noAddValidation, and it does not fire when the library's own public registration method callsAddValidation(). The second pins the intended library authoring pattern, which is currently not documented or tested anywhere.
Generated by Copilot, reviewed by @oroztocil.
| // Skip compiler generated properties, indexers, static properties, properties without | ||
| // a public getter, and . |
| // TODO: This logic sounds wrong. | ||
| // If a property has some validation attributes and its type has SkipValidationAttribute, we | ||
| // should only skip the "type validation" part of the property, but still validate the property itself. |
There was a problem hiding this comment.
Regarding the SkipValidation logic:
if type has SkipValidationAttribute, we should only skip the "type validation" part of the property
That would not be very useful. If you want to skip type-level validation, you just don't add type-level attributes on the type 🙂
The idea behind the logic as it is now is that you can put SkipValidation on a type to disable validation of all properties and parameters of that type, while not disabling validation of any nested types when those are reached elsewhere in the type graph.
Example:
class A
{
B NestedB { get; set; }
C NestedC { get; set; }
}
[SkipValidation]
class B
{
C NestedC { get; set; }
}
class C
{
[Required]
string? Name { get; set; }
}
A valueA = new();Here valueA.NestedB.NestedC.Name is not validated, while valueA.NestedC.Name is validated.
Scenario "validate the attributes on the property but on its type" can be, again, expressed by not adding type-level attributes on the property's type.
What we do not have direct way of expressing is the scenario "validate the property's attributes and its type's attributes, but do not recurse into the type's members" - at least not as per-property opt out. In the example above, you can put SkipValidation on B.NestedC but that means that you don't recurse into NestedC for all uses of B.
However, I would argue that having too subtle type graphs where sometimes you do nested validation and sometimes not is an anti-pattern: it creates footguns for code that uses such models. You can go further and say that only the "parse, don't validate" kind of approaches are safe. That said, there are smaller and bigger footguns, and we are trying to keep ours small. Hence the simple SkipValidation rules: on property/parameter it skips validation for that member, on type it skips validation for all members of that type. (MVC's ValidateNever has the same semantics.)
| var topLevelValidatableTypes = new ConcurrentDictionary<ITypeSymbol, byte>(SymbolEqualityComparer.Default); | ||
| var endpointParameters = new ConcurrentDictionary<IParameterSymbol, byte>(SymbolEqualityComparer.Default); | ||
|
|
||
| var validatableTypeAttributeLocations = new ConcurrentDictionary<Location?, byte>(); |
| // Skip file-local types, which are only accessible within their declaring file | ||
| // and cannot be referenced from generated code in a different file | ||
| if (typeSymbol is INamedTypeSymbol { IsFileLocal: true }) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| // Skip types that are not accessible from generated code | ||
| if (typeSymbol.DeclaredAccessibility is not (Accessibility.Public or Accessibility.Internal)) | ||
| { | ||
| return false; | ||
| } |
There was a problem hiding this comment.
The analyzer should now be correct but the generator itself has different logic.
For types private or file-local types with nested public types, e.g.
class Host { private class Priv { public class Inner { } } }`the generator does not skip and creates identifier global::Host.Priv.Inner which will break the build on the generated code (while the analyzer only emits warning saying that the type will be skipped from validation).
| | __`ASP0035`__ | Validatable property or its type is not accessible | | ||
| | __`ASP0036`__ | Validatable property or its type is not accessible | |
There was a problem hiding this comment.
We should probably differentiate the two diagnostics in wording, at least slightly.
| private static bool IsPropertyIgnoredDueToAccessibility(IPropertySymbol property) | ||
| => property.DeclaredAccessibility != Accessibility.Public || | ||
| IsInaccessibleFromGeneratedCode(property.Type.UnwrapType()); |
There was a problem hiding this comment.
ValidationsGenerator.TypesParser.cs:286 checks DeclaredAccessibility of the getter method rather than the property itself. What about properties public int X { private get; set; } - these two checks will return different results, no?
| } | ||
|
|
||
| [Fact] | ||
| public async Task ReportsNonPublicProperty_OnRecordType() |
There was a problem hiding this comment.
Can we add test with primary constructor parameters? They have separate code paths in multiple places.
Per the dotnet#65418 discussion, the silent skip becomes an author-facing diagnostic: ASP0039 reports at the declaration when a [ValidatableType] type tree still contains a type parameter (its own, or an enclosing type's). Lives in the ValidationsDiagnosticAnalyzer introduced in dotnet#67993 and reuses the generator's ContainsTypeParameter walk so the analyzer and the emit-time guard cannot drift apart. ID and wording are placeholders for review. The guard itself stays as the safety net for shapes no attribute-based analyzer can see: post-dotnet#67821 a generic registration helper forwarding Func<Command<TRequest>, IResult> to MapPost hands the parser the open Command<TRequest>, which passes the accessibility check and would reach emission as typeof(global::Command<TRequest>). A regression test covers that shape end to end. Co-Authored-By: Claude Fable 5 <[email protected]>
Related to #64435
This PR adds an analyzer with 3 descriptors.
ASP0033: [ValidatableType] is applied to an inaccessible type
Whenever
[ValidatableType]attribute is applied to a file-local type or a nested private type, this diagnostic produces a warning. The source-generated code won't be able to generate a resolver for such type.ASP0034: Endpoint parameter type is inaccessible from generated code
Similar to ASP0033, but for endpoint parameters.
ASP0035: Validatable property or its type is not accessible
If a property is internal, we don't handle it today in the generation. In addition, if the property is public but its type isn't accessible by the same rule governing ASP0033 and ASP0034, a warning is also produced for the property.
ASP0036: [ValidatableType] cannot be used in generated code
If
[ValidatableType]is used in generated code. Our source generator won't be able to see them.ASP0037: [ValidatableType] should not be used without a call to 'AddValidation'
If
[ValidatableType]is used without a call toAddValidation. Our source generator will do nothing and the attribute has no effect.