Commit my random junk
[sandbox] / pylox / main.py
diff --git a/pylox/main.py b/pylox/main.py
new file mode 100644 (file)
index 0000000..1972baa
--- /dev/null
@@ -0,0 +1,88 @@
+import enum
+import sys
+
+class TokenType(enum.Enum):
+    LEFT_PARENTHESE = enum.auto()
+    RIGHT_PARENTHESE = enum.auto()
+    LEFT_BRACE = enum.auto()
+    RIGHT_BRACE = enum.auto()
+    LEFT_BRACKET = enum.auto()
+    RIGHT_BRACKET = enum.auo()
+    COMMA = enum.auto()
+    DOT = enum.auto()
+    MINUS = enum.auto()
+    PLUS = enum.auto()
+    SLASH = enum.auto()
+    STAR = enum.auto()
+    PERCENT = enum.auto()
+
+    BANG = enum.auto()
+    BANG_EQUALS = enum.auto()
+    EQUAL = enum.auto()
+    EQUALS_EQUALS = enum.auto()
+    LESS_THAN = enum.auto()
+    LESS_THAN_EQUALS = enum.auto()
+    GREATER_THAN = enum.auto()
+    GREATER_THAN_EQUALS = enum.auto()
+
+    IDENTIFIER = enum.auto()
+    STRING = enum.auto()
+    NUMBER = enum.auto()
+
+    AND = enum.auto()
+    ELSE = enum.auto()
+    END = enum.auto()
+    FALSE = enum.auto()
+    FOR = enum.auto()
+    IF = enum.auto()
+    NIL = enum.auto()
+    NOT = enum.auto()
+    OR = enum.auto()
+    TRUE = enum.auto()
+
+
+had_error = False
+
+def error(line, message):
+    report(line, '', message)
+
+def report(line, where, message):
+    print('[line {}] Error {}: {}'.format(
+        line,
+        where,
+        message,
+    )
+
+    had_error = True
+
+def run(source):
+    tokens = scan_tokens(source)
+
+    for token in tokens:
+        print(token)
+
+def run_file(path):
+    with open(path, 'r') as f:
+        run(f.read())
+
+    if had_error:
+        sys.exit(65)
+
+def run_prompt():
+    while True:
+        line = input('> ')
+        if not line:
+            break
+        run(line)
+        had_error = False
+
+if __name__ == '__main__':
+    if len(sys.argv) > 2:
+        print('Usage: pylox [script]')
+        sys.exit(65)
+
+    elif len(sys.argv) == 2:
+        run_file(sys.args[1])
+
+    else:
+        run_prompt()