All files / src/backend DetailsListener.ts

0% Statements 0/141
0% Branches 0/70
0% Functions 0/37
0% Lines 0/140

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
/*
 * This file is released under the MIT license.
 * Copyright (c) 2016, 2021, Mike Lischke
 *
 * See LICENSE file for more info.
 */
 
// Need explicit any and any-spread for constructor functions.
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unsafe-argument */
 
import { ANTLRv4ParserListener } from "../parser/ANTLRv4ParserListener";
import {
    LexerRuleSpecContext, ParserRuleSpecContext, TokensSpecContext, ChannelsSpecContext,
    ModeSpecContext, DelegateGrammarContext, TerminalRuleContext, RulerefContext,
    BlockContext, AlternativeContext, RuleBlockContext, EbnfSuffixContext,
    OptionsSpecContext, ActionBlockContext, ArgActionBlockContext, LabeledElementContext,
    LexerRuleBlockContext, LexerAltContext, ElementContext, LexerElementContext, NamedActionContext,
    LexerCommandContext, OptionContext, OptionValueContext, ANTLRv4Parser,
} from "../parser/ANTLRv4Parser";
 
import {
    ContextSymbolTable, FragmentTokenSymbol, TokenSymbol, TokenReferenceSymbol, RuleSymbol, RuleReferenceSymbol,
    VirtualTokenSymbol, TokenChannelSymbol, LexerModeSymbol, ImportSymbol, AlternativeSymbol, EbnfSuffixSymbol,
    ArgumentSymbol, OperatorSymbol, GlobalNamedActionSymbol, ExceptionActionSymbol, FinallyActionSymbol,
    ParserActionSymbol, LexerActionSymbol, OptionsSymbol, OptionSymbol, LexerPredicateSymbol,
    ParserPredicateSymbol, LocalNamedActionSymbol, LexerCommandSymbol,
} from "./ContextSymbolTable";
 
import { SourceContext } from "./SourceContext";
 
import { LiteralSymbol, BlockSymbol, BaseSymbol, VariableSymbol, SymbolConstructor } from "antlr4-c3";
import { ParseTree, TerminalNode } from "antlr4ts/tree";
import { ANTLRv4Lexer } from "../parser/ANTLRv4Lexer";
 
/**
 * Removes outer quotes from the input.
 *
 * @param input The input to clean up.
 * @param quoteChar The quote char to remove.
 *
 * @returns The cleaned string.
 */
const unquote = (input: string, quoteChar?: string): string => {
    quoteChar = quoteChar || '"';
    Iif (input[0] === quoteChar && input[input.length - 1] === quoteChar) {
        return input.slice(1, input.length - 1);
    }
 
    return input;
};
 
export class DetailsListener implements ANTLRv4ParserListener {
    private symbolStack: BaseSymbol[] = [];
 
    public constructor(private symbolTable: ContextSymbolTable, private imports: string[]) { }
 
    /**
     * The symbol stack usually contains entries beginning with a rule context, followed by a number of blocks and alts
     * as well as additional parts like actions or predicates.
     * This function returns the name of the first symbol, which represents the rule (parser/lexer) which we are
     * currently walking over.
     *
     * @returns The rule name from the start symbol.
     */
    private get ruleName(): string {
        return this.symbolStack.length === 0 ? "" : this.symbolStack[0].name;
    }
 
    public enterParserRuleSpec(ctx: ParserRuleSpecContext): void {
        this.pushNewSymbol(RuleSymbol, ctx, ctx.RULE_REF().text);
    }
 
    public exitParserRuleSpec(_ctx: ParserRuleSpecContext): void {
        this.popSymbol();
    }
 
    public enterRuleBlock(ctx: RuleBlockContext): void {
        this.pushNewSymbol(BlockSymbol, ctx, "");
    }
 
    public exitRuleBlock(): void {
        this.popSymbol();
    }
 
