All files SymbolTable.ts

68.85% Statements 241/350
86.2% Branches 25/29
60% Functions 9/15
68.85% Lines 241/350

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 3511x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 10x 1x 1x 96338x 96338x 96338x 96338x 96338x 1x 1x       1x 1x 3x 5x 3x 3x 1x 1x         1x 1x 76914x 76914x 76914x 76914x 76914x 22615x 76914x 54299x 54299x 76913x 76913x 76913x 1x 1x 4x 4x 4x 4x 4x 5x 5x 3x 3x 5x 5x 5x 4x 4x 4x 1x 1x                                 1x 1x 17x 17x 17x 17x 17x 10x 10x 10x 17x 17x 17x 10x 17x 17x 17x 17x 17x 1x 1x                     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 21x 1x 1x 20x 21x 7x 20x 20x 3x 3x 20x 4x 17x 17x 1x 1x 1x 1x 1x 1x 1x 1x 1x                           1x 1x                                                                                         1x 1x 5x 5x               5x 5x 5x 1x 1x                         1x  
/*
 * This file is released under the MIT license.
 * Copyright (c) 2017, 2021, Mike Lischke
 *
 * See LICENSE file for more info.
 */
 
import { SymbolTableOptions, SymbolConstructor } from "./types";
 
import { BaseSymbol } from "./BaseSymbol";
import { ParseTree } from "antlr4ts/tree/ParseTree";
import { IScopedSymbol, ScopedSymbol } from "./ScopedSymbol";
import { NamespaceSymbol } from "./NamespaceSymbol";
 
export interface ISymbolTable extends IScopedSymbol {
    options: SymbolTableOptions;
 
    /**
     * @returns instance information, mostly relevant for unit testing.
     */
    info: { dependencyCount: number, symbolCount: number; };
 
    clear(): void;
    addDependencies(...tables: SymbolTable[]): void;
    removeDependency(table: SymbolTable): void;
    addNewSymbolOfType<T extends BaseSymbol>(t: SymbolConstructor<T>,
        parent: ScopedSymbol | undefined, ...args: unknown[]): T;
 
    /**
     * Asynchronously adds a new namespace to the symbol table or the given parent. The path parameter specifies a
     * single namespace name or a chain of namespaces (which can be e.g. "outer.intermittent.inner.final").
     * If any of the parent namespaces is missing they are created implicitly. The final part must not exist however
     * or you'll get a duplicate symbol error.
     *
     * @param parent The parent to add the namespace to.
     * @param path The namespace path.
     * @param delimiter The delimiter used in the path.
     *
     * @returns The new symbol.
     */
    addNewNamespaceFromPath(parent: ScopedSymbol | undefined, path: string,
        delimiter?: string): Promise<NamespaceSymbol>;
 
    /**
     * Synchronously adds a new namespace to the symbol table or the given parent. The path parameter specifies a
     * single namespace name or a chain of namespaces (which can be e.g. "outer.intermittent.inner.final").
     * If any of the parent namespaces is missing they are created implicitly. The final part must not exist however
     * or you'll get a duplicate symbol error.
     *
     * @param parent The parent to add the namespace to.
     * @param path The namespace path.
     * @param delimiter The delimiter used in the path.
     *
     * @returns The new symbol.
     */
    addNewNamespaceFromPathSync(parent: ScopedSymbol | undefined, path: string,
        delimiter?: string): NamespaceSymbol;
 
    /**
     * Asynchronously returns all symbols from this scope (and optionally those from dependencies) of a specific type.
     *
     * @param t The type of the symbols to return.
     * @param localOnly If true do not search dependencies.
     *
     * @returns A promise which resolves when all symbols are collected.
     */
    getAllSymbols<T extends BaseSymbol>(t: SymbolConstructor<T>, localOnly: boolean): Promise<T[]>;
 
