All files / src/rules check_subrc.ts

96.28% Statements 259/269
91.73% Branches 111/121
100% Functions 15/15
96.28% Lines 259/269

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 2691x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 42200x 42200x 42200x 42200x 42200x 42200x 42200x 42200x 42200x 42200x 42200x 42200x 42200x 42200x 42200x 42200x 42200x 1x 21101x 21101x 21101x 21101x 103490x 103490x 103490x 103490x 103490x 103490x 103490x 103490x 103490x 103490x 103490x 103490x 103490x 103490x 103490x 103490x 103490x 103490x 103490x 103490x 103490x 103490x 103490x 103490x 103490x 103490x 103490x 103490x 21101x 21101x 22818x 22818x 21101x 21101x 375x 375x 21101x 21101x 21101x 21101x 2613x 2613x 2613x 2613x 2613x 2613x 2613x 2613x 2x 2x 2613x     2611x 7x 7x 2611x 3x 3x 3x 3x 2604x 1x 1x 2601x 1x 1x 2600x     2599x     2599x 12x 2599x 9x 2587x 4x 2578x 18x 18x 18x 18x 2574x 26x 2556x 2530x 2530x 83x 83x 2613x 2613x 62x 62x 2613x 2613x 21101x 21101x 20x 20x 20x 20x 20x 21101x 21101x 452x 452x 452x 452x 452x 2616x 2616x 2616x 3x 3x 2613x 2613x 2616x 2592x 2592x 2616x 2616x 2616x 2616x 2616x 2616x 21101x 21101x 21101x 21101x 9x 8x 8x 8x 5x 5x 8x 4x 4x 21101x 21101x 21101x 39x 20x 21x 21x 17x 17x 21x 3x 22x 22x 21101x 21101x 16x 16x 21101x 21101x 4x 4x 4x 21101x 21101x 5x 1x 1x 1x   1x 1x   1x 1x 1x 1x 4x 4x 21101x 21101x 21101x 8x 8x 8x 21101x 21101x 46x 46x 46x 46x 46x 16x 16x 16x 16x 16x 46x 46x 41x 41x 41x 3x 2x 2x 41x 38x 38x 38x 5x 38x 33x 3x 3x 33x 30x 30x 1x 30x 29x 2x 29x 27x 1x 1x 27x     26x 27x 27x 27x 41x 17x 17x 21101x
import * as Statements from "../abap/2_statements/statements";
import * as Expressions from "../abap/2_statements/expressions";
import {Issue} from "../issue";
import {BasicRuleConfig} from "./_basic_rule_config";
import {ABAPRule} from "./_abap_rule";
import {IRuleMetadata, RuleTag} from "./_irule";
import {StatementNode} from "../abap/nodes/statement_node";
import {Comment} from "../abap/2_statements/statements/_statement";
import {ABAPFile} from "../abap/abap_file";
import {EditHelper} from "../edit_helper";
import {findClosing} from "./_statement_blocks";
 
export class CheckSubrcConf extends BasicRuleConfig {
  public openDataset: boolean = true;
  public authorityCheck: boolean = true;
  public selectSingle: boolean = true;
  public selectTable: boolean = true;
  public updateDatabase: boolean = true;
  public insertDatabase: boolean = true;
  public modifyDatabase: boolean = true;
  public deleteDatabase: boolean = true;
  public readTable: boolean = true;
  public assign: boolean = true;
  public find: boolean = true;
  /** CALL FUNCTION with EXCEPTIONS, unless every exception is mapped to 0 */
  public callFunction: boolean = true;
  /** Method call with EXCEPTIONS, unless every exception is mapped to 0 */
  public callMethod: boolean = true;
}
 
export class CheckSubrc extends ABAPRule {
  private conf = new CheckSubrcConf();
 
  public getMetadata(): IRuleMetadata {
    return {
      key: "check_subrc",
      title: "Check sy-subrc",
      shortDescription: `Check sy-subrc`,
      extendedInformation: `Pseudo comment "#EC CI_SUBRC can be added to suppress findings
 
If sy-dbcnt is checked after database statements, it is considered okay.
 
"SELECT SINGLE @abap_true FROM " is considered as an existence check, also "SELECT COUNT( * )" is considered okay
 
If IS ASSIGNED is checked after assigning, it is considered okay.
 
FIND statement with MATCH COUNT is considered okay if subrc is not checked
 
CALL FUNCTION and method calls are checked if they have an EXCEPTIONS addition that maps an exception to a value other than 0,
including CALL FUNCTION DESTINATION and STARTING NEW TASK. Not checked: calls without EXCEPTIONS, calls where every exception
is mapped to 0, EXCEPTION-TABLE, CALL FUNCTION IN UPDATE TASK and IN BACKGROUND.
For CALL FUNCTION the pragma ##FM_SUBRC_OK is also accepted.
 
A call of a method with SUBRC in its name, like check_subrc( ), is considered a check.
 
After ELSE, ELSEIF, WHEN, CATCH and CLEANUP the check continues after the end of the block, as these branches are not run
after the statement`,
      tags: [RuleTag.SingleFile, RuleTag.Quickfix],
      pseudoComment: "EC CI_SUBRC",
      pragma: "##SUBRC_OK",
    };
  }
 
