I've got the dragonbook but it doesn't seem to handle that topic...
In the most modern languages it's possible to use certain variables even if their appearance in the code is unordered.
Example
class Foo {
void bar() {
plonk = 42;
}
int plonk;
}
It doesn't matter that the variable plonk
is declared after the function.
Question
Is there any best practice/useful pattern how to implement this? There are two approaches which cam to my mind:
While parsing add dummy symbols for unseen symbols. When the declaration is parsed those dummies get replaced by their real symbols. After the parsing we can check if there are dummies left and if so output an error.
Don't do any symbol stuff while parsing but only create the AST. After parsing step through the AST and depending on the node add symbols. For e.g. a class node add symbols of the children and process them after. For e.g. statement blocks step through children and add symbols immediatly before the child is processed.
I would expect approach 1. is easier and also more useful for stuff like "importing other compilation units".
Edit:
A problem i see with approach 1 is that there needs some kind of handling for ordered symbols. E.g. withing a function it's not possible to use a local symbol before it is used.