-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathpip.py
272 lines (263 loc) · 10.3 KB
/
pip.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
#!/usr/bin/env python3
import sys
import argparse
import pprint
import version
from scanning import scan, addSpaces
from parsing import parse
from ptypes import Scalar
from execution import ProgramState
from errors import FatalError
def pip(code=None, argv=None, interactive=True):
if code is not None or argv is not None:
interactive = False
if interactive:
print(f"=== Welcome to Pip, version {version.VERSION} ===")
print("Enter command-line args, terminated by newline (-h for help):")
argv = input()
if argv is not None:
# Artificial command-line input was provided
if isinstance(argv, list):
# Args are already in list form, just make sure each one
# is a string
argv = [str(arg) for arg in argv]
else:
# Parse the fake command-line input, simplistically accepting
# single- and double-quoted strings (with no escapes or shell
# expansion)
argv_string = str(argv) + " "
argv = []
quote = None
buffer = None
for char in argv_string:
if char in "'\"":
if quote is None:
# Open quote
quote = char
buffer = buffer or ""
elif quote == char:
# Close quote
quote = None
else:
# Already inside the other type of quote
buffer += char
elif char == " " and quote is None:
if buffer is not None:
argv.append(buffer)
buffer = None
else:
buffer = buffer or ""
buffer += char
argparser = argparse.ArgumentParser()
codeSources = argparser.add_mutually_exclusive_group()
listFormats = argparser.add_mutually_exclusive_group()
argparser.add_argument("-d",
"--debug",
help="equivalent to -pvw",
action="store_true")
codeSources.add_argument("-e",
"--execute",
help="execute the given code")
codeSources.add_argument("-f",
"--file",
help="execute code from the given file")
codeSources.add_argument("-i",
"--stdin",
help="execute code read from stdin",
action="store_true")
listFormats.add_argument("-l",
"--lines",
help=("output list items on separate lines, "
"concatenated"),
action="store_true")
listFormats.add_argument("-n",
"--newline",
help="concatenate lists on newline",
action="store_true")
listFormats.add_argument("-p",
"--repr",
help="print lists in repr form",
action="store_true")
listFormats.add_argument("-P",
"--reprlines",
help=("output list items on separate lines, "
"repr'd"),
action="store_true")
argparser.add_argument("-r",
"--readlines",
help="read args from lines of stdin",
action="store_true")
listFormats.add_argument("-s",
"--space",
help="concatenate lists on space",
action="store_true")
listFormats.add_argument("-S",
"--spacelines",
help=("output list items on separate lines, "
"space-concatenated"),
action="store_true")
argparser.add_argument("-v",
"--verbose",
help="show extra messages",
action="store_true")
argparser.add_argument("-V",
"--version",
help="display version info and quit",
action="store_true")
argparser.add_argument("-w",
"--warnings",
help="show nonfatal warning messages",
action="store_true")
argparser.add_argument("-x",
"--exec-args",
help=("treat each arg as Pip code (useful for "
"args that need to be evaluated "
"as expressions)"),
action="store_true")
argparser.add_argument("args",
help="arguments to main function",
nargs="*")
if argv is not None:
# Parse options from artificial command-line input
options = argparser.parse_args(argv)
else:
# Parse options from actual command-line input
options = argparser.parse_args()
#!print(options)
if options.version:
print(f"Pip {version.VERSION} (updated {version.COMMIT_DATE})")
return
if options.debug:
options.warnings = options.verbose = options.repr = True
listFormat = ("p" if options.repr else
"P" if options.reprlines else
"s" if options.space else
"S" if options.spacelines else
"n" if options.newline else
"l" if options.lines else
None)
if (code is None and options.execute is None and options.file is None
and not options.stdin):
if interactive:
options.stdin = True
print("Enter your program, terminated by Ctrl-D or Ctrl-Z:")
elif options.args:
# Treat first non-option arg as name of code file
options.file = options.args.pop(0)
else:
print(f"Type {sys.argv[0]} -h for usage information.")
sys.exit(0)
if code is not None:
# Code is passed into function
program = code
elif options.execute is not None:
# Code is given as command-line argument
program = options.execute
elif options.file is not None:
# Get code from specified file
if interactive:
print("Reading", options.file)
try:
with open(options.file) as f:
program = f.read()
except:
print("Could not read from file", options.file, file=sys.stderr)
sys.exit(1)
elif options.stdin:
# Get code from stdin, stopping at EOF
program = ""
try:
while True:
program += input() + "\n"
except EOFError:
pass
if program:
program = program[:-1]
if options.verbose:
charcount = len(program)
bytecount = len(program.encode("utf-8"))
print(f"{bytecount} bytes (UTF-8), {charcount} characters")
print()
try:
tokens = scan(program)
except FatalError as err:
print("Fatal error while scanning:", err, file=sys.stderr)
print("Execution aborted.", file=sys.stderr)
sys.exit(1)
if options.verbose:
print(addSpaces(tokens))
print()
try:
parse_tree = parse(tokens)
except FatalError as err:
print("Fatal error while parsing:", err, file=sys.stderr)
print("Execution aborted.", file=sys.stderr)
sys.exit(1)
if options.verbose:
pprint.pprint(parse_tree)
print()
state = ProgramState(listFormat, options.warnings)
if options.readlines:
raw_args = []
try:
while True:
raw_args.append(input())
except EOFError:
pass
else:
raw_args = options.args
if options.exec_args:
# Treat each argument as a Pip statement/expression
program_args = []
for arg in raw_args:
try:
arg_tokens = scan(arg)
except FatalError as err:
print(f"Fatal error while scanning argument {arg!r}:",
err, file=sys.stderr)
print("Execution aborted.", file=sys.stderr)
sys.exit(1)
try:
arg_parse_tree = parse(arg_tokens)
except FatalError as err:
print(f"Fatal error while parsing argument {arg!r}:",
err, file=sys.stderr)
print("Execution aborted.", file=sys.stderr)
sys.exit(1)
parsed_arg = arg_parse_tree[0]
try:
program_args.append(state.executeStatement(parsed_arg))
except (FatalError, RuntimeError) as err:
# RuntimeError probably means we exceeded Python's
# max recursion depth
print(f"Fatal error while evaluating argument {arg!r}:",
err, file=sys.stderr)
print("Execution aborted.", file=sys.stderr)
sys.exit(1)
except KeyboardInterrupt:
print("Program terminated by user while evaluating "
f"argument {arg!r}.",
file=sys.stderr)
sys.exit(1)
else:
# Treat each argument as a Scalar
program_args = [Scalar(arg) for arg in raw_args]
if interactive:
print("Executing...")
try:
state.executeProgram(parse_tree, program_args)
except (FatalError, RuntimeError) as err:
# RuntimeError probably means we exceeded Python's max
# recursion depth
print("Fatal error during execution:", err, file=sys.stderr)
print("Program terminated.", file=sys.stderr)
sys.exit(1)
except KeyboardInterrupt:
print("Program terminated by user.", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
if len(sys.argv) == 1:
# No arguments given, just the name of the code file in argv
pip(interactive=True)
else:
pip(interactive=False)