All files / src/rules unused_methods.ts

89% Statements 267/300
82.65% Branches 81/98
94.44% Functions 17/18
89% Lines 267/300

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 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 3011x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 228x 228x 1x 1x 14x 14x 1x 1x 11x 11x 3x 2x 2x 2x 3x 9x 1x 1x 6x 6x 1x 1x 6x 5x 5x 1x 1x 229x 229x 1x 1x 228x 228x 1x 1x 1x 1x 11073x 11073x 11073x 11073x 11073x 11073x 32991x 32991x 32991x 32991x 32991x 32991x 32991x 32991x 32991x 32991x 32991x 32991x 32991x 32991x 32991x 32991x 32991x 32991x 32991x 32991x 32991x 32991x 11073x 11073x 10504x 10504x 11073x 11073x 261x 261x 11073x 11073x 279x 279x 279x 11073x 11073x 345x 63x 345x 20x 282x 1x 1x 261x 345x 267x 1611x 5x 5x 1611x 262x 256x 256x 256x 345x 28x 28x 228x 228x 228x 345x 234x 131x 61x 61x 61x 10x 61x 51x 1x 1x 51x 1x 51x 50x 3x 3x 47x 47x 61x 14x 14x 61x 131x 234x 228x 228x 228x 228x 228x 228x 345x 12x 12x 12x     12x 12x     12x 1x 1x 11x 1x 1x 10x 10x 10x 12x 12x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 228x 228x 228x 11073x 11073x                                   11073x 11073x 10x 10x 10x 10x 10x 10x     10x 10x         11073x 11073x 11x     11x 11x     11x 11x 11x 102x 1x 1x 102x 11x 11x 102x 10x 10x 10x 11073x 11073x 229x 229x 229x 228x 228x 1x 1x 229x     1x 229x 2x 2x 1x 1x 1x 1x 1x 2x 1x 1x 11073x 11073x 1144x 915x 915x 1144x 1144x 915x 915x 1144x 11073x 11073x 915x 370x 11x 11x 370x 915x 11073x 11073x  
import {Issue} from "../issue";
import {BasicRuleConfig} from "./_basic_rule_config";
import {IRegistry} from "../_iregistry";
import {IRule, IRuleMetadata, RuleTag} from "./_irule";
import {IObject} from "../objects/_iobject";
import {SyntaxLogic} from "../abap/5_syntax/syntax";
import {ABAPObject} from "../objects/_abap_object";
import {ScopeType} from "../abap/5_syntax/_scope_type";
import {Class, Interface, Program} from "../objects";
import {ISpaghettiScopeNode} from "../abap/5_syntax/_spaghetti_scope";
import {Identifier} from "../abap/4_file_information/_identifier";
import {ReferenceType} from "../abap/5_syntax/_reference";
import {Visibility} from "../abap/4_file_information/visibility";
import {InfoMethodDefinition} from "../abap/4_file_information/_abap_file_information";
import {EditHelper, IEdit} from "../edit_helper";
import {Comment, Unknown} from "../abap/2_statements/statements/_statement";
import {StatementNode} from "../abap/nodes/statement_node";
import {ABAPFile} from "../abap/abap_file";
import {StructureNode} from "../abap/nodes";
import * as Structures from "../abap/3_structures/structures";
import * as Expressions from "../abap/2_statements/expressions";
 
export class UnusedMethodsConf extends BasicRuleConfig {
}
 
class WorkArea {
  private readonly list: InfoMethodDefinition[] = [];
 
  public constructor() {
    this.list = [];
  }
 
  public push(id: InfoMethodDefinition) {
    this.list.push(id);
  }
 
  public removeIfExists(id: Identifier) {
    // todo: optimize
    for (let i = 0; i < this.list.length; i++) {
      if (id.equals(this.list[i].identifier)) {
        this.list.splice(i, 1);
        return;
      }
    }
  }
 
  public containsProteted(): boolean {
    for (const m of this.list) {
      if (m.visibility === Visibility.Protected) {
        return true;
      }
    }
    return false;
  }
 
  public getLength(): number {
    return this.list.length;
  }
 
  public get(): readonly InfoMethodDefinition[] {
    return this.list;
  }
}
 
// todo: add possibility to also search public methods
// todo: for protected methods, also search subclasses
export class UnusedMethods implements IRule {
  private conf = new UnusedMethodsConf();
  private reg: IRegistry;
  private wa: WorkArea;
 
  public getMetadata(): IRuleMetadata {
    return {
      key: "unused_methods",
      title: "Unused methods",
      shortDescription: `Checks for unused methods`,
      extendedInformation: `Checks private and protected methods.
 
Unused methods are not reported if the object contains parser or syntax errors.
Quick fixes only appears for private methods or projected methods where the class doesnt have any subclasses.
 
Skips:
* methods FOR TESTING
* methods SETUP + TEARDOWN + CLASS_SETUP + CLASS_TEARDOWN in testclasses
* class_constructor + constructor methods
* event handlers
* methods that are redefined
* INCLUDEs
`,
      tags: [RuleTag.Quickfix],
      pragma: "##CALLED",
      pseudoComment: "EC CALLED",
    };
  }
 
  public getConfig() {
    return this.conf;
  }
 
  public setConfig(conf: UnusedMethodsConf) {
    this.conf = conf;
  }
 
  public initialize(reg: IRegistry) {
    this.reg = reg;
    return this;
  }
 
