编写解释器,需要帮助表示这些数据
我正在编写一个小型解释器来展示巴科斯-诺尔形式的示例,我想寻求帮助来表示一些数据。
<statement> : <assignment> | HALT | PRINT(<variable>)
<assignment> : <variable> = <expression>
<expression> : <term> | <term><operator><expression>
<term> : <number> | <variable>
<variable> : x | y | z
<operator> : + | -
<number> : 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
如您所见,所有内容都封装在声明中。然后是赋值和表达式。表达式封装了一个术语,术语封装了一个数字和一个变量。赋值封装了变量和表达式。我的问题是我使用什么数据结构来表示所有这些?我认为它应该是一个集合,但这提出了一个问题:我应该有嵌套集合吗?
I am writing a small interpreter to show an example of Backus-Naur form and i would like to ask for help representing some data.
<statement> : <assignment> | HALT | PRINT(<variable>)
<assignment> : <variable> = <expression>
<expression> : <term> | <term><operator><expression>
<term> : <number> | <variable>
<variable> : x | y | z
<operator> : + | -
<number> : 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
As you can see everything is encapsulated in a statement. An then there assignments and expression. An expression encapsulates a term, which encapsulate a number and a variable. An assignment encapsulates a variable and a expression. My question is what data structure do i use to represent all of this? I am thinking it should be a set, but then that raises the question should i have nested sets?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这看起来像一个简单的表达式解析器,添加了一些命令(PRINT 和 HALT)。解析此类事物的最简单方法可能是使用递归下降解析器。如果您正在构建解释器,则可以在解析时解释表达式,或者构建表达式的后缀(或前缀)表示形式以供以后解释。
This looks like a simple expression parser with a few added commands (PRINT and HALT). Probably the easiest way to parse such a thing is with a recursive descent parser. If you're building an interpreter, you can then either interpret the expression while parsing, or build a postfix (or prefix) representation of the expression for later interpretation.
我会使用面向对象的方法:
等等。根据您需要与变量关联的信息量(可能是声明它们的位置、出现的行和列等),您可能会使用
String
作为变量type 和 int 作为您的数字类型。I would use an OO approach:
and so on. Depending on how much information you need to associate with variables (perhaps where they were declared, what line and column this occurrence appeared, and so on), you could possibly get away with using
String
s as your variable type andint
s as your number type.