|
| 1 | +/* |
| 2 | + * COPYRIGHT: See COPYING in the top level directory |
| 3 | + * PROJECT: Core.Apps.Rules |
| 4 | + * FILE: MagicNumberAnalyzer.cs |
| 5 | + * PURPOSE: Detects unexplained numeric literals (magic numbers). |
| 6 | + * PROGRAMMER: Peter Geinitz (Wayfarer) |
| 7 | + */ |
| 8 | + |
| 9 | +using System; |
| 10 | +using System.Collections.Generic; |
| 11 | +using System.IO; |
| 12 | +using System.Linq; |
| 13 | +using Core.Apps.Enums; |
| 14 | +using Core.Apps.Helper; |
| 15 | +using Core.Apps.Interface; |
| 16 | +using Microsoft.CodeAnalysis; |
| 17 | +using Microsoft.CodeAnalysis.CSharp; |
| 18 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 19 | +using Weaver; |
| 20 | +using Weaver.Interfaces; |
| 21 | +using Weaver.Messages; |
| 22 | + |
| 23 | +namespace Core.Apps.Rules |
| 24 | +{ |
| 25 | + /// <inheritdoc cref="ICodeAnalyzer" /> |
| 26 | + /// <summary> |
| 27 | + /// Analyzer that detects unexplained numeric literals (magic numbers) in method bodies, which can hurt readability and maintainability. |
| 28 | + /// It ignores common "safe" numbers like 0, 1, -1, and 2, as well as literals that are part of constant definitions. |
| 29 | + /// </summary> |
| 30 | + /// <seealso cref="ICommand" /> |
| 31 | + public sealed class MagicNumberAnalyzer : ICommand, ICodeAnalyzer |
| 32 | + { |
| 33 | + /// <inheritdoc cref="ICodeAnalyzer" /> |
| 34 | + public string Namespace => "Analyzer"; |
| 35 | + |
| 36 | + /// <inheritdoc cref="ICodeAnalyzer" /> |
| 37 | + public string Name => "MagicNumber"; |
| 38 | + |
| 39 | + /// <inheritdoc cref="ICodeAnalyzer" /> |
| 40 | + public string Description => "Detects unexplained numeric literals in method bodies."; |
| 41 | + |
| 42 | + /// <inheritdoc /> |
| 43 | + public int ParameterCount => 1; |
| 44 | + |
| 45 | + /// <inheritdoc /> |
| 46 | + public CommandSignature Signature => new(Namespace, Name, ParameterCount); |
| 47 | + |
| 48 | + /// <summary> |
| 49 | + /// The safe numbers |
| 50 | + /// Constants that are usually considered "safe" or self-documenting |
| 51 | + /// </summary> |
| 52 | + private static readonly HashSet<string> SafeNumbers = new() { "0", "1", "-1", "2" }; |
| 53 | + |
| 54 | + /// <inheritdoc /> |
| 55 | + public IEnumerable<Diagnostic> Analyze(string filePath, string fileContent) |
| 56 | + { |
| 57 | + if (CoreHelper.ShouldIgnoreFile(filePath)) yield break; |
| 58 | + |
| 59 | + var tree = CSharpSyntaxTree.ParseText(fileContent); |
| 60 | + var compilation = CSharpCompilation.Create("Analysis") |
| 61 | + .AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location)) |
| 62 | + .AddSyntaxTrees(tree); |
| 63 | + |
| 64 | + var model = compilation.GetSemanticModel(tree); |
| 65 | + var root = tree.GetCompilationUnitRoot(); |
| 66 | + |
| 67 | + // Find all methods |
| 68 | + var methods = root.DescendantNodes().OfType<MethodDeclarationSyntax>(); |
| 69 | + |
| 70 | + foreach (var method in methods) |
| 71 | + { |
| 72 | + // Find all numeric literals inside the method body |
| 73 | + var literals = method.DescendantNodes().OfType<LiteralExpressionSyntax>() |
| 74 | + .Where(l => l.IsKind(SyntaxKind.NumericLiteralExpression)); |
| 75 | + |
| 76 | + foreach (var literal in literals) |
| 77 | + { |
| 78 | + string value = literal.Token.ValueText; |
| 79 | + |
| 80 | + // Skip "safe" numbers and ignore if it's already part of a constant definition |
| 81 | + if (SafeNumbers.Contains(value) || IsInConstantDefinition(literal)) |
| 82 | + continue; |
| 83 | + |
| 84 | + yield return new Diagnostic( |
| 85 | + Name, |
| 86 | + Enums.DiagnosticSeverity.Info, |
| 87 | + filePath, |
| 88 | + literal.GetLocation().GetLineSpan().StartLinePosition.Line + 1, |
| 89 | + $"Magic number '{value}' detected. Replace with a named constant.", |
| 90 | + DiagnosticImpact.Readability |
| 91 | + ); |
| 92 | + } |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + /// <summary> |
| 97 | + /// Determines whether [is in constant definition] [the specified node]. |
| 98 | + /// </summary> |
| 99 | + /// <param name="node">The node.</param> |
| 100 | + /// <returns> |
| 101 | + /// <c>true</c> if [is in constant definition] [the specified node]; otherwise, <c>false</c>. |
| 102 | + /// </returns> |
| 103 | + private static bool IsInConstantDefinition(SyntaxNode node) |
| 104 | + { |
| 105 | + // Don't flag if the literal is actually being assigned to a 'const' variable |
| 106 | + return node.Ancestors().OfType<FieldDeclarationSyntax>().Any(f => f.Modifiers.Any(SyntaxKind.ConstKeyword)); |
| 107 | + } |
| 108 | + |
| 109 | + /// <inheritdoc /> |
| 110 | + public CommandResult Execute(params string[] args) |
| 111 | + { |
| 112 | + try |
| 113 | + { |
| 114 | + var results = AnalyzerExecutor.ExecutePath(this, args, "Usage: MagicNumber <fileOrDirectoryPath>"); |
| 115 | + var output = results.Count > 0 |
| 116 | + ? string.Join("\n", results.Select(d => $"{Path.GetFileName(d.FilePath)} ({d.LineNumber}): {d.Message}")) |
| 117 | + : "No magic numbers found."; |
| 118 | + return CommandResult.Ok(output, EnumTypes.Wstring); |
| 119 | + } |
| 120 | + catch (Exception ex) |
| 121 | + { |
| 122 | + return CommandResult.Fail(ex.Message); |
| 123 | + } |
| 124 | + } |
| 125 | + } |
| 126 | +} |
0 commit comments