【发布时间】:2012-03-18 18:56:32
【问题描述】:
这是我之前问过How to encode FIRST & FOLLOW sets inside a compiler 的问题的后续,但这个问题更多的是关于我的程序设计。
我正在通过编写递归下降解析器来实现编译器的语法分析阶段。我需要能够利用 FIRST 和 FOLLOW 集,以便更有效地处理源程序语法中的错误。我已经为我的所有非终端计算了 FIRST 和 FOLLOW,但是我无法决定在我的程序中逻辑地将它们放在哪里以及这样做的最佳数据结构是什么。
注意:所有代码都是伪代码
选项 1) 使用映射,并将所有非终端按其名称映射到包含其 FIRST 和 FOLLOW 集的两个集合:
class ParseConstants
Map firstAndFollowMap = #create a map .....
firstAndFollowMap.put("<program>", FIRST_SET, FOLLOW_SET)
end
这似乎是一个可行的选择,但在我的解析器内部,我需要这样的丑陋代码来检索 FIRST 和 FOLLOW 并传递给错误函数:
#processes the <program> non-terminal
def program
List list = firstAndFollowMap.get("<program>")
Set FIRST = list.get(0)
Set FOLLOW = list.get(1)
error(current_symbol, FOLLOW)
end
选项 2)为每个非终端创建一个类并具有 FIRST 和 FOLLOW 属性:
class Program
FIRST = .....
FOLLOW = ....
end
这导致代码看起来更好:
#processes the <program> non-terminal
def program
error(current_symbol, Program.FOLLOW)
end
这是我想到的两个选项,我很想听听任何其他关于如何编码这两个集合的建议,以及对我发布的两种方式的任何批评和补充都会有所帮助。 谢谢
我也在这里发布了这个问题:http://www.coderanch.com/t/570697/java/java/Encode-FIRST-FOLLOW-sets-recursive
【问题讨论】:
标签: parsing data-structures compiler-construction recursive-descent