Parsing complete mathematical expressions with PEG.js

I am trying to extend the PEG.js grammar example to parse mathematical expressions with all 4 operators for my online BASIC interpreter experiment

http://www.dantonag.it/basicjs/basicjs.html

but not all expressions are parsed correctly.

This is my PEG grammar:

expression = additive

additive = left:multiplicative atag:("+" / "-") right:additive { return {tag: atag, left:left, right:right}; } / multiplicative

multiplicative = left:primary atag:("*" / "/") right:multiplicative { return {tag: atag, left:left, right:right}; } / primary

primary = number / "(" additive:additive ")" { return additive; }

number = digits:[0-9]+ { return parseInt(digits.join(""), 10); }

It correctly parses expressions such as 2 * 3 + 1 (giving 7), but not an expression like 2-1-1, which gives 2 instead of 0.

Can you help me improve and debug this?

Thanks in advance.

Change . I added the number rule to the grammar. And yes, my grammar gives as a conclusion a recursive structure that is analogous to a parsing tree.

+4
2

-: number. , , , ( number) 2, . , ?


: , . , . - - - , , , + -, * /.

, 2*3+1 , , , ( , 2+3*1 , , , 2*3+1 , ).

, , - -, - :

  • :

    1-2-3
    
  • ( 1-(2-3)):

    {
       "tag": "-",
       "left": "1",
       "right": {
          "tag": "-",
          "left": "2",
          "right": "3"
       }
    }
    

( (1-2)-3):

{
   "tag": "-",
   "left": {
      "tag": "-",
      "left": "1",
      "right": "2"
   },
   "right": "3"
}

, -, -.

: , peg.js, - googling this,

(. Python ), [ ] . , .

+5

Matt , , pegjs:

expression = additive

additive
  = first:multiplicative rest:(("+" / "-") multiplicative)+ {
    return rest.reduce(function(memo, curr) {
      return {atag: curr[0], left: memo, right: curr[1]};
    }, first);
  }
  / multiplicative

multiplicative
  = first:primary rest:(("*" / "/") primary)+ {
    return rest.reduce(function(memo, curr) {
      return {atag: curr[0], left: memo, right: curr[1]};
    }, first);
  }
  / primary

primary
  = number
  / "(" additive:additive ")" { return additive; }

number
  = digits:[0-9]+ { return parseInt(digits.join(""), 10); }

javascript.pegjs - . , , , .

+7

All Articles