-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
790 lines (694 loc) · 27.3 KB
/
main.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
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
import ast
import os
import sys
from typing import Union
def generate_error(kind, node):
message = f"(* At {kind}: unsupported node type: {type(node).__name__} *)"
if hasattr(node, "lineno") and hasattr(node, "col_offset"):
# Print the location information
print(
f"Line: {node.lineno}, Column: {node.col_offset}",
file=sys.stderr,
)
print(message, file=sys.stderr)
if kind == "expr":
return f"Constant.str \"{message}\""
return message
def generate_indent(indent):
return " " * indent
def generate_name(name):
reserved_names = {
"Definition",
"End",
"Import",
"in",
"left",
"Ltac",
"mod",
"Module",
"Parameter",
"Require",
"right",
"Set",
"Type",
}
if name in reserved_names:
return name + "_"
return name
def generate_constant(node, value):
if value is None:
return "Constant.None_"
elif value is True:
return "Constant.bool true"
elif value is False:
return "Constant.bool false"
elif isinstance(value, int):
return f"Constant.int {str(value)}"
elif isinstance(value, float):
return f"Constant.float \"{str(value)}\""
elif isinstance(value, str):
return "Constant.str \"" + value.replace("\"", "\"\"") + "\""
elif isinstance(value, bytes):
return "Constant.bytes \"" + value.hex() + "\""
elif value == ...:
return "Constant.ellipsis"
else:
return generate_error(f"constant {type(value)}", node)
def generate_mod(node: ast.mod):
if isinstance(node, ast.Module):
return "\n\n".join(generate_top_level_stmt(stmt) for stmt in node.body)
elif isinstance(node, ast.Interactive):
return generate_error("mod", node)
elif isinstance(node, ast.Interactive):
return generate_error("mod", node)
elif isinstance(node, ast.Interactive):
return generate_error("mod", node)
else:
return generate_error("mod", node)
def get_globals_of_import(node: ast.ImportFrom) -> str:
module = node.module.replace(".", "/") if node.module is not None else ""
# If this is an absolute import
if node.level == 0:
return module.replace("/", ".")
# If this is a relative path
actual_path = input_file_name
for _ in range(node.level):
actual_path = os.path.dirname(actual_path)
if module != "":
actual_path += "/" + module
return actual_path.replace("/", ".")
def generate_klass(
klass_name: str,
bases: list[str],
class_methods: list[tuple[str, str]],
methods: list[tuple[str, str]],
) -> str:
text = f"Definition {klass_name} : Value.t := "
text += "make_klass {|\n"
# Bases
text += generate_indent(1) + "Klass.bases := ["
not_first = False
for base in bases:
if not_first:
text += ";"
text += "\n"
text += generate_indent(2) + f"(globals, \"{base}\")"
not_first = True
text += "\n"
text += generate_indent(1) + "];\n"
# Class methods
text += generate_indent(1) + "Klass.class_methods := ["
not_first = False
for (name, body) in class_methods:
if not_first:
text += ";"
text += "\n"
text += generate_indent(2) + "(\n"
text += generate_indent(3) + f"\"{name}\"," + "\n"
text += generate_indent(3) + body + "\n"
text += generate_indent(2) + ")"
not_first = True
text += "\n"
text += generate_indent(1) + "];\n"
# Methods
text += generate_indent(1) + "Klass.methods := ["
not_first = False
for (name, body) in methods:
if not_first:
text += ";"
text += "\n"
text += generate_indent(2) + "(\n"
text += generate_indent(3) + f"\"{name}\"," + "\n"
text += generate_indent(3) + body + "\n"
text += generate_indent(2) + ")"
not_first = True
text += "\n"
text += generate_indent(1) + "];\n"
text += "|}."
return text
def generate_top_level_stmt(node: ast.stmt):
if isinstance(node, ast.FunctionDef):
return f"Definition {generate_name(node.name)} : Value.t -> Value.t -> M :=\n" + \
generate_indent(1) + generate_function_def_body(1, node) + ".\n\n" + \
f"Axiom {generate_name(node.name)}_in_globals :\n" +\
generate_indent(1) + \
f"IsInGlobals globals \"{node.name}\" (make_function {generate_name(node.name)})."
elif isinstance(node, ast.AsyncFunctionDef):
return generate_error("top_level_stmt", node)
elif isinstance(node, ast.ClassDef):
name = generate_name(node.name)
bases = [
generate_name(base.id)
if isinstance(base, ast.Name)
else generate_error("base", base)
for base in node.bases
]
class_methods = [
(stmt.name, generate_function_def_body(3, stmt))
for stmt in node.body
if isinstance(stmt, ast.FunctionDef) and len(stmt.decorator_list) == 1 and
isinstance(stmt.decorator_list[0], ast.Name) and
stmt.decorator_list[0].id == "classmethod"
]
methods = [
(stmt.name, generate_function_def_body(3, stmt))
for stmt in node.body
if isinstance(stmt, ast.FunctionDef) and len(stmt.decorator_list) == 0
]
# If the class is a `@dataclass`
if len(node.decorator_list) == 1 and \
isinstance(node.decorator_list[0], ast.Name) and \
node.decorator_list[0].id == "dataclass":
# TODO: add an `__init__` function, ...
pass
return generate_klass(name, bases, class_methods, methods)
elif isinstance(node, ast.Assign):
if len(node.targets) >= 2:
return generate_error("top_level_stmt", node)
target = node.targets[0]
if isinstance(target, ast.Name):
return "Definition " + target.id + \
" : Value.t := M.run ltac:(M.monadic (\n" + \
generate_indent(1) + generate_expr(1, False, node.value) + "\n" + \
"))."
return generate_error("top_level_stmt", node)
elif isinstance(node, ast.Import):
return generate_error("top_level_stmt", node)
elif isinstance(node, ast.ImportFrom):
module = get_globals_of_import(node)
snake_module = module.replace(".", "_")
return "\n".join(
f"Axiom {snake_module}_imports_{alias.name} :\n" +
generate_indent(1) +
f"IsImported globals \"{module}\" \"{alias.name}\"."
for alias in node.names
)
elif isinstance(node, ast.Global):
return generate_error("top_level_stmt", node)
elif isinstance(node, ast.Nonlocal):
return generate_error("top_level_stmt", node)
elif isinstance(node, ast.Expr):
return f"Definition expr_{node.lineno} : Value.t :=\n" + \
generate_indent(1) + generate_expr(1, False, node.value) + "."
else:
return generate_error("top_level_stmt", node)
def generate_function_def_body(indent, node):
params = "; ".join(f"\"{arg.arg}\"" for arg in node.args.args)
body = generate_stmts(indent + 1, node.body)
return "fun (args kwargs : Value.t) =>\n" + \
generate_indent(indent + 1) + \
f"let- locals_stack := M.create_locals locals_stack args kwargs [ {params} ] in\n" + \
generate_indent(indent + 1) + "ltac:(M.monadic (\n" + \
body + "))"
def generate_if_then_else(
indent,
condition: ast.expr,
success: Union[ast.expr, list[ast.stmt]],
error: Union[ast.expr, list[ast.stmt]],
):
return generate_indent(indent) + "(* if *)\n" + \
generate_indent(indent) + "M.if_then_else (|\n" + \
generate_indent(indent + 1) + generate_expr(indent + 1, False, condition) + ",\n" + \
generate_indent(indent) + "(* then *)\n" + \
generate_indent(indent) + "ltac:(M.monadic (\n" + \
(generate_expr(indent + 1, False, success)
if isinstance(success, ast.expr)
else generate_stmts(indent + 1, success)) + \
"\n" + \
generate_indent(indent) + "(* else *)\n" + \
generate_indent(indent) + ")), ltac:(M.monadic (\n" + \
(generate_expr(indent + 1, False, error)
if isinstance(error, ast.expr)
else generate_stmts(indent + 1, error)) + \
"\n" + \
generate_indent(indent) + ")) |)"
def generate_stmts(indent, nodes: list[ast.stmt]):
return "\n".join(
[generate_stmt(indent, stmt) for stmt in nodes] +
[generate_indent(indent) + "M.pure Constant.None_"]
)
def generate_stmt(indent, node: ast.stmt):
if isinstance(node, ast.FunctionDef):
return generate_error("stmt", node)
elif isinstance(node, ast.AsyncFunctionDef):
return generate_error("stmt", node)
elif isinstance(node, ast.ClassDef):
return generate_error("stmt", node)
elif isinstance(node, ast.Return):
return generate_indent(indent) + "let _ := M.return_ (|\n" + \
generate_indent(indent + 1) + \
(generate_expr(indent + 1, False, node.value)
if node.value is not None
else "Constant.None_") + \
"\n" + \
generate_indent(indent) + "|) in"
elif isinstance(node, ast.Delete):
return "\n".join(
generate_indent(indent) + "let _ := M.delete (| " +
generate_expr(1, False, target) + " |) in"
for target in node.targets
)
elif isinstance(node, ast.Assign):
if len(node.targets) >= 2:
return generate_error("stmt", node)
target = node.targets[0]
if isinstance(target, ast.Name):
return generate_indent(indent) + "let _ := M.assign_local (|\n" + \
generate_indent(indent + 1) + \
"\"" + target.id + "\" ,\n" + \
generate_indent(indent + 1) + \
generate_expr(indent + 1, False, node.value) + "\n" + \
generate_indent(indent) + "|) in"
return generate_indent(indent) + "let _ := M.assign (|\n" + \
generate_indent(indent + 1) + \
generate_expr(indent + 1, False, target) + ",\n" + \
generate_indent(indent + 1) + \
generate_expr(indent + 1, False, node.value) + "\n" + \
generate_indent(indent) + "|) in"
# elif isinstance(node, ast.TypeAlias):
# return generate_error("stmt", node)
elif isinstance(node, ast.AugAssign):
if isinstance(node.target, ast.Name):
return generate_indent(indent) + "let _ := M.assign_op_local (|\n" + \
generate_indent(indent + 1) + generate_operator(node.op) + ",\n" + \
generate_indent(indent + 1) + "\"" + node.target.id + "\",\n" + \
generate_indent(indent + 1) + generate_expr(1, False, node.value) + "\n" +\
generate_indent(indent) + "|) in"
return generate_indent(indent) + "let _ := M.assign_op (|\n" + \
generate_indent(indent + 1) + generate_operator(node.op) + ",\n" + \
generate_indent(indent + 1) + generate_expr(1, False, node.target) + ",\n" + \
generate_indent(indent + 1) + generate_expr(1, False, node.value) + "\n" +\
generate_indent(indent) + "|) in"
elif isinstance(node, ast.AnnAssign):
return generate_error("stmt", node)
elif isinstance(node, ast.For):
return generate_indent(indent) + "let _ :=\n" + \
generate_indent(indent + 1) + "M.for_ (|\n" + \
generate_indent(indent + 2) + generate_expr(2, False, node.target) + ",\n" + \
generate_indent(indent + 2) + generate_expr(2, False, node.iter) + ",\n" + \
generate_indent(indent + 2) + "ltac:(M.monadic (\n" + \
generate_stmts(indent + 3, node.body) + "\n" + \
generate_indent(indent + 2) + ")),\n" + \
generate_indent(indent + 2) + "ltac:(M.monadic (\n" + \
generate_stmts(indent + 3, node.orelse) + "\n" + \
generate_indent(indent + 2) + "))\n" + \
generate_indent(indent) + "|) in"
elif isinstance(node, ast.AsyncFor):
return generate_error("stmt", node)
elif isinstance(node, ast.While):
return generate_indent(indent) + "let _ :=\n" + \
generate_indent(indent + 1) + "M.while (|\n" + \
generate_indent(indent + 2) + generate_expr(2, False, node.test) + ",\n" + \
generate_indent(indent + 2) + "ltac:(M.monadic (\n" + \
generate_stmts(indent + 3, node.body) + "\n" + \
generate_indent(indent + 2) + ")),\n" + \
generate_indent(indent + 2) + "ltac:(M.monadic (\n" + \
generate_stmts(indent + 3, node.orelse) + "\n" + \
generate_indent(indent + 2) + "))\n" + \
generate_indent(indent) + "|) in"
elif isinstance(node, ast.If):
return generate_indent(indent) + "let _ :=\n" + \
generate_if_then_else(indent + 1, node.test, node.body, node.orelse) + \
" in"
elif isinstance(node, ast.With):
return generate_error("stmt", node)
elif isinstance(node, ast.AsyncWith):
return generate_error("stmt", node)
elif sys.version_info >= (3, 10) and isinstance(node, ast.Match):
return generate_error("stmt", node)
elif isinstance(node, ast.Raise):
return generate_indent(indent) + "let _ := M.raise (| " + \
("Some (" + generate_expr(indent, False, node.exc) + ")"
if node.exc is not None
else "None") + \
" |) in"
elif isinstance(node, ast.Try):
return generate_error("stmt", node)
# elif isinstance(node, ast.TryStar):
# return generate_error("stmt", node)
elif isinstance(node, ast.Assert):
return generate_indent(indent) + "let _ := M.assert (| " + \
generate_expr(1, False, node.test) + " |) in"
elif isinstance(node, ast.Import):
return generate_error("stmt", node)
elif isinstance(node, ast.ImportFrom):
return generate_error("stmt", node)
elif isinstance(node, ast.Global):
return generate_error("stmt", node)
elif isinstance(node, ast.Nonlocal):
return generate_error("stmt", node)
elif isinstance(node, ast.Expr):
return generate_indent(indent) + "let _ := " + generate_expr(1, False, node.value) + " in"
elif isinstance(node, ast.Pass):
return generate_indent(indent) + "let _ := M.pass (| |) in"
elif isinstance(node, ast.Break):
return generate_indent(indent) + "let _ := M.break (| |) in"
elif isinstance(node, ast.Continue):
return generate_indent(indent) + "let _ := M.continue (| |) in"
else:
return generate_error("stmt", node)
def paren(is_with_paren, text):
return "(" + text + ")" if is_with_paren else text
def generate_bool_op(indent, is_with_paren, op, nodes):
if len(nodes) == 0:
return generate_error("expr", nodes)
elif len(nodes) == 1:
return generate_expr(indent, False, nodes[0])
return paren(
is_with_paren,
op + " (|\n" +
generate_indent(indent + 1) +
generate_expr(indent + 1, False, nodes[0]) + ",\n" +
generate_indent(indent + 1) + "ltac:(M.monadic (\n" +
generate_indent(indent + 2) +
generate_bool_op(indent + 2, False, op, nodes[1:]) + "\n" +
generate_indent(indent + 1) + "))\n" +
generate_indent(indent) + "|)"
)
def generate_compare(indent, is_with_paren, op, left, right):
return paren(
is_with_paren,
generate_cmpop(op) + " (|\n" +
generate_indent(indent + 1) +
generate_expr(indent + 1, False, left) + ",\n" +
generate_indent(indent + 1) +
generate_expr(indent + 1, False, right) + "\n" +
generate_indent(indent) + "|)"
)
def generate_compares(indent, is_with_paren, left, ops, comparators):
if len(ops) == 0:
raise ValueError("No comparison operators provided")
elif len(ops) == 1:
return generate_compare(indent, is_with_paren, ops[0], left, comparators[0])
return paren(
is_with_paren,
"BoolOp.and (|\n" +
generate_indent(indent + 1) +
generate_compare(indent + 1, is_with_paren, ops[0], left, comparators[0]) + ",\n" +
generate_indent(indent + 1) + "ltac:(M.monadic (\n" +
generate_indent(indent + 2) +
generate_compares(indent + 2, False, comparators[0], ops[1:], comparators[1:]) +
"\n" +
generate_indent(indent + 1) + "))\n" +
generate_indent(indent) + "|)"
)
def generate_single_list_or_node(indent, is_with_paren, nodes):
if isinstance(nodes, list):
return paren(
is_with_paren,
"make_list [\n" +
';\n'.join(
generate_indent(indent + 1) +
generate_expr(indent + 1, False, node)
for node in nodes
) + "\n" +
generate_indent(indent) + "]"
)
# In this case the [nodes] expression represents a list, but is not syntactically as
# a list.
return generate_expr(indent, is_with_paren, nodes)
def generate_list(indent, is_with_paren, nodes):
lists_to_concat = []
current_list = []
for node in nodes:
if isinstance(node, ast.Starred):
if len(current_list) > 0:
lists_to_concat.append(current_list)
lists_to_concat.append(node.value)
current_list = []
else:
current_list.append(node)
if len(current_list) > 0:
lists_to_concat.append(current_list)
if len(lists_to_concat) == 0:
return paren(
is_with_paren,
"make_list []"
)
elif len(lists_to_concat) == 1:
return generate_single_list_or_node(indent, is_with_paren, lists_to_concat[0])
return paren(
is_with_paren,
"make_list_concat (| [\n" +
';\n'.join(
generate_indent(indent + 1) +
generate_single_list_or_node(indent + 1, False, list_to_concat)
for list_to_concat in lists_to_concat
) + "\n" +
generate_indent(indent) + "] |)"
)
def generate_expr(indent, is_with_paren, node: ast.expr):
if isinstance(node, ast.BoolOp):
return generate_bool_op(
indent, is_with_paren, generate_boolop(node.op), node.values
)
elif isinstance(node, ast.NamedExpr):
return generate_error("expr", node)
elif isinstance(node, ast.BinOp):
return paren(
is_with_paren,
generate_operator(node.op) + " (|\n" +
generate_indent(indent + 1) +
generate_expr(indent + 1, False, node.left) + ",\n" +
generate_indent(indent + 1) +
generate_expr(indent + 1, False, node.right) + "\n" +
generate_indent(indent) + "|)"
)
elif isinstance(node, ast.UnaryOp):
return paren(
is_with_paren,
generate_unaryop(node.op) + " (| " +
generate_expr(indent, False, node.operand) +
" |)"
)
elif isinstance(node, ast.Lambda):
return paren(
is_with_paren,
f"fun (args kwargs : Value.t) => {generate_expr(indent, False, node.body)}"
)
elif isinstance(node, ast.IfExp):
return paren(
is_with_paren,
generate_if_then_else(indent, node.test, node.body, node.orelse)
)
elif isinstance(node, ast.Dict):
return generate_error("expr", node)
elif isinstance(node, ast.Set):
return generate_error("expr", node)
elif isinstance(node, ast.ListComp):
return generate_error("expr", node)
elif isinstance(node, ast.SetComp):
return generate_error("expr", node)
elif isinstance(node, ast.DictComp):
return generate_error("expr", node)
elif isinstance(node, ast.GeneratorExp):
return generate_error("expr", node)
elif isinstance(node, ast.Await):
return paren(
is_with_paren,
f"M.await (| {generate_expr(indent, False, node.value)} |)"
)
elif isinstance(node, ast.Yield):
return paren(
is_with_paren,
"M.yield (| " +
(generate_expr(indent, False, node.value)
if node.value is not None
else "Constant.None_") +
" |)"
)
elif isinstance(node, ast.YieldFrom):
return paren(
is_with_paren,
f"M.yield_from (| {generate_expr(indent, False, node.value)} |)"
)
elif isinstance(node, ast.Compare):
return generate_compares(
indent, is_with_paren, node.left, node.ops, node.comparators
)
elif isinstance(node, ast.Call):
return paren(
is_with_paren,
"M.call (|\n" +
generate_indent(indent + 1) + generate_expr(indent + 1, False, node.func) +
",\n" +
generate_indent(indent + 1) +
generate_list(indent + 1, False, node.args) + ",\n" +
generate_indent(indent + 1) + "make_dict []\n" +
generate_indent(indent) + "|)"
)
elif isinstance(node, ast.FormattedValue):
return generate_error("expr", node)
elif isinstance(node, ast.JoinedStr):
return generate_error("expr", node)
elif isinstance(node, ast.Constant):
return paren(
is_with_paren,
generate_constant(node, node.value)
)
elif isinstance(node, ast.Attribute):
return paren(
is_with_paren,
f"M.get_field (| {generate_expr(indent, False, node.value)}, \"{node.attr}\" |)"
)
elif isinstance(node, ast.Subscript):
slice = node.slice
if isinstance(slice, ast.Slice):
return paren(
is_with_paren,
"M.slice (|\n" +
generate_indent(indent + 1) +
generate_expr(indent + 1, False, node.value) + ",\n" +
generate_indent(indent + 1) +
(generate_expr(indent + 1, False, slice.lower)
if slice.lower is not None
else "Constant.None_") + ",\n" +
generate_indent(indent + 1) +
(generate_expr(indent + 1, False, slice.upper)
if slice.upper is not None
else "Constant.None_") + ",\n" +
generate_indent(indent + 1) +
(generate_expr(indent + 1, False, slice.step)
if slice.step is not None
else "Constant.None_") + "\n" +
generate_indent(indent) + "|)"
)
return paren(
is_with_paren,
"M.get_subscript (|\n" +
generate_indent(indent + 1) +
generate_expr(indent + 1, False, node.value) + ",\n" +
generate_indent(indent + 1) +
generate_expr(indent + 1, False, slice) + "\n" +
generate_indent(indent) + "|)"
)
elif isinstance(node, ast.Starred):
# We should handle this kind of expression as part of the enclosing expression
return generate_error("expr", node)
elif isinstance(node, ast.Name):
return paren(
is_with_paren,
f"M.get_name (| globals, locals_stack, \"{node.id}\" |)"
)
elif isinstance(node, ast.List):
return generate_list(indent, is_with_paren, node.elts)
elif isinstance(node, ast.Tuple):
return paren(
is_with_paren,
"make_tuple [ " +
"; ".join(generate_expr(indent, False, elt) for elt in node.elts) +
" ]"
)
elif isinstance(node, ast.Slice):
# This case is supposed to only appear as part of a Subscript node, so we
# do not handle it here.
return paren(
is_with_paren,
"M.slice (| " +
(generate_expr(indent, False, node.lower)
if node.lower is not None
else "Constant.None_") +
", " +
(generate_expr(indent, False, node.upper)
if node.upper is not None
else "Constant.None_") +
" |)"
)
else:
return generate_error("expr", node)
def generate_boolop(node):
if isinstance(node, ast.And):
return "BoolOp.and"
elif isinstance(node, ast.Or):
return "BoolOp.or"
else:
return generate_error("boolop", node)
def generate_operator(node):
if isinstance(node, ast.Add):
return "BinOp.add"
elif isinstance(node, ast.Sub):
return "BinOp.sub"
elif isinstance(node, ast.Mult):
return "BinOp.mult"
elif isinstance(node, ast.MatMult):
return "BinOp.mat_mult"
elif isinstance(node, ast.Div):
return "BinOp.div"
elif isinstance(node, ast.Mod):
return "BinOp.mod_"
elif isinstance(node, ast.Pow):
return "BinOp.pow"
elif isinstance(node, ast.LShift):
return "BinOp.l_shift"
elif isinstance(node, ast.RShift):
return "BinOp.r_shift"
elif isinstance(node, ast.BitOr):
return "BinOp.bit_or"
elif isinstance(node, ast.BitXor):
return "BinOp.bit_xor"
elif isinstance(node, ast.BitAnd):
return "BinOp.bit_and"
elif isinstance(node, ast.FloorDiv):
return "BinOp.floor_div"
else:
return generate_error("operator", node)
def generate_unaryop(node):
if isinstance(node, ast.Invert):
return "UnOp.invert"
elif isinstance(node, ast.Not):
return "UnOp.not"
elif isinstance(node, ast.UAdd):
return "UnOp.add"
elif isinstance(node, ast.USub):
return "UnOp.sub"
else:
return generate_error("unaryop", node)
def generate_cmpop(node):
if isinstance(node, ast.Eq):
return "Compare.eq"
elif isinstance(node, ast.NotEq):
return "Compare.not_eq"
elif isinstance(node, ast.Lt):
return "Compare.lt"
elif isinstance(node, ast.LtE):
return "Compare.lt_e"
elif isinstance(node, ast.Gt):
return "Compare.gt"
elif isinstance(node, ast.GtE):
return "Compare.gt_e"
elif isinstance(node, ast.Is):
return "Compare.is"
elif isinstance(node, ast.IsNot):
return "Compare.is_not"
elif isinstance(node, ast.In):
return "Compare.in_"
elif isinstance(node, ast.NotIn):
return "Compare.not_in"
else:
return generate_error("cmpop", node)
def generate_arg(node):
return generate_name(node.arg)
input_file_name = sys.argv[1]
output_file_name = "../../CoqOfPython/" + input_file_name.replace(".py", ".v")
print(f"Processing {input_file_name} -> {output_file_name}")
file_content = open(input_file_name).read()
parsed_tree = ast.parse(file_content)
globals = input_file_name.replace("/", ".").replace(".py", "")
# Generate Coq code from the AST
coq_code = f"""Require Import CoqOfPython.CoqOfPython.
Definition globals : Globals.t := "{globals}".
Definition locals_stack : list Locals.t := [].
{generate_mod(parsed_tree)}
"""
# Ensure that the directory exists
output_directory = os.path.dirname(output_file_name)
if not os.path.exists(output_directory):
os.makedirs(output_directory)
# Output the generated Coq code only if the content changed
if os.path.exists(output_file_name):
with open(output_file_name, "r") as output_file:
if output_file.read() == coq_code:
sys.exit(0)
with open(output_file_name, "w") as output_file:
output_file.write(coq_code)
# print(ast.dump(parsed_tree, indent=4))