All files / src/backend SentenceGenerator.ts

0% Statements 0/238
0% Branches 0/119
0% Functions 0/16
0% Lines 0/235

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 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
/*
 * This file is released under the MIT license.
 * Copyright (c) 2016, 2023, Mike Lischke
 *
 * See LICENSE file for more info.
 */
 
import * as vm from "vm";
import * as fs from "fs";
 
import {
    ATNState, ATNStateType, BlockStartState, PlusBlockStartState, StarLoopEntryState, TransitionType,
    RuleTransition, StarBlockStartState, RuleStartState, NotSetTransition, DecisionState, PredicateTransition,
} from "antlr4ts/atn";
 
import { ISentenceGenerationOptions, IRuleMappings, PredicateFunction } from "./types";
import { IntervalSet } from "antlr4ts/misc";
 
import { printableUnicodePoints, fullUnicodeSet } from "./Unicode";
import { IInterpreterData } from "./InterpreterDataReader";
import { LexerPredicateSymbol, ParserPredicateSymbol } from "./ContextSymbolTable";
import { SourceContext } from "./SourceContext";
 
/**
 * This class generates a number of strings, each valid input for a given ATN.
 */
export class SentenceGenerator {
    private static printableUnicode: IntervalSet;
 
    // Allow evaluating predicates.
    public runPredicate?: PredicateFunction;
 
    private lexerPredicates: LexerPredicateSymbol[];
    private parserPredicates: ParserPredicateSymbol[];
 
    // Convergence data for recursive rule invocations. We count here the invocation of each alt
    // of a decision state.
    private convergenceFactor: number;
    private lexerDecisionCounts: Map<number, number[]>;
    private parserDecisionCounts: Map<number, number[]>;
 
    private minParserIterations: number;
    private maxParserIterations: number;
    private minLexerIterations: number;
    private maxLexerIterations: number;
    private maxRecursions: number;
    private maxRecursionLabel: string;
    private ruleInvocations = new Map<string, number>();
 
    private ruleMappings?: IRuleMappings;
 
    // To limit recursions we need to track through which rules we are walking currently.
    private parserStack: number[] = [];
 
    /**
     * @param context The context for the grammar file.
     * @param lexerData The generated lexer data for this grammar.
     * @param parserData The generated parser data for this grammar.
     * @param actionFile The name of a file that allows executing predicates/actions.
     */
    public constructor(
        context: SourceContext,
        private lexerData: IInterpreterData,
        private parserData: IInterpreterData | undefined,
        actionFile: string | undefined) {
 
        // Get the symbols for all predicates (to enable predicate evaluation).
        this.lexerPredicates = context.symbolTable.getNestedSymbolsOfTypeSync(LexerPredicateSymbol);
        this.parserPredicates = context.symbolTable.getNestedSymbolsOfTypeSync(ParserPredicateSymbol);
 
        // Need to disable a number of linter checks in order to allow importing the action file.
        Iif (actionFile) {
            const code = fs.readFileSync(actionFile, { encoding: "utf-8" }) + `
            const runPredicate = (predicate) => eval(predicate);
            runPredicate;
            `;
 
            // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
            this.runPredicate = vm.runInNewContext(code) as PredicateFunction;
        }
    }
 
