All files / src/rules unused_variables.ts

94.86% Statements 277/292
89% Branches 89/100
100% Functions 18/18
94.86% Lines 277/292

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 2921x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 22765x 22765x 22765x 22765x 22765x 22765x 22765x 22765x 1x 362x 362x 362x 362x 505x 291x 70x 70x 291x 435x 435x 362x 362x 460x     460x 551x 323x 323x 270x 270x 323x 323x 551x 137x 362x 362x 362x 362x 362x 362x 397x 397x 362x 1x 11461x 11461x 11461x 11461x 11461x 11461x 34082x 34082x 34082x 34082x 34082x 34082x 34082x 34082x 34082x 34082x 34082x 34082x 34082x 34082x 34082x 34082x 34082x 34082x 34082x 34082x 34082x 34082x 34082x 34082x 11461x 11461x 10810x 10810x 11461x 11461x 234x 234x 2x 2x 234x 11461x 11461x 392x 392x 392x 11461x 11461x 465x 66x 465x 21x 21x 378x 465x 385x 1933x 8x 8x 1933x 377x 370x 370x 370x 465x 8x 8x 362x 362x 362x 362x 362x 465x 75x 75x 287x 287x 465x 344x 285x 344x 35x     35x 35x 35x 3x 3x 35x 344x 284x 284x 284x 11461x 11461x 1354x 1354x 766x 766x 766x 460x 460x 766x 1354x 1354x 1032x 1032x 1354x 11461x 11461x 1571x 1571x 1571x 2x 2x 1569x 1571x 1209x 1209x 1569x 1571x 1208x 1208x 788x 788x 788x 788x   788x 1x 788x 787x 787x 787x 282x 282x 282x 505x 788x 788x 1208x 1571x 11461x 11461x 362x 362x 362x 165x 165x   165x 5x 5x 160x 160x 165x 7x 165x 1x 1x 152x 152x 152x 152x 152x 152x 152x 362x 362x 362x 11461x 11461x 153x     153x 153x 153x 2x 2x 151x 151x 153x 902x 12x 12x 902x 151x 151x 902x 139x 139x 139x 11461x 11461x 160x 160x     160x 160x     160x 160x     160x 160x 160x 160x 11461x 11461x 152x 152x 2x 2x 150x 150x 152x   152x 95x 95x 55x 55x 11461x
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, IdentifierMeta} from "../abap/types/_typed_identifier";
import {Interface, Program} from "../objects";
import {ISpaghettiScopeNode} from "../abap/5_syntax/_spaghetti_scope";
import {Identifier} from "../abap/4_file_information/_identifier";
import {EditHelper, IEdit} from "../edit_helper";
import {StatementNode} from "../abap/nodes/statement_node";
import * as Statements from "../abap/2_statements/statements";
import {Comment, Unknown} from "../abap/2_statements/statements/_statement";
import {ReferenceType} from "../abap/5_syntax/_reference";
 
 
export class UnusedVariablesConf extends BasicRuleConfig {
  /** skip specific names, case insensitive
   * @uniqueItems true
  */
  public skipNames?: string[] = [];
  /** skip parameters from abstract methods */
  public skipAbstract: boolean = false;
}
 
class WorkArea {
  private readonly workarea: {id: TypedIdentifier, count: number}[] = [];
 
  public push(id: TypedIdentifier, count = 1) {
    for (const w of this.workarea) {
      if (id.equals(w.id)) {
        return;
      }
    }
    this.workarea.push({id, count});
  }
 
  public removeIfExists(id: Identifier | undefined): void {
    if (id === undefined) {
      return;
    }
    for (let i = 0; i < this.workarea.length; i++) {
      if (id.equals(this.workarea[i].id)) {
        this.workarea[i].count--;
        if (this.workarea[i].count === 0) {
          this.workarea.splice(i, 1);
        }
        return;
      }
    }
  }
 
  public get() {
    return this.workarea;
  }
 
  public count(): number {
    return this.workarea.length;
  }
}
 
export class UnusedVariables implements IRule {
  private conf = new UnusedVariablesConf();
  private reg: IRegistry;
  private workarea: WorkArea;
 
  public getMetadata(): IRuleMetadata {
    return {
      key: "unused_variables",
      title: "Unused variables",
      shortDescription: `Checks for unused variables and constants`,
      extendedInformation: `Skips event parameters.
 
Note that this currently does not work if the source code uses macros.
 
Unused variables are not reported if the object contains parser or syntax errors.
 
Errors found in INCLUDES are reported for the main program.`,
      tags: [RuleTag.Quickfix],
      pragma: "##NEEDED",
      pseudoComment: "EC NEEDED",
      badExample: `DATA: BEGIN OF blah1,
      test  TYPE string,
      test2 TYPE string,
    END OF blah1.`,
      goodExample: `DATA: BEGIN OF blah2 ##NEEDED,
      test  TYPE string,
      test2 TYPE string,
    END OF blah2.`,
    };
  }
 
  public getConfig() {
    return this.conf;
  }
 
