-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsemantic_analyzer.py
More file actions
786 lines (648 loc) · 32.7 KB
/
Copy pathsemantic_analyzer.py
File metadata and controls
786 lines (648 loc) · 32.7 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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
"""
semantic_analyzer.py – Semantic Analysis phase for the Mini-Java compiler.
Pipeline position:
Lexer → Parser → AST → [SemanticAnalyzer] → Error Summary
Architecture
────────────
SymbolTable Manages a stack of Scopes. Each Scope is a plain dict
mapping name → Symbol. Walking the stack from top
(innermost) to bottom (global) gives standard lexical
scoping.
Symbol Lightweight record: name, kind, type_, line.
kind ∈ { 'variable', 'param', 'lambda_param',
'method', 'class', 'enum' }
SemanticAnalyzer
Single-pass AST visitor. Each visit_* method corresponds
to one ASTNode.node_type. The dispatcher (visit) looks up
visit_<node_type> and falls back to visit_children for
nodes that need no special logic.
Errors vs Warnings
──────────────────
All issues are stored as SemanticIssue objects carrying:
code – 'E-SEM-NNN' (error) or 'W-SEM-NNN' (warning)
line – source line (may be None)
message – human-readable description
Error catalogue
E-SEM-001 Undeclared variable used
E-SEM-002 Duplicate variable declaration in the same scope
E-SEM-003 Duplicate parameter name
E-SEM-004 Duplicate class name
E-SEM-005 Duplicate enum name
E-SEM-006 Call to undefined method
E-SEM-007 Assignment to undeclared variable
E-SEM-008 Type mismatch in assignment
Warning catalogue
W-SEM-001 Variable shadows a name from an outer scope
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Optional
from ast_nodes import ASTNode
# ═════════════════════════════════════════════════════════════════════════════
# Data structures
# ═════════════════════════════════════════════════════════════════════════════
@dataclass
class Symbol:
"""One entry in a scope dictionary."""
name: str
kind: str # 'variable' | 'param' | 'lambda_param' |
# 'method' | 'class' | 'enum'
type_: str # 'int' | 'string' | 'void' | 'int[]' | ClassName …
line: Optional[int] = None
def __repr__(self):
return f"Symbol({self.kind} {self.name!r}: {self.type_}, line={self.line})"
class Scope:
"""
A single lexical scope – essentially a named dict of Symbols.
Parameters
----------
label : str
Human-readable tag used in debug output, e.g. 'class:MyClass' or
'method:add'.
parent : Scope | None
The enclosing scope; None for the global scope.
"""
def __init__(self, label: str, parent: Optional["Scope"] = None):
self.label = label
self.parent = parent
self._table: dict[str, Symbol] = {}
# ── Mutation ──────────────────────────────────────────────────────────────
def define(self, symbol: Symbol) -> None:
"""Add *symbol* to this scope (caller must check for duplicates first)."""
self._table[symbol.name] = symbol
# ── Lookup ────────────────────────────────────────────────────────────────
def lookup_local(self, name: str) -> Optional[Symbol]:
"""Search *only* this scope (no parent traversal)."""
return self._table.get(name)
def lookup(self, name: str) -> Optional[Symbol]:
"""
Search from this scope outward toward global.
Returns the innermost Symbol found, or None.
"""
sym = self._table.get(name)
if sym is not None:
return sym
if self.parent is not None:
return self.parent.lookup(name)
return None
def lookup_outer(self, name: str) -> Optional[Symbol]:
"""
Check whether *name* exists in any *parent* scope (not this one).
Used to detect shadowing.
"""
if self.parent is None:
return None
return self.parent.lookup(name)
def __repr__(self):
return f"Scope({self.label!r}, symbols={list(self._table.keys())})"
class SymbolTable:
"""
Stack-based symbol table that drives scope enter/exit.
The 'current' property always points to the innermost active scope.
"""
def __init__(self):
# Seed with the global scope
self._stack: list[Scope] = [Scope("global")]
# ── Scope management ──────────────────────────────────────────────────────
def enter_scope(self, label: str) -> Scope:
"""Push a new child scope and return it."""
new_scope = Scope(label, parent=self.current)
self._stack.append(new_scope)
return new_scope
def exit_scope(self) -> Scope:
"""Pop and return the innermost scope. Global scope can't be popped."""
if len(self._stack) == 1:
raise RuntimeError("Cannot exit the global scope.")
return self._stack.pop()
@property
def current(self) -> Scope:
return self._stack[-1]
# ── Convenience wrappers ──────────────────────────────────────────────────
def define(self, symbol: Symbol) -> None:
self.current.define(symbol)
def lookup(self, name: str) -> Optional[Symbol]:
return self.current.lookup(name)
def lookup_local(self, name: str) -> Optional[Symbol]:
return self.current.lookup_local(name)
def lookup_outer(self, name: str) -> Optional[Symbol]:
return self.current.lookup_outer(name)
# ═════════════════════════════════════════════════════════════════════════════
# Issue model
# ═════════════════════════════════════════════════════════════════════════════
@dataclass
class SemanticIssue:
"""
One semantic error or warning.
Attributes
----------
code : str – 'E-SEM-NNN' for errors, 'W-SEM-NNN' for warnings.
line : int | None – source line, or None when unknown.
message : str – human-readable description.
"""
code: str
line: Optional[int]
message: str
@property
def is_error(self) -> bool:
return self.code.startswith("E-")
@property
def is_warning(self) -> bool:
return self.code.startswith("W-")
def __str__(self):
loc = f"line {self.line}" if self.line else "EOF"
tag = "✗ ERROR " if self.is_error else "⚠ WARNING"
return f" {tag} [{self.code}] {loc}: {self.message}"
# ═════════════════════════════════════════════════════════════════════════════
# Semantic Analyzer
# ═════════════════════════════════════════════════════════════════════════════
# Maps a literal token/type string to its canonical type name so that
# type-mismatch comparisons are consistent.
_TYPE_NORMALIZE = {
"int": "int",
"string": "string",
"void": "void",
}
def _normalize_type(raw: str) -> str:
"""
Normalize a raw type string to lowercase where applicable.
Array types (e.g. 'int[]', 'String[]') are preserved as-is after
lower-casing the base component.
"""
if raw is None:
return "unknown"
if raw.endswith("[]"):
base = raw[:-2]
return _TYPE_NORMALIZE.get(base.lower(), base) + "[]"
return _TYPE_NORMALIZE.get(raw.lower(), raw) # custom class names kept as-is
def _infer_literal_type(node: ASTNode) -> Optional[str]:
"""
Return the static type of a simple literal / leaf ASTNode, or None
when the node is not a recognizable literal.
"""
if node.node_type == "NumberLiteral":
return "int"
if node.node_type == "StringLiteral":
return "string"
return None
class SemanticAnalyzer:
"""
Single-pass recursive AST visitor that performs semantic analysis.
Usage
─────
analyzer = SemanticAnalyzer()
analyzer.analyze(ast_root)
issues = analyzer.issues # list[SemanticIssue]
errors = analyzer.errors # filtered list
warnings = analyzer.warnings # filtered list
"""
def __init__(self):
self.symbol_table = SymbolTable()
self.issues: list[SemanticIssue] = []
# Track which method names have been declared so we can validate calls.
# Populated during visit_MethodDecl; used during visit_MethodCall.
self._declared_methods: set[str] = set()
# ── Public entry point ────────────────────────────────────────────────────
def analyze(self, root: ASTNode) -> list[SemanticIssue]:
"""
Walk the AST rooted at *root* and collect all semantic issues.
Returns the issues list (also stored in self.issues).
"""
self.issues.clear()
self._declared_methods.clear()
# Reset symbol table to a clean global scope
self.symbol_table = SymbolTable()
if root is not None:
self.visit(root)
return self.issues
# ── Filtered views ────────────────────────────────────────────────────────
@property
def errors(self) -> list[SemanticIssue]:
return [i for i in self.issues if i.is_error]
@property
def warnings(self) -> list[SemanticIssue]:
return [i for i in self.issues if i.is_warning]
# ── Issue recording helpers ───────────────────────────────────────────────
def _error(self, code: str, line: Optional[int], message: str):
self.issues.append(SemanticIssue(code=code, line=line, message=message))
def _warning(self, code: str, line: Optional[int], message: str):
self.issues.append(SemanticIssue(code=code, line=line, message=message))
# ── Visitor dispatcher ────────────────────────────────────────────────────
def visit(self, node: ASTNode):
"""
Dispatch to visit_<NodeType>. Falls back to visit_children when
no specialized handler exists, so new node types are handled
gracefully without crashing.
"""
if not isinstance(node, ASTNode):
return # skip plain strings / ints that appear as leaf values
method_name = f"visit_{node.node_type}"
handler = getattr(self, method_name, self.visit_children)
handler(node)
def visit_children(self, node: ASTNode):
"""Default: recursively visit every child."""
for child in node.children:
if isinstance(child, ASTNode):
self.visit(child)
elif isinstance(child, list):
for item in child:
if isinstance(item, ASTNode):
self.visit(item)
# ═════════════════════════════════════════════════════════════════════════
# Visitor methods (one per relevant node_type)
# ═════════════════════════════════════════════════════════════════════════
# ── Program ───────────────────────────────────────────────────────────────
def visit_Program(self, node: ASTNode):
"""
The root node. We do a two-pass approach on the global scope:
Pass 1 – hoist all class, enum, and method names so forward
references resolve correctly.
Pass 2 – deep-visit everything for full semantic checking.
"""
self._hoist_top_level(node.children)
self.visit_children(node)
def _hoist_top_level(self, children):
"""
Register the names of classes, enums, and top-level methods into
the global scope *before* the main traversal. This lets a method
call reference a class defined later in the file.
"""
for child in children:
if not isinstance(child, ASTNode):
continue
if child.node_type == "ClassDecl":
# Register without entering scope yet (full visit handles that)
self._hoist_class_name(child)
elif child.node_type == "EnumDecl":
self._hoist_enum_name(child)
elif child.node_type == "MethodDecl":
# Top-level (outside a class) method – hoist its name.
ret_node = next(
(c for c in child.children
if isinstance(c, ASTNode) and c.node_type == "ReturnType"),
None
)
ret_type = _normalize_type(ret_node.value) if ret_node else "void"
self._declared_methods.add(child.value)
# Don't redefine in symbol table here; visit_MethodDecl will.
def _hoist_class_name(self, node: ASTNode):
"""Register a class name in the global scope (duplicate check)."""
name = node.value
if self.symbol_table.lookup_local(name):
self._error("E-SEM-004", node.line,
f"Duplicate class name: '{name}'")
else:
self.symbol_table.define(
Symbol(name=name, kind="class", type_="class", line=node.line)
)
def _hoist_enum_name(self, node: ASTNode):
"""Register an enum name in the global scope (duplicate check)."""
name = node.value
if self.symbol_table.lookup_local(name):
self._error("E-SEM-005", node.line,
f"Duplicate enum name: '{name}'")
else:
self.symbol_table.define(
Symbol(name=name, kind="enum", type_="enum", line=node.line)
)
# ── Class Declaration ─────────────────────────────────────────────────────
def visit_ClassDecl(self, node: ASTNode):
"""
Enter a class scope. The class name is already in the global scope
from hoisting; here we open the inner scope for its methods.
"""
class_name = node.value
self.symbol_table.enter_scope(f"class:{class_name}")
# Visit all children (TypeParam nodes, MethodDecl nodes, etc.)
self.visit_children(node)
self.symbol_table.exit_scope()
# ── Enum Declaration ──────────────────────────────────────────────────────
def visit_EnumDecl(self, node: ASTNode):
"""
Enum names were hoisted; here we just register the constants inside
a dedicated enum scope.
"""
enum_name = node.value
self.symbol_table.enter_scope(f"enum:{enum_name}")
for child in node.children:
if isinstance(child, ASTNode) and child.node_type == "EnumConstant":
const_name = child.value
if self.symbol_table.lookup_local(const_name):
self._error("E-SEM-002", child.line,
f"Duplicate enum constant '{const_name}' in enum '{enum_name}'")
else:
self.symbol_table.define(
Symbol(name=const_name, kind="variable",
type_=enum_name, line=child.line)
)
self.symbol_table.exit_scope()
# ── Method Declaration ────────────────────────────────────────────────────
def visit_MethodDecl(self, node: ASTNode):
"""
1. Register the method symbol in the *current* (class or global) scope.
2. Open a new scope for parameters and body.
3. Detect duplicate parameter names.
4. Recurse into the body.
"""
method_name = node.value
line = node.line
# ── Determine return type from the ReturnType child ──────────────────
ret_node = next(
(c for c in node.children
if isinstance(c, ASTNode) and c.node_type == "ReturnType"),
None
)
ret_type = _normalize_type(ret_node.value) if ret_node else "void"
# ── Register method name in enclosing scope ───────────────────────────
# (Overloading is already checked in parser.py; here we just track
# the name so call-site validation works.)
self._declared_methods.add(method_name)
# Register once in current scope (class scope, or global).
# We allow the same name because parser already handles overloads;
# we just don't want to re-error on the second overload variant here.
if not self.symbol_table.lookup_local(method_name):
self.symbol_table.define(
Symbol(name=method_name, kind="method",
type_=ret_type, line=line)
)
# ── Open method scope ─────────────────────────────────────────────────
self.symbol_table.enter_scope(f"method:{method_name}")
# ── Process parameters ────────────────────────────────────────────────
params_node = next(
(c for c in node.children
if isinstance(c, ASTNode) and c.node_type == "Params"),
None
)
if params_node:
seen_params: set[str] = set()
for param in params_node.children:
if not isinstance(param, ASTNode) or param.node_type != "Param":
continue
pname = param.value
# Determine param type from its Type child
type_child = next(
(c for c in param.children
if isinstance(c, ASTNode) and c.node_type == "Type"),
None
)
ptype = _normalize_type(type_child.value) if type_child else "unknown"
if pname in seen_params:
self._error("E-SEM-003", param.line,
f"Duplicate parameter name '{pname}' in method '{method_name}'")
else:
seen_params.add(pname)
self.symbol_table.define(
Symbol(name=pname, kind="param",
type_=ptype, line=param.line)
)
# ── Recurse into body ─────────────────────────────────────────────────
body_node = next(
(c for c in node.children
if isinstance(c, ASTNode) and c.node_type == "Body"),
None
)
if body_node:
self.visit_children(body_node)
self.symbol_table.exit_scope()
# ── Lambda Expression ─────────────────────────────────────────────────────
def visit_LambdaExpr(self, node: ASTNode):
"""
Open a new scope for lambda parameters and body.
Parameters are registered as 'lambda_param' symbols.
"""
self.symbol_table.enter_scope("lambda")
params_node = next(
(c for c in node.children
if isinstance(c, ASTNode) and c.node_type == "LambdaParams"),
None
)
if params_node:
seen: set[str] = set()
for param in params_node.children:
if not isinstance(param, ASTNode) or param.node_type != "Param":
continue
pname = param.value
type_child = next(
(c for c in param.children
if isinstance(c, ASTNode) and c.node_type == "Type"),
None
)
ptype = _normalize_type(type_child.value) if type_child else "unknown"
if pname in seen:
self._error("E-SEM-003", param.line,
f"Duplicate parameter name '{pname}' in lambda")
else:
seen.add(pname)
# Shadow check
if self.symbol_table.lookup_outer(pname):
self._warning("W-SEM-001", param.line,
f"Lambda parameter '{pname}' shadows an "
f"outer-scope declaration")
self.symbol_table.define(
Symbol(name=pname, kind="lambda_param",
type_=ptype, line=param.line)
)
body_node = next(
(c for c in node.children
if isinstance(c, ASTNode) and c.node_type == "LambdaBody"),
None
)
if body_node:
self.visit_children(body_node)
self.symbol_table.exit_scope()
# ── Try-Catch ─────────────────────────────────────────────────────────────
def visit_TryCatch(self, node: ASTNode):
"""
The try body and catch body each get their own scope.
The exception variable is declared at the top of the catch scope.
"""
# ── Try body ──────────────────────────────────────────────────────────
try_body = next(
(c for c in node.children
if isinstance(c, ASTNode) and c.node_type == "TryBody"),
None
)
self.symbol_table.enter_scope("try")
if try_body:
self.visit_children(try_body)
self.symbol_table.exit_scope()
# ── Catch body ────────────────────────────────────────────────────────
exc_type_node = next(
(c for c in node.children
if isinstance(c, ASTNode) and c.node_type == "ExcType"),
None
)
exc_var_node = next(
(c for c in node.children
if isinstance(c, ASTNode) and c.node_type == "ExcVar"),
None
)
catch_body = next(
(c for c in node.children
if isinstance(c, ASTNode) and c.node_type == "CatchBody"),
None
)
self.symbol_table.enter_scope("catch")
if exc_var_node and exc_type_node:
var_name = exc_var_node.value
var_type = _normalize_type(exc_type_node.value)
if self.symbol_table.lookup_local(var_name):
self._error("E-SEM-002", exc_var_node.line,
f"Duplicate variable declaration: '{var_name}'")
else:
self.symbol_table.define(
Symbol(name=var_name, kind="variable",
type_=var_type, line=exc_var_node.line)
)
if catch_body:
self.visit_children(catch_body)
self.symbol_table.exit_scope()
# ── Variable Declaration (top-level, outside class) ───────────────────────
def visit_VarDecl(self, node: ASTNode):
"""
`var name = lambda_expr;`
Register 'name' in the current scope, then visit the lambda.
"""
var_name = node.value
line = node.line
if self.symbol_table.lookup_local(var_name):
self._error("E-SEM-002", line,
f"Duplicate variable declaration: '{var_name}'")
else:
outer = self.symbol_table.lookup_outer(var_name)
if outer:
self._warning("W-SEM-001", line,
f"Variable '{var_name}' shadows '{outer.name}' "
f"declared at line {outer.line}")
self.symbol_table.define(
Symbol(name=var_name, kind="variable",
type_="lambda", line=line)
)
# Visit the lambda body
self.visit_children(node)
# ── Assignment Statements ─────────────────────────────────────────────────
def visit_AssignStmt(self, node: ASTNode):
"""
`lhs = rhs;`
Checks:
• lhs must be declared (E-SEM-007)
• type of rhs must match type of lhs (E-SEM-008)
"""
lhs_name = node.value
line = node.line
lhs_sym = self.symbol_table.lookup(lhs_name)
if lhs_sym is None:
self._error("E-SEM-007", line,
f"Assignment to undeclared variable: '{lhs_name}'")
else:
# Type-check the RHS
if node.children:
rhs_node = node.children[0]
rhs_type = self._resolve_type(rhs_node)
if rhs_type and lhs_sym.type_ not in ("unknown", "lambda"):
lhs_type = _normalize_type(lhs_sym.type_)
if lhs_type != rhs_type and rhs_type != "unknown":
self._error("E-SEM-008", line,
f"Type mismatch: cannot assign {rhs_type} "
f"to '{lhs_name}' (declared as {lhs_type})")
# Visit children to catch nested errors (e.g. in lambdas on the RHS)
self.visit_children(node)
def visit_VarAssignStmt(self, node: ASTNode):
"""
`var name = lambda_expr;` or `name = lambda_expr;`
When the LHS is 'var', infer and register; otherwise look up.
"""
lhs_name = node.value
line = node.line
if lhs_name == "var":
# Type-infer from RHS lambda – register as 'lambda' type
self.symbol_table.define(
Symbol(name="var", kind="variable",
type_="lambda", line=line)
)
else:
lhs_sym = self.symbol_table.lookup(lhs_name)
if lhs_sym is None:
self._error("E-SEM-007", line,
f"Assignment to undeclared variable: '{lhs_name}'")
self.visit_children(node)
# ── Identifiers used as expressions ───────────────────────────────────────
def visit_Identifier(self, node: ASTNode):
"""
Any standalone identifier reference (e.g. on the RHS of an
assignment or as a return value) must be declared.
"""
name = node.value
if self.symbol_table.lookup(name) is None:
self._error("E-SEM-001", node.line,
f"Use of undeclared variable: '{name}'")
# ── Return statements ─────────────────────────────────────────────────────
def visit_ReturnStmt(self, node: ASTNode):
"""Visit children (the returned Identifier, if any)."""
self.visit_children(node)
# ── Method Call ───────────────────────────────────────────────────────────
def visit_MethodCall(self, node: ASTNode):
"""
Validate that the called method has been declared somewhere in the
program. We intentionally allow 'obj.method()' style calls where
'method' is looked up by its plain name (since we don't track full
object types — that would require a full type-inference pass).
"""
callee_node = next(
(c for c in node.children
if isinstance(c, ASTNode) and c.node_type == "Callee"),
None
)
if callee_node:
# callee value is e.g. "obj.doSomething" or "a.b.c"
method_name = callee_node.value.split(".")[-1]
if method_name not in self._declared_methods:
self._error("E-SEM-006", callee_node.line,
f"Call to undefined method: '{method_name}'")
self.visit_children(node)
# ═════════════════════════════════════════════════════════════════════════
# Internal helpers
# ═════════════════════════════════════════════════════════════════════════
def _resolve_type(self, node: ASTNode) -> Optional[str]:
"""
Return the static type of *node* as a normalized string, or None
when the type cannot be determined without a full inference pass.
Handles:
NumberLiteral → 'int'
StringLiteral → 'string'
Identifier → look up in symbol table
Everything else → None (not checked)
"""
if node.node_type == "NumberLiteral":
return "int"
if node.node_type == "StringLiteral":
return "string"
if node.node_type == "Identifier":
sym = self.symbol_table.lookup(node.value)
if sym:
return _normalize_type(sym.type_)
return None
# ═════════════════════════════════════════════════════════════════════════════
# Pretty-printer for issue summaries (used by main.py)
# ═════════════════════════════════════════════════════════════════════════════
def format_semantic_report(issues: list[SemanticIssue]) -> str:
"""
Return a formatted, human-readable semantic analysis report.
Errors are listed before warnings.
"""
errors = [i for i in issues if i.is_error]
warnings = [i for i in issues if i.is_warning]
lines = []
if not issues:
lines.append(" ✓ Semantic analysis passed — no errors or warnings.")
return "\n".join(lines)
if errors:
lines.append(f" ✗ {len(errors)} semantic error(s):")
for e in errors:
loc = f"line {e.line}" if e.line else "EOF"
lines.append(f" • [{e.code}] {loc}: {e.message}")
if warnings:
lines.append(f" ⚠ {len(warnings)} warning(s):")
for w in warnings:
loc = f"line {w.line}" if w.line else "EOF"
lines.append(f" • [{w.code}] {loc}: {w.message}")
return "\n".join(lines)