Skip to content

Commit afad5d2

Browse files
committed
Do base type check early in ClassUsingAttributeInsteadOfInheritanceAnalyzer
1 parent 857b4b8 commit afad5d2

File tree

1 file changed

+10
-13
lines changed

1 file changed

+10
-13
lines changed

src/CommunityToolkit.Mvvm.SourceGenerators/Diagnostics/Analyzers/ClassUsingAttributeInsteadOfInheritanceAnalyzer.cs

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ public override void Initialize(AnalysisContext context)
6868
context.RegisterSymbolAction(context =>
6969
{
7070
// We're looking for class declarations that don't have any base type
71-
if (context.Symbol is not INamedTypeSymbol { TypeKind: TypeKind.Class, IsRecord: false, IsStatic: false, IsImplicitlyDeclared: false } classSymbol)
71+
if (context.Symbol is not INamedTypeSymbol { TypeKind: TypeKind.Class, IsRecord: false, IsStatic: false, IsImplicitlyDeclared: false, BaseType.SpecialType: SpecialType.System_Object } classSymbol)
7272
{
7373
return;
7474
}
@@ -80,18 +80,15 @@ public override void Initialize(AnalysisContext context)
8080
typeSymbols.TryGetValue(attributeName, out INamedTypeSymbol? attributeSymbol) &&
8181
SymbolEqualityComparer.Default.Equals(attributeClass, attributeSymbol))
8282
{
83-
// The type is annotated with either [ObservableObject] or [INotifyPropertyChanged].
84-
if (classSymbol.BaseType is { SpecialType: SpecialType.System_Object })
85-
{
86-
// This type is using the attribute when it could just inherit from ObservableObject, which is preferred
87-
context.ReportDiagnostic(Diagnostic.Create(
88-
GeneratorAttributeNamesToDiagnosticsMap[attributeClass.Name],
89-
context.Symbol.Locations.FirstOrDefault(),
90-
ImmutableDictionary.Create<string, string?>()
91-
.Add(TypeNameKey, classSymbol.Name)
92-
.Add(AttributeTypeNameKey, attributeName),
93-
context.Symbol));
94-
}
83+
// The type is annotated with either [ObservableObject] or [INotifyPropertyChanged], and we already validated
84+
// that it has no other base type, so emit a diagnostic to suggest inheriting from ObservableObject instead.
85+
context.ReportDiagnostic(Diagnostic.Create(
86+
GeneratorAttributeNamesToDiagnosticsMap[attributeClass.Name],
87+
context.Symbol.Locations.FirstOrDefault(),
88+
ImmutableDictionary.Create<string, string?>()
89+
.Add(TypeNameKey, classSymbol.Name)
90+
.Add(AttributeTypeNameKey, attributeName),
91+
context.Symbol));
9592
}
9693
}
9794
}, SymbolKind.NamedType);

0 commit comments

Comments
 (0)