    public enterLexerRuleSpec(ctx: LexerRuleSpecContext): void {
        if (ctx.FRAGMENT()) {
            this.pushNewSymbol(FragmentTokenSymbol, ctx, ctx.TOKEN_REF().text);
        } else {
            this.pushNewSymbol(TokenSymbol, ctx, ctx.TOKEN_REF().text);
        }
    }
 
    public exitLexerRuleSpec(): void {
        this.popSymbol();
    }
 
    public enterLexerRuleBlock(ctx: LexerRuleBlockContext): void {
        this.pushNewSymbol(BlockSymbol, ctx, "");
    }
 
    public exitLexerRuleBlock(_ctx: LexerRuleBlockContext): void {
        this.popSymbol();
    }
 
    public enterBlock(ctx: BlockContext): void {
        this.pushNewSymbol(BlockSymbol, ctx, "");
    }
 
    public exitBlock(_ctx: BlockContext): void {
        this.popSymbol();
    }
 
    public enterAlternative(ctx: AlternativeContext): void {
        this.pushNewSymbol(AlternativeSymbol, ctx, "");
    }
 
    public exitAlternative(_ctx: AlternativeContext): void {
        this.popSymbol();
    }
 
    public enterLexerAlt(ctx: LexerAltContext): void {
        this.pushNewSymbol(AlternativeSymbol, ctx, "");
    }
 
    public exitLexerAlt(_ctx: LexerAltContext): void {
        this.popSymbol();
    }
 
    public exitTokensSpec(ctx: TokensSpecContext): void {
        const idList = ctx.idList();
        Iif (idList) {
            for (const identifier of idList.identifier()) {
                this.addNewSymbol(VirtualTokenSymbol, ctx, identifier.text);
            }
        }
    }
 
    public exitChannelsSpec(ctx: ChannelsSpecContext): void {
        const idList = ctx.idList();
        Iif (idList) {
            for (const identifier of idList.identifier()) {
                this.addNewSymbol(TokenChannelSymbol, ctx, identifier.text);
            }
        }
    }
 
    public exitTerminalRule(ctx: TerminalRuleContext): void {
        let token = ctx.TOKEN_REF();
        if (token) {
            this.addNewSymbol(TokenReferenceSymbol, ctx, token.text);
        } else {
            // Must be a string literal then.
            token = ctx.STRING_LITERAL();
            Iif (token) {
                const refName = unquote(token.text, "'");
                this.addNewSymbol(LiteralSymbol, token, refName, refName);
            }
        }
    }
 
    public exitRuleref(ctx: RulerefContext): void {
        const token = ctx.RULE_REF();
        Iif (token) {
            this.addNewSymbol(RuleReferenceSymbol, ctx, token.text);
        }
    }
 
    public exitModeSpec(ctx: ModeSpecContext): void {
        this.addNewSymbol(LexerModeSymbol, ctx, ctx.identifier().text);
    }
 
    public exitDelegateGrammar(ctx: DelegateGrammarContext): void {
        const context = ctx.identifier()[ctx.identifier().length - 1];
        Iif (context) {
            const name = SourceContext.definitionForContext(context, false)!.text;
            this.addNewSymbol(ImportSymbol, context, name);
            this.imports.push(name);
        }
    }
 
    public enterOptionsSpec(ctx: OptionsSpecContext): void {
        this.pushNewSymbol(OptionsSymbol, ctx, "options");
    }
 
    public exitOptionsSpec(_ctx: OptionsSpecContext): void {
        this.popSymbol();
    }
 
    public exitOption(ctx: OptionContext): void {
        const option = ctx.identifier().text;
        const valueContext = ctx.tryGetRuleContext(0, OptionValueContext);
        Iif (valueContext && valueContext.childCount > 0) {
            const symbol = this.addNewSymbol(OptionSymbol, valueContext.getChild(0), option);
            symbol.value = valueContext.text;
            Iif (option === "tokenVocab") {
                this.imports.push(valueContext.text);
            }
        }
    }
 
