All files / src/rules identical_conditions.ts

97.56% Statements 240/246
94.04% Branches 79/84
100% Functions 15/15
97.56% Lines 240/246

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 2461x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 140x 140x 1x 1x 159x 159x 1x 1x 139x 139x 1x 1x 1x 34589x 34589x 34589x 34589x 1x 17301x 17301x 17301x 17301x 168552x 168552x 168552x 168552x 168552x 168552x 168552x 168552x 168552x 168552x 168552x 168552x 168552x 168552x 168552x 168552x 168552x 168552x 168552x 168552x 168552x 168552x 168552x 168552x 168552x 168552x 168552x 168552x 168552x 168552x 168552x 168552x 17301x 17301x 16683x 16683x 17301x 17301x 287x 287x 17301x 17301x 376x 376x 376x 376x 12x 12x 364x 376x 63x 63x 376x 3x 3x 376x 74x 74x 376x 331x 331x 364x 364x 364x 17301x 17301x 17301x 17301x 331x 331x 331x 1806x 1x 1x 1806x 55x 55x 55x 55x 55x 55x 55x 55x 2x 2x 53x 53x 53x 55x 34x 34x 55x 55x 55x 55x 55x 1805x 331x 331x 331x 17301x 17301x 17301x 53x 43x 53x 7x 7x 3x 3x 17301x 17301x 17301x 96x 96x 96x 96x 96x 96x 96x 12x 12x 84x 190x 190x 84x 84x 17301x 17301x 74x 74x 74x 74x 103x 88x 103x 13x 15x 1x 1x 103x 73x 73x 74x 3x 3x 3x 3x 70x 70x 70x 17301x 17301x 63x 63x 63x 63x     63x 63x 63x 63x 63x 63x 1x 1x 1x 1x 1x 63x 63x 63x 1x 1x 1x 1x 62x 62x 62x 17301x 17301x 3x 3x 3x 3x     3x 3x 5x 5x     5x 7x 7x 5x 3x 3x 3x 2x 2x 2x 2x 1x 1x 1x 17301x
import * as Expressions from "../abap/2_statements/expressions";
import * as Statements from "../abap/2_statements/statements";
import * as Structures from "../abap/3_structures/structures";
import {Issue} from "../issue";
import {BasicRuleConfig} from "./_basic_rule_config";
import {ABAPRule} from "./_abap_rule";
import {IRuleMetadata, RuleTag} from "./_irule";
import {ExpressionNode, StructureNode} from "../abap/nodes";
import {ABAPFile} from "../abap/abap_file";
import {countLeadingNot} from "../abap/5_syntax/_key_compare";
 
class Conditions {
  private readonly arr: string[] = [];
 
  public constructor() {
    this.arr = [];
  }
 
  public push(e: ExpressionNode) {
    this.arr.push(e.concatTokens());
  }
 
  public findFirstDuplicate() {
    return this.arr.find(x => this.arr.indexOf(x) !== this.arr.lastIndexOf(x));
  }
}
 
 
export class IdenticalConditionsConf extends BasicRuleConfig {
  /** Report a comparison of an operand with itself, like a = a or a <> a */
  public selfComparison: boolean = true;
}
 
export class IdenticalConditions extends ABAPRule {
  private conf = new IdenticalConditionsConf();
 
  public getMetadata(): IRuleMetadata {
    return {
      key: "identical_conditions",
      title: "Identical conditions",
      shortDescription: `Find identical conditions in IF + CASE + WHILE etc
 
Prerequsites: code is pretty printed with identical cAsE`,
      extendedInformation: `Option selfComparison: reports a comparison with =, <>, <, >, <= or >= (and EQ, NE, LT, GT, LE, GE)
whose two operands are the same data object, like a = a or ls_new-id <> ls_new-id. The comparison is always true or
always false, usually one side should be another field.
 
Only operands that are data objects are compared: fields, components, attributes, field symbols, dereferences,
offset/length and table expressions without calls. Not reported: method calls and built-in functions, which can
return different values, literals like 1 = 1, ASSERT, and SQL conditions.`,
      tags: [RuleTag.SingleFile],
      badExample: `IF foo = bar OR 1 = a OR foo = bar.
ENDIF.
CASE bar.
  WHEN '1'.
  WHEN 'A' OR '1'.
ENDCASE.
IF ls_new-id = ls_new-id.
ENDIF.`,
      goodExample: `IF foo = bar OR 1 = a.
ENDIF.
CASE bar.
  WHEN '1'.
  WHEN 'A'.
ENDCASE.
IF ls_new-id = ls_old-id.
ENDIF.`,
    };
  }
 
  public getConfig() {
    return this.conf;
  }
 
  public setConfig(conf: IdenticalConditionsConf) {
    this.conf = conf;
  }
 
  public runParsed(file: ABAPFile): Issue[] {
    let issues: Issue[] = [];
 
    const structure = file.getStructure();
    if (structure === undefined) {
      return [];
    }
 
    for (const i of structure.findAllStructures(Structures.If)) {
      issues = issues.concat(this.analyzeIf(file, i));
    }
    for (const i of structure.findAllStructures(Structures.Case)) {
      issues = issues.concat(this.analyzeWhen(file, i));
    }
    for (const i of structure.findAllExpressions(Expressions.Cond)) {
      issues = issues.concat(this.analyzeCond(file, i));
    }
    if (this.conf.selfComparison) {
      issues = issues.concat(this.analyzeSelfComparison(file));
    }
 
    return issues;
  }
 
////////////////
 
