All files / src/abap/2_statements statement_parser.ts

98.57% Statements 415/421
96.96% Branches 128/132
100% Functions 19/19
98.57% Lines 415/421

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 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 4221x 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 37x 37x 37x 43084x 43084x 6844x 43084x     36240x 11796x 11796x 43084x 37x 37x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 317x 317x     317x 325x 148x 325x 177x 177x 325x 317x 1x 1x 1x 277758x 277758x 9367x 9367x 277758x 175x 321x 321x 175x 268391x 268391x 1x 1x 1x 1x 1x 1x 1x 1x 20500x 20500x 20500x 20500x 1x 1x 264165x 264165x 264165x 264165x 1x 1x 20500x 20500x 1x 1x 264165x 264165x 264165x 16506x 16506x 264165x 1515220x 1515220x 264165x 264165x 264165x 1x 1x 1x 1x 1x 1x 1x 1x 1x 20400x 20400x 1x 1x 20400x 20400x 20400x 20400x 1x 1x 1x 20400x 20400x 20400x 20400x 20400x 20500x 20500x 20500x 20500x 20400x 20400x 20500x 20500x 20500x 1609x 1609x 20500x 20500x 20400x 20400x 20400x 1x 1x 1x 1099x 1099x 1099x 6443x 6443x 1099x 1099x 1099x 1x 1x 1x 1x 1x 1609x 1609x 1609x 6036x 6036x 1682x 1682x 1682x 1682x 1682x 1682x 1682x 1550x 414x 4x 4x 410x 414x 53x 53x 53x 53x 414x 1550x 1682x 6036x 6036x 1609x 1609x 1609x 1x 1x 1550x 1550x 1550x 1550x 1550x 28627x 417x 417x 28627x 28627x 28627x 1550x 1550x 1550x 1x 1x 20500x 20500x 20500x 264896x 264896x 264896x 264896x 32x 264896x 57x 57x 17x 57x 40x 40x 40x 3x 3x 3x 3x 3x 3x 3x 3x 40x 57x 264896x 20500x 1x 1x 1x 20500x 20500x 20500x 264732x 264732x 20500x 20500x 1x 1x 265142x 265142x 265142x 265142x 265142x 265142x 265142x 17x 17x 265142x 264558x 4x 4x 264558x 264393x 264554x     161x 3x 3x 3x 3x 264558x 265142x 265142x 265142x 1x 1x 264393x 264393x 264393x 1261468x 87x 87x 87x 1261468x 264393x 264306x 264306x 87x 87x 87x 264393x 756x 756x 88x 756x 668x 668x 756x 87x 87x 87x 1x 1x 264393x 264393x 264393x 3x 3x 264390x 264393x 500107x 500107x 251022x 251022x 251022x 251022x 251022x 500107x 13368x 264393x 25031x 25031x 11319x 11319x 11319x 11319x 11319x 25031x 2049x 2049x 2049x 1x 1x 1x 1x 1x 20500x 20500x 20500x 20500x 20500x 20500x 20500x 20500x 20500x 1525165x 567x 567x 567x 1524598x 1524598x 1524598x 1524598x 1525165x 533993x 252325x 252325x 252325x 252325x 252325x 533993x 11679x 11679x 281668x 4639x 4639x 4639x 4639x 269989x 1x 1x 533993x 1525165x 20500x 20500x 161x 161x 20500x 1x 1x 1x 1x 252325x 252325x 252325x 252325x 252325x 252325x 31999x 31999x 252325x 4638x 4638x 4638x 4638x 4638x 252325x 11x 11x 215677x 215677x 215677x 252325x 252325x 252325x 23x 23x 215654x 215654x 1x  
import * as Statements from "./statements";
import * as Expressions from "./expressions";
import * as Tokens from "../1_lexer/tokens";
import {ABAPRelease, LanguageVersion} from "../../version";
import {IFile} from "../../files/_ifile";
import {TokenNode, StatementNode} from "../nodes";
import {ArtifactsABAP} from "../artifacts";
import {Combi} from "./combi";
import {Unknown, Empty, Comment, NativeSQL, IStatement} from "./statements/_statement";
import {IStatementResult} from "./statement_result";
import {AbstractToken} from "../1_lexer/tokens/abstract_token";
import {IABAPLexerResult} from "../1_lexer/lexer_result";
import {ExpandMacros} from "./expand_macros";
import {Pragma} from "../1_lexer/tokens";
import {IRegistry} from "../../_iregistry";
import {IStatementRunnable} from "./statement_runnable";
import {reclassifySelect} from "./_select_reclassify";
 
export const STATEMENT_MAX_TOKENS = 20000;
// each operator nests the matching of Source one level deeper, "a && a && ..." exceeds the default
// call stack of node at about 950 operators on a first parse, the longest found in real code is about 450
export const STATEMENT_MAX_OPERATORS = 700;
 
