All files / src/rules prefix_is_current_class.ts

98.23% Statements 223/227
88.88% Branches 56/63
100% Functions 11/11
98.23% Lines 223/227

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 2281x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 42219x 42219x 42219x 42219x 42219x 42219x 1x 21120x 21120x 21120x 21120x 184297x 184297x 184297x 184297x 184297x 184297x 184297x 184297x 184297x 184297x 184297x 184297x 184297x 184297x 184297x 184297x 184297x 21120x 21120x 20205x 20205x 21120x 21120x 376x 376x 21120x 21120x 408x 408x 21120x 21120x 408x 408x 13x 13x 395x 395x 395x 408x 63x 63x     63x 63x 63x 69x 69x 3x 3x     3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 69x 63x 63x 395x 395x 395x 21120x 21120x 408x 408x 13x 13x 395x 395x 395x 395x 395x 395x 408x 354x 354x 354x 354x 354x 1392x 1392x 15x 15x 15x 15x 15x 15x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 1392x 1377x 1377x 4x 4x 3x 3x 3x 3x 3x 3x 3x 3x 4x 1392x 354x 395x 395x 21120x 21120x 21120x 4x 4x 5x 5x 5x 5x 5x 3x 3x 5x 1x 1x 21120x 21120x 21120x 15x 15x 15x 92x 92x 16x 16x 16x 16x 16x 92x 15x 15x 21120x 21120x 21120x 21120x 354x 354x 179x 179x 175x 175x 175x 175x 354x 92x 92x 92x 92x 92x 92x 97x 87x 52x 52x 87x 87x 97x 92x 92x 92x 21x 21x 92x 4x 4x 4x 4x 4x 92x 92x 27x 27x 92x 197x 197x 65x 175x 175x 21120x  
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],
      badExample: `METHOD run.
  zcl_current=>helper( ).
  me->do_work( ).
ENDMETHOD.`,
      goodExample: `METHOD run.
  helper( ).
  do_work( ).
ENDMETHOD.`,
    };
  }
 
  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 = this.findMeMethodCall(s);
          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 "me->method( )", position is the start of "me", "me->attribute" is not a method call */
  private findMeMethodCall(s: StatementNode): Position | undefined {
    const tokens = s.getTokens();
    for (const call of s.findAllExpressionsRecursive(MethodCall)) {
      const start = call.getFirstToken().getStart();
      const index = tokens.findIndex(t => t.getStart().equals(start));
      if (index >= 2
          && tokens[index - 1].getStr() === "->"
          && tokens[index - 2].getStr().toUpperCase() === "ME") {
        return tokens[index - 2].getStart();
      }
    }
    return undefined;
  }
 
  /** 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;
  }
}