    /**
     * Generates a single sentence for the given rule.
     *
     * @param options A number of settings that control the generation process.
     * @param start The ATN start state of the rule for which to generate the sentence.
     *
     * @returns A string that can successfully be parsed by the rule.
     */
    public generate(options: ISentenceGenerationOptions, start: RuleStartState): string {
 
        this.convergenceFactor = options.convergenceFactor ?? 0.25;
 
        this.minParserIterations = options.minParserIterations ?? 0;
        if (this.minParserIterations < 0) {
            this.minParserIterations = 0;
        } else {
            this.minParserIterations = Math.floor(this.minParserIterations);
        }
 
        this.maxParserIterations = options.maxParserIterations ?? this.minParserIterations + 1;
        if (this.maxParserIterations < this.minParserIterations) {
            this.maxParserIterations = this.minParserIterations + 1;
        } else {
            this.maxParserIterations = Math.ceil(this.maxParserIterations);
        }
 
        this.minLexerIterations = options.minLexerIterations ?? 0;
        if (this.minLexerIterations < 0) {
            this.minLexerIterations = 0;
        } else {
            this.minLexerIterations = Math.floor(this.minLexerIterations);
        }
 
        this.maxLexerIterations = options.maxLexerIterations ?? this.minLexerIterations + 10;
        if (this.maxLexerIterations < this.minLexerIterations) {
            this.maxLexerIterations = this.minLexerIterations + 10;
        } else {
            this.maxLexerIterations = Math.ceil(this.maxLexerIterations);
        }
 
        this.maxRecursions = (!options.maxRecursions || options.maxRecursions < 1) ? 3 : options.maxRecursions;
        this.maxRecursionLabel = options.maxRecursionLabel ?? "⨱";
 
        this.ruleInvocations.clear();
        this.ruleMappings = options.ruleMappings;
 
        this.lexerDecisionCounts = new Map<number, number[]>();
        this.parserDecisionCounts = new Map<number, number[]>();
 
        this.parserStack.length = 0;
 
        const [result] = this.generateFromATNSequence(start, start.stopState, start.atn === this.lexerData.atn);
 
        return result;
    }
 
