Because we haven’t had it for a while here’s the front cover. If you are not sure what this post is about check out episode 1 https://jollygoodsw.wordpress.com/2025/03/13/working-through-writing-a-c-compiler/

This is a short chapter, the only real change is that the variable name / scope resolution gets fancier. This is beacuse we can now have
int x = 2;
if (x == 1){
int x = 42;
int y = x + 4;
{
int y = x + 10;
}
}
Ie we really do need to keep track of which variables x, y and z are referring to at different points in the code. It is interesting to compare this to the Crafting Interpreters mechanism I described in https://jollygoodsw.wordpress.com/2025/03/14/working-through-wacc-chapter-5-local-variables/
The steps are:
- We already had a name mapping table (x => x0), this is extended to include an ‘added in this block’ boolean
- Implement a stack of these tables
- When we enter a new scope duplicate the table, set all the markers to false and place it at the top of the stack
- New names go into the top of stack table, marked as ‘added in this block’, if the name already existed with that marker its an error
- Any name resolution looks at the top of stack name table
- When we exit a scope pop the top name table.
FYI here are pointers to my implementation
- Start of a function, with an empty stack https://github.com/pm100/mycc/blob/14130827de65b92ada3e9a949c3dbaf5b6aa25a1/src/parser.rs#L88
- start a new scope https://github.com/pm100/mycc/blob/fa17ff3da67e9729bfca36e3dab7e798982af881/src/parser.rs#L166
- new variable declaration https://github.com/pm100/mycc/blob/14130827de65b92ada3e9a949c3dbaf5b6aa25a1/src/parser.rs#L133
- Name lookup https://github.com/pm100/mycc/blob/14130827de65b92ada3e9a949c3dbaf5b6aa25a1/src/expr.rs#L252
- Scope exit https://github.com/pm100/mycc/blob/fa17ff3da67e9729bfca36e3dab7e798982af881/src/parser.rs#L96
Not sure if its useful putting pointers to my code in this blog or not. I was going to paste the code into the blog itself but I cant work out how to make the code window wide enough , still a wordpress noob.
Backend
Once again another chapter passes where we don’t have to change the back end, it all just worked
Leave a comment