0

背景:我正在制作一个编译器,扫描仪和解析器已经完成。我们有我们的形式语法,它将程序定义为:

program = 
 declarations 
 procedureDeclarations
 main  (  ){  
     declarations 
     statementSequence
 }

所以你会注意到声明可以是全局的,也可以是主方法的局部。所以当我解析时,我需要一种存储这三件事的方法: 传入的标识符是:常量还是变量(我可以通过解析方法来判断我在使用的解析方法,parseConst() 还是 parseVar()),全局或本地,它的实际名称,它的价值(如果我还知道的话)。

我有点困惑如何存储所有这些。在我的数据结构类中,我们实际上只需要存储两件事,一个键和一个值。所以我会有类似的东西:

 identHashMap<String, String> // where the first string is the ident's name, and the second is if it's a constant or var (this could be a boolean also)
 constantIdentifiers<String, String> // first string is the ident's name, second is whether it's local/global (could be a string)
 varIdentifiers<String, String> // first string is the ident's name, second is whether it's local/global (could be a string)
 identifierValues<String, Integer> // ident's name, Ident's value

对于一项简单的任务,似乎太多的数据结构。我应该创建一个类、标识符,并拥有一个全局/本地布尔字段,以及一个常量/var 布尔值吗?然后将它们全部放在一个标识符哈希图中?

谢谢!

4

1 回答 1

0

我认为您正在寻找的是作用域,您需要作用域来将与其关联的所有变量保存在类似堆栈的结构中,例如,函数将具有自己的作用域,当函数离开时,该作用域会从堆栈中弹出。

于 2010-10-25T08:47:12.243 回答