-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Expand file tree
/
Copy pathnodes.py
More file actions
5504 lines (4551 loc) · 181 KB
/
nodes.py
File metadata and controls
5504 lines (4551 loc) · 181 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
"""Abstract syntax tree node classes (i.e. parse tree)."""
from __future__ import annotations
import os
from abc import abstractmethod
from collections import defaultdict
from collections.abc import Callable, Iterator, Sequence
from contextlib import contextmanager
from enum import Enum, unique
from typing import (
TYPE_CHECKING,
Any,
Final,
Optional,
TypeAlias as _TypeAlias,
TypedDict,
TypeGuard,
TypeVar,
Union,
cast,
)
from typing_extensions import NotRequired
from librt.internal import (
extract_symbol,
read_float as read_float_bare,
read_int as read_int_bare,
read_str as read_str_bare,
write_int as write_int_bare,
write_str as write_str_bare,
)
from mypy_extensions import trait
import mypy.strconv
from mypy.cache import (
DICT_INT_GEN,
DICT_STR_GEN,
DT_SPEC,
END_TAG,
LIST_GEN,
LIST_STR,
LITERAL_COMPLEX,
LITERAL_FALSE,
LITERAL_NONE,
LITERAL_TRUE,
ReadBuffer,
Tag,
WriteBuffer,
read_bool,
read_bytes,
read_int,
read_int_list,
read_int_opt,
read_json,
read_literal,
read_str,
read_str_list,
read_str_opt,
read_str_opt_list,
read_tag,
write_bool,
write_bytes,
write_int,
write_int_list,
write_int_opt,
write_json,
write_literal,
write_str,
write_str_list,
write_str_opt,
write_str_opt_list,
write_tag,
)
from mypy.modules_state import modules_state
from mypy.options import Options
from mypy.util import is_sunder, is_typeshed_file, short_type
from mypy.visitor import ExpressionVisitor, NodeVisitor, StatementVisitor
if TYPE_CHECKING:
from mypy.patterns import Pattern
@unique
class NotParsed(Enum):
VALUE = "NotParsed"
class Context:
"""Base type for objects that are valid as error message locations."""
__slots__ = ("line", "column", "end_line", "end_column")
def __init__(self, line: int = -1, column: int = -1) -> None:
self.line = line
self.column = column
self.end_line: int | None = None
self.end_column: int | None = None
def set_line(
self,
target: Context | int,
column: int | None = None,
end_line: int | None = None,
end_column: int | None = 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
self.end_column = target.end_column
if column is not None:
self.column = column
if end_line is not None:
self.end_line = end_line
if end_column is not None:
self.end_column = end_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
# Kinds of 'literal' expressions.
#
# Use the function mypy.literals.literal to calculate these.
#
# TODO: Can we make these less confusing?
LITERAL_YES: Final = 2 # Value of expression known statically
LITERAL_TYPE: Final = 1 # Type of expression can be narrowed (e.g. variable reference)
LITERAL_NO: Final = 0 # None of the above
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",
"__annotations__": None, # dict[str, Any] bounded in add_implicit_module_attrs()
"__spec__": None, # importlib.machinery.ModuleSpec bounded in add_implicit_module_attrs()
}
# 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",
# HACK: a lie in lieu of actual support for PEP 675
"typing.LiteralString": "builtins.str",
}
# This keeps track of the oldest supported Python version where the corresponding
# alias source is available.
type_aliases_source_versions: Final = {"typing.LiteralString": (3, 11)}
# 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",
# HACK: a lie in lieu of actual support for PEP 675
"typing_extensions.LiteralString": "builtins.str",
}
reverse_builtin_aliases: Final = {
"builtins.list": "typing.List",
"builtins.dict": "typing.Dict",
"builtins.set": "typing.Set",
"builtins.frozenset": "typing.FrozenSet",
}
RUNTIME_PROTOCOL_DECOS: Final = (
"typing.runtime_checkable",
"typing_extensions.runtime",
"typing_extensions.runtime_checkable",
)
LAMBDA_NAME: Final = "<lambda>"
class Node(Context):
"""Common base class for all non-type parse tree nodes."""
__slots__ = ()
def __str__(self) -> str:
return self.accept(mypy.strconv.StrConv(options=Options()))
def str_with_options(self, options: Options) -> str:
a = self.accept(mypy.strconv.StrConv(options=options))
assert a
return a
def accept(self, visitor: NodeVisitor[T]) -> T:
raise RuntimeError("Not implemented", type(self))
@trait
class Statement(Node):
"""A statement node."""
__slots__ = ()
def accept(self, visitor: StatementVisitor[T]) -> T:
raise RuntimeError("Not implemented", type(self))
@trait
class Expression(Node):
"""An expression node."""
__slots__ = ()
def accept(self, visitor: ExpressionVisitor[T]) -> T:
raise RuntimeError("Not implemented", type(self))
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
# Fully qualified name
@property
@abstractmethod
def fullname(self) -> 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(f"unexpected .class {classname}")
def write(self, data: WriteBuffer) -> None:
raise NotImplementedError(f"Cannot serialize {self.__class__.__name__} instance")
@classmethod
def read(cls, data: ReadBuffer) -> SymbolNode:
raise NotImplementedError(f"Cannot deserialize {cls.__name__} instance")
# Items: fullname, related symbol table node, surrounding type (if any)
Definition: _TypeAlias = tuple[str, "SymbolTableNode", Optional["TypeInfo"]]
class ParseError(TypedDict):
line: int
column: int
message: str
blocker: NotRequired[bool]
code: NotRequired[str]
def write_parse_error(data: WriteBuffer, err: ParseError) -> None:
write_int(data, err["line"])
write_int(data, err["column"])
write_str(data, err["message"])
if (blocker := err.get("blocker")) is not None:
write_bool(data, blocker)
else:
write_tag(data, LITERAL_NONE)
write_str_opt(data, err.get("code"))
def read_parse_error(data: ReadBuffer) -> ParseError:
err: ParseError = {"line": read_int(data), "column": read_int(data), "message": read_str(data)}
tag = read_tag(data)
if tag == LITERAL_TRUE:
err["blocker"] = True
elif tag == LITERAL_FALSE:
err["blocker"] = False
else:
assert tag == LITERAL_NONE
if (code := read_str_opt(data)) is not None:
err["code"] = code
return err
class FileRawData:
"""Raw (binary) data representing parsed, but not deserialized file."""
__slots__ = (
"defs",
"imports",
"raw_errors",
"ignored_lines",
"is_partial_stub_package",
"uses_template_strings",
"source_hash",
"mypy_comments",
)
defs: bytes
imports: bytes
raw_errors: list[ParseError]
ignored_lines: dict[int, list[str]]
is_partial_stub_package: bool
uses_template_strings: bool
source_hash: str
mypy_comments: list[tuple[int, str]]
def __init__(
self,
defs: bytes,
imports: bytes,
raw_errors: list[ParseError],
ignored_lines: dict[int, list[str]],
is_partial_stub_package: bool,
uses_template_strings: bool,
source_hash: str = "",
mypy_comments: list[tuple[int, str]] | None = None,
) -> None:
self.defs = defs
self.imports = imports
self.raw_errors = raw_errors
self.ignored_lines = ignored_lines
self.is_partial_stub_package = is_partial_stub_package
self.uses_template_strings = uses_template_strings
self.source_hash = source_hash
self.mypy_comments = mypy_comments if mypy_comments is not None else []
def write(self, data: WriteBuffer) -> None:
write_bytes(data, self.defs)
write_bytes(data, self.imports)
write_tag(data, LIST_GEN)
write_int_bare(data, len(self.raw_errors))
for err in self.raw_errors:
write_parse_error(data, err)
write_tag(data, DICT_INT_GEN)
write_int_bare(data, len(self.ignored_lines))
for line, codes in self.ignored_lines.items():
write_int(data, line)
write_str_list(data, codes)
write_bool(data, self.is_partial_stub_package)
write_bool(data, self.uses_template_strings)
write_str(data, self.source_hash)
write_tag(data, LIST_GEN)
write_int_bare(data, len(self.mypy_comments))
for line, text in self.mypy_comments:
write_int(data, line)
write_str(data, text)
@classmethod
def read(cls, data: ReadBuffer) -> FileRawData:
defs = read_bytes(data)
imports = read_bytes(data)
assert read_tag(data) == LIST_GEN
raw_errors = [read_parse_error(data) for _ in range(read_int_bare(data))]
assert read_tag(data) == DICT_INT_GEN
ignored_lines = {read_int(data): read_str_list(data) for _ in range(read_int_bare(data))}
is_partial_stub_package = read_bool(data)
uses_template_strings = read_bool(data)
source_hash = read_str(data)
assert read_tag(data) == LIST_GEN
mypy_comments = [(read_int(data), read_str(data)) for _ in range(read_int_bare(data))]
return FileRawData(
defs,
imports,
raw_errors,
ignored_lines,
is_partial_stub_package,
uses_template_strings,
source_hash,
mypy_comments,
)
class MypyFile(SymbolNode):
"""The abstract syntax tree of a single source file."""
__slots__ = (
"_fullname",
"path",
"defs",
"alias_deps",
"module_refs",
"is_bom",
"names",
"imports",
"ignored_lines",
"skipped_lines",
"is_stub",
"is_cache_skeleton",
"is_partial_stub_package",
"uses_template_strings",
"plugin_deps",
"future_import_flags",
"_is_typeshed_file",
"raw_data",
)
__match_args__ = ("name", "path", "defs")
# Fully qualified module name
_fullname: 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]]
# The set of all dependencies (suppressed or not) that this module accesses, either
# directly or indirectly.
module_refs: 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]]
# Lines that were skipped during semantic analysis e.g. due to ALWAYS_FALSE, MYPY_FALSE,
# or platform/version checks. Those lines would not be type-checked.
skipped_lines: set[int]
# 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
# True if module contains at least one t-string (PEP 750 TemplateStr).
uses_template_strings: bool
# Plugin-created dependencies
plugin_deps: dict[str, set[str]]
# Future imports defined in this file. Populated during semantic analysis.
future_import_flags: set[str]
_is_typeshed_file: bool | None
# For native parser store actual serialized data here.
raw_data: FileRawData | None
def __init__(
self,
defs: list[Statement],
imports: list[ImportBase],
is_bom: bool = False,
ignored_lines: dict[int, list[str]] | None = None,
) -> None:
super().__init__()
self.defs = defs
self.line = 1 # Dummy line number
self.column = 0 # Dummy column
self.imports = imports
self.is_bom = is_bom
self.alias_deps = defaultdict(set)
self.module_refs = set()
self.plugin_deps = {}
if ignored_lines:
self.ignored_lines = ignored_lines
else:
self.ignored_lines = {}
self.skipped_lines = set()
self.path = ""
self.is_stub = False
self.is_cache_skeleton = False
self.is_partial_stub_package = False
self.uses_template_strings = False
self.future_import_flags = set()
self._is_typeshed_file = None
self.raw_data = None
def local_definitions(self, *, impl_only: bool = False) -> Iterator[Definition]:
"""Return all definitions within the module (including nested).
This doesn't include imported definitions.
"""
return local_definitions(self.names, self.fullname, impl_only=impl_only)
@property
def name(self) -> str:
return "" if not self._fullname else self._fullname.split(".")[-1]
@property
def fullname(self) -> 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 is_future_flag_set(self, flag: str) -> bool:
return flag in self.future_import_flags
def is_typeshed_file(self, options: Options) -> bool:
# Cache result since this is called a lot
if self._is_typeshed_file is None:
self._is_typeshed_file = is_typeshed_file(options.abs_custom_typeshed_dir, self.path)
return self._is_typeshed_file
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,
"future_import_flags": sorted(self.future_import_flags),
}
@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
tree.future_import_flags = set(data["future_import_flags"])
return tree
def write(self, data: WriteBuffer) -> None:
write_tag(data, MYPY_FILE)
write_str(data, self._fullname)
self.names.write(data, self._fullname)
write_bool(data, self.is_stub)
write_str(data, self.path)
write_bool(data, self.is_partial_stub_package)
write_str_list(data, sorted(self.future_import_flags))
write_tag(data, END_TAG)
@classmethod
def read(cls, data: ReadBuffer) -> MypyFile:
assert read_tag(data) == MYPY_FILE
tree = MypyFile([], [])
tree._fullname = read_str(data)
tree.names = SymbolTable.read(data)
tree.is_stub = read_bool(data)
tree.path = read_str(data)
tree.is_partial_stub_package = read_bool(data)
tree.future_import_flags = set(read_str_list(data))
tree.is_cache_skeleton = True
assert read_tag(data) == END_TAG
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",)
__match_args__ = ("ids",)
ids: list[tuple[str, str | None]] # (module id, as id)
def __init__(self, ids: list[tuple[str, str | None]]) -> 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")
__match_args__ = ("id", "names", "relative")
id: str
relative: int
names: list[tuple[str, str | None]] # Tuples (name, as name)
def __init__(self, id: str, relative: int, names: list[tuple[str, str | None]]) -> 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")
__match_args__ = ("id", "relative")
id: str
relative: int
def __init__(self, id: str, relative: int) -> None:
super().__init__()
self.id = id
self.relative = relative
def accept(self, visitor: StatementVisitor[T]) -> T:
return visitor.visit_import_all(self)
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" (explicit or implicit)
"is_final", # Uses "@final"
"is_explicit_override", # Uses "@override"
"is_type_check_only", # Uses "@type_check_only"
"def_or_infer_vars",
"_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: mypy.types.ProperType | None = None
# Original, not semantically analyzed type (used for reprocessing)
self.unanalyzed_type: mypy.types.ProperType | None = None
# If method, reference to TypeInfo
self.info = FUNC_NO_INFO
self.is_property = False
self.is_class = False
# Is this a `@staticmethod` (explicit or implicit)?
# Note: use has_self_or_cls_argument to check if there is `self` or `cls` argument
self.is_static = False
self.is_final = False
self.is_explicit_override = False
self.is_type_check_only = False
# Can this function/method define variables or infer variables defined outside?
# In particular, we set this in cases like:
# x = None
# def foo() -> None:
# global x
# x = 1
# and
# class C:
# x = None
# def foo(self) -> None:
# self.x = 1
self.def_or_infer_vars = False
# Name with module prefix
self._fullname = ""
@property
@abstractmethod
def name(self) -> str:
pass
@property
def fullname(self) -> str:
return self._fullname
@property
def has_self_or_cls_argument(self) -> bool:
"""If used as a method, does it have an argument for method binding (`self`, `cls`)?
This is true for `__new__` even though `__new__` does not undergo method binding,
because we still usually assume that `cls` corresponds to the enclosing class.
"""
return not self.is_static or self.name == "__new__"
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",
"deprecated",
"setter_index",
"_is_trivial_self",
)
items: list[OverloadPart]
unanalyzed_items: list[OverloadPart]
impl: OverloadPart | None
deprecated: str | None
setter_index: int | None
def __init__(self, items: list[OverloadPart]) -> None:
super().__init__()
self.items = items
self.unanalyzed_items = items.copy()
self.impl = None
self.deprecated = None
self.setter_index = None
self._is_trivial_self: bool | None = None
if items:
# TODO: figure out how to reliably set end position (we don't know the impl here).
self.set_line(items[0].line, items[0].column)
@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
@property
def is_trivial_self(self) -> bool:
"""Check we can use bind_self() fast path for this overload.
This will return False if at least one overload:
* Has an explicit self annotation, or Self in signature.
* Has a non-trivial decorator.
"""
if self._is_trivial_self is not None:
return self._is_trivial_self
for i, item in enumerate(self.items):
# Note: bare @property is removed in visit_decorator().
trivial = 1 if i > 0 or not self.is_property else 0
if isinstance(item, FuncDef):
if not item.is_trivial_self:
self._is_trivial_self = False
return False
elif len(item.decorators) > trivial or not item.func.is_trivial_self:
self._is_trivial_self = False
return False
self._is_trivial_self = True
return True
@property
def setter(self) -> Decorator:
# Do some consistency checks first.
first_item = self.items[0]
assert isinstance(first_item, Decorator)
assert first_item.var.is_settable_property
assert self.setter_index is not None
item = self.items[self.setter_index]
assert isinstance(item, Decorator)
return item
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),
"deprecated": self.deprecated,
"setter_index": self.setter_index,
}
@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"])
res.deprecated = data["deprecated"]
res.setter_index = data["setter_index"]
# NOTE: res.info will be set in the fixup phase.
return res
def write(self, data: WriteBuffer) -> None:
write_tag(data, OVERLOADED_FUNC_DEF)
write_tag(data, LIST_GEN)
write_int_bare(data, len(self.items))
for item in self.items:
item.write(data)
mypy.types.write_type_opt(data, self.type)
write_str(data, self._fullname)
if self.impl is None:
write_tag(data, LITERAL_NONE)
else:
self.impl.write(data)
write_flags(data, [self.is_property, self.is_class, self.is_static, self.is_final])
write_str_opt(data, self.deprecated)
write_int_opt(data, self.setter_index)
write_tag(data, END_TAG)
@classmethod
def read(cls, data: ReadBuffer) -> OverloadedFuncDef:
assert read_tag(data) == LIST_GEN
res = OverloadedFuncDef([read_overload_part(data) for _ in range(read_int_bare(data))])
typ = mypy.types.read_type_opt(data)
if typ is not None:
assert isinstance(typ, mypy.types.ProperType)
res.type = typ
res._fullname = read_str(data)
tag = read_tag(data)
if tag != LITERAL_NONE:
res.impl = read_overload_part(data, tag)
# set line for empty overload items, as not set in __init__
if len(res.items) > 0:
res.set_line(res.impl.line)
res.is_property, res.is_class, res.is_static, res.is_final = read_flags(data, num_flags=4)
res.deprecated = read_str_opt(data)
res.setter_index = read_int_opt(data)
# NOTE: res.info will be set in the fixup phase.
assert read_tag(data) == END_TAG
return res
def is_dynamic(self) -> bool:
return all(item.is_dynamic() for item in self.items)
class Argument(Node):
"""A single argument in a FuncItem."""
__slots__ = ("variable", "type_annotation", "initializer", "kind", "pos_only")
__match_args__ = ("variable", "type_annotation", "initializer", "kind", "pos_only")
def __init__(
self,
variable: Var,
type_annotation: mypy.types.Type | None,
initializer: Expression | None,
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: Context | int,
column: int | None = None,
end_line: int | None = None,
end_column: int | None = None,
) -> None:
super().set_line(target, column, end_line, end_column)
if self.initializer and self.initializer.line < 0:
self.initializer.set_line(self.line, self.column, self.end_line, self.end_column)
self.variable.set_line(self.line, self.column, self.end_line, self.end_column)
# These specify the kind of a TypeParam
TYPE_VAR_KIND: Final = 0
PARAM_SPEC_KIND: Final = 1
TYPE_VAR_TUPLE_KIND: Final = 2
class TypeParam:
__slots__ = ("name", "kind", "upper_bound", "values", "default")
def __init__(
self,
name: str,
kind: int,
upper_bound: mypy.types.Type | None,
values: list[mypy.types.Type],
default: mypy.types.Type | None,
) -> None:
self.name = name