All files / src/abap/5_syntax _sorted_key_write.ts

94.71% Statements 233/246
76.56% Branches 98/128
100% Functions 10/10
94.71% Lines 233/246

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 2471x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7885x 7885x 7885x 7885x 7885x 81293x 34045x 34045x 34045x 81293x 7885x 7885x 81293x 34045x 34045x 81293x 320x 320x 27x 27x 27x 27x 320x 81293x 7885x 7885x 7885x 98084x 98001x 98001x 83x 98084x 54x 54x 29x 29x 29x 29x 19x 19x 19x 29x 10x 7885x 7885x 7885x 53895x 11536x 11536x 42359x 42359x 42359x 53895x 48x 6x 6x 48x 1x 1x 48x 38x 12x 12x 38x 48x 42359x 42359x 42359x 42359x 53895x 126x 126x 126x 53895x 95x 95x 95x 53895x 53895x 53895x 42140x 42140x 219x 219x 219x 53895x 67x 53895x 9x 9x 9x 9x 9x 9x 9x 53895x 53895x 53895x 53895x 144x 144x 75x 75x 53895x 43x 43x 53895x 7885x 7885x 7885x 7885x 19x 19x 10x 10x 19x 7885x 7885x 29x 29x 29x     29x 29x 29x     29x 29x 29x 29x 5x 3x 3x 5x 1x 1x 1x 1x 1x 5x 29x 24x 24x 24x 24x 24x     24x 28x 29x 3x 3x 25x 29x 16x 16x 9x 9x 7885x 7885x 7885x 75x 75x 30x 30x 45x 75x 1x 1x 44x 75x 75x 3x 3x 75x   41x 1x 1x 40x 40x 7885x 7885x 7885x 75x 75x 75x 75x     75x 75x 75x 1x 1x 1x     1x 1x 1x 1x 1x     1x 75x 75x 7885x 7885x 162586x 162586x 162586x 7885x  
import * as Expressions from "../2_statements/expressions";
import * as Statements from "../2_statements/statements";
import * as Structures from "../3_structures/structures";
import {ExpressionNode, StatementNode, StructureNode} from "../nodes";
import {Dash, InstanceArrow} from "../1_lexer/tokens";
import {TypedIdentifier} from "../types/_typed_identifier";
import {ObjectReferenceType, StructureType, TableAccessType, TableKeyType, TableType, UnknownType, VoidType} from "../types/basic";
import {AbstractType} from "../types/basic/_abstract_type";
import {Position} from "../../position";
import {ObjectOriented} from "./_object_oriented";
import {CurrentScope} from "./_current_scope";
import {SyntaxInput, syntaxIssue} from "./_syntax_input";
 
type Binding = {
  /** the primary key components, or "line" when the key is the whole line */
  key: string[] | "line",
  reference: boolean,
  /** the LOOP statement that assigned it, the binding ends with the LOOP */
  loop: StatementNode | undefined,
};
 
/** The key components of the primary key of a sorted or hashed table line are write-protected,
 *  "write accesses to key fields using a field symbol or a data reference produce a syntax error if
 *  this is known statically, otherwise a runtime error", see the ABAP keyword documentation for LOOP AT itab
 *  and READ TABLE, result.
 *  Only conservative cases are handled: a field symbol or data reference local to the method, form or function
 *  module, bound by LOOP AT or READ TABLE ... ASSIGNING / REFERENCE INTO a table named by a plain chain of
 *  names, components and attributes, and written by an assignment or CLEAR. The binding of a LOOP ends with the LOOP,
 *  any other assignment of the field symbol or reference ends it as well. */
export class SortedKeyWrite {
  private readonly bindings = new Map<TypedIdentifier, Binding>();
  private procedure: {filename: string, start: Position} | undefined = undefined;
 
  public enter(node: StructureNode, filename: string): void {
    if (SortedKeyWrite.isProcedure(node)) {
      this.bindings.clear();
      this.procedure = {filename, start: node.getFirstToken().getStart()};
    }
  }
 
