-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
215 lines (174 loc) · 10.9 KB
/
Copy pathmain.py
File metadata and controls
215 lines (174 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
"""
main.py – Entry point for the Mini-Java Syntax + Semantic Analyzer.
Pipeline
────────
1. Parsing (PLY lexer + LALR parser → AST)
2. AST display (pretty-printed tree)
3. Semantic analysis (SemanticAnalyzer → symbol-table checks)
4. Error summary (syntax errors first, then semantic errors/warnings)
Usage
─────
python main.py # interactive mode – type END to finish a block
python main.py file.java # parse + analyse a file
python main.py --help # show usage
"""
import sys
import argparse
from parser import parser, get_errors, reset_errors, reset_method_table
import lexer as lexer_module
from semantic_analyzer import SemanticAnalyzer, format_semantic_report
# ─────────────────────────────────────────────────────────────────────────────
# Shared SemanticAnalyzer instance (stateless between calls via analyze())
# ─────────────────────────────────────────────────────────────────────────────
_sem_analyzer = SemanticAnalyzer()
# ─────────────────────────────────────────────────────────────────────────────
# Core pipeline
# ─────────────────────────────────────────────────────────────────────────────
def run_parse(code: str, source_label: str = "<input>"):
"""
Full compiler front-end pipeline for one code block:
Parsing → AST → Semantic Analysis → Error Summary
"""
# ── Reset state ───────────────────────────────────────────────────────────
reset_errors()
reset_method_table()
lexer_module.lexer.lineno = 1
lexer_module.lexer.linestart = 0
# ── Header ────────────────────────────────────────────────────────────────
print(f"\n{'─'*60}")
print(f" Source : {source_label}")
print(f"{'─'*60}")
# ══════════════════════════════════════════════════════════════════════════
# PHASE 1 – Parsing
# ══════════════════════════════════════════════════════════════════════════
print("\n ┌─────────────────────────────┐")
print(" │ Phase 1 · Parsing │")
print(" └─────────────────────────────┘")
ast = parser.parse(code, lexer=lexer_module.lexer)
syntax_errors = get_errors() # list of (line, message)
# ══════════════════════════════════════════════════════════════════════════
# PHASE 2 – AST Display
# ══════════════════════════════════════════════════════════════════════════
print("\n ┌─────────────────────────────┐")
print(" │ Phase 2 · Abstract Syntax │")
print(" │ Tree │")
print(" └─────────────────────────────┘")
if ast is not None:
print()
tree_str = ast.pretty(last=True, prefix=" ")
print(tree_str)
else:
print("\n [AST] Parse failed entirely — no tree produced.")
# ══════════════════════════════════════════════════════════════════════════
# PHASE 3 – Semantic Analysis
# ══════════════════════════════════════════════════════════════════════════
print("\n ┌─────────────────────────────┐")
print(" │ Phase 3 · Semantic │")
print(" │ Analysis │")
print(" └─────────────────────────────┘")
sem_issues = []
if ast is not None:
sem_issues = _sem_analyzer.analyze(ast)
report = format_semantic_report(sem_issues)
print()
print(report)
else:
print("\n (Skipped — no AST to analyse.)")
# ══════════════════════════════════════════════════════════════════════════
# PHASE 4 – Error Summary
# ══════════════════════════════════════════════════════════════════════════
print("\n ┌─────────────────────────────┐")
print(" │ Phase 4 · Error Summary │")
print(" └─────────────────────────────┘\n")
total_syntax = len(syntax_errors)
total_sem_err = len(_sem_analyzer.errors)
total_sem_warn = len(_sem_analyzer.warnings)
grand_errors = total_syntax + total_sem_err
# ── Syntax errors ─────────────────────────────────────────────────────────
if syntax_errors:
print(f" Syntax errors ({total_syntax}):")
for line, msg in syntax_errors:
loc = f"line {line}" if line else "EOF"
print(f" • {loc}: {msg}")
else:
print(" Syntax errors : none")
# ── Semantic errors ───────────────────────────────────────────────────────
if _sem_analyzer.errors:
print(f"\n Semantic errors ({total_sem_err}):")
for e in _sem_analyzer.errors:
loc = f"line {e.line}" if e.line else "EOF"
print(f" • [{e.code}] {loc}: {e.message}")
else:
print(" Semantic errors: none")
# ── Warnings ──────────────────────────────────────────────────────────────
if _sem_analyzer.warnings:
print(f"\n Warnings ({total_sem_warn}):")
for w in _sem_analyzer.warnings:
loc = f"line {w.line}" if w.line else "EOF"
print(f" • [{w.code}] {loc}: {w.message}")
else:
print(" Warnings : none")
# ── Final verdict ─────────────────────────────────────────────────────────
print()
if grand_errors == 0 and total_sem_warn == 0:
print(" ✓ All phases passed — valid MiniJava construct.")
elif grand_errors == 0:
print(f" ⚠ Parsed successfully with {total_sem_warn} warning(s).")
else:
print(f" ✗ {grand_errors} error(s) total "
f"({total_syntax} syntax, {total_sem_err} semantic).")
print(f"\n{'─'*60}\n")
# ─────────────────────────────────────────────────────────────────────────────
# Interactive mode
# ─────────────────────────────────────────────────────────────────────────────
def interactive_mode():
print("Mini-Java Compiler Front-End (syntax + semantic analysis + AST)")
print(" • Enter Java code blocks. Type END on a new line to run.")
print(" • Type 'exit' to quit.\n")
block_num = 0
while True:
lines = []
print("Enter Java code (END to analyse, exit to quit):")
while True:
try:
line = input()
except EOFError:
line = "END"
if line.strip().lower() == "exit":
print("Bye!")
sys.exit(0)
if line.strip() == "END":
break
lines.append(line)
code = "\n".join(lines).strip()
if not code:
continue
block_num += 1
run_parse(code, source_label=f"block #{block_num}")
# ─────────────────────────────────────────────────────────────────────────────
# Main
# ─────────────────────────────────────────────────────────────────────────────
def main():
ap = argparse.ArgumentParser(
description=(
"Mini-Java Compiler Front-End — "
"parses .java-like code, builds an AST, and runs semantic analysis."
)
)
ap.add_argument(
"file", nargs="?", default=None,
help="Path to a Java source file (omit for interactive mode)"
)
args = ap.parse_args()
if args.file:
try:
with open(args.file, "r", encoding="utf-8") as fh:
code = fh.read()
except FileNotFoundError:
print(f"Error: file not found: {args.file}")
sys.exit(1)
run_parse(code, source_label=args.file)
else:
interactive_mode()
if __name__ == "__main__":
main()