const OPERATORS = new Set(["&&", "&", "*", "/", "**", "DIV", "MOD"]);
 
/** counts the operators of arithmetic and string expressions in the tokens of a statement */
export function countOperators(tokens: readonly AbstractToken[]): number {
  let count = 0;
  for (let i = 0; i < tokens.length; i++) {
    const token = tokens[i];
    if (token instanceof Tokens.WPlusW || token instanceof Tokens.WDashW) {
      count++;
    } else if (token instanceof Tokens.Dash && tokens[i - 1]?.getStr().toUpperCase() === "BIT") {
      // "BIT-AND", "BIT-OR" and "BIT-XOR" are lexed as three tokens
      count++;
    } else if (token instanceof Tokens.Identifier && OPERATORS.has(token.getStr().toUpperCase())) {
      count++;
    }
  }
  return count;
}
 
const EMPTY_PRAGMAS: readonly AbstractToken[] = Object.freeze([]);
 
class StatementMap {
  // this also serves as container for statement matcher singletons,
  private readonly map: {[index: string]: {statement: IStatement, matcher?: IStatementRunnable}[]};
 
  public constructor() {
    this.map = {};
 
    for (const stat of ArtifactsABAP.getStatements()) {
      const f = stat.getMatcher().first();
      if (f.length === 0) {
        throw new Error("StatementMap, first must have contents");
      }
      for (const first of f) {
        if (this.map[first]) {
          this.map[first].push({statement: stat});
        } else {
          this.map[first] = [{statement: stat}];
        }
      }
    }
  }
 
  public lookup(str: string): readonly {statement: IStatement, matcher: IStatementRunnable}[] {
    const res = this.map[str.toUpperCase()];
    if (res === undefined) {
      return [];
    }
    if (res[0].matcher === undefined) {
      for (const r of res) {
        r.matcher = r.statement.getMatcher();
      }
    }
    return res as readonly {statement: IStatement, matcher: IStatementRunnable}[];
  }
}
 
class WorkArea {
  public readonly file: IFile;
  public readonly tokens: readonly AbstractToken[];
  public statements: StatementNode[];
 
  public constructor(file: IFile, tokens: readonly AbstractToken[]) {
    this.file = file;
    this.tokens = tokens;
    this.statements = [];
  }
 
  public addUnknown(pre: AbstractToken[], post: AbstractToken[], colon: AbstractToken | undefined) {
    const st = new StatementNode(new Unknown(), colon);
    st.setChildren(this.tokensToNodes(pre, post));
    this.statements.push(st);
  }
 
  public toResult(): IStatementResult {
    return {file: this.file, tokens: this.tokens, statements: this.statements};
  }
 
  private tokensToNodes(tokens1: AbstractToken[], tokens2: AbstractToken[]): TokenNode[] {
    const ret: TokenNode[] = [];
 
    for (const t of tokens1) {
      ret.push(new TokenNode(t));
    }
    for (const t of tokens2) {
      ret.push(new TokenNode(t));
    }
 
    return ret;
  }
}
 
export class StatementParser {
  private static map: StatementMap;
  private readonly release: ABAPRelease;
  private readonly languageVersion: LanguageVersion;
  private readonly reg?: IRegistry;
 
  public constructor(release: ABAPRelease, reg?: IRegistry,
                     languageVersion: LanguageVersion = LanguageVersion.Normal) {
    if (!StatementParser.map) {
      StatementParser.map = new StatementMap();
    }
    this.release = release;
    this.languageVersion = languageVersion;
    this.reg = reg;
  }
 
  /** input is one full object */
  public run(input: readonly IABAPLexerResult[], globalMacros: readonly string[]): IStatementResult[] {
    const macros = new ExpandMacros(globalMacros, this.release, this.reg, this.languageVersion);
 
    const wa = input.map(i => new WorkArea(i.file, i.tokens));
 
    for (const w of wa) {
      this.process(w);
      this.categorize(w);
      macros.find(w.statements, w.file);
    }
 
    for (const w of wa) {
      const res = macros.handleMacros(w.statements, w.file);
      w.statements = res.statements;
      if (res.containsUnknown === true) {
        this.lazyUnknown(w);
      }
      this.nativeSQL(w);
    }
 
    return wa.map(w => w.toResult());
  }
 
