2

引用PEGJS 教程

要生成解析器,请调用 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,但我做错了。如果我写 PEG.buildParser(additive)PEG.buildParser(start),FireBug 说 SyntaxError: Expected "=" or string but end of input found;如果我写PEG.buildParser(start = additive),我会得到GrammarError: Referenced rule "additive" does not exist;通过我的语法的正确方法是什么?

4

2 回答 2

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'));
于 2014-04-16T11:11:09.697 回答
1

如果您想从文件加载语法并将解析器导出到文件,请尝试此示例

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
于 2019-12-23T00:21:17.780 回答