11#!.venv/bin/python3
22import typer
3+ from rich .console import Console
34from antlr4 import InputStream , CommonTokenStream , ParseTreeWalker
45from generated .MyLexer import MyLexer
56from generated .MyParser import MyParser
67from ast_listener import ASTListener
78from semantic_listener import SemanticListener
89
910app = 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 ()
1324def 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 ()
2636def 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 ()
3948def 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 ()
5563def 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 )
0 commit comments