All files / src/rules uncaught_exception.ts

94.84% Statements 276/291
80.3% Branches 106/132
100% Functions 16/16
94.84% Lines 276/291

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 23443x 23443x 23443x 23443x 1x 11732x 11732x 11732x 11732x 11732x 11732x 11732x 11732x 11732x 11732x 11732x 35006x 35006x 35006x 35006x 35006x 35006x 35006x 35006x 11732x 11732x 11187x 11187x 11732x 11732x 274x 274x 274x 274x 11732x 11732x 253x 253x 11732x 11732x 421x 20x 421x 11x 11x 390x 390x 421x 12x 12x 378x 378x 378x 378x 421x 7x 7x 371x 371x 371x 421x 794x 794x 371x 371x 371x 11732x 11732x 2044x 2044x 2044x 312x 312x 1732x 2044x 676x 5x 5x 5x 5x 4x 4x 5x 5x 5x 9x 9x 5x 5x     676x 671x 1237x 1237x 671x 2044x 1056x 69x 1056x 69x 987x 8x 8x 8x 1x 1x 918x 8x 910x 15x 15x 15x 15x 14x 15x 1x 1x 1x 1x 15x 15x 902x   887x 887x 887x 1056x 2044x 2044x 11732x 11732x 11732x 11732x 19x 10x 10x 10x 19x 11732x 11732x 887x 887x 887x 887x 887x 659x 659x 659x 659x 7x 7x 2x 2x 659x 652x 652x 652x 6x 6x 2x 2x 6x 659x 887x 11732x 11732x 6x 3x 2x 2x 3x 4x 4x 4x 4x 4x 6x 6x 6x 11732x 11732x 5x     5x 5x 5x     5x 5x 5x 5x 5x 11732x 11732x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x 69x     69x 69x 69x 11732x 11732x 41x 1x 1x 40x 40x 41x     41x     40x 40x 41x     41x 2x 2x 38x 38x 41x 41x 41x 11732x 11732x 274x 274x 274x 493x 315x 315x 493x 493x 51x 51x 127x 493x 493x 274x 11732x 11732x 378x 378x 378x 399x 296x 21x 21x 296x 399x 378x 11732x 11732x  
import {Issue} from "../issue";
import {ABAPRule} from "./_abap_rule";
import {BasicRuleConfig} from "./_basic_rule_config";
import * as Statements from "../abap/2_statements/statements";
import * as Expressions from "../abap/2_statements/expressions";
import * as Structures from "../abap/3_structures/structures";
import {IRuleMetadata, RuleTag} from "./_irule";
import {ABAPFile} from "../abap/abap_file";
import {StatementNode, StructureNode} from "../abap/nodes";
import {IRegistry} from "../_iregistry";
import {Class, Program} from "../objects";
import {DDIC} from "../ddic";
import {SyntaxLogic} from "../abap/5_syntax/syntax";
import {ABAPObject} from "../objects/_abap_object";
import {ISpaghettiScopeNode, ISyntaxResult} from "../abap/5_syntax/_spaghetti_scope";
import {ReferenceType} from "../abap/5_syntax/_reference";
import {ClassDefinition, MethodDefinition} from "../abap/types";
import {IClassDefinition} from "../abap/types/_class_definition";
 
export class UncaughtExceptionConf extends BasicRuleConfig {
  public reportDynamic = false;
  public reportNoCheck = false;
}
 
export class UncaughtException extends ABAPRule {
 
  private conf = new UncaughtExceptionConf();
 
  private globalExceptions: {[index: string]: string | undefined};
  private localExceptions: {[index: string]: string | undefined};
  private issues: Issue[] = [];
  private sinked: string[] | undefined;
  private syntax: ISyntaxResult;
 
  public getMetadata(): IRuleMetadata {
    return {
      key: "uncaught_exception",
      title: "Uncaught Exception",
      shortDescription: `Checks for uncaught static exception`,
      extendedInformation: `Does not report any issues if the code contains syntax errors`,
      tags: [RuleTag.Syntax],
    };
  }
 
  public getConfig() {
    return this.conf;
  }
 
  public initialize(reg: IRegistry) {
    super.initialize(reg);
    this.findGlobalExceptions();
    return this;
  }
 