  public leave(node: StructureNode): void {
    if (SortedKeyWrite.isProcedure(node)) {
      this.bindings.clear();
      this.procedure = undefined;
    } else if (node.get() instanceof Structures.Loop) {
      const loop = node.findDirectStatement(Statements.Loop);
      for (const [identifier, binding] of this.bindings) {
        if (binding.loop === loop) {
          this.bindings.delete(identifier);
        }
      }
    }
  }
 
  /** call before the statement is checked */
  public check(node: StatementNode, input: SyntaxInput): void {
    if (this.bindings.size === 0) {
      return;
    }
    const s = node.get();
    if (!(s instanceof Statements.Move) && !(s instanceof Statements.Clear)) {
      return;
    }
 
    for (const target of node.findDirectExpressions(Expressions.Target)) {
      const message = this.checkTarget(target, input.scope);
      if (message !== undefined) {
        input.issues.push(syntaxIssue(input, target.getFirstToken(), message));
        return;
      }
    }
  }
 
  /** call after the statement is checked, the inline declarations are then known */
  public update(node: StatementNode, input: SyntaxInput): void {
    if (this.procedure === undefined) {
      return;
    }
 
    // any assignment of a field symbol or reference ends its binding,
    // skipped when nothing is bound, this runs for every statement
    if (this.bindings.size > 0) {
      for (const fs of node.findAllExpressions(Expressions.FSTarget)) {
        this.unbind(fs.findFirstExpression(Expressions.TargetFieldSymbol), input.scope);
      }
      if (node.get() instanceof Statements.Unassign) {
        this.unbind(node.findDirectExpression(Expressions.TargetFieldSymbol), input.scope);
      }
      for (const target of node.findAllExpressions(Expressions.Target)) {
        if (target.getChildren().length === 1) {
          this.unbind(target.findDirectExpression(Expressions.TargetField), input.scope);
        }
      }
    }
 
    const s = node.get();
    let table: ExpressionNode | undefined = undefined;
    let result: ExpressionNode | undefined = undefined;
    if (s instanceof Statements.Loop && node.findDirectExpression(Expressions.LoopGroupBy) === undefined) {
      table = node.findDirectExpression(Expressions.LoopSource)?.findDirectExpression(Expressions.SimpleSource2)
        ?? node.findDirectExpression(Expressions.LoopSource)?.findDirectExpression(Expressions.Source);
      result = node.findDirectExpression(Expressions.LoopTarget);
    } else if (s instanceof Statements.ReadTable) {
      table = node.findDirectExpression(Expressions.SimpleSource2) ?? node.findDirectExpression(Expressions.Source);
      result = node.findDirectExpression(Expressions.ReadTableTarget);
    }
    if (table === undefined || result === undefined
        || result.findDirectTokenByText("CASTING") !== undefined
        || node.findDirectTokenByText("CASTING") !== undefined) {
      return;
    }
 
    let name: ExpressionNode | undefined = undefined;
    let reference = false;
    if (result.findDirectTokenByText("ASSIGNING") !== undefined) {
      name = result.findDirectExpression(Expressions.FSTarget)?.findFirstExpression(Expressions.TargetFieldSymbol);
    } else if (result.findDirectTokenByText("REFERENCE") !== undefined) {
      const target = result.findDirectExpression(Expressions.Target);
      if (target?.getChildren().length === 1) {
        name = target.findDirectExpression(Expressions.TargetField)
          ?? target.findDirectExpression(Expressions.InlineData)?.findDirectExpression(Expressions.TargetField);
      }
      reference = true;
    }
    const identifier = input.scope.findVariable(name?.concatTokens());
    if (identifier === undefined
        || identifier.getFilename() !== this.procedure.filename
        || identifier.getStart().isBefore(this.procedure.start)) {
      return;
    }
 
    const key = SortedKeyWrite.findKey(SortedKeyWrite.findType(table, input.scope));
    if (key !== undefined) {
      this.bindings.set(identifier, {key, reference, loop: s instanceof Statements.Loop ? node : undefined});
    }
  }
 
////////////////
 
  private unbind(node: ExpressionNode | undefined, scope: CurrentScope): void {
    const found = node ? scope.findVariable(node.concatTokens()) : undefined;
    if (found !== undefined) {
      this.bindings.delete(found);
    }
  }
 
