|
| 1 | +namespace EffectiveCSharp.Analyzers; |
| 2 | + |
| 3 | +/// <summary> |
| 4 | +/// A <see cref="DiagnosticAnalyzer"/> for Effective C# Item #1 - Prefer implicit types except on numbers. |
| 5 | +/// </summary> |
| 6 | +/// <seealso cref="Microsoft.CodeAnalysis.Diagnostics.DiagnosticAnalyzer" /> |
| 7 | +[DiagnosticAnalyzer(LanguageNames.CSharp)] |
| 8 | +public class PreferExplicitTypesOnNumbersAnalyzer : DiagnosticAnalyzer |
| 9 | +{ |
| 10 | + private const string Id = DiagnosticIds.PreferImplicitlyTypedLocalVariables; |
| 11 | + |
| 12 | + private static readonly DiagnosticDescriptor Rule = new( |
| 13 | + id: Id, |
| 14 | + title: "Prefer implicitly typed local variables", |
| 15 | + description: "Use var to declare local variables for better readability and efficiency, except for built-in numeric types where explicit typing prevents potential conversion issues.", |
| 16 | + messageFormat: "Use explicit type instead of 'var' for numeric variables", |
| 17 | + category: "Style", |
| 18 | + defaultSeverity: DiagnosticSeverity.Info, |
| 19 | + isEnabledByDefault: true, |
| 20 | + helpLinkUri: $"https://github.com/rjmurillo/EffectiveCSharp.Analyzers/blob/{ThisAssembly.GitCommitId}/docs/{Id}.md"); |
| 21 | + |
| 22 | + /// <inheritdoc /> |
| 23 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); |
| 24 | + |
| 25 | + /// <inheritdoc /> |
| 26 | + public override void Initialize(AnalysisContext context) |
| 27 | + { |
| 28 | + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); |
| 29 | + context.EnableConcurrentExecution(); |
| 30 | + context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.LocalDeclarationStatement); |
| 31 | + } |
| 32 | + |
| 33 | + private static void AnalyzeNode(SyntaxNodeAnalysisContext context) |
| 34 | + { |
| 35 | + LocalDeclarationStatementSyntax localDeclaration = (LocalDeclarationStatementSyntax)context.Node; |
| 36 | + |
| 37 | + foreach (VariableDeclaratorSyntax variable in localDeclaration.Declaration.Variables) |
| 38 | + { |
| 39 | + ExpressionSyntax? initializer = variable.Initializer?.Value; |
| 40 | + |
| 41 | + if (initializer is null) |
| 42 | + { |
| 43 | + continue; |
| 44 | + } |
| 45 | + |
| 46 | + TypeInfo typeInfo = context.SemanticModel.GetTypeInfo(initializer, context.CancellationToken); |
| 47 | + ITypeSymbol? type = typeInfo.ConvertedType; |
| 48 | + |
| 49 | + if (type?.IsNumericType() != true) |
| 50 | + { |
| 51 | + continue; |
| 52 | + } |
| 53 | + |
| 54 | + if (localDeclaration.Declaration.Type.IsVar) |
| 55 | + { |
| 56 | + Diagnostic diagnostic = localDeclaration.GetLocation().CreateDiagnostic(Rule); |
| 57 | + context.ReportDiagnostic(diagnostic); |
| 58 | + } |
| 59 | + else if (HasPotentialConversionIssues(type, initializer, context.SemanticModel, context.CancellationToken)) |
| 60 | + { |
| 61 | + Diagnostic diagnostic = initializer.GetLocation().CreateDiagnostic(Rule); |
| 62 | + context.ReportDiagnostic(diagnostic); |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + private static bool HasPotentialConversionIssues(ITypeSymbol type, ExpressionSyntax initializer, SemanticModel semanticModel, CancellationToken cancellationToken) |
| 68 | + { |
| 69 | + TypeInfo typeInfo = semanticModel.GetTypeInfo(initializer, cancellationToken); |
| 70 | + return !SymbolEqualityComparer.IncludeNullability.Equals(typeInfo.Type, type); |
| 71 | + } |
| 72 | +} |
0 commit comments