X-Git-Url: https://code.kerkeslager.com/?p=sandbox;a=blobdiff_plain;f=pylox%2Fmain.py;fp=pylox%2Fmain.py;h=1972baad636dc667f17ab4654b6c43b14ba0ed33;hp=0000000000000000000000000000000000000000;hb=968af6bc53d70e889bae92c15606212c084e0168;hpb=45ec9c36ab7241cee93e615b3c901b5b80aa7aff diff --git a/pylox/main.py b/pylox/main.py new file mode 100644 index 0000000..1972baa --- /dev/null +++ b/pylox/main.py @@ -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()