All files / src/rules prefix_is_current_class.ts

98.03% Statements 200/204
87.03% Branches 47/54
100% Functions 10/10
98.03% Lines 200/204

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 2041x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 21574x 21574x 21574x 21574x 21574x 21574x 1x 10796x 10796x 10796x 10796x 32193x 32193x 32193x 32193x 32193x 32193x 32193x 32193x 32193x 10796x 10796x 10267x 10267x 10796x 10796x 242x 242x 10796x 10796x 269x 269x 10796x 10796x 269x 269x 12x 12x 257x 257x 257x 269x 61x 61x     61x 61x 61x 68x 68x 3x 3x     3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 68x 61x 61x 257x 257x 257x 10796x 10796x 269x 269x 12x 12x 257x 257x 257x 257x 257x 257x 269x 272x 272x 272x 272x 272x 1085x 1085x 14x 14x 14x 14x 14x 14x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 1085x 1071x 1071x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1085x 272x 257x 257x 10796x 10796x 10796x 14x 14x 14x 86x 86x 15x 15x 15x 15x 15x 86x 14x 14x 10796x 10796x 10796x 10796x 272x 272x 138x 138x 134x 134x 134x 134x 272x 71x 71x 71x 71x 71x 71x 71x 67x 39x 39x 67x 67x 71x 71x 71x 71x 13x 13x 71x 3x 3x 3x 3x 3x 71x 71x 25x 25x 71x 127x 127x 46x 134x 134x 10796x
import {Issue} from "../issue";
import {ABAPRule} from "./_abap_rule";
import * as Structures from "../abap/3_structures/structures";
import * as Statements from "../abap/2_statements/statements";
import {BasicRuleConfig} from "./_basic_rule_config";
import {ClassName, MethodCall, InterfaceName, TypeName, MethodName, MethodParamName, DefinitionName, InlineData, TargetField} from "../abap/2_statements/expressions";
import {Position} from "../position";
import {EditHelper} from "../edit_helper";
import {RuleTag} from "./_irule";
import {ABAPFile} from "../abap/abap_file";
import {StatementNode, StructureNode} from "../abap/nodes";
import {Comment} from "../abap/1_lexer/tokens/comment";
 
export class PrefixIsCurrentClassConf extends BasicRuleConfig {
  /**
   * Checks usages of self references with 'me' when calling instance methods
   */
  public omitMeInstanceCalls: boolean = true;
}
 
export class PrefixIsCurrentClass extends ABAPRule {
  private conf = new PrefixIsCurrentClassConf();
 
  public getMetadata() {
    return {
      key: "prefix_is_current_class",
      title: "Prefix is current class",
      shortDescription: `Reports errors if the current class or interface references itself with "current_class=>"`,
      // eslint-disable-next-line max-len
      extendedInformation: `https://github.com/SAP/styleguides/blob/main/clean-abap/CleanABAP.md#omit-the-self-reference-me-when-calling-an-instance-attribute-or-method`,
      tags: [RuleTag.Styleguide, RuleTag.Quickfix, RuleTag.SingleFile],
    };
  }
 
  public getConfig() {
    return this.conf;
  }
 
  public setConfig(conf: PrefixIsCurrentClassConf) {
    this.conf = conf;
  }
 
  public runParsed(file: ABAPFile) {
    return this.checkClasses(file).concat(this.checkInterfaces(file));
  }
 
  private checkInterfaces(file: ABAPFile): Issue[] {
    const struc = file.getStructure();
    if (struc === undefined) {
      return [];
    }
 
    const issues: Issue[] = [];
 
    for (const s of struc.findDirectStructures(Structures.Interface)) {
      const name = s.findFirstExpression(InterfaceName)?.getFirstToken().getStr().toUpperCase();
      if (name === undefined) {
        continue;
      }
      const staticAccess = name + "=>";
 
      for (const e of s.findAllExpressions(TypeName)) {
        const concat = e.concatTokens().toUpperCase();
        if (concat.startsWith(staticAccess)) {
          const stat = e.findDirectTokenByText("=>");
          if (stat === undefined) {
            continue;
          }
          const start = new Position(stat.getRow(), stat.getCol() - name.length);
          const end = new Position(stat.getRow(), stat.getCol() + 2);
          const fix = EditHelper.deleteRange(file, start, end);
          issues.push(Issue.atToken(
            file,
            e.getFirstToken(),
            "Reference to current interface can be omitted",
            this.getMetadata().key,
            this.conf.severity,
            fix));
        }
      }
 
    }
 
    return issues;
  }
 