    /**
     * Handles all types of native actions in various locations, instead of doing that in individual listener methods.
     *
     * @param ctx The parser context for the action block.
     */
    public exitActionBlock(ctx: ActionBlockContext): void {
        let run = ctx.parent;
 
        while (run) {
            switch (run.ruleIndex) {
                case ANTLRv4Parser.RULE_optionValue: {
                    // The grammar allows to assign a native action block to an option variable, but ANTLR4 itself
                    // doesn't accept that. So we ignore it here too.
                    return;
                }
 
                case ANTLRv4Parser.RULE_namedAction: {
                    // Global level named action, like @parser.
                    const localContext = run as NamedActionContext;
                    let prefix = "";
 
                    const actionScopeName = localContext.actionScopeName();
                    Iif (actionScopeName) {
                        prefix = actionScopeName.text + "::";
                    }
 
                    const symbol = this.addNewSymbol(GlobalNamedActionSymbol, ctx,
                        prefix + localContext.identifier().text);
                    this.symbolTable.defineNamedAction(symbol);
 
                    return;
                }
 
                case ANTLRv4Parser.RULE_exceptionHandler: {
                    this.addNewSymbol(ExceptionActionSymbol, ctx);
 
                    return;
                }
 
                case ANTLRv4Parser.RULE_finallyClause: {
                    this.addNewSymbol(FinallyActionSymbol, ctx);
 
                    return;
                }
 
                case ANTLRv4Parser.RULE_ruleAction: {
                    // Rule level named actions, like @init.
                    const symbol = this.addNewSymbol(LocalNamedActionSymbol, ctx, this.ruleName);
                    this.symbolTable.defineNamedAction(symbol);
 
                    return;
                }
 
                case ANTLRv4Parser.RULE_lexerElement: {
                    // Lexer inline action or predicate.
                    const localContext = run as LexerElementContext;
                    if (localContext.QUESTION()) {
                        const symbol = this.addNewSymbol(LexerPredicateSymbol, ctx);
                        this.symbolTable.definePredicate(symbol);
                    } else {
                        const symbol = this.addNewSymbol(LexerActionSymbol, ctx);
                        this.symbolTable.defineLexerAction(symbol);
                    }
 
                    return;
                }
 
                case ANTLRv4Parser.RULE_element: {
                    // Parser inline action or predicate.
                    const localContext = run as ElementContext;
                    if (localContext.QUESTION()) {
                        const symbol = this.addNewSymbol(ParserPredicateSymbol, ctx);
                        this.symbolTable.definePredicate(symbol);
                    } else {
                        const symbol = this.addNewSymbol(ParserActionSymbol, ctx);
                        this.symbolTable.defineParserAction(symbol);
                    }
 
                    return;
                }
 
                default: {
                    run = run.parent;
 
                    break;
                }
            }
        }
    }
 
    /**
     * Handles argument action code blocks.
     *
     * @param ctx The parser context for the action block.
     */
    public exitArgActionBlock(ctx: ArgActionBlockContext): void {
        Iif (this.symbolStack.length === 0) {
            return;
        }
 
        let run = ctx.parent;
        while (run && run !== this.symbolStack[0].context) {
            run = run.parent;
        }
 
        Iif (run) {
            switch (run.ruleIndex) {
                case ANTLRv4Parser.RULE_exceptionHandler: {
                    this.addNewSymbol(ArgumentSymbol, ctx, "exceptionHandler");
 
                    break;
                }
 
                case ANTLRv4Parser.RULE_finallyClause: {
                    this.addNewSymbol(ArgumentSymbol, ctx, "finallyClause");
 
                    break;
                }
 
                case ANTLRv4Parser.RULE_ruleReturns: {
                    this.addNewSymbol(ArgumentSymbol, ctx, "ruleReturns");
 
                    break;
                }
 
                case ANTLRv4Parser.RULE_localsSpec: {
                    this.addNewSymbol(ArgumentSymbol, ctx, "localsSpec");
 
                    break;
                }
 
                case ANTLRv4Parser.RULE_ruleref: {
                    this.addNewSymbol(ArgumentSymbol, ctx, "ruleRef");
 
                    break;
                }
 
                case ANTLRv4Parser.RULE_parserRuleSpec: {
                    this.addNewSymbol(ArgumentSymbol, ctx, "parserRuleSpec");
 
                    break;
                }
 
                default: {
                    break;
                }
            }
        }
    }
 