  public setConfig(conf: UnusedVariablesConf) {
    this.conf = conf;
    if (this.conf.skipNames === undefined) {
      this.conf.skipNames = [];
    }
  }
 
  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 [];
    }
 
    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 []; // contains syntax errors
    }
 
    this.workarea = new WorkArea();
    const top = syntax.spaghetti.getTop();
    this.buildWorkarea(top, obj);
 
    if (this.workarea.count() === 0) {
      return this.buildIssues(obj); // exit early if all variables are used
    }
    this.findUses(top, obj);
 
    for (const o of this.reg.getObjects()) {
      if (o === obj) {
        continue;
      } else if (o instanceof ABAPObject) {
        if (this.reg.isDependency(o)) {
          continue; // do not search in dependencies
        }
        const syntax = new SyntaxLogic(this.reg, o).run();
        this.findUses(syntax.spaghetti.getTop(), o);
        if (this.workarea.count() === 0) {
          return this.buildIssues(obj); // exit early if all variables are used
        }
      }
    }
 
    return this.buildIssues(obj);
  }
 
  private findUses(node: ISpaghettiScopeNode, obj: ABAPObject): void {
 
    for (const r of node.getData().references) {
      if (r.referenceType === ReferenceType.DataReadReference
          || r.referenceType === ReferenceType.DataWriteReference
          || r.referenceType === ReferenceType.TypeReference) {
        this.workarea.removeIfExists(r.resolved);
      }
    }
 
    for (const c of node.getChildren()) {
      this.findUses(c, obj);
    }
  }
 
  private buildWorkarea(node: ISpaghettiScopeNode, obj: ABAPObject): void {
    const stype = node.getIdentifier().stype;
 
    if (stype === ScopeType.OpenSQL) {
      return;
    }
 
    for (const c of node.getChildren()) {
      this.buildWorkarea(c, obj);
    }
 
    if (stype !== ScopeType.BuiltIn) {
      const vars = node.getData().vars;
      for (const name in vars) {
        const meta = vars[name].getMeta();
        if (this.conf.skipNames
            && this.conf.skipNames.length > 0
            && this.conf.skipNames.some((a) => a.toUpperCase() === name)) {
          continue;
        } else if (this.conf.skipAbstract === true && meta.includes(IdentifierMeta.Abstract)) {
          continue;
        } else if (name === "ME"
            || name === "SUPER"
            || meta.includes(IdentifierMeta.SelectionScreenTab)
            || meta.includes(IdentifierMeta.EventParameter)) {
          // todo, workaround for "me" and "super", these should somehow be typed to built-in
          continue;
        }
        const isInline = meta.includes(IdentifierMeta.InlineDefinition);
        this.workarea.push(vars[name], isInline ? 2 : 1);
      }
    }
  }
 
  private buildIssues(obj: ABAPObject): Issue[] {
    const ret: Issue[] = [];
 
    for (const w of this.workarea.get()) {
      const filename = w.id.getFilename();
      if (this.reg.isFileDependency(filename) === true) {
        continue;
      } else if (obj instanceof Program === false && obj.containsFile(filename) === false) {
        continue;
      }
 
      const statement = this.findStatement(w.id);
      if (statement?.getPragmas().map(t => t.getStr()).includes(this.getMetadata().pragma + "")) {
        continue;
      } else if (this.suppressedbyPseudo(statement, w.id, obj)) {
        continue;
      }
 
      const name = w.id.getName();
      const message = "Variable \"" + name.toLowerCase() + "\" not used";
 
      const fix = this.buildFix(w.id, obj);
      ret.push(Issue.atIdentifier(w.id, message, this.getMetadata().key, this.conf.severity, fix));
    }
 
    return ret;
  }
 
  private suppressedbyPseudo(statement: StatementNode | undefined, v: TypedIdentifier, obj: ABAPObject): boolean {
    if (statement === undefined) {
      return false;
    }
 
    const file = obj.getABAPFileByName(v.getFilename());
    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 findStatement(v: TypedIdentifier): StatementNode | undefined {
    const file = this.reg.getFileByName(v.getFilename());
    if (file === undefined) {
      return undefined;
    }
    const object = this.reg.findObjectForFile(file);
    if (!(object instanceof ABAPObject)) {
      return undefined;
    }
    const abapfile = object.getABAPFileByName(v.getFilename());
    if (abapfile === undefined) {
      return undefined;
    }
 
    const statement = EditHelper.findStatement(v.getToken(), abapfile);
    return statement;
  }
 
  private buildFix(v: TypedIdentifier, obj: ABAPObject): IEdit | undefined {
    const file = obj.getABAPFileByName(v.getFilename());
    if (file === undefined) {
      return undefined;
    }
 
    const statement = EditHelper.findStatement(v.getToken(), file);
    if (statement === undefined) {
      return undefined;
    } else if (statement.get() instanceof Statements.Data) {
      return EditHelper.deleteStatement(file, statement);
    }
    return undefined;
  }
}