forked from python/mypy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathops.py
More file actions
2258 lines (1718 loc) · 74 KB
/
ops.py
File metadata and controls
2258 lines (1718 loc) · 74 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
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
"""Representation of low-level opcodes for compiler intermediate representation (IR).
Opcodes operate on abstract registers in a register machine. Each
register has a type and a name, specified in an environment. A register
can hold various things:
- local variables
- intermediate values of expressions
- condition flags (true/false)
- literals (integer literals, True, False, etc.)
"""
from abc import abstractmethod
from typing import (
List, Sequence, Dict, Generic, TypeVar, Optional, Any, NamedTuple, Tuple, Callable,
Union, Iterable, Set
)
from typing_extensions import Final, Type, ClassVar
from collections import OrderedDict
from mypy.nodes import ARG_NAMED_OPT, ARG_OPT, ARG_POS, Block, FuncDef, SymbolNode
from mypyc.common import PROPSET_PREFIX
from mypy_extensions import trait
from mypyc.namegen import NameGenerator, exported_name
T = TypeVar('T')
JsonDict = Dict[str, Any]
class RType:
"""Abstract base class for runtime types (erased, only concrete; no generics)."""
name = None # type: str
is_unboxed = False
c_undefined = None # type: str
is_refcounted = True # If unboxed: does the unboxed version use reference counting?
_ctype = None # type: str # C type; use Emitter.ctype() to access
@abstractmethod
def accept(self, visitor: 'RTypeVisitor[T]') -> T:
raise NotImplementedError
def short_name(self) -> str:
return short_name(self.name)
def __str__(self) -> str:
return short_name(self.name)
def __repr__(self) -> str:
return '<%s>' % self.__class__.__name__
def __eq__(self, other: object) -> bool:
return isinstance(other, RType) and other.name == self.name
def __hash__(self) -> int:
return hash(self.name)
def serialize(self) -> Union[JsonDict, str]:
raise NotImplementedError('Cannot serialize {} instance'.format(self.__class__.__name__))
# We do a three-pass deserialization scheme in order to resolve name
# references.
# 1. Create an empty ClassIR for each class in an SCC.
# 2. Deserialize all of the functions, which can contain references
# to ClassIRs in their types
# 3. Deserialize all of the classes, which contain lots of references
# to the functions they contain. (And to other classes.)
#
# Note that this approach differs from how we deserialize ASTs in mypy itself,
# where everything is deserialized in one pass then a second pass cleans up
# 'cross_refs'. We don't follow that approach here because it seems to be more
# code for not a lot of gain since it is easy in mypyc to identify all the objects
# we might need to reference.
#
# Because of these references, we need to maintain maps from class
# names to ClassIRs and func names to FuncIRs.
#
# These are tracked in a DeserMaps which is passed to every
# deserialization function.
#
# (Serialization and deserialization *will* be used for incremental
# compilation but so far it is not hooked up to anything.)
DeserMaps = NamedTuple('DeserMaps',
[('classes', Dict[str, 'ClassIR']), ('functions', Dict[str, 'FuncIR'])])
def deserialize_type(data: Union[JsonDict, str], ctx: DeserMaps) -> 'RType':
"""Deserialize a JSON-serialized RType.
Arguments:
data: The decoded JSON of the serialized type
ctx: The deserialization maps to use
"""
# Since there are so few types, we just case on them directly. If
# more get added we should switch to a system like mypy.types
# uses.
if isinstance(data, str):
if data in ctx.classes:
return RInstance(ctx.classes[data])
elif data in RPrimitive.primitive_map:
return RPrimitive.primitive_map[data]
elif data == "void":
return RVoid()
else:
assert False, "Can't find class {}".format(data)
elif data['.class'] == 'RTuple':
return RTuple.deserialize(data, ctx)
elif data['.class'] == 'RUnion':
return RUnion.deserialize(data, ctx)
raise NotImplementedError('unexpected .class {}'.format(data['.class']))
class RTypeVisitor(Generic[T]):
@abstractmethod
def visit_rprimitive(self, typ: 'RPrimitive') -> T:
raise NotImplementedError
@abstractmethod
def visit_rinstance(self, typ: 'RInstance') -> T:
raise NotImplementedError
@abstractmethod
def visit_runion(self, typ: 'RUnion') -> T:
raise NotImplementedError
@abstractmethod
def visit_rtuple(self, typ: 'RTuple') -> T:
raise NotImplementedError
@abstractmethod
def visit_rvoid(self, typ: 'RVoid') -> T:
raise NotImplementedError
class RVoid(RType):
"""void"""
is_unboxed = False
name = 'void'
ctype = 'void'
def accept(self, visitor: 'RTypeVisitor[T]') -> T:
return visitor.visit_rvoid(self)
def serialize(self) -> str:
return 'void'
void_rtype = RVoid() # type: Final
class RPrimitive(RType):
"""Primitive type such as 'object' or 'int'.
These often have custom ops associated with them.
"""
# Map from primitive names to primitive types and is used by deserialization
primitive_map = {} # type: ClassVar[Dict[str, RPrimitive]]
def __init__(self,
name: str,
is_unboxed: bool,
is_refcounted: bool,
ctype: str = 'PyObject *') -> None:
RPrimitive.primitive_map[name] = self
self.name = name
self.is_unboxed = is_unboxed
self._ctype = ctype
self.is_refcounted = is_refcounted
if ctype == 'CPyTagged':
self.c_undefined = 'CPY_INT_TAG'
elif ctype == 'PyObject *':
self.c_undefined = 'NULL'
elif ctype == 'char':
self.c_undefined = '2'
else:
assert False, 'Unrecognized ctype: %r' % ctype
def accept(self, visitor: 'RTypeVisitor[T]') -> T:
return visitor.visit_rprimitive(self)
def serialize(self) -> str:
return self.name
def __repr__(self) -> str:
return '<RPrimitive %s>' % self.name
# Used to represent arbitrary objects and dynamically typed values
object_rprimitive = RPrimitive('builtins.object', is_unboxed=False,
is_refcounted=True) # type: Final
int_rprimitive = RPrimitive('builtins.int', is_unboxed=True, is_refcounted=True,
ctype='CPyTagged') # type: Final
short_int_rprimitive = RPrimitive('short_int', is_unboxed=True, is_refcounted=False,
ctype='CPyTagged') # type: Final
float_rprimitive = RPrimitive('builtins.float', is_unboxed=False,
is_refcounted=True) # type: Final
bool_rprimitive = RPrimitive('builtins.bool', is_unboxed=True, is_refcounted=False,
ctype='char') # type: Final
none_rprimitive = RPrimitive('builtins.None', is_unboxed=True, is_refcounted=False,
ctype='char') # type: Final
list_rprimitive = RPrimitive('builtins.list', is_unboxed=False, is_refcounted=True) # type: Final
dict_rprimitive = RPrimitive('builtins.dict', is_unboxed=False, is_refcounted=True) # type: Final
set_rprimitive = RPrimitive('builtins.set', is_unboxed=False, is_refcounted=True) # type: Final
# At the C layer, str is refered to as unicode (PyUnicode)
str_rprimitive = RPrimitive('builtins.str', is_unboxed=False, is_refcounted=True) # type: Final
# Tuple of an arbitrary length (corresponds to Tuple[t, ...], with explicit '...')
tuple_rprimitive = RPrimitive('builtins.tuple', is_unboxed=False,
is_refcounted=True) # type: Final
def is_int_rprimitive(rtype: RType) -> bool:
return rtype is int_rprimitive
def is_short_int_rprimitive(rtype: RType) -> bool:
return rtype is short_int_rprimitive
def is_float_rprimitive(rtype: RType) -> bool:
return isinstance(rtype, RPrimitive) and rtype.name == 'builtins.float'
def is_bool_rprimitive(rtype: RType) -> bool:
return isinstance(rtype, RPrimitive) and rtype.name == 'builtins.bool'
def is_object_rprimitive(rtype: RType) -> bool:
return isinstance(rtype, RPrimitive) and rtype.name == 'builtins.object'
def is_none_rprimitive(rtype: RType) -> bool:
return isinstance(rtype, RPrimitive) and rtype.name == 'builtins.None'
def is_list_rprimitive(rtype: RType) -> bool:
return isinstance(rtype, RPrimitive) and rtype.name == 'builtins.list'
def is_dict_rprimitive(rtype: RType) -> bool:
return isinstance(rtype, RPrimitive) and rtype.name == 'builtins.dict'
def is_set_rprimitive(rtype: RType) -> bool:
return isinstance(rtype, RPrimitive) and rtype.name == 'builtins.set'
def is_str_rprimitive(rtype: RType) -> bool:
return isinstance(rtype, RPrimitive) and rtype.name == 'builtins.str'
def is_tuple_rprimitive(rtype: RType) -> bool:
return isinstance(rtype, RPrimitive) and rtype.name == 'builtins.tuple'
class TupleNameVisitor(RTypeVisitor[str]):
"""Produce a tuple name based on the concrete representations of types."""
def visit_rinstance(self, t: 'RInstance') -> str:
return "O"
def visit_runion(self, t: 'RUnion') -> str:
return "O"
def visit_rprimitive(self, t: 'RPrimitive') -> str:
if t._ctype == 'CPyTagged':
return 'I'
elif t._ctype == 'char':
return 'C'
assert not t.is_unboxed, "{} unexpected unboxed type".format(t)
return 'O'
def visit_rtuple(self, t: 'RTuple') -> str:
parts = [elem.accept(self) for elem in t.types]
return 'T{}{}'.format(len(parts), ''.join(parts))
def visit_rvoid(self, t: 'RVoid') -> str:
assert False, "rvoid in tuple?"
class RTuple(RType):
"""Fixed-length unboxed tuple (represented as a C struct)."""
is_unboxed = True
def __init__(self, types: List[RType]) -> None:
self.name = 'tuple'
self.types = tuple(types)
self.is_refcounted = any(t.is_refcounted for t in self.types)
# Generate a unique id which is used in naming corresponding C identifiers.
# This is necessary since C does not have anonymous structural type equivalence
# in the same way python can just assign a Tuple[int, bool] to a Tuple[int, bool].
self.unique_id = self.accept(TupleNameVisitor())
# Nominally the max c length is 31 chars, but I'm not honestly worried about this.
self.struct_name = 'tuple_{}'.format(self.unique_id)
self._ctype = '{}'.format(self.struct_name)
def accept(self, visitor: 'RTypeVisitor[T]') -> T:
return visitor.visit_rtuple(self)
def __str__(self) -> str:
return 'tuple[%s]' % ', '.join(str(typ) for typ in self.types)
def __repr__(self) -> str:
return '<RTuple %s>' % ', '.join(repr(typ) for typ in self.types)
def __eq__(self, other: object) -> bool:
return isinstance(other, RTuple) and self.types == other.types
def __hash__(self) -> int:
return hash((self.name, self.types))
def serialize(self) -> JsonDict:
types = [x.serialize() for x in self.types]
return {'.class': 'RTuple', 'types': types}
@classmethod
def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> 'RTuple':
types = [deserialize_type(t, ctx) for t in data['types']]
return RTuple(types)
exc_rtuple = RTuple([object_rprimitive, object_rprimitive, object_rprimitive])
class RInstance(RType):
"""Instance of user-defined class (compiled to C extension class)."""
is_unboxed = False
def __init__(self, class_ir: 'ClassIR') -> None:
# name is used for formatting the name in messages and debug output
# so we want the fullname for precision.
self.name = class_ir.fullname
self.class_ir = class_ir
self._ctype = 'PyObject *'
def accept(self, visitor: 'RTypeVisitor[T]') -> T:
return visitor.visit_rinstance(self)
def struct_name(self, names: NameGenerator) -> str:
return self.class_ir.struct_name(names)
def getter_index(self, name: str) -> int:
return self.class_ir.vtable_entry(name)
def setter_index(self, name: str) -> int:
return self.getter_index(name) + 1
def method_index(self, name: str) -> int:
return self.class_ir.vtable_entry(name)
def attr_type(self, name: str) -> RType:
return self.class_ir.attr_type(name)
def __repr__(self) -> str:
return '<RInstance %s>' % self.name
def serialize(self) -> str:
return self.name
class RUnion(RType):
"""union[x, ..., y]"""
is_unboxed = False
def __init__(self, items: List[RType]) -> None:
self.name = 'union'
self.items = items
self.items_set = frozenset(items)
self._ctype = 'PyObject *'
def accept(self, visitor: 'RTypeVisitor[T]') -> T:
return visitor.visit_runion(self)
def __repr__(self) -> str:
return '<RUnion %s>' % ', '.join(str(item) for item in self.items)
def __str__(self) -> str:
return 'union[%s]' % ', '.join(str(item) for item in self.items)
# We compare based on the set because order in a union doesn't matter
def __eq__(self, other: object) -> bool:
return isinstance(other, RUnion) and self.items_set == other.items_set
def __hash__(self) -> int:
return hash(('union', self.items_set))
def serialize(self) -> JsonDict:
types = [x.serialize() for x in self.items]
return {'.class': 'RUnion', 'types': types}
@classmethod
def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> 'RUnion':
types = [deserialize_type(t, ctx) for t in data['types']]
return RUnion(types)
def optional_value_type(rtype: RType) -> Optional[RType]:
if isinstance(rtype, RUnion) and len(rtype.items) == 2:
if rtype.items[0] == none_rprimitive:
return rtype.items[1]
elif rtype.items[1] == none_rprimitive:
return rtype.items[0]
return None
def is_optional_type(rtype: RType) -> bool:
return optional_value_type(rtype) is not None
class AssignmentTarget(object):
type = None # type: RType
@abstractmethod
def to_str(self, env: 'Environment') -> str:
raise NotImplementedError
class AssignmentTargetRegister(AssignmentTarget):
"""Register as assignment target"""
def __init__(self, register: 'Register') -> None:
self.register = register
self.type = register.type
def to_str(self, env: 'Environment') -> str:
return self.register.name
class AssignmentTargetIndex(AssignmentTarget):
"""base[index] as assignment target"""
def __init__(self, base: 'Value', index: 'Value') -> None:
self.base = base
self.index = index
# TODO: This won't be right for user-defined classes. Store the
# lvalue type in mypy and remove this special case.
self.type = object_rprimitive
def to_str(self, env: 'Environment') -> str:
return '{}[{}]'.format(self.base.name, self.index.name)
class AssignmentTargetAttr(AssignmentTarget):
"""obj.attr as assignment target"""
def __init__(self, obj: 'Value', attr: str) -> None:
self.obj = obj
self.attr = attr
if isinstance(obj.type, RInstance) and obj.type.class_ir.has_attr(attr):
self.obj_type = obj.type # type: RType
self.type = obj.type.attr_type(attr)
else:
self.obj_type = object_rprimitive
self.type = object_rprimitive
def to_str(self, env: 'Environment') -> str:
return '{}.{}'.format(self.obj.to_str(env), self.attr)
class AssignmentTargetTuple(AssignmentTarget):
"""x, ..., y as assignment target"""
def __init__(self, items: List[AssignmentTarget],
star_idx: Optional[int] = None) -> None:
self.items = items
self.star_idx = star_idx
# The shouldn't be relevant, but provide it just in case.
self.type = object_rprimitive
def to_str(self, env: 'Environment') -> str:
return '({})'.format(', '.join(item.to_str(env) for item in self.items))
class Environment:
"""Maintain the register symbol table and manage temp generation"""
def __init__(self, name: Optional[str] = None) -> None:
self.name = name
self.indexes = OrderedDict() # type: Dict[Value, int]
self.symtable = OrderedDict() # type: OrderedDict[SymbolNode, AssignmentTarget]
self.temp_index = 0
self.names = {} # type: Dict[str, int]
self.vars_needing_init = set() # type: Set[Value]
def regs(self) -> Iterable['Value']:
return self.indexes.keys()
def add(self, reg: 'Value', name: str) -> None:
# Ensure uniqueness of variable names in this environment.
# This is needed for things like list comprehensions, which are their own scope--
# if we don't do this and two comprehensions use the same variable, we'd try to
# declare that variable twice.
unique_name = name
while unique_name in self.names:
unique_name = name + str(self.names[name])
self.names[name] += 1
self.names[unique_name] = 0
reg.name = unique_name
self.indexes[reg] = len(self.indexes)
def add_local(self, symbol: SymbolNode, typ: RType, is_arg: bool = False) -> 'Register':
assert isinstance(symbol, SymbolNode)
reg = Register(typ, symbol.line, is_arg=is_arg)
self.symtable[symbol] = AssignmentTargetRegister(reg)
self.add(reg, symbol.name())
return reg
def add_local_reg(self, symbol: SymbolNode,
typ: RType, is_arg: bool = False) -> AssignmentTargetRegister:
self.add_local(symbol, typ, is_arg)
target = self.symtable[symbol]
assert isinstance(target, AssignmentTargetRegister)
return target
def add_target(self, symbol: SymbolNode, target: AssignmentTarget) -> AssignmentTarget:
self.symtable[symbol] = target
return target
def lookup(self, symbol: SymbolNode) -> AssignmentTarget:
return self.symtable[symbol]
def add_temp(self, typ: RType, is_arg: bool = False) -> 'Register':
assert isinstance(typ, RType)
reg = Register(typ, is_arg=is_arg)
self.add(reg, 'r%d' % self.temp_index)
self.temp_index += 1
return reg
def add_op(self, reg: 'RegisterOp') -> None:
if reg.is_void:
return
self.add(reg, 'r%d' % self.temp_index)
self.temp_index += 1
def format(self, fmt: str, *args: Any) -> str:
result = []
i = 0
arglist = list(args)
while i < len(fmt):
n = fmt.find('%', i)
if n < 0:
n = len(fmt)
result.append(fmt[i:n])
if n < len(fmt):
typespec = fmt[n + 1]
arg = arglist.pop(0)
if typespec == 'r':
result.append(arg.name)
elif typespec == 'd':
result.append('%d' % arg)
elif typespec == 'f':
result.append('%f' % arg)
elif typespec == 'l':
if isinstance(arg, BasicBlock):
arg = arg.label
result.append('L%s' % arg)
elif typespec == 's':
result.append(str(arg))
else:
raise ValueError('Invalid format sequence %{}'.format(typespec))
i = n + 2
else:
i = n
return ''.join(result)
def to_lines(self) -> List[str]:
result = []
i = 0
regs = list(self.regs())
while i < len(regs):
i0 = i
group = [regs[i0].name]
while i + 1 < len(regs) and regs[i + 1].type == regs[i0].type:
i += 1
group.append(regs[i].name)
i += 1
result.append('%s :: %s' % (', '.join(group), regs[i0].type))
return result
class BasicBlock:
"""Basic IR block.
Ends with a jump, branch, or return.
When building the IR, ops that raise exceptions can be included in
the middle of a basic block, but the exceptions aren't checked.
Afterwards we perform a transform that inserts explicit checks for
all error conditions and splits basic blocks accordingly to preserve
the invariant that a jump, branch or return can only ever appear
as the final op in a block. Manually inserting error checking ops
would be boring and error-prone.
BasicBlocks have an error_handler attribute that determines where
to jump if an error occurs. If none is specified, an error will
propagate up out of the function. This is compiled away by the
`exceptions` module.
Block labels are used for pretty printing and emitting C code, and get
filled in by those passes.
Ops that may terminate the program aren't treated as exits.
"""
def __init__(self, label: int = -1) -> None:
self.label = label
self.ops = [] # type: List[Op]
self.error_handler = None # type: Optional[BasicBlock]
# Never generates an exception
ERR_NEVER = 0 # type: Final
# Generates magic value (c_error_value) based on target RType on exception
ERR_MAGIC = 1 # type: Final
# Generates false (bool) on exception
ERR_FALSE = 2 # type: Final
# Hack: using this line number for an op will supress it in tracebacks
NO_TRACEBACK_LINE_NO = -10000
class Value:
# Source line number
line = -1
name = '?'
type = void_rtype # type: RType
is_borrowed = False
def __init__(self, line: int) -> None:
self.line = line
@property
def is_void(self) -> bool:
return isinstance(self.type, RVoid)
@abstractmethod
def to_str(self, env: Environment) -> str:
raise NotImplementedError
class Register(Value):
def __init__(self, type: RType, line: int = -1, is_arg: bool = False, name: str = '') -> None:
super().__init__(line)
self.name = name
self.type = type
self.is_arg = is_arg
self.is_borrowed = is_arg
def to_str(self, env: Environment) -> str:
return self.name
@property
def is_void(self) -> bool:
return False
class Op(Value):
def __init__(self, line: int) -> None:
super().__init__(line)
def can_raise(self) -> bool:
# Override this is if Op may raise an exception. Note that currently the fact that
# only RegisterOps may raise an exception in hard coded in some places.
return False
@abstractmethod
def sources(self) -> List[Value]:
pass
def stolen(self) -> List[Value]:
"""Return arguments that have a reference count stolen by this op"""
return []
def unique_sources(self) -> List[Value]:
result = [] # type: List[Value]
for reg in self.sources():
if reg not in result:
result.append(reg)
return result
@abstractmethod
def accept(self, visitor: 'OpVisitor[T]') -> T:
pass
class ControlOp(Op):
# Basically just for hierarchy organization.
# We could plausibly have a targets() method if we wanted.
pass
class Goto(ControlOp):
"""Unconditional jump."""
error_kind = ERR_NEVER
def __init__(self, label: BasicBlock, line: int = -1) -> None:
super().__init__(line)
self.label = label
def __repr__(self) -> str:
return '<Goto %s>' % self.label.label
def sources(self) -> List[Value]:
return []
def to_str(self, env: Environment) -> str:
return env.format('goto %l', self.label)
def accept(self, visitor: 'OpVisitor[T]') -> T:
return visitor.visit_goto(self)
class Branch(ControlOp):
"""if [not] r1 goto 1 else goto 2"""
# Branch ops must *not* raise an exception. If a comparison, for example, can raise an
# exception, it needs to split into two opcodes and only the first one may fail.
error_kind = ERR_NEVER
BOOL_EXPR = 100 # type: Final
IS_ERROR = 101 # type: Final
op_names = {
BOOL_EXPR: ('%r', 'bool'),
IS_ERROR: ('is_error(%r)', ''),
} # type: Final
def __init__(self, left: Value, true_label: BasicBlock,
false_label: BasicBlock, op: int, line: int = -1, *, rare: bool = False) -> None:
super().__init__(line)
self.left = left
self.true = true_label
self.false = false_label
self.op = op
self.negated = False
# If not None, the true label should generate a traceback entry (func name, line number)
self.traceback_entry = None # type: Optional[Tuple[str, int]]
self.rare = rare
def sources(self) -> List[Value]:
return [self.left]
def to_str(self, env: Environment) -> str:
fmt, typ = self.op_names[self.op]
if self.negated:
fmt = 'not {}'.format(fmt)
cond = env.format(fmt, self.left)
tb = ''
if self.traceback_entry:
tb = ' (error at %s:%d)' % self.traceback_entry
fmt = 'if {} goto %l{} else goto %l'.format(cond, tb)
if typ:
fmt += ' :: {}'.format(typ)
return env.format(fmt, self.true, self.false)
def invert(self) -> None:
self.negated = not self.negated
def accept(self, visitor: 'OpVisitor[T]') -> T:
return visitor.visit_branch(self)
class Return(ControlOp):
error_kind = ERR_NEVER
def __init__(self, reg: Value, line: int = -1) -> None:
super().__init__(line)
self.reg = reg
def sources(self) -> List[Value]:
return [self.reg]
def stolen(self) -> List[Value]:
return [self.reg]
def to_str(self, env: Environment) -> str:
return env.format('return %r', self.reg)
def accept(self, visitor: 'OpVisitor[T]') -> T:
return visitor.visit_return(self)
class Unreachable(ControlOp):
"""Added to the end of non-None returning functions.
Mypy statically guarantees that the end of the function is not unreachable
if there is not a return statement.
This prevents the block formatter from being confused due to lack of a leave
and also leaves a nifty note in the IR. It is not generally processed by visitors.
"""
error_kind = ERR_NEVER
def __init__(self, line: int = -1) -> None:
super().__init__(line)
def to_str(self, env: Environment) -> str:
return "unreachable"
def sources(self) -> List[Value]:
return []
def accept(self, visitor: 'OpVisitor[T]') -> T:
return visitor.visit_unreachable(self)
class RegisterOp(Op):
"""An operation that can be written as r1 = f(r2, ..., rn).
Takes some registers, performs an operation and generates an output.
Doesn't do any control flow, but can raise an error.
"""
error_kind = -1 # Can this raise exception and how is it signalled; one of ERR_*
_type = None # type: Optional[RType]
def __init__(self, line: int) -> None:
super().__init__(line)
assert self.error_kind != -1, 'error_kind not defined'
def can_raise(self) -> bool:
return self.error_kind != ERR_NEVER
class IncRef(RegisterOp):
"""inc_ref r"""
error_kind = ERR_NEVER
def __init__(self, src: Value, line: int = -1) -> None:
assert src.type.is_refcounted
super().__init__(line)
self.src = src
def to_str(self, env: Environment) -> str:
s = env.format('inc_ref %r', self.src)
if is_bool_rprimitive(self.src.type) or is_int_rprimitive(self.src.type):
s += ' :: {}'.format(short_name(self.src.type.name))
return s
def sources(self) -> List[Value]:
return [self.src]
def accept(self, visitor: 'OpVisitor[T]') -> T:
return visitor.visit_inc_ref(self)
class DecRef(RegisterOp):
"""dec_ref r
The is_xdec flag says to use an XDECREF, which checks if the
pointer is NULL first.
"""
error_kind = ERR_NEVER
def __init__(self, src: Value, is_xdec: bool = False, line: int = -1) -> None:
assert src.type.is_refcounted
super().__init__(line)
self.src = src
self.is_xdec = is_xdec
def __repr__(self) -> str:
return '<%sDecRef %r>' % ('X' if self.is_xdec else '', self.src)
def to_str(self, env: Environment) -> str:
s = env.format('%sdec_ref %r', 'x' if self.is_xdec else '', self.src)
if is_bool_rprimitive(self.src.type) or is_int_rprimitive(self.src.type):
s += ' :: {}'.format(short_name(self.src.type.name))
return s
def sources(self) -> List[Value]:
return [self.src]
def accept(self, visitor: 'OpVisitor[T]') -> T:
return visitor.visit_dec_ref(self)
class Call(RegisterOp):
"""Native call f(arg, ...)
The call target can be a module-level function or a class.
"""
error_kind = ERR_MAGIC
def __init__(self, fn: 'FuncDecl', args: Sequence[Value], line: int) -> None:
super().__init__(line)
self.fn = fn
self.args = list(args)
self.type = fn.sig.ret_type
def to_str(self, env: Environment) -> str:
args = ', '.join(env.format('%r', arg) for arg in self.args)
# TODO: Display long name?
short_name = self.fn.shortname
s = '%s(%s)' % (short_name, args)
if not self.is_void:
s = env.format('%r = ', self) + s
return s
def sources(self) -> List[Value]:
return list(self.args[:])
def accept(self, visitor: 'OpVisitor[T]') -> T:
return visitor.visit_call(self)
class MethodCall(RegisterOp):
"""Native method call obj.m(arg, ...) """
error_kind = ERR_MAGIC
def __init__(self,
obj: Value,
method: str,
args: List[Value],
line: int = -1) -> None:
super().__init__(line)
self.obj = obj
self.method = method
self.args = args
assert isinstance(obj.type, RInstance), "Methods can only be called on instances"
self.receiver_type = obj.type
method_ir = self.receiver_type.class_ir.method_sig(method)
assert method_ir is not None, "{} doesn't have method {}".format(
self.receiver_type.name, method)
self.type = method_ir.ret_type
def to_str(self, env: Environment) -> str:
args = ', '.join(env.format('%r', arg) for arg in self.args)
s = env.format('%r.%s(%s)', self.obj, self.method, args)
if not self.is_void:
s = env.format('%r = ', self) + s
return s
def sources(self) -> List[Value]:
return self.args[:] + [self.obj]
def accept(self, visitor: 'OpVisitor[T]') -> T:
return visitor.visit_method_call(self)
@trait
class EmitterInterface():
@abstractmethod
def reg(self, name: Value) -> str:
raise NotImplementedError
@abstractmethod
def c_error_value(self, rtype: RType) -> str:
raise NotImplementedError
@abstractmethod
def temp_name(self) -> str:
raise NotImplementedError
@abstractmethod
def emit_line(self, line: str) -> None:
raise NotImplementedError
@abstractmethod
def emit_lines(self, *lines: str) -> None:
raise NotImplementedError
@abstractmethod
def emit_declaration(self, line: str) -> None:
raise NotImplementedError
EmitCallback = Callable[[EmitterInterface, List[str], str], None]
# True steals all arguments, False steals none, a list steals those in matching positions
StealsDescription = Union[bool, List[bool]]