All files / src/rules sort_empty_key.ts

98.84% Statements 171/173
94.91% Branches 56/59
100% Functions 9/9
98.84% Lines 171/173

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 1741x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 42200x 42200x 42200x 42200x 1x 21102x 21102x 21102x 21102x 21102x 63083x 63083x 63083x 63083x 63083x 63083x 63083x 63083x 63083x 63083x 63083x 63083x 63083x 63083x 63083x 63083x 63083x 63083x 63083x 63083x 63083x 63083x 63083x 63083x 63083x 63083x 63083x 63083x 63083x 21102x 21102x 20206x 20206x 21102x 21102x 415x 415x 415x 21102x 21102x 375x 375x 21102x 21102x 625x 229x 229x 396x 396x 396x 396x 625x 406x 2565x 2565x 2565x 2565x 26x 3x 3x 23x 23x 2565x 34x 2539x 20x 20x 20x 13x 13x 7x 7x 2505x 2485x 2485x 64x 64x 64x 2565x 13x 13x 13x 13x 13x 13x 2565x     64x 2565x 31x 31x 64x 64x 2565x 2565x 2565x 34x 34x 30x 30x 2565x 12x 12x 2565x 2565x 2565x 406x 396x 396x 396x 21102x 21102x 21102x 21102x 21102x 2533x 2533x 2533x 2533x 2470x 2470x 63x 63x 2533x 2533x 2533x 2533x 21102x 21102x 18x 18x 18x 18x 18x 1x 1x 17x 17x 17x 17x 17x 17x 17x 21102x  
import * as Expressions from "../abap/2_statements/expressions";
import * as Statements from "../abap/2_statements/statements";
import {BasicRuleConfig} from "./_basic_rule_config";
import {Issue} from "../issue";
import {IRule, IRuleMetadata, RuleTag} from "./_irule";
import {SyntaxLogic} from "../abap/5_syntax/syntax";
import {IObject} from "../objects/_iobject";
import {ABAPObject} from "../objects/_abap_object";
import {IRegistry} from "../_iregistry";
import {StructureType, TableAccessType, TableKeyType, TableType, UnknownType, VoidType} from "../abap/types/basic";
import {AbstractType} from "../abap/types/basic/_abstract_type";
import {ExpressionNode, StatementNode} from "../abap/nodes";
import {ABAPFile} from "../abap/abap_file";
import {ISpaghettiScope} from "../abap/5_syntax/_spaghetti_scope";
import {Punctuation} from "../abap/1_lexer/tokens";
import {EditHelper, IEdit} from "../edit_helper";
import {nodeChainType} from "./_type_lookup";
 
export class SortEmptyKeyConf extends BasicRuleConfig {
  /** Also report READ TABLE, DELETE TABLE and MODIFY TABLE ... FROM wa, which address a row through the empty primary key */
  public tableKeyAccess: boolean = true;
}
 
export class SortEmptyKey implements IRule {
  private reg: IRegistry;
  private conf = new SortEmptyKeyConf();
 
  public getMetadata(): IRuleMetadata {
    return {
      key: "sort_empty_key",
      title: "Statement uses the empty primary key of a table",
      shortDescription: `SORT without BY, DELETE ADJACENT DUPLICATES without COMPARING and
READ TABLE, DELETE TABLE and MODIFY TABLE ... FROM wa on a table with an empty primary key`,
      extendedInformation: `Without BY or COMPARING, SORT and DELETE ADJACENT DUPLICATES use the primary key of the table. For a table
declared WITH EMPTY KEY there is nothing to sort or compare by, SORT does nothing.
 
READ TABLE itab FROM wa, DELETE TABLE itab FROM wa and MODIFY TABLE itab FROM wa search the row by the primary key.
With an empty key there is nothing to compare, the first row of the table is read, deleted or modified, whatever wa contains.
This part can be switched off with tableKeyAccess, there is no quick fix for it.
 
The syntax check warns: "ITAB is a table with an empty primary key. Check the semantics of the statement."
https://help.sap.com/doc/abapdocu_latest_index_htm/latest/en-US/abenitab_empty_key.htm
 
Sorted and hashed tables, tables with a default or explicit key, and tables of unknown or generic type are not reported.
 
The quick fix adds BY table_line or COMPARING table_line, for tables with an elementary row type.`,
      tags: [RuleTag.SingleFile, RuleTag.Quickfix],
      badExample: `DATA result TYPE STANDARD TABLE OF string WITH EMPTY KEY.
SORT result.
DELETE ADJACENT DUPLICATES FROM result.
DELETE TABLE result FROM \`foo\`.`,
      goodExample: `DATA result TYPE STANDARD TABLE OF string WITH EMPTY KEY.
SORT result BY table_line.
DELETE ADJACENT DUPLICATES FROM result COMPARING table_line.
DELETE result WHERE table_line = \`foo\`.`,
    };
  }
 
