-
Notifications
You must be signed in to change notification settings - Fork 10.9k
Add analyzer for RazorComponentResult parameter validation #67617
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
dkamburov
wants to merge
10
commits into
dotnet:main
Choose a base branch
from
dkamburov:type-safety-razor-component-result
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
8659a9e
Add analyzer for RazorComponentResult parameter validation
dkamburov 7375654
Merge branch 'main' into type-safety-razor-component-result
dkamburov 8515238
Potential fix for pull request finding
dkamburov 2a5d3ad
Apply review comments
dkamburov 017cf0e
Merge branch 'main' into type-safety-razor-component-result
dkamburov 973ebce
Potential fix for pull request finding
dkamburov cff922c
Potential fix for pull request finding
dkamburov 9654dec
Merge branch 'main' into type-safety-razor-component-result
dkamburov bbe182d
Merge branch 'main' into type-safety-razor-component-result
dkamburov a6f3082
Merge branch 'main' into type-safety-razor-component-result
dkamburov File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
160 changes: 160 additions & 0 deletions
160
src/Components/Analyzers/src/RazorComponentResultParameterAnalyzer.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,160 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Collections.Immutable; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CSharp; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
| using Microsoft.CodeAnalysis.Diagnostics; | ||
| using Microsoft.CodeAnalysis.Operations; | ||
|
|
||
| #nullable enable | ||
|
|
||
| namespace Microsoft.AspNetCore.Components.Analyzers; | ||
|
|
||
| [DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
| public sealed class RazorComponentResultParameterAnalyzer : DiagnosticAnalyzer | ||
| { | ||
| public RazorComponentResultParameterAnalyzer() | ||
| { | ||
| SupportedDiagnostics = ImmutableArray.Create( | ||
| DiagnosticDescriptors.RazorComponentResultParameterDoesNotExist); | ||
| } | ||
|
|
||
| public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } | ||
|
|
||
| public override void Initialize(AnalysisContext context) | ||
| { | ||
| context.EnableConcurrentExecution(); | ||
| context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); | ||
| context.RegisterCompilationStartAction(context => | ||
| { | ||
| if (!ComponentSymbols.TryCreate(context.Compilation, out var symbols)) | ||
| { | ||
| // Types we need are not defined. | ||
| return; | ||
| } | ||
|
|
||
| var razorComponentResultOfT = context.Compilation.GetTypeByMetadataName(ComponentsApi.RazorComponentResultOfT.MetadataName); | ||
| if (razorComponentResultOfT is null) | ||
| { | ||
| // RazorComponentResult<TComponent> is not referenced by this compilation. | ||
| return; | ||
| } | ||
|
|
||
| context.RegisterOperationAction(context => | ||
| { | ||
| var objectCreation = (IObjectCreationOperation)context.Operation; | ||
|
|
||
| // We only care about constructing RazorComponentResult<TComponent> with a single loosely-typed | ||
| // parameters argument, which is the ergonomic (and error-prone) overload from the issue. | ||
| if (objectCreation.Type is not INamedTypeSymbol createdType || | ||
| !SymbolEqualityComparer.Default.Equals(createdType.OriginalDefinition, razorComponentResultOfT)) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| if (createdType.TypeArguments.Length != 1 || | ||
| createdType.TypeArguments[0] is not INamedTypeSymbol componentType) | ||
| { | ||
| // The component type is an open generic type parameter; we cannot resolve its parameters. | ||
| return; | ||
| } | ||
|
|
||
| if (objectCreation.Arguments.Length != 1) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| if (UnwrapConversions(objectCreation.Arguments[0].Value) is not IAnonymousObjectCreationOperation anonymousObject) | ||
| { | ||
| // Only anonymous objects (e.g. new { Foo = 1 }) expose statically known parameter names. | ||
| // Dictionaries and named types are matched by name at runtime and are intentionally ignored. | ||
| return; | ||
| } | ||
|
|
||
| if (!TryGetComponentParameterNames(symbols, componentType, out var parameterNames)) | ||
| { | ||
| // The component captures unmatched values, so any parameter name is accepted at runtime. | ||
| return; | ||
| } | ||
|
|
||
| foreach (var initializer in anonymousObject.Initializers) | ||
| { | ||
| if (initializer is not ISimpleAssignmentOperation { Target: IPropertyReferenceOperation propertyReference }) | ||
| { | ||
| continue; | ||
| } | ||
|
|
||
| var parameterName = propertyReference.Property.Name; | ||
| if (parameterNames.Contains(parameterName)) | ||
| { | ||
| continue; | ||
| } | ||
|
|
||
| context.ReportDiagnostic(Diagnostic.Create( | ||
| DiagnosticDescriptors.RazorComponentResultParameterDoesNotExist, | ||
| GetParameterNameLocation(initializer.Syntax), | ||
| componentType.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat), | ||
| parameterName)); | ||
| } | ||
| }, OperationKind.ObjectCreation); | ||
| }); | ||
| } | ||
|
|
||
| private static IOperation UnwrapConversions(IOperation operation) | ||
| { | ||
| while (operation is IConversionOperation conversion) | ||
| { | ||
| operation = conversion.Operand; | ||
| } | ||
|
|
||
| return operation; | ||
| } | ||
|
|
||
| private static bool TryGetComponentParameterNames( | ||
| ComponentSymbols symbols, | ||
| INamedTypeSymbol componentType, | ||
| out HashSet<string> parameterNames) | ||
| { | ||
| parameterNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); | ||
|
|
||
| for (INamedTypeSymbol? type = componentType; type is not null; type = type.BaseType) | ||
| { | ||
| foreach (var member in type.GetMembers()) | ||
| { | ||
| if (member is not IPropertySymbol property) | ||
| { | ||
| continue; | ||
| } | ||
|
|
||
| if (ComponentFacts.IsParameterWithCaptureUnmatchedValues(symbols, property)) | ||
| { | ||
| // The component accepts arbitrary parameter names via CaptureUnmatchedValues, | ||
| // so no name can be considered invalid. | ||
| return false; | ||
| } | ||
|
|
||
| if (ComponentFacts.IsParameter(symbols, property)) | ||
| { | ||
| parameterNames.Add(property.Name); | ||
| } | ||
|
dkamburov marked this conversation as resolved.
|
||
| } | ||
| } | ||
|
|
||
| return true; | ||
| } | ||
|
|
||
| private static Location GetParameterNameLocation(SyntaxNode syntax) | ||
| { | ||
| // Point the diagnostic at the member name (e.g. `Foo` in `Foo = 1`) rather than the whole declarator. | ||
| return syntax switch | ||
| { | ||
| AnonymousObjectMemberDeclaratorSyntax { NameEquals: { } nameEquals } => nameEquals.Name.GetLocation(), | ||
| AnonymousObjectMemberDeclaratorSyntax { Expression: IdentifierNameSyntax identifier } => identifier.GetLocation(), | ||
| _ => syntax.GetLocation(), | ||
| }; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.