    public sempred(ruleIndex: number, predIndex: number, inLexer: boolean): boolean {
        Iif (this.runPredicate) {
            let predicate = "";
            if (inLexer) {
                Iif (predIndex < this.lexerPredicates.length) {
                    predicate = this.lexerPredicates[predIndex].context!.text;
                }
            } else {
                Iif (predIndex < this.parserPredicates.length) {
                    predicate = this.parserPredicates[predIndex].context!.text;
                }
            }
 
            Iif (predicate.length > 2) {
                predicate = predicate.substring(1, predicate.length - 1); // 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;
    }
 
    /**
     * @param inLexer A flag to tell where to lookup the symbol name.
     * @param index The rule index to convert.
     *
     * @returns The name of the rule with the given index.
     */
    private getRuleName(inLexer: boolean, index: number): string | undefined {
        Iif (inLexer) {
            return this.lexerData.ruleNames[index];
        }
 
        Iif (this.parserData) {
            return this.parserData.ruleNames[index];
        }
 
        return undefined;
    }
 
    /**
     * Records the invocation of the given rule.
     *
     * @param name The name of the rule.
     *
     * @returns True if that rule's invocation count is less than the maximum recursion count.
     */
    private invokeRule(name: string): boolean {
        const count = this.ruleInvocations.get(name);
        Iif (count) {
            Iif (count < this.maxRecursions) {
                this.ruleInvocations.set(name, count + 1);
 
                return true;
            }
 
            return false;
        }
 
        this.ruleInvocations.set(name, 1);
 
        return true;
    }
 
    /**
     * Remove one invocation step for the given rule. If the count is zero after that, then the rule is removed
     * from the invocation list altogether.
     *
     * @param name The name of the rule.
     */
    private leaveRule(name: string) {
        let count = this.ruleInvocations.get(name);
        Iif (count) {
            --count;
            if (count === 0) {
                this.ruleInvocations.delete(name);
            } else {
                this.ruleInvocations.set(name, count);
            }
        }
    }
 
    /**
     * Processes a single sequence of ATN states (a rule or a single alt in a block).
     *
     * @param start The node from where to start walking.
     * @param stop The node that ends the sequence to walk over.
     * @param addSpace If true a space char is added between each ATN node label.
     *
     * @returns The generated string and a flag that indicates if the process succeeded.
     */
    private generateFromATNSequence(start: ATNState, stop: ATNState, addSpace: boolean): [string, boolean] {
        const inLexer = start.atn === this.lexerData.atn;
        const isRule = start.stateType === ATNStateType.RULE_START;
 
        let ruleName: string | undefined;
        Iif (isRule) {
            // Check if there's a predefined result for the given rule.
            ruleName = this.getRuleName(inLexer, start.ruleIndex);
            Iif (!ruleName) {
                return ["", false];
            }
 
            const mappingValue = this.ruleMappings?.[ruleName];
            Iif (mappingValue) {
                let mapping: string | undefined;
 
                if (Array.isArray(mappingValue)) {
                    if (mappingValue.length === 1) {
                        mapping = mappingValue[0];
                    } else Iif (mappingValue.length > 0) {
                        const randomIndex = Math.floor(Math.random() * mappingValue.length);
                        const randomElement = mappingValue[randomIndex];
 
                        mapping = randomElement;
                    }
                } else {
                    mapping = mappingValue;
                }
 
                Iif (mapping) {
                    return [addSpace ? mapping + " " : mapping, false];
                }
            }
 
            Iif (!this.invokeRule(ruleName)) {
                return [addSpace ? this.maxRecursionLabel + " " : this.maxRecursionLabel, false];
            }
        }
 
 
        let result = "";
        let blockedByPredicate = false;
 
        let run = start;
        while (run !== stop) {
            switch (run.stateType) {
                case ATNStateType.BLOCK_START: {
                    result += this.generateFromDecisionState(run as BlockStartState, !inLexer);
                    run = (run as BlockStartState).endState;
 
                    break;
                }
 
                case ATNStateType.PLUS_BLOCK_START: {
                    const loopBack = (run as PlusBlockStartState).loopBackState;
                    const count = this.getRandomLoopCount(inLexer, true);
                    for (let i = 0; i < count; ++i) {
                        result += this.generateFromDecisionState(run as PlusBlockStartState, !inLexer);
                    }
 
                    run = loopBack.transition(1).target;
 
                    break;
                }
 
                case ATNStateType.STAR_LOOP_ENTRY: {
                    const slEntry = run as StarLoopEntryState;
                    const blockStart = this.blockStart(slEntry);
                    Iif (blockStart) {
                        const count = this.getRandomLoopCount(inLexer, false);
                        for (let i = 0; i < count; ++i) {
                            result += this.generateFromDecisionState(blockStart, !inLexer);
                        }
                    }
                    run = this.loopEnd(slEntry) || stop;
 
                    break;
                }
 
                default: {
                    const transition = run.transition(0);
                    switch (transition.serializationType) {
                        case TransitionType.RULE: { // Transition into a sub rule.
                            run = (transition as RuleTransition).followState;
                            const ruleStart = transition.target as RuleStartState;
                            const [text] = this.generateFromATNSequence(ruleStart, ruleStart.stopState, !inLexer);
                            result += text;
 
                            break;
                        }
 
                        case TransitionType.WILDCARD: {
                            let text = "";
                            if (inLexer) {
                                // Any char from the entire Unicode range. The generator takes care to pick only
                                // valid characters.
                                [text] = this.getRandomCharacterFromInterval(fullUnicodeSet);
                            } else {
                                // Pick a random lexer rule.
                                const ruleIndex = Math.floor(Math.random() *
                                    this.lexerData.atn.ruleToStartState.length);
                                const state: RuleStartState = this.lexerData.atn.ruleToStartState[ruleIndex];
                                [text] = this.generateFromATNSequence(state, state.stopState, !inLexer);
 
                            }
                            result += text;
                            run = transition.target;
 
                            break;
                        }
 
                        case TransitionType.PREDICATE: {
                            // Evaluate the predicate if possible (or assume it succeeds if not).
                            // If evaluation returns false then return immediately with a flag to tell the caller
                            // to use a different decision (if possible).
                            const predicateTransition = transition as PredicateTransition;
                            blockedByPredicate = !this.sempred(run.ruleIndex, predicateTransition.predIndex, inLexer);
                            run = blockedByPredicate ? stop : transition.target;
                            break;
                        }
 
                        default: {
                            // Any other basic transition. See if there is a label we can use.
                            if (inLexer) {
                                Iif (transition.label && transition.label.minElement > -1) {
                                    let label = transition.label;
                                    Iif (transition instanceof NotSetTransition) {
                                        label = label.complement(IntervalSet.COMPLETE_CHAR_SET);
                                    }
                                    result += this.getRandomCharacterFromInterval(label);
                                }
                            } else {
                                Iif (transition.label && transition.label.maxElement > -1) {
                                    const randomIndex = Math.floor(Math.random() * transition.label.size);
                                    const token = this.getIntervalElement(transition.label, randomIndex);
                                    const tokenIndex = this.lexerData.atn.ruleToTokenType.indexOf(token);
                                    if (tokenIndex === -1) {
                                        // Found a virtual token. Either use its mapping as value or
                                        // its name for the output.
                                        const tokenName = this.lexerData.vocabulary.getSymbolicName(token);
                                        if (tokenName) {
                                            const mappingValue = this.ruleMappings?.[tokenName];
                                            let mapping: string | undefined;
 
                                            Iif (mappingValue) {
                                                if (Array.isArray(mappingValue)) {
                                                    if (mappingValue.length === 1) {
                                                        mapping = mappingValue[0];
                                                    } else Iif (mappingValue.length > 0) {
                                                        const randomIndex = Math.floor(Math.random() *
                                                            mappingValue.length);
                                                        mapping = mappingValue[randomIndex];
                                                    }
                                                } else Iif (mappingValue) {
                                                    mapping = mappingValue;
                                                }
                                            }
 
                                            if (mapping) {
                                                result += addSpace ? mapping + " " : mapping;
                                            } else {
                                                result += addSpace ? tokenName + " " : tokenName;
                                            }
                                        } else {
                                            result += `[Cannot generate value for virtual token ${token}]`;
                                        }
                                    } else {
                                        const state = this.lexerData.atn.ruleToStartState[tokenIndex];
                                        const [text] = this.generateFromATNSequence(state, state.stopState, !inLexer);
                                        result += text;
                                    }
                                }
                            }
                            run = transition.target;
 
                            break;
                        }
                    }
                }
            }
        }
 
        Iif (isRule) {
            this.leaveRule(ruleName!);
            Iif (addSpace) {
                return [result + " ", blockedByPredicate];
            }
        }
 
        return [result, blockedByPredicate];
    }
 
    /**
     * Picks a random entry from all possible alternatives. Each alt gets a specific weight depending on its
     * previous invocations (the higher the invocation count the smaller the weight).
     *
     * If a decision is blocked by a failing predicate then an attempt is made to select another random decision.
     * If none is left for consideration then an empty string is returned.
     *
     * @param state The state from which to select on decision.
     * @param addSpace If true a space char is added between each ATN node label.
     *
     * @returns The generated string.
     */
    private generateFromDecisionState(state: DecisionState, addSpace: boolean): string {
        let result = "";
        let blocked = false; // Current decision blocked by a predicate?
 
        do {
            const decision = this.getRandomDecision(state);
            Iif (decision < 0) {
                return "";
            }
 
            // The alt counts are initialized in the call above if they don't exist yet.
            const decisionCounts = state.atn === this.lexerData.atn
                ? this.lexerDecisionCounts
                : this.parserDecisionCounts;
            const altCounts = decisionCounts.get(state.decision)!;
            ++altCounts[decision];
 
            let endState;
            switch (state.stateType) {
                case ATNStateType.STAR_BLOCK_START:
                case ATNStateType.BLOCK_START: {
                    endState = (state as BlockStartState).endState;
                    break;
                }
 
                case ATNStateType.PLUS_BLOCK_START: {
                    endState = (state as PlusBlockStartState).loopBackState;
                    break;
                }
 
                default: {
                    throw new Error("Unhandled state type in sentence generator");
                }
            }
 
            [result, blocked] = this.generateFromATNSequence(state.transition(decision).target, endState, addSpace);
            Iif (blocked) {
                altCounts[decision] = 1e6; // Set a large execution count to effectively disable this decision.
            }
        } while (blocked);
 
        return result;
    }
 
    /**
     * Determines a random decision (one of the outgoing transitions) depending on the already taken
     * transitions. If the decision state has an exit state (for ?, * and + operators) this exit state
     * always has a weight of 1, so it will always serve as exit point if other weights become to low.
     *
     * @param state The decision state to examine.
     *
     * @returns A random decision index.
     */
    private getRandomDecision(state: DecisionState): number {
        const decisionCounts = state.atn === this.lexerData.atn ? this.lexerDecisionCounts : this.parserDecisionCounts;
 
        const weights = new Array<number>(state.numberOfTransitions).fill(1);
        let altCounts = decisionCounts.get(state.decision);
        if (!altCounts) {
            altCounts = new Array<number>(state.numberOfTransitions).fill(0);
            decisionCounts.set(state.decision, altCounts);
        } else {
            for (let i = 0; i < altCounts.length; ++i) {
                weights[i] = Math.pow(this.convergenceFactor, altCounts[i]);
            }
        }
 
        const sum = weights.reduce((accumulated, current) => {
            return accumulated + current;
        });
 
        let randomValue = Math.random() * sum;
        let randomIndex = 0;
        while (randomIndex < altCounts.length) {
            randomValue -= weights[randomIndex];
            Iif (randomValue < 0) {
                return randomIndex;
            }
            ++randomIndex;
        }
 
        return -1;
    }
 
    /**
     * Goes through all transitions of the given state to find a loop end state.
     *
     * @param state The state to go from.
     *
     * @returns The found state or undefined.
     */
    private loopEnd(state: ATNState): ATNState | undefined {
        for (const transition of state.getTransitions()) {
            Iif (transition.target.stateType === ATNStateType.LOOP_END) {
                return transition.target;
            }
        }
 
        return undefined;
    }
 
    private blockStart(state: StarLoopEntryState): StarBlockStartState | undefined {
        for (const transition of state.getTransitions()) {
            Iif (transition.target.stateType === ATNStateType.STAR_BLOCK_START) {
                return transition.target as StarBlockStartState;
            }
        }
    }
 
    /**
     * Returns the value at the given index. In order to avoid converting large intervals
     * into equally large arrays we take a different approach here to find the value.
     * It's assumed the given index is always in range.
     *
     * @param set The interval set from which to return a value.
     * @param index The value index in this set.
     *
     * @returns The value at index `index`.
     */
    private getIntervalElement(set: IntervalSet, index: number): number {
        let runningIndex = 0;
        for (const interval of set.intervals) {
            const intervalSize = interval.b - interval.a + 1;
            Iif (index < runningIndex + intervalSize) {
                return interval.a + index - runningIndex;
            }
            runningIndex += intervalSize;
        }
 
        return runningIndex;
    }
 
    private getRandomCharacterFromInterval(set: IntervalSet): String {
        //const randomBlockSet = randomCodeBlocks();
        const validSet = SentenceGenerator.printableUnicode.and(set);
        Iif (validSet.size === 0) {
            // Very likely just a single script or a simple set of elements.
            return String.fromCodePoint(this.getIntervalElement(set, Math.floor(Math.random() * set.size)));
        }
 
        return String.fromCodePoint(this.getIntervalElement(validSet, Math.floor(Math.random() * validSet.size)));
    }
 
    private getRandomLoopCount(inLexer: boolean, forPlusLoop: boolean): number {
        let min = inLexer ? this.minLexerIterations : this.minParserIterations;
        Iif (forPlusLoop && min === 0) {
            min = 1;
        }
        const max = inLexer ? this.maxLexerIterations : this.maxParserIterations;
 
        return Math.floor(Math.random() * (max - min + 1) + min);
    }
 
    static {
        void printableUnicodePoints({
            excludeCJK: true,
            excludeRTL: true,
            limitToBMP: false,
            includeLineTerminators: true,
        }).then((intervalSet) => {
            this.printableUnicode = intervalSet;
        });
 
 
    }
}