-
Notifications
You must be signed in to change notification settings - Fork 226
Expand file tree
/
Copy path_matcher_base.py
More file actions
1943 lines (1644 loc) · 77.3 KB
/
_matcher_base.py
File metadata and controls
1943 lines (1644 loc) · 77.3 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
# 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 collections.abc
import inspect
import re
from abc import ABCMeta
from dataclasses import dataclass, fields
from enum import auto, Enum
from typing import (
Callable,
cast,
Dict,
Generic,
Iterator,
List,
Mapping,
NoReturn,
Optional,
Pattern,
Sequence,
Tuple,
Type,
TypeVar,
Union,
)
import libcst
import libcst.metadata as meta
from libcst import CSTLogicError, FlattenSentinel, MaybeSentinel, RemovalSentinel
from libcst._metadata_dependent import LazyValue
class DoNotCareSentinel(Enum):
"""
A sentinel that is used in matcher classes to indicate that a caller
does not care what this value is. We recommend that you do not use this
directly, and instead use the :func:`DoNotCare` helper. You do not
need to use this for concrete matcher attributes since :func:`DoNotCare`
is already the default.
"""
DEFAULT = auto()
def __repr__(self) -> str:
return "DoNotCare()"
_MatcherT = TypeVar("_MatcherT", covariant=True)
_MatchIfTrueT = TypeVar("_MatchIfTrueT", covariant=True)
_BaseMatcherNodeSelfT = TypeVar("_BaseMatcherNodeSelfT", bound="BaseMatcherNode")
_OtherNodeT = TypeVar("_OtherNodeT")
_MetadataValueT = TypeVar("_MetadataValueT")
_MatcherTypeT = TypeVar("_MatcherTypeT", bound=Type["BaseMatcherNode"])
_OtherNodeMatcherTypeT = TypeVar(
"_OtherNodeMatcherTypeT", bound=Type["BaseMatcherNode"]
)
_METADATA_MISSING_SENTINEL = object()
class AbstractBaseMatcherNodeMeta(ABCMeta):
"""
Metaclass that all matcher nodes uses. Allows chaining 2 node type
together with an bitwise-or operator to produce an :class:`TypeOf`
matcher.
"""
# pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently.
def __or__(self, node: Type["BaseMatcherNode"]) -> "TypeOf[Type[BaseMatcherNode]]":
return TypeOf(self, node)
class BaseMatcherNode:
"""
Base class that all concrete matchers subclass from. :class:`OneOf` and
:class:`AllOf` also subclass from this in order to allow them to be used in
any place that a concrete matcher is allowed. This means that, for example,
you can call :func:`matches` with a concrete matcher, or a :class:`OneOf` with
several concrete matchers as options.
"""
# pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently.
def __or__(
self: _BaseMatcherNodeSelfT, other: _OtherNodeT
) -> "OneOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]":
return OneOf(self, other)
def __and__(
self: _BaseMatcherNodeSelfT, other: _OtherNodeT
) -> "AllOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]":
return AllOf(self, other)
def __invert__(self: _BaseMatcherNodeSelfT) -> "_BaseMatcherNodeSelfT":
return cast(_BaseMatcherNodeSelfT, _InverseOf(self))
def DoNotCare() -> DoNotCareSentinel:
"""
Used when you want to match exactly one node, but you do not care what node it is.
Useful inside sequences such as a :class:`libcst.matchers.Call`'s args attribte.
You do not need to use this for concrete matcher attributes since :func:`DoNotCare`
is already the default.
For example, the following matcher would match against any function calls with
three arguments, regardless of the arguments themselves and regardless of the
function name that we were calling::
m.Call(args=[m.DoNotCare(), m.DoNotCare(), m.DoNotCare()])
"""
return DoNotCareSentinel.DEFAULT
class TypeOf(Generic[_MatcherTypeT], BaseMatcherNode):
"""
Matcher that matches any one of the given types. Useful when you want to work
with trees where a common property might belong to more than a single type.
For example, if you want either a binary operation or a boolean operation
where the left side has a name ``foo``::
m.TypeOf(m.BinaryOperation, m.BooleanOperation)(left = m.Name("foo"))
Or you could use the shorthand, like::
(m.BinaryOperation | m.BooleanOperation)(left = m.Name("foo"))
Also :class:`TypeOf` matchers can be used with initalizing in the default
state of other node matchers (without passing any extra patterns)::
m.Name | m.SimpleString
The will be equal to::
m.OneOf(m.Name(), m.SimpleString())
"""
def __init__(self, *options: Union[_MatcherTypeT, "TypeOf[_MatcherTypeT]"]) -> None:
actual_options: List[_MatcherTypeT] = []
for option in options:
if isinstance(option, TypeOf):
if option.initalized:
raise ValueError(
"Cannot chain an uninitalized TypeOf with an initalized one"
)
actual_options.extend(option._raw_options)
else:
actual_options.append(option)
self._initalized = False
self._call_items: Tuple[Tuple[object, ...], Dict[str, object]] = ((), {})
self._raw_options: Tuple[_MatcherTypeT, ...] = tuple(actual_options)
@property
def initalized(self) -> bool:
return self._initalized
@property
def options(self) -> Iterator[BaseMatcherNode]:
for option in self._raw_options:
args, kwargs = self._call_items
matcher_pattern = option(*args, **kwargs)
yield matcher_pattern
def __call__(self, *args: object, **kwargs: object) -> BaseMatcherNode:
self._initalized = True
self._call_items = (args, kwargs)
return self
# pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently.
def __or__(
self, other: _OtherNodeMatcherTypeT
) -> "TypeOf[Union[_MatcherTypeT, _OtherNodeMatcherTypeT]]":
return TypeOf[Union[_MatcherTypeT, _OtherNodeMatcherTypeT]](self, other)
# pyre-fixme[14]: `__and__` overrides method defined in `BaseMatcherNode`
# inconsistently.
def __and__(self, other: _OtherNodeMatcherTypeT) -> NoReturn:
left, right = type(self).__name__, other.__name__
raise TypeError(
f"TypeError: unsupported operand type(s) for &: {left!r} and {right!r}"
)
def __invert__(self) -> "AllOf[BaseMatcherNode]":
return AllOf(*map(DoesNotMatch, self.options))
def __repr__(self) -> str:
types = ", ".join(repr(option) for option in self._raw_options)
return f"TypeOf({types}, initalized = {self.initalized})"
class OneOf(Generic[_MatcherT], BaseMatcherNode):
"""
Matcher that matches any one of its options. Useful when you want to match
against one of several options for a single node. You can also construct a
:class:`OneOf` matcher by using Python's bitwise or operator with concrete
matcher classes.
For example, you could match against ``True``/``False`` like::
m.OneOf(m.Name("True"), m.Name("False"))
Or you could use the shorthand, like::
m.Name("True") | m.Name("False")
"""
def __init__(self, *options: Union[_MatcherT, "OneOf[_MatcherT]"]) -> None:
actual_options: List[_MatcherT] = []
for option in options:
if isinstance(option, AllOf):
raise ValueError("Cannot use AllOf and OneOf in combination!")
elif isinstance(option, (OneOf, TypeOf)):
actual_options.extend(option.options)
else:
actual_options.append(option)
self._options: Sequence[_MatcherT] = tuple(actual_options)
@property
def options(self) -> Sequence[_MatcherT]:
"""
The normalized list of options that we can choose from to satisfy a
:class:`OneOf` matcher. If any of these matchers are true, the
:class:`OneOf` matcher will also be considered a match.
"""
return self._options
# pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently.
def __or__(self, other: _OtherNodeT) -> "OneOf[Union[_MatcherT, _OtherNodeT]]":
return OneOf(self, other)
def __and__(self, other: _OtherNodeT) -> NoReturn:
raise ValueError("Cannot use AllOf and OneOf in combination!")
def __invert__(self) -> "AllOf[_MatcherT]":
# Invert using De Morgan's Law so we don't have to complicate types.
return AllOf(*[DoesNotMatch(m) for m in self._options])
def __repr__(self) -> str:
return f"OneOf({', '.join([repr(o) for o in self._options])})"
class AllOf(Generic[_MatcherT], BaseMatcherNode):
"""
Matcher that matches all of its options. Useful when you want to match
against a concrete matcher and a :class:`MatchIfTrue` at the same time. Also
useful when you want to match against a concrete matcher and a
:func:`DoesNotMatch` at the same time. You can also construct a
:class:`AllOf` matcher by using Python's bitwise and operator with concrete
matcher classes.
For example, you could match against ``True`` in a roundabout way like::
m.AllOf(m.Name(), m.Name("True"))
Or you could use the shorthand, like::
m.Name() & m.Name("True")
Similar to :class:`OneOf`, this can be used in place of any concrete matcher.
Real-world cases where :class:`AllOf` is useful are hard to come by but they
are still provided for the limited edge cases in which they make sense. In
the example above, we are redundantly matching against any LibCST
:class:`~libcst.Name` node as well as LibCST :class:`~libcst.Name` nodes that
have the ``value`` of ``True``. We could drop the first option entirely and
get the same result. Often, if you are using a :class:`AllOf`,
you can refactor your code to be simpler.
For example, the following matches any function call to ``foo``, and
any function call which takes zero arguments::
m.AllOf(m.Call(func=m.Name("foo")), m.Call(args=()))
This could be refactored into the following equivalent concrete matcher::
m.Call(func=m.Name("foo"), args=())
"""
def __init__(self, *options: Union[_MatcherT, "AllOf[_MatcherT]"]) -> None:
actual_options: List[_MatcherT] = []
for option in options:
if isinstance(option, OneOf):
raise ValueError("Cannot use AllOf and OneOf in combination!")
elif isinstance(option, TypeOf):
raise ValueError("Cannot use AllOf and TypeOf in combination!")
elif isinstance(option, AllOf):
actual_options.extend(option.options)
else:
actual_options.append(option)
self._options: Sequence[_MatcherT] = tuple(actual_options)
@property
def options(self) -> Sequence[_MatcherT]:
"""
The normalized list of options that we can choose from to satisfy a
:class:`AllOf` matcher. If all of these matchers are true, the
:class:`AllOf` matcher will also be considered a match.
"""
return self._options
# pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently.
def __or__(self, other: _OtherNodeT) -> NoReturn:
raise ValueError("Cannot use AllOf and OneOf in combination!")
def __and__(self, other: _OtherNodeT) -> "AllOf[Union[_MatcherT, _OtherNodeT]]":
return AllOf(self, other)
def __invert__(self) -> "OneOf[_MatcherT]":
# Invert using De Morgan's Law so we don't have to complicate types.
return OneOf(*[DoesNotMatch(m) for m in self._options])
def __repr__(self) -> str:
return f"AllOf({', '.join([repr(o) for o in self._options])})"
class _InverseOf(Generic[_MatcherT]):
"""
Matcher that inverts the match result of its child. You can also construct a
:class:`_InverseOf` matcher by using Python's bitwise invert operator with concrete
matcher classes or any special matcher.
Note that you should refrain from constructing a :class:`_InverseOf` directly, and
should instead use the :func:`DoesNotMatch` helper function.
For example, the following matches against any identifier that isn't
``True``/``False``::
m.DoesNotMatch(m.OneOf(m.Name("True"), m.Name("False")))
Or you could use the shorthand, like:
~(m.Name("True") | m.Name("False"))
"""
def __init__(self, matcher: _MatcherT) -> None:
self._matcher: _MatcherT = matcher
@property
def matcher(self) -> _MatcherT:
"""
The matcher that we will evaluate and invert. If this matcher is true, then
:class:`_InverseOf` will be considered not a match, and vice-versa.
"""
return self._matcher
# pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently.
def __or__(self, other: _OtherNodeT) -> "OneOf[Union[_MatcherT, _OtherNodeT]]":
# Without a cast, pyre thinks that the below OneOf is type OneOf[object]
# even though it has the types passed into it.
return cast(OneOf[Union[_MatcherT, _OtherNodeT]], OneOf(self, other))
def __and__(self, other: _OtherNodeT) -> "AllOf[Union[_MatcherT, _OtherNodeT]]":
# Without a cast, pyre thinks that the below AllOf is type AllOf[object]
# even though it has the types passed into it.
return cast(AllOf[Union[_MatcherT, _OtherNodeT]], AllOf(self, other))
def __getattr__(self, key: str) -> object:
# We lie about types to make _InverseOf appear transparent. So, its conceivable
# that somebody might try to dereference an attribute on the _MatcherT wrapped
# node and become surprised that it doesn't work.
return getattr(self._matcher, key)
def __invert__(self) -> _MatcherT:
return self._matcher
def __repr__(self) -> str:
return f"DoesNotMatch({repr(self._matcher)})"
class _ExtractMatchingNode(Generic[_MatcherT]):
"""
Transparent pass-through matcher that captures the node which matches its children,
making it available to the caller of :func:`extract` or :func:`extractall`.
Note that you should refrain from constructing a :class:`_ExtractMatchingNode`
directly, and should instead use the :func:`SaveMatchedNode` helper function.
For example, the following will match against any binary operation whose left
and right operands are not integers, saving those expressions for later inspection.
If used inside :func:`extract` or :func:`extractall`, the resulting dictionary will
contain the keys ``left_operand`` and ``right_operand``.
m.BinaryOperation(
left=m.SaveMatchedNode(
m.DoesNotMatch(m.Integer()),
"left_operand",
),
right=m.SaveMatchedNode(
m.DoesNotMatch(m.Integer()),
"right_operand",
),
)
"""
def __init__(self, matcher: _MatcherT, name: str) -> None:
self._matcher: _MatcherT = matcher
self._name: str = name
@property
def matcher(self) -> _MatcherT:
"""
The matcher that we will evaluate and capture matching LibCST nodes for.
If this matcher is true, then :class:`_ExtractMatchingNode` will be considered
a match and will save the node which matched.
"""
return self._matcher
@property
def name(self) -> str:
"""
The name we will call our captured LibCST node inside the resulting dictionary
returned by :func:`extract` or :func:`extractall`.
"""
return self._name
# pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently.
def __or__(self, other: _OtherNodeT) -> "OneOf[Union[_MatcherT, _OtherNodeT]]":
# Without a cast, pyre thinks that the below OneOf is type OneOf[object]
# even though it has the types passed into it.
return cast(OneOf[Union[_MatcherT, _OtherNodeT]], OneOf(self, other))
def __and__(self, other: _OtherNodeT) -> "AllOf[Union[_MatcherT, _OtherNodeT]]":
# This doesn't make sense. If we have multiple SaveMatchedNode captures
# that are captured with an and, either all of them will be assigned the
# same node, or none of them. It makes more sense to move the SaveMatchedNode
# up to wrap the AllOf.
raise ValueError(
(
"Cannot use AllOf with SavedMatchedNode children! Instead, you should "
+ "use SaveMatchedNode(AllOf(options...))."
)
)
def __getattr__(self, key: str) -> object:
# We lie about types to make _ExtractMatchingNode appear transparent. So,
# its conceivable that somebody might try to dereference an attribute on
# the _MatcherT wrapped node and become surprised that it doesn't work.
return getattr(self._matcher, key)
def __invert__(self) -> "_MatcherT":
# This doesn't make sense. We don't want to capture a node only if it
# doesn't match, since this will never capture anything.
raise ValueError(
(
"Cannot invert a SaveMatchedNode. Instead you should wrap SaveMatchedNode "
"around your inversion itself"
)
)
def __repr__(self) -> str:
return (
f"SaveMatchedNode(matcher={repr(self._matcher)}, name={repr(self._name)})"
)
class MatchIfTrue(Generic[_MatchIfTrueT]):
"""
Matcher that matches if its child callable returns ``True``. The child callable
should take one argument which is the attribute on the LibCST node we are
trying to match against. This is useful if you want to do complex logic to
determine if an attribute should match or not. One example of this is the
:func:`MatchRegex` matcher build on top of :class:`MatchIfTrue` which takes a
regular expression and matches any string attribute where a regex match is found.
For example, to match on any identifier spelled with the letter ``e``::
m.Name(value=m.MatchIfTrue(lambda value: "e" in value))
This can be used in place of any concrete matcher as long as it is not the
root matcher. Calling :func:`matches` directly on a :class:`MatchIfTrue` is
redundant since you can just call the child callable directly with the node
you are passing to :func:`matches`.
"""
_func: Callable[[_MatchIfTrueT], bool]
def __init__(self, func: Callable[[_MatchIfTrueT], bool]) -> None:
self._func = func
@property
def func(self) -> Callable[[_MatchIfTrueT], bool]:
"""
The function that we will call with a LibCST node in order to determine
if we match. If the function returns ``True`` then we consider ourselves
to be a match.
"""
return self._func
# pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently.
def __or__(
self, other: _OtherNodeT
) -> "OneOf[Union[MatchIfTrue[_MatchIfTrueT], _OtherNodeT]]":
return OneOf(self, other)
def __and__(
self, other: _OtherNodeT
) -> "AllOf[Union[MatchIfTrue[_MatchIfTrueT], _OtherNodeT]]":
return AllOf(self, other)
def __invert__(self) -> "MatchIfTrue[_MatchIfTrueT]":
# Construct a wrapped version of MatchIfTrue for typing simplicity.
# Without the cast, pyre doesn't seem to think the lambda is valid.
return MatchIfTrue(lambda val: not self._func(val))
def __repr__(self) -> str:
return f"MatchIfTrue({repr(self._func)})"
def MatchRegex(regex: Union[str, Pattern[str]]) -> MatchIfTrue[str]:
"""
Used as a convenience wrapper to :class:`MatchIfTrue` which allows for
matching a string attribute against a regex. ``regex`` can be any regular
expression string or a compiled ``Pattern``. This uses Python's re module
under the hood and is compatible with syntax documented on
`docs.python.org <https://docs.python.org/3/library/re.html>`_.
For example, to match against any identifier that is at least one character
long and only contains alphabetical characters::
m.Name(value=m.MatchRegex(r'[A-Za-z]+'))
This can be used in place of any string literal when constructing a concrete
matcher.
"""
def _match_func(value: object) -> bool:
if isinstance(value, str):
return bool(re.fullmatch(regex, value))
else:
return False
return MatchIfTrue(_match_func)
class _BaseMetadataMatcher:
"""
Class that's only around for typing purposes.
"""
pass
class MatchMetadata(_BaseMetadataMatcher):
"""
Matcher that looks up the metadata on the current node using the provided
metadata provider and compares the value on the node against the value provided
to :class:`MatchMetadata`.
If the metadata provider is unresolved, a :class:`LookupError` exeption will be
raised and ask you to provide a :class:`~libcst.metadata.MetadataWrapper`.
If the metadata value does not exist for a particular node, :class:`MatchMetadata`
will be considered not a match.
For example, to match against any function call which has one parameter which
is used in a load expression context::
m.Call(
args=[
m.Arg(
m.MatchMetadata(
meta.ExpressionContextProvider,
meta.ExpressionContext.LOAD,
)
)
]
)
To match against any :class:`~libcst.Name` node for the identifier ``foo``
which is the target of an assignment::
m.Name(
value="foo",
metadata=m.MatchMetadata(
meta.ExpressionContextProvider,
meta.ExpressionContext.STORE,
)
)
This can be used in place of any concrete matcher as long as it is not the
root matcher. Calling :func:`matches` directly on a :class:`MatchMetadata` is
redundant since you can just check the metadata on the root node that you
are passing to :func:`matches`.
"""
def __init__(
self,
key: Type[meta.BaseMetadataProvider[_MetadataValueT]],
value: _MetadataValueT,
) -> None:
self._key: Type[meta.BaseMetadataProvider[_MetadataValueT]] = key
self._value: _MetadataValueT = value
@property
def key(self) -> meta.ProviderT:
"""
The metadata provider that we will use to fetch values when identifying whether
a node matches this matcher. We compare the value returned from the metadata
provider to the value provided in ``value`` when determining a match.
"""
return self._key
@property
def value(self) -> object:
"""
The value that we will compare against the return from the metadata provider
for each node when determining a match.
"""
return self._value
# pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently.
def __or__(self, other: _OtherNodeT) -> "OneOf[Union[MatchMetadata, _OtherNodeT]]":
return OneOf(self, other)
def __and__(self, other: _OtherNodeT) -> "AllOf[Union[MatchMetadata, _OtherNodeT]]":
return AllOf(self, other)
def __invert__(self) -> "MatchMetadata":
# We intentionally lie here, for the same reason given in the documentation
# for DoesNotMatch.
return cast(MatchMetadata, _InverseOf(self))
def __repr__(self) -> str:
return f"MatchMetadata(key={repr(self._key)}, value={repr(self._value)})"
class MatchMetadataIfTrue(_BaseMetadataMatcher):
"""
Matcher that looks up the metadata on the current node using the provided
metadata provider and passes it to a callable which can inspect the metadata
further, returning ``True`` if the matcher should be considered a match.
If the metadata provider is unresolved, a :class:`LookupError` exeption will be
raised and ask you to provide a :class:`~libcst.metadata.MetadataWrapper`.
If the metadata value does not exist for a particular node,
:class:`MatchMetadataIfTrue` will be considered not a match.
For example, to match against any arg whose qualified name might be
``typing.Dict``::
m.Call(
args=[
m.Arg(
m.MatchMetadataIfTrue(
meta.QualifiedNameProvider,
lambda qualnames: any(n.name == "typing.Dict" for n in qualnames)
)
)
]
)
To match against any :class:`~libcst.Name` node for the identifier ``foo``
as long as that identifier is found at the beginning of an unindented line::
m.Name(
value="foo",
metadata=m.MatchMetadataIfTrue(
meta.PositionProvider,
lambda position: position.start.column == 0,
)
)
This can be used in place of any concrete matcher as long as it is not the
root matcher. Calling :func:`matches` directly on a :class:`MatchMetadataIfTrue`
is redundant since you can just check the metadata on the root node that you
are passing to :func:`matches`.
"""
def __init__(
self,
key: Type[meta.BaseMetadataProvider[_MetadataValueT]],
func: Callable[[_MetadataValueT], bool],
) -> None:
self._key: Type[meta.BaseMetadataProvider[_MetadataValueT]] = key
self._func: Callable[[_MetadataValueT], bool] = func
@property
def key(self) -> meta.ProviderT:
"""
The metadata provider that we will use to fetch values when identifying whether
a node matches this matcher. We pass the value returned from the metadata
provider to the callable given to us in ``func``.
"""
return self._key
@property
def func(self) -> Callable[[object], bool]:
"""
The function that we will call with a value retrieved from the metadata provider
provided in ``key``. If the function returns ``True`` then we consider ourselves
to be a match.
"""
return self._func
# pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently.
def __or__(
self, other: _OtherNodeT
) -> "OneOf[Union[MatchMetadataIfTrue, _OtherNodeT]]":
return OneOf(self, other)
def __and__(
self, other: _OtherNodeT
) -> "AllOf[Union[MatchMetadataIfTrue, _OtherNodeT]]":
return AllOf(self, other)
def __invert__(self) -> "MatchMetadataIfTrue":
# Construct a wrapped version of MatchMetadataIfTrue for typing simplicity.
return MatchMetadataIfTrue(self._key, lambda val: not self._func(val))
def __repr__(self) -> str:
return f"MatchMetadataIfTrue(key={repr(self._key)}, func={repr(self._func)})"
class _BaseWildcardNode:
"""
A typing-only class for internal helpers in this module to be able to
specify that they take a wildcard node type.
"""
pass
class AtLeastN(Generic[_MatcherT], _BaseWildcardNode):
"""
Matcher that matches ``n`` or more LibCST nodes in a row in a sequence.
:class:`AtLeastN` defaults to matching against the :func:`DoNotCare` matcher,
so if you do not specify a matcher as a child, :class:`AtLeastN`
will match only by count. If you do specify a matcher as a child,
:class:`AtLeastN` will instead make sure that each LibCST node matches the
matcher supplied.
For example, this will match all function calls with at least 3 arguments::
m.Call(args=[m.AtLeastN(n=3)])
This will match all function calls with 3 or more integer arguments::
m.Call(args=[m.AtLeastN(n=3, matcher=m.Arg(m.Integer()))])
You can combine sequence matchers with concrete matchers and special matchers
and it will behave as you expect. For example, this will match all function
calls that have 2 or more integer arguments in a row, followed by any arbitrary
argument::
m.Call(args=[m.AtLeastN(n=2, matcher=m.Arg(m.Integer())), m.DoNotCare()])
And finally, this will match all function calls that have at least 5
arguments, the final one being an integer::
m.Call(args=[m.AtLeastN(n=4), m.Arg(m.Integer())])
"""
def __init__(
self,
matcher: Union[_MatcherT, DoNotCareSentinel] = DoNotCareSentinel.DEFAULT,
*,
n: int,
) -> None:
if n < 0:
raise ValueError(
f"{self.__class__.__qualname__} n attribute must be positive"
)
self._n: int = n
self._matcher: Union[_MatcherT, DoNotCareSentinel] = matcher
@property
def n(self) -> int:
"""
The number of nodes in a row that must match :attr:`AtLeastN.matcher` for
this matcher to be considered a match. If there are less than ``n`` matches,
this matcher will not be considered a match. If there are equal to or more
than ``n`` matches, this matcher will be considered a match.
"""
return self._n
@property
def matcher(self) -> Union[_MatcherT, DoNotCareSentinel]:
"""
The matcher which each node in a sequence needs to match.
"""
return self._matcher
# pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently.
def __or__(self, other: object) -> NoReturn:
raise ValueError("AtLeastN cannot be used in a OneOf matcher")
def __and__(self, other: object) -> NoReturn:
raise ValueError("AtLeastN cannot be used in an AllOf matcher")
def __invert__(self) -> NoReturn:
raise ValueError("Cannot invert an AtLeastN matcher!")
def __repr__(self) -> str:
if self._n == 0:
return f"ZeroOrMore({repr(self._matcher)})"
else:
return f"AtLeastN({repr(self._matcher)}, n={self._n})"
def ZeroOrMore(
matcher: Union[_MatcherT, DoNotCareSentinel] = DoNotCareSentinel.DEFAULT,
) -> AtLeastN[Union[_MatcherT, DoNotCareSentinel]]:
"""
Used as a convenience wrapper to :class:`AtLeastN` when ``n`` is equal to ``0``.
Use this when you want to match against any number of nodes in a sequence.
For example, this will match any function call with zero or more arguments, as
long as all of the arguments are integers::
m.Call(args=[m.ZeroOrMore(m.Arg(m.Integer()))])
This will match any function call where the first argument is an integer and
it doesn't matter what the rest of the arguments are::
m.Call(args=[m.Arg(m.Integer()), m.ZeroOrMore()])
You will often want to use :class:`ZeroOrMore` on both sides of a concrete
matcher in order to match against sequences that contain a particular node
in an arbitrary location. For example, the following will match any function
call that takes in at least one string argument anywhere::
m.Call(args=[m.ZeroOrMore(), m.Arg(m.SimpleString()), m.ZeroOrMore()])
"""
return cast(AtLeastN[Union[_MatcherT, DoNotCareSentinel]], AtLeastN(matcher, n=0))
class AtMostN(Generic[_MatcherT], _BaseWildcardNode):
"""
Matcher that matches ``n`` or fewer LibCST nodes in a row in a sequence.
:class:`AtMostN` defaults to matching against the :func:`DoNotCare` matcher,
so if you do not specify a matcher as a child, :class:`AtMostN` will
match only by count. If you do specify a matcher as a child,
:class:`AtMostN` will instead make sure that each LibCST node matches the
matcher supplied.
For example, this will match all function calls with 3 or fewer arguments::
m.Call(args=[m.AtMostN(n=3)])
This will match all function calls with 0, 1 or 2 string arguments::
m.Call(args=[m.AtMostN(n=2, matcher=m.Arg(m.SimpleString()))])
You can combine sequence matchers with concrete matchers and special matchers
and it will behave as you expect. For example, this will match all function
calls that have 0, 1 or 2 string arguments in a row, followed by an arbitrary
argument::
m.Call(args=[m.AtMostN(n=2, matcher=m.Arg(m.SimpleString())), m.DoNotCare()])
And finally, this will match all function calls that have at least 2
arguments, the final one being a string::
m.Call(args=[m.AtMostN(n=2), m.Arg(m.SimpleString())])
"""
def __init__(
self,
matcher: Union[_MatcherT, DoNotCareSentinel] = DoNotCareSentinel.DEFAULT,
*,
n: int,
) -> None:
if n < 0:
raise ValueError(
f"{self.__class__.__qualname__} n attribute must be positive"
)
self._n: int = n
self._matcher: Union[_MatcherT, DoNotCareSentinel] = matcher
@property
def n(self) -> int:
"""
The number of nodes in a row that must match :attr:`AtLeastN.matcher` for
this matcher to be considered a match. If there are less than or equal to
``n`` matches, then this matcher will be considered a match. Any more than
``n`` matches in a row and this matcher will stop matching and be considered
not a match.
"""
return self._n
@property
def matcher(self) -> Union[_MatcherT, DoNotCareSentinel]:
"""
The matcher which each node in a sequence needs to match.
"""
return self._matcher
# pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently.
def __or__(self, other: object) -> NoReturn:
raise ValueError("AtMostN cannot be used in a OneOf matcher")
def __and__(self, other: object) -> NoReturn:
raise ValueError("AtMostN cannot be used in an AllOf matcher")
def __invert__(self) -> NoReturn:
raise ValueError("Cannot invert an AtMostN matcher!")
def __repr__(self) -> str:
if self._n == 1:
return f"ZeroOrOne({repr(self._matcher)})"
else:
return f"AtMostN({repr(self._matcher)}, n={self._n})"
def ZeroOrOne(
matcher: Union[_MatcherT, DoNotCareSentinel] = DoNotCareSentinel.DEFAULT,
) -> AtMostN[Union[_MatcherT, DoNotCareSentinel]]:
"""
Used as a convenience wrapper to :class:`AtMostN` when ``n`` is equal to ``1``.
This is effectively a maybe clause.
For example, this will match any function call with zero or one integer
argument::
m.Call(args=[m.ZeroOrOne(m.Arg(m.Integer()))])
This will match any function call that has two or three arguments, and
the first and last arguments are strings::
m.Call(args=[m.Arg(m.SimpleString()), m.ZeroOrOne(), m.Arg(m.SimpleString())])
"""
return cast(AtMostN[Union[_MatcherT, DoNotCareSentinel]], AtMostN(matcher, n=1))
def DoesNotMatch(obj: _OtherNodeT) -> _OtherNodeT:
"""
Matcher helper that inverts the match result of its child. You can also invert a
matcher by using Python's bitwise invert operator on concrete matchers or any
special matcher.
For example, the following matches against any identifier that isn't
``True``/``False``::
m.DoesNotMatch(m.OneOf(m.Name("True"), m.Name("False")))
Or you could use the shorthand, like::
~(m.Name("True") | m.Name("False"))
This can be used in place of any concrete matcher as long as it is not the
root matcher. Calling :func:`matches` directly on a :func:`DoesNotMatch` is
redundant since you can invert the return of :func:`matches` using a bitwise not.
"""
# This type is a complete, dirty lie, but there's no way to recursively apply
# a parameter to each type inside a Union that may be in a _OtherNodeT.
# However, given the way _InverseOf works (it will unwrap itself if
# inverted again), and the way we apply De Morgan's law for OneOf and AllOf,
# this lie ends up getting us correct typing. Anywhere a node is valid, using
# DoesNotMatch(node) is also valid.
#
# ~MatchIfTrue is still MatchIfTrue
# ~MatchMetadataIfTrue is still MatchMetadataIfTrue
# ~OneOf[x] is AllOf[~x]
# ~AllOf[x] is OneOf[~x]
# ~~x is x
#
# So, under all circumstances, since OneOf/AllOf are both allowed in every
# instance, and given that inverting MatchIfTrue is still MatchIfTrue,
# and inverting an inverted value returns us the original, its clear that
# there are no operations we can possibly do that bring us outside of the
# types specified in the concrete matchers as long as we lie that DoesNotMatch
# returns the value passed in.
if isinstance(
obj,
(
BaseMatcherNode,
MatchIfTrue,
_BaseMetadataMatcher,
_InverseOf,
_ExtractMatchingNode,
),
):
# We can use the overridden __invert__ in this case. Pyre doesn't think
# we can though, and casting doesn't fix the issue.
inverse = ~obj
else:
# We must wrap in a _InverseOf.
inverse = _InverseOf(obj)
return cast(_OtherNodeT, inverse)
def SaveMatchedNode(matcher: _OtherNodeT, name: str) -> _OtherNodeT:
"""
Matcher helper that captures the matched node that matched against a matcher
class, making it available in the dictionary returned by :func:`extract` or
:func:`extractall`.
For example, the following will match against any binary operation whose left
and right operands are not integers, saving those expressions for later inspection.
If used inside :func:`extract` or :func:`extractall`, the resulting dictionary
will contain the keys ``left_operand`` and ``right_operand``::
m.BinaryOperation(
left=m.SaveMatchedNode(