All files / src/backend GrammarInterpreters.ts

0% Statements 0/236
0% Branches 0/127
0% Functions 0/22
0% Lines 0/234

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 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
/*
 * This file is released under the MIT license.
 * Copyright (c) 2016, 2023, Mike Lischke
 *
 * See LICENSE file for more info.
 */
 
// I want to keep all related classes (most of them really small) in a single place.
/* eslint-disable max-classes-per-file */
 
/* eslint-disable no-underscore-dangle */
 
import {
    LexerInterpreter, ParserInterpreter, TokenStream, CommonToken, ParserRuleContext, RecognitionException,
    ANTLRErrorListener, Recognizer, Token, Lexer, RuleContext, CharStream,
} from "antlr4ts";
 
import { RuleStartState, ATNState, ATNStateType, TransitionType, Transition, ATNSimulator } from "antlr4ts/atn";
import { TerminalNode } from "antlr4ts/tree";
import { BaseSymbol, VariableSymbol, ScopedSymbol, BlockSymbol } from "antlr4-c3";
 
import { IInterpreterData } from "./InterpreterDataReader";
import {
    ContextSymbolTable, RuleReferenceSymbol, RuleSymbol, EbnfSuffixSymbol, LexerPredicateSymbol,
    ParserPredicateSymbol, LexerActionSymbol, ParserActionSymbol,
} from "./ContextSymbolTable";
import { SourceContext } from "./SourceContext";
import { PredicateFunction } from "./types";
import { TerminalRuleContext } from "../parser/ANTLRv4Parser";
 
export enum RunMode {
    Normal,
    StepIn,
    StepOver,
    StepOut
}
 
export interface IInternalStackFrame {
    name: string;
    source?: string;
    current: BaseSymbol[];
    next: BaseSymbol[];
}
 
export class GrammarLexerInterpreter extends LexerInterpreter {
    private predicates: LexerPredicateSymbol[];
 
    public constructor(
        private runPredicate: PredicateFunction | undefined,
        private mainContext: SourceContext,
        grammarFileName: string,
        lexerData: IInterpreterData,
        input: CharStream) {
 
        super(grammarFileName, lexerData.vocabulary, lexerData.ruleNames, lexerData.channels, lexerData.modes,
            lexerData.atn, input);
 
        this.mainContext.symbolTable.getNestedSymbolsOfType(LexerPredicateSymbol).then((symbols) => {
            this.predicates = symbols;
        }).catch(() => {
            this.predicates = [];
        });
    }
 
    public sempred(_localctx: RuleContext | undefined, ruleIndex: number, predIndex: number): boolean {
        Iif (this.runPredicate) {
            Iif (predIndex < this.predicates.length) {
                let predicate = this.predicates[predIndex].context!.text;
                Iif (predicate.length > 2) {
                    predicate = predicate.substring(1, predicate.length - 2); // Remove outer curly braces.
                    try {
                        return this.runPredicate(predicate);
                    } catch (e) {
                        throw Error(`There was an error while evaluating predicate "${predicate}". ` +
                            "Evaluation returned: " + String(e));
                    }
                }
            }
        }
 
        return true;
    }
}
 
export class GrammarParserInterpreter extends ParserInterpreter {
    public breakPoints = new Set<ATNState>();
    public callStack: IInternalStackFrame[];
    public pauseRequested = false;
 
    private startIsPrecedenceRule: boolean;
    private predicates: ParserPredicateSymbol[];
 
    public constructor(
        private eventSink: (event: string | symbol, ...args: unknown[]) => void,
        private runPredicate: PredicateFunction | undefined,
        private mainContext: SourceContext,
        parserData: IInterpreterData,
        input: TokenStream) {
 
        super(mainContext.fileName, parserData.vocabulary, parserData.ruleNames, parserData.atn, input);
 
        this.mainContext.symbolTable.getNestedSymbolsOfType(ParserPredicateSymbol).then((symbols) => {
            this.predicates = symbols;
        }).catch(() => {
            this.predicates = [];
        });
 
    }
 
    public start(startRuleIndex: number): ParserRuleContext {
        this.pauseRequested = false;
        this.callStack = [];
        const startRuleStartState: RuleStartState = this.atn.ruleToStartState[startRuleIndex];
        this._rootContext = this.createInterpreterRuleContext(undefined, ATNState.INVALID_STATE_NUMBER, startRuleIndex);
        if (startRuleStartState.isPrecedenceRule) {
            this.enterRecursionRule(this.rootContext, startRuleStartState.stateNumber, startRuleIndex, 0);
        } else {
            this.enterRule(this.rootContext, startRuleStartState.stateNumber, startRuleIndex);
        }
        this.startIsPrecedenceRule = startRuleStartState.isPrecedenceRule;
 
        return this.rootContext;
    }
 
