-
Notifications
You must be signed in to change notification settings - Fork 1
/
pinkiepy.py
93 lines (73 loc) · 2.39 KB
/
pinkiepy.py
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
import sys
import traceback
import argparse
from colorama import Fore, Style
from pathlib import Path
from fim_debugger import Debugger
from fim_lexer import Lexer
from fim_parser import Parser
from fim_interpreter import Interpreter
from fim_resolver import Resolver
from fim_exception import FimException
def handle_errors(function):
def wrapper(*args, **kwargs):
try:
return function(*args, **kwargs)
except FimException as e:
print(f'{Fore.RED}{type(e).__name__}:'
f' {str(e)}{Style.RESET_ALL}')
except KeyboardInterrupt:
print(f'{Fore.RED}Program interrupted by user{Style.RESET_ALL}')
except RecursionError:
print(f'{Fore.RED}Recursion error{Style.RESET_ALL}')
except Exception as e:
traceback.print_exc()
print(f'{Fore.RED}Oops! There is some bug in the interpreter!:'
f' {str(e)}{Style.RESET_ALL}')
return wrapper
@handle_errors
def interpret(program):
lexer = Lexer(program)
lexer.lex()
parser = Parser(lexer)
interpreter = Interpreter(parser)
tree = parser.parse()
resolver = Resolver(interpreter)
resolver.resolve(tree)
interpreter.interpret(tree)
@handle_errors
def debug(program):
lexer = Lexer(program)
lexer.lex()
parser = Parser(lexer)
interpreter = Debugger(parser, program)
tree = parser.parse()
resolver = Resolver(interpreter)
resolver.resolve(tree)
interpreter.interpret(tree)
def interpret_file(absolute_path, interpret_function=interpret):
if not absolute_path.is_file():
print(f'{Fore.RED}File not found{Style.RESET_ALL}')
return
with absolute_path.open('r') as program_file:
program = program_file.read()
interpret_function(program)
def interpret_from_command_line():
args = parse_args()
path = args.path
is_debug = args.debug
if is_debug:
interpret_file(Path(path).absolute(), debug)
else:
interpret_file(Path(path).absolute())
def parse_args():
parser = argparse.ArgumentParser()
add_args(parser)
return parser.parse_args()
def add_args(parser):
parser.add_argument('path', type=str, help='Path to file')
parser.add_argument('-d', '--debug',
action='store_true',
help='debug')
if __name__ == '__main__':
interpret_from_command_line()