    /**
     * Synchronously returns all symbols from this scope (and optionally those from dependencies) of a specific type.
     *
     * @param t The type of the symbols to return.
     * @param localOnly If true do not search dependencies.
     *
     * @returns A list with all symbols.
     */
    getAllSymbolsSync<T extends BaseSymbol>(t: SymbolConstructor<T>, localOnly: boolean): T[];
 
    /**
     * Asynchronously looks for a symbol which is connected with a given parse tree context.
     *
     * @param context The context to search for.
     *
     * @returns A promise resolving to the found symbol or undefined.
     */
    symbolWithContext(context: ParseTree): Promise<BaseSymbol | undefined>;
 
    /**
     * Synchronously looks for a symbol which is connected with a given parse tree context.
     *
     * @param context The context to search for.
     *
     * @returns The found symbol or undefined.
     */
    symbolWithContextSync(context: ParseTree): BaseSymbol | undefined;
 
    /**
     * Asynchronously resolves a name to a symbol.
     *
     * @param name The name of the symbol to find.
     * @param localOnly A flag indicating if only this symbol table should be used or also its dependencies.
     *
     * @returns A promise resolving to the found symbol or undefined.
     */
    resolve(name: string, localOnly: boolean): Promise<BaseSymbol | undefined>;
 
    /**
     * Synchronously resolves a name to a symbol.
     *
     * @param name The name of the symbol to find.
     * @param localOnly A flag indicating if only this symbol table should be used or also its dependencies.
     *
     * @returns The found symbol or undefined.
     */
    resolveSync(name: string, localOnly: boolean): BaseSymbol | undefined;
}
 
/** The main class managing all the symbols for a top level entity like a file, library or similar. */
export class SymbolTable extends ScopedSymbol implements ISymbolTable {
    /**  Other symbol information available to this instance. */
    protected dependencies: Set<SymbolTable> = new Set();
 
    public constructor(name: string, public readonly options: SymbolTableOptions) {
        super(name);
    }
 
    public get info(): { dependencyCount: number, symbolCount: number; } {
        return {
            dependencyCount: this.dependencies.size,
            symbolCount: this.children.length,
        };
    }
 
    public override clear(): void {
        super.clear();
        this.dependencies.clear();
    }
 
    public addDependencies(...tables: SymbolTable[]): void {
        tables.forEach((value, key) => {
            this.dependencies.add(value);
        });
    }
 
    public removeDependency(table: SymbolTable): void {
        if (this.dependencies.has(table)) {
            this.dependencies.delete(table);
        }
    }
 
    public addNewSymbolOfType<T extends BaseSymbol>(t: SymbolConstructor<T>,
        parent: ScopedSymbol | undefined, ...args: unknown[]): T {
 
        // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
        const result = new t(...args);
        if (!parent || parent === this) {
            this.addSymbol(result);
        } else {
            parent.addSymbol(result);
        }
 
        return result;
    }
 
    public async addNewNamespaceFromPath(parent: ScopedSymbol | undefined, path: string,
        delimiter = "."): Promise<NamespaceSymbol> {
        const parts = path.split(delimiter);
        let i = 0;
        let currentParent = (parent === undefined) ? this : parent;
        while (i < parts.length - 1) {
            let namespace = await currentParent.resolve(parts[i], true) as NamespaceSymbol;
            if (namespace === undefined) {
                namespace = this.addNewSymbolOfType(NamespaceSymbol, currentParent, parts[i]);
            }
            currentParent = namespace;
            ++i;
        }
 
        return this.addNewSymbolOfType(NamespaceSymbol, currentParent, parts[parts.length - 1]);
    }
 
    public addNewNamespaceFromPathSync(parent: ScopedSymbol | undefined, path: string,
        delimiter = "."): NamespaceSymbol {
        const parts = path.split(delimiter);
        let i = 0;
        let currentParent = (parent === undefined) ? this : parent;

        while (i < parts.length - 1) {
            let namespace = currentParent.resolveSync(parts[i], true) as NamespaceSymbol;
            if (namespace === undefined) {
                namespace = this.addNewSymbolOfType(NamespaceSymbol, currentParent, parts[i]);
            }
            currentParent = namespace;
            ++i;
        }

        return this.addNewSymbolOfType(NamespaceSymbol, currentParent, parts[parts.length - 1]);
    }
 
