All files / src/rules unused_types.ts

95.38% Statements 248/260
88.6% Branches 70/79
100% Functions 20/20
95.38% Lines 248/260

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 2601x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 378x 378x 378x 378x 378x 182x 182x 135x 135x 182x 378x 378x 238x 238x 378x 378x 378x 41x 45x 13x 13x 45x 41x 378x 378x 31x 31x 378x 378x 419x 419x 378x 378x 378x 453x 453x 453x 453x 378x 1x 42220x 42220x 42220x 42220x 42220x 42220x 1x 21122x 21122x 21122x 21122x 21122x 21122x 21122x 21122x 63082x 63082x 63082x 63082x 63082x 63082x 63082x 63082x 63082x 63082x 21122x 21122x 20205x 20205x 21122x 21122x 374x 374x     374x 21122x 21122x 398x 398x 398x 398x 21122x 21122x 608x 208x 208x 400x 608x 409x 2574x 13x 13x 2574x 396x 387x 387x 387x 608x 9x 9x 378x 378x 378x 378x 608x 337x 337x 41x 41x 41x 608x 10x 10x 31x 31x 31x 608x 32x 32x 32x 32x     32x 32x     32x 1x 32x 1x 1x 30x 30x 30x 30x 31x 31x 21122x 21122x 31x     31x 31x     31x 31x 31x 216x 1x 1x 216x 31x 31x 216x 30x 30x 30x 21122x 21122x 21122x 21122x 41x 38x 38x 56x 1x 1x 55x 55x 55x 38x 38x 41x 41x 21122x 21122x 21122x 239x 184x 86x 33x 33x 86x 184x 239x 239x 184x 184x 239x 21122x 21122x 3212x 3212x 2492x 2492x 3212x 3212x 2456x 2456x 3212x 3212x 21122x 21122x 2492x 2492x 2492x 1246x 1246x 205x 205x   205x 205x 205x   205x 23x 23x 182x 182x 1246x 2492x 2492x 1192x 238x 238x 1192x 2492x 2492x 2492x 21122x 21122x 30x 6x 6x 24x 24x 21122x
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 {TypedIdentifier} from "../abap/types/_typed_identifier";
import {ISpaghettiScopeNode} from "../abap/5_syntax/_spaghetti_scope";
import {EditHelper, IEdit} from "../edit_helper";
import {ReferenceType} from "../abap/5_syntax/_reference";
import {Identifier} from "../abap/4_file_information/_identifier";
import {ABAPFile} from "../abap/abap_file";
import {StatementNode} from "../abap/nodes";
import {Comment, Unknown} from "../abap/2_statements/statements/_statement";
import {VirtualPosition} from "../virtual_position";
 
class WorkArea {
  // keyed by identifier position, insertion order is kept
  private readonly workarea = new Map<string, TypedIdentifier>();
 
  public push(id: TypedIdentifier) {
    const key = WorkArea.buildKey(id);
    if (this.workarea.has(key) === false) {
      this.workarea.set(key, id);
    }
  }
 
  public removeIfExists(id: Identifier) {
    this.workarea.delete(WorkArea.buildKey(id));
  }
 
  /** removes the identifiers referenced somewhere */
  public removeReferenced(referenced: ReadonlySet<string>) {
    for (const key of [...this.workarea.keys()]) {
      if (referenced.has(key)) {
        this.workarea.delete(key);
      }
    }
  }
 
  public get(): readonly TypedIdentifier[] {
    return [...this.workarea.values()];
  }
 
  public count(): number {
    return this.workarea.size;
  }
 
  /** identifiers from one macro call share the row and column, the virtual position tells them apart */
  public static buildKey(id: Identifier): string {
    const start = id.getStart();
    const key = id.getFilename() + "," + start.getRow() + "," + start.getCol();
    return start instanceof VirtualPosition ? key + "," + start.vrow + "," + start.vcol : key;
  }
}
 
export class UnusedTypesConf extends BasicRuleConfig {
  /** skip specific names, case insensitive
   * @uniqueItems true
   */
  public skipNames?: string[] = [];
}
 
export class UnusedTypes implements IRule {
  private conf = new UnusedTypesConf();
  private reg: IRegistry;
  private workarea: WorkArea;
  /** keys of the identifiers with a type reference in any object, built once per run when needed */
  private referenced: Set<string> | undefined = undefined;
 
  public getMetadata(): IRuleMetadata {
    return {
      key: "unused_types",
      title: "Unused types",
      shortDescription: `Checks for unused TYPE definitions`,
      extendedInformation: `Unused types are not reported if the object contains parser or syntax errors.`,
      tags: [RuleTag.Quickfix],
      pragma: "##NEEDED",
      pseudoComment: "EC NEEDED",
    };
  }
 