  public getConfig() {
    return this.conf;
  }
 
  public initialize(reg: IRegistry) {
    this.reg = reg;
    return this;
  }
 
  public setConfig(conf: SortEmptyKeyConf): void {
    this.conf = conf;
  }
 
  public run(obj: IObject): Issue[] {
    if (!(obj instanceof ABAPObject) || obj.getType() === "INTF") {
      return [];
    }
 
    const issues: Issue[] = [];
    let spaghetti: ISpaghettiScope | undefined = undefined;
 
    for (const file of obj.getABAPFiles()) {
      for (const statement of file.getStatements()) {
        // the addition the quick fix adds, undefined for the access through the table key
        let addition: string | undefined = undefined;
        let verb: string;
        if (statement.get() instanceof Statements.Sort) {
          if (statement.findDirectTokenByText("BY") !== undefined) {
            continue;
          }
          addition = "BY";
          verb = "SORT without BY";
        } else if (this.conf.tableKeyAccess === true && this.isTableKeyAccess(statement)) {
          verb = statement.getFirstToken().getStr().toUpperCase() + " TABLE ... FROM";
        } else if (statement.get() instanceof Statements.DeleteInternal) {
          if (statement.findDirectTokenByText("ADJACENT") === undefined
              || statement.findDirectTokenByText("COMPARING") !== undefined
              || statement.findDirectTokenByText("USING") !== undefined) {
            continue;
          }
          addition = "COMPARING";
          verb = "DELETE ADJACENT DUPLICATES without COMPARING";
        } else {
          continue;
        }
 
        // the table is a Target, only in READ TABLE it is a source, the third child after READ and TABLE
        let target = statement.findDirectExpression(Expressions.Target);
        if (statement.get() instanceof Statements.ReadTable) {
          const source = statement.getChildren()[2];
          const chain = source instanceof ExpressionNode ? source.getFirstChild() : undefined;
          target = chain instanceof ExpressionNode
            && chain.get() instanceof Expressions.FieldChain
            && source.getChildren().length === 1 ? chain : undefined;
        }
        if (target === undefined) {
          continue;
        }
 
        if (spaghetti === undefined) {
          spaghetti = new SyntaxLogic(this.reg, obj).run().spaghetti;
        }
        const type = nodeChainType(target, spaghetti, file);
        if (!(type instanceof TableType)
            || type.getOptions().keyType !== TableKeyType.empty
            || type.isGeneric()
            || (type.getAccessType() !== undefined && type.getAccessType() !== TableAccessType.standard)) {
          continue;
        }
 
        let message = `${verb} on "${target.concatTokens()}", a table with an empty primary key`;
        if (addition === undefined) {
          message += ", always finds the first row";
        }
        const fix = addition ? this.buildFix(file, statement, type.getRowType(), addition) : undefined;
        issues.push(Issue.atStatement(file, statement, message, this.getMetadata().key, this.conf.severity, fix));
      }
    }
 
    return issues;
  }
 
////////////////
 
  /** READ TABLE itab FROM wa, DELETE TABLE itab FROM wa and MODIFY TABLE itab FROM wa, all three use the primary key */
  private isTableKeyAccess(statement: StatementNode): boolean {
    const get = statement.get();
    if (!(get instanceof Statements.ReadTable)
        && !(get instanceof Statements.DeleteInternal)
        && !(get instanceof Statements.ModifyInternal)) {
      return false;
    }
    // without TABLE, FROM is an index (DELETE itab FROM idx) or the row is found by index (MODIFY itab FROM wa)
    return statement.findDirectTokenByText("TABLE") !== undefined
      && statement.findDirectTokenByText("FROM") !== undefined
      && statement.findDirectTokenByText("INDEX") === undefined
      && statement.findDirectTokenByText("USING") === undefined;
  }
 
  private buildFix(file: ABAPFile, statement: StatementNode, rowType: AbstractType, addition: string): IEdit | undefined {
    if (rowType instanceof StructureType
        || rowType instanceof TableType
        || rowType instanceof VoidType
        || rowType instanceof UnknownType
        || rowType.isGeneric()) {
      return undefined;
    }
    const tokens = statement.getTokens();
    let last = tokens[tokens.length - 1];
    if (last instanceof Punctuation) {
      last = tokens[tokens.length - 2];
    }
    return EditHelper.insertAt(file, last.getEnd(), ` ${addition} table_line`);
  }
}