-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
genops.py
5356 lines (4511 loc) · 238 KB
/
genops.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
"""Transform a mypy AST to the IR form (Intermediate Representation).
For example, consider a function like this:
def f(x: int) -> int:
return x * 2 + 1
It would be translated to something that conceptually looks like this:
r0 = 2
r1 = 1
r2 = x * r0 :: int
r3 = r2 + r1 :: int
return r3
"""
from typing import (
TypeVar, Callable, Dict, List, Tuple, Optional, Union, Sequence, Set, Any, cast
)
from typing_extensions import overload, NoReturn
from collections import OrderedDict
from abc import abstractmethod
import importlib.util
import itertools
from mypy.build import Graph
from mypy.nodes import (
MypyFile, SymbolNode, Statement, FuncItem, FuncDef, ReturnStmt, AssignmentStmt, OpExpr,
IntExpr, NameExpr, LDEF, Var, IfStmt, UnaryExpr, ComparisonExpr, WhileStmt, CallExpr,
IndexExpr, Block, Expression, ListExpr, ExpressionStmt, MemberExpr, ForStmt, RefExpr, Lvalue,
BreakStmt, ContinueStmt, ConditionalExpr, OperatorAssignmentStmt, TupleExpr, ClassDef,
TypeInfo, Import, ImportFrom, ImportAll, DictExpr, StrExpr, CastExpr, TempNode,
PassStmt, PromoteExpr, AssignmentExpr, AwaitExpr, BackquoteExpr, AssertStmt, BytesExpr,
ComplexExpr, Decorator, DelStmt, DictionaryComprehension, EllipsisExpr, EnumCallExpr, ExecStmt,
FloatExpr, GeneratorExpr, GlobalDecl, LambdaExpr, ListComprehension, SetComprehension,
NamedTupleExpr, NewTypeExpr, NonlocalDecl, OverloadedFuncDef, PrintStmt, RaiseStmt,
RevealExpr, SetExpr, SliceExpr, StarExpr, SuperExpr, TryStmt, TypeAliasExpr, TypeApplication,
TypeVarExpr, TypedDictExpr, UnicodeExpr, WithStmt, YieldFromExpr, YieldExpr, GDEF, ARG_POS,
ARG_OPT, ARG_NAMED, ARG_NAMED_OPT, ARG_STAR, ARG_STAR2, is_class_var, op_methods
)
import mypy.nodes
import mypy.errors
from mypy.types import (
Type, Instance, CallableType, NoneTyp, TupleType, UnionType, AnyType, TypeVarType, PartialType,
TypeType, Overloaded, TypeOfAny, UninhabitedType, UnboundType, TypedDictType,
LiteralType,
get_proper_type,
)
from mypy.visitor import ExpressionVisitor, StatementVisitor
from mypy.checkexpr import map_actuals_to_formals
from mypy.state import strict_optional_set
from mypyc.common import (
ENV_ATTR_NAME, NEXT_LABEL_ATTR_NAME, TEMP_ATTR_NAME, LAMBDA_NAME,
MAX_LITERAL_SHORT_INT, TOP_LEVEL_NAME, SELF_NAME, decorator_helper_name,
FAST_ISINSTANCE_MAX_SUBCLASSES, PROPSET_PREFIX
)
from mypyc.prebuildvisitor import PreBuildVisitor
from mypyc.ops import (
BasicBlock, AssignmentTarget, AssignmentTargetRegister, AssignmentTargetIndex,
AssignmentTargetAttr, AssignmentTargetTuple, Environment, Op, LoadInt, RType, Value, Register,
Return, FuncIR, Assign, Branch, Goto, RuntimeArg, Call, Box, Unbox, Cast, RTuple, Unreachable,
TupleGet, TupleSet, ClassIR, NonExtClassInfo, RInstance, ModuleIR, GetAttr, SetAttr,
LoadStatic, InitStatic, MethodCall, INVALID_FUNC_DEF, int_rprimitive, float_rprimitive,
bool_rprimitive, list_rprimitive, is_list_rprimitive, dict_rprimitive, set_rprimitive,
str_rprimitive, tuple_rprimitive, none_rprimitive, is_none_rprimitive, object_rprimitive,
exc_rtuple,
PrimitiveOp, ControlOp, OpDescription, RegisterOp,
is_object_rprimitive, LiteralsMap, FuncSignature, VTableAttr, VTableMethod, VTableEntries,
NAMESPACE_TYPE, RaiseStandardError, LoadErrorValue, NO_TRACEBACK_LINE_NO, FuncDecl,
FUNC_NORMAL, FUNC_STATICMETHOD, FUNC_CLASSMETHOD,
RUnion, is_optional_type, optional_value_type, all_concrete_classes
)
from mypyc.ops_primitive import binary_ops, unary_ops, func_ops, method_ops, name_ref_ops
from mypyc.ops_list import (
list_append_op, list_extend_op, list_len_op, new_list_op, to_list, list_pop_last
)
from mypyc.ops_tuple import list_tuple_op, new_tuple_op
from mypyc.ops_dict import (
new_dict_op, dict_get_item_op, dict_set_item_op, dict_update_in_display_op,
)
from mypyc.ops_set import new_set_op, set_add_op, set_update_op
from mypyc.ops_misc import (
none_op, none_object_op, true_op, false_op, iter_op, next_op, next_raw_op,
check_stop_op, send_op, yield_from_except_op, coro_op,
py_getattr_op, py_setattr_op, py_delattr_op, py_hasattr_op,
py_call_op, py_call_with_kwargs_op, py_method_call_op,
fast_isinstance_op, bool_op, new_slice_op,
type_op, pytype_from_template_op, import_op, get_module_dict_op,
ellipsis_op, method_new_op, type_is_op, type_object_op, py_calc_meta_op
)
from mypyc.ops_exc import (
raise_exception_op, raise_exception_with_tb_op, reraise_exception_op,
error_catch_op, restore_exc_info_op, exc_matches_op, get_exc_value_op,
get_exc_info_op, keep_propagating_op, set_stop_iteration_value,
)
from mypyc.genops_for import ForGenerator, ForRange, ForList, ForIterable, ForEnumerate, ForZip
from mypyc.rt_subtype import is_runtime_subtype
from mypyc.subtype import is_subtype
from mypyc.sametype import is_same_type, is_same_method_signature
from mypyc.crash import catch_errors
from mypyc.options import CompilerOptions
GenFunc = Callable[[], None]
DictEntry = Tuple[Optional[Value], Value]
class UnsupportedException(Exception):
pass
class Errors:
def __init__(self) -> None:
self.num_errors = 0
self.num_warnings = 0
self._errors = mypy.errors.Errors()
def error(self, msg: str, path: str, line: int) -> None:
self._errors.report(line, None, msg, severity='error', file=path)
self.num_errors += 1
def warning(self, msg: str, path: str, line: int) -> None:
self._errors.report(line, None, msg, severity='warning', file=path)
self.num_warnings += 1
def flush_errors(self) -> None:
for error in self._errors.new_messages():
print(error)
# The stubs for callable contextmanagers are busted so cast it to the
# right type...
F = TypeVar('F', bound=Callable[..., Any])
strict_optional_dec = cast(Callable[[F], F], strict_optional_set(True))
@strict_optional_dec # Turn on strict optional for any type manipulations we do
def build_ir(modules: List[MypyFile],
graph: Graph,
types: Dict[Expression, Type],
options: CompilerOptions) -> Tuple[LiteralsMap, List[Tuple[str, ModuleIR]], int]:
result = []
mapper = Mapper()
errors = Errors()
# Collect all classes defined in the compilation unit.
classes = []
for module in modules:
module_classes = [node for node in module.defs if isinstance(node, ClassDef)]
classes.extend([(module, cdef) for cdef in module_classes])
# Collect all class mappings so that we can bind arbitrary class name
# references even if there are import cycles.
for module, cdef in classes:
class_ir = ClassIR(cdef.name, module.fullname(), is_trait(cdef),
is_abstract=cdef.info.is_abstract)
mapper.type_to_ir[cdef.info] = class_ir
# Figure out which classes need to be compiled as non-extension classes.
mark_non_ext_classes(mapper.type_to_ir)
# Populate structural information in class IR for extension classes.
for module, cdef in classes:
with catch_errors(module.path, cdef.line):
if mapper.type_to_ir[cdef.info].is_ext_class:
prepare_class_def(module.path, module.fullname(), cdef, errors, mapper)
else:
prepare_non_ext_class_def(module.path, module.fullname(), cdef, errors, mapper)
# Collect all the functions also. We collect from the symbol table
# so that we can easily pick out the right copy of a function that
# is conditionally defined.
for module in modules:
for name, node in module.names.items():
# We need to filter out functions that are imported or
# aliases. The best way to do this seems to be by
# checking that the fullname matches.
if (isinstance(node.node, (FuncDef, Decorator, OverloadedFuncDef))
and node.fullname == module.fullname() + '.' + name):
prepare_func_def(module.fullname(), None, get_func_def(node.node), mapper)
# TODO: what else?
# Generate IR for all modules.
module_names = [mod.fullname() for mod in modules]
class_irs = []
for module in modules:
# First pass to determine free symbols.
pbv = PreBuildVisitor()
module.accept(pbv)
# Second pass.
builder = IRBuilder(types, graph, errors, mapper, module_names, pbv, options)
builder.visit_mypy_file(module)
module_ir = ModuleIR(
list(builder.imports),
builder.functions,
builder.classes,
builder.final_names
)
result.append((module.fullname(), module_ir))
class_irs.extend(builder.classes)
# Compute vtables.
for cir in class_irs:
if cir.is_ext_class:
compute_vtable(cir)
errors.flush_errors()
return mapper.literals, result, errors.num_errors
def is_extension_class(cdef: ClassDef) -> bool:
if any(not (isinstance(d, RefExpr) and d.fullname == 'mypy_extensions.trait')
for d in cdef.decorators):
return False
elif (cdef.info.metaclass_type and cdef.info.metaclass_type.type.fullname() not in (
'abc.ABCMeta', 'typing.TypingMeta', 'typing.GenericMeta')):
return False
return True
def mark_non_ext_classes(class_map: Dict[TypeInfo, ClassIR]) -> None:
"""
Mark which classes should be compiled as non-extension classes.
Classes in the chain of base classes of a non-extension class
will all be marked as non-extension because currently
non-extension classes cannot inherit from extension classes.
"""
visit_first = list(class_map.keys())
visit_second = [] # type: List[TypeInfo]
# First pass to gather all non-extension classes without
# considering base class chains
for typ in visit_first:
ir = class_map[typ]
ir.is_ext_class = is_extension_class(typ.defn)
if not ir.is_ext_class:
visit_second.append(typ)
# Second pass to propagate non-extension markings up the base class
# chains of classes marked as non-extension classes during the first pass.
for typ in visit_second:
todo = [typ]
while todo:
child = todo.pop()
for parent in child.bases:
if parent.type in class_map:
parent_ir = class_map[parent.type]
if not parent_ir.is_ext_class:
continue
parent_ir.is_ext_class = False
todo.append(parent.type)
def is_trait(cdef: ClassDef) -> bool:
return any(d.fullname == 'mypy_extensions.trait' for d in cdef.decorators
if isinstance(d, NameExpr))
def get_func_def(op: Union[FuncDef, Decorator, OverloadedFuncDef]) -> FuncDef:
if isinstance(op, OverloadedFuncDef):
assert op.impl
op = op.impl
if isinstance(op, Decorator):
op = op.func
return op
def specialize_parent_vtable(cls: ClassIR, parent: ClassIR) -> VTableEntries:
"""Generate the part of a vtable corresponding to a parent class or trait"""
updated = []
for entry in parent.vtable_entries:
if isinstance(entry, VTableMethod):
# Find the original method corresponding to this vtable entry.
# (This may not be the method in the entry, if it was overridden.)
orig_parent_method = entry.cls.get_method(entry.name)
assert orig_parent_method
method_cls = cls.get_method_and_class(entry.name)
if method_cls:
child_method, defining_cls = method_cls
# TODO: emit a wrapper for __init__ that raises or something
if (is_same_method_signature(orig_parent_method.sig, child_method.sig)
or orig_parent_method.name == '__init__'):
entry = VTableMethod(entry.cls, entry.name, child_method)
else:
entry = VTableMethod(entry.cls, entry.name,
defining_cls.glue_methods[(entry.cls, entry.name)])
else:
# If it is an attribute from a trait, we need to find out
# the real class it got mixed in at and point to that.
if parent.is_trait:
_, origin_cls = cls.attr_details(entry.name)
entry = VTableAttr(origin_cls, entry.name, entry.is_setter)
updated.append(entry)
return updated
def compute_vtable(cls: ClassIR) -> None:
"""Compute the vtable structure for a class."""
if cls.vtable is not None: return
if not cls.is_generated:
cls.has_dict = any(x.inherits_python for x in cls.mro)
for t in cls.mro[1:]:
# Make sure all ancestors are processed first
compute_vtable(t)
# Merge attributes from traits into the class
if not t.is_trait:
continue
for name, typ in t.attributes.items():
if not cls.is_trait and not any(name in b.attributes for b in cls.base_mro):
cls.attributes[name] = typ
cls.vtable = {}
if cls.base:
assert cls.base.vtable is not None
cls.vtable.update(cls.base.vtable)
cls.vtable_entries = specialize_parent_vtable(cls, cls.base)
# Include the vtable from the parent classes, but handle method overrides.
entries = cls.vtable_entries
# Traits need to have attributes in the vtable, since the
# attributes can be at different places in different classes, but
# regular classes can just directly get them.
if cls.is_trait:
# Traits also need to pull in vtable entries for non-trait
# parent classes explicitly.
for t in cls.mro:
for attr in t.attributes:
if attr in cls.vtable:
continue
cls.vtable[attr] = len(entries)
entries.append(VTableAttr(t, attr, is_setter=False))
entries.append(VTableAttr(t, attr, is_setter=True))
all_traits = [t for t in cls.mro if t.is_trait]
for t in [cls] + cls.traits:
for fn in itertools.chain(t.methods.values()):
# TODO: don't generate a new entry when we overload without changing the type
if fn == cls.get_method(fn.name):
cls.vtable[fn.name] = len(entries)
entries.append(VTableMethod(t, fn.name, fn))
# Compute vtables for all of the traits that the class implements
if not cls.is_trait:
for trait in all_traits:
compute_vtable(trait)
cls.trait_vtables[trait] = specialize_parent_vtable(cls, trait)
class Mapper:
"""Keep track of mappings from mypy concepts to IR concepts.
This state is shared across all modules in a compilation unit.
"""
def __init__(self) -> None:
self.type_to_ir = {} # type: Dict[TypeInfo, ClassIR]
self.func_to_decl = {} # type: Dict[SymbolNode, FuncDecl]
# Maps integer, float, and unicode literals to a static name
self.literals = {} # type: LiteralsMap
def type_to_rtype(self, typ: Optional[Type]) -> RType:
if typ is None:
return object_rprimitive
typ = get_proper_type(typ)
if isinstance(typ, Instance):
if typ.type.fullname() == 'builtins.int':
return int_rprimitive
elif typ.type.fullname() == 'builtins.float':
return float_rprimitive
elif typ.type.fullname() == 'builtins.str':
return str_rprimitive
elif typ.type.fullname() == 'builtins.bool':
return bool_rprimitive
elif typ.type.fullname() == 'builtins.list':
return list_rprimitive
# Dict subclasses are at least somewhat common and we
# specifically support them, so make sure that dict operations
# get optimized on them.
elif any(cls.fullname() == 'builtins.dict' for cls in typ.type.mro):
return dict_rprimitive
elif typ.type.fullname() == 'builtins.set':
return set_rprimitive
elif typ.type.fullname() == 'builtins.tuple':
return tuple_rprimitive # Varying-length tuple
elif typ.type in self.type_to_ir:
return RInstance(self.type_to_ir[typ.type])
else:
return object_rprimitive
elif isinstance(typ, TupleType):
# Use our unboxed tuples for raw tuples but fall back to
# being boxed for NamedTuple.
if typ.partial_fallback.type.fullname() == 'builtins.tuple':
return RTuple([self.type_to_rtype(t) for t in typ.items])
else:
return tuple_rprimitive
elif isinstance(typ, CallableType):
return object_rprimitive
elif isinstance(typ, NoneTyp):
return none_rprimitive
elif isinstance(typ, UnionType):
return RUnion([self.type_to_rtype(item)
for item in typ.items])
elif isinstance(typ, AnyType):
return object_rprimitive
elif isinstance(typ, TypeType):
return object_rprimitive
elif isinstance(typ, TypeVarType):
# Erase type variable to upper bound.
# TODO: Erase to union if object has value restriction?
return self.type_to_rtype(typ.upper_bound)
elif isinstance(typ, PartialType):
assert typ.var.type is not None
return self.type_to_rtype(typ.var.type)
elif isinstance(typ, Overloaded):
return object_rprimitive
elif isinstance(typ, TypedDictType):
return dict_rprimitive
elif isinstance(typ, LiteralType):
return self.type_to_rtype(typ.fallback)
elif isinstance(typ, (UninhabitedType, UnboundType)):
# Sure, whatever!
return object_rprimitive
# I think we've covered everything that is supposed to
# actually show up, so anything else is a bug somewhere.
assert False, 'unexpected type %s' % type(typ)
def get_arg_rtype(self, typ: Type, kind: int) -> RType:
if kind == ARG_STAR:
return tuple_rprimitive
elif kind == ARG_STAR2:
return dict_rprimitive
else:
return self.type_to_rtype(typ)
def fdef_to_sig(self, fdef: FuncDef) -> FuncSignature:
if isinstance(fdef.type, CallableType):
arg_types = [self.get_arg_rtype(typ, kind)
for typ, kind in zip(fdef.type.arg_types, fdef.type.arg_kinds)]
ret = self.type_to_rtype(fdef.type.ret_type)
else:
# Handle unannotated functions
arg_types = [object_rprimitive for arg in fdef.arguments]
ret = object_rprimitive
args = [RuntimeArg(arg.variable.name(), arg_type, arg.kind)
for arg, arg_type in zip(fdef.arguments, arg_types)]
# We force certain dunder methods to return objects to support letting them
# return NotImplemented. It also avoids some pointless boxing and unboxing,
# since tp_richcompare needs an object anyways.
if fdef.name() in ('__eq__', '__ne__', '__lt__', '__gt__', '__le__', '__ge__'):
ret = object_rprimitive
return FuncSignature(args, ret)
def literal_static_name(self, value: Union[int, float, complex, str, bytes]) -> str:
# Include type to distinguish between 1 and 1.0, and so on.
key = (type(value), value)
if key not in self.literals:
if isinstance(value, str):
prefix = 'unicode_'
else:
prefix = type(value).__name__ + '_'
self.literals[key] = prefix + str(len(self.literals))
return self.literals[key]
def prepare_func_def(module_name: str, class_name: Optional[str],
fdef: FuncDef, mapper: Mapper) -> FuncDecl:
kind = FUNC_STATICMETHOD if fdef.is_static else (
FUNC_CLASSMETHOD if fdef.is_class else FUNC_NORMAL)
decl = FuncDecl(fdef.name(), class_name, module_name, mapper.fdef_to_sig(fdef), kind)
mapper.func_to_decl[fdef] = decl
return decl
def prepare_method_def(ir: ClassIR, module_name: str, cdef: ClassDef, mapper: Mapper,
node: Union[FuncDef, Decorator]) -> None:
if isinstance(node, FuncDef):
ir.method_decls[node.name()] = prepare_func_def(module_name, cdef.name, node, mapper)
elif isinstance(node, Decorator):
# TODO: do something about abstract methods here. Currently, they are handled just like
# normal methods.
decl = prepare_func_def(module_name, cdef.name, node.func, mapper)
if not node.decorators:
ir.method_decls[node.name()] = decl
elif isinstance(node.decorators[0], MemberExpr) and node.decorators[0].name == 'setter':
# Make property setter name different than getter name so there are no
# name clashes when generating C code, and property lookup at the IR level
# works correctly.
decl.name = PROPSET_PREFIX + decl.name
decl.is_prop_setter = True
ir.method_decls[PROPSET_PREFIX + node.name()] = decl
if node.func.is_property:
assert node.func.type
decl.is_prop_getter = True
ir.property_types[node.name()] = decl.sig.ret_type
def is_valid_multipart_property_def(prop: OverloadedFuncDef) -> bool:
# Checks to ensure supported property decorator semantics
if len(prop.items) == 2:
getter = prop.items[0]
setter = prop.items[1]
if isinstance(getter, Decorator) and isinstance(setter, Decorator):
if getter.func.is_property and len(setter.decorators) == 1:
if isinstance(setter.decorators[0], MemberExpr):
if setter.decorators[0].name == "setter":
return True
return False
def can_subclass_builtin(builtin_base: str) -> bool:
# BaseException and dict are special cased.
return builtin_base in (
('builtins.Exception', 'builtins.LookupError', 'builtins.IndexError',
'builtins.Warning', 'builtins.UserWarning', 'builtins.ValueError',
'builtins.object', ))
def prepare_class_def(path: str, module_name: str, cdef: ClassDef,
errors: Errors, mapper: Mapper) -> None:
ir = mapper.type_to_ir[cdef.info]
info = cdef.info
# We sort the table for determinism here on Python 3.5
for name, node in sorted(info.names.items()):
if isinstance(node.node, Var):
assert node.node.type, "Class member %s missing type" % name
if not node.node.is_classvar and name != '__slots__':
ir.attributes[name] = mapper.type_to_rtype(node.node.type)
elif isinstance(node.node, (FuncDef, Decorator)):
prepare_method_def(ir, module_name, cdef, mapper, node.node)
elif isinstance(node.node, OverloadedFuncDef):
# Handle case for property with both a getter and a setter
if node.node.is_property:
if is_valid_multipart_property_def(node.node):
for item in node.node.items:
prepare_method_def(ir, module_name, cdef, mapper, item)
else:
errors.error("Unsupported property decorator semantics", path, cdef.line)
# Handle case for regular function overload
else:
assert node.node.impl
prepare_method_def(ir, module_name, cdef, mapper, node.node.impl)
# Check for subclassing from builtin types
for cls in info.mro:
# Special case exceptions and dicts
# XXX: How do we handle *other* things??
if cls.fullname() == 'builtins.BaseException':
ir.builtin_base = 'PyBaseExceptionObject'
elif cls.fullname() == 'builtins.dict':
ir.builtin_base = 'PyDictObject'
elif cls.fullname().startswith('builtins.'):
if not can_subclass_builtin(cls.fullname()):
# Note that if we try to subclass a C extension class that
# isn't in builtins, bad things will happen and we won't
# catch it here! But this should catch a lot of the most
# common pitfalls.
errors.error("Inheriting from most builtin types is unimplemented",
path, cdef.line)
if ir.builtin_base:
ir.attributes.clear()
# Set up a constructor decl
init_node = cdef.info['__init__'].node
if not ir.is_trait and not ir.builtin_base and isinstance(init_node, FuncDef):
init_sig = mapper.fdef_to_sig(init_node)
ctor_sig = FuncSignature(init_sig.args[1:], RInstance(ir))
ir.ctor = FuncDecl(cdef.name, None, module_name, ctor_sig)
mapper.func_to_decl[cdef.info] = ir.ctor
# Set up the parent class
bases = [mapper.type_to_ir[base.type] for base in info.bases
if base.type in mapper.type_to_ir]
if not all(c.is_trait for c in bases[1:]):
errors.error("Non-trait bases must appear first in parent list", path, cdef.line)
ir.traits = [c for c in bases if c.is_trait]
mro = []
base_mro = []
for cls in info.mro:
if cls not in mapper.type_to_ir:
if cls.fullname() != 'builtins.object':
ir.inherits_python = True
continue
base_ir = mapper.type_to_ir[cls]
if not base_ir.is_trait:
base_mro.append(base_ir)
mro.append(base_ir)
if cls.defn.removed_base_type_exprs or not base_ir.is_ext_class:
ir.inherits_python = True
base_idx = 1 if not ir.is_trait else 0
if len(base_mro) > base_idx:
ir.base = base_mro[base_idx]
if not all(base_mro[i].base == base_mro[i + 1] for i in range(len(base_mro) - 1)):
errors.error("Non-trait MRO must be linear", path, cdef.line)
ir.mro = mro
ir.base_mro = base_mro
for base in bases:
base.children.append(ir)
def prepare_non_ext_class_def(path: str, module_name: str, cdef: ClassDef,
errors: Errors, mapper: Mapper) -> None:
ir = mapper.type_to_ir[cdef.info]
info = cdef.info
for name, node in info.names.items():
if isinstance(node.node, (FuncDef, Decorator)):
prepare_method_def(ir, module_name, cdef, mapper, node.node)
elif isinstance(node.node, OverloadedFuncDef):
# Handle case for property with both a getter and a setter
if node.node.is_property:
errors.error("Non-extension classes do not support property setters",
path, cdef.line)
# Handle case for regular function overload
else:
errors.error("Non-extension classes do not support overlaoded functions",
path, cdef.line)
def concrete_arg_kind(kind: int) -> int:
"""Find the concrete version of an arg kind that is being passed."""
if kind == ARG_OPT:
return ARG_POS
elif kind == ARG_NAMED_OPT:
return ARG_NAMED
else:
return kind
class FuncInfo(object):
"""Contains information about functions as they are generated."""
def __init__(self,
fitem: FuncItem = INVALID_FUNC_DEF,
name: str = '',
class_name: Optional[str] = None,
namespace: str = '',
is_nested: bool = False,
contains_nested: bool = False,
is_decorated: bool = False,
in_non_ext: bool = False) -> None:
self.fitem = fitem
self.name = name if not is_decorated else decorator_helper_name(name)
self.class_name = class_name
self.ns = namespace
# Callable classes implement the '__call__' method, and are used to represent functions
# that are nested inside of other functions.
self._callable_class = None # type: Optional[ImplicitClass]
# Environment classes are ClassIR instances that contain attributes representing the
# variables in the environment of the function they correspond to. Environment classes are
# generated for functions that contain nested functions.
self._env_class = None # type: Optional[ClassIR]
# Generator classes implement the '__next__' method, and are used to represent generators
# returned by generator functions.
self._generator_class = None # type: Optional[GeneratorClass]
# Environment class registers are the local registers associated with instances of an
# environment class, used for getting and setting attributes. curr_env_reg is the register
# associated with the current environment.
self._curr_env_reg = None # type: Optional[Value]
# These are flags denoting whether a given function is nested, contains a nested function,
# is decorated, or is within a non-extension class.
self.is_nested = is_nested
self.contains_nested = contains_nested
self.is_decorated = is_decorated
self.in_non_ext = in_non_ext
# TODO: add field for ret_type: RType = none_rprimitive
def namespaced_name(self) -> str:
return '_'.join(x for x in [self.name, self.class_name, self.ns] if x)
@property
def is_generator(self) -> bool:
return self.fitem.is_generator or self.fitem.is_coroutine
@property
def callable_class(self) -> 'ImplicitClass':
assert self._callable_class is not None
return self._callable_class
@callable_class.setter
def callable_class(self, cls: 'ImplicitClass') -> None:
self._callable_class = cls
@property
def env_class(self) -> ClassIR:
assert self._env_class is not None
return self._env_class
@env_class.setter
def env_class(self, ir: ClassIR) -> None:
self._env_class = ir
@property
def generator_class(self) -> 'GeneratorClass':
assert self._generator_class is not None
return self._generator_class
@generator_class.setter
def generator_class(self, cls: 'GeneratorClass') -> None:
self._generator_class = cls
@property
def curr_env_reg(self) -> Value:
assert self._curr_env_reg is not None
return self._curr_env_reg
class ImplicitClass(object):
"""Contains information regarding classes that are generated as a result of nested functions or
generated functions, but not explicitly defined in the source code.
"""
def __init__(self, ir: ClassIR) -> None:
# The ClassIR instance associated with this class.
self.ir = ir
# The register associated with the 'self' instance for this generator class.
self._self_reg = None # type: Optional[Value]
# Environment class registers are the local registers associated with instances of an
# environment class, used for getting and setting attributes. curr_env_reg is the register
# associated with the current environment. prev_env_reg is the self.__mypyc_env__ field
# associated with the previous environment.
self._curr_env_reg = None # type: Optional[Value]
self._prev_env_reg = None # type: Optional[Value]
@property
def self_reg(self) -> Value:
assert self._self_reg is not None
return self._self_reg
@self_reg.setter
def self_reg(self, reg: Value) -> None:
self._self_reg = reg
@property
def curr_env_reg(self) -> Value:
assert self._curr_env_reg is not None
return self._curr_env_reg
@curr_env_reg.setter
def curr_env_reg(self, reg: Value) -> None:
self._curr_env_reg = reg
@property
def prev_env_reg(self) -> Value:
assert self._prev_env_reg is not None
return self._prev_env_reg
@prev_env_reg.setter
def prev_env_reg(self, reg: Value) -> None:
self._prev_env_reg = reg
class GeneratorClass(ImplicitClass):
def __init__(self, ir: ClassIR) -> None:
super().__init__(ir)
# This register holds the label number that the '__next__' function should go to the next
# time it is called.
self._next_label_reg = None # type: Optional[Value]
self._next_label_target = None # type: Optional[AssignmentTarget]
# These registers hold the error values for the generator object for the case that the
# 'throw' function is called.
self.exc_regs = None # type: Optional[Tuple[Value, Value, Value]]
# Holds the arg passed to send
self.send_arg_reg = None # type: Optional[Value]
# The switch block is used to decide which instruction to go using the value held in the
# next-label register.
self.switch_block = BasicBlock()
self.blocks = [] # type: List[BasicBlock]
@property
def next_label_reg(self) -> Value:
assert self._next_label_reg is not None
return self._next_label_reg
@next_label_reg.setter
def next_label_reg(self, reg: Value) -> None:
self._next_label_reg = reg
@property
def next_label_target(self) -> AssignmentTarget:
assert self._next_label_target is not None
return self._next_label_target
@next_label_target.setter
def next_label_target(self, target: AssignmentTarget) -> None:
self._next_label_target = target
# Infrastructure for special casing calls to builtin functions in a
# programmatic way. Most special cases should be handled using the
# data driven "primitive ops" system, but certain operations require
# special handling that has access to the AST/IR directly and can make
# decisions/optimizations based on it.
#
# For example, we use specializers to statically emit the length of a
# fixed length tuple and to emit optimized code for any/all calls with
# generator comprehensions as the argument.
#
# Specalizers are attempted before compiling the arguments to the
# function. Specializers can return None to indicate that they failed
# and the call should be compiled normally. Otherwise they should emit
# code for the call and return a value containing the result.
#
# Specializers take three arguments: the IRBuilder, the CallExpr being
# compiled, and the RefExpr that is the left hand side of the call.
#
# Specializers can operate on methods as well, and are keyed on the
# name and RType in that case.
Specializer = Callable[['IRBuilder', CallExpr, RefExpr], Optional[Value]]
specializers = {} # type: Dict[Tuple[str, Optional[RType]], Specializer]
def specialize_function(
name: str, typ: Optional[RType] = None) -> Callable[[Specializer], Specializer]:
"""Decorator to register a function as being a specializer."""
def wrapper(f: Specializer) -> Specializer:
specializers[name, typ] = f
return f
return wrapper
class NonlocalControl:
"""Represents a stack frame of constructs that modify nonlocal control flow.
The nonlocal control flow constructs are break, continue, and
return, and their behavior is modified by a number of other
constructs. The most obvious is loop, which override where break
and continue jump to, but also `except` (which needs to clear
exc_info when left) and (eventually) finally blocks (which need to
ensure that the finally block is always executed when leaving the
try/except blocks).
"""
@abstractmethod
def gen_break(self, builder: 'IRBuilder', line: int) -> None: pass
@abstractmethod
def gen_continue(self, builder: 'IRBuilder', line: int) -> None: pass
@abstractmethod
def gen_return(self, builder: 'IRBuilder', value: Value, line: int) -> None: pass
class BaseNonlocalControl(NonlocalControl):
def gen_break(self, builder: 'IRBuilder', line: int) -> None:
assert False, "break outside of loop"
def gen_continue(self, builder: 'IRBuilder', line: int) -> None:
assert False, "continue outside of loop"
def gen_return(self, builder: 'IRBuilder', value: Value, line: int) -> None:
builder.add(Return(value))
class LoopNonlocalControl(NonlocalControl):
def __init__(self, outer: NonlocalControl,
continue_block: BasicBlock, break_block: BasicBlock) -> None:
self.outer = outer
self.continue_block = continue_block
self.break_block = break_block
def gen_break(self, builder: 'IRBuilder', line: int) -> None:
builder.add(Goto(self.break_block))
def gen_continue(self, builder: 'IRBuilder', line: int) -> None:
builder.add(Goto(self.continue_block))
def gen_return(self, builder: 'IRBuilder', value: Value, line: int) -> None:
self.outer.gen_return(builder, value, line)
class GeneratorNonlocalControl(BaseNonlocalControl):
def gen_return(self, builder: 'IRBuilder', value: Value, line: int) -> None:
# Assign an invalid next label number so that the next time __next__ is called, we jump to
# the case in which StopIteration is raised.
builder.assign(builder.fn_info.generator_class.next_label_target,
builder.add(LoadInt(-1)),
line)
# Raise a StopIteration containing a field for the value that should be returned. Before
# doing so, create a new block without an error handler set so that the implicitly thrown
# StopIteration isn't caught by except blocks inside of the generator function.
builder.error_handlers.append(None)
builder.goto_new_block()
# Skip creating a traceback frame when we raise here, because
# we don't care about the traceback frame and it is kind of
# expensive since raising StopIteration is an extremely common case.
# Also we call a special internal function to set StopIteration instead of
# using RaiseStandardError because the obvious thing doesn't work if the
# value is a tuple (???).
builder.primitive_op(set_stop_iteration_value, [value], NO_TRACEBACK_LINE_NO)
builder.add(Unreachable())
builder.error_handlers.pop()
class CleanupNonlocalControl(NonlocalControl):
"""Abstract nonlocal control that runs some cleanup code. """
def __init__(self, outer: NonlocalControl) -> None:
self.outer = outer
@abstractmethod
def gen_cleanup(self, builder: 'IRBuilder', line: int) -> None: ...
def gen_break(self, builder: 'IRBuilder', line: int) -> None:
self.gen_cleanup(builder, line)
self.outer.gen_break(builder, line)
def gen_continue(self, builder: 'IRBuilder', line: int) -> None:
self.gen_cleanup(builder, line)
self.outer.gen_continue(builder, line)
def gen_return(self, builder: 'IRBuilder', value: Value, line: int) -> None:
self.gen_cleanup(builder, line)
self.outer.gen_return(builder, value, line)
class TryFinallyNonlocalControl(NonlocalControl):
def __init__(self, target: BasicBlock) -> None:
self.target = target
self.ret_reg = None # type: Optional[Register]
def gen_break(self, builder: 'IRBuilder', line: int) -> None:
builder.error("break inside try/finally block is unimplemented", line)
def gen_continue(self, builder: 'IRBuilder', line: int) -> None:
builder.error("continue inside try/finally block is unimplemented", line)
def gen_return(self, builder: 'IRBuilder', value: Value, line: int) -> None:
if self.ret_reg is None:
self.ret_reg = builder.alloc_temp(builder.ret_types[-1])
builder.add(Assign(self.ret_reg, value))
builder.add(Goto(self.target))
class ExceptNonlocalControl(CleanupNonlocalControl):
"""Nonlocal control for except blocks.
Just makes sure that sys.exc_info always gets restored when we leave.
This is super annoying.
"""
def __init__(self, outer: NonlocalControl, saved: Union[Value, AssignmentTarget]) -> None:
super().__init__(outer)
self.saved = saved
def gen_cleanup(self, builder: 'IRBuilder', line: int) -> None:
builder.primitive_op(restore_exc_info_op, [builder.read(self.saved)], line)
class FinallyNonlocalControl(CleanupNonlocalControl):
"""Nonlocal control for finally blocks.
Just makes sure that sys.exc_info always gets restored when we
leave and the return register is decrefed if it isn't null.
"""
def __init__(self, outer: NonlocalControl, ret_reg: Optional[Value], saved: Value) -> None:
super().__init__(outer)
self.ret_reg = ret_reg
self.saved = saved
def gen_cleanup(self, builder: 'IRBuilder', line: int) -> None:
# Do an error branch on the return value register, which
# may be undefined. This will allow it to be properly
# decrefed if it is not null. This is kind of a hack.
if self.ret_reg:
target = BasicBlock()
builder.add(Branch(self.ret_reg, target, target, Branch.IS_ERROR))
builder.activate_block(target)
# Restore the old exc_info
target, cleanup = BasicBlock(), BasicBlock()
builder.add(Branch(self.saved, target, cleanup, Branch.IS_ERROR))
builder.activate_block(cleanup)
builder.primitive_op(restore_exc_info_op, [self.saved], line)
builder.goto_and_activate(target)
class IRBuilder(ExpressionVisitor[Value], StatementVisitor[None]):
def __init__(self,
types: Dict[Expression, Type],
graph: Graph,