PEGJS:如何传递语法

时间:2014-04-15 18:18:00

标签: javascript parsing pegjs

引自PEGJS Tutorial

  

要生成解析器,请调用PEG.buildParser方法和       将你的语法作为参数传递:

var parser = PEG.buildParser("start = ('a' / 'b')+");

我的语法有点复杂:

start
  = additive

additive
  = left:multiplicative "+" right:additive { return left + right; }
  / multiplicative

multiplicative
  = left:primary "*" right:multiplicative { return left * right; }
  / primary

primary
  = integer
  / "(" additive:additive ")" { return additive; }

integer "integer"
  = digits:[0-9]+ { return parseInt(digits.join(""), 10); }

我应该传递PEG.buildParser我的语法的起始规则,即additive,但我无法做到正确。 如果我写 FireBug说,PEG.buildParser(additive)PEG.buildParser(start) SyntaxError: Expected "=" or string but end of input found; 如果我写PEG.buildParser(start = additive),我会GrammarError: Referenced rule "additive" does not exist; 通过我的语法的正确方法是什么?

2 个答案:

答案 0 :(得分:1)

必须将完整的语法解析为buildParser作为字符串,例如

PEG = require('pegjs');
var parser = PEG.buildParser(
  'start\n' +
  '  = additive\n' +
  '\n' +
  'additive\n' +
  '  = left:multiplicative "+" right:additive { return left + right; }\n' +
  '  / multiplicative\n' +
  '\n' +
  'multiplicative\n' +
  '  = left:primary "*" right:multiplicative { return left * right; }\n' +
  '  / primary\n' +
  '\n' +
  'primary\n' +
  '  = integer\n' +
  '  / "(" additive:additive ")" { return additive; }\n' +
  '\n' +
  'integer "integer"\n' +
  '  = digits:[0-9]+ { return parseInt(digits.join(""), 10); }'
);
console.log(parser.parse('(1+2)*3'));

答案 1 :(得分:0)

如果要从文件加载语法并将解析器导出到文件,请尝试以下示例

const peg = require('pegjs');
const fs = require('fs');

const grammarAsString = fs.readFileSync('./grammar.pegjs').toString();

const option = {
  output: 'source',
};

const parserSourceCode = peg.generate(grammarAsString, option);
fs.writeFileSync('./parser.js', parserSourceCode);

const parser = required('./parser.js');
const output = parser.parse("(1 + 2) * 3"); // output = 9

如果您希望解析器成为对象并使用它直接将输出值从“源”更改为“解析器”,或者根本不传递它,则默认为解析器。

const peg = require('pegjs');
const fs = require('fs');

const grammarAsString = fs.readFileSync('./grammar.pegjs').toString();

const parserObjet = peg.generate(grammarAsString);
const output = parserObject.parse("(1 + 2) * 3"); // output = 9