As part of my parser I want to add arithmetic and boolean expressions. I wanted to take default PEG.js example at https://pegjs.org/online but the problem is that that parser is recursive and you can't write two or more lines:
For instance this is valid JavaScript:
2 * (3 + 4)
2 * (3 + 4)
2 * (3 + 4)
+ 10
as you can see there are 3 expressions and end of the line don't terminate them. But with PEG.js they need to be explicitly encoded, so the expression can terminate.
How would you go and create infinite expressions like this, that terminate and go to next expression?
You could add a Start
rule like the following for multiple expressions.
Start
= head:Expression tail:("\n" Expression)* {
return [head].concat(tail.map(function(element) {
return element[1];
}));
}
Expression
= head:Term tail:(_ ("+" / "-") _ Term)* {
return tail.reduce(function(result, element) {
if (element[1] === "+") { return result + element[3]; }
if (element[1] === "-") { return result - element[3]; }
}, head);
}
Term
= head:Factor tail:(_ ("*" / "/") _ Factor)* {
return tail.reduce(function(result, element) {
if (element[1] === "*") { return result * element[3]; }
if (element[1] === "/") { return result / element[3]; }
}, head);
}
Factor
= "(" _ expr:Expression _ ")" { return expr; }
/ Integer
Integer "integer"
= _ [0-9]+ { return parseInt(text(), 10); }
_ "whitespace"
= [ \t\n\r]*