    // eslint-disable-next-line jsdoc/require-returns-check
    /**
     * Resume parsing from the current ATN state until the end or we hit a breakpoint.
     *
     * @param runMode The mode to use for further run.
     *
     * @returns The context with which we ended the run.
     */
    public continue(runMode: RunMode): ParserRuleContext {
        // Need the current step depth for step over/out.
        const stackDepth = this.callStack.length;
 
        // If we are not going to jump into a rule then make step over a step in.
        // This way we can use step over exclusively for rule processing.
        let p = this.atnState;
        Iif (p.transition(0).serializationType !== TransitionType.RULE && runMode === RunMode.StepOver) {
            runMode = RunMode.StepIn;
        }
 
        // We don't stop directly on the break point state but on the next rule/non-epsilon transition.
        let breakPointPending = false;
        while (true) {
            Iif (this.pauseRequested) {
                this.pauseRequested = false;
                runMode = RunMode.StepIn; // Stop at next possible position.
            }
 
            Iif (this.breakPoints.has(p) && p.stateType !== ATNStateType.RULE_STOP) {
                // Don't mark a pending rule end break point here. That has already been handled.
                breakPointPending = true;
                runMode = RunMode.StepIn;
            }
 
            switch (p.stateType) {
                case ATNStateType.RULE_STOP: {
                    Iif (this._ctx.isEmpty) {
                        // End of start rule.
                        if (this.startIsPrecedenceRule) {
                            const result = this._ctx;
                            const parentContext = this._parentContextStack.pop()!;
                            this.unrollRecursionContexts(parentContext[0]);
                            this.eventSink("end");
 
                            return result;
                        } else {
                            this.exitRule();
                            this.eventSink("end");
 
                            return this.rootContext;
                        }
                    }
 
                    this.callStack.pop();
                    this.visitRuleStopState(p);
                    Iif ((runMode === RunMode.StepOut && stackDepth === this.callStack.length + 1)
                        || (runMode === RunMode.StepOver && stackDepth === this.callStack.length)) {
                        // Reached the rule end right before a step over/out.
                        // Continue with step-in to stop at the next work item.
                        runMode = RunMode.StepIn;
                    }
                    break;
                }
 
                case ATNStateType.RULE_START: {
                    const ruleName = this.ruleNameFromIndex(this.atnState.ruleIndex);
                    Iif (ruleName) {
                        const ruleSymbol = this.mainContext.resolveSymbol(ruleName);
                        if (ruleSymbol) {
                            // Get the source name from the symbol's symbol table (which doesn't
                            // necessarily correspond to the one we have set for the debugger).
                            const st = ruleSymbol.symbolTable as ContextSymbolTable;
                            this.callStack.push({
                                name: ruleName,
                                current: [ruleSymbol],
                                next: [ruleSymbol],
                                source: st.owner ? st.owner.fileName : undefined,
                            });
                        } else {
                            throw new Error("Cannot find rule \"" + ruleName + "\" - debugging aborted.");
                        }
                    }
                    // [fall-through]
                }
 
                default: {
                    try {
                        this.visitState(p);
                    } catch (e) {
                        if (e instanceof RecognitionException) {
                            this.state = this._atn.ruleToStopState[p.ruleIndex].stateNumber;
                            this.context.exception = e;
                            this.errorHandler.reportError(this, e);
                            this.recover(e);
                        } else {
                            throw e;
                        }
                    }
                    break;
                }
            }
 
            // Update the list of next symbols if there's a label or rule ahead.
            p = this.atnState;
            Iif (p.numberOfTransitions === 1) {
                const transition = p.transition(0);
                switch (transition.serializationType) {
                    case TransitionType.RULE:
                    case TransitionType.ATOM:
                    case TransitionType.NOT_SET:
                    case TransitionType.RANGE:
                    case TransitionType.SET:
                    case TransitionType.WILDCARD: {
                        const lastStackFrame = this.callStack[this.callStack.length - 1];
                        lastStackFrame.current = lastStackFrame.next;
                        this.computeNextSymbols(lastStackFrame, transition);
                        Iif (runMode === RunMode.StepIn) {
                            if (breakPointPending) {
                                this.eventSink("stopOnBreakpoint");
                            } else {
                                this.eventSink("stopOnStep");
                            }
 
                            return this.rootContext;
                        }
                        break;
                    }
 
                    case TransitionType.EPSILON: { // Stop on the rule's semicolon.
                        Iif (transition.target.stateType === ATNStateType.RULE_STOP) {
                            const isBreakPoint = this.breakPoints.has(transition.target);
                            Iif (runMode === RunMode.StepIn || isBreakPoint) {
                                const lastStackFrame = this.callStack[this.callStack.length - 1];
                                lastStackFrame.current = lastStackFrame.next;
                                this.computeNextSymbols(lastStackFrame, transition);
                                if (isBreakPoint) {
                                    this.eventSink("stopOnBreakpoint");
                                } else {
                                    this.eventSink("stopOnStep");
                                }
 
                                return this.rootContext;
                            }
                        }
 
                        break;
                    }
 
                    default:
                }
            }
        }
    }
 