  public setConfig(conf: UncaughtExceptionConf) {
    this.conf = conf;
  }
 
  public runParsed(file: ABAPFile, obj: ABAPObject) {
    if (obj.getType() === "INTF") { // nothing can be raised in interfaces
      return [];
    } if (obj instanceof Program && obj.isInclude() === true) {
      return [];
    }
 
    const stru = file.getStructure();
    if (stru === undefined) {
      return [];
    }
 
    this.findLocalExceptions(obj);
 
    this.syntax = new SyntaxLogic(this.reg, obj).run();
    if (this.syntax.issues.length > 0) {
      return [];
    }
 
    this.issues = [];
    this.sinked = undefined;
    for (const c of stru.getChildren()) {
      this.traverse(c, file);
    }
 
    return this.issues;
  }
 
  private traverse(n: StructureNode | StatementNode, file: ABAPFile) {
    const get = n.get();
    if (get instanceof Structures.ClassDefinition
        || get instanceof Structures.Interface) {
      return; // to optimize performance
    }
 
    if (n instanceof StructureNode) {
      if (get instanceof Structures.Try) {
        // note that TRY-CATCH might be arbitrarily nested
        const previous = this.sinked ? this.sinked.slice() : undefined;
        this.addFromTryStructure(n);
        for (const c of n.findDirectStructure(Structures.Body)?.getChildren() || []) {
          this.traverse(c, file);
        }
        this.sinked = previous;
        for (const catchStructure of n.findDirectStructures(Structures.Catch)) {
          for (const c of catchStructure.getChildren()) {
            this.traverse(c, file);
          }
        }
        for (const c of n.findDirectStructure(Structures.Cleanup)?.getChildren() || []) {
          this.traverse(c, file);
        }
      } else {
        for (const c of n.getChildren()) {
          this.traverse(c, file);
        }
      }
    } else if (n instanceof StatementNode) {
      if (get instanceof Statements.MethodImplementation) {
        this.setSinkedFromMethod(n, file);
      } else if (get instanceof Statements.EndMethod) {
        this.sinked = undefined; // back to top level
      } else if (get instanceof Statements.Form) {
        this.sinked = [];
        const raising = n.findDirectExpression(Expressions.FormRaising);
        for (const c of raising?.findAllExpressions(Expressions.ClassName) || []) {
          this.sinked.push(c.concatTokens().toUpperCase());
        }
      } else if (get instanceof Statements.EndForm) {
        this.sinked = undefined; // back to top level
      } else if (get instanceof Statements.Raise) {
        let name: string | undefined = undefined;
 
        const concat = n.concatTokens().toUpperCase();
        if (concat.startsWith("RAISE EXCEPTION TYPE ")) {
          name = n.findFirstExpression(Expressions.ClassName)?.getFirstToken().getStr().toUpperCase();
        } else if (concat.startsWith("RAISE EXCEPTION NEW ")) {
          name = n.findFirstExpression(Expressions.NewObject)?.findFirstExpression(
            Expressions.TypeNameOrInfer)?.getFirstToken().getStr().toUpperCase();
// todo: else its a normal Source, infer the type from it
        }
 
        this.check(name, n, file);
      } else if (get instanceof Statements.Perform) {
        // todo, PERFORM, or is this not statically checked?
      } else {
        this.checkForMethodCalls(n, file);
      }
    }
 
  }
 
////////////////////////////////
 
  private check(name: string | undefined, n: StatementNode, file: ABAPFile) {
    if (this.isSinked(name) === false) {
      const issue = Issue.atStatement(file, n, "Uncaught exception " + name, this.getMetadata().key, this.getConfig().severity);
      this.issues.push(issue);
    }
  }
 
