UNPKG

@parser-generator/grammar-interpreter

Version:

A Parser Generator that supports LL,SLR,LR1,LALR

75 lines (72 loc) 2.1 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const definition_1 = require("@parser-generator/definition"); const core_1 = require("@parser-generator/core"); const left_1 = __importDefault(require("./left")); const right_1 = __importDefault(require("./right")); /* #GRAMMAR S -> Stmt ; Stmt -> If | Other <% (e)=>e[0] %> ; If -> 'if' Expr Stmt | 'if' Expr Stmt 'else' Stmt <% (e)=> new IfStmt(e) %>; Expr -> 'Expr' <% (e)=>e[0] %>; Other -> 'Other' <% (e)=>e[0] %>; #GRAMMAR S -> Stmt ; Stmt -> If | Other <% (e)=>e[0] %> ; If -> 'if' Expr Stmt | 'if' Expr Stmt 'else' Stmt <% (e)=> new IfStmt(e) %>; Expr -> 'Expr' <% (e)=>e[0] %>; Other -> 'Other' <% (e)=>e[0] %>; #SYMBOL_ASSOC_PREC If left */ class IfStmt { constructor(children) { this.children = children; } toString() { return "(" + this.children.join(" ") + ")"; } } exports.IfStmt = IfStmt; class Token { constructor(lexeme) { this.lexeme = lexeme; } key() { return this.lexeme; } toString() { return this.lexeme; } } class Lexer { constructor(lexemes) { this.i = 0; this.lexemes = lexemes; } peek() { return this.i >= this.lexemes.length ? new Token(definition_1.EOF) : new Token(this.lexemes[this.i]); } next() { return this.i < this.lexemes.length ? new Token(this.lexemes[this.i++]) : new Token(definition_1.EOF); } } exports.parser1 = new core_1.LRParser(left_1.default); let ast1 = exports.parser1.parse(new Lexer(["if", "Expr", "if", "Expr", "Other", "else", "Other"])); console.log(ast1.toString()); //(if Expr (if Expr Other) else Other) exports.parser2 = new core_1.LRParser(right_1.default); let ast2 = exports.parser2.parse(new Lexer(["if", "Expr", "if", "Expr", "Other", "else", "Other"])); console.log(ast2.toString()); //(if Expr (if Expr Other else Other)) //# sourceMappingURL=test.js.map