Master the fundamental concepts of semantic analysis through this focused micro-challenge.
Every declaration inserts a name; every use looks it up. Compilers chain symbol tables for nested scopes: function body inside file scope inside namespace. LLVM, GCC, and Clang all use scoped hash tables with push/pop on block entry and exit.
On entering a block, push a new table. On declaration, insert (name, type, location) in the current scope. On use, search innermost scope first, then outer scopes. On exit, pop the inner table.
cLoading…
x hides outer xProduction compilers embed this step inside a longer pipeline. GCC flows through cpp, cc1, assembly, and ld; Clang uses the driver, Sema, LLVM IR passes, and a target backend. LLVM bitcode, JVM bytecode, and WASM are other familiar IRs at the same layer. The exercise isolates one pass so you can test it alone before chaining it to the next stage.
You will implement a scoped symbol table with insert, lookup, and push/pop for blocks. This exercise requires tracking declared names and resolving identifiers to their declarations during semantic analysis.
Implement a symbol table with proper scope management.
Define data structures:
Symbol: Entry for one identifierScope: Collection of symbols with parent pointerSymbolTable: Manages scope stackImplement scope operations:
scope_enter(): Enter a new scope (function, block)scope_exit(): Leave current scopescope_current(): Get current scope levelImplement symbol operations:
symbol_define(name, type): Add symbol to current scopesymbol_lookup(name): Find symbol (current scope and parents)symbol_lookup_local(name): Find symbol in current scope onlysymbol_exists(name): Check if symbol is defined anywhereHandle edge cases:
Three hints are available for this task, revealed one at a time inside the code workspace so you can struggle productively before seeing them.
All starter code and reference implementations are available for your local setup.
View on Github