-
Notifications
You must be signed in to change notification settings - Fork 0
/
compiler.py
2564 lines (2150 loc) · 82.1 KB
/
compiler.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
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import ast
import pprint
import unittest
from dataclasses import dataclass
from typing import Dict, List, Optional, Union
from pytezos.context.impl import ExecutionContext
from pytezos.michelson.instructions.adt import *
from pytezos.michelson.instructions.arithmetic import *
from pytezos.michelson.instructions.control import *
from pytezos.michelson.instructions.stack import *
from pytezos.michelson.instructions.struct import *
from pytezos.michelson.micheline import MichelsonRuntimeError
from pytezos.michelson.program import *
from pytezos.michelson.repl import InterpreterResult
from pytezos.michelson.sections import CodeSection
from pytezos.michelson.sections.parameter import ParameterSection
from pytezos.michelson.sections.storage import StorageSection
from pytezos.michelson.stack import MichelsonStack
from pytezos.michelson.types import core
from pytezos.michelson.types.core import *
from pytezos.michelson.types.domain import AddressType
from pytezos.michelson.types.map import MapType
from pytezos.michelson.types.operation import *
from pytezos.michelson.types.pair import PairType
from pytezos import ContractInterface
import instr_types as t
from compiler_backend import CompilerBackend
from macro_expander import macro_expander
from helpers import Tree, ast_to_tree
from vm_types import (Array, Contract, Entrypoint, FunctionPrototype, Instr,
Pair, Some)
class CompilerError(Exception):
"""Raised when the compiler fails
Attributes:
message -- error message
"""
def __init__(self, message):
self.message = message
def debug(cb):
def f(*args, **kwargs):
self = args[0]
if self.isDebug:
print(cb.__name__)
return cb(*args, **kwargs)
return f
def Comment(msg: str):
return Instr("COMMENT", [msg], {})
class Record(Tree):
def __init__(self, attribute_names, attribute_types, attribute_annotations):
self.attribute_names = attribute_names
self.attribute_types = attribute_types
self.attribute_annotations = attribute_annotations
def make_node(self, left, right):
return Pair(car=left, cdr=right)
def get_type(self, i=0, acc=None):
attribute_type = self.attribute_types[i]
if acc == None:
acc = self.make_node(None, None)
if i == 0:
return self.make_node(attribute_type, self.get_type(i+1))
elif i == len(self.attribute_types) - 1:
return attribute_type
else:
return self.make_node(attribute_type, self.get_type(i+1))
def get_attribute_type(self, attribute_name: str):
attribute_index = self.attribute_names.index(attribute_name)
return self.attribute_types[attribute_index]
def get_attribute_annotation(self, attribute_name: str):
attribute_index = self.attribute_names.index(attribute_name)
return self.attribute_annotations[attribute_index]
def navigate_to_tree_leaf(self, attribute_name, acc=None):
el_number = 1
for i, candidate in enumerate(self.attribute_names):
if i == len(self.attribute_names) - 1:
el_number = 2 * i
elif attribute_name == candidate:
el_number = 2 * i + 1
break
return [Instr("GET", [t.Int(), el_number], {})]
def update_tree_leaf(self, attribute_name, e):
el_number = 1
for i, candidate in enumerate(self.attribute_names):
if i == len(self.attribute_names) - 1:
el_number = 2 * i
elif attribute_name == candidate:
el_number = 2 * i + 1
break
e.sp -= 1 # account for update
return [Instr("UPDATE", [t.Int(), el_number], {})]
def compile_record(self, attribute_values, compile_function, env):
instructions = []
for attribute_value, attribute_type in zip(reversed(attribute_values), reversed(self.attribute_types)):
instructions += compile_function(attribute_value, env, current_type=attribute_type)
env.sp -= len(attribute_values) - 1
return instructions + [Instr("PAIR", [len(attribute_values)], {})]
@dataclass
class Env:
vars: Dict[str, int]
sp: int
args: Dict[str, List[str]]
records: Dict[str, Record]
types: Dict[str, str]
def copy(self):
return Env(
self.vars.copy(),
self.sp,
self.args.copy(),
self.records.copy(),
self.types.copy(),
)
class Compiler:
def __init__(self, src: str, isDebug=False):
self.ast = ast.parse(src)
self.isDebug = isDebug
self.type_parser = t.TypeParser()
self.contract = Contract(
storage_type=t.Int(),
storage=0,
entrypoints={},
instructions=[],
)
def print_ast(self):
print(pprint.pformat(ast_to_tree(self.ast)))
def compile_module(self, m: ast.Module, e: Env) -> List[Instr]:
instructions: List[Instr] = []
for key, value in ast.iter_fields(m):
if key == "body":
for childNode in value:
if type(childNode) == ast.ClassDef:
if childNode.name == "Contract":
instructions += self._compile(childNode, e, instructions)
else:
instructions += self._compile(childNode, e)
else:
instructions += self._compile(childNode, e)
return instructions
def _compile_reassign(self, reassign_ast: ast.Assign, e: Env) -> List[Instr]:
instructions: List[Instr] = []
var_name = reassign_ast.targets[0]
value = reassign_ast.value
var_addr = e.vars[var_name.id]
instructions = self._compile(value, e)
free_vars_instructions, _ = self.free_var(var_name.id, e)
instructions = instructions + free_vars_instructions + [
Instr("DUG", [e.sp - var_addr], {}),
]
e.vars[var_name.id] = var_addr
try:
if reassign_ast.value.func.id in e.records:
e.types[var_name.id] = reassign_ast.value.func.id
except:
pass
try:
print_val = value.value
except:
print_val = "[object]"
return [Comment(f"Reassigning {var_name.id} = {print_val}")] + instructions
@debug
def compile_assign_storage_attribute(self, assign_ast: ast.Assign, e: Env) -> List[Instr]:
new_ast = ast.Assign(
targets=[
ast.Attribute(value=ast.Name(id='__STORAGE__', ctx=ast.Load()), attr=assign_ast.targets[0].attr, ctx=ast.Store())
],
value=assign_ast.value,
type_comment=None,
)
return self.compile_assign(new_ast, e)
def compile_dict(self, dict_ast: ast.Dict, key_type: t.Type, value_type: t.Type, e: Env) -> List[Instr]:
e.sp += 1 # account for pushing dict
return [Instr("EMPTY_MAP", [key_type, value_type], {})]
def compile_literal(self, literal, e: Env) -> List[Instr]:
if type(literal) == ast.Dict:
return self.compile_dict(literal, e)
else:
return self.compile_expr(literal, e)
def _is_literal(self, literal_ast):
if type(literal_ast) == ast.Dict:
return True
else:
return False
@debug
def compile_ann_assign(self, assign: ast.AnnAssign, e: Env) -> List[Instr]:
try:
# is reassignment
if assign.targets[0].id in e.vars.keys():
raise CompilerError("Cannot reassign with annotation")
except:
pass
instructions: List[Instr] = []
var_name = assign.target
if self._is_literal(assign.value):
compiled_value = self.compile_literal(assign.value, e)
else:
compiled_value = self._compile(assign.value, e)
value = assign.value
instructions = self._compile(var_name, e) + compiled_value
e.vars[var_name.id] = e.sp
try:
if assign.value.func.id in e.records:
e.types[var_name.id] = assign.value.func.id
except:
pass
try:
print_val = value.value
except:
print_val = "[object]"
return [Comment(f"{var_name.id} = {print_val}")] + instructions
def _get_assign_subscript_target_addr(self, node) -> str:
if type(node) == ast.Name:
return node.id
if type(node) == ast.Attribute:
current_node = node
while 1:
if type(current_node.value) == ast.Attribute:
current_node = current_node.value
elif type(current_node.value) == ast.Name:
return node.value.id
else:
raise NotImplementedError
raise NotImplementedError
def _fetch_variable(self, var_name: str, e: Env) -> List[Instr]:
jump_length = e.sp - e.vars[var_name]
e.sp += 1
return [
Instr("DIG", [jump_length], {}),
Instr("DUP", [], {}),
Instr("DUG", [jump_length + 1], {}),
]
@debug
def compile_assign_subscript(self, assign_subscript: ast.Assign, e: Env) -> List[Instr]:
if type(assign_subscript.targets[0].value) == ast.Attribute:
record_spec = self._get_record_spec(assign_subscript.targets[0].value, e)
# fetch the dictionary
#fetch_dict_bk = self._fetch_variable(record_spec["attribute_names"][0], e)
dictionary = self._get_record_with_replace(record_spec, e) + [Instr("DUP", [], {})] + record_spec["records"][-1].navigate_to_tree_leaf(record_spec["attribute_names"][-1])
e.sp += 1 # account for DUP
value = self._compile(assign_subscript.value, e)
key = self._compile(assign_subscript.targets[0].slice.value, e)
update_dictionary = dictionary + value + [Instr("SOME", [], {})] + key + [Instr("UPDATE", [], {})]
e.sp -= 2 # account for update dropping the key and value from the stack
# set the record
set_dictionary = self._set_record(record_spec, e)
var_name = record_spec["attribute_names"][0]
return update_dictionary + set_dictionary + self._replace_var(var_name, e)
else:
dictionary = self._compile(assign_subscript.targets[0].value, e)
value = self._compile(assign_subscript.value, e)
key = self._compile(assign_subscript.targets[0].slice.value, e)
e.sp -= 2 # account for update dropping the key and value from the stack
#dictionary_name = assign_subscript.targets[0].value.id
dictionary_name = self._get_assign_subscript_target_addr(assign_subscript.targets[0].value)
update_dictionary = dictionary + value + [Instr("SOME", [], {})] + key + [Instr("UPDATE", [], {})]
dict_addr = e.vars[dictionary_name]
free_old_dict, _ = self.free_var(dictionary_name, e)
replace_old_dict = [Instr("DUG", [e.sp - dict_addr], {})]
e.vars[dictionary_name] = dict_addr
return update_dictionary + free_old_dict + replace_old_dict
def _get_record_spec(self, node: ast.Attribute, e: Env):
acc = []
cond = True
attribute_names = []
current_node = node
while cond:
if type(current_node.value) == ast.Attribute:
acc.append(current_node.attr)
current_node = current_node.value
pass
elif type(current_node.value) == ast.Name:
acc.append(current_node.attr)
acc.append(current_node.value.id)
cond = False
else:
cond = False
acc.reverse()
records = []
for i, el in enumerate(acc[:-1]):
if i == 0:
record_type_name = e.types[el]
records.append(e.records[record_type_name])
else:
index = None
current_record = records[-1]
for i, attribute_name in enumerate(current_record.attribute_names):
if attribute_name == el:
index = i
nested_record_type = current_record.attribute_annotations[index].id
records.append(e.records[nested_record_type])
return {"attribute_names": acc, "records": records}
def _get_record_with_replace(self, record_spec, e: Env) -> List[Instr]:
attribute_names = record_spec["attribute_names"]
records = record_spec["records"]
instructions = self._compile(ast.Name(attribute_names[0], ctx=ast.Load()), e)
for i in range(len(records[:-1])):
instructions += [Instr("DUP", [], {})]
e.sp += 1
record = records[i]
attr_name = attribute_names[i + 1]
instructions += record.navigate_to_tree_leaf(attr_name)
return instructions
def _set_record(self, record_spec, e: Env) -> List[Instr]:
attribute_names = record_spec["attribute_names"]
records = record_spec["records"]
instructions = []
for i in range(len(records)):
reversed_i = len(records) - 1 - i
record = records[reversed_i]
attr_name = attribute_names[reversed_i + 1]
instructions += record.update_tree_leaf(attr_name, e)
return instructions
def _replace_var(self, var_name: str, e: Env) -> List[Instr]:
# override new record with old record
old_record_location = e.vars[var_name]
free_old_record, _ = self.free_var(var_name, e)
move_back_new_record= [
Instr("DUG", [e.sp - old_record_location], {}),
]
e.vars[var_name] = old_record_location
return free_old_record + move_back_new_record
@debug
def compile_assign_record(self, node: ast.Assign, e: Env) -> List[Instr]:
record_spec = self._get_record_spec(node.targets[0], e)
attribute_names = record_spec["attribute_names"]
var_name = attribute_names[0]
instructions = self._get_record_with_replace(record_spec, e)
instructions += self._compile(node.value, e)
instructions += self._set_record(record_spec, e)
instructions += self._replace_var(var_name, e)
return instructions
@debug
def compile_assign(self, assign: ast.Assign, e: Env) -> List[Instr]:
# Handle storage assignments
try:
cond1 = assign.targets[0].value.value.id == "self"
cond2 = assign.targets[0].value.attr == "storage"
if cond1 and cond2:
return self.compile_assign_storage_attribute(assign, e)
except:
pass
# Handle reassignments
try:
if assign.targets[0].id in e.vars.keys():
return self._compile_reassign(assign, e)
except:
pass
# Handle subscript assignments
if type(assign.targets[0]) == ast.Subscript:
return self.compile_assign_subscript(assign, e)
# Handle record key assignments
if type(assign.targets[0]) == ast.Attribute:
return self.compile_assign_record(assign, e)
instructions: List[Instr] = []
var_name = assign.targets[0]
if self._is_literal(assign.value):
compiled_value = self.compile_literal(assign.value, e)
else:
compiled_value = self._compile(assign.value, e)
value = assign.value
instructions = self._compile(var_name, e) + compiled_value
e.vars[var_name.id] = e.sp
try:
if assign.value.func.id in e.records:
e.types[var_name.id] = assign.value.func.id
except:
pass
try:
print_val = value.value
except:
print_val = "[object]"
return [Comment(f"{var_name.id} = {print_val}")] + instructions
@debug
def compile_expr(self, expr: ast.Expr, e: Env) -> List[Instr]:
return self._compile(expr.value, e)
def _is_string_address(self, string: str) -> bool:
is_tz_address = len(string) == 36 and string[:2] == "tz"
is_kt_address = len(string) == 36 and string[:2] == "KT"
return is_tz_address or is_kt_address
@debug
def compile_constant(self, constant: ast.Constant, e: Env, force_type = None) -> List[Instr]:
e.sp += 1 # Account for PUSH
constant_type: t.Type = t.Int()
if force_type != None:
constant_type = force_type
elif type(constant.value) == str:
if self._is_string_address(constant.value):
constant_type = t.Address()
else:
constant_type = t.String()
elif type(constant.value) == int:
constant_type = t.Int()
elif type(constant.value) == bool:
constant_type = t.Bool()
else:
raise NotImplementedError
return [
Instr("PUSH", [constant_type, constant.value], {}),
]
@debug
def compile_name(self, name: ast.Name, e: Env) -> List[Instr]:
if name.id == "SENDER":
return self.get_sender(name, e)
var_name = name
if type(name.ctx) == ast.Load:
var_addr = e.vars[var_name.id]
jump_length = e.sp - var_addr
comment = [
Comment(
f"Loading {var_name.id} at {var_addr}, e.sp = {e.sp}, jump = {jump_length}"
)
]
instructions = [
Instr("DIG", [jump_length], {}),
Instr("DUP", [], {}),
Instr("DUG", [jump_length + 1], {}),
]
e.sp += 1 # Account for DUP
return comment + instructions
elif type(name.ctx) == ast.Store:
# will get set to actual value in `compile_assign`
e.vars[var_name.id] = 42
return []
else:
raise NotImplementedError
@debug
def compile_binop(self, t: ast.BinOp, e: Env) -> List[Instr]:
left = self._compile(t.right, e)
right = self._compile(t.left, e)
op = self._compile(t.op, e)
return left + right + op
@debug
def compile_sub(self, t: ast.Sub, e: Env) -> List[Instr]:
e.sp -= 1 # Account for SUB
return [
Instr("SUB", [], {}),
]
@debug
def compile_add(self, t: ast.Add, e: Env) -> List[Instr]:
e.sp -= 1 # Account for ADD
return [
Instr("ADD", [], {}),
]
@debug
def create_list(self, e: Env) -> List[Instr]:
e.sp += 1 # Account for pushing list
return [
Instr("NIL", [t.Int()], {}),
]
@debug
def append_before_list_el(self, el, e) -> List[Instr]:
# no sp chage b/c they cancel out btwn the two instructions
return self._compile(el, e) + [Instr("CONS", [], {})]
@debug
def compile_list(self, l: ast.List, e: Env) -> List[Instr]:
e.sp += 1 # Account for pushing list
instructions = self.create_list(e)
for el in reversed(l.elts):
instructions += self.append_before_list_el(el, e)
return instructions
def free_var(self, var_name, e: Env):
var_location = e.vars[var_name]
comment = [Comment(f"Freeing var {var_name} at {var_location}, e.sp = {e.sp}")]
jump = e.sp - var_location
e.sp -= 1 # account for freeing var
del e.vars[var_name]
return (
comment
+ [
Instr(
"DIP",
[
jump,
[
Instr("DROP", [], {}),
],
],
{},
),
],
e,
)
def _get_function_prototype(self, f: ast.FunctionDef, e: Env) -> FunctionPrototype:
return FunctionPrototype(
self.type_parser.parse(f.args.args[0].annotation, e),
self.type_parser.parse(f.returns, e),
)
@debug
def compile_defun(self, f: ast.FunctionDef, e: Env) -> List[Instr]:
e.sp += 1 # account for body push
e.vars[f.name] = e.sp
for arg_ast in f.args.args:
e.args[f.name] = arg_ast.arg
# type argument
if type(arg_ast.annotation) == ast.Name:
if arg_ast.annotation.id in e.records:
e.types[arg_ast.arg] = arg_ast.annotation.id
prototype = self._get_function_prototype(f, e)
arg_type, return_type = prototype.arg_type, prototype.return_type
# get init env keys
init_var_names = set(e.vars.keys())
# We work on an env copy to prevent from polluting the environment
# with vars that we'd need to remove.
func_env = e.copy()
# store argument in env
for arg_ast in f.args.args:
func_env.sp += 1
func_env.vars[arg_ast.arg] = func_env.sp
body_instructions = self._compile_block(f.body, func_env)
# freeing the argument
body_instructions += self.free_var(f.args.args[0].arg, func_env)[0]
comment = [Comment(f"Storing function {f.name} at {e.vars[f.name]}")]
return comment + [
Instr(
"LAMBDA",
[arg_type, return_type, body_instructions],
{},
),
]
@debug
def compile_ccall(self, c: ast.Call, e: Env):
"""Call to class constructor"""
instructions = e.records[c.func.id].compile_record(c.args, self._compile, e)
return instructions
def _compile_dict_safe_get(self, key, default, e: Env) -> List[Instr]:
# dictionary = self._compile(subscript.value, e)
key = self._compile(key, e)
# get_instructions = self._compile_get_subscript(e)
# return dictionary + key + get_instructions
e.sp -= 1 # account for get
if_not_env = e.copy()
if_not_env.sp -= 1 # account for if none
default = self._compile(default, if_not_env)
return key + [
Instr("GET", [], {}),
Instr("IF_NONE", [default, []], {}),
]
def _initialize_operations(self, e: Env) -> List[Instr]:
instructions = []
if "__OPERATIONS__" not in e.vars:
instructions += [
Instr("NIL", [t.Operation()], {})
]
e.sp += 1 # account for pushing empty list
e.vars["__OPERATIONS__"] = e.sp
return instructions
def _compile_transaction(self, f: ast.Call, e: Env) -> List[Instr]:
# fetch the operation list
instructions = self._fetch_variable("__OPERATIONS__", e)
# create the transaction
for arg in f.args:
instructions += self._compile(arg, e)
# add the transaction to the list
instructions += [
Instr("TRANSFER_TOKENS", [], {}),
Instr("CONS", [], {}),
]
e.sp -= 2 # account for transfer_tokens
e.sp -= 1 # account for cons
# replace __OPERATIONS__
operations_addr = e.vars["__OPERATIONS__"]
free_old_ops_instructions, e = self.free_var("__OPERATIONS__", e)
instructions += free_old_ops_instructions
instructions += [
Instr("DUG", [e.sp - operations_addr], {}),
]
e.vars["__OPERATIONS__"] = operations_addr
return instructions
def _compile_mutez(self, f: ast.Call, e: Env) -> List[Instr]:
return self.compile_constant(f.args[0], e, force_type=t.Mutez())
@debug
def compile_fcall(self, f: ast.Call, e: Env):
# check if we are calling .dict on a dictionary
if type(f.func) == ast.Attribute and f.func.attr == "get":
instructions = self._compile(f.func.value, e)
instructions += self._compile_dict_safe_get(f.args[0], f.args[1], e)
return instructions
# check if we are calling transaction
if f.func.id == "transaction":
return self._compile_transaction(f, e)
# check if we are instantiating a mutez
if f.func.id == "mutez":
return self._compile_mutez(f, e)
# if dealing with a record instantiation, compile as such
if f.func.id in e.records.keys():
return self.compile_ccall(f, e)
func_addr = e.vars[f.func.id]
jump_length = e.sp - func_addr
comment = [
Comment(f"Moving to function {f.func.id} at {func_addr}, e.sp = {e.sp}")
]
load_function = [
Instr("DIG", [jump_length], {}),
Instr("DUP", [], {}),
Instr("DUG", [jump_length + 1], {}),
]
e.sp += 1 # Account for DUP
# fetch arg name for function
load_arg = self._compile(f.args[0], e)
e.sp += 1 # Account for pushing argument
execute_function = [Instr("EXEC", [], {})]
e.sp -= 2 # Account popping EXEC and LAMBDA
instr = comment + load_function + load_arg + execute_function
return instr
@debug
def compile_return(self, r: ast.FunctionDef, e: Env):
return self._compile(r.value, e)
def get_init_env(self):
return Env({}, -1, {}, {}, {})
@debug
def compile_entrypoint(self, f: ast.FunctionDef, e: Env, prologue_instructions: List[Instr]) -> List[Instr]:
e = e.copy()
# we update the variable pointers to account for the fact that the first
# element on the stack is Pair(param, storage).
# we are targetting a stack that will look like [storage, {prologue_instructions}, param]
# hence, we need to add 1 to all the addresses of the variables in `prologue_instructions`
e.vars = {var_name: address + 1 for var_name, address in e.vars.items()}
e.sp += 1 # account for pushing Pair(param, storage)
e.sp += 1 # account for breaking up Pair(param, storage)
# Save the storage and entrypoint argument on the stack
self.contract.instructions = [
Instr("DUP", [], {}), # [Pair(param, storage), Pair(param, storage)]
Instr("CDR", [], {}), # [Pair(param, storage), storage]
Instr("DUG", [1], {}), # [storage, Pair(param, storage)]
Instr("CAR", [], {}), # [storage, param]
] + prologue_instructions + [
Instr("DIG", [e.sp - 1], {}), # fetch the entrypoint argument
]
# the storage is at the bottom of the stack
e.vars["__STORAGE__"] = 0
# the parameter is a the top of the stack
# N.B. all variables declared in the prologue instructions) are
# laying between the storage and the parameter (hence the +1 above)
e.vars[f.args.args[0].arg] = e.sp
init_operations_instructions = self._initialize_operations(e)
# type argument if record
if type(f.args.args[0].annotation) == ast.Name:
if f.args.args[0].annotation.id in e.records:
e.types[f.args.args[0].arg] = f.args.args[0].annotation.id
block_instructions, operations_addr = self._compile_block(f.body, e, return_operations=True)
if operations_addr:
e.vars["__OPERATIONS__"] = operations_addr
entrypoint_instructions = block_instructions
if "__OPERATIONS__" in e.vars:
get_operations = self._fetch_variable("__OPERATIONS__", e)
pass
else:
get_operations = [Instr("NIL", [t.Operation()], {})]
e.sp += 1
epilogue = get_operations + [
Instr("PAIR", [], {}),
]
e.sp -= 1
free_vars_instructions = self.free_vars(list(e.vars.keys()), e)
entrypoint_instructions = init_operations_instructions + entrypoint_instructions + epilogue + free_vars_instructions
prototype = self._get_function_prototype(f, e)
entrypoint = Entrypoint(prototype, entrypoint_instructions)
self.contract.add_entrypoint(f.name, entrypoint)
return []
def free_vars(self, var_names: List[str], e: Env) -> List[Instr]:
# Free from the top of the stack. this ensures that the variable pointers
# are not changed as variables are freed from the stack
sorted_keys = sorted(var_names, key=lambda var_name: e.vars[var_name], reverse=True)
# remove env vars from memory
free_var_instructions = []
for var_name in sorted_keys:
instr, _ = self.free_var(var_name, e)
free_var_instructions += instr
return free_var_instructions
def _compile_block(self, block_ast: List[ast.AST], block_env: Env, return_operations = False) -> Union[List[Instr], Tuple[List[Instr], Union[bool, int]]]:
"""frees newly declared variables at the end of the block, hence °e°
should be the same befor and after the block"""
# get init env keys
init_var_names = set(block_env.vars.keys())
if return_operations:
init_var_names.add("__OPERATIONS__")
# iterate body instructions
block_instructions = []
for i in block_ast:
block_instructions += self._compile(i, block_env)
# get new func_env keys
new_var_names = set(block_env.vars.keys())
# intersect init and new env keys
intersection = list(new_var_names - init_var_names)
free_var_instructions = self.free_vars(intersection, block_env)
instructions = block_instructions + free_var_instructions
if return_operations:
return instructions, block_env.vars.get("__OPERATIONS__", None)
return instructions
@debug
def compile_storage(self, storage_ast, e: Env):
if type(storage_ast) == ast.Call:
# assume constructed from record
storage_type = storage_ast.func.id
e.types["__STORAGE__"] = storage_type
self.contract.storage_type = e.records[storage_type].get_type()
else:
return NotImplementedError
@debug
def _compile_contract(self, contract_ast: ast.ClassDef, e: Env, prologue_instructions: List[Instr]) -> List[Instr]:
instructions = []
for entrypoint in contract_ast.body:
if entrypoint.name == "deploy":
if type(entrypoint.body[0]) == ast.Return:
self.compile_storage(entrypoint.body[0].value, e)
else:
return NotImplementedError
else:
instructions += self.compile_entrypoint(entrypoint, e, prologue_instructions)
return instructions
@debug
def compile_record(self, record_ast: ast.ClassDef, e: Env) -> List[Instr]:
attribute_names = [attr.target.id for attr in record_ast.body]
attribute_types = []
attribute_annotations = []
for attr_name, attr in zip(attribute_names, record_ast.body):
attribute_annotations.append(attr.annotation)
attribute_types.append(self.type_parser.parse(attr.annotation, e, "%" + attr_name))
e.records[record_ast.name] = Record(attribute_names, attribute_types, attribute_annotations)
return []
def handle_get_storage(self, storage_get_ast: ast.Attribute, e: Env) -> List[Instr]:
if storage_get_ast.attr != "storage":
# storage is record
key = storage_get_ast.attr
load_storage_instr = self.compile_name(ast.Name(id='__STORAGE__', ctx=ast.Load()), e)
storage_key_name = storage_get_ast.attr
get_storage_key_instr = e.records[e.types['__STORAGE__']].navigate_to_tree_leaf(storage_key_name)
return load_storage_instr + get_storage_key_instr
else:
return self.compile_name(ast.Name(id='__STORAGE__', ctx=ast.Load()), e)
def check_get_storage(self, storage_get_ast: ast.Attribute) -> bool:
# tmp fix
if type(storage_get_ast.value) == ast.Subscript:
return False
try:
return (
storage_get_ast.value.value.id == "self"
and storage_get_ast.value.attr == "storage"
)
except:
return (
storage_get_ast.value.id == "self"
and storage_get_ast.attr == "storage"
)
def check_get_sender(self, sender_ast: ast.Attribute) -> bool:
return (
sender_ast.value.id == "self"
and sender_ast.attr == "sender"
)
def get_sender(self, sender_ast: ast.Name, e: Env) -> List[Instr]:
e.sp += 1 # account for pushing sender
return [Instr("SENDER", [], {})]
@debug
def _compile_attribute(self, node: ast.Attribute, e: Env, instructions = None, recursing = False):
if instructions is None:
instructions = []
def get_next_record(annotation):
if type(annotation) == ast.Name:
return annotation.id
elif type(annotation) == ast.Subscript:
if len(annotation.slice.value.elts) == 2:
# dict
return annotation.slice.value.elts[1].id
elif len(annotation.slice.value.elts) == 1:
# list
raise NotImplementedError
else:
raise NotImplementedError
if type(node.value) == ast.Attribute:
instructions, record = self._compile_attribute(node.value, e, instructions, True)
instructions += record.navigate_to_tree_leaf(node.attr)
if recursing:
new_record_name = record.get_attribute_annotation(node.attr).id
new_record = e.records[new_record_name]
return instructions, new_record
elif type(node.value) == ast.Name:
var_name = node.value.id
var_type = e.types[var_name]
record = e.records[var_type]
instructions += self._compile(node.value, e)
instructions += record.navigate_to_tree_leaf(node.attr)
if recursing:
new_record_annotation = record.get_attribute_annotation(node.attr)
new_record_name = get_next_record(new_record_annotation)
new_record = e.records[new_record_name]
return instructions, new_record
elif type(node.value) == ast.Subscript:
instructions, record = self._compile_attribute(node.value.value, e, instructions, True)
instructions += self._compile(node.value.slice.value, e)
instructions += self._compile_get_subscript(e)
instructions += record.navigate_to_tree_leaf(node.attr)
if recursing:
new_record_name = record.get_attribute_annotation(node.attr).id
new_record = e.records[new_record_name]
return instructions, new_record
else:
raise NotImplementedError
return instructions
@debug
def compile_attribute(self, attribute_ast: ast.Attribute, e: Env) -> List[Instr]:
if self.check_get_storage(attribute_ast):
return self.handle_get_storage(attribute_ast, e)
return self._compile_attribute(attribute_ast, e)
@debug
def compile_compare(self, compare_ast: ast.Compare, e: Env) -> List[Instr]:
compare_instructions = (
self._compile(compare_ast.comparators[0], e)
+ self._compile(compare_ast.left, e)
+ [Instr("COMPARE", [], {})]
)
# Account for COMPARE
e.sp -= 1
operator_type = type(compare_ast.ops[0])
if operator_type == ast.Eq:
operator_instructions = [Instr("EQ", [], {})]
elif operator_type == ast.NotEq:
operator_instructions = [Instr("NEQ", [], {})]
elif operator_type == ast.Lt: