This repository has been archived by the owner on May 18, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterpreter.py
79 lines (65 loc) · 1.72 KB
/
interpreter.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
from __future__ import annotations
import argparse
from argparse import ArgumentParser
from typing import TYPE_CHECKING
from stackscript.runtime import ScriptRuntime
from stackscript.repl import REPL
from stackscript.values import TupleValue, StringValue
if TYPE_CHECKING:
pass
cli = ArgumentParser(
description = 'Stack-based script interpreter.',
)
cli.add_argument(
'-i',
action = 'store_true',
help = 'enter interactive mode after running script',
dest = 'interactive',
)
cli.add_argument(
'-d',
action = 'store_true',
help = 'print contents of stack on exit',
dest = 'dump_stack',
)
input_group = cli.add_mutually_exclusive_group()
input_group.add_argument(
'-c',
help = 'program passed in as string at command line',
metavar = 'cmd',
dest = 'cmd',
)
input_group.add_argument(
'file',
nargs = '?',
help = 'read program from script file',
)
cli.add_argument(
'args',
nargs = argparse.REMAINDER,
help = 'arguments passed to program in argv',
)
def _load_script(path: str) -> str:
with open(path, 'rt') as file:
return file.read()
if __name__ == '__main__':
args = cli.parse_args()
runtime = ScriptRuntime()
argv = TupleValue(StringValue(str(o)) for o in args.args)
runtime.get_globals()['argv'] = argv
script = None
if args.cmd is not None:
script = args.cmd
elif args.file is not None:
script = _load_script(args.file)
if script is None:
repl = REPL(runtime)
repl.run()
elif args.interactive:
repl = REPL(runtime)
repl.run(script)
else:
runtime.run_script(script)
if args.dump_stack:
dump = '\n'.join(runtime.format_stack())
print(dump)