Question

Quoting from PEGJS Tutorial:

To generate a parser, call the PEG.buildParser method and pass your grammar as a parameter:

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

My grammar is a bit more complicated:

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); }

I should pass to PEG.buildParser the Starting Rule of my grammar, i.e. additive, but I can't get it right. If I write PEG.buildParser(additive) or PEG.buildParser(start), FireBug said SyntaxError: Expected "=" or string but end of input found; if I write PEG.buildParser(start = additive), I get GrammarError: Referenced rule "additive" does not exist; what is the correct way to pass my grammar?

Was it helpful?

Solution

The complete grammar must be parsed to buildParser as a string, e.g.

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'));

OTHER TIPS

try this example if you want to load your grammar from a file and export the parser to a file

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

if you want your parser to be object and use it directly change output value from "source" to "parser" or don't pass it at all the default is parser.

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top