  public getConfig() {
    return this.conf;
  }
 
  public setConfig(conf: UnusedTypesConf) {
    this.conf = conf;
    if (this.conf.skipNames === undefined) {
      this.conf.skipNames = [];
    }
  }
 
  public initialize(reg: IRegistry) {
    this.reg = reg;
    this.referenced = undefined;
    return this;
  }
 
  public run(obj: IObject): Issue[] {
    if (!(obj instanceof ABAPObject)) {
      return [];
    }
 
    for (const file of obj.getABAPFiles()) {
      for (const statement of file.getStatements()) {
        if (statement.get() instanceof Unknown) {
          return []; // contains parser errors
        }
      }
    }
 
    // dont report unused variables when there are syntax errors
    const syntax = new SyntaxLogic(this.reg, obj).run();
    if (syntax.issues.length > 0) {
      return [];
    }
 
    this.workarea = new WorkArea();
    this.traverse(syntax.spaghetti.getTop(), obj, true);
    this.traverse(syntax.spaghetti.getTop(), obj, false);
    if (this.workarea.count() === 0) {
      return []; // exit early if all types are used in the current object
    }
 
    // uses in other objects, collected once instead of searching all objects for each object
    this.workarea.removeReferenced(this.getReferenced());
    if (this.workarea.count() === 0) {
      return []; // exit early if all types are used
    }
 
    // what is left is unused
    const ret: Issue[] = [];
    for (const t of this.workarea.get()) {
      const message = "Type \"" + t.getName() + "\" not used";
 
      const file = obj.getABAPFileByName(t.getFilename());
      if (file === undefined) {
        continue;
      }
      const statement = EditHelper.findStatement(t.getToken(), file);
      if (statement === undefined) {
        continue;
      }
      if (statement.getPragmas().some(t => t.getStr() === this.getMetadata().pragma)) {
        continue;
      } else if (this.suppressedbyPseudo(statement, file)) {
        continue;
      }
 
      const fix = this.buildFix(file, statement);
      ret.push(Issue.atIdentifier(t, message, this.getMetadata().key, this.conf.severity, fix));
    }
    return ret;
  }
 
  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 getReferenced(): ReadonlySet<string> {
    if (this.referenced === undefined) {
      const referenced = new Set<string>();
      for (const o of this.reg.getObjects()) {
        if (!(o instanceof ABAPObject) || this.reg.isDependency(o)) {
          continue; // do not search in dependencies
        }
        const syntax = new SyntaxLogic(this.reg, o).run();
        this.collectReferenced(syntax.spaghetti.getTop(), referenced);
      }
      this.referenced = referenced;
    }
    return this.referenced;
  }
 
  /** same nodes and references as checkNode() with add = false */
  private collectReferenced(node: ISpaghettiScopeNode, referenced: Set<string>) {
    if (node.getIdentifier().stype !== ScopeType.BuiltIn) {
      for (const r of node.getData().references) {
        if (r.referenceType === ReferenceType.TypeReference && r.resolved) {
          referenced.add(WorkArea.buildKey(r.resolved));
        }
      }
    }
 
    for (const c of node.getChildren()) {
      this.collectReferenced(c, referenced);
    }
  }
 
  private traverse(node: ISpaghettiScopeNode, obj: ABAPObject, add: boolean) {
 
    if (node.getIdentifier().stype !== ScopeType.BuiltIn) {
      this.checkNode(node, obj, add);
    }
 
    for (const c of node.getChildren()) {
      this.traverse(c, obj, add);
    }
 
  }
 
  private checkNode(node: ISpaghettiScopeNode, obj: ABAPObject, add: boolean) {
    const ret: Issue[] = [];
 
    if (add === true) {
      const types = node.getData().types;
      for (const name in types) {
        const identifier = types[name];
        if (obj.containsFile(identifier.getFilename()) === false) {
          continue;
        } else if (this.conf.skipNames
            && this.conf.skipNames.length > 0
            && this.conf.skipNames.some((a) => a.toUpperCase() === name)) {
          continue;
        } else if (name !== identifier.getName().toUpperCase()) {
          continue; // may have aliases via interfaces
        }
        this.workarea.push(identifier);
      }
    }
 
    for (const r of node.getData().references) {
      if (r.referenceType === ReferenceType.TypeReference && r.resolved) {
        this.workarea.removeIfExists(r.resolved);
      }
    }
 
    return ret;
  }
 
  private buildFix(file: ABAPFile, statement: StatementNode): IEdit | undefined {
    if (statement.concatTokens().toUpperCase().includes("BEGIN OF")) {
      return undefined;
    }
    return EditHelper.deleteStatement(file, statement);
  }
}