All files / src/rules clear_exporting_parameters.ts

96.36% Statements 212/220
86.56% Branches 58/67
100% Functions 13/13
96.36% Lines 212/220

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 2211x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 22194x 22194x 22194x 22194x 22194x 22194x 1x 11107x 11107x 11107x 11107x 11107x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 96534x 11107x 11107x 10568x 10568x 11107x 11107x 245x 245x     245x 11107x 11107x 265x 265x 265x 11107x 11107x 348x 91x 91x 257x 348x 268x 1580x 7x 7x 1580x 261x 250x 250x 348x 7x 7x 243x 243x 243x 243x 243x 11107x 11107x 1152x 1152x 70x 70x 1152x 909x 909x 1152x 11107x 11107x 70x 70x 70x 54x 54x 16x 16x 16x 16x 6x 6x 16x 16x 11107x 11107x 70x 70x 70x 162x 71x 71x 162x 70x 70x 82x 82x 82x 82x 82x 65x 82x 1x 1x 16x 82x     16x 16x 70x 70x 11107x 11107x 70x 70x 70x     70x 70x 11107x 11107x 16x 16x 16x 16x 47x 47x 47x 18x 18x 29x 47x 11x 11x 11x 47x 18x 14x 14x 18x 47x 16x 16x 5x 5x 11x 11x 11x 16x 16x 5x 5x 6x 6x 6x 6x 11107x 11107x 22x 22x 137x 137x 137x 137x 22x 22x 137x     11107x  
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 {IdentifierMeta, TypedIdentifier} from "../abap/types/_typed_identifier";
import {Interface} from "../objects";
import {ISpaghettiScopeNode} from "../abap/5_syntax/_spaghetti_scope";
import {ReferenceType, IReference} from "../abap/5_syntax/_reference";
import {VoidType, UnknownType} from "../abap/types/basic";
import {Position} from "../position";
import {Unknown} from "../abap/2_statements/statements/_statement";
 
export class ClearExportingParametersConf extends BasicRuleConfig {
  /** Skip specific parameter names, case insensitive
   * @uniqueItems true
   */
  public skipNames?: string[] = [];
}
 
export class ClearExportingParameters implements IRule {
  private conf = new ClearExportingParametersConf();
  private reg: IRegistry;
 
  public getMetadata(): IRuleMetadata {
    return {
      key: "clear_exporting_parameters",
      title: "Clear EXPORTING parameters",
      shortDescription: `Checks that EXPORTING parameters passed by reference are cleared or assigned before they are read`,
      extendedInformation: `An EXPORTING parameter passed by reference behaves like a CHANGING parameter: it is not
initialized when the method is called, so it can still contain a value supplied by the caller. Clear or overwrite it
before reading it, so a leftover value is not accidentally used.
 
https://github.com/SAP/styleguides/blob/main/clean-abap/CleanABAP.md#clear-or-overwrite-exporting-reference-parameters
 
https://help.sap.com/doc/abapdocu_latest_index_htm/latest/en-US/abenref_transf_output_param_guidl.htm
 
Note: EXPORTING parameters passed by VALUE are always initialized and are therefore not reported.
Reading and writing the parameter in the same statement (e.g. "ev_result = ev_result + 1") is reported,
as the source is evaluated before the parameter is assigned.
Objects containing parser or syntax errors are not reported.
 
Class and interface method implementations and function modules are checked.`,
      tags: [RuleTag.Styleguide],
      badExample: `CLASS lcl DEFINITION.
  PUBLIC SECTION.
    METHODS foo EXPORTING ev_result TYPE i.
ENDCLASS.
CLASS lcl IMPLEMENTATION.
  METHOD foo.
    ev_result = ev_result + 1.
  ENDMETHOD.
ENDCLASS.`,
      goodExample: `CLASS lcl DEFINITION.
  PUBLIC SECTION.
    METHODS foo EXPORTING ev_result TYPE i.
ENDCLASS.
CLASS lcl IMPLEMENTATION.
  METHOD foo.
    CLEAR ev_result.
    ev_result = ev_result + 1.
  ENDMETHOD.
ENDCLASS.`,
    };
  }
 
  public getConfig() {
    return this.conf;
  }
 
