javascriptparsingpegjs

PEGjs | Implement Variable in Parser


I am very beginner to PEGjs I need help to implement variable (identifier) declaration support to my parser.

My input code look like:

a=4;
print a

My PEGjs grammer:

start
=(line)*
line
=left:var"="right:integer";" {left=right;}
/ 
print middle:var {return middle;}
print
="print"
var
=(a-zA-z)+
Integer "integer"
= _ [0-9]+ { return parseInt(text(), 10); }

Expected output: 4


Solution

  • try this:

    all
      = _ mn:multiPutN _ pn:printN _ 
      {
        return mn[pn];
      }
    
    multiPutN
      = mp:putN+ _ 
      {
        var r = {};
        mp.forEach(it => {
            r[it[0]]=it[1];
        });
        return r;
      }
      
    putN
      = vn:varName _ "=" _ nn:n _ ";" { return [vn, nn]}
    
    printN
      = print _ n:varName _ {return n;}
      
    varName
      = [a-zA-Z]+ {return text();}
      
    print 
      ="print"
    
    n "integer number"
      = _ [0-9]+ { return parseInt(text(), 10); }
      
    _ "whitespace or new line"
      = [ \t\n\r]*
    
    

    so that code above also support multi variables but can only print one variable. I wrote the grammar based in your example so when assigning variable value you need to put ";" at the end but print var should not need with that