|
| 1 | +// © 2024 Koninklijke Philips N.V. See License.md in the project root for license information. |
| 2 | + |
| 3 | +using Microsoft.CodeAnalysis; |
| 4 | +using Microsoft.CodeAnalysis.CSharp; |
| 5 | +using Microsoft.CodeAnalysis.CSharp.Syntax; |
| 6 | +using Microsoft.CodeAnalysis.Diagnostics; |
| 7 | +using Philips.CodeAnalysis.Common; |
| 8 | + |
| 9 | +namespace Philips.CodeAnalysis.MaintainabilityAnalyzers.Maintainability |
| 10 | +{ |
| 11 | + /// <summary> |
| 12 | + /// Diagnostic for incorrect condition in backwards for-loops. |
| 13 | + /// </summary> |
| 14 | + [DiagnosticAnalyzer(LanguageNames.CSharp)] |
| 15 | + public class AvoidIncorrectForLoopConditionAnalyzer : SingleDiagnosticAnalyzer |
| 16 | + { |
| 17 | + private const string Title = "Backwards for-loop boundary check should use >= 0 instead of > 0"; |
| 18 | + private const string MessageFormat = "Use '>= 0' instead of '> 0' in backwards for-loop condition to include element at index 0"; |
| 19 | + private const string Description = "When looping backwards from a collection count to 0, use '>= 0' to ensure the element at index 0 is processed"; |
| 20 | + |
| 21 | + public AvoidIncorrectForLoopConditionAnalyzer() |
| 22 | + : base(DiagnosticId.AvoidIncorrectForLoopCondition, Title, MessageFormat, Description, Categories.Maintainability) |
| 23 | + { } |
| 24 | + |
| 25 | + /// <summary> |
| 26 | + /// <inheritdoc cref="DiagnosticAnalyzer"/> |
| 27 | + /// </summary> |
| 28 | + protected override void InitializeCompilation(CompilationStartAnalysisContext context) |
| 29 | + { |
| 30 | + context.RegisterSyntaxNodeAction(AnalyzeForStatement, SyntaxKind.ForStatement); |
| 31 | + } |
| 32 | + |
| 33 | + private void AnalyzeForStatement(SyntaxNodeAnalysisContext context) |
| 34 | + { |
| 35 | + if (Helper.ForGeneratedCode.IsGeneratedCode(context)) |
| 36 | + { |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + var forStatement = (ForStatementSyntax)context.Node; |
| 41 | + |
| 42 | + // Check if this is a backwards loop with problematic condition |
| 43 | + if (IsBackwardsLoopWithIncorrectCondition(forStatement)) |
| 44 | + { |
| 45 | + Location location = forStatement.Condition.GetLocation(); |
| 46 | + context.ReportDiagnostic(Diagnostic.Create(Rule, location)); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + private static bool IsBackwardsLoopWithIncorrectCondition(ForStatementSyntax forStatement) |
| 51 | + { |
| 52 | + // Must have a condition |
| 53 | + if (forStatement.Condition == null) |
| 54 | + { |
| 55 | + return false; |
| 56 | + } |
| 57 | + |
| 58 | + // Must have incrementors (decrementors in this case) |
| 59 | + if (forStatement.Incrementors.Count == 0) |
| 60 | + { |
| 61 | + return false; |
| 62 | + } |
| 63 | + |
| 64 | + // Check if any incrementor is decrementing |
| 65 | + var hasDecrement = false; |
| 66 | + var decrementedVariable = string.Empty; |
| 67 | + |
| 68 | + foreach (ExpressionSyntax incrementor in forStatement.Incrementors) |
| 69 | + { |
| 70 | + if (IsDecrementOperation(incrementor, out var varName)) |
| 71 | + { |
| 72 | + hasDecrement = true; |
| 73 | + decrementedVariable = varName; |
| 74 | + break; |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + if (!hasDecrement || string.IsNullOrEmpty(decrementedVariable)) |
| 79 | + { |
| 80 | + return false; |
| 81 | + } |
| 82 | + |
| 83 | + // Check if condition is "variable > 0" |
| 84 | + return IsGreaterThanZeroCondition(forStatement.Condition, decrementedVariable); |
| 85 | + } |
| 86 | + |
| 87 | + private static bool IsDecrementOperation(ExpressionSyntax expression, out string variableName) |
| 88 | + { |
| 89 | + variableName = null; |
| 90 | + |
| 91 | + switch (expression) |
| 92 | + { |
| 93 | + // Handle i--, --i |
| 94 | + case PostfixUnaryExpressionSyntax postfix when postfix.IsKind(SyntaxKind.PostDecrementExpression): |
| 95 | + if (postfix.Operand is IdentifierNameSyntax postfixIdentifier) |
| 96 | + { |
| 97 | + variableName = postfixIdentifier.Identifier.ValueText; |
| 98 | + return true; |
| 99 | + } |
| 100 | + break; |
| 101 | + |
| 102 | + case PrefixUnaryExpressionSyntax prefix when prefix.IsKind(SyntaxKind.PreDecrementExpression): |
| 103 | + if (prefix.Operand is IdentifierNameSyntax prefixIdentifier) |
| 104 | + { |
| 105 | + variableName = prefixIdentifier.Identifier.ValueText; |
| 106 | + return true; |
| 107 | + } |
| 108 | + break; |
| 109 | + |
| 110 | + // Handle i -= 1 |
| 111 | + case AssignmentExpressionSyntax assignment when assignment.IsKind(SyntaxKind.SubtractAssignmentExpression): |
| 112 | + if (assignment.Left is IdentifierNameSyntax subtractIdentifier && IsLiteralOne(assignment.Right)) |
| 113 | + { |
| 114 | + variableName = subtractIdentifier.Identifier.ValueText; |
| 115 | + return true; |
| 116 | + } |
| 117 | + break; |
| 118 | + |
| 119 | + // Handle i = i - 1 |
| 120 | + case AssignmentExpressionSyntax assignment when assignment.IsKind(SyntaxKind.SimpleAssignmentExpression): |
| 121 | + if (assignment.Left is IdentifierNameSyntax leftId && |
| 122 | + assignment.Right is BinaryExpressionSyntax binary && |
| 123 | + binary.IsKind(SyntaxKind.SubtractExpression) && |
| 124 | + binary.Left is IdentifierNameSyntax rightId && |
| 125 | + leftId.Identifier.ValueText == rightId.Identifier.ValueText && |
| 126 | + IsLiteralOne(binary.Right)) |
| 127 | + { |
| 128 | + variableName = leftId.Identifier.ValueText; |
| 129 | + return true; |
| 130 | + } |
| 131 | + break; |
| 132 | + } |
| 133 | + |
| 134 | + return false; |
| 135 | + } |
| 136 | + |
| 137 | + private static bool IsLiteralOne(ExpressionSyntax expression) |
| 138 | + { |
| 139 | + return expression is LiteralExpressionSyntax literal && |
| 140 | + literal.IsKind(SyntaxKind.NumericLiteralExpression) && |
| 141 | + literal.Token.ValueText == "1"; |
| 142 | + } |
| 143 | + |
| 144 | + private static bool IsGreaterThanZeroCondition(ExpressionSyntax condition, string variableName) |
| 145 | + { |
| 146 | + if (condition is BinaryExpressionSyntax binary) |
| 147 | + { |
| 148 | + // Check for "variable > 0" |
| 149 | + if (binary.IsKind(SyntaxKind.GreaterThanExpression) && |
| 150 | + binary.Left is IdentifierNameSyntax leftId && |
| 151 | + leftId.Identifier.ValueText == variableName && |
| 152 | + IsLiteralZero(binary.Right)) |
| 153 | + { |
| 154 | + return true; |
| 155 | + } |
| 156 | + |
| 157 | + // Check for "0 < variable" (equivalent but less common) |
| 158 | + if (binary.IsKind(SyntaxKind.LessThanExpression) && |
| 159 | + IsLiteralZero(binary.Left) && |
| 160 | + binary.Right is IdentifierNameSyntax rightId && |
| 161 | + rightId.Identifier.ValueText == variableName) |
| 162 | + { |
| 163 | + return true; |
| 164 | + } |
| 165 | + } |
| 166 | + |
| 167 | + return false; |
| 168 | + } |
| 169 | + |
| 170 | + private static bool IsLiteralZero(ExpressionSyntax expression) |
| 171 | + { |
| 172 | + return expression is LiteralExpressionSyntax literal && |
| 173 | + literal.IsKind(SyntaxKind.NumericLiteralExpression) && |
| 174 | + literal.Token.ValueText == "0"; |
| 175 | + } |
| 176 | + } |
| 177 | +} |
0 commit comments