javascriptparsingpegjs

PEGJS: How to pass a grammar


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?


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