  private checkClasses(file: ABAPFile): Issue[] {
    const struc = file.getStructure();
    if (struc === undefined) {
      return [];
    }
 
    const issues: Issue[] = [];
    const classStructures = struc.findDirectStructures(Structures.ClassImplementation);
    classStructures.push(...struc.findDirectStructures(Structures.ClassDefinition));
    const meAccess = "ME->";
 
    for (const c of classStructures) {
      const className = c.findFirstExpression(ClassName)!.getFirstToken().getStr().toUpperCase();
      const staticAccess = className + "=>";
      const shadowed = this.buildShadowedNames(struc, c, className);
 
      for (const s of c.findAllStatementNodes()) {
        const concat = s.concatTokensWithoutStringsAndComments().toUpperCase();
        if (concat.includes(staticAccess)) {
          // when the referenced member is shadowed by a method parameter or local
          // declaration, the class prefix is required and cannot be omitted, see issues #3755 and #3707
          const names = shadowed.get(s);
          const ref = this.findStaticReferences(s, className).find(
            r => r.member === undefined || names?.has(r.member) !== true);
          if (ref) {
            const tokenPos = ref.pos;
            const end = new Position(tokenPos.getRow(), tokenPos.getCol() + className.length + 2);
            const fix = EditHelper.deleteRange(file, tokenPos, end);
            issues.push(Issue.atRange(
              file,
              tokenPos, end,
              "Reference to current class can be omitted: \"" + staticAccess + "\"",
              this.getMetadata().key,
              this.conf.severity,
              fix));
          }
        } else if (this.conf.omitMeInstanceCalls === true
            && concat.includes(meAccess)
            && s.findFirstExpression(MethodCall)) {
          const tokenPos = s.findTokenSequencePosition("me", "->");
          if (tokenPos) {
            const end = new Position(tokenPos.getRow(), tokenPos.getCol() + 4);
            const fix = EditHelper.deleteRange(file, tokenPos, end);
            issues.push(Issue.atRange(
              file,
              tokenPos, end,
              "Omit 'me->' in instance calls",
              this.getMetadata().key, this.conf.severity, fix));
          }
        }
      }
    }
    return issues;
  }
 
  /** finds "className=>member" references in the statement, position is the start of the class name */
  private findStaticReferences(s: StatementNode, className: string): {pos: Position, member: string | undefined}[] {
    const refs: {pos: Position, member: string | undefined}[] = [];
    const tokens = s.getTokens().filter(t => !(t instanceof Comment));
    for (let i = 0; i < tokens.length - 1; i++) {
      if (tokens[i].getStr().toUpperCase() === className
          && tokens[i + 1].getStr() === "=>") {
        refs.push({
          pos: tokens[i].getStart(),
          member: tokens[i + 2]?.getStr().toUpperCase(),
        });
      }
    }
    return refs;
  }
 
  /** for each statement in a method implementation: the method parameter and local
   *  declaration names that shadow class members of the same name */
  private buildShadowedNames(struc: StructureNode, impl: StructureNode, className: string): Map<StatementNode, Set<string>> {
    const map = new Map<StatementNode, Set<string>>();
    if (!(impl.get() instanceof Structures.ClassImplementation)) {
      return map;
    }
 
    const definition = struc.findDirectStructures(Structures.ClassDefinition).find(
      d => d.findFirstExpression(ClassName)?.getFirstToken().getStr().toUpperCase() === className);
 
    for (const method of impl.findAllStructuresRecursive(Structures.Method)) {
      const names = new Set<string>();
 
      const methodName = method.findFirstStatement(Statements.MethodImplementation)
        ?.findFirstExpression(MethodName)?.concatTokens().toUpperCase();
      if (definition !== undefined && methodName !== undefined) {
        for (const def of definition.findAllStatements(Statements.MethodDef)) {
          if (def.findFirstExpression(MethodName)?.concatTokens().toUpperCase() === methodName) {
            for (const param of def.findAllExpressions(MethodParamName)) {
              names.add(param.concatTokens().toUpperCase());
            }
            break;
          }
        }
      }
 
      for (const d of method.findAllExpressions(DefinitionName)) {
        names.add(d.concatTokens().toUpperCase());
      }
      for (const inline of method.findAllExpressions(InlineData)) {
        const field = inline.findFirstExpression(TargetField);
        if (field) {
          names.add(field.concatTokens().toUpperCase());
        }
      }
 
      if (names.size === 0) {
        continue;
      }
      for (const statement of method.findAllStatementNodes()) {
        map.set(statement, names);
      }
    }
    return map;
  }
}