aa1
aa1

Reputation: 803

How does a compiler remember declared variable when used in expression?

How does a compiler keep track of the declaration of a variable when it is used in an expression?

For example, if I have the following code:

int num = 1; //declaration
num = 2; //expression

I know that the syntax tree will generate a branch for the declaration and a branch for the expression but how does it maintain the connection between them in the semantic analyzer?

Upvotes: 0

Views: 107

Answers (1)

ForceBru
ForceBru

Reputation: 44858

The compiler's semantic analysis phase includes dealing with a symbol table, which, as the name implies, keeps track of all the symbols (names) used in the program. This also allows to detect undeclared names, for example.

So, when the analyzer "sees" a declaration, it creates a new symbol (like Symbol(type=Int, offset=0)) and inserts it into a map name -> Symbol. For example, symbol_table["num"] = Symbol(type=Int, offset=0).

Then, when analyzing an expression or a statement (it's a statement in your example), the compiler can, for example, analyze the types of its members. To do this, it looks up the names used in the symbol table:

assign_to_symbol = symbol_table["num"]
if assign_to_symbol.type == right_hand_side.type:
    DoStuff()
else:
    ThatIsAnError()

If there's no name "num" in this scope, the lookup fails, thus signaling an error.

Upvotes: 3

Related Questions