Skip to content

Commit 1ce7da8

Browse files
committed
Handle FileNotFoundError
1 parent 8e155b6 commit 1ce7da8

File tree

3 files changed

+18
-8
lines changed

3 files changed

+18
-8
lines changed

main.py

+15-8
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,29 @@
11
#!.venv/bin/python3
22
import typer
3+
from rich.console import Console
34
from antlr4 import InputStream, CommonTokenStream, ParseTreeWalker
45
from generated.MyLexer import MyLexer
56
from generated.MyParser import MyParser
67
from ast_listener import ASTListener
78
from semantic_listener import SemanticListener
89

910
app = typer.Typer(no_args_is_help=True)
11+
err_console = Console(stderr=True)
12+
13+
14+
def _read_code_from_file(filename: str) -> str:
15+
try:
16+
with open(filename, encoding="utf-8") as f:
17+
return f.read()
18+
except FileNotFoundError as e:
19+
err_console.print(f"[bold red]File '{filename}' not found")
20+
raise typer.Exit(code=1) from e
1021

1122

1223
@app.command()
1324
def lex(filename: str):
1425
"""Lexical analysis"""
15-
with open(filename, encoding="utf-8") as f:
16-
string = f.read()
26+
string = _read_code_from_file(filename)
1727

1828
lexer = MyLexer(InputStream(string))
1929

@@ -25,8 +35,7 @@ def lex(filename: str):
2535
@app.command()
2636
def parse(filename: str):
2737
"""Syntactic analysis"""
28-
with open(filename, encoding="utf-8") as f:
29-
string = f.read()
38+
string = _read_code_from_file(filename)
3039

3140
lexer = MyLexer(InputStream(string))
3241
stream = CommonTokenStream(lexer)
@@ -38,8 +47,7 @@ def parse(filename: str):
3847
@app.command()
3948
def ast(filename: str):
4049
"""Abstract syntax tree"""
41-
with open(filename, encoding="utf-8") as f:
42-
string = f.read()
50+
string = _read_code_from_file(filename)
4351

4452
lexer = MyLexer(InputStream(string))
4553
stream = CommonTokenStream(lexer)
@@ -54,8 +62,7 @@ def ast(filename: str):
5462
@app.command()
5563
def sem(filename: str):
5664
"""Semantic analysis"""
57-
with open(filename, encoding="utf-8") as f:
58-
string = f.read()
65+
string = _read_code_from_file(filename)
5966

6067
lexer = MyLexer(InputStream(string))
6168
stream = CommonTokenStream(lexer)

pyproject.toml

+1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ readme = "README.md"
66
requires-python = ">=3.12"
77
dependencies = [
88
"antlr4-python3-runtime>=4.13.2",
9+
"rich>=13.9.4",
910
"typer>=0.14.0",
1011
]
1112

uv.lock

+2
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)