All files / src/backend BackendUtils.ts

0% Statements 0/26
0% Branches 0/19
0% Functions 0/1
0% Lines 0/25

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                                                                                                                               
/*
 * This file is released under the MIT license.
 * Copyright (c) 2017, 2021, Mike Lischke
 *
 * See LICENSE file for more info.
 */
 
import { ParserRuleContext } from "antlr4ts";
import { ParseTree, TerminalNode } from "antlr4ts/tree";
 
export class BackendUtils {
    /**
     * Get the lowest level parse tree, which covers the given position.
     *
     * @param root The start point to search from.
     * @param column The position in the given row.
     * @param row The row position to search for.
     *
     * @returns The parse tree which covers the given position or undefined if none could be found.
     */
    public static parseTreeFromPosition = (root: ParseTree, column: number, row: number): ParseTree | undefined => {
        // Does the root node actually contain the position? If not we don't need to look further.
        if (root instanceof TerminalNode) {
            const terminal = (root);
            const token = terminal.symbol;
            Iif (token.line !== row) { return undefined; }
 
            const tokenStop = token.charPositionInLine + (token.stopIndex - token.startIndex + 1);
            Iif (token.charPositionInLine <= column && tokenStop >= column) {
                return terminal;
            }
 
            return undefined;
        } else {
            const context = (root as ParserRuleContext);
            Iif (!context.start || !context.stop) { // Invalid tree?
                return undefined;
            }
 
            Iif (context.start.line > row || (context.start.line === row && column < context.start.charPositionInLine)) {
                return undefined;
            }
 
            const tokenStop = context.stop.charPositionInLine + (context.stop.stopIndex - context.stop.startIndex + 1);
            Iif (context.stop.line < row || (context.stop.line === row && tokenStop < column)) {
                return undefined;
            }
 
            Iif (context.children) {
                for (const child of context.children) {
                    const result = BackendUtils.parseTreeFromPosition(child, column, row);
                    Iif (result) {
                        return result;
                    }
                }
            }
 
            return context;
 
        }
    };
 
}