-
Notifications
You must be signed in to change notification settings - Fork 192
/
scope_provider.py
1179 lines (974 loc) · 44.2 KB
/
scope_provider.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
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import abc
import builtins
from collections import defaultdict
from contextlib import contextmanager
from dataclasses import dataclass
from enum import auto, Enum
from typing import (
Collection,
Dict,
Iterator,
List,
Mapping,
MutableMapping,
Optional,
Set,
Tuple,
Type,
Union,
)
import libcst as cst
from libcst import ensure_type
from libcst._add_slots import add_slots
from libcst.helpers import get_full_name_for_node
from libcst.metadata.base_provider import BatchableMetadataProvider
from libcst.metadata.expression_context_provider import (
ExpressionContext,
ExpressionContextProvider,
)
# Comprehensions are handled separately in _visit_comp_alike due to
# the complexity of the semantics
_ASSIGNMENT_LIKE_NODES = (
cst.AnnAssign,
cst.AsName,
cst.Assign,
cst.AugAssign,
cst.ClassDef,
cst.CompFor,
cst.FunctionDef,
cst.Global,
cst.Import,
cst.ImportFrom,
cst.NamedExpr,
cst.Nonlocal,
cst.Parameters,
cst.WithItem,
)
@add_slots
@dataclass(frozen=False)
class Access:
"""
An Access records an access of an assignment.
.. note::
This scope analysis only analyzes access via a :class:`~libcst.Name` or a :class:`~libcst.Name`
node embedded in other node like :class:`~libcst.Call` or :class:`~libcst.Attribute`.
It doesn't support type annontation using :class:`~libcst.SimpleString` literal for forward
references. E.g. in this example, the ``"Tree"`` isn't parsed as an access::
class Tree:
def __new__(cls) -> "Tree":
...
"""
#: The node of the access. A name is an access when the expression context is
#: :attr:`ExpressionContext.LOAD`. This is usually the name node representing the
#: access, except for: 1) dotted imports, when it might be the attribute that
#: represents the most specific part of the imported symbol; and 2) string
#: annotations, when it is the entire string literal
node: Union[cst.Name, cst.Attribute, cst.BaseString]
#: The scope of the access. Note that a access could be in a child scope of its
#: assignment.
scope: "Scope"
is_annotation: bool
is_type_hint: bool
__assignments: Set["BaseAssignment"]
__index: int
def __init__(
self, node: cst.Name, scope: "Scope", is_annotation: bool, is_type_hint: bool
) -> None:
self.node = node
self.scope = scope
self.is_annotation = is_annotation
self.is_type_hint = is_type_hint
self.__assignments = set()
self.__index = scope._assignment_count
def __hash__(self) -> int:
return id(self)
@property
def referents(self) -> Collection["BaseAssignment"]:
"""Return all assignments of the access."""
return self.__assignments
@property
def _index(self) -> int:
return self.__index
def record_assignment(self, assignment: "BaseAssignment") -> None:
if assignment.scope != self.scope or assignment._index < self.__index:
self.__assignments.add(assignment)
def record_assignments(self, name: str) -> None:
assignments = self.scope[name]
# filter out assignments that happened later than this access
previous_assignments = {
assignment
for assignment in assignments
if assignment.scope != self.scope or assignment._index < self.__index
}
if not previous_assignments and assignments and self.scope.parent != self.scope:
previous_assignments = self.scope.parent[name]
self.__assignments |= previous_assignments
class QualifiedNameSource(Enum):
IMPORT = auto()
BUILTIN = auto()
LOCAL = auto()
@add_slots
@dataclass(frozen=True)
class QualifiedName:
#: Qualified name, e.g. ``a.b.c`` or ``fn.<locals>.var``.
name: str
#: Source of the name, either :attr:`QualifiedNameSource.IMPORT`, :attr:`QualifiedNameSource.BUILTIN`
#: or :attr:`QualifiedNameSource.LOCAL`.
source: QualifiedNameSource
class BaseAssignment(abc.ABC):
"""Abstract base class of :class:`Assignment` and :class:`BuitinAssignment`."""
#: The name of assignment.
name: str
#: The scope associates to assignment.
scope: "Scope"
__accesses: Set[Access]
def __init__(self, name: str, scope: "Scope") -> None:
self.name = name
self.scope = scope
self.__accesses = set()
def record_access(self, access: Access) -> None:
if access.scope != self.scope or self._index < access._index:
self.__accesses.add(access)
def record_accesses(self, accesses: Set[Access]) -> None:
later_accesses = {
access
for access in accesses
if access.scope != self.scope or self._index < access._index
}
self.__accesses |= later_accesses
earlier_accesses = accesses - later_accesses
if earlier_accesses and self.scope.parent != self.scope:
# Accesses "earlier" than the relevant assignment should be attached
# to assignments of the same name in the parent
for shadowed_assignment in self.scope.parent[self.name]:
shadowed_assignment.record_accesses(earlier_accesses)
@property
def references(self) -> Collection[Access]:
"""Return all accesses of the assignment."""
# we don't want to publicly expose the mutable version of this
return self.__accesses
def __hash__(self) -> int:
return id(self)
@property
def _index(self) -> int:
"""Return an integer that represents the order of assignments in `scope`"""
return -1
@abc.abstractmethod
def get_qualified_names_for(self, full_name: str) -> Set[QualifiedName]:
...
class Assignment(BaseAssignment):
"""An assignment records the name, CSTNode and its accesses."""
#: The node of assignment, it could be a :class:`~libcst.Import`, :class:`~libcst.ImportFrom`,
#: :class:`~libcst.Name`, :class:`~libcst.FunctionDef`, or :class:`~libcst.ClassDef`.
node: cst.CSTNode
__index: int
def __init__(
self, name: str, scope: "Scope", node: cst.CSTNode, index: int
) -> None:
self.node = node
self.__index = index
super().__init__(name, scope)
@property
def _index(self) -> int:
return self.__index
def get_qualified_names_for(self, full_name: str) -> Set[QualifiedName]:
scope = self.scope
name_prefixes = []
while scope:
if isinstance(scope, ClassScope):
name_prefixes.append(scope.name)
elif isinstance(scope, FunctionScope):
name_prefixes.append(f"{scope.name}.<locals>")
elif isinstance(scope, ComprehensionScope):
name_prefixes.append("<comprehension>")
elif not isinstance(scope, (GlobalScope, BuiltinScope)):
raise Exception(f"Unexpected Scope: {scope}")
scope = scope.parent if scope.parent != scope else None
parts = [*reversed(name_prefixes)]
if full_name:
parts.append(full_name)
return {QualifiedName(".".join(parts), QualifiedNameSource.LOCAL)}
# even though we don't override the constructor.
class BuiltinAssignment(BaseAssignment):
"""
A BuiltinAssignment represents an value provide by Python as a builtin, including
`functions <https://docs.python.org/3/library/functions.html>`_,
`constants <https://docs.python.org/3/library/constants.html>`_, and
`types <https://docs.python.org/3/library/stdtypes.html>`_.
"""
def get_qualified_names_for(self, full_name: str) -> Set[QualifiedName]:
return {QualifiedName(f"builtins.{self.name}", QualifiedNameSource.BUILTIN)}
class ImportAssignment(Assignment):
"""An assignment records the import node and it's alias"""
as_name: cst.CSTNode
def __init__(
self,
name: str,
scope: "Scope",
node: cst.CSTNode,
index: int,
as_name: cst.CSTNode,
) -> None:
super().__init__(name, scope, node, index)
self.as_name = as_name
def get_module_name_for_import(self) -> str:
module = ""
if isinstance(self.node, cst.ImportFrom):
module_attr = self.node.module
relative = self.node.relative
if module_attr:
module = get_full_name_for_node(module_attr) or ""
if relative:
module = "." * len(relative) + module
return module
def get_qualified_names_for(self, full_name: str) -> Set[QualifiedName]:
module = self.get_module_name_for_import()
results = set()
assert isinstance(self.node, (cst.ImportFrom, cst.Import))
import_names = self.node.names
if not isinstance(import_names, cst.ImportStar):
for name in import_names:
real_name = get_full_name_for_node(name.name)
if not real_name:
continue
# real_name can contain `.` for dotted imports
# for these we want to find the longest prefix that matches full_name
parts = real_name.split(".")
real_names = [".".join(parts[:i]) for i in range(len(parts), 0, -1)]
for real_name in real_names:
as_name = real_name
if module and module.endswith("."):
# from . import a
# real_name should be ".a"
real_name = f"{module}{real_name}"
elif module:
real_name = f"{module}.{real_name}"
if name and name.asname:
eval_alias = name.evaluated_alias
if eval_alias is not None:
as_name = eval_alias
if full_name.startswith(as_name):
remaining_name = full_name.split(as_name, 1)[1].lstrip(".")
results.add(
QualifiedName(
f"{real_name}.{remaining_name}"
if remaining_name
else real_name,
QualifiedNameSource.IMPORT,
)
)
break
return results
class Assignments:
"""A container to provide all assignments in a scope."""
def __init__(self, assignments: Mapping[str, Collection[BaseAssignment]]) -> None:
self._assignments = assignments
def __iter__(self) -> Iterator[BaseAssignment]:
"""Iterate through all assignments by ``for i in scope.assignments``."""
for assignments in self._assignments.values():
for assignment in assignments:
yield assignment
def __getitem__(self, node: Union[str, cst.CSTNode]) -> Collection[BaseAssignment]:
"""Get assignments given a name str or :class:`~libcst.CSTNode` by ``scope.assignments[node]``"""
name = _NameUtil.get_name_for(node)
return set(self._assignments[name]) if name in self._assignments else set()
def __contains__(self, node: Union[str, cst.CSTNode]) -> bool:
"""Check if a name str or :class:`~libcst.CSTNode` has any assignment by ``node in scope.assignments``"""
return len(self[node]) > 0
class Accesses:
"""A container to provide all accesses in a scope."""
def __init__(self, accesses: Mapping[str, Collection[Access]]) -> None:
self._accesses = accesses
def __iter__(self) -> Iterator[Access]:
"""Iterate through all accesses by ``for i in scope.accesses``."""
for accesses in self._accesses.values():
for access in accesses:
yield access
def __getitem__(self, node: Union[str, cst.CSTNode]) -> Collection[Access]:
"""Get accesses given a name str or :class:`~libcst.CSTNode` by ``scope.accesses[node]``"""
name = _NameUtil.get_name_for(node)
return self._accesses[name] if name in self._accesses else set()
def __contains__(self, node: Union[str, cst.CSTNode]) -> bool:
"""Check if a name str or :class:`~libcst.CSTNode` has any access by ``node in scope.accesses``"""
return len(self[node]) > 0
class _NameUtil:
@staticmethod
def get_name_for(node: Union[str, cst.CSTNode]) -> Optional[str]:
"""A helper function to retrieve simple name str from a CSTNode or str"""
if isinstance(node, cst.Name):
return node.value
elif isinstance(node, str):
return node
elif isinstance(node, cst.Call):
return _NameUtil.get_name_for(node.func)
elif isinstance(node, cst.Subscript):
return _NameUtil.get_name_for(node.value)
elif isinstance(node, (cst.FunctionDef, cst.ClassDef)):
return _NameUtil.get_name_for(node.name)
return None
class Scope(abc.ABC):
"""
Base class of all scope classes. Scope object stores assignments from imports,
variable assignments, function definition or class definition.
A scope has a parent scope which represents the inheritance relationship. That means
an assignment in parent scope is viewable to the child scope and the child scope may
overwrites the assignment by using the same name.
Use ``name in scope`` to check whether a name is viewable in the scope.
Use ``scope[name]`` to retrieve all viewable assignments in the scope.
.. note::
This scope analysis module only analyzes local variable names and it doesn't handle
attribute names; for example, given ``a.b.c = 1``, local variable name ``a`` is recorded
as an assignment instead of ``c`` or ``a.b.c``. To analyze the assignment/access of
arbitrary object attributes, we leave the job to type inference metadata provider
coming in the future.
"""
#: Parent scope. Note the parent scope of a GlobalScope is itself.
parent: "Scope"
#: Refers to the GlobalScope.
globals: "GlobalScope"
_assignments: MutableMapping[str, Set[BaseAssignment]]
_accesses: MutableMapping[str, Set[Access]]
_assignment_count: int
def __init__(self, parent: "Scope") -> None:
super().__init__()
self.parent = parent
self.globals = parent.globals
self._assignments = defaultdict(set)
self._accesses = defaultdict(set)
self._assignment_count = 0
def record_assignment(self, name: str, node: cst.CSTNode) -> None:
target = self._find_assignment_target(name)
target._assignments[name].add(
Assignment(
name=name, scope=target, node=node, index=target._assignment_count
)
)
def record_import_assignment(
self, name: str, node: cst.CSTNode, as_name: cst.CSTNode
) -> None:
target = self._find_assignment_target(name)
target._assignments[name].add(
ImportAssignment(
name=name,
scope=target,
node=node,
as_name=as_name,
index=target._assignment_count,
)
)
def _find_assignment_target(self, name: str) -> "Scope":
return self
def _find_assignment_target_parent(self, name: str) -> "Scope":
return self
def record_access(self, name: str, access: Access) -> None:
self._accesses[name].add(access)
def _getitem_from_self_or_parent(self, name: str) -> Set[BaseAssignment]:
"""Overridden by ClassScope to hide it's assignments from child scopes."""
return self[name]
def _contains_in_self_or_parent(self, name: str) -> bool:
"""Overridden by ClassScope to hide it's assignments from child scopes."""
return name in self
@abc.abstractmethod
def __contains__(self, name: str) -> bool:
"""Check if the name str exist in current scope by ``name in scope``."""
...
@abc.abstractmethod
def __getitem__(self, name: str) -> Set[BaseAssignment]:
"""
Get assignments given a name str by ``scope[name]``.
.. note::
*Why does it return a list of assignments given a name instead of just one assignment?*
Many programming languages differentiate variable declaration and assignment.
Further, those programming languages often disallow duplicate declarations within
the same scope, and will often hoist the declaration (without its assignment) to
the top of the scope. These design decisions make static analysis much easier,
because it's possible to match a name against its single declaration for a given scope.
As an example, the following code would be valid in JavaScript::
function fn() {
console.log(value); // value is defined here, because the declaration is hoisted, but is currently 'undefined'.
var value = 5; // A function-scoped declaration.
}
fn(); // prints 'undefined'.
In contrast, Python's declaration and assignment are identical and are not hoisted::
if conditional_value:
value = 5
elif other_conditional_value:
value = 10
print(value) # possibly valid, depending on conditional execution
This code may throw a ``NameError`` if both conditional values are falsy.
It also means that depending on the codepath taken, the original declaration
could come from either ``value = ...`` assignment node.
As a result, instead of returning a single declaration,
we're forced to return a collection of all of the assignments we think could have
defined a given name by the time a piece of code is executed.
For the above example, value would resolve to a set of both assignments.
"""
...
def __hash__(self) -> int:
return id(self)
@abc.abstractmethod
def record_global_overwrite(self, name: str) -> None:
...
@abc.abstractmethod
def record_nonlocal_overwrite(self, name: str) -> None:
...
def get_qualified_names_for(
self, node: Union[str, cst.CSTNode]
) -> Collection[QualifiedName]:
"""Get all :class:`~libcst.metadata.QualifiedName` in current scope given a
:class:`~libcst.CSTNode`.
The source of a qualified name can be either :attr:`QualifiedNameSource.IMPORT`,
:attr:`QualifiedNameSource.BUILTIN` or :attr:`QualifiedNameSource.LOCAL`.
Given the following example, ``c`` has qualified name ``a.b.c`` with source ``IMPORT``,
``f`` has qualified name ``Cls.f`` with source ``LOCAL``, ``a`` has qualified name
``Cls.f.<locals>.a``, ``i`` has qualified name ``Cls.f.<locals>.<comprehension>.i``,
and the builtin ``int`` has qualified name ``builtins.int`` with source ``BUILTIN``::
from a.b import c
class Cls:
def f(self) -> "c":
c()
a = int("1")
[i for i in c()]
We extends `PEP-3155 <https://www.python.org/dev/peps/pep-3155/>`_
(defines ``__qualname__`` for class and function only; function namespace is followed
by a ``<locals>``) to provide qualified name for all :class:`~libcst.CSTNode`
recorded by :class:`~libcst.metadata.Assignment` and :class:`~libcst.metadata.Access`.
The namespace of a comprehension (:class:`~libcst.ListComp`, :class:`~libcst.SetComp`,
:class:`~libcst.DictComp`) is represented with ``<comprehension>``.
An imported name may be used for type annotation with :class:`~libcst.SimpleString` and
currently resolving the qualified given :class:`~libcst.SimpleString` is not supported
considering it could be a complex type annotation in the string which is hard to
resolve, e.g. ``List[Union[int, str]]``.
"""
results = set()
full_name = get_full_name_for_node(node)
if full_name is None:
return results
assignments = set()
parts = full_name.split(".")
for i in range(len(parts), 0, -1):
prefix = ".".join(parts[:i])
if prefix in self:
assignments = self[prefix]
break
for assignment in assignments:
names = assignment.get_qualified_names_for(full_name)
if (
isinstance(assignment, Assignment)
and not isinstance(node, str)
and _is_assignment(node, assignment.node)
):
return names
results |= names
return results
@property
def assignments(self) -> Assignments:
"""Return an :class:`~libcst.metadata.Assignments` contains all assignmens in current scope."""
return Assignments(self._assignments)
@property
def accesses(self) -> Accesses:
"""Return an :class:`~libcst.metadata.Accesses` contains all accesses in current scope."""
return Accesses(self._accesses)
class BuiltinScope(Scope):
"""
A BuiltinScope represents python builtin declarations. See https://docs.python.org/3/library/builtins.html
"""
def __init__(self, globals: Scope) -> None:
self.globals: Scope = globals # must be defined before Scope.__init__ is called
super().__init__(parent=self)
def __contains__(self, name: str) -> bool:
return hasattr(builtins, name)
def __getitem__(self, name: str) -> Set[BaseAssignment]:
if name in self._assignments:
return self._assignments[name]
if hasattr(builtins, name):
# note - we only see the builtin assignments during the deferred
# access resolution. unfortunately that means we have to create the
# assignment here, which can cause the set to mutate during iteration
self._assignments[name].add(BuiltinAssignment(name, self))
return self._assignments[name]
return set()
def record_global_overwrite(self, name: str) -> None:
raise NotImplementedError("global overwrite in builtin scope are not allowed")
def record_nonlocal_overwrite(self, name: str) -> None:
raise NotImplementedError("declarations in builtin scope are not allowed")
def _find_assignment_target(self, name: str) -> "Scope":
raise NotImplementedError("assignments in builtin scope are not allowed")
class GlobalScope(Scope):
"""
A GlobalScope is the scope of module. All module level assignments are recorded in GlobalScope.
"""
def __init__(self) -> None:
super().__init__(parent=BuiltinScope(self))
def __contains__(self, name: str) -> bool:
if name in self._assignments:
return len(self._assignments[name]) > 0
return self.parent._contains_in_self_or_parent(name)
def __getitem__(self, name: str) -> Set[BaseAssignment]:
if name in self._assignments:
return self._assignments[name]
else:
return self.parent._getitem_from_self_or_parent(name)
def record_global_overwrite(self, name: str) -> None:
pass
def record_nonlocal_overwrite(self, name: str) -> None:
raise NotImplementedError("nonlocal declaration not allowed at module level")
class LocalScope(Scope, abc.ABC):
_scope_overwrites: Dict[str, Scope]
#: Name of function. Used as qualified name.
name: Optional[str]
#: The :class:`~libcst.CSTNode` node defines the current scope.
node: cst.CSTNode
def __init__(
self, parent: Scope, node: cst.CSTNode, name: Optional[str] = None
) -> None:
super().__init__(parent)
self.name = name
self.node = node
self._scope_overwrites = {}
def record_global_overwrite(self, name: str) -> None:
self._scope_overwrites[name] = self.globals
def record_nonlocal_overwrite(self, name: str) -> None:
self._scope_overwrites[name] = self.parent
def _find_assignment_target(self, name: str) -> "Scope":
if name in self._scope_overwrites:
return self._scope_overwrites[name]._find_assignment_target_parent(name)
else:
return super()._find_assignment_target(name)
def __contains__(self, name: str) -> bool:
if name in self._scope_overwrites:
return name in self._scope_overwrites[name]
if name in self._assignments:
return len(self._assignments[name]) > 0
return self.parent._contains_in_self_or_parent(name)
def __getitem__(self, name: str) -> Set[BaseAssignment]:
if name in self._scope_overwrites:
return self._scope_overwrites[name]._getitem_from_self_or_parent(name)
if name in self._assignments:
return self._assignments[name]
else:
return self.parent._getitem_from_self_or_parent(name)
# even though we don't override the constructor.
class FunctionScope(LocalScope):
"""
When a function is defined, it creates a FunctionScope.
"""
pass
# even though we don't override the constructor.
class ClassScope(LocalScope):
"""
When a class is defined, it creates a ClassScope.
"""
def _find_assignment_target_parent(self, name: str) -> "Scope":
"""
Forward the assignment to parent.
def outer_fn():
v = ... # outer_fn's declaration
class InnerCls:
v = ... # shadows outer_fn's declaration
def inner_fn():
nonlocal v
v = ... # this should actually refer to outer_fn's declaration
# and not to InnerCls's, because InnerCls's scope is
# hidden from its children.
"""
return self.parent._find_assignment_target_parent(name)
def _getitem_from_self_or_parent(self, name: str) -> Set[BaseAssignment]:
"""
Class variables are only accessible using ClassName.attribute, cls.attribute, or
self.attribute in child scopes. They cannot be accessed with their bare names.
"""
return self.parent._getitem_from_self_or_parent(name)
def _contains_in_self_or_parent(self, name: str) -> bool:
"""
See :meth:`_getitem_from_self_or_parent`
"""
return self.parent._contains_in_self_or_parent(name)
# even though we don't override the constructor.
class ComprehensionScope(LocalScope):
"""
Comprehensions and generator expressions create their own scope. For example, in
[i for i in range(10)]
The variable ``i`` is only viewable within the ComprehensionScope.
"""
# TODO: Assignment expressions (Python 3.8) will complicate ComprehensionScopes,
# and will require us to handle such assignments as non-local.
# https://www.python.org/dev/peps/pep-0572/#scope-of-the-target
pass
# Generates dotted names from an Attribute or Name node:
# Attribute(value=Name(value="a"), attr=Name(value="b")) -> ("a.b", "a")
# each string has the corresponding CSTNode attached to it
def _gen_dotted_names(
node: Union[cst.Attribute, cst.Name]
) -> Iterator[Tuple[str, Union[cst.Attribute, cst.Name]]]:
if isinstance(node, cst.Name):
yield node.value, node
else:
value = node.value
if isinstance(value, cst.Call):
value = value.func
if isinstance(value, (cst.Attribute, cst.Name)):
name_values = _gen_dotted_names(value)
try:
next_name, next_node = next(name_values)
except StopIteration:
return
else:
yield next_name, next_node
yield from name_values
elif isinstance(value, (cst.Attribute, cst.Name)):
name_values = _gen_dotted_names(value)
try:
next_name, next_node = next(name_values)
except StopIteration:
return
else:
yield f"{next_name}.{node.attr.value}", node
yield next_name, next_node
yield from name_values
def _is_assignment(node: cst.CSTNode, assignment_node: cst.CSTNode) -> bool:
"""
Returns true if ``node`` is part of the assignment at ``assignment_node``.
Normally this is just a simple identity check, except for imports where the
assignment is attached to the entire import statement but we are interested in
``Name`` nodes inside the statement.
"""
if node is assignment_node:
return True
if isinstance(assignment_node, (cst.Import, cst.ImportFrom)):
aliases = assignment_node.names
if isinstance(aliases, cst.ImportStar):
return False
for alias in aliases:
if alias.name is node:
return True
asname = alias.asname
if asname is not None:
if asname.name is node:
return True
return False
@dataclass(frozen=True)
class DeferredAccess:
access: Access
enclosing_attribute: Optional[cst.Attribute]
enclosing_string_annotation: Optional[cst.BaseString]
class ScopeVisitor(cst.CSTVisitor):
# since it's probably not useful. That can makes this visitor cleaner.
def __init__(self, provider: "ScopeProvider") -> None:
self.provider: ScopeProvider = provider
self.scope: Scope = GlobalScope()
self.__deferred_accesses: List[DeferredAccess] = []
self.__top_level_attribute_stack: List[Optional[cst.Attribute]] = [None]
self.__in_annotation_stack: List[bool] = [False]
self.__in_type_hint_stack: List[bool] = [False]
self.__in_ignored_subscript: Set[cst.Subscript] = set()
self.__last_string_annotation: Optional[cst.BaseString] = None
self.__ignore_annotation: int = 0
@contextmanager
def _new_scope(
self, kind: Type[LocalScope], node: cst.CSTNode, name: Optional[str] = None
) -> Iterator[None]:
parent_scope = self.scope
self.scope = kind(parent_scope, node, name)
try:
yield
finally:
self.scope = parent_scope
@contextmanager
def _switch_scope(self, scope: Scope) -> Iterator[None]:
current_scope = self.scope
self.scope = scope
try:
yield
finally:
self.scope = current_scope
def _visit_import_alike(self, node: Union[cst.Import, cst.ImportFrom]) -> bool:
names = node.names
if isinstance(names, cst.ImportStar):
return False
# make sure node.names is Sequence[ImportAlias]
for name in names:
self.provider.set_metadata(name, self.scope)
asname = name.asname
if asname is not None:
name_values = _gen_dotted_names(cst.ensure_type(asname.name, cst.Name))
import_node_asname = asname.name
else:
name_values = _gen_dotted_names(name.name)
import_node_asname = name.name
for name_value, _ in name_values:
self.scope.record_import_assignment(
name_value, node, import_node_asname
)
return False
def visit_Import(self, node: cst.Import) -> Optional[bool]:
return self._visit_import_alike(node)
def visit_ImportFrom(self, node: cst.ImportFrom) -> Optional[bool]:
return self._visit_import_alike(node)
def visit_Attribute(self, node: cst.Attribute) -> Optional[bool]:
if self.__top_level_attribute_stack[-1] is None:
self.__top_level_attribute_stack[-1] = node
node.value.visit(self) # explicitly not visiting attr
if self.__top_level_attribute_stack[-1] is node:
self.__top_level_attribute_stack[-1] = None
return False
def visit_Call(self, node: cst.Call) -> Optional[bool]:
self.__top_level_attribute_stack.append(None)
self.__in_type_hint_stack.append(False)
qnames = {qn.name for qn in self.scope.get_qualified_names_for(node)}
if "typing.NewType" in qnames or "typing.TypeVar" in qnames:
node.func.visit(self)
self.__in_type_hint_stack[-1] = True
for arg in node.args[1:]:
arg.visit(self)
return False
if "typing.cast" in qnames:
node.func.visit(self)
if len(node.args) > 0:
self.__in_type_hint_stack.append(True)
node.args[0].visit(self)
self.__in_type_hint_stack.pop()
for arg in node.args[1:]:
arg.visit(self)
return False
return True
def leave_Call(self, original_node: cst.Call) -> None:
self.__top_level_attribute_stack.pop()
self.__in_type_hint_stack.pop()
def visit_Annotation(self, node: cst.Annotation) -> Optional[bool]:
self.__in_annotation_stack.append(True)
def leave_Annotation(self, original_node: cst.Annotation) -> None:
self.__in_annotation_stack.pop()
def visit_SimpleString(self, node: cst.SimpleString) -> Optional[bool]:
self._handle_string_annotation(node)
return False
def visit_ConcatenatedString(self, node: cst.ConcatenatedString) -> Optional[bool]:
return not self._handle_string_annotation(node)
def _handle_string_annotation(
self, node: Union[cst.SimpleString, cst.ConcatenatedString]
) -> bool:
"""Returns whether it successfully handled the string annotation"""
if (
self.__in_type_hint_stack[-1] or self.__in_annotation_stack[-1]
) and not self.__in_ignored_subscript:
value = node.evaluated_value
if value:
top_level_annotation = self.__last_string_annotation is None
if top_level_annotation:
self.__last_string_annotation = node
try:
mod = cst.parse_module(value)
mod.visit(self)
except cst.ParserSyntaxError:
# swallow string annotation parsing errors
# this is the same behavior as cPython
pass
if top_level_annotation:
self.__last_string_annotation = None
return True
return False
def visit_Subscript(self, node: cst.Subscript) -> Optional[bool]:
in_type_hint = False
if isinstance(node.value, cst.Name):
qnames = {qn.name for qn in self.scope.get_qualified_names_for(node.value)}
if any(qn.startswith(("typing.", "typing_extensions.")) for qn in qnames):
in_type_hint = True
if "typing.Literal" in qnames or "typing_extensions.Literal" in qnames:
self.__in_ignored_subscript.add(node)
self.__in_type_hint_stack.append(in_type_hint)
return True
def leave_Subscript(self, original_node: cst.Subscript) -> None:
self.__in_type_hint_stack.pop()
self.__in_ignored_subscript.discard(original_node)
def visit_Name(self, node: cst.Name) -> Optional[bool]:
# not all Name have ExpressionContext
context = self.provider.get_metadata(ExpressionContextProvider, node, None)
if context == ExpressionContext.STORE:
self.scope.record_assignment(node.value, node)
elif context in (ExpressionContext.LOAD, ExpressionContext.DEL, None):
access = Access(
node,
self.scope,
is_annotation=bool(
self.__in_annotation_stack[-1] and not self.__ignore_annotation
),
is_type_hint=bool(self.__in_type_hint_stack[-1]),
)
self.__deferred_accesses.append(
DeferredAccess(
access=access,
enclosing_attribute=self.__top_level_attribute_stack[-1],
enclosing_string_annotation=self.__last_string_annotation,
)
)
def visit_FunctionDef(self, node: cst.FunctionDef) -> Optional[bool]:
self.scope.record_assignment(node.name.value, node)
self.provider.set_metadata(node.name, self.scope)
with self._new_scope(FunctionScope, node, get_full_name_for_node(node.name)):
node.params.visit(self)
node.body.visit(self)
for decorator in node.decorators:
decorator.visit(self)
returns = node.returns
if returns:
returns.visit(self)
return False
def visit_Lambda(self, node: cst.Lambda) -> Optional[bool]:
with self._new_scope(FunctionScope, node):
node.params.visit(self)
node.body.visit(self)
return False
def visit_Param(self, node: cst.Param) -> Optional[bool]:
self.scope.record_assignment(node.name.value, node)
self.provider.set_metadata(node.name, self.scope)
with self._switch_scope(self.scope.parent):