-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
Copy pathnodes.py
3451 lines (2699 loc) · 115 KB
/
nodes.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
"""Abstract syntax tree node classes (i.e. parse tree)."""
import os
from enum import Enum, unique
from abc import abstractmethod
from mypy.backports import OrderedDict
from collections import defaultdict
from typing import (
Any, TypeVar, List, Tuple, cast, Set, Dict, Union, Optional, Callable, Sequence, Iterator
)
from typing_extensions import DefaultDict, Final, TYPE_CHECKING, TypeAlias as _TypeAlias
from mypy_extensions import trait
import mypy.strconv
from mypy.util import short_type
from mypy.visitor import NodeVisitor, StatementVisitor, ExpressionVisitor
from mypy.bogus_type import Bogus
class Context:
"""Base type for objects that are valid as error message locations."""
__slots__ = ('line', 'column', 'end_line')
def __init__(self, line: int = -1, column: int = -1) -> None:
self.line = line
self.column = column
self.end_line: Optional[int] = None
def set_line(self,
target: Union['Context', int],
column: Optional[int] = None,
end_line: Optional[int] = None) -> None:
"""If target is a node, pull line (and column) information
into this node. If column is specified, this will override any column
information coming from a node.
"""
if isinstance(target, int):
self.line = target
else:
self.line = target.line
self.column = target.column
self.end_line = target.end_line
if column is not None:
self.column = column
if end_line is not None:
self.end_line = end_line
def get_line(self) -> int:
"""Don't use. Use x.line."""
return self.line
def get_column(self) -> int:
"""Don't use. Use x.column."""
return self.column
if TYPE_CHECKING:
# break import cycle only needed for mypy
import mypy.types
T = TypeVar('T')
JsonDict: _TypeAlias = Dict[str, Any]
# Symbol table node kinds
#
# TODO rename to use more descriptive names
LDEF: Final = 0
GDEF: Final = 1
MDEF: Final = 2
# Placeholder for a name imported via 'from ... import'. Second phase of
# semantic will replace this the actual imported reference. This is
# needed so that we can detect whether a name has been imported during
# XXX what?
UNBOUND_IMPORTED: Final = 3
# RevealExpr node kinds
REVEAL_TYPE: Final = 0
REVEAL_LOCALS: Final = 1
LITERAL_YES: Final = 2
LITERAL_TYPE: Final = 1
LITERAL_NO: Final = 0
node_kinds: Final = {
LDEF: 'Ldef',
GDEF: 'Gdef',
MDEF: 'Mdef',
UNBOUND_IMPORTED: 'UnboundImported',
}
inverse_node_kinds: Final = {_kind: _name for _name, _kind in node_kinds.items()}
implicit_module_attrs: Final = {
'__name__': '__builtins__.str',
'__doc__': None, # depends on Python version, see semanal.py
'__path__': None, # depends on if the module is a package
'__file__': '__builtins__.str',
'__package__': '__builtins__.str'
}
# These aliases exist because built-in class objects are not subscriptable.
# For example `list[int]` fails at runtime. Instead List[int] should be used.
type_aliases: Final = {
'typing.List': 'builtins.list',
'typing.Dict': 'builtins.dict',
'typing.Set': 'builtins.set',
'typing.FrozenSet': 'builtins.frozenset',
'typing.ChainMap': 'collections.ChainMap',
'typing.Counter': 'collections.Counter',
'typing.DefaultDict': 'collections.defaultdict',
'typing.Deque': 'collections.deque',
'typing.OrderedDict': 'collections.OrderedDict',
}
# This keeps track of the oldest supported Python version where the corresponding
# alias source is available.
type_aliases_source_versions: Final = {
'typing.List': (2, 7),
'typing.Dict': (2, 7),
'typing.Set': (2, 7),
'typing.FrozenSet': (2, 7),
'typing.ChainMap': (3, 3),
'typing.Counter': (2, 7),
'typing.DefaultDict': (2, 7),
'typing.Deque': (2, 7),
'typing.OrderedDict': (3, 7),
}
# This keeps track of aliases in `typing_extensions`, which we treat specially.
typing_extensions_aliases: Final = {
# See: https://github.com/python/mypy/issues/11528
'typing_extensions.OrderedDict': 'collections.OrderedDict',
}
reverse_builtin_aliases: Final = {
'builtins.list': 'typing.List',
'builtins.dict': 'typing.Dict',
'builtins.set': 'typing.Set',
'builtins.frozenset': 'typing.FrozenSet',
}
_nongen_builtins: Final = {"builtins.tuple": "typing.Tuple", "builtins.enumerate": ""}
_nongen_builtins.update((name, alias) for alias, name in type_aliases.items())
# Drop OrderedDict from this for backward compatibility
del _nongen_builtins['collections.OrderedDict']
def get_nongen_builtins(python_version: Tuple[int, int]) -> Dict[str, str]:
# After 3.9 with pep585 generic builtins are allowed.
return _nongen_builtins if python_version < (3, 9) else {}
RUNTIME_PROTOCOL_DECOS: Final = (
"typing.runtime_checkable",
"typing_extensions.runtime",
"typing_extensions.runtime_checkable",
)
class Node(Context):
"""Common base class for all non-type parse tree nodes."""
__slots__ = ()
def __str__(self) -> str:
ans = self.accept(mypy.strconv.StrConv())
if ans is None:
return repr(self)
return ans
def accept(self, visitor: NodeVisitor[T]) -> T:
raise RuntimeError('Not implemented')
@trait
class Statement(Node):
"""A statement node."""
__slots__ = ()
def accept(self, visitor: StatementVisitor[T]) -> T:
raise RuntimeError('Not implemented')
@trait
class Expression(Node):
"""An expression node."""
__slots__ = ()
def accept(self, visitor: ExpressionVisitor[T]) -> T:
raise RuntimeError('Not implemented')
class FakeExpression(Expression):
"""A dummy expression.
We need a dummy expression in one place, and can't instantiate Expression
because it is a trait and mypyc barfs.
"""
__slots__ = ()
# TODO:
# Lvalue = Union['NameExpr', 'MemberExpr', 'IndexExpr', 'SuperExpr', 'StarExpr'
# 'TupleExpr']; see #1783.
Lvalue: _TypeAlias = Expression
@trait
class SymbolNode(Node):
"""Nodes that can be stored in a symbol table."""
__slots__ = ()
@property
@abstractmethod
def name(self) -> str: pass
# fullname can often be None even though the type system
# disagrees. We mark this with Bogus to let mypyc know not to
# worry about it.
@property
@abstractmethod
def fullname(self) -> Bogus[str]: pass
@abstractmethod
def serialize(self) -> JsonDict: pass
@classmethod
def deserialize(cls, data: JsonDict) -> 'SymbolNode':
classname = data['.class']
method = deserialize_map.get(classname)
if method is not None:
return method(data)
raise NotImplementedError('unexpected .class {}'.format(classname))
# Items: fullname, related symbol table node, surrounding type (if any)
Definition: _TypeAlias = Tuple[str, 'SymbolTableNode', Optional['TypeInfo']]
class MypyFile(SymbolNode):
"""The abstract syntax tree of a single source file."""
__slots__ = ('_fullname', 'path', 'defs', 'alias_deps',
'is_bom', 'names', 'imports', 'ignored_lines', 'is_stub',
'is_cache_skeleton', 'is_partial_stub_package', 'plugin_deps')
# Fully qualified module name
_fullname: Bogus[str]
# Path to the file (empty string if not known)
path: str
# Top-level definitions and statements
defs: List[Statement]
# Type alias dependencies as mapping from target to set of alias full names
alias_deps: DefaultDict[str, Set[str]]
# Is there a UTF-8 BOM at the start?
is_bom: bool
names: "SymbolTable"
# All import nodes within the file (also ones within functions etc.)
imports: List["ImportBase"]
# Lines on which to ignore certain errors when checking.
# If the value is empty, ignore all errors; otherwise, the list contains all
# error codes to ignore.
ignored_lines: Dict[int, List[str]]
# Is this file represented by a stub file (.pyi)?
is_stub: bool
# Is this loaded from the cache and thus missing the actual body of the file?
is_cache_skeleton: bool
# Does this represent an __init__.pyi stub with a module __getattr__
# (i.e. a partial stub package), for such packages we suppress any missing
# module errors in addition to missing attribute errors.
is_partial_stub_package: bool
# Plugin-created dependencies
plugin_deps: Dict[str, Set[str]]
def __init__(self,
defs: List[Statement],
imports: List['ImportBase'],
is_bom: bool = False,
ignored_lines: Optional[Dict[int, List[str]]] = None) -> None:
super().__init__()
self.defs = defs
self.line = 1 # Dummy line number
self.imports = imports
self.is_bom = is_bom
self.alias_deps = defaultdict(set)
self.plugin_deps = {}
if ignored_lines:
self.ignored_lines = ignored_lines
else:
self.ignored_lines = {}
self.path = ''
self.is_stub = False
self.is_cache_skeleton = False
self.is_partial_stub_package = False
def local_definitions(self) -> Iterator[Definition]:
"""Return all definitions within the module (including nested).
This doesn't include imported definitions.
"""
return local_definitions(self.names, self.fullname)
@property
def name(self) -> str:
return '' if not self._fullname else self._fullname.split('.')[-1]
@property
def fullname(self) -> Bogus[str]:
return self._fullname
def accept(self, visitor: NodeVisitor[T]) -> T:
return visitor.visit_mypy_file(self)
def is_package_init_file(self) -> bool:
return len(self.path) != 0 and os.path.basename(self.path).startswith('__init__.')
def serialize(self) -> JsonDict:
return {'.class': 'MypyFile',
'_fullname': self._fullname,
'names': self.names.serialize(self._fullname),
'is_stub': self.is_stub,
'path': self.path,
'is_partial_stub_package': self.is_partial_stub_package,
}
@classmethod
def deserialize(cls, data: JsonDict) -> 'MypyFile':
assert data['.class'] == 'MypyFile', data
tree = MypyFile([], [])
tree._fullname = data['_fullname']
tree.names = SymbolTable.deserialize(data['names'])
tree.is_stub = data['is_stub']
tree.path = data['path']
tree.is_partial_stub_package = data['is_partial_stub_package']
tree.is_cache_skeleton = True
return tree
class ImportBase(Statement):
"""Base class for all import statements."""
__slots__ = ('is_unreachable', 'is_top_level', 'is_mypy_only', 'assignments')
is_unreachable: bool # Set by semanal.SemanticAnalyzerPass1 if inside `if False` etc.
is_top_level: bool # Ditto if outside any class or def
is_mypy_only: bool # Ditto if inside `if TYPE_CHECKING` or `if MYPY`
# If an import replaces existing definitions, we construct dummy assignment
# statements that assign the imported names to the names in the current scope,
# for type checking purposes. Example:
#
# x = 1
# from m import x <-- add assignment representing "x = m.x"
assignments: List["AssignmentStmt"]
def __init__(self) -> None:
super().__init__()
self.assignments = []
self.is_unreachable = False
self.is_top_level = False
self.is_mypy_only = False
class Import(ImportBase):
"""import m [as n]"""
__slots__ = ('ids',)
ids: List[Tuple[str, Optional[str]]] # (module id, as id)
def __init__(self, ids: List[Tuple[str, Optional[str]]]) -> None:
super().__init__()
self.ids = ids
def accept(self, visitor: StatementVisitor[T]) -> T:
return visitor.visit_import(self)
class ImportFrom(ImportBase):
"""from m import x [as y], ..."""
__slots__ = ('id', 'names', 'relative')
id: str
relative: int
names: List[Tuple[str, Optional[str]]] # Tuples (name, as name)
def __init__(self, id: str, relative: int, names: List[Tuple[str, Optional[str]]]) -> None:
super().__init__()
self.id = id
self.names = names
self.relative = relative
def accept(self, visitor: StatementVisitor[T]) -> T:
return visitor.visit_import_from(self)
class ImportAll(ImportBase):
"""from m import *"""
__slots__ = ('id', 'relative', 'imported_names')
id: str
relative: int
# NOTE: Only filled and used by old semantic analyzer.
imported_names: List[str]
def __init__(self, id: str, relative: int) -> None:
super().__init__()
self.id = id
self.relative = relative
self.imported_names = []
def accept(self, visitor: StatementVisitor[T]) -> T:
return visitor.visit_import_all(self)
class ImportedName(SymbolNode):
"""Indirect reference to a fullname stored in symbol table.
This node is not present in the original program as such. This is
just a temporary artifact in binding imported names. After semantic
analysis pass 2, these references should be replaced with direct
reference to a real AST node.
Note that this is neither a Statement nor an Expression so this
can't be visited.
"""
__slots__ = ('target_fullname',)
def __init__(self, target_fullname: str) -> None:
super().__init__()
self.target_fullname = target_fullname
@property
def name(self) -> str:
return self.target_fullname.split('.')[-1]
@property
def fullname(self) -> str:
return self.target_fullname
def serialize(self) -> JsonDict:
assert False, "ImportedName leaked from semantic analysis"
@classmethod
def deserialize(cls, data: JsonDict) -> 'ImportedName':
assert False, "ImportedName should never be serialized"
def __str__(self) -> str:
return 'ImportedName(%s)' % self.target_fullname
FUNCBASE_FLAGS: Final = ["is_property", "is_class", "is_static", "is_final"]
class FuncBase(Node):
"""Abstract base class for function-like nodes.
N.B: Although this has SymbolNode subclasses (FuncDef,
OverloadedFuncDef), avoid calling isinstance(..., FuncBase) on
something that is typed as SymbolNode. This is to work around
mypy bug #3603, in which mypy doesn't understand multiple
inheritance very well, and will assume that a SymbolNode
cannot be a FuncBase.
Instead, test against SYMBOL_FUNCBASE_TYPES, which enumerates
SymbolNode subclasses that are also FuncBase subclasses.
"""
__slots__ = ('type',
'unanalyzed_type',
'info',
'is_property',
'is_class', # Uses "@classmethod" (explicit or implicit)
'is_static', # Uses "@staticmethod"
'is_final', # Uses "@final"
'_fullname',
)
def __init__(self) -> None:
super().__init__()
# Type signature. This is usually CallableType or Overloaded, but it can be
# something else for decorated functions.
self.type: Optional[mypy.types.ProperType] = None
# Original, not semantically analyzed type (used for reprocessing)
self.unanalyzed_type: Optional[mypy.types.ProperType] = None
# If method, reference to TypeInfo
# TODO: Type should be Optional[TypeInfo]
self.info = FUNC_NO_INFO
self.is_property = False
self.is_class = False
self.is_static = False
self.is_final = False
# Name with module prefix
# TODO: Type should be Optional[str]
self._fullname = cast(Bogus[str], None)
@property
@abstractmethod
def name(self) -> str: pass
@property
def fullname(self) -> Bogus[str]:
return self._fullname
OverloadPart: _TypeAlias = Union['FuncDef', 'Decorator']
class OverloadedFuncDef(FuncBase, SymbolNode, Statement):
"""A logical node representing all the variants of a multi-declaration function.
A multi-declaration function is often an @overload, but can also be a
@property with a setter and a/or a deleter.
This node has no explicit representation in the source program.
Overloaded variants must be consecutive in the source file.
"""
__slots__ = ('items', 'unanalyzed_items', 'impl')
items: List[OverloadPart]
unanalyzed_items: List[OverloadPart]
impl: Optional[OverloadPart]
def __init__(self, items: List['OverloadPart']) -> None:
super().__init__()
self.items = items
self.unanalyzed_items = items.copy()
self.impl = None
if len(items) > 0:
self.set_line(items[0].line, items[0].column)
self.is_final = False
@property
def name(self) -> str:
if self.items:
return self.items[0].name
else:
# This may happen for malformed overload
assert self.impl is not None
return self.impl.name
def accept(self, visitor: StatementVisitor[T]) -> T:
return visitor.visit_overloaded_func_def(self)
def serialize(self) -> JsonDict:
return {'.class': 'OverloadedFuncDef',
'items': [i.serialize() for i in self.items],
'type': None if self.type is None else self.type.serialize(),
'fullname': self._fullname,
'impl': None if self.impl is None else self.impl.serialize(),
'flags': get_flags(self, FUNCBASE_FLAGS),
}
@classmethod
def deserialize(cls, data: JsonDict) -> 'OverloadedFuncDef':
assert data['.class'] == 'OverloadedFuncDef'
res = OverloadedFuncDef([
cast(OverloadPart, SymbolNode.deserialize(d))
for d in data['items']])
if data.get('impl') is not None:
res.impl = cast(OverloadPart, SymbolNode.deserialize(data['impl']))
# set line for empty overload items, as not set in __init__
if len(res.items) > 0:
res.set_line(res.impl.line)
if data.get('type') is not None:
typ = mypy.types.deserialize_type(data['type'])
assert isinstance(typ, mypy.types.ProperType)
res.type = typ
res._fullname = data['fullname']
set_flags(res, data['flags'])
# NOTE: res.info will be set in the fixup phase.
return res
class Argument(Node):
"""A single argument in a FuncItem."""
__slots__ = ('variable', 'type_annotation', 'initializer', 'kind', 'pos_only')
def __init__(self,
variable: 'Var',
type_annotation: 'Optional[mypy.types.Type]',
initializer: Optional[Expression],
kind: 'ArgKind',
pos_only: bool = False) -> None:
super().__init__()
self.variable = variable
self.type_annotation = type_annotation
self.initializer = initializer
self.kind = kind # must be an ARG_* constant
self.pos_only = pos_only
def set_line(self,
target: Union[Context, int],
column: Optional[int] = None,
end_line: Optional[int] = None) -> None:
super().set_line(target, column, end_line)
if self.initializer and self.initializer.line < 0:
self.initializer.set_line(self.line, self.column, self.end_line)
self.variable.set_line(self.line, self.column, self.end_line)
FUNCITEM_FLAGS: Final = FUNCBASE_FLAGS + [
'is_overload', 'is_generator', 'is_coroutine', 'is_async_generator',
'is_awaitable_coroutine',
]
class FuncItem(FuncBase):
"""Base class for nodes usable as overloaded function items."""
__slots__ = ('arguments', # Note that can be None if deserialized (type is a lie!)
'arg_names', # Names of arguments
'arg_kinds', # Kinds of arguments
'min_args', # Minimum number of arguments
'max_pos', # Maximum number of positional arguments, -1 if no explicit
# limit (*args not included)
'body', # Body of the function
'is_overload', # Is this an overload variant of function with more than
# one overload variant?
'is_generator', # Contains a yield statement?
'is_coroutine', # Defined using 'async def' syntax?
'is_async_generator', # Is an async def generator?
'is_awaitable_coroutine', # Decorated with '@{typing,asyncio}.coroutine'?
'expanded', # Variants of function with type variables with values expanded
)
__deletable__ = ('arguments', 'max_pos', 'min_args')
def __init__(self,
arguments: List[Argument],
body: 'Block',
typ: 'Optional[mypy.types.FunctionLike]' = None) -> None:
super().__init__()
self.arguments = arguments
self.arg_names = [None if arg.pos_only else arg.variable.name for arg in arguments]
self.arg_kinds: List[ArgKind] = [arg.kind for arg in self.arguments]
self.max_pos: int = (
self.arg_kinds.count(ARG_POS) + self.arg_kinds.count(ARG_OPT))
self.body: 'Block' = body
self.type = typ
self.unanalyzed_type = typ
self.is_overload: bool = False
self.is_generator: bool = False
self.is_coroutine: bool = False
self.is_async_generator: bool = False
self.is_awaitable_coroutine: bool = False
self.expanded: List[FuncItem] = []
self.min_args = 0
for i in range(len(self.arguments)):
if self.arguments[i] is None and i < self.max_fixed_argc():
self.min_args = i + 1
def max_fixed_argc(self) -> int:
return self.max_pos
def set_line(self,
target: Union[Context, int],
column: Optional[int] = None,
end_line: Optional[int] = None) -> None:
super().set_line(target, column, end_line)
for arg in self.arguments:
arg.set_line(self.line, self.column, self.end_line)
def is_dynamic(self) -> bool:
return self.type is None
FUNCDEF_FLAGS: Final = FUNCITEM_FLAGS + [
'is_decorated', 'is_conditional', 'is_abstract',
]
class FuncDef(FuncItem, SymbolNode, Statement):
"""Function definition.
This is a non-lambda function defined using 'def'.
"""
__slots__ = ('_name',
'is_decorated',
'is_conditional',
'is_abstract',
'original_def',
)
def __init__(self,
name: str, # Function name
arguments: List[Argument],
body: 'Block',
typ: 'Optional[mypy.types.FunctionLike]' = None) -> None:
super().__init__(arguments, body, typ)
self._name = name
self.is_decorated = False
self.is_conditional = False # Defined conditionally (within block)?
self.is_abstract = False
self.is_final = False
# Original conditional definition
self.original_def: Union[None, FuncDef, Var, Decorator] = None
@property
def name(self) -> str:
return self._name
def accept(self, visitor: StatementVisitor[T]) -> T:
return visitor.visit_func_def(self)
def serialize(self) -> JsonDict:
# We're deliberating omitting arguments and storing only arg_names and
# arg_kinds for space-saving reasons (arguments is not used in later
# stages of mypy).
# TODO: After a FuncDef is deserialized, the only time we use `arg_names`
# and `arg_kinds` is when `type` is None and we need to infer a type. Can
# we store the inferred type ahead of time?
return {'.class': 'FuncDef',
'name': self._name,
'fullname': self._fullname,
'arg_names': self.arg_names,
'arg_kinds': [int(x.value) for x in self.arg_kinds],
'type': None if self.type is None else self.type.serialize(),
'flags': get_flags(self, FUNCDEF_FLAGS),
# TODO: Do we need expanded, original_def?
}
@classmethod
def deserialize(cls, data: JsonDict) -> 'FuncDef':
assert data['.class'] == 'FuncDef'
body = Block([])
ret = FuncDef(data['name'],
[],
body,
(None if data['type'] is None
else cast(mypy.types.FunctionLike,
mypy.types.deserialize_type(data['type']))))
ret._fullname = data['fullname']
set_flags(ret, data['flags'])
# NOTE: ret.info is set in the fixup phase.
ret.arg_names = data['arg_names']
ret.arg_kinds = [ArgKind(x) for x in data['arg_kinds']]
# Leave these uninitialized so that future uses will trigger an error
del ret.arguments
del ret.max_pos
del ret.min_args
return ret
# All types that are both SymbolNodes and FuncBases. See the FuncBase
# docstring for the rationale.
SYMBOL_FUNCBASE_TYPES = (OverloadedFuncDef, FuncDef)
class Decorator(SymbolNode, Statement):
"""A decorated function.
A single Decorator object can include any number of function decorators.
"""
__slots__ = ('func', 'decorators', 'original_decorators', 'var', 'is_overload')
func: FuncDef # Decorated function
decorators: List[Expression] # Decorators (may be empty)
# Some decorators are removed by semanal, keep the original here.
original_decorators: List[Expression]
# TODO: This is mostly used for the type; consider replacing with a 'type' attribute
var: "Var" # Represents the decorated function obj
is_overload: bool
def __init__(self, func: FuncDef, decorators: List[Expression],
var: 'Var') -> None:
super().__init__()
self.func = func
self.decorators = decorators
self.original_decorators = decorators.copy()
self.var = var
self.is_overload = False
@property
def name(self) -> str:
return self.func.name
@property
def fullname(self) -> Bogus[str]:
return self.func.fullname
@property
def is_final(self) -> bool:
return self.func.is_final
@property
def info(self) -> 'TypeInfo':
return self.func.info
@property
def type(self) -> 'Optional[mypy.types.Type]':
return self.var.type
def accept(self, visitor: StatementVisitor[T]) -> T:
return visitor.visit_decorator(self)
def serialize(self) -> JsonDict:
return {'.class': 'Decorator',
'func': self.func.serialize(),
'var': self.var.serialize(),
'is_overload': self.is_overload,
}
@classmethod
def deserialize(cls, data: JsonDict) -> 'Decorator':
assert data['.class'] == 'Decorator'
dec = Decorator(FuncDef.deserialize(data['func']),
[],
Var.deserialize(data['var']))
dec.is_overload = data['is_overload']
return dec
VAR_FLAGS: Final = [
'is_self', 'is_initialized_in_class', 'is_staticmethod',
'is_classmethod', 'is_property', 'is_settable_property', 'is_suppressed_import',
'is_classvar', 'is_abstract_var', 'is_final', 'final_unset_in_class', 'final_set_in_init',
'explicit_self_type', 'is_ready', 'from_module_getattr',
'has_explicit_value',
]
class Var(SymbolNode):
"""A variable.
It can refer to global/local variable or a data attribute.
"""
__slots__ = ('_name',
'_fullname',
'info',
'type',
'final_value',
'is_self',
'is_ready',
'is_inferred',
'is_initialized_in_class',
'is_staticmethod',
'is_classmethod',
'is_property',
'is_settable_property',
'is_classvar',
'is_abstract_var',
'is_final',
'final_unset_in_class',
'final_set_in_init',
'is_suppressed_import',
'explicit_self_type',
'from_module_getattr',
'has_explicit_value',
)
def __init__(self, name: str, type: 'Optional[mypy.types.Type]' = None) -> None:
super().__init__()
self._name = name # Name without module prefix
# TODO: Should be Optional[str]
self._fullname = cast('Bogus[str]', None) # Name with module prefix
# TODO: Should be Optional[TypeInfo]
self.info = VAR_NO_INFO
self.type: Optional[mypy.types.Type] = type # Declared or inferred type, or None
# Is this the first argument to an ordinary method (usually "self")?
self.is_self = False
self.is_ready = True # If inferred, is the inferred type available?
self.is_inferred = (self.type is None)
# Is this initialized explicitly to a non-None value in class body?
self.is_initialized_in_class = False
self.is_staticmethod = False
self.is_classmethod = False
self.is_property = False
self.is_settable_property = False
self.is_classvar = False
self.is_abstract_var = False
# Set to true when this variable refers to a module we were unable to
# parse for some reason (eg a silenced module)
self.is_suppressed_import = False
# Was this "variable" (rather a constant) defined as Final[...]?
self.is_final = False
# If constant value is a simple literal,
# store the literal value (unboxed) for the benefit of
# tools like mypyc.
self.final_value: Optional[Union[int, float, bool, str]] = None
# Where the value was set (only for class attributes)
self.final_unset_in_class = False
self.final_set_in_init = False
# This is True for a variable that was declared on self with an explicit type:
# class C:
# def __init__(self) -> None:
# self.x: int
# This case is important because this defines a new Var, even if there is one
# present in a superclass (without explicit type this doesn't create a new Var).
# See SemanticAnalyzer.analyze_member_lvalue() for details.
self.explicit_self_type = False
# If True, this is an implicit Var created due to module-level __getattr__.
self.from_module_getattr = False
# Var can be created with an explicit value `a = 1` or without one `a: int`,
# we need a way to tell which one is which.
self.has_explicit_value = False
@property
def name(self) -> str:
return self._name
@property
def fullname(self) -> Bogus[str]:
return self._fullname
def accept(self, visitor: NodeVisitor[T]) -> T:
return visitor.visit_var(self)
def serialize(self) -> JsonDict:
# TODO: Leave default values out?
# NOTE: Sometimes self.is_ready is False here, but we don't care.
data: JsonDict = {
".class": "Var",
"name": self._name,
"fullname": self._fullname,
"type": None if self.type is None else self.type.serialize(),
"flags": get_flags(self, VAR_FLAGS),
}
if self.final_value is not None:
data['final_value'] = self.final_value
return data
@classmethod
def deserialize(cls, data: JsonDict) -> 'Var':
assert data['.class'] == 'Var'
name = data['name']
type = None if data['type'] is None else mypy.types.deserialize_type(data['type'])
v = Var(name, type)
v.is_ready = False # Override True default set in __init__
v._fullname = data['fullname']
set_flags(v, data['flags'])
v.final_value = data.get('final_value')
return v
class ClassDef(Statement):
"""Class definition"""
__slots__ = ('name', 'fullname', 'defs', 'type_vars', 'base_type_exprs',
'removed_base_type_exprs', 'info', 'metaclass', 'decorators',
'keywords', 'analyzed', 'has_incompatible_baseclass')
name: str # Name of the class without module prefix
fullname: Bogus[str] # Fully qualified name of the class
defs: "Block"
type_vars: List["mypy.types.TypeVarLikeType"]
# Base class expressions (not semantically analyzed -- can be arbitrary expressions)
base_type_exprs: List[Expression]
# Special base classes like Generic[...] get moved here during semantic analysis
removed_base_type_exprs: List[Expression]
info: "TypeInfo" # Related TypeInfo
metaclass: Optional[Expression]
decorators: List[Expression]
keywords: "OrderedDict[str, Expression]"
analyzed: Optional[Expression]
has_incompatible_baseclass: bool
def __init__(self,
name: str,
defs: 'Block',
type_vars: Optional[List['mypy.types.TypeVarLikeType']] = None,
base_type_exprs: Optional[List[Expression]] = None,
metaclass: Optional[Expression] = None,
keywords: Optional[List[Tuple[str, Expression]]] = None) -> None:
super().__init__()
self.name = name
self.fullname = None # type: ignore
self.defs = defs
self.type_vars = type_vars or []
self.base_type_exprs = base_type_exprs or []
self.removed_base_type_exprs = []
self.info = CLASSDEF_NO_INFO
self.metaclass = metaclass
self.decorators = []
self.keywords = OrderedDict(keywords or [])