parseit.js
Version:
Customizable parsing library for converting a list of tokens into an AST tree
59 lines (58 loc) • 3.01 kB
TypeScript
import { ASTNodeConstructor } from "../classes/ASTNode";
import Token from "../classes/Token";
import GrammarRule, { GrammarAtom, GrammarEither } from "./rule";
export declare type GrammarRulesMap = {
[key: string]: GrammarRule[];
};
export declare type GrammarRuleShorthand = string | GrammarEither;
/** Grammar object class. Used to define rules and other parsing details */
export default class Grammar {
private rules;
private currentData;
private ignored;
/** The name of the rule from which the parser will begin matching */
startRule: string;
/** Define a rule variation */
rule: (name: string) => {
from: (...args: GrammarRuleShorthand[]) => any;
binaryLoop: (args: GrammarRuleShorthand[]) => any;
blockLoop: (statement: GrammarRuleShorthand, separator?: GrammarRuleShorthand) => any;
overrideIgnore: (...args: GrammarRuleShorthand[]) => any;
preventRollback: () => any;
as: (match: ASTNodeConstructor) => void;
pass: () => void;
decide: (func: Function) => void;
select: (index: number) => void;
};
/** Define a starting rule, from which the parser will begin matching */
startFrom(rule: string): void;
/** Ignore specific tokens globally. This can be overrided with a "overrideIgnore" rule method */
ignore(...args: GrammarRuleShorthand[]): void;
/** Check if a token is globally ignored */
getIgnored(token: Token, rule?: GrammarRule): GrammarAtom;
/** Get a rule by name. Will return a rule object with all of it's variations */
getRule(name: string): GrammarRule[];
/** Add tokens and other rules to the rule normally */
private from;
/** Add tokens and other rules within a binary loop */
private binaryLoop;
/** Add a statement and a separator within a block loop */
private blockLoop;
/** Override global ignore settings for this rule variation. This will completely replace the global ignore settings */
private overrideIgnore;
/** By default, when going to the next rule, the parser rewinds itself to the tokens that were previosly skip.
This can sometimes cause infinite loops. Use this method to prevent this behaviour for the rule variation */
private preventRollback;
/** Convert data automatically to a specific AST node. The arguments for the node's constructor must be in the correct order */
private as;
/** Keep the existing data as is. This will pass the first data item to the next rule */
private pass;
/** Use a function to convert the data in some way. This function takes an array of data items as the argument */
private decide;
/** Selects a certain item from the data list. Similar to pass, except instead of the first, you can pick any index */
private select;
private make;
private chain;
}
/** This selector allows multiple variants inside a single rule. Useful with loops */
export declare function either(...args: string[]): GrammarEither;