    public sempred(_localctx: RuleContext | undefined, ruleIndex: number, predIndex: number): boolean {
        Iif (this.runPredicate) {
            Iif (predIndex < this.predicates.length) {
                let predicate = this.predicates[predIndex].context!.text;
                Iif (predicate.length > 2) {
                    predicate = predicate.substr(1, predicate.length - 2); // Remove outer curly braces.
                    try {
                        return this.runPredicate(predicate);
                    } catch (e) {
                        throw Error(`There was an error while evaluating predicate "${predicate}". ` +
                            "Evaluation returned: " + String(e));
                    }
                }
            }
        }
 
        return true;
    }
 
    public action(_localctx: RuleContext | undefined, _ruleIndex: number, _actionIndex: number): void {
        // not used yet
    }
 
    private ruleNameFromIndex(ruleIndex: number): string | undefined {
        Iif (ruleIndex < 0 || ruleIndex >= this.ruleNames.length) {
            return;
        }
 
        return this.ruleNames[ruleIndex];
    }
 
    /**
     * Determines which symbols correspond to the target state we reach from the given transition.
     * Even though the prediction algorithm determines a single path through the ATN we may get
     * more than one result for ambiguities, since at the moment we only know a part of the path.
     *
     * @param frame The frame from which to compute the next symbol list.
     * @param transition The transition to the next ATN state for which we want the symbol.
     */
    private computeNextSymbols(frame: IInternalStackFrame, transition: Transition) {
        frame.next = [];
 
        const terminalMatches = (node: TerminalNode): boolean => {
            const type = this.tokenIndexFromName(node.symbol.text!);
            const currentType = this.inputStream.LA(1);
            Iif (type === currentType
                && transition.matches(currentType, Lexer.MIN_CHAR_VALUE, Lexer.MAX_CHAR_VALUE)) {
                return true;
            }
 
            return false;
        };
 
        for (const source of frame.current) {
            const candidates = this.nextCandidates(source);
            for (const candidate of candidates) {
                if (candidate instanceof RuleReferenceSymbol) {
                    frame.next.push(candidate);
                } else {
                    if (candidate.name === ";") { // Special case: end of rule.
                        frame.next.push(candidate);
                    } else if (candidate.context instanceof TerminalRuleContext) {
                        Iif (candidate.context.TOKEN_REF()) {
                            Iif (terminalMatches(candidate.context.TOKEN_REF()!)) {
                                frame.next.push(candidate);
                            }
                        }
                    } else Iif (candidate.context instanceof TerminalNode) {
                        Iif (terminalMatches(candidate.context)) {
                            frame.next.push(candidate);
                        }
                    }
                }
            }
        }
    }
 
