【发布时间】:2014-09-15 03:37:27
【问题描述】:
昨天我问了语法,今天在 Java 中,我正在学习如何使用我完成的词法分析器中的标记来实现解析语法的算法。
对于这个问题,我需要一个人来检查我的理解。
假设给定 Scheme 语法:
exp -> ( rest
| #f
| #t
| ' exp
| integer_constant
| string_constant
| identifier
rest -> )
| exp+ [ . exp ] )
下面的伪代码正确吗?我研究了递归下降解析器,需要通过创建解析树的节点来为解释器制作解析树。
Node parseExp() {
check to see if the token is left parenthesis
if true, return a node for Cons (which is a non-terminating node in Scheme
parse tree) and call parseRest()
else check to see if the token is #f
if true, return a node for Boolean with stored value #f
else check to see if the token is #t
if true, return a node for Boolean with stored value #t
else check to see if the token is quote
if true, return a node for Quote and recursively call parseExp()
else check to see if the token is integer_constant
if true, return a node for Integer with stored value int
else check to see if the token is string_constant
if true, return a node for String with stored string value
else check to see if the token is identifier
if true, return a node for identifier with stored string value
else
print error message saying a Syntax error occured
return null
}
Node parseRest() {
check to see if the token is right parenthesis
if true, return a node for Nil (which is a terminating () node in scheme
parse tree)
else // I am having difficulty trying to put this into an algorithm here
call parseExp() for the first expression
while (token does not equal right parenthesis) {
getNextToken()
if (token equals right parenthesis)
return a node for right parenthesis
else if (token equals dot)
return a node for dot
getNextToken()
if (token equals right parenthesis)
print error message saying a Syntax error occurred
return null
else
call parseExp()
else
parseExp()
}
}
如果我对此有错误的想法,请纠正我。据说 parseRest() 需要一个前瞻令牌才能做出决定,这可以解释一下吗?可能是一个伪代码示例?
谢谢!
【问题讨论】:
-
写一个正则表达式并通过
string.matches(...)测试输入会更容易吗? -
当然可以,但是我正在为 Java 中的方案构建编译器。它需要配备错误检查。解析后的下一部分是构建解释器,这需要解析树等数据结构。
-
@Hannes Java 正则表达式不支持递归,即使他们支持,编写这样一个怪物正则表达式很可能不会比这更容易(而且绝对不会更易读或更易于维护)。通常不建议使用正则表达式解析上下文无关语言(在 Java 中甚至不可能)。当然,即使你有这样一个正则表达式,它也不会给你一个 AST,所以你所能做的就是检查有效的语法,这不是我们想要的。