  private checkForMethodCalls(n: StatementNode, file: ABAPFile) {
    const start = n.getFirstToken().getStart();
    const end = n.getLastToken().getEnd();
 
    const scope = this.syntax.spaghetti.lookupPosition(start, file.getFilename());
    for (const r of scope?.getData().references || []) {
      if (r.referenceType === ReferenceType.MethodReference
          && r.position.getStart().isAfter(start)
          && r.position.getEnd().isBefore(end)
          && r.resolved instanceof MethodDefinition) {
 
        for (const name of r.resolved.getRaising()) {
          this.check(name, n, file);
        }
      } else if (r.referenceType === ReferenceType.ConstructorReference
          && r.position.getStart().isAfter(start)
          && r.position.getEnd().isBefore(end)
          && r.resolved instanceof ClassDefinition) {
        const method = this.findConstructor(r.resolved, scope);
        for (const name of method?.getRaising() || []) {
          this.check(name, n, file);
        }
      }
    }
  }
 
  private findConstructor(def: IClassDefinition, scope: ISpaghettiScopeNode | undefined): MethodDefinition | undefined {
    for (const method of def.getMethodDefinitions().getAll()) {
      if (method instanceof MethodDefinition && method.getName().toUpperCase() === "CONSTRUCTOR") {
        return method;
      }
    }
 
    const sup = def.getSuperClass();
    if (sup === undefined) {
      return undefined;
    }
    const superDefinition = scope?.findClassDefinition(sup);
    return superDefinition ? this.findConstructor(superDefinition, scope) : undefined;
  }
 
  private addFromTryStructure(s: StructureNode) {
    if (this.sinked === undefined) {
      return;
    }
    for (const structure of s.findDirectStructures(Structures.Catch)) {
      const c = structure.findDirectStatement(Statements.Catch);
      if (c === undefined) {
        continue;
      }
      for (const cn of c.findDirectExpressions(Expressions.ClassName)) {
        this.sinked.push(cn.concatTokens());
      }
    }
  }
 
  private setSinkedFromMethod(s: StatementNode, file: ABAPFile) {
    this.sinked = [];
 
    const scope = this.syntax.spaghetti.lookupPosition(s.getLastToken().getEnd(), file.getFilename());
 
    let def: MethodDefinition | undefined = undefined;
    for (const r of scope?.getData().references || []) {
      // there should be only one, so the first is okay
      if (r.referenceType === ReferenceType.MethodImplementationReference
          && r.resolved instanceof MethodDefinition) {
        def = r.resolved;
        break;
      }
    }
    if (def === undefined) {
      return; // this should not occur, so just report everything as errors
    }
 
    def.getRaising().forEach(r => this.sinked?.push(r));
  }
 
  private isSinked(name: string | undefined): boolean {
    if (this.sinked === undefined || name === undefined) {
      return true;
    }
 
    const sup = this.globalExceptions[name.toUpperCase()];
    if (sup === "CX_DYNAMIC_CHECK" && this.getConfig().reportDynamic !== true) {
      return true;
    }
    if (sup === "CX_NO_CHECK" && this.getConfig().reportNoCheck !== true) {
      return true;
    }
 
    const lsup = this.localExceptions[name.toUpperCase()];
    if (lsup === "CX_DYNAMIC_CHECK" && this.getConfig().reportDynamic !== true) {
      return true;
    }
    if (lsup === "CX_NO_CHECK" && this.getConfig().reportNoCheck !== true) {
      return true;
    }
 
    return this.sinked.some(a => a.toUpperCase() === name.toUpperCase())
      || (sup !== undefined && this.isSinked(sup) === true)
      || (lsup !== undefined && this.isSinked(lsup) === true);
  }
 
  private findGlobalExceptions() {
    this.globalExceptions = {};
    const ddic = new DDIC(this.reg);
    for (const o of this.reg.getObjects()) {
      if (!(o instanceof Class)) {
        continue;
      }
      const def = o.getMainABAPFile()?.getInfo().getClassDefinitionByName(o.getName());
      if (def === undefined || ddic.isException(def, o) === false) {
        continue;
      }
 
      this.globalExceptions[o.getName().toUpperCase()] = def.superClassName?.toUpperCase();
    }
  }
 
  private findLocalExceptions(obj: ABAPObject) {
    this.localExceptions = {};
 
    for (const file of obj.getABAPFiles()) {
      for (const def of file.getInfo().listClassDefinitions()) {
        if (def.isLocal === true && def.superClassName !== undefined) {
          this.localExceptions[def.name.toUpperCase()] = def.superClassName?.toUpperCase();
        }
      }
    }
  }
 
}