Skip to content

[Blazor] Implement property analyzer also for [PersistentState]Β #63235

@javiercn

Description

@javiercn

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.

[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);
});
}

Metadata

Metadata

Assignees

Labels

area-blazorIncludes: Blazor, Razor Components

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions