-
-
Notifications
You must be signed in to change notification settings - Fork 278
/
Copy path_base_nodes.py
674 lines (575 loc) · 23.5 KB
/
_base_nodes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE
# Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt
"""This module contains some base nodes that can be inherited for the different nodes.
Previously these were called Mixin nodes.
"""
from __future__ import annotations
import itertools
from collections.abc import Callable, Generator, Iterator
from functools import cached_property, lru_cache, partial
from typing import TYPE_CHECKING, Any, ClassVar, Optional, Union
from astroid import bases, nodes, util
from astroid.const import PY310_PLUS
from astroid.context import (
CallContext,
InferenceContext,
bind_context_to_node,
)
from astroid.exceptions import (
AttributeInferenceError,
InferenceError,
)
from astroid.interpreter import dunder_lookup
from astroid.nodes.node_ng import NodeNG
from astroid.typing import InferenceResult
if TYPE_CHECKING:
from astroid.nodes.node_classes import LocalsDictNodeNG
GetFlowFactory = Callable[
[
InferenceResult,
Optional[InferenceResult],
Union[nodes.AugAssign, nodes.BinOp],
InferenceResult,
Optional[InferenceResult],
InferenceContext,
InferenceContext,
],
list[partial[Generator[InferenceResult]]],
]
class Statement(NodeNG):
"""Statement node adding a few attributes.
NOTE: This class is part of the public API of 'astroid.nodes'.
"""
is_statement = True
"""Whether this node indicates a statement."""
def next_sibling(self):
"""The next sibling statement node.
:returns: The next sibling statement node.
:rtype: NodeNG or None
"""
stmts = self.parent.child_sequence(self)
index = stmts.index(self)
try:
return stmts[index + 1]
except IndexError:
return None
def previous_sibling(self):
"""The previous sibling statement.
:returns: The previous sibling statement node.
:rtype: NodeNG or None
"""
stmts = self.parent.child_sequence(self)
index = stmts.index(self)
if index >= 1:
return stmts[index - 1]
return None
class NoChildrenNode(NodeNG):
"""Base nodes for nodes with no children, e.g. Pass."""
def get_children(self) -> Iterator[NodeNG]:
yield from ()
class FilterStmtsBaseNode(NodeNG):
"""Base node for statement filtering and assignment type."""
def _get_filtered_stmts(self, _, node, _stmts, mystmt: Statement | None):
"""Method used in _filter_stmts to get statements and trigger break."""
if self.statement() is mystmt:
# original node's statement is the assignment, only keep
# current node (gen exp, list comp)
return [node], True
return _stmts, False
def assign_type(self):
return self
class AssignTypeNode(NodeNG):
"""Base node for nodes that can 'assign' such as AnnAssign."""
def assign_type(self):
return self
def _get_filtered_stmts(self, lookup_node, node, _stmts, mystmt: Statement | None):
"""Method used in filter_stmts."""
if self is mystmt:
return _stmts, True
if self.statement() is mystmt:
# original node's statement is the assignment, only keep
# current node (gen exp, list comp)
return [node], True
return _stmts, False
class ParentAssignNode(AssignTypeNode):
"""Base node for nodes whose assign_type is determined by the parent node."""
def assign_type(self):
return self.parent.assign_type()
class ImportNode(FilterStmtsBaseNode, NoChildrenNode, Statement):
"""Base node for From and Import Nodes."""
modname: str | None
"""The module that is being imported from.
This is ``None`` for relative imports.
"""
names: list[tuple[str, str | None]]
"""What is being imported from the module.
Each entry is a :class:`tuple` of the name being imported,
and the alias that the name is assigned to (if any).
"""
def _infer_name(self, frame, name):
return name
def do_import_module(self, modname: str | None = None) -> nodes.Module:
"""Return the ast for a module whose name is <modname> imported by <self>."""
mymodule = self.root()
level: int | None = getattr(self, "level", None) # Import has no level
if modname is None:
modname = self.modname
# If the module ImportNode is importing is a module with the same name
# as the file that contains the ImportNode we don't want to use the cache
# to make sure we use the import system to get the correct module.
if (
modname
# pylint: disable-next=no-member # pylint doesn't recognize type of mymodule
and mymodule.relative_to_absolute_name(modname, level) == mymodule.name
):
use_cache = False
else:
use_cache = True
# pylint: disable-next=no-member # pylint doesn't recognize type of mymodule
return mymodule.import_module(
modname,
level=level,
relative_only=bool(level and level >= 1),
use_cache=use_cache,
)
def real_name(self, asname: str) -> str:
"""Get name from 'as' name."""
for name, _asname in self.names:
if name == "*":
return asname
if not _asname:
name = name.split(".", 1)[0]
_asname = name
if asname == _asname:
return name
raise AttributeInferenceError(
"Could not find original name for {attribute} in {target!r}",
target=self,
attribute=asname,
)
class MultiLineBlockNode(NodeNG):
"""Base node for multi-line blocks, e.g. For and FunctionDef.
Note that this does not apply to every node with a `body` field.
For instance, an If node has a multi-line body, but the body of an
IfExpr is not multi-line, and hence cannot contain Return nodes,
Assign nodes, etc.
"""
_multi_line_block_fields: ClassVar[tuple[str, ...]] = ()
@cached_property
def _multi_line_blocks(self):
return tuple(getattr(self, field) for field in self._multi_line_block_fields)
def _get_return_nodes_skip_functions(self):
for block in self._multi_line_blocks:
for child_node in block:
if child_node.is_function:
continue
yield from child_node._get_return_nodes_skip_functions()
def _get_yield_nodes_skip_functions(self):
for block in self._multi_line_blocks:
for child_node in block:
if child_node.is_function:
continue
yield from child_node._get_yield_nodes_skip_functions()
def _get_yield_nodes_skip_lambdas(self):
for block in self._multi_line_blocks:
for child_node in block:
if child_node.is_lambda:
continue
yield from child_node._get_yield_nodes_skip_lambdas()
@cached_property
def _assign_nodes_in_scope(self) -> list[nodes.Assign]:
children_assign_nodes = (
child_node._assign_nodes_in_scope
for block in self._multi_line_blocks
for child_node in block
)
return list(itertools.chain.from_iterable(children_assign_nodes))
class MultiLineWithElseBlockNode(MultiLineBlockNode):
"""Base node for multi-line blocks that can have else statements."""
@cached_property
def blockstart_tolineno(self):
return self.lineno
def _elsed_block_range(
self, lineno: int, orelse: list[nodes.NodeNG], last: int | None = None
) -> tuple[int, int]:
"""Handle block line numbers range for try/finally, for, if and while
statements.
"""
if lineno == self.fromlineno:
return lineno, lineno
if orelse:
if lineno >= orelse[0].fromlineno:
return lineno, orelse[-1].tolineno
return lineno, orelse[0].fromlineno - 1
return lineno, last or self.tolineno
class LookupMixIn(NodeNG):
"""Mixin to look up a name in the right scope."""
@lru_cache # noqa
def lookup(self, name: str) -> tuple[LocalsDictNodeNG, list[NodeNG]]:
"""Lookup where the given variable is assigned.
The lookup starts from self's scope. If self is not a frame itself
and the name is found in the inner frame locals, statements will be
filtered to remove ignorable statements according to self's location.
:param name: The name of the variable to find assignments for.
:returns: The scope node and the list of assignments associated to the
given name according to the scope where it has been found (locals,
globals or builtin).
"""
return self.scope().scope_lookup(self, name)
def ilookup(self, name):
"""Lookup the inferred values of the given variable.
:param name: The variable name to find values for.
:type name: str
:returns: The inferred values of the statements returned from
:meth:`lookup`.
:rtype: iterable
"""
frame, stmts = self.lookup(name)
context = InferenceContext()
return bases._infer_stmts(stmts, context, frame)
def _reflected_name(name) -> str:
return "__r" + name[2:]
def _augmented_name(name) -> str:
return "__i" + name[2:]
BIN_OP_METHOD = {
"+": "__add__",
"-": "__sub__",
"/": "__truediv__",
"//": "__floordiv__",
"*": "__mul__",
"**": "__pow__",
"%": "__mod__",
"&": "__and__",
"|": "__or__",
"^": "__xor__",
"<<": "__lshift__",
">>": "__rshift__",
"@": "__matmul__",
}
REFLECTED_BIN_OP_METHOD = {
key: _reflected_name(value) for (key, value) in BIN_OP_METHOD.items()
}
AUGMENTED_OP_METHOD = {
key + "=": _augmented_name(value) for (key, value) in BIN_OP_METHOD.items()
}
class OperatorNode(NodeNG):
@staticmethod
def _filter_operation_errors(
infer_callable: Callable[
[InferenceContext | None],
Generator[InferenceResult | util.BadOperationMessage],
],
context: InferenceContext | None,
error: type[util.BadOperationMessage],
) -> Generator[InferenceResult]:
for result in infer_callable(context):
if isinstance(result, error):
# For the sake of .infer(), we don't care about operation
# errors, which is the job of a linter. So return something
# which shows that we can't infer the result.
yield util.Uninferable
else:
yield result
@staticmethod
def _is_not_implemented(const) -> bool:
"""Check if the given const node is NotImplemented."""
return isinstance(const, nodes.Const) and const.value is NotImplemented
@staticmethod
def _infer_old_style_string_formatting(
instance: nodes.Const, other: nodes.NodeNG, context: InferenceContext
) -> tuple[util.UninferableBase | nodes.Const]:
"""Infer the result of '"string" % ...'.
TODO: Instead of returning Uninferable we should rely
on the call to '%' to see if the result is actually uninferable.
"""
if isinstance(other, nodes.Tuple):
if util.Uninferable in other.elts:
return (util.Uninferable,)
inferred_positional = [util.safe_infer(i, context) for i in other.elts]
if all(isinstance(i, nodes.Const) for i in inferred_positional):
values = tuple(i.value for i in inferred_positional)
else:
values = None
elif isinstance(other, nodes.Dict):
values: dict[Any, Any] = {}
for pair in other.items:
key = util.safe_infer(pair[0], context)
if not isinstance(key, nodes.Const):
return (util.Uninferable,)
value = util.safe_infer(pair[1], context)
if not isinstance(value, nodes.Const):
return (util.Uninferable,)
values[key.value] = value.value
elif isinstance(other, nodes.Const):
values = other.value
else:
return (util.Uninferable,)
try:
return (nodes.const_factory(instance.value % values),)
except (TypeError, KeyError, ValueError):
return (util.Uninferable,)
@staticmethod
def _invoke_binop_inference(
instance: InferenceResult,
opnode: nodes.AugAssign | nodes.BinOp,
op: str,
other: InferenceResult,
context: InferenceContext,
method_name: str,
) -> Generator[InferenceResult]:
"""Invoke binary operation inference on the given instance."""
methods = dunder_lookup.lookup(instance, method_name)
context = bind_context_to_node(context, instance)
method = methods[0]
context.callcontext.callee = method
if (
isinstance(instance, nodes.Const)
and isinstance(instance.value, str)
and op == "%"
):
return iter(
OperatorNode._infer_old_style_string_formatting(
instance, other, context
)
)
try:
inferred = next(method.infer(context=context))
except StopIteration as e:
raise InferenceError(node=method, context=context) from e
if isinstance(inferred, util.UninferableBase):
raise InferenceError
if not isinstance(
instance,
(nodes.Const, nodes.Tuple, nodes.List, nodes.ClassDef, bases.Instance),
):
raise InferenceError # pragma: no cover # Used as a failsafe
return instance.infer_binary_op(opnode, op, other, context, inferred)
@staticmethod
def _aug_op(
instance: InferenceResult,
opnode: nodes.AugAssign,
op: str,
other: InferenceResult,
context: InferenceContext,
reverse: bool = False,
) -> partial[Generator[InferenceResult]]:
"""Get an inference callable for an augmented binary operation."""
method_name = AUGMENTED_OP_METHOD[op]
return partial(
OperatorNode._invoke_binop_inference,
instance=instance,
op=op,
opnode=opnode,
other=other,
context=context,
method_name=method_name,
)
@staticmethod
def _bin_op(
instance: InferenceResult,
opnode: nodes.AugAssign | nodes.BinOp,
op: str,
other: InferenceResult,
context: InferenceContext,
reverse: bool = False,
) -> partial[Generator[InferenceResult]]:
"""Get an inference callable for a normal binary operation.
If *reverse* is True, then the reflected method will be used instead.
"""
if reverse:
method_name = REFLECTED_BIN_OP_METHOD[op]
else:
method_name = BIN_OP_METHOD[op]
return partial(
OperatorNode._invoke_binop_inference,
instance=instance,
op=op,
opnode=opnode,
other=other,
context=context,
method_name=method_name,
)
@staticmethod
def _bin_op_or_union_type(
left: bases.UnionType | nodes.ClassDef | nodes.Const,
right: bases.UnionType | nodes.ClassDef | nodes.Const,
) -> Generator[InferenceResult]:
"""Create a new UnionType instance for binary or, e.g. int | str."""
yield bases.UnionType(left, right)
@staticmethod
def _get_binop_contexts(context, left, right):
"""Get contexts for binary operations.
This will return two inference contexts, the first one
for x.__op__(y), the other one for y.__rop__(x), where
only the arguments are inversed.
"""
# The order is important, since the first one should be
# left.__op__(right).
for arg in (right, left):
new_context = context.clone()
new_context.callcontext = CallContext(args=[arg])
new_context.boundnode = None
yield new_context
@staticmethod
def _same_type(type1, type2) -> bool:
"""Check if type1 is the same as type2."""
return type1.qname() == type2.qname()
@staticmethod
def _get_aug_flow(
left: InferenceResult,
left_type: InferenceResult | None,
aug_opnode: nodes.AugAssign,
right: InferenceResult,
right_type: InferenceResult | None,
context: InferenceContext,
reverse_context: InferenceContext,
) -> list[partial[Generator[InferenceResult]]]:
"""Get the flow for augmented binary operations.
The rules are a bit messy:
* if left and right have the same type, then left.__augop__(right)
is first tried and then left.__op__(right).
* if left and right are unrelated typewise, then
left.__augop__(right) is tried, then left.__op__(right)
is tried and then right.__rop__(left) is tried.
* if left is a subtype of right, then left.__augop__(right)
is tried and then left.__op__(right).
* if left is a supertype of right, then left.__augop__(right)
is tried, then right.__rop__(left) and then
left.__op__(right)
"""
from astroid import helpers # pylint: disable=import-outside-toplevel
bin_op = aug_opnode.op.strip("=")
aug_op = aug_opnode.op
if OperatorNode._same_type(left_type, right_type):
methods = [
OperatorNode._aug_op(left, aug_opnode, aug_op, right, context),
OperatorNode._bin_op(left, aug_opnode, bin_op, right, context),
]
elif helpers.is_subtype(left_type, right_type):
methods = [
OperatorNode._aug_op(left, aug_opnode, aug_op, right, context),
OperatorNode._bin_op(left, aug_opnode, bin_op, right, context),
]
elif helpers.is_supertype(left_type, right_type):
methods = [
OperatorNode._aug_op(left, aug_opnode, aug_op, right, context),
OperatorNode._bin_op(
right, aug_opnode, bin_op, left, reverse_context, reverse=True
),
OperatorNode._bin_op(left, aug_opnode, bin_op, right, context),
]
else:
methods = [
OperatorNode._aug_op(left, aug_opnode, aug_op, right, context),
OperatorNode._bin_op(left, aug_opnode, bin_op, right, context),
OperatorNode._bin_op(
right, aug_opnode, bin_op, left, reverse_context, reverse=True
),
]
return methods
@staticmethod
def _get_binop_flow(
left: InferenceResult,
left_type: InferenceResult | None,
binary_opnode: nodes.AugAssign | nodes.BinOp,
right: InferenceResult,
right_type: InferenceResult | None,
context: InferenceContext,
reverse_context: InferenceContext,
) -> list[partial[Generator[InferenceResult]]]:
"""Get the flow for binary operations.
The rules are a bit messy:
* if left and right have the same type, then only one
method will be called, left.__op__(right)
* if left and right are unrelated typewise, then first
left.__op__(right) is tried and if this does not exist
or returns NotImplemented, then right.__rop__(left) is tried.
* if left is a subtype of right, then only left.__op__(right)
is tried.
* if left is a supertype of right, then right.__rop__(left)
is first tried and then left.__op__(right)
"""
from astroid import helpers # pylint: disable=import-outside-toplevel
op = binary_opnode.op
if OperatorNode._same_type(left_type, right_type):
methods = [OperatorNode._bin_op(left, binary_opnode, op, right, context)]
elif helpers.is_subtype(left_type, right_type):
methods = [OperatorNode._bin_op(left, binary_opnode, op, right, context)]
elif helpers.is_supertype(left_type, right_type):
methods = [
OperatorNode._bin_op(
right, binary_opnode, op, left, reverse_context, reverse=True
),
OperatorNode._bin_op(left, binary_opnode, op, right, context),
]
else:
methods = [
OperatorNode._bin_op(left, binary_opnode, op, right, context),
OperatorNode._bin_op(
right, binary_opnode, op, left, reverse_context, reverse=True
),
]
# pylint: disable = too-many-boolean-expressions
if (
PY310_PLUS
and op == "|"
and (
isinstance(left, (bases.UnionType, nodes.ClassDef))
or (isinstance(left, nodes.Const) and left.value is None)
)
and (
isinstance(right, (bases.UnionType, nodes.ClassDef))
or (isinstance(right, nodes.Const) and right.value is None)
)
):
methods.extend([partial(OperatorNode._bin_op_or_union_type, left, right)])
return methods
@staticmethod
def _infer_binary_operation(
left: InferenceResult,
right: InferenceResult,
binary_opnode: nodes.AugAssign | nodes.BinOp,
context: InferenceContext,
flow_factory: GetFlowFactory,
) -> Generator[InferenceResult | util.BadBinaryOperationMessage]:
"""Infer a binary operation between a left operand and a right operand.
This is used by both normal binary operations and augmented binary
operations, the only difference is the flow factory used.
"""
from astroid import helpers # pylint: disable=import-outside-toplevel
context, reverse_context = OperatorNode._get_binop_contexts(
context, left, right
)
left_type = helpers.object_type(left)
right_type = helpers.object_type(right)
methods = flow_factory(
left, left_type, binary_opnode, right, right_type, context, reverse_context
)
for method in methods:
try:
results = list(method())
except AttributeError:
continue
except AttributeInferenceError:
continue
except InferenceError:
yield util.Uninferable
return
else:
if any(isinstance(result, util.UninferableBase) for result in results):
yield util.Uninferable
return
if all(map(OperatorNode._is_not_implemented, results)):
continue
not_implemented = sum(
1 for result in results if OperatorNode._is_not_implemented(result)
)
if not_implemented and not_implemented != len(results):
# Can't infer yet what this is.
yield util.Uninferable
return
yield from results
return
# The operation doesn't seem to be supported so let the caller know about it
yield util.BadBinaryOperationMessage(left_type, binary_opnode.op, right_type)