-
Notifications
You must be signed in to change notification settings - Fork 410
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Duplicate dependency field analyzer (#5463)
* Duplicate dependency field analyzer Detects cases of duplicate [Dependency] fields in a type. We apparently have 27 of these across RT + SS14. * Fix duplicate dependencies in Robust
- Loading branch information
Showing
7 changed files
with
212 additions
and
22 deletions.
There are no files selected for viewing
This file contains 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,63 @@ | ||
using System.Threading.Tasks; | ||
using Microsoft.CodeAnalysis.CSharp.Testing; | ||
using Microsoft.CodeAnalysis.Testing; | ||
using Microsoft.CodeAnalysis.Testing.Verifiers; | ||
using NUnit.Framework; | ||
using VerifyCS = | ||
Microsoft.CodeAnalysis.CSharp.Testing.NUnit.AnalyzerVerifier<Robust.Analyzers.DuplicateDependencyAnalyzer>; | ||
|
||
namespace Robust.Analyzers.Tests; | ||
|
||
[Parallelizable(ParallelScope.All | ParallelScope.Fixtures)] | ||
[TestFixture] | ||
[TestOf(typeof(DuplicateDependencyAnalyzer))] | ||
public sealed class DuplicateDependencyAnalyzerTest | ||
{ | ||
private static Task Verifier(string code, params DiagnosticResult[] expected) | ||
{ | ||
var test = new CSharpAnalyzerTest<DuplicateDependencyAnalyzer, NUnitVerifier>() | ||
{ | ||
TestState = | ||
{ | ||
Sources = { code } | ||
}, | ||
}; | ||
|
||
TestHelper.AddEmbeddedSources( | ||
test.TestState, | ||
"Robust.Shared.IoC.DependencyAttribute.cs" | ||
); | ||
|
||
// ExpectedDiagnostics cannot be set, so we need to AddRange here... | ||
test.TestState.ExpectedDiagnostics.AddRange(expected); | ||
|
||
return test.RunAsync(); | ||
} | ||
|
||
[Test] | ||
public async Task Test() | ||
{ | ||
const string code = """ | ||
using Robust.Shared.IoC; | ||
|
||
public sealed class Foo | ||
{ | ||
[Dependency] | ||
private object? Field; | ||
|
||
[Dependency] | ||
private object? Field2; | ||
|
||
[Dependency] | ||
private string? DifferentField; | ||
|
||
private string? NonDependency1; | ||
private string? NonDependency2; | ||
} | ||
"""; | ||
|
||
await Verifier(code, | ||
// /0/Test0.cs(9,21): warning RA0032: Another [Dependency] field of type 'object?' already exists in this type as field 'Field' | ||
VerifyCS.Diagnostic().WithSpan(9, 21, 9, 27).WithArguments("object?", "Field")); | ||
} | ||
} |
This file contains 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,126 @@ | ||
using System.Collections.Immutable; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.CSharp; | ||
using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
using Microsoft.CodeAnalysis.Diagnostics; | ||
using Robust.Roslyn.Shared; | ||
|
||
namespace Robust.Analyzers; | ||
|
||
#nullable enable | ||
|
||
/// <summary> | ||
/// Analyzer that detects duplicate <c>[Dependency]</c> fields inside a single type. | ||
/// </summary> | ||
[DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
public sealed class DuplicateDependencyAnalyzer : DiagnosticAnalyzer | ||
{ | ||
private const string DependencyAttributeType = "Robust.Shared.IoC.DependencyAttribute"; | ||
|
||
private static readonly DiagnosticDescriptor Rule = new( | ||
Diagnostics.IdDuplicateDependency, | ||
"Duplicate dependency field", | ||
"Another [Dependency] field of type '{0}' already exists in this type with field '{1}'", | ||
"Usage", | ||
DiagnosticSeverity.Warning, | ||
true); | ||
|
||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); | ||
|
||
public override void Initialize(AnalysisContext context) | ||
{ | ||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
context.EnableConcurrentExecution(); | ||
context.RegisterCompilationStartAction(compilationContext => | ||
{ | ||
var dependencyAttributeType = compilationContext.Compilation.GetTypeByMetadataName(DependencyAttributeType); | ||
if (dependencyAttributeType == null) | ||
return; | ||
compilationContext.RegisterSymbolStartAction(symbolContext => | ||
{ | ||
var typeSymbol = (INamedTypeSymbol)symbolContext.Symbol; | ||
// Only deal with non-static classes, doesn't make sense to have dependencies in anything else. | ||
if (typeSymbol.TypeKind != TypeKind.Class || typeSymbol.IsStatic) | ||
return; | ||
var state = new AnalyzerState(dependencyAttributeType); | ||
symbolContext.RegisterSyntaxNodeAction(state.AnalyzeField, SyntaxKind.FieldDeclaration); | ||
symbolContext.RegisterSymbolEndAction(state.End); | ||
}, | ||
SymbolKind.NamedType); | ||
}); | ||
} | ||
|
||
private sealed class AnalyzerState(INamedTypeSymbol dependencyAttributeType) | ||
{ | ||
private readonly Dictionary<ITypeSymbol, List<IFieldSymbol>> _dependencyFields = new(SymbolEqualityComparer.Default); | ||
|
||
public void AnalyzeField(SyntaxNodeAnalysisContext context) | ||
{ | ||
var field = (FieldDeclarationSyntax)context.Node; | ||
if (field.AttributeLists.Count == 0) | ||
return; | ||
|
||
if (context.ContainingSymbol is not IFieldSymbol fieldSymbol) | ||
return; | ||
|
||
// Can't have [Dependency]s for non-reference types. | ||
if (!fieldSymbol.Type.IsReferenceType) | ||
return; | ||
|
||
if (!IsDependency(context.ContainingSymbol)) | ||
return; | ||
|
||
lock (_dependencyFields) | ||
{ | ||
if (!_dependencyFields.TryGetValue(fieldSymbol.Type, out var dependencyFields)) | ||
{ | ||
dependencyFields = []; | ||
_dependencyFields.Add(fieldSymbol.Type, dependencyFields); | ||
} | ||
|
||
dependencyFields.Add(fieldSymbol); | ||
} | ||
} | ||
|
||
private bool IsDependency(ISymbol symbol) | ||
{ | ||
foreach (var attributeData in symbol.GetAttributes()) | ||
{ | ||
if (SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, dependencyAttributeType)) | ||
return true; | ||
} | ||
|
||
return false; | ||
} | ||
|
||
public void End(SymbolAnalysisContext context) | ||
{ | ||
lock (_dependencyFields) | ||
{ | ||
foreach (var pair in _dependencyFields) | ||
{ | ||
var fieldType = pair.Key; | ||
var fields = pair.Value; | ||
if (fields.Count <= 1) | ||
continue; | ||
|
||
// Sort so we can have deterministic order to skip reporting for a single field. | ||
// Whichever sorts first doesn't get reported. | ||
fields.Sort(static (a, b) => string.Compare(a.Name, b.Name, StringComparison.Ordinal)); | ||
|
||
// Start at index 1 to skip first field. | ||
var firstField = fields[0]; | ||
for (var i = 1; i < fields.Count; i++) | ||
{ | ||
var field = fields[i]; | ||
|
||
context.ReportDiagnostic( | ||
Diagnostic.Create(Rule, field.Locations[0], fieldType.ToDisplayString(), firstField.Name)); | ||
} | ||
} | ||
} | ||
} | ||
} | ||
} |
This file contains 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 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 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 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 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