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

98.73% Statements 156/158
93.85% Branches 61/65
100% Functions 19/19
98.69% Lines 151/153

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 3011x 1x 1x     1x 1x 1x 1x       1x   1x           1x   1x 292x 292x     292x 299x 128x   171x             13311x 13311x 670x   12641x                   5089x 5089x 5089x       12307x 12307x 12307x       5089x       12307x   12307x 1161x   12307x 72009x     12307x       1x         5071x 1x   5071x         5071x   5089x   5071x 5089x 5089x 5089x     5071x 5089x 5089x 5089x 277x   5089x     5089x         287x   287x 1457x     287x             277x   277x 497x 282x 101x 101x 24x 24x 24x       497x     277x       282x 282x 282x   282x 2489x 101x   2489x 2489x     282x       5089x   5089x 12509x 12509x 12509x   13x 12496x 14x   5x 9x 9x                 5089x   5089x 12446x   5089x       12547x   12547x 12547x   12547x 13x 13x   12534x   12534x 12293x     12547x       12293x 12293x     12293x 61731x 61731x 29x   61702x       12293x       12293x 12293x 12293x 1x     12292x 24847x 24847x 11273x 11273x 11273x       1019x 1813x 1813x 717x 717x 717x       302x             5089x 5089x 5089x   5089x 73248x 139x 139x     73109x   73109x 73109x 11668x 11668x 11668x 11668x 61441x 540x 540x 60901x 513x 513x 513x 513x 60388x 2x       5089x 99x      
import * as Statements from "./statements";
import * as Expressions from "./expressions";
import * as Tokens from "../1_lexer/tokens";
import {Version} from "../../version";
import {IFile} from "../../files/_ifile";
import {TokenNode, StatementNode} from "../nodes";
import {Artifacts} from "../artifacts";
import {Combi} from "./combi";
import {Unknown, Empty, Comment, NativeSQL, IStatement} from "./statements/_statement";
import {IStatementResult} from "./statement_result";
import {Token} from "../1_lexer/tokens/_token";
import {ILexerResult} from "../1_lexer/lexer_result";
import {ExpandMacros} from "./expand_macros";
 
export const STATEMENT_MAX_TOKENS = 1000;
 
class StatementMap {
  private readonly map: {[index: string]: IStatement[]};
 
  public constructor() {
    this.map = {};
 
    for (const stat of Artifacts.getStatements()) {
      const f = stat.getMatcher().first();
      Iif (f.length === 0) {
        throw new Error("StatementMap, first must have contents");
      }
      for (const first of f) {
        if (this.map[first]) {
          this.map[first].push(stat);
        } else {
          this.map[first] = [stat];
        }
      }
    }
  }
 
  public lookup(str: string): readonly IStatement[] {
    const res = this.map[str.toUpperCase()];
    if (res === undefined) {
      return [];
    }
    return res;
  }
}
 
class WorkArea {
  private readonly file: IFile;
  public readonly tokens: readonly Token[];
  public statements: StatementNode[];
 
  public constructor(file: IFile, tokens: readonly Token[]) {
    this.file = file;
    this.tokens = tokens;
    this.statements = [];
  }
 
  public addUnknown(pre: Token[], post: Token[], colon: Token | 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: Token[], tokens2: Token[]): 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 version: Version;
 
  public constructor(version: Version) {
    if (!StatementParser.map) {
      StatementParser.map = new StatementMap();
    }
    this.version = version;
  }
 
  /** input is one full object */
  public run(input: readonly ILexerResult[], globalMacros: readonly string[]): IStatementResult[] {
    const macros = new ExpandMacros(globalMacros, this.version);
 
    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);
    }
 
    for (const w of wa) {
      const res = macros.handleMacros(w.statements);
      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 Token[]): 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) {
      if (statement.get() instanceof Unknown) {
        for (const {first, second} of this.buildSplits(statement.getTokens())) {
          const s = this.categorizeStatement(new StatementNode(new Unknown()).setChildren(this.tokensToNodes(second)));
          if (!(s.get() instanceof Unknown)) {
            result.push(new StatementNode(new Unknown()).setChildren(this.tokensToNodes(first)));
            statement = s;
            break;
          }
        }
      }
      result.push(statement);
    }
 
    wa.statements = result;
  }
 
  private buildSplits(tokens: readonly Token[]): {first: Token[], second: Token[]}[] {
    const res: {first: Token[], second: Token[]}[] = [];
    const before: Token[] = [];
    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 Eif (!(type instanceof Comment)) {
          wa.statements[i] = new StatementNode(new NativeSQL()).setChildren(this.tokensToNodes(statement.getTokens()));
        }
      }
    }
 
  }
 
// 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 isPunctuation = input.getLastToken() instanceof Tokens.Punctuation;
 
    if (length === 1 && isPunctuation) {
      const tokens = statement.getTokens();
      statement = new StatementNode(new Empty()).setChildren(this.tokensToNodes(tokens));
// if the statement contains more than STATEMENT_MAX_TOKENS tokens, just give up
    } else Iif (length > STATEMENT_MAX_TOKENS && statement.get() instanceof Unknown) {
      statement = input;
    } else if (statement.get() instanceof Unknown && isPunctuation) {
      statement = this.match(statement);
    }
 
    return statement;
  }
 
  private removePragma(tokens: readonly Token[]): {tokens: Token[], pragmas: Token[]} {
    const result: Token[] = [];
    const pragmas: Token[] = [];
 
    // skip the last token as it is the punctuation
    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.getMatcher(), filtered, this.version);
      if (match) {
        const last = tokens[tokens.length - 1];
        match.push(new TokenNode(last));
        return new StatementNode(st, statement.getColon(), pragmas).setChildren(match);
      }
    }
    // next try the statements without specific keywords
    for (const st of StatementParser.map.lookup("")) {
      const match = Combi.run(st.getMatcher(), filtered, this.version);
      if (match) {
        const last = tokens[tokens.length - 1];
        match.push(new TokenNode(last));
        return new StatementNode(st, statement.getColon(), pragmas).setChildren(match);
      }
    }
 
    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: Token[] = [];
    let pre: Token[] = [];
    let colon: Token | undefined = undefined;
 
    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 === ".") {
        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) {
        colon = token;
        add.pop(); // do not add colon token to statement
        pre.push(...add);
        add = [];
      } else if (str === ":") {
        add.pop(); // do not add colon token to statement
      }
    }
 
    if (add.length > 0) {
      wa.addUnknown(pre, add, colon);
    }
  }
}