开发者

Storing vars and constants during compilation. (sample language)

Background: I'm making a compiler, the scanner and parser is already done. We have our formal grammar, which defines a program as:

program = 
 declarations 
 procedureDeclarati开发者_运维知识库ons
 main  (  ){  
     declarations 
     statementSequence
 }

So you can notice that declarations can be either global or local to the main method. So as I parse, I need a way of storing these three things: Whether the identifier coming in is a: Constant or Variable (I can tell by which parsing method I'm in, parseConst() or parseVar()), global or local, its actual name, and it's value (if I know it yet).

I'm kind of confused how to store all this. In my data structures class we really only 2 things needed to store, a key and a value. So would I have something like:

 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

it seems like wayyy too many data structures for a simple task. Should I make a class, Identifier, and have a Global/local boolean field, aswell as a constant/var boolean? And then put them all in one identifiers hashmap?

Thanks!


I think what you are looking for is scopes, you would need scopes to hold all variables associated to it in a stack-like structure e.g. a function would have its own scope which is popped off the stack when the function is left.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