I am trying to implement 'variable declaration future' to my parsed language.
PEG.js source:
start
=begin line (pl)+ end
pl
=varx" " left:identifier" "to" "middle:integer line { left=middle;}
/
print"(" middle:identifier ")" line {alert(middle);}
line
="\n"
begin
="start"
print
="print"
if
="if"
equals
="equals"
gth
="greater than"
identifier
=[a-zA-Z]+ {return text();}
to
="to"
varx
="set"
end
="end"
integer "integer"
= digits:[0-9]+ { return Number(parseInt(digits.join(""), 10)); }
My custom input source:
start
set a to 5
print(a)
end
What output I got:
[
"start",
"
",
[
undefined,
undefined
],
"end"
]
And as alert I got only the variable name a no the value...
try this
all
= "start" nl _ ptp:putThenPrint+ _ "end"
{
var all = [];
ptp.forEach(it => {
all.push(it);
});
var r = []
all.forEach(tp => {
tp.toPrint.forEach(p => {
r.push(tp.values[p])
});
});
return "\n" + r.join("\n") + "\n";
}
putThenPrint
= _ mn:multiPutN _ pn:multiPrintN _
{
return {values:mn,toPrint:pn};
}
multiPrintN
= _ mp:printN+ _
{
var r = [];
mp.forEach(it => {
r.push(it);
});
return r;
}
multiPutN
= _ mp:putN+ _
{
var r = {};
mp.forEach(it => {
r[it[0]]=it[1];
});
return r;
}
putN
= _ "set " _ vn:varName _ "to " _ vv:n _ nl+ { return [vn, vv]}
printN
= _ "print(" _ n:varName _ ")" _ nl+ {return n;}
varName
= [a-zA-Z]+ {return text();}
n "integer number"
= _ [0-9]+ { return parseInt(text(), 10); }
nl "new line"
= [\n]
_ "whitespace"
= [ \t]*
this grammar does not support "if" and some other things you are trying to do in your grammar but it will give you a start up idea. You need to elaborate more of what you want in text with more example and expected output