  private analyzeSelfComparison(file: ABAPFile): Issue[] {
    const issues: Issue[] = [];
 
    for (const statement of file.getStatements()) {
      if (statement.get() instanceof Statements.Assert) {
        continue;
      }
      for (const compare of statement.findAllExpressionsRecursive(Expressions.Compare)) {
        const children = compare.getChildren();
        const nots = countLeadingNot(compare);
        const negated = nots % 2 === 1;
        const rest = children.slice(nots);
        if (rest.length !== 3
            || !(rest[0] instanceof ExpressionNode) || !(rest[0].get() instanceof Expressions.Source)
            || !(rest[1] instanceof ExpressionNode) || !(rest[1].get() instanceof Expressions.CompareOperator)
            || !(rest[2] instanceof ExpressionNode) || !(rest[2].get() instanceof Expressions.Source)) {
          continue;
        }
        const operator = rest[1].concatTokens().toUpperCase().replace(/ /g, "");
        const value = this.selfValue(operator);
        const left = this.dataObject(rest[0]);
        if (value === undefined || left === undefined || left !== this.dataObject(rest[2])) {
          continue;
        }
        const result = value !== negated ? "true" : "false";
        const message = "Comparison is always " + result + ", " + rest[0].concatTokens() + " is compared with itself";
        issues.push(Issue.atRange(file, compare.getFirstToken().getStart(), compare.getLastToken().getEnd(),
                                  message, this.getMetadata().key, this.conf.severity));
      }
    }
 
    return issues;
  }
 
  /** result of comparing a value with itself, undefined for operators like CO or CP */
  private selfValue(operator: string): boolean | undefined {
    if (["=", "EQ", "<=", "=<", "LE", ">=", "=>", "GE"].includes(operator)) {
      return true;
    } else if (["<>", "><", "NE", "<", "LT", ">", "GT"].includes(operator)) {
      return false;
    }
    return undefined;
  }
 
  /** the text of an operand that is a data object without calls, names in upper case, literals as they are */
  private dataObject(source: ExpressionNode): string | undefined {
    const children = source.getChildren();
    if (!(children[0] instanceof ExpressionNode) || !(children[0].get() instanceof Expressions.FieldChain)
        || (children.length === 2 && !(children[1].get() instanceof Expressions.Dereference))
        || children.length > 2
        || source.findFirstExpression(Expressions.MethodCall) !== undefined
        || source.findFirstExpression(Expressions.MethodCallChain) !== undefined
        || source.findFirstExpression(Expressions.NewObject) !== undefined) {
      return undefined;
    }
    return source.getTokens().map(t => {
      const str = t.getStr();
      return str.startsWith("'") || str.startsWith("`") || str.startsWith("|") || str.startsWith("}") ? str : str.toUpperCase();
    }).join(" ");
  }
 
  private analyzeCond(file: ABAPFile, node: ExpressionNode): Issue[] {
    const conditions = new Conditions();
    let operator = "";
 
    for (const c of node.getChildren()) {
      if (c instanceof ExpressionNode) {
        conditions.push(c);
      } else if (operator === "") {
        operator = c.get().getStr().toUpperCase();
      } else if (operator !== c.get().getStr().toUpperCase()) {
        return [];
      }
    }
 
    const duplicate = conditions.findFirstDuplicate();
    if (duplicate) {
      const message = "Identical conditions: " + duplicate;
      const issue = Issue.atToken(file, node.getFirstToken(), message, this.getMetadata().key, this.conf.severity);
      return [issue];
    }
 
    return [];
  }
 
  private analyzeIf(file: ABAPFile, node: StructureNode): Issue[] {
    const conditions = new Conditions();
 
    const i = node.findDirectStatement(Statements.If);
    if (i === undefined) {
      throw new Error("identical_conditions, no IF found");
    }
    const c = i?.findDirectExpression(Expressions.Cond);
    if (c) {
      conditions.push(c);
    }
 
    for (const e of node.findDirectStructures(Structures.ElseIf)) {
      const c = e.findDirectStatement(Statements.ElseIf)?.findDirectExpression(Expressions.Cond);
      if (c) {
        conditions.push(c);
      }
    }
 
    const duplicate = conditions.findFirstDuplicate();
    if (duplicate) {
      const message = "Identical conditions: " + duplicate;
      const issue = Issue.atStatement(file, i, message, this.getMetadata().key, this.conf.severity);
      return [issue];
    }
 
    return [];
  }
 
  private analyzeWhen(file: ABAPFile, node: StructureNode): Issue[] {
    const conditions = new Conditions();
 
    const i = node.findDirectStatement(Statements.Case);
    if (i === undefined) {
      throw new Error("identical_conditions, no CASE found");
    }
 
    for (const e of node.findDirectStructures(Structures.When)) {
      const w = e.findDirectStatement(Statements.When);
      if (w === undefined) {
        continue;
      }
      for (const s of w.findAllExpressions(Expressions.Source)) {
        conditions.push(s);
      }
    }
 
    const duplicate = conditions.findFirstDuplicate();
    if (duplicate) {
      const message = "Identical conditions: " + duplicate;
      const issue = Issue.atStatement(file, i, message, this.getMetadata().key, this.conf.severity);
      return [issue];
    }
 
    return [];
  }
}