Symbol tables: entries, implementation and scopes
Practical notes on symbol tables: what entries contain, how to implement them (hash tables, chaining, scope stacks), and how static vs dynamic scopes are resolved.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Symbol tables are a central data structure in a compiler front end. An engineer uses symbol tables during lexical, syntactic and semantic analysis to record identifiers (names), their meanings (types, storage), and the scope where they are visible — this information is then used for type checking, code generation and optimisations. Primarily, construction and scope resolution occur during semantic analysis; the lexer may intern identifier lexemes but does not manage scopes.
Key ideas
- Scope — the region of a program source text where a declaration is valid (visible). A scope has a well-defined start and end. Examples: global scope, block scope, function scope, class scope.
- Scope level — an integer assigned to each scope to denote nesting depth; global is usually 0, each nested block increases the level by 1.
- Static (lexical) scoping — the rule that an identifier reference is resolved by examining the program text to find the nearest enclosing declaration in textual (lexical) nesting. Assume the source program is fixed; resolution depends on source structure, not run-time call history.
- Dynamic scoping — the rule that an identifier reference is resolved by searching the chain of active procedure calls at run time (call stack) for a declaration. Assume run-time call stack is used.
Exact statements often required in exams
- Definition (Symbol table entry): "A symbol table entry is a tuple (name, kind, type, scope, storage, attributes) representing one declaration in the program." State the assumption that each declaration produces exactly one entry (unless language allows redeclaration semantics).
- Static scoping theorem (informal but exact): "Under static scoping, the binding of an identifier occurrence is determined uniquely by the nearest declaration that lexically encloses that occurrence. If no such declaration exists, the identifier refers to a global declaration or is undefined." Mention assumption: program is parsed and nesting structure is available.
- Operations required on symbol tables:
INSERT(name, attributes),LOOKUP(name),BEGIN_SCOPE(),END_SCOPE(), and sometimesREMOVE(name)orENTER_SCOPE(scope_id)/EXIT_SCOPE(scope_id).
How to implement with scopes (common approaches)
Separate symbol tables per scope (stack of tables): maintain a stack where each stack frame is a symbol table for that scope. On BEGIN_SCOPE push a new empty table, on END_SCOPE pop it. LOOKUP searches top to bottom (current to global) until found. Diagram to draw: a vertical stack of boxes labelled Scope 2, Scope 1, Scope 0; within each box list name→entry pairs; draw an arrow from lookup request at top to search downwards.
Single hash table with chaining and scope links (scope stamping): use one global hash table mapping name to a linked list of entries (most recent declaration first). Each entry has a
scope_levelor a pointer to the next entry for the same name. On INSERT, add a new entry at head of name's chain; record the scope in a separate stack of inserted entries so END_SCOPE can remove entries inserted in that scope in O(k) where k is number of inserts in the scope. Diagram to draw: show hash buckets, each bucket pointing to a linked list of entries; show each entry has a scope field and a next pointer; show a separate stack of entries per scope.Name list per identifier (push/pop method): for each identifier maintain a stack (linked list) of definitions; when entering a scope push declarations, on exit pop them. LOOKUP reads the top of the identifier's stack. Diagram: show a map from name to a vertical list of declarations with top pointer.
Complexity and trade-offs (state assumptions):
- Hash table average-case lookup/insert is O(1) assuming good hash and load factor. Worst-case O(n) if many collisions (assume separate chaining or open addressing). Mention memory overhead for per-entry pointers.
- Stack-of-tables makes BEGIN_SCOPE/END_SCOPE O(1) to push/pop but LOOKUP can be O(s) where s is number of nested scopes to search. If each scope is small, cost is small. State this assumption.
What to draw in exam diagrams (exactly):
- For scope stack: draw 3 boxes vertically labelled Scope 0 (global), Scope 1, Scope 2. Inside each write an example pair like x:int, y:float. Show an arrow labelled LOOKUP(x) from top of stack to the first box that contains x.
- For hash + chaining: draw 4 buckets 0..3; show bucket 2 with a linked list [x@2 -> x@1] where x@2 means x declared in scope 2. Also draw a separate stack that records inserted entries in scope 2, scope 1.
Formulas
List of operations (syntax to remember):
INSERT(name, attributes) — insert a declaration for name with attributes into current scope; detect and report a duplicate if the name already has a declaration in the current scope.
LOOKUP(name) — return attributes of the most closely visible declaration for name or NULL if not found (report an undeclared-identifier error if the language requires it).
BEGIN_SCOPE() — start a new (nested) scope; subsequent INSERTs are recorded in this scope.
END_SCOPE() — end current scope and remove all declarations introduced in it.
Complexity notes (apply when using a hash table with separate chaining and a good hash):
Average-case INSERT : O(1) — average constant time per insert.
Average-case LOOKUP : O(1) — average constant time.
Worst-case INSERT or LOOKUP : O(n) — when all keys collide.
(Meanings: n = number of entries; assumes a randomizing hash or low load factor.)
Worked examples
Example 1 — Trace: stack-of-tables for nested blocks Code (pseudo): 1: int x; 2: { 3: float x; 4: y = x; // which x? 5: } 6: x = 1; // which x?
Steps:
- BEGIN_SCOPE() for global (level 0). INSERT(x, kind=var, type=int, scope=0).
- BEGIN_SCOPE() for block (level 1). INSERT(x, kind=var, type=float, scope=1).
- LOOKUP at line 4: search scope 1 -> find x:float. So y = x uses x:float.
- END_SCOPE() pop scope 1; x:float removed.
- At line 6 LOOKUP x -> search scope 0 -> find x:int. So x = 1 uses x:int. Final: correct resolution by static scoping.
Example 2 — Hash table with chaining and scope stamping (trace of inserts and end-scope removal) Assume hash(name) -> bucket k.
- Global: BEGIN_SCOPE(). INSERT(a,type=int). Hash bucket k gets entry a@0.
- Enter function: BEGIN_SCOPE(). INSERT(b,type=int), INSERT(a,type=float). Bucket k now has a@1 -> a@0.
- LOOKUP(a) finds a@1 (top of chain) -> float.
- END_SCOPE(): remove all entries inserted in scope 1. We pop a@1 and b@1 from their chains, restoring bucket k to a@0.
- LOOKUP(a) now returns a@0 -> int.
Example 3 — Static vs Dynamic scoping (model exam question answer) Program (pseudo): 1: var x = 1; 2: proc p() { print(x); } 3: proc q() { var x = 2; p(); } 4: q();
Static scoping: p's print refers to the x declared in global scope (line 1) because p was defined in that scope. Output: 1. Dynamic scoping: at runtime, q calls p; the most recent active x is x=2 from q, so output: 2. Explain assumptions: static uses program text nesting; dynamic uses call chain at runtime.
Common mistakes
- Assuming hash tables give guaranteed O(1) worst-case lookup (forgetting worst-case collisions). Always qualify with average vs worst case.
- Missing fields in an entry: e.g., forgetting to store scope level or storage offset needed later by code generator.
- Not recording order of declarations when language allows shadowing and redeclaration rules (e.g., function overloads).
For your exam
Types of questions
- Definitions: "Define symbol table, entry, scope, static scoping, dynamic scoping." Include fields of an entry and examples.
- Short notes: compare implementations (stack of tables vs single table with chaining vs per-name stacks). Give complexity and memory trade-offs.
- Derivations/algorithms: write pseudocode for INSERT/LOOKUP/BEGIN_SCOPE/END_SCOPE and argue correctness and complexity.
- Programs/traces: show a step-by-step trace of symbol table actions on a given program fragment with nested scopes.
- Diagrams: draw a stack-of-tables or hash buckets with chained entries and show where lookups go.
What a full-marks answer includes
- Precise definitions with bold term names, explicit assumptions (e.g., language uses block scoping, identifiers are case-sensitive).
- Correct algorithm/pseudocode for operations and explanation of how scope begins/ends are handled.
- Complexity analysis stating average and worst-case and the assumptions for each.
- A clear diagram when asked and a small traced example demonstrating correctness.
- If asked about static vs dynamic scoping, give an illustrative program and the two different outputs, with explanation.
Quick check
- Name two common ways to implement scope handling in symbol tables.
- Under static scoping, where is an identifier resolved from?
- What does END_SCOPE() need to do when using a single chained hash table implementation? Answers: 1) Stack of symbol tables per scope; single global table with chaining and scope stamping (or per-name stacks). 2) From the nearest lexically enclosing declaration in the source text (or global if none). 3) Remove all entries that were inserted in that scope (pop them from chains or tables) so they are no longer returned by LOOKUP.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?