  public getConfig() {
    return this.conf;
  }
 
  public setConfig(conf: CheckSubrcConf) {
    this.conf = conf;
  }
 
  /** "fix" if the statement sets sy-subrc which is not checked afterwards, "noFix" if it is also not to be
   * ignored with a pragma, which does not make sense for OPEN DATASET and AUTHORITY-CHECK */
  private uncheckedKind(statement: StatementNode, index: number, statements: readonly StatementNode[]): "fix" | "noFix" | undefined {
    const config = this.getConfig();
    const get = statement.get();
    const concat = get instanceof Statements.Select ? statement.concatTokens().toUpperCase() : "";
    let relevant: boolean;
    let fix = true;
    // sy-dbcnt can be checked instead
    let dbcnt = false;
    if (get instanceof Statements.OpenDataset) {
      relevant = config.openDataset === true;
      fix = false;
    } else if (get instanceof Statements.AuthorityCheck) {
      relevant = config.authorityCheck === true;
      fix = false;
    } else if (get instanceof Statements.Select && concat.startsWith("SELECT SINGLE ")) {
      relevant = config.selectSingle === true && concat.startsWith("SELECT SINGLE @ABAP_TRUE FROM ") === false;
      dbcnt = true;
    } else if (get instanceof Statements.Select) {
      relevant = config.selectTable === true
        && concat.startsWith("SELECT COUNT( * ) ") === false
        && concat.startsWith("SELECT COUNT(*) ") === false;
      dbcnt = true;
    } else if (get instanceof Statements.UpdateDatabase) {
      relevant = config.updateDatabase === true;
      dbcnt = true;
    } else if (get instanceof Statements.DeleteDatabase) {
      relevant = config.deleteDatabase === true;
      dbcnt = true;
    } else if (get instanceof Statements.InsertDatabase) {
      relevant = config.insertDatabase === true;
      dbcnt = true;
    } else if (get instanceof Statements.ModifyDatabase) {
      relevant = config.modifyDatabase === true;
      dbcnt = true;
    } else if (get instanceof Statements.ReadTable) {
      relevant = config.readTable === true;
    } else if (get instanceof Statements.Assign) {
      relevant = config.assign === true && this.isSimpleAssign(statement) === false;
    } else if (get instanceof Statements.Find) {
      relevant = config.find === true && this.isExemptedFind(statement) === false;
    } else if (get instanceof Statements.CallFunction) {
      relevant = config.callFunction === true
        && statement.getPragmas().some(t => t.getStr().toUpperCase() === "##FM_SUBRC_OK") === false
        && this.isUpdateOrBackgroundTask(statement) === false
        && this.mapsExceptionToNonZero(statement) === true;
    } else if (get instanceof Statements.Call) {
      relevant = config.callMethod === true && this.mapsExceptionToNonZero(statement) === true;
    } else {
      return undefined;
    }
 
    if (relevant === false
        || this.isChecked(index, statements) === true
        || (dbcnt === true && this.checksDbcnt(index, statements) === true)) {
      return undefined;
    }
    return fix ? "fix" : "noFix";
  }
 
  private buildFix(file: ABAPFile, statement: StatementNode) {
    return {
      description: "Add ##SUBRC_OK",
      edit: EditHelper.insertAt(file, statement.getLastToken().getStart(), " ##SUBRC_OK"),
    };
  }
 
  public runParsed(file: ABAPFile): Issue[] {
    const issues: Issue[] = [];
    const statements = file.getStatements();
    const message = "Check sy-subrc";
 
    for (let i = 0; i < statements.length; i++) {
      const statement = statements[i];
 
      if (statement.getPragmas().some(t => t.getStr() === this.getMetadata().pragma)) {
        continue;
      }
 
      const unchecked = this.uncheckedKind(statement, i, statements);
      if (unchecked === undefined) {
        continue;
      }
      const fix = unchecked === "fix" ? [this.buildFix(file, statement)] : undefined;
      issues.push(Issue.atStatement(file, statement, message, this.getMetadata().key, this.conf.severity, undefined, fix));
    }
 
    return issues;
  }
 
////////////////
 
