Taslima Akhter
Taslima Akhter

Reputation: 61

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

Upvotes: 1

Views: 380

Answers (2)

Joe Hildebrand
Joe Hildebrand

Reputation: 10414

I started from @digital-alpha's code, and got this (only tested on Peggy):

{
const vars = {};
const result = [];
}

lines = (line _)* { return result; }

line 
  = set 
  / print

set = v:varName _ "=" _ num:n _ ";" { vars[v] = num; }
  
print = "print" _ v:varName { result.push(vars[v]); }
  
varName = $[a-zA-Z]+
  
n "integer number" = num:$[0-9]+ { return parseInt(num, 10); }
  
_ "whitespace or new line" = [ \t\n\r]*

Which should handle multiple variables, multiple print statements, and print statements interleaved with variables. Note that the block of code inside the {} is executed for each run of the parser, so those variables won't interfere with other runs.

Input:

a=4;
print a
print b
b=5;
print b
a=6;
print a

Output:

[
  4,
  undefined,
  5,
  6
]

Upvotes: 0

Digital Alpha
Digital Alpha

Reputation: 300

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

Upvotes: 2

Related Questions