  private checkTarget(target: ExpressionNode, scope: CurrentScope): string | undefined {
    const children = target.getChildren();
    const first = children[0];
    if (!(first?.get() instanceof Expressions.TargetFieldSymbol) && !(first?.get() instanceof Expressions.TargetField)) {
      return undefined;
    }
    const found = scope.findVariable(first.concatTokens());
    const binding = found ? this.bindings.get(found) : undefined;
    if (binding === undefined) {
      return undefined;
    }
 
    let i = 1;
    const path: string[] = [];
    if (binding.reference === true) {
      if (children[i]?.get() instanceof InstanceArrow && children[i + 1]?.get() instanceof Expressions.AttributeName) {
        path.push(children[i + 1].concatTokens().toUpperCase());
        i = i + 2;
      } else if (children[i]?.get() instanceof Expressions.Dereference) {
        i = i + 1;
      } else {
        // the reference itself
        return undefined;
      }
    }
    for (; i < children.length; i++) {
      const get = children[i].get();
      if (get instanceof Dash && children[i + 1]?.get() instanceof Expressions.ComponentName) {
        path.push(children[i + 1].concatTokens().toUpperCase());
        i++;
      } else if (!(get instanceof Expressions.FieldOffset) && !(get instanceof Expressions.FieldLength)) {
        return undefined;
      }
    }
 
    if (binding.key === "line") {
      return "The line of a sorted or hashed table cannot be changed, it is the table key";
    }
    const name = path.join("-");
    if (name !== "" && binding.key.some(k => k === name || k.startsWith(name + "-") || name.startsWith(k + "-"))) {
      return `Key component "${name}" of a sorted or hashed table line cannot be changed`;
    }
    return undefined;
  }
 
  /** the primary key components of a sorted or hashed table, "line" when it is the whole line, else undefined */
  private static findKey(type: AbstractType | undefined): string[] | "line" | undefined {
    if (!(type instanceof TableType)
        || (type.getAccessType() !== TableAccessType.sorted && type.getAccessType() !== TableAccessType.hashed)) {
      return undefined;
    }
    const row = type.getRowType();
    if (row instanceof VoidType || row instanceof UnknownType || row.isGeneric()) {
      return undefined;
    }
    const keyType = type.getOptions().keyType;
    const fields = type.getOptions().primaryKey?.keyFields || [];
    if (keyType === TableKeyType.default) {
      // the default key of a structured line is not resolved
      return row instanceof StructureType ? undefined : "line";
    } else if (keyType !== TableKeyType.user || fields.length === 0) {
      return undefined;
    } else if (fields.includes("TABLE_LINE")) {
      return "line";
    }
    return fields;
  }
 
  /** the type of a table given by a plain chain of names, components and attributes, else undefined */
  private static findType(node: ExpressionNode, scope: CurrentScope): AbstractType | undefined {
    const chain = node.getChildren().length === 1 ? node.findDirectExpression(Expressions.FieldChain) : undefined;
    const children = chain?.getChildren() || [];
    const first = children[0];
    if (!(first?.get() instanceof Expressions.SourceField) && !(first?.get() instanceof Expressions.SourceFieldSymbol)) {
      return undefined;
    }
 
    let type = scope.findVariable(first.concatTokens())?.getType();
    for (let i = 1; i < children.length && type !== undefined; i++) {
      const get = children[i].get();
      const next = children[i + 1];
      if (get instanceof Dash && next?.get() instanceof Expressions.ComponentName) {
        type = type instanceof StructureType ? type.getComponentByName(next.concatTokens()) : undefined;
        i++;
      } else if (get instanceof InstanceArrow && next?.get() instanceof Expressions.AttributeName) {
        const def = type instanceof ObjectReferenceType ? scope.findObjectDefinition(type.getIdentifierName()) : undefined;
        type = new ObjectOriented(scope).searchAttributeName(def, next.concatTokens())?.getType();
        i++;
      } else if (!(get instanceof Expressions.TableBody) || i !== children.length - 1) {
        return undefined;
      }
    }
    return type;
  }
 
  private static isProcedure(node: StructureNode): boolean {
    const get = node.get();
    return get instanceof Structures.Method || get instanceof Structures.Form || get instanceof Structures.FunctionModule;
  }
}