  public setConfig(conf: ClearExportingParametersConf) {
    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) || obj instanceof Interface) {
      return [];
    }
 
    for (const file of obj.getABAPFiles()) {
      for (const statement of file.getStatements()) {
        if (statement.get() instanceof Unknown) {
          return []; // contains parser errors
        }
      }
    }
 
    const syntax = new SyntaxLogic(this.reg, obj).run();
    if (syntax.issues.length > 0) {
      return []; // contains syntax errors
    }
 
    const issues: Issue[] = [];
    this.traverse(syntax.spaghetti.getTop(), obj, issues);
    return issues;
  }
 
  private traverse(node: ISpaghettiScopeNode, obj: ABAPObject, issues: Issue[]): void {
    if (node.getIdentifier().stype === ScopeType.Method
        || node.getIdentifier().stype === ScopeType.FunctionModule) {
      this.checkProcedure(node, obj, issues);
    }
    for (const child of node.getChildren()) {
      this.traverse(child, obj, issues);
    }
  }
 
  private checkProcedure(node: ISpaghettiScopeNode, obj: ABAPObject, issues: Issue[]): void {
    const references = this.collectReferences(node);
    const parameters = this.findExportingByReference(node, references);
    if (parameters.length === 0) {
      return;
    }
 
    for (const parameter of parameters) {
      const issue = this.checkParameter(parameter, references, obj);
      if (issue !== undefined) {
        issues.push(issue);
      }
    }
  }
 
  private findExportingByReference(node: ISpaghettiScopeNode, references: IReference[]): TypedIdentifier[] {
    const ret: TypedIdentifier[] = [];
    const candidates = new Set<TypedIdentifier>(Object.values(node.getData().vars));
    for (const reference of references) {
      if (reference.resolved instanceof TypedIdentifier) {
        candidates.add(reference.resolved);
      }
    }
 
    for (const parameter of candidates) {
      const meta = parameter.getMeta();
      const exporting = meta.includes(IdentifierMeta.MethodExporting)
        || meta.includes(IdentifierMeta.FunctionModuleExporting);
      if (exporting === false
          || meta.includes(IdentifierMeta.PassByValue) === true) {
        continue;
      } else if (this.conf.skipNames?.some(s => s.toUpperCase() === parameter.getName().toUpperCase())) {
        continue;
      }
      const type = parameter.getType();
      if (type instanceof VoidType || type instanceof UnknownType) {
        continue; // e.g. RAP magic parameters, or unresolved types
      }
      ret.push(parameter);
    }
    return ret;
  }
 
  private collectReferences(node: ISpaghettiScopeNode): IReference[] {
    // procedures do not nest, so all descendant scopes (FOR, LET, ...) belong to this procedure
    const ret: IReference[] = [...node.getData().references];
    for (const child of node.getChildren()) {
      ret.push(...this.collectReferences(child));
    }
    return ret;
  }
 
  private checkParameter(parameter: TypedIdentifier, references: IReference[], obj: ABAPObject): Issue | undefined {
    let firstRead: IReference | undefined = undefined;
    let earliestWrite: IReference | undefined = undefined;
 
    for (const reference of references) {
      if (reference.resolved === undefined
          || parameter.equals(reference.resolved) === false
          || parameter.getName().toUpperCase() !== reference.resolved.getName().toUpperCase()) {
        continue;
      }
      const pos = reference.position.getStart();
      if (reference.referenceType === ReferenceType.DataReadReference) {
        if (firstRead === undefined || pos.isBefore(firstRead.position.getStart())) {
          firstRead = reference;
        }
      } else if (reference.referenceType === ReferenceType.DataWriteReference) {
        if (earliestWrite === undefined || pos.isBefore(earliestWrite.position.getStart())) {
          earliestWrite = reference;
        }
      }
    }
 
    if (firstRead === undefined) {
      return undefined; // never read, no hazard
    }
 
    // the parameter is safe only if it is written in a statement strictly before the first read
    const readStatement = this.statementStart(firstRead, obj);
    const writeStatement = earliestWrite === undefined ? undefined : this.statementStart(earliestWrite, obj);
    if (writeStatement !== undefined && readStatement !== undefined && writeStatement.isBefore(readStatement)) {
      return undefined;
    }
 
    const message = `EXPORTING parameter "${parameter.getName().toLowerCase()}" read before it is cleared or assigned`;
    return Issue.atIdentifier(firstRead.position, message, this.getMetadata().key, this.conf.severity);
  }
 
  private statementStart(reference: IReference, obj: ABAPObject): Position | undefined {
    const file = obj.getABAPFileByName(reference.position.getFilename());
    for (const statement of file?.getStatements() || []) {
      const pos = reference.position.getStart();
      const start = statement.getStart();
      const end = statement.getEnd();
      if (pos.equals(start) || (pos.isAfter(start) && pos.isBefore(end))) {
        return start;
      }
    }
    return undefined;
  }
}