BNF 中的 JavaScript for 循环
我正在为 JavaScript 编写 BNF,它将用于生成该语言的词法分析器和解析器。 不过,我想要一些关于如何设计 for 循环的想法。 这是我当前 BNF 的简化版本:
[...]
VarDecl. Statement ::= "var" Identifier "=" Expr ";"
ForLoop. Statement ::= "for" "(" Expr ";" Expr ";" Expr ")"
[...]
如您所见,示例中有两个语句,变量声明和 for 循环。 有很多不同的表达式,但没有一个表达式也是语句。
现在的问题是这段 JavaScript 代码不会通过解析器:
for (var x = 3; [...]; [...])
这是因为变量声明不是表达式。
您对如何解决这个问题有什么想法? 我可以想到几个办法,但是不想妨碍大家自己的想法,所以这里就不说了。
I'm writing BNF for JavaScript which will be used to generate a lexer and a parser for the language. However, I'd like some ideas on how to design the for-loop. Here is the simplified version of my current BNF:
[...]
VarDecl. Statement ::= "var" Identifier "=" Expr ";"
ForLoop. Statement ::= "for" "(" Expr ";" Expr ";" Expr ")"
[...]
So as you can see, there are two statements in the example, variable declarations and for-loops. There are a bunch of different expressions, but none of the expressions are also statements.
The problem now is that this JavaScript code will not pass through the parser:
for (var x = 3; [...]; [...])
This is because a variable declaration is not an expression.
What are your ideas on how to solve this? I can think of a few ways, but I don't want to get in the way of your own thoughts, so I won't mention them here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
网上有一些示例,在 ANTLR ECMAScript 语法 中,您可以找到这个结构:
There are a few examples over the net, in an ANTLR ECMAScript grammar you can find this structure:
您应该能够在那里放置任何“简单”语句(即 vardecl、表达式、void 函数调用等)。 简单地说,我的意思是任何不是复合语句的东西(即带有附加花括号,例如 if/else/for/function 等)。
You should be able to put any "simple" statement there (i.e vardecl, expression, void function call, etc) there. By simple I mean anything that isn't a compound statement (i.e. with additional curly-braces, such as if/else/for/function, etc).