@fauton/cfg
Version:
A package to work with context free grammars and LL1 parsers
31 lines (30 loc) • 1.17 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractTerminalsFromCfg = void 0;
/**
* Extract terminals from cfg rules
* @param cfg Cfg object
* @returns An array of terminals
*/
function extractTerminalsFromCfg(inputCfg) {
if (!inputCfg.variables) {
inputCfg.variables = Object.keys(inputCfg.productionRules);
}
const terminals = [];
// Creating a set of variables initially to improve search performance
const variablesSet = new Set(inputCfg.variables);
Object.values(inputCfg.productionRules).forEach((rules) => {
rules.forEach((rule) => {
const tokens = rule.split(' ');
// Loop through each of the tokens to see which of them are terminals
tokens.forEach((token) => {
// If the token is not a variable and not empty string, its a terminal
if (!variablesSet.has(token) && token) {
terminals.push(token);
}
});
});
});
return Array.from(new Set(terminals));
}
exports.extractTerminalsFromCfg = extractTerminalsFromCfg;