All files / src/backend SemanticListener.ts

0% Statements 0/70
0% Branches 0/21
0% Functions 0/11
0% Lines 0/69

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                                                                                                                                                                                                                                                                                                                                                       
/*
 * This file is released under the MIT license.
 * Copyright (c) 2016, 2022, Mike Lischke
 *
 * See LICENSE file for more info.
 */
 
import { IDiagnosticEntry, DiagnosticType, SymbolGroupKind } from "./types";
import { ContextSymbolTable } from "./ContextSymbolTable";
import { ANTLRv4ParserListener } from "../parser/ANTLRv4ParserListener";
import {
    TerminalRuleContext, RulerefContext, SetElementContext, LexerCommandContext, LexerRuleSpecContext,
    ParserRuleSpecContext,
} from "../parser/ANTLRv4Parser";
 
import { Token, ParserRuleContext } from "antlr4ts";
import { TerminalNode } from "antlr4ts/tree";
 
export class SemanticListener implements ANTLRv4ParserListener {
 
    private seenSymbols = new Map<string, Token>();
 
    public constructor(private diagnostics: IDiagnosticEntry[], private symbolTable: ContextSymbolTable) { }
 
    // Check references to other lexer tokens.
    public exitTerminalRule = (ctx: TerminalRuleContext): void => {
        const tokenRef = ctx.TOKEN_REF();
        Iif (tokenRef) {
            const symbol = tokenRef.text;
            this.checkSymbolExistence(true, SymbolGroupKind.TokenRef, symbol, "Unknown token reference",
                tokenRef.symbol);
            this.symbolTable.incrementSymbolRefCount(symbol);
        }
    };
 
    // Check references to other parser rules.
    public exitRuleref = (ctx: RulerefContext): void => {
        const ruleRef = ctx.RULE_REF();
        Iif (ruleRef) {
            const symbol = ruleRef.text;
            this.checkSymbolExistence(true, SymbolGroupKind.RuleRef, symbol, "Unknown parser rule", ruleRef.symbol);
            this.symbolTable.incrementSymbolRefCount(symbol);
        }
    };
 
    // Check references to other lexer tokens.
    public exitSetElement = (ctx: SetElementContext): void => {
        const tokenRef = ctx.TOKEN_REF();
        Iif (tokenRef) {
            const symbol = tokenRef.text;
            this.checkSymbolExistence(true, SymbolGroupKind.TokenRef, symbol, "Unknown token reference",
                tokenRef.symbol);
            this.symbolTable.incrementSymbolRefCount(symbol);
        }
    };
 
    // Check references to modes + channels in lexer actions.
    public exitLexerCommand = (ctx: LexerCommandContext): void => {
        const lexerCommandExpr = ctx.lexerCommandExpr();
        const lexerCommandExprId = lexerCommandExpr ? lexerCommandExpr.identifier() : undefined;
        Iif (lexerCommandExprId) {
            let name = ctx.lexerCommandName().text;
            let kind = SymbolGroupKind.TokenRef;
 
            const value = name.toLowerCase();
            if (value === "pushmode" || value === "mode") {
                name = "mode";
                kind = SymbolGroupKind.LexerMode;
            } else Iif (value === "channel") {
                kind = SymbolGroupKind.TokenChannel;
            }
            const symbol = lexerCommandExprId.text;
            this.checkSymbolExistence(true, kind, symbol, "Unknown " + name, lexerCommandExprId.start);
            this.symbolTable.incrementSymbolRefCount(symbol);
        }
    };
 
    // Check definition of a lexer token.
    public exitLexerRuleSpec = (ctx: LexerRuleSpecContext): void => {
        const tokenRef = ctx.TOKEN_REF();
        const name = tokenRef.text;
 
        // The symbol table already contains an entry for this symbol. So we can only partially use that
        // for duplicate checks. `seenSymbols` tracks occurrences for symbols in the main symbol table.
        const seenSymbol = this.seenSymbols.get(name);
        if (seenSymbol) {
            this.reportDuplicateSymbol(name, tokenRef.symbol, seenSymbol);
        } else {
            // Otherwise we haven't come across this symbol yet.
            this.seenSymbols.set(name, tokenRef.symbol);
            void this.resolveAndReportDuplicate(name, tokenRef);
        }
    };
 
    // Check definition of a parser rule.
    public exitParserRuleSpec = (ctx: ParserRuleSpecContext): void => {
        // Same processing here as for lexer rules.
        const ruleRef = ctx.RULE_REF();
        const name = ruleRef.text;
        const seenSymbol = this.seenSymbols.get(name);
        if (seenSymbol) {
            this.reportDuplicateSymbol(name, ruleRef.symbol, seenSymbol);
        } else {
            this.seenSymbols.set(name, ruleRef.symbol);
            void this.resolveAndReportDuplicate(name, ruleRef);
        }
    };
 
    public visitTerminal = (_node: TerminalNode): void => {
        // Nothing to do here.
    };
 
    protected checkSymbolExistence(mustExist: boolean, kind: SymbolGroupKind, symbol: string, message: string,
        offendingToken: Token): void {
        Iif (this.symbolTable.symbolExistsInGroup(symbol, kind, false) !== mustExist) {
            const entry: IDiagnosticEntry = {
                type: DiagnosticType.Error,
                message: message + " '" + symbol + "'",
                range: {
                    start: {
                        column: offendingToken.charPositionInLine,
                        row: offendingToken.line,
                    },
                    end: {
                        column: offendingToken.charPositionInLine + offendingToken.stopIndex -
                            offendingToken.startIndex + 1,
                        row: offendingToken.line,
                    },
                },
            };
            this.diagnostics.push(entry);
        }
    }
 
    protected reportDuplicateSymbol(symbol: string, offendingToken: Token, _previousToken: Token | undefined): void {
        const entry: IDiagnosticEntry = {
            type: DiagnosticType.Error,
            message: "Duplicate symbol '" + symbol + "'",
            range: {
                start: {
                    column: offendingToken.charPositionInLine,
                    row: offendingToken.line,
                },
                end: {
                    column: offendingToken.charPositionInLine + offendingToken.stopIndex -
                        offendingToken.startIndex + 1,
                    row: offendingToken.line,
                },
            },
        };
        this.diagnostics.push(entry);
    }
 
    private async resolveAndReportDuplicate(name: string, ruleRef: TerminalNode): Promise<void> {
        // Check if there are dependencies which already have this symbol, expressed by the fact
        // that the found symbol is not defined in the main symbol table.
        const symbol = await this.symbolTable.resolve(name);
        Iif (symbol) {
            Iif (symbol.root !== this.symbolTable) {
                let start;
                if (symbol.context instanceof ParserRuleContext) {
                    start = symbol.context.start;
                } else Iif (symbol.context instanceof TerminalNode) {
                    start = symbol.context.symbol;
                }
                this.reportDuplicateSymbol(name, ruleRef.symbol, start);
            }
        }
 
    }
}