Commit my random junk
[sandbox] / pylox / main.py
1 import enum
2 import sys
3
4 class TokenType(enum.Enum):
5     LEFT_PARENTHESE = enum.auto()
6     RIGHT_PARENTHESE = enum.auto()
7     LEFT_BRACE = enum.auto()
8     RIGHT_BRACE = enum.auto()
9     LEFT_BRACKET = enum.auto()
10     RIGHT_BRACKET = enum.auo()
11     COMMA = enum.auto()
12     DOT = enum.auto()
13     MINUS = enum.auto()
14     PLUS = enum.auto()
15     SLASH = enum.auto()
16     STAR = enum.auto()
17     PERCENT = enum.auto()
18
19     BANG = enum.auto()
20     BANG_EQUALS = enum.auto()
21     EQUAL = enum.auto()
22     EQUALS_EQUALS = enum.auto()
23     LESS_THAN = enum.auto()
24     LESS_THAN_EQUALS = enum.auto()
25     GREATER_THAN = enum.auto()
26     GREATER_THAN_EQUALS = enum.auto()
27
28     IDENTIFIER = enum.auto()
29     STRING = enum.auto()
30     NUMBER = enum.auto()
31
32     AND = enum.auto()
33     ELSE = enum.auto()
34     END = enum.auto()
35     FALSE = enum.auto()
36     FOR = enum.auto()
37     IF = enum.auto()
38     NIL = enum.auto()
39     NOT = enum.auto()
40     OR = enum.auto()
41     TRUE = enum.auto()
42
43
44 had_error = False
45
46 def error(line, message):
47     report(line, '', message)
48
49 def report(line, where, message):
50     print('[line {}] Error {}: {}'.format(
51         line,
52         where,
53         message,
54     )
55
56     had_error = True
57
58 def run(source):
59     tokens = scan_tokens(source)
60
61     for token in tokens:
62         print(token)
63
64 def run_file(path):
65     with open(path, 'r') as f:
66         run(f.read())
67
68     if had_error:
69         sys.exit(65)
70
71 def run_prompt():
72     while True:
73         line = input('> ')
74         if not line:
75             break
76         run(line)
77         had_error = False
78
79 if __name__ == '__main__':
80     if len(sys.argv) > 2:
81         print('Usage: pylox [script]')
82         sys.exit(65)
83
84     elif len(sys.argv) == 2:
85         run_file(sys.args[1])
86
87     else:
88         run_prompt()