Search code examples
grammarpegjs

Left Recursion Error in Peg.JS


I am currently making a programming language for a science fair.

This is my PEG.js grammar:

start
  = s:Statements
    { return ['Program', {}].concat(s); }
  / _

Statements
  = s:Statement ";"
    { return s; }
  / ss:Statements s:Statement ";"
    { return ss; ss.push(s); }
  / _

Statement
  = SetVar

SetVar
  = i:Ident "=" e:Expr
    { return ['SetVarStmt', {}, i, e]; }

Expr
  = Ident
  / Number

Number
  = n:[0-9]+
    { return ['Number', { val: parseInt(n.join(""), 10) }]; }

Ident
  = i:[a-zA-Z._]*
    { return ['Ident', { name: i.join("") }]; }

_ = [ \t\r\n]*

I get the following error: "Left recursion detected for rule 'Statements'." But I cannot figure out why this is occurring.


Solution

  • You have Statements = Statements Statement, which is left recursive.

    When using PEG, it is best to write Statements = Statement+, or Statements = Statement Statement*.