    public exitEbnfSuffix(ctx: EbnfSuffixContext): void {
        this.addNewSymbol(EbnfSuffixSymbol, ctx, ctx.text);
    }
 
    public enterLexerCommand(ctx: LexerCommandContext): void {
        this.pushNewSymbol(LexerCommandSymbol, ctx, ctx.lexerCommandName().text);
    }
 
    public exitLexerCommand(_ctx: LexerCommandContext): void {
        this.popSymbol();
    }
 
    public exitLabeledElement(ctx: LabeledElementContext): void {
        this.addNewSymbol(VariableSymbol, ctx, ctx.identifier().text);
    }
 
    public visitTerminal = (node: TerminalNode): void => {
        // Ignore individual terminals under certain circumstances.
        Iif (this.currentSymbol() instanceof LexerCommandSymbol) {
            return;
        }
 
        switch (node.symbol.type) {
            case ANTLRv4Lexer.COLON:
            case ANTLRv4Lexer.COLONCOLON:
            case ANTLRv4Lexer.COMMA:
            case ANTLRv4Lexer.SEMI:
            case ANTLRv4Lexer.LPAREN:
            case ANTLRv4Lexer.RPAREN:
            case ANTLRv4Lexer.LBRACE:
            case ANTLRv4Lexer.RBRACE:
            case ANTLRv4Lexer.RARROW:
            case ANTLRv4Lexer.LT:
            case ANTLRv4Lexer.GT:
            case ANTLRv4Lexer.ASSIGN:
            case ANTLRv4Lexer.QUESTION:
            case ANTLRv4Lexer.STAR:
            case ANTLRv4Lexer.PLUS_ASSIGN:
            case ANTLRv4Lexer.PLUS:
            case ANTLRv4Lexer.OR:
            case ANTLRv4Lexer.DOLLAR:
            case ANTLRv4Lexer.RANGE:
            case ANTLRv4Lexer.DOT:
            case ANTLRv4Lexer.AT:
            case ANTLRv4Lexer.POUND:
            case ANTLRv4Lexer.NOT: {
                this.addNewSymbol(OperatorSymbol, node, node.text);
                break;
            }
 
            default: {
                // Ignore the rest.
                break;
            }
        }
    };
 
    private currentSymbol<T extends BaseSymbol>(): T | undefined {
        Iif (this.symbolStack.length === 0) {
            return undefined;
        }
 
        return this.symbolStack[this.symbolStack.length - 1] as T;
    }
 
    /**
     * Adds a new symbol to the current symbol TOS.
     *
     * @param type The type of the symbol to add.
     * @param context The symbol's parse tree, to allow locating it.
     * @param args The actual arguments for the new symbol.
     *
     * @returns The new symbol.
     */
    private addNewSymbol<T extends BaseSymbol>(type: new (...args: any[]) => T, context: ParseTree,
        ...args: any[]): T {
        const symbol = this.symbolTable.addNewSymbolOfType(type, this.currentSymbol(), ...args);
        symbol.context = context;
 
        return symbol;
    }
 
    /**
     * Creates a new symbol and starts a new scope with it on the symbol stack.
     *
     * @param type The type of the symbol to add.
     * @param context The symbol's parse tree, to allow locating it.
     * @param args The actual arguments for the new symbol.
     *
     * @returns The new scoped symbol.
     */
    private pushNewSymbol<T extends BaseSymbol, Args extends unknown[]>(type: SymbolConstructor<T, Args>,
        context: ParseTree, ...args: Args): BaseSymbol {
        const symbol = this.symbolTable.addNewSymbolOfType<T, Args>(type, this.currentSymbol(), ...args);
        symbol.context = context;
        this.symbolStack.push(symbol);
 
        return symbol;
    }
 
    private popSymbol(): BaseSymbol | undefined {
        return this.symbolStack.pop();
    }
}