-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
388 lines (303 loc) · 12.1 KB
/
Copy pathcli.py
File metadata and controls
388 lines (303 loc) · 12.1 KB
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
"""
"""
import re
import os
import pathlib
import click
import traceback
import sys
from io import StringIO
import contextlib
from ib_pseudocode_python import spec as ib_specification_glue_code
form_group = click.group
make_command = click.command
add_argument = click.argument
add_option = click.option
add_argument = click.argument
pass_pseudo = click.pass_context
on_repl = pathlib.Path('/home/runner/.local/').exists()
from io import StringIO
import contextlib
@contextlib.contextmanager
def stdoutIO(stdout=None):
old = sys.stdout
if stdout is None:
stdout = StringIO()
sys.stdout = stdout
yield stdout
sys.stdout = old
class Screen:
output_to_screen = staticmethod(click.echo)
stylize_string = staticmethod(click.style)
prompt_user = staticmethod(click.prompt)
wait_for_any_key = staticmethod(click.pause)
def echo_green(self, s, **kwargs):
self.output_to_screen(self.stylize_string(s, fg='green'), **kwargs)
def echo_yellow(self, s):
self.output_to_screen(self.stylize_string(s, fg='yellow'))
def echo_white(self, s):
self.output_to_screen(self.stylize_string(s, fg='white'))
def echo_red(self, s):
self.output_to_screen(self.stylize_string(s, fg='red'))
def styled_echo(self, s, **kwargs):
self.output_to_screen(self.stylize_string(s, **kwargs))
def stylized_echo(self, s, echo={}, style={}):
self.output_to_screen(self.stylize_string(s, **style), **echo)
def new_line(self):
self.output_to_screen()
def clear_screen(self):
click.clear()
def prompt(self, s, **kwargs):
return self.prompt_user(s, **kwargs)
def styled_prompt(self, s, style={}, prompt={}):
return self.prompt_user(self.stylize_string(s, **style), **prompt)
def pause(self, **kwargs):
wait_for_any_key(**kwargs)
class Transpiler:
"""
"""
def __init__(self):
"""
"""
self.screen = Screen()
@staticmethod
def if_statement(match):
return re.sub(r'[^!<>]={1}', r'==', match.group(0))
@staticmethod
def increment_second_range_param(match):
groups = match.groups()
if len(groups) != 3:
raise("Something wicked this way comes")
return f"for {groups[0]} in range({groups[1]}, {groups[2]}+1):"
@staticmethod
def inverse_while(match):
operand1, operator, operand2 = match.groups()
inverse_operator = {
'>': '<=',
'<': '>=',
'<=': '>',
'>=': '<',
'=': '!=',
'==': '!=',
'!=': '==',
'≠': '=='
}.get(operator)
return f"while {operand1} {inverse_operator} {operand2}:"
def transpile(self, file, prepend_spec_code=False) -> str:
"""
"""
if isinstance(file, tuple):
files = file
else:
files = [file]
codebase = []
for f_ in files:
try:
path = pathlib.Path(f_)
if not path.exists():
path = path.with_suffix('.pseudo')
if not path.exists():
raise FileNotFoundError(f"You need to create a file called {path}")
try:
with open(path) as source:
# readin from source
pc = source.read()
except IsADirectoryError:
# just skip directories
pc = None
except TypeError:
# probably a StringIO or file object
pc = f_.read()
if pc is not None:
codebase.append(pc)
pseudocode = '\n'.join(codebase)
# change tabs to four spaces
code = pseudocode.replace(r'\t', " ")
# remove comments: TODO What if "//"" in string?
code = re.sub(r'//.*', '', code)
# change output keyword to output function (which is exec as print statement)
code = re.sub(r"\boutput (.*)", r"print(\1)", code)
# change out to output with end=""
code = re.sub(r"\bout (.*)", r'print(\1, end="")', code)
# change comparison with one = to ==, keeping "then" (removed in next)
code = re.sub("if (.*) ={1} (.*)", self.if_statement, code)
# change "else if" to "elif"
code = re.sub(r'\belse if (.*) then', r"elif \1:", code)
# add colon in else statements
code = re.sub(r"\belse\b", r"else:", code)
# change any if statements with "then"
code = re.sub(r"\bif (.*) then", r"if \1:", code)
# change any func statements with def ..() :
code = re.sub(r"\bsub\b(.*)", r"def \1:", code)
# just remove any "end" statements
code = re.sub(r"\bend .*", "", code)
# change loop with single = to ==
code = re.sub(r'\bloop\b.*', self.if_statement, code)
# change "loop while" to just "while"
code = re.sub(r'\bloop while (.*)', r"while \1:", code)
# change "loop until" to "while <inverse comparison>"
code = re.sub(r'\bloop until (.*) ([=><]{1,2}) (.*)', self.inverse_while, code)
# change loop until <expr>
code = re.sub(r'\bloop until (.*)', r'while not \1:', code)
# Python's range second param in non-inclusive, but IB spec is inclusive, so need extra handling here (hence the func)
code = re.sub("loop ([A-Z]+) from (.+) to (.+)", self.increment_second_range_param, code)
# standardize cases; TODO: What if user enters falSe?
code = re.sub(r"\b((NOT)|(AND)|(OR))\b", lambda m: m.group(1).lower(), code)
code = re.sub(r'\bfalse\b', 'False', code)
code = re.sub(r'\btrue\b', 'True', code)
code = re.sub(r'\bmod\b', '%', code)
code = re.sub(r'\bdiv\b', '/', code)
if prepend_spec_code:
# In case you want to manually add to top of file
with open(ib_specification_glue_code.__file__) as ib:
code = ib.read() + '\n' + code
return pseudocode, code
def execute_and_capture(self, code, pseudocode, **kwargs):
"""
Execute code but capture stdout and return that
"""
with stdoutIO() as captured:
error = self.execute(code, pseudocode, **kwargs)
return captured.getvalue(), error
def execute(self, code, pseudocode, lineoffset=0):
"""
Executes and outputs results to stdout
return true if error occurred and false if not
"""
ret = False
hand_off_globals = {
'Array': ib_specification_glue_code.Array,
'Stack': ib_specification_glue_code.Stack,
'Collection': ib_specification_glue_code.Collection,
'Queue': ib_specification_glue_code.Queue,
}
try:
exec(code, hand_off_globals)
except SyntaxError as err:
ret = True
pseudocode_lines = pseudocode.split('\n')
code_lines = code.split('\n')
error_class = err.__class__.__name__
detail = err.args[0]
line_number = err.lineno
pseudo_line = pseudocode_lines[line_number-1].strip()
transpiled_line = code_lines[line_number-1].strip()
# determine some common sytnax errors
if re.match(r'\b(while)|(until)\b', pseudo_line) and not re.match(r'\bloop\b', pseudo_line):
detail = "'loop' keyword expected, but not found"
if pseudo_line.lstrip().startswith('if ') and not pseudo_line.rstrip().endswith('then'):
detail = "'then' expected to end if statement, but not found"
if transpiled_line.rstrip().endswith('::'):
detail = "extra ':' found"
self.screen.output_to_screen(
self.screen.stylize_string(
f"Programming error on line {err.lineno+lineoffset}:",
fg='red')
)
self.screen.output_to_screen(
'\t' + self.screen.stylize_string(
pseudo_line,
fg="green"
) + " (pseudocode)"
)
self.screen.output_to_screen(
'\t' + self.screen.stylize_string(
transpiled_line,
fg="yellow"
) + " (python)"
)
self.screen.output_to_screen(
self.screen.stylize_string(
f"{error_class}: {detail}",
fg='red'
)
)
except Exception as err:
ret = True
pseudocode_lines = pseudocode.split('\n')
code_lines = code.split('\n')
error_class = err.__class__.__name__
detail = err.args[0]
cl, exc, tb = sys.exc_info()
# TODO: line_number in multi-files is incorrect
line_number = traceback.extract_tb(tb)[-1][1]
pseudo_line = pseudocode_lines[line_number-1].strip()
transpiled_line = code_lines[line_number-1].strip()
click.echo(click.style(f"Execution error on line {line_number+lineoffset}:", fg='red'))
click.echo('\t' + click.style(pseudo_line, fg="green") + " (pseudocode)")
click.echo('\t' + click.style(transpiled_line, fg="yellow") + " (python)")
click.echo(click.style(f"{error_class}: {detail}", fg='red'))
return ret
class CliGroup(click.Group):
def list_commands(self, _):
# only these ones
return ['transpile', 'execute', 'run']
class CliGroupRepl(CliGroup):
def collect_usage_pieces(self, ctx):
more = super().collect_usage_pieces(ctx)
return ['\b' * len('pseudo '), "cli('pseudo"] + more + ["')"]
@form_group(cls=CliGroupRepl if on_repl else CliGroup)
@pass_pseudo
def cli(app, *args, **kwargs):
app.obj = Transpiler(*args, **kwargs)
class CliCommandRepl(click.Command):
def collect_usage_pieces(self, ctx):
more = super().collect_usage_pieces(ctx)
return ['\b' * (len('psuedo ') + len(ctx.command.name + ' ')), "cli('pseudo " + ctx.command.name] + more + ["')"]
@cli.command('interface', cls=CliCommandRepl if on_repl else None, hidden=True)
@pass_pseudo
def interface(app):
res = {}
for command_name in cli.list_commands(app):
cmd = cli.get_command(app, command_name)
obj = {'help': cmd.help}
obj['params'] = []
for param in cmd.params:
if type(param) == click.core.Option and param.required:
obj['params'].append( (param.name, param.help) )
elif type(param) == click.core.Command:
obj['params'].append( (param.name, param.help) )
res[command_name] = obj
print(res) # plainly print it for parsing : BLECHT
@cli.command('transpile', cls=CliCommandRepl if on_repl else None)
@add_argument('file', nargs=-1)
@pass_pseudo
def transpile(app, file):
"""
Convert pseudocode in file and output
"""
_, code = app.obj.transpile(file)
app.obj.screen.output_to_screen(code)
@cli.command('execute', cls=CliCommandRepl if on_repl else None)
@add_argument('file', default=None, nargs=-1)
@pass_pseudo
def execute(app, *args, file=None, **kwargs):
"""
Executes Python code from pseudocode in file
"""
pseudocode, code = app.obj.transpile(*args, file=file, **kwargs)
app.obj.execute(code, pseudocode)
@cli.command('capture', cls=CliCommandRepl if on_repl else None)
@add_argument('file', default=None)
@pass_pseudo
def capture(app, *args, file=None, **kwargs):
pseudocode, code = app.obj.transpile(*args, file=file, **kwargs)
result = app.obj.execute_and_capture(code, pseudocode)
@cli.command('run', cls=CliCommandRepl if on_repl else None)
@add_option('-d', '--directory', default=None)
@pass_pseudo
def run(app, directory):
"""
Executes all, one by one
"""
if directory is None:
directory = os.getcwd()
enclosing = pathlib.Path(directory)
paths = list([str(e) for e in enclosing.glob("*.pseudo")])
paths.sort()
for i, c in enumerate(paths):
click.secho("=" * 5 + c.split("/")[-1] + "="*5, fg="green")
app.invoke(
execute,
file=c
)