-
Notifications
You must be signed in to change notification settings - Fork 10.5k
Closed
Labels
area-blazorIncludes: Blazor, Razor ComponentsIncludes: Blazor, Razor Components
Description
The same rules that govern [SupplyParameterFromForm] apply to [PersistentState]. Properties declared with it shouldn't use an initializer that does not initialize to the default value.
aspnetcore/src/Components/Analyzers/src/SupplyParameterFromFormAnalyzer.cs
Lines 15 to 83 in e336a0b
[DiagnosticAnalyzer(LanguageNames.CSharp)] | |
public sealed class SupplyParameterFromFormAnalyzer : DiagnosticAnalyzer | |
{ | |
public SupplyParameterFromFormAnalyzer() | |
{ | |
SupportedDiagnostics = ImmutableArray.Create( | |
DiagnosticDescriptors.SupplyParameterFromFormShouldNotHavePropertyInitializer); | |
} | |
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; | |
} | |
context.RegisterSyntaxNodeAction(context => | |
{ | |
var propertyDeclaration = (PropertyDeclarationSyntax)context.Node; | |
// Check if property has an initializer | |
if (propertyDeclaration.Initializer == null) | |
{ | |
return; | |
} | |
// Ignore initializers that set to default values (null, default, etc.) | |
if (IsDefaultValueInitializer(propertyDeclaration.Initializer.Value)) | |
{ | |
return; | |
} | |
var propertySymbol = context.SemanticModel.GetDeclaredSymbol(propertyDeclaration); | |
if (propertySymbol == null) | |
{ | |
return; | |
} | |
// Check if property has [SupplyParameterFromForm] attribute | |
if (!ComponentFacts.IsSupplyParameterFromForm(symbols, propertySymbol)) | |
{ | |
return; | |
} | |
// Check if the containing type inherits from ComponentBase | |
var containingType = propertySymbol.ContainingType; | |
if (!ComponentFacts.IsComponentBase(symbols, containingType)) | |
{ | |
return; | |
} | |
var propertyLocation = propertySymbol.Locations.FirstOrDefault(); | |
if (propertyLocation != null) | |
{ | |
context.ReportDiagnostic(Diagnostic.Create( | |
DiagnosticDescriptors.SupplyParameterFromFormShouldNotHavePropertyInitializer, | |
propertyLocation, | |
propertySymbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat))); | |
} | |
}, SyntaxKind.PropertyDeclaration); | |
}); | |
} |
Copilot
Metadata
Metadata
Assignees
Labels
area-blazorIncludes: Blazor, Razor ComponentsIncludes: Blazor, Razor Components