    public override async getAllSymbols<T extends BaseSymbol>(t: SymbolConstructor<T>,
        localOnly = false): Promise<T[]> {
        const result: T[] = await super.getAllSymbols(t, localOnly);
 
        if (!localOnly) {
            const dependencyResults = await Promise.all([...this.dependencies].map((dependency) => {
                return (
                    dependency.getAllSymbols(t, localOnly)
                );
            }));
 
            dependencyResults.forEach((value) => {
                result.push(...value);
            });
        }
 
        return result;
    }
 
    public override getAllSymbolsSync<T extends BaseSymbol>(t: SymbolConstructor<T>, localOnly = false): T[] {
        const result: T[] = super.getAllSymbolsSync(t, localOnly);

        if (!localOnly) {
            this.dependencies.forEach((dependency) => {
                result.push(...dependency.getAllSymbolsSync(t, localOnly));
            });
        }

        return result;
    }
 
    public async symbolWithContext(context: ParseTree): Promise<BaseSymbol | undefined> {
        /**
         * Local function to find a symbol recursively.
         *
         * @param symbol The symbol to search through.
         *
         * @returns The symbol with the given context, if found.
         */
        const findRecursive = (symbol: BaseSymbol): BaseSymbol | undefined => {
            if (symbol.context === context) {
                return symbol;
            }
 
            if (symbol instanceof ScopedSymbol) {
                for (const child of symbol.children) {
                    const result = findRecursive(child);
                    if (result) {
                        return result;
                    }
                }
            }
 
            return undefined;
        };
 
        let symbols = await this.getAllSymbols(BaseSymbol);
        for (const symbol of symbols) {
            const result = findRecursive(symbol);
            if (result) {
                return result;
            }
        }

        for (const dependency of this.dependencies) {
            symbols = await dependency.getAllSymbols(BaseSymbol);
            for (const symbol of symbols) {
                const result = findRecursive(symbol);
                if (result) {
                    return result;
                }
            }
        }

        return undefined;
    }
 
    public symbolWithContextSync(context: ParseTree): BaseSymbol | undefined {
        /**
         * Local function to find a symbol recursively.
         *
         * @param symbol The symbol to search through.
         *
         * @returns The symbol with the given context, if found.
         */
        const findRecursive = (symbol: BaseSymbol): BaseSymbol | undefined => {
            if (symbol.context === context) {
                return symbol;
            }

            if (symbol instanceof ScopedSymbol) {
                for (const child of symbol.children) {
                    const result = findRecursive(child);
                    if (result) {
                        return result;
                    }
                }
            }

            return undefined;
        };

        let symbols = this.getAllSymbolsSync(BaseSymbol);
        for (const symbol of symbols) {
            const result = findRecursive(symbol);
            if (result) {
                return result;
            }
        }

        for (const dependency of this.dependencies) {
            symbols = dependency.getAllSymbolsSync(BaseSymbol);
            for (const symbol of symbols) {
                const result = findRecursive(symbol);
                if (result) {
                    return result;
                }
            }
        }

        return undefined;
    }
 
    public override async resolve(name: string, localOnly = false): Promise<BaseSymbol | undefined> {
        let result = await super.resolve(name, localOnly);
        if (!result && !localOnly) {
            for (const dependency of this.dependencies) {
                result = await dependency.resolve(name, false);
                if (result) {
                    return result;
                }
            }
        }
 
        return result;
    }
 
    public override resolveSync(name: string, localOnly = false): BaseSymbol | undefined {
        let result = super.resolveSync(name, localOnly);
        if (!result && !localOnly) {
            for (const dependency of this.dependencies) {
                result = dependency.resolveSync(name, false);
                if (result) {
                    return result;
                }
            }
        }

        return result;
    }
}