  public run(obj: IObject): Issue[] {
    if (!(obj instanceof ABAPObject)) {
      return [];
    } else if (obj instanceof Interface) { // todo, how to handle interfaces?
      return [];
    } else if (obj instanceof Program && obj.isInclude() === true) {
      return [];
    }
 
    for (const file of obj.getABAPFiles()) {
      for (const statement of file.getStatements()) {
        if (statement.get() instanceof Unknown) {
          return []; // contains parser errors
        }
      }
    }
 
    // dont report anything when there are syntax errors
    const syntax = new SyntaxLogic(this.reg, obj).run();
    if (syntax.issues.length > 0) {
      return [];
    }
 
    this.wa = new WorkArea();
 
    for (const file of obj.getABAPFiles()) {
      for (const def of file.getInfo().listClassDefinitions()) {
        for (const method of def.methods) {
          if (method.isForTesting === true
              || method.isRedefinition === true
              || method.isEventHandler === true) {
            continue;
          } else if (def.isForTesting === true
              && (method.name.toUpperCase() === "SETUP"
              || method.name.toUpperCase() === "CLASS_SETUP"
              || method.name.toUpperCase() === "TEARDOWN"
              || method.name.toUpperCase() === "CLASS_TEARDOWN")) {
            continue;
          } else if (method.name.toUpperCase() === "CONSTRUCTOR"
              || method.name.toUpperCase() === "CLASS_CONSTRUCTOR") {
            continue;
          }
 
          if (method.visibility === Visibility.Private
              || method.visibility === Visibility.Protected) {
            this.wa.push(method);
          }
        }
      }
    }
 
    this.traverse(syntax.spaghetti.getTop());
 
    this.searchGlobalSubclasses(obj);
 
    const issues: Issue[] = [];
    for (const i of this.wa.get()) {
 
      const file = obj.getABAPFileByName(i.identifier.getFilename());
      if (file === undefined) {
        continue;
      }
      const statement = EditHelper.findStatement(i.identifier.getToken(), file);
      if (statement === undefined) {
        continue;
      }
      if (statement.getPragmas().some(t => t.getStr() === this.getMetadata().pragma)) {
        continue;
      }
      else if (this.suppressedbyPseudo(statement, file)) {
        continue;
      }
 
      let fix: IEdit | undefined = undefined;
      if (i.visibility === Visibility.Private
          || i.isFinal === true
          || (i.visibility === Visibility.Protected && this.hasSubClass(obj) === false)) {
        const implementation = this.findMethodImplementation(i, file);
        if (implementation !== undefined) {
          const fix1 = EditHelper.deleteStatement(file, statement);
          const fix2 = EditHelper.deleteRange(file, implementation.getFirstToken().getStart(), implementation.getLastToken().getEnd());
          fix = EditHelper.merge(fix1, fix2);
        }
      }
 
      const message = "Method \"" + i.identifier.getName() + "\" not used";
      issues.push(Issue.atIdentifier(i.identifier, message, this.getMetadata().key, this.conf.severity, fix));
    }
 
    return issues;
  }
 
  private hasSubClass(obj: ABAPObject): boolean {
    if (!(obj instanceof Class)) {
      return false;
    }

    if (obj.getDefinition()?.isFinal() === true) {
      return false;
    }

    for (const r of this.reg.getObjects()) {
      if (r instanceof Class
          && r.getDefinition()?.getSuperClass()?.toUpperCase() === obj.getName().toUpperCase()) {
        return true;
      }
    }

    return false;
  }
 
  private findMethodImplementation(method: InfoMethodDefinition, file: ABAPFile): StructureNode | undefined {
    for (const classImplementation of file.getStructure()?.findAllStructures(Structures.ClassImplementation) || []) {
      // todo, this will break if there are class implemtations with the same method names
      // const className = classImplementation.findFirstExpression(Expressions.ClassName)?.concatTokens().toUpperCase();
      for (const methodImplementation of classImplementation.findAllStructures(Structures.Method)) {
        const methodName = methodImplementation.findFirstExpression(Expressions.MethodName)?.concatTokens().toUpperCase() || "";
        if (methodName !== method.name.toUpperCase()) {
          continue;
        }
        return methodImplementation;
      }
    }

    return undefined;
  }
 
  private suppressedbyPseudo(statement: StatementNode | undefined, file: ABAPFile): boolean {
    if (statement === undefined) {
      return false;
    }
 
    if (file === undefined) {
      return false;
    }
 
    let next = false;
    for (const s of file.getStatements()) {
      if (next === true && s.get() instanceof Comment) {
        return s.concatTokens().includes(this.getMetadata().pseudoComment + "");
      }
      if (s === statement) {
        next = true;
      }
    }
 
    return false;
  }
 
  private searchGlobalSubclasses(obj: ABAPObject) {
    if (this.wa.getLength() === 0
        || !(obj instanceof Class)
        || this.wa.containsProteted() === false) {
      return;
    }
 
    const sup = obj.getDefinition();
    if (sup === undefined) {
      return;
    }
 
    for (const r of this.reg.getObjects()) {
      if (r instanceof Class
          && r.getDefinition()?.getSuperClass()?.toUpperCase() === sup.getName().toUpperCase()) {
        const syntax = new SyntaxLogic(this.reg, r).run();
        this.traverse(syntax.spaghetti.getTop());
        // recurse to sub-sub-* classes
        this.searchGlobalSubclasses(r);
      }
    }
 
  }
 
  private traverse(node: ISpaghettiScopeNode) {
    if (node.getIdentifier().stype !== ScopeType.BuiltIn) {
      this.checkNode(node);
    }
 
    for (const c of node.getChildren()) {
      this.traverse(c);
    }
  }
 
  private checkNode(node: ISpaghettiScopeNode) {
    for (const v of node.getData().references) {
      if (v.referenceType === ReferenceType.MethodReference && v.resolved) {
        this.wa.removeIfExists(v.resolved);
      }
    }
  }
 
}