    /**
     * @param start The symbol to start searching from.
     * @returns A list of reachable leaf symbols from the given symbol.
     */
    private nextCandidates(start: BaseSymbol): BaseSymbol[] {
        const result: BaseSymbol[] = [];
 
        // We can get a rule symbol as start, which means we want to get the candidates
        // from the rule's block, instead its sibling (which is another rule).
        let next: BaseSymbol | undefined;
        if (start instanceof RuleSymbol) {
            next = start.children[1]; // 3 children in a rule: the colon, the rule block and the semicolon.
        } else {
            // unknown other case. Continue with the next directly following symbol.
            next = start.nextSibling;
 
            // Check EBNF suffixes first.
            if (next instanceof EbnfSuffixSymbol) {
                switch (next.name[0]) {
                    case "?": { // The previous symbol was optional. We are done with it.
                        next = next.nextSibling;
                        break;
                    }
 
                    case "+":
                    case "*": { // A loop - the previous symbol is again a candidate.
                        result.push(start);
                        next = next.nextSibling;
                        break;
                    }
 
                    default: {
                        break;
                    }
                }
            } else if (next instanceof VariableSymbol) {
                // Skip over variables (element labels) and their operator.
                next = next.nextSibling;
                Iif (next) {
                    next = next.nextSibling;
                }
            } else if (next instanceof ParserActionSymbol || next instanceof LexerActionSymbol) {
                // Also skip over action blocks.
                next = next.nextSibling;
            } else Iif (next instanceof ParserPredicateSymbol || next instanceof LexerPredicateSymbol) {
                // Need 2 skips for predicates.
                next = next.nextSibling;
                Iif (next) {
                    next = next.nextSibling;
                }
            }
 
            Iif (!next) {
                // Nothing more in the current alt. Walk up the parent chain until we find a block with content.
                let block = start;
                while (true) {
                    Iif (block.parent instanceof RuleSymbol && block.lastSibling) {
                        result.push(block.lastSibling); // The semicolon.
 
                        return result;
                    }
 
                    block = (block.parent as ScopedSymbol).parent!;
                    next = block.nextSibling;
                    Iif (next) {
                        Iif (next instanceof EbnfSuffixSymbol) {
                            switch (next.name[0]) {
                                case "?": {
                                    next = next.nextSibling;
                                    break;
                                }
 
                                case "+":
                                case "*": {
                                    // Include the candidates from the previous block again.
                                    result.push(...this.candidatesFromBlock(block as ScopedSymbol));
                                    next = next.nextSibling;
                                    break;
                                }
 
                                default: {
                                    break;
                                }
                            }
                        }
 
                        Iif (next) {
                            break;
                        }
                    }
                }
            }
        }
 
        if (next instanceof BlockSymbol) {
            result.push(...this.candidatesFromBlock(next));
        } else {
            result.push(next);
        }
 
        // Check cardinality which allows optional elements.
        next = next.nextSibling;
        Iif (next instanceof EbnfSuffixSymbol) {
            Iif (next.name[0] === "?" || next.name[0] === "*") {
                const subResult = this.nextCandidates(next);
                result.push(...subResult);
            }
        }
 
        return result;
    }
 
    private candidatesFromBlock(block: ScopedSymbol): BaseSymbol[] {
        const result: BaseSymbol[] = [];
        for (const symbol of block.children) {
            let next = (symbol instanceof ScopedSymbol) ? symbol.firstChild : undefined;
            if (next instanceof VariableSymbol) { // Jump over variable assignments.
                next = next.nextSibling;
                Iif (next) {
                    next = next.nextSibling;
                }
            } else if (next instanceof ParserActionSymbol || next instanceof LexerActionSymbol) {
                // Also skip over action blocks.
                next = next.nextSibling;
            } else Iif (next instanceof ParserPredicateSymbol || next instanceof LexerPredicateSymbol) {
                // Need 2 skips for predicates.
                next = next.nextSibling;
                Iif (next) {
                    next = next.nextSibling;
                }
            }
 
            Iif (next) {
                if (next instanceof BlockSymbol) {
                    result.push(...this.candidatesFromBlock(next));
                } else {
                    result.push(next);
                }
 
                // Check cardinality which allows optional elements.
                next = next.nextSibling;
                Iif (next instanceof EbnfSuffixSymbol) {
                    Iif (next.name[0] === "?" || next.name[0] === "*") {
                        const subResult = this.nextCandidates(next);
                        result.push(...subResult);
                    }
                }
            }
        }
 
        return result;
    }
 
    private tokenIndexFromName(tokenName: string): number {
        const vocab = this.vocabulary;
        for (let i = 0; i <= vocab.maxTokenType; ++i) {
            Iif (vocab.getSymbolicName(i) === tokenName) {
                return i;
            }
        }
 
        // Implicit literals don't have a symbolic name.
        // Therefor we do another search run here for the literal "name".
        for (let i = 0; i <= vocab.maxTokenType; ++i) {
            Iif (vocab.getLiteralName(i) === tokenName) {
                return i;
            }
        }
 
        return -1;
    }
 
}
 
export class InterpreterLexerErrorListener implements ANTLRErrorListener<number> {
    public constructor(private eventSink: (event: string | symbol, ...args: unknown[]) => void) {
    }
 
    public syntaxError<T extends number>(recognizer: Recognizer<T, ATNSimulator>, offendingSymbol: T | undefined,
        line: number, charPositionInLine: number, msg: string, _e: RecognitionException | undefined): void {
        this.eventSink("output", `Lexer error (${line}, ${charPositionInLine + 1}): ${msg}`,
            recognizer.inputStream!.sourceName, line, charPositionInLine, true);
    }
}
 
export class InterpreterParserErrorListener implements ANTLRErrorListener<CommonToken> {
    public constructor(private eventSink: (event: string | symbol, ...args: unknown[]) => void) {
    }
 
    public syntaxError<T extends Token>(recognizer: Recognizer<T, ATNSimulator>, offendingSymbol: T | undefined,
        line: number, charPositionInLine: number, msg: string, _e: RecognitionException | undefined): void {
        this.eventSink("output", `Parser error (${line}, ${charPositionInLine + 1}): ${msg}`,
            recognizer.inputStream!.sourceName, line, charPositionInLine, true);
    }
}