  private isSimpleAssign(statement: StatementNode): boolean {
    if (statement.getChildren().length === 5) {
      const source = statement.findDirectExpression(Expressions.AssignSource);
      if (source?.getChildren().length === 1
          && source.findDirectExpression(Expressions.Source) !== undefined) {
        return true;
      }
    }
    return false;
  }
 
  /** true if the EXCEPTIONS addition maps an exception to a value other than 0, then the call sets sy-subrc */
  private mapsExceptionToNonZero(statement: StatementNode): boolean {
    for (const list of statement.findAllExpressions(Expressions.ParameterListExceptions)) {
      for (const exception of list.findDirectExpressions(Expressions.ParameterException)) {
        const value = exception.findDirectExpression(Expressions.Integer);
        if (value === undefined || parseInt(value.concatTokens().replace(/\s/g, ""), 10) !== 0) {
          return true;
        }
      }
    }
    return false;
  }
 
  private isUpdateOrBackgroundTask(statement: StatementNode): boolean {
    return statement.findDirectTokenByText("UPDATE") !== undefined || statement.findDirectTokenByText("BACKGROUND") !== undefined;
  }
 
  private isExemptedFind(s: StatementNode): boolean {
// see https://github.com/abaplint/abaplint/issues/2130
    return s.concatTokens().toUpperCase().includes(" MATCH COUNT ") === true;
  }
 
  private checksDbcnt(index: number, statements: readonly StatementNode[]): boolean {
    for (let i = index + 1; i < statements.length; i++) {
      const statement = statements[i];
      const concat = statement.concatTokens().toUpperCase();
      if (statement.get() instanceof Comment) {
        continue;
      } else if (statement.get() instanceof Statements.EndIf
          || statement.get() instanceof Statements.EndTestSeam) {
        continue;
      } else {
        return concat.includes("SY-DBCNT");
      }
    }
    return false;
  }
 
  /** a method call like check_subrc( ), the method reads sy-subrc */
  private callsSubrcMethod(statement: StatementNode): boolean {
    return statement.get() instanceof Statements.Call
      && statement.findAllExpressions(Expressions.MethodName).some(m => m.concatTokens().toUpperCase().includes("SUBRC"));
  }
 
  private isChecked(index: number, statements: readonly StatementNode[]): boolean {
    let assigned: string | undefined = undefined;
    let assignedn: string | undefined = undefined;
 
    if (statements[index].get() instanceof Statements.Assign
        || statements[index].get() instanceof Statements.ReadTable) {
      const fs = statements[index].findFirstExpression(Expressions.FSTarget
      )?.findFirstExpression(Expressions.FieldSymbol)?.getFirstToken().getStr();
      assigned = fs?.toUpperCase() + " IS ASSIGNED";
      assignedn = fs?.toUpperCase() + " IS NOT ASSIGNED";
    }
 
    for (let i = index + 1; i < statements.length; i++) {
      const statement = statements[i];
      const concat = statement.concatTokens().toUpperCase();
      if (statement.get() instanceof Comment) {
        if (concat.includes("" + this.getMetadata().pseudoComment)) {
          return true;
        }
      } else if (statement.get() instanceof Statements.EndIf
          || statement.get() instanceof Statements.EndCase
          || statement.get() instanceof Statements.EndTry
          || statement.get() instanceof Statements.EndTestSeam) {
        continue;
      } else if (statement.get() instanceof Statements.Else
          || statement.get() instanceof Statements.ElseIf) {
// the other branches are not run after this one, continue after ENDIF
        i = findClosing(i, statements, [Statements.If], Statements.EndIf, false) ?? statements.length;
      } else if (statement.get() instanceof Statements.When
          || statement.get() instanceof Statements.WhenOthers
          || statement.get() instanceof Statements.WhenType) {
        i = findClosing(i, statements, [Statements.Case, Statements.CaseType], Statements.EndCase, false) ?? statements.length;
      } else if (statement.get() instanceof Statements.Catch
          || statement.get() instanceof Statements.Cleanup) {
        i = findClosing(i, statements, [Statements.Try], Statements.EndTry, false) ?? statements.length;
      } else {
        if (assigned && concat.includes(assigned)) {
          return true;
        }
        if (assignedn && concat.includes(assignedn)) {
          return true;
        }
        return concat.includes(" SY-SUBRC")
          || concat.includes("CL_ABAP_UNIT_ASSERT=>ASSERT_SUBRC")
          || this.callsSubrcMethod(statement);
      }
    }
    return false;
  }
}