A symbol analyzer registers action callbacks to analyze one or more kinds of symbol declarations, such as types, methods, fields, properties, events, and so on, reports semantic issues about declarations.
In this section, we will create a symbol analyzer that extends the compiler diagnostic CS0542 (member names cannot be the same as their enclosing type) to report a diagnostic if member names are the same as any of the outer parent type. For example, the analyzer will report a diagnostic for the innermost type NestedClass
here:
public class NestedClass { public class InnerClass { public class NestedClass { } } }
You will need to have created and opened an analyzer project, say CSharpAnalyzers
in Visual Studio 2017. Refer to the first recipe in this chapter to create this project.
- In
Solution Explorer
, double-click onResources.resx
file inCSharpAnalyzers
project to open the resource file in the resource editor. - Replace the existing resource strings for
AnalyzerDescription
,AnalyzerMessageFormat
andAnalyzerTitle
with new strings:
- Replace the
Initialize
method implementation with the following:
public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(symbolContext => { var symbolName = symbolContext.Symbol.Name; // Skip the immediate containing type, CS0542 already covers this case. var outerType = symbolContext.Symbol.ContainingType?.ContainingType; while (outerType != null) { // Check if the current outer type has the same name as the given member. if (symbolName.Equals(outerType.Name)) { // For all such symbols, report a diagnostic. var diagnostic = Diagnostic.Create(Rule, symbolContext.Symbol.Locations[0], symbolContext.Symbol.Name); symbolContext.ReportDiagnostic(diagnostic); return; } outerType = outerType.ContainingType; } }, SymbolKind.NamedType, SymbolKind.Method, SymbolKind.Field, SymbolKind.Event, SymbolKind.Property); }
- Click on Ctrl + F5 to start a new Visual Studio instance with the analyzer enabled.
- In the new Visual Studio instance, create a new C# class library with the following code:
namespace ClassLibrary { public class OuterClass { public class NestedClass { public class NestedClass { } } } }
- Verify the compiler reported diagnostic CS0542 in the error list:
'NestedClass': member names cannot be the same as their enclosing type
. - Change the class library code to following:
namespace ClassLibrary { public class OuterClass { public class NestedClass { public class InnerClass { public class NestedClass { } } } } }
- Verify that CS0542 isn t reported anymore, but the error list has our analyzer diagnostic:
- Replace the innermost type declaration for
NestedClass
with a field:public int NestedClass
, and verify the same analyzer diagnostic is reported. You should get the same diagnostic for other member kinds such as method, property, and events with the same name.
Symbol analyzers register one or more symbol action callbacks to analyze symbol kinds of interest. Note that, unlike the default implementation that registered a delegate method named AnalyzeSymbol
, we registered a lambda callback.
We specified interest in analyzing all the top-level symbol kinds that can have an enclosing type, namely types, methods, fields, properties, and events in the RegisterSymbolAction
invocation:
context.RegisterSymbolAction(symbolContext => { ... }, SymbolKind.NamedType, SymbolKind.Method, SymbolKind.Field, SymbolKind.Event, SymbolKind.Property);
The analyzer driver ensures that the registered lambda is invoked for all symbols of the registered interest kinds in the compilation.
Analysis skips the immediate enclosing type, as C# compiler already reports error CS0542, if a member has the same name as its enclosing type.
// Skip the immediate containing type, CS0542 already covers this case. var outerType = symbolContext.Symbol.ContainingType?.ContainingType;
Core analysis works by looping over the outer types and comparing the name of the symbol in a symbol analysis context with the relevant outer types, until it finds a match, in which case, it reports a diagnostic; if the outer type has no containing type, it doesn t report a diagnostic.
while (outerType != null) { // Check if the current outer type has the same name as the given member. if (symbolName.Equals(outerType.Name)) { // For all such symbols, report a diagnostic. ... } outerType = outerType.ContainingType; }
Trivia: The preceding implementation of the symbol analyzer does not have optimal performance. For example, if you have n levels of type nesting, and m fields in the inner innermost nested type, the analysis we implemented will be O(m*n) algorithmic complexity. Can you implement an alternate implementation where the analysis can be implemented with a much superior O(m + n) complexity?
Our current analyzer implementation is completely stateless because it doesn t require analysis that is dependent upon more than one symbol at a time. We analyze each symbol individually and report diagnostics for it. However, if you need to do more complex analysis that requires collecting state from multiple symbols and then doing a compilation-wide analysis, you should write a stateful compilation analyzer with symbol and compilation actions. This is covered later in this chapter in the recipe Creating a compilation analyzer to analyze a whole compilation and report issues.