-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsemantic.py
More file actions
375 lines (287 loc) · 10.9 KB
/
semantic.py
File metadata and controls
375 lines (287 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
"""
PHASE 3: SEMANTIC ANALYZER
What is Semantic Analysis?
---------------------------
Semantic analysis checks if the program makes SENSE, even if it's syntactically correct.
Example of syntactically correct but sema ntically wrong code:
print(z); // z was never declared!
The parser says "yes, this is a valid print statement"
But the semantic analyzer says "wait, what is z?"
Why do we need it?
------------------
Syntax only checks FORM, not MEANING.
Consider English:
- Syntactically correct: "The colorless green ideas sleep furiously"
- Semantically wrong: Makes no sense!
Similarly in programming:
- Syntactically correct: x = y + z;
- Semantically wrong if y or z don't exist!
What does it check?
-------------------
1. **Variable Declaration**: Is a variable declared before use?
2. **Type Checking**: Do types match? (we only have integers, so this is simple)
3. **Scope Rules**: Is a variable accessible here? (we have global scope only)
The Symbol Table
----------------
The key data structure is the SYMBOL TABLE.
It's like a dictionary that tracks all variables:
Symbol Table Example:
┌──────────┬──────────┬───────────┐
│ Name │ Type │ Declared? │
├──────────┼──────────┼───────────┤
│ x │ int │ Yes │
│ y │ int │ Yes │
└──────────┴──────────┴───────────┘
Real compilers have complex symbol tables with:
- Scopes (global, function, block)
- Types (int, float, string, custom classes)
- Attributes (const, static, public, private)
We keep it simple: just track variable names.
"""
from ast_parser import (
ASTNode, ProgramNode, AssignmentNode, PrintNode,
BinaryOpNode, NumberNode, VariableNode
)
class SymbolTable:
"""
Symbol Table - tracks all declared variables
In real compilers, this is a sophisticated data structure with:
- Nested scopes (global, function, block)
- Type information
- Memory locations
- Attributes (const, static, etc.)
Our simple version just tracks variable names.
"""
def __init__(self):
"""
Initialize empty symbol table
We use a dictionary: variable_name → True
(In real compilers, the value would be a Symbol object with type, scope, etc.)
"""
self.symbols = {} # {variable_name: True}
def declare(self, name):
"""
Declare a variable
This happens when we see an assignment to a new variable.
In languages with explicit declarations (like C), this would
happen at 'int x;'
Args:
name: Variable name
"""
if name in self.symbols:
# In our simple language, redeclaration is OK (just reassignment)
# In C/Java, this would be an error
pass
self.symbols[name] = True
print(f" ✓ Declared variable: {name}")
def is_declared(self, name):
"""
Check if a variable is declared
Args:
name: Variable name
Returns:
True if declared, False otherwise
"""
return name in self.symbols
def __repr__(self):
"""Pretty print the symbol table"""
if not self.symbols:
return "Symbol Table: (empty)"
result = "Symbol Table:\n"
result += "┌" + "─" * 20 + "┐\n"
result += "│ Variable Name │\n"
result += "├" + "─" * 20 + "┤\n"
for name in self.symbols:
result += f"│ {name:<18} │\n"
result += "└" + "─" * 20 + "┘"
return result
class SemanticAnalyzer:
"""
Semantic Analyzer - checks if the program makes sense
Process:
1. Walk through the AST (tree traversal)
2. For each variable assignment, add to symbol table
3. For each variable use, check if it's in symbol table
4. Report errors if variables are used before declaration
This is called "tree walking" or "AST traversal"
"""
def __init__(self):
"""Initialize with empty symbol table"""
self.symbol_table = SymbolTable()
self.errors = [] # List of semantic errors found
def error(self, message):
"""
Record a semantic error
We collect all errors instead of stopping at the first one.
This is better UX - show all problems at once!
Real compilers do this and show multiple errors.
"""
self.errors.append(message)
print(f" ✗ Semantic Error: {message}")
def analyze(self, ast):
"""
Main entry point for semantic analysis
Args:
ast: The root of the AST (ProgramNode)
Returns:
True if no errors, False if errors found
"""
print("\n🔍 Starting Semantic Analysis...")
print("-" * 60)
# Visit the AST
self.visit(ast)
# Report results
print("-" * 60)
if self.errors:
print(f"\n❌ Found {len(self.errors)} semantic error(s)")
return False
else:
print("\n✅ No semantic errors found!")
return True
def visit(self, node):
"""
Visit a node in the AST
This uses the "Visitor Pattern":
- For each node type, call a specific visit method
- Example: ProgramNode → visit_program()
This is a common pattern in compilers!
"""
method_name = f'visit_{type(node).__name__}'
visitor = getattr(self, method_name, self.generic_visit)
return visitor(node)
def generic_visit(self, node):
"""
Fallback for nodes without specific visitor
"""
raise Exception(f'No visit method for {type(node).__name__}')
# ========================================================================
# VISITOR METHODS - one for each AST node type
# ========================================================================
def visit_ProgramNode(self, node):
"""
Visit the program (root node)
Just visit all statements in order.
"""
print(" Analyzing program...")
for statement in node.statements:
self.visit(statement)
def visit_AssignmentNode(self, node):
"""
Visit an assignment statement
Example: x = 5 + 3;
Steps:
1. Analyze the right-hand side expression (5 + 3)
2. Declare the variable (x) in symbol table
Note: In our language, assignment also declares the variable.
In C/Java, you'd need separate declaration: int x;
"""
print(f" Analyzing assignment to '{node.variable_name}'...")
# First, analyze the expression (right-hand side)
# This checks if any variables used in the expression are declared
self.visit(node.expression)
# Then declare this variable
# (In our language, first assignment declares the variable)
self.symbol_table.declare(node.variable_name)
def visit_PrintNode(self, node):
"""
Visit a print statement
Example: print(x + 5);
Just analyze the expression being printed.
"""
print(" Analyzing print statement...")
self.visit(node.expression)
def visit_BinaryOpNode(self, node):
"""
Visit a binary operation
Example: x + 5
Analyze both operands (left and right).
Type checking would happen here:
- Check if left and right have compatible types
- Determine result type
We skip this since we only have integers.
"""
# Analyze left operand
self.visit(node.left)
# Analyze right operand
self.visit(node.right)
# In a real compiler with multiple types, we'd check:
# - Can we apply this operator to these types?
# - What's the result type?
# Example: "hello" + 5 → type error in most languages
def visit_NumberNode(self, node):
"""
Visit a number literal
Example: 42
Nothing to check - numbers are always valid!
"""
# Numbers are always OK, nothing to check
pass
def visit_VariableNode(self, node):
"""
Visit a variable reference
Example: x (in an expression like x + 5)
This is the KEY semantic check:
- Is this variable declared?
- If not, it's a semantic error!
Example error:
y = x + 5; // If x was never declared, ERROR!
"""
# Check if variable is declared
if not self.symbol_table.is_declared(node.name):
self.error(f"Variable '{node.name}' used before declaration")
else:
print(f" ✓ Variable '{node.name}' is declared")
def demo_semantic_analyzer():
"""
Demonstration of semantic analysis
"""
print("=" * 60)
print("PHASE 3: SEMANTIC ANALYSIS DEMO")
print("=" * 60)
from lexer import Lexer
from ast_parser import Parser
# Example 1: Valid program
print("\n" + "=" * 60)
print("Example 1: VALID PROGRAM")
print("=" * 60)
source_code_valid = """
x = 5;
y = x + 10;
print(y);
"""
print("\n📝 Source Code:")
print(source_code_valid)
lexer = Lexer(source_code_valid)
tokens = lexer.tokenize()
parser = Parser(tokens)
ast = parser.parse()
analyzer = SemanticAnalyzer()
is_valid = analyzer.analyze(ast)
print("\n📋 " + str(analyzer.symbol_table))
# Example 2: Invalid program (using undeclared variable)
print("\n\n" + "=" * 60)
print("Example 2: INVALID PROGRAM (undeclared variable)")
print("=" * 60)
source_code_invalid = """
x = 5;
y = z + 10;
print(y);
"""
print("\n📝 Source Code:")
print(source_code_invalid)
print(" Note: 'z' is used but never declared!")
lexer = Lexer(source_code_invalid)
tokens = lexer.tokenize()
parser = Parser(tokens)
ast = parser.parse()
analyzer = SemanticAnalyzer()
is_valid = analyzer.analyze(ast)
print("\n📋 " + str(analyzer.symbol_table))
print("\n\n💡 What happened?")
print(" - Semantic analyzer walks through the AST")
print(" - It maintains a symbol table of declared variables")
print(" - When a variable is used, it checks the symbol table")
print(" - Catches errors like using undeclared variables")
print(" - This catches bugs that the parser can't detect!\n")
if __name__ == "__main__":
demo_semantic_analyzer()