  // todo, refactor, remove method here and only have in WorkArea class
  private tokensToNodes(tokens: readonly AbstractToken[]): TokenNode[] {
    const ret: TokenNode[] = [];
 
    for (const t of tokens) {
      ret.push(new TokenNode(t));
    }
 
    return ret;
  }
 
// tries to split Unknown statements by newlines, when adding/writing a new statement
// in an editor, adding the statement terminator is typically the last thing to do
// note: this will not work if the second statement is a macro call, guess this is okay
  private lazyUnknown(wa: WorkArea) {
    const result: StatementNode[] = [];
 
    for (let statement of wa.statements) {
      // dont use CALL METHOD, when executing lazy, it easily gives a Move for the last statement if lazy logic is evaluated
      if (statement.get() instanceof Unknown) {
        const concat = statement.concatTokens().toUpperCase();
        if (concat.startsWith("CALL METHOD ") === false
            && concat.startsWith("RAISE EXCEPTION TYPE ") === false
            && concat.startsWith("READ TABLE ") === false
            && concat.startsWith("LOOP AT ") === false
            && concat.startsWith("SELECT SINGLE ") === false
            && concat.startsWith("CALL FUNCTION ") === false) {
          for (const {first, second} of this.buildSplits(statement.getTokens())) {
            if (second.length === 1) {
              continue; // probably punctuation
            }
            const s = this.categorizeStatement(new StatementNode(new Unknown()).setChildren(this.tokensToNodes(second)));
            if (!(s.get() instanceof Unknown) && !(s.get() instanceof Empty)) {
              result.push(new StatementNode(new Unknown()).setChildren(this.tokensToNodes(first)));
              statement = s;
              break;
            }
          }
        }
      }
      result.push(statement);
    }
 
    wa.statements = result;
  }
 
  private buildSplits(tokens: readonly AbstractToken[]): {first: AbstractToken[], second: AbstractToken[]}[] {
    const res: {first: AbstractToken[], second: AbstractToken[]}[] = [];
    const before: AbstractToken[] = [];
    let prevRow = tokens[0].getRow();
 
    for (let i = 0; i < tokens.length; i++) {
      if (tokens[i].getRow() !== prevRow) {
        res.push({first: [...before], second: [...tokens].splice(i)});
      }
      prevRow = tokens[i].getRow();
      before.push(tokens[i]);
    }
 
    return res;
  }
 
  private nativeSQL(wa: WorkArea) {
    let sql = false;
 
    for (let i = 0; i < wa.statements.length; i++) {
      const statement = wa.statements[i];
      const type = statement.get();
      if (type instanceof Statements.ExecSQL
          || (type instanceof Statements.MethodImplementation && statement.findDirectExpression(Expressions.Language))) {
        sql = true;
      } else if (sql === true) {
        if (type instanceof Statements.EndExec
            || type instanceof Statements.EndMethod) {
          sql = false;
        } else {
          wa.statements[i] = new StatementNode(new NativeSQL()).setChildren(this.tokensToNodes(statement.getTokens()));
 
          if (statement.concatTokens().toUpperCase().endsWith("ENDMETHOD.")) {
            const tokens = statement.getTokens();
            const startTokens = this.tokensToNodes(tokens.slice(tokens.length - 2, tokens.length));
            const endTokens = this.tokensToNodes(tokens.slice(0, tokens.length - 2));
            wa.statements[i] = new StatementNode(new NativeSQL()).setChildren(endTokens);
            const item = new StatementNode(new Statements.EndMethod()).setChildren(startTokens);
            wa.statements.splice(i + 1, 0, item);
            sql = false;
          }
        }
      }
    }
  }
 
// for each statement, run statement matchers to figure out which kind of statement it is
  private categorize(wa: WorkArea) {
    const result: StatementNode[] = [];
 
    for (const statement of wa.statements) {
      result.push(this.categorizeStatement(statement));
    }
    wa.statements = result;
  }
 
  private categorizeStatement(input: StatementNode) {
    let statement = input;
 
    const length = input.getChildren().length;
    const lastToken = input.getLastToken();
    const isPunctuation = lastToken instanceof Tokens.Punctuation;
 
    if (length === 1 && isPunctuation) {
      const tokens = statement.getTokens();
      statement = new StatementNode(new Empty()).setChildren(this.tokensToNodes(tokens));
    } else if (statement.get() instanceof Unknown) {
      if (length > STATEMENT_MAX_OPERATORS && countOperators(input.getTokens()) > STATEMENT_MAX_OPERATORS) {
        // matching would exceed the call stack, give up, parser_error reports it
        statement = input;
      } else if (isPunctuation) {
        statement = this.match(statement);
      } else if (length > STATEMENT_MAX_TOKENS) {
        // if the statement contains more than STATEMENT_MAX_TOKENS tokens, just give up
        statement = input;
      } else if (length === 1 && lastToken instanceof Pragma) {
        // special case, everything crashes if StatementNodes doesnt have children
        statement = new StatementNode(new Empty(), undefined, [lastToken])
          .setChildren(this.tokensToNodes([lastToken]));
      }
    }
 
    return statement;
  }
 
  private removePragma(tokens: readonly AbstractToken[]): {tokens: AbstractToken[], pragmas: readonly AbstractToken[]} {
    let hasPragma = false;
    // skip the last token as it is the punctuation
    for (let i = 0; i < tokens.length - 1; i++) {
      if (tokens[i] instanceof Tokens.Pragma) {
        hasPragma = true;
        break;
      }
    }
    if (hasPragma === false) {
      return {tokens: tokens.slice(0, tokens.length - 1), pragmas: EMPTY_PRAGMAS};
    }
 
    const result: AbstractToken[] = [];
    const pragmas: AbstractToken[] = [];
    for (let i = 0; i < tokens.length - 1; i++) {
      const t = tokens[i];
      if (t instanceof Tokens.Pragma) {
        pragmas.push(t);
      } else {
        result.push(t);
      }
    }
 
    return {tokens: result, pragmas: pragmas};
  }
 
  private match(statement: StatementNode): StatementNode {
    const tokens = statement.getTokens();
    const {tokens: filtered, pragmas} = this.removePragma(tokens);
    if (filtered.length === 0) {
      return new StatementNode(new Empty()).setChildren(this.tokensToNodes(tokens));
    }
 
    for (const st of StatementParser.map.lookup(filtered[0].getStr())) {
      const match = Combi.run(st.matcher, filtered, this.release, this.languageVersion);
      if (match) {
        const last = tokens[tokens.length - 1];
        match.push(new TokenNode(last));
        const matched = new StatementNode(st.statement, statement.getColon(), pragmas).setChildren(match);
        return reclassifySelect(matched, st.statement, pragmas);
      }
    }
    // next try the statements without specific keywords
    for (const st of StatementParser.map.lookup("")) {
      const match = Combi.run(st.matcher, filtered, this.release, this.languageVersion);
      if (match) {
        const last = tokens[tokens.length - 1];
        match.push(new TokenNode(last));
        const matched = new StatementNode(st.statement, statement.getColon(), pragmas).setChildren(match);
        return reclassifySelect(matched, st.statement, pragmas);
      }
    }
 
    return statement;
  }
 
// takes care of splitting tokens into statements, also handles chained statements
// statements are split by "," or "."
// additional colons/chaining after the first colon are ignored
  private process(wa: WorkArea) {
    let add: AbstractToken[] = [];
    let pre: AbstractToken[] = [];
    let colon: AbstractToken | undefined = undefined;
    // inside EXEC SQL and an AMDP body a colon reads a host variable, ":lv_a",
    // and is not the chaining marker; recognized here because nativeSQL() runs
    // afterwards and can only re-wrap what this has already cut
    let native = false;
 
    for (const token of wa.tokens) {
      if (token instanceof Tokens.Comment) {
        wa.statements.push(new StatementNode(new Comment()).setChildren(this.tokensToNodes([token])));
        continue;
      }
 
      add.push(token);
 
      const str = token.getStr();
      if (str.length === 1) {
        if (str === ".") {
          native = this.nativeAfter(native, add, colon);
          wa.addUnknown(pre, add, colon);
          add = [];
          pre = [];
          colon = undefined;
        } else if (str === "," && pre.length > 0) {
          wa.addUnknown(pre, add, colon);
          add = [];
        } else if (str === ":" && colon === undefined && native === false) {
          colon = token;
          add.pop(); // do not add colon token to statement
          pre.push(...add);
          add = [];
        } else if (str === ":" && native === false) {
          add.pop(); // do not add colon token to statement
        }
      }
    }
 
    if (add.length > 0) {
      wa.addUnknown(pre, add, colon);
    }
  }
 
  /** whether the statement that just ended opens or closes a region where a
   * colon belongs to the statement rather than chaining it */
  private nativeAfter(native: boolean, tokens: readonly AbstractToken[], colon: AbstractToken | undefined): boolean {
    // a pragma sits between the closing keyword and the period, so it is left
    // out before the last word is read: "ENDEXEC ##NEEDED." closes the region
    const words = tokens.filter(t => !(t instanceof Tokens.Pragma)).map(t => t.getStr().toUpperCase());
    // a native body usually arrives as one blob terminated by its own closing
    // keyword, so the terminator is the word before the period
    if (words[words.length - 2] === "ENDEXEC" || words[words.length - 2] === "ENDMETHOD") {
      return false;
    }
    if (colon !== undefined) {
      // a fragment of a chain cannot OPEN a region: it is only part of a
      // statement, and taking "DATA: lv_a TYPE i, exec sql." for one would
      // turn chaining off for the rest of the file
      return native;
    }
    if (words[0] === "EXEC" && words[1] === "SQL") {
      return true;
    }
    // "BY DATABASE" as well as LANGUAGE, and not LANGUAGE alone: a method
    // may be NAMED language
    if (words[0] === "METHOD"
        && words.includes("BY")
        && words.includes("DATABASE")
        && words.includes("LANGUAGE")) {
      return true;
    }
    return native;
  }
}