1
1
#!.venv/bin/python3
2
2
import typer
3
+ from rich .console import Console
3
4
from antlr4 import InputStream , CommonTokenStream , ParseTreeWalker
4
5
from generated .MyLexer import MyLexer
5
6
from generated .MyParser import MyParser
6
7
from ast_listener import ASTListener
7
8
from semantic_listener import SemanticListener
8
9
9
10
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
10
21
11
22
12
23
@app .command ()
13
24
def lex (filename : str ):
14
25
"""Lexical analysis"""
15
- with open (filename , encoding = "utf-8" ) as f :
16
- string = f .read ()
26
+ string = _read_code_from_file (filename )
17
27
18
28
lexer = MyLexer (InputStream (string ))
19
29
@@ -25,8 +35,7 @@ def lex(filename: str):
25
35
@app .command ()
26
36
def parse (filename : str ):
27
37
"""Syntactic analysis"""
28
- with open (filename , encoding = "utf-8" ) as f :
29
- string = f .read ()
38
+ string = _read_code_from_file (filename )
30
39
31
40
lexer = MyLexer (InputStream (string ))
32
41
stream = CommonTokenStream (lexer )
@@ -38,8 +47,7 @@ def parse(filename: str):
38
47
@app .command ()
39
48
def ast (filename : str ):
40
49
"""Abstract syntax tree"""
41
- with open (filename , encoding = "utf-8" ) as f :
42
- string = f .read ()
50
+ string = _read_code_from_file (filename )
43
51
44
52
lexer = MyLexer (InputStream (string ))
45
53
stream = CommonTokenStream (lexer )
@@ -54,8 +62,7 @@ def ast(filename: str):
54
62
@app .command ()
55
63
def sem (filename : str ):
56
64
"""Semantic analysis"""
57
- with open (filename , encoding = "utf-8" ) as f :
58
- string = f .read ()
65
+ string = _read_code_from_file (filename )
59
66
60
67
lexer = MyLexer (InputStream (string ))
61
68
stream = CommonTokenStream (lexer )
0 commit comments