我正试图实现'变量声明未来'到我的解析语言。
PEG.js来源:
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)); }
我的自定义输入源:
start
set a to 5
print(a)
end
输出结果:
[
"start",
"
",
[
undefined,
undefined
],
"end"
]
作为警告,我只得到变量名a
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]*
这个语法不支持"if"还有其他一些你想在语法中做的事情,但它会给你一个开始的想法。您需要通过更多示例和预期输出详细说明您想要的文本内容