UNPKG

@fauton/cfg

Version:

A package to work with context free grammars and LL1 parsers

38 lines (37 loc) 1.5 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.convertStringToGrammar = void 0; const extractTerminalsFromCfg_1 = require("./extractTerminalsFromCfg"); /** * Convert a string representation of cfg object to a cfg object * @param grammarString Grammar string to convert to cfg object * @returns Converted cfg object */ function convertStringToGrammar(grammarString) { const productionRules = grammarString.split('\n'); const cfg = { productionRules: {}, startVariable: '', terminals: [], variables: [], }; productionRules.forEach((productionRule) => { const [variable, rules] = productionRule.split(' -> '); // Only create the production rule if it doesn't exist, otherwise we might replace the existing one if (!cfg.productionRules[variable]) { cfg.productionRules[variable] = []; } // Each production rule is separated by | rules.split(' | ').forEach((rule) => { cfg.productionRules[variable].push(rule); }); cfg.variables.push(variable); }); cfg.variables = Array.from(new Set(cfg.variables)); // Set the first variable as the start variable // eslint-disable-next-line cfg.startVariable = cfg.variables[0]; cfg.terminals = (0, extractTerminalsFromCfg_1.extractTerminalsFromCfg)(cfg); return cfg; } exports.convertStringToGrammar = convertStringToGrammar;