UNPKG

@parser-generator/core

Version:

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

91 lines 3.01 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const definition_1 = require("@parser-generator/definition"); const definition_2 = require("./definition"); const automata_1 = require("./automata"); const first_follow_1 = require("../first-follow"); const parsing_table_1 = require("./parsing-table"); class SLRAutotamaTools { /** * 求指定项集的闭包 * * 例 * 考虑文法: * E->E+T | T * T->T*F | F * F->(E) | id * * 输入: * E->·E+T * E->·T * * 输出: * E->·E+T * E->·T * T->·T*F * T->·F * F->·(E) * F->·id * * @param itemSet 项集 */ closure(itemSet) { let itemSetClosure = itemSet; //考虑实际情况 不需要深拷贝 let added = new Set(); //项集的每一个项 item for (let processedIdx = 0; processedIdx < itemSetClosure.length; processedIdx++) { let item = itemSetClosure[processedIdx]; /* 没有闭包的情况 1. 「点」已经到了产生式的最后末尾 A-> X· 2. 后继符号不是终结符 没有闭包 A-> ·a */ if (!item.hasNext()) continue; let next = item.nextSymbol(); if (!(next instanceof definition_1.NonTerminal)) continue; //如果已经添加过 则跳过 if (added.has(next)) continue; //将后继符号的产生式加入 closure for (let prod of next.prods) { itemSetClosure.push(new definition_2.Item(prod)); } added.add(next); } return itemSetClosure; } GOTO(I, inputSymbol) { let nextItemSet = new definition_2.ItemSet(); for (let item of I) { if (!item.hasNext()) continue; if (item.nextSymbol() == inputSymbol) { nextItemSet.push(item.nextItem()); } } return this.closure(nextItemSet); } getStartState(grammar) { return new definition_2.State(0, this.closure(new definition_2.ItemSet(new definition_2.Item(grammar.startNT().prods[0])))); } } exports.SLRAutotamaTools = SLRAutotamaTools; function getSLRAutomata(grammar) { return automata_1.getAutomata(grammar, new SLRAutotamaTools()); } exports.getSLRAutomata = getSLRAutomata; function getSLRParsingTable(grammar, automata, fol) { if (automata == undefined) automata = getSLRAutomata(grammar); if (fol == undefined) { let foll = new first_follow_1.FollowCalculator(grammar, new first_follow_1.FirstCalculator(grammar)); fol = (i) => foll.getFollowSet(i); } return parsing_table_1.getParsingTable(automata, grammar.startNT(), (i) => fol(i.prod.head)); } exports.getSLRParsingTable = getSLRParsingTable; //# sourceMappingURL=slr.js.map