1# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
2# For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE
3# Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt
4
5"""Astroid hooks for various builtins."""
6
7from __future__ import annotations
8
9import itertools
10import re
11from collections.abc import Callable, Iterable, Iterator
12from functools import lru_cache, partial
13from typing import NoReturn, cast
14
15from astroid import arguments, helpers, nodes, objects, util
16from astroid.bases import Instance
17from astroid.builder import AstroidBuilder
18from astroid.context import InferenceContext
19from astroid.exceptions import (
20 AstroidTypeError,
21 AttributeInferenceError,
22 InferenceError,
23 MroError,
24 UseInferenceDefault,
25)
26from astroid.inference_tip import inference_tip
27from astroid.manager import AstroidManager
28from astroid.nodes import scoped_nodes
29from astroid.typing import (
30 ConstFactoryResult,
31 InferenceResult,
32 SuccessfulInferenceResult,
33)
34
35ContainerObjects = (
36 objects.FrozenSet | objects.DictItems | objects.DictKeys | objects.DictValues
37)
38
39BuiltContainers = type[tuple] | type[list] | type[set] | type[frozenset]
40
41CopyResult = nodes.Dict | nodes.List | nodes.Set | objects.FrozenSet
42
43OBJECT_DUNDER_NEW = "object.__new__"
44
45# Largest field width/precision we are willing to materialize when inferring a
46# str.format() call. A crafted template such as "{:>2000000000}" would otherwise
47# eagerly build a multi-gigabyte string during inference.
48_MAX_FORMAT_FIELD_SIZE = int(1e8)
49
50# Largest str/bytes constant we are willing to expand into one node per
51# character when inferring container calls and dict.fromkeys.
52_MAX_INFERABLE_STR_LEN = int(1e8)
53
54
55@lru_cache(maxsize=1)
56def _get_bounded_formatter():
57 """Build the formatter lazily: importing ``string`` is costly at import time."""
58 import string # pylint: disable=import-outside-toplevel
59
60 class _BoundedFormatter(string.Formatter):
61 """A ``str.format`` implementation that refuses oversized width/precision.
62
63 The only multi-digit numbers in a format spec are the width and the
64 precision, so bailing when any digit run exceeds the limit covers both.
65 Nested replacement fields ("{:>{}}") are already resolved by ``Formatter``
66 before ``format_field`` runs, so this also catches sizes passed as
67 arguments.
68 """
69
70 def format_field(self, value: object, format_spec: str) -> str:
71 for size in re.findall(r"\d+", format_spec):
72 if int(size) > _MAX_FORMAT_FIELD_SIZE:
73 raise ValueError("format field size exceeds inference limit")
74 return cast(str, super().format_field(value, format_spec))
75
76 return _BoundedFormatter()
77
78
79STR_CLASS = """
80class whatever(object):
81 def join(self, iterable):
82 return {rvalue}
83 def replace(self, old, new, count=None):
84 return {rvalue}
85 def format(self, *args, **kwargs):
86 return {rvalue}
87 def encode(self, encoding='ascii', errors=None):
88 return b''
89 def decode(self, encoding='ascii', errors=None):
90 return u''
91 def capitalize(self):
92 return {rvalue}
93 def title(self):
94 return {rvalue}
95 def lower(self):
96 return {rvalue}
97 def upper(self):
98 return {rvalue}
99 def swapcase(self):
100 return {rvalue}
101 def index(self, sub, start=None, end=None):
102 return 0
103 def find(self, sub, start=None, end=None):
104 return 0
105 def count(self, sub, start=None, end=None):
106 return 0
107 def strip(self, chars=None):
108 return {rvalue}
109 def lstrip(self, chars=None):
110 return {rvalue}
111 def rstrip(self, chars=None):
112 return {rvalue}
113 def rjust(self, width, fillchar=None):
114 return {rvalue}
115 def center(self, width, fillchar=None):
116 return {rvalue}
117 def ljust(self, width, fillchar=None):
118 return {rvalue}
119"""
120
121
122BYTES_CLASS = """
123class whatever(object):
124 def join(self, iterable):
125 return {rvalue}
126 def replace(self, old, new, count=None):
127 return {rvalue}
128 def decode(self, encoding='ascii', errors=None):
129 return u''
130 def capitalize(self):
131 return {rvalue}
132 def title(self):
133 return {rvalue}
134 def lower(self):
135 return {rvalue}
136 def upper(self):
137 return {rvalue}
138 def swapcase(self):
139 return {rvalue}
140 def index(self, sub, start=None, end=None):
141 return 0
142 def find(self, sub, start=None, end=None):
143 return 0
144 def count(self, sub, start=None, end=None):
145 return 0
146 def strip(self, chars=None):
147 return {rvalue}
148 def lstrip(self, chars=None):
149 return {rvalue}
150 def rstrip(self, chars=None):
151 return {rvalue}
152 def rjust(self, width, fillchar=None):
153 return {rvalue}
154 def center(self, width, fillchar=None):
155 return {rvalue}
156 def ljust(self, width, fillchar=None):
157 return {rvalue}
158"""
159
160
161def _use_default() -> NoReturn: # pragma: no cover
162 raise UseInferenceDefault()
163
164
165def _extend_string_class(class_node, code, rvalue):
166 """Function to extend builtin str/unicode class."""
167 code = code.format(rvalue=rvalue)
168 fake = AstroidBuilder(AstroidManager()).string_build(code)["whatever"]
169 for method in fake.mymethods():
170 method.parent = class_node
171 method.lineno = None
172 method.col_offset = None
173 if "__class__" in method.locals:
174 method.locals["__class__"] = [class_node]
175 class_node.locals[method.name] = [method]
176 method.parent = class_node
177
178
179def _extend_builtins(class_transforms):
180 builtin_ast = AstroidManager().builtins_module
181 for class_name, transform in class_transforms.items():
182 transform(builtin_ast[class_name])
183
184
185def on_bootstrap():
186 """Called by astroid_bootstrapping()."""
187 _extend_builtins(
188 {
189 "bytes": partial(_extend_string_class, code=BYTES_CLASS, rvalue="b''"),
190 "str": partial(_extend_string_class, code=STR_CLASS, rvalue="''"),
191 }
192 )
193
194
195def _builtin_dispatch_predicate(node: nodes.Call) -> bool:
196 # pylint: disable = too-many-boolean-expressions
197 # This runs on every Call node, so the checks are ordered by cost: each one
198 # is a constant-time attribute or type check, except ``node.root()``, which
199 # walks up every parent to the module and must stay last.
200 if (
201 isinstance(node.func, nodes.Name)
202 and node.func.name == "type"
203 and isinstance(node.parent, nodes.Assign)
204 and len(node.parent.targets) == 1
205 and isinstance(node.parent.targets[0], nodes.AssignName)
206 and node.parent.targets[0].name in {"Pattern", "Match"}
207 and node.root().name == "re"
208 ):
209 # Handle re.Pattern and re.Match in brain_re
210 # Match these patterns from stdlib/re.py
211 # ```py
212 # Pattern = type(...)
213 # Match = type(...)
214 # ```
215 return False
216 if isinstance(node.func, nodes.Name):
217 return node.func.name in _BUILTIN_INFERENCE_FUNCS
218 if isinstance(node.func, nodes.Attribute):
219 return (
220 node.func.attrname == "fromkeys"
221 and isinstance(node.func.expr, nodes.Name)
222 and node.func.expr.name == "dict"
223 )
224 return False
225
226
227def _builtin_dispatch_transform(
228 node: nodes.Call, context: InferenceContext | None = None
229) -> Iterator:
230 func = node.func
231 if isinstance(func, nodes.Name):
232 builtin_name = func.name
233 else:
234 builtin_name = "dict.fromkeys"
235 transform = _BUILTIN_INFERENCE_FUNCS[builtin_name]
236 result = transform(node, context=context)
237 if result:
238 if not result.parent:
239 # Let the transformation function determine
240 # the parent for its result. Otherwise,
241 # we set it to be the node we transformed from.
242 result.parent = node
243
244 if result.lineno is None:
245 result.lineno = node.lineno
246 # Can be a 'Module' see https://github.com/pylint-dev/pylint/issues/4671
247 # We don't have a regression test on this one: be careful
248 if hasattr(result, "col_offset") and result.col_offset is None:
249 result.col_offset = node.col_offset
250 return iter([result])
251
252
253def _container_generic_inference(
254 node: nodes.Call,
255 context: InferenceContext | None,
256 node_type: type[nodes.BaseContainer],
257 transform: Callable[[SuccessfulInferenceResult], nodes.BaseContainer | None],
258) -> nodes.BaseContainer:
259 args = node.args
260 if not args:
261 return node_type(
262 lineno=node.lineno,
263 col_offset=node.col_offset,
264 parent=node.parent,
265 end_lineno=node.end_lineno,
266 end_col_offset=node.end_col_offset,
267 )
268 if len(node.args) > 1:
269 raise UseInferenceDefault()
270
271 (arg,) = args
272 transformed = transform(arg)
273 if not transformed:
274 try:
275 inferred = next(arg.infer(context=context))
276 except (InferenceError, StopIteration) as exc:
277 raise UseInferenceDefault from exc
278 if isinstance(inferred, util.UninferableBase):
279 raise UseInferenceDefault
280 transformed = transform(inferred)
281 if not transformed or isinstance(transformed, util.UninferableBase):
282 raise UseInferenceDefault
283 return transformed
284
285
286def _container_generic_transform(
287 arg: SuccessfulInferenceResult,
288 context: InferenceContext | None,
289 klass: type[nodes.BaseContainer],
290 iterables: tuple[type[nodes.BaseContainer] | type[ContainerObjects], ...],
291 build_elts: BuiltContainers,
292) -> nodes.BaseContainer | None:
293 elts: Iterable | str | bytes
294
295 if isinstance(arg, klass):
296 return arg
297 if isinstance(arg, iterables):
298 arg = cast((nodes.BaseContainer | ContainerObjects), arg)
299 if all(isinstance(elt, nodes.Const) for elt in arg.elts):
300 elts = [cast(nodes.Const, elt).value for elt in arg.elts]
301 else:
302 # TODO: Does not handle deduplication for sets.
303 elts = []
304 for element in arg.elts:
305 if not element:
306 continue
307 inferred = util.safe_infer(element, context=context)
308 if inferred:
309 evaluated_object = nodes.EvaluatedObject(
310 original=element, value=inferred
311 )
312 elts.append(evaluated_object)
313 elif isinstance(arg, nodes.Dict):
314 # Dicts need to have consts as strings already.
315 elts = [
316 item[0].value if isinstance(item[0], nodes.Const) else _use_default()
317 for item in arg.items
318 ]
319 elif isinstance(arg, nodes.Const) and isinstance(arg.value, (str, bytes)):
320 # Don't expand an oversized string into one Const node per character.
321 if len(arg.value) > _MAX_INFERABLE_STR_LEN:
322 return None
323 elts = arg.value
324 else:
325 return None
326 return klass.from_elements(elts=build_elts(elts))
327
328
329def _infer_builtin_container(
330 node: nodes.Call,
331 context: InferenceContext | None,
332 klass: type[nodes.BaseContainer],
333 iterables: tuple[type[nodes.NodeNG] | type[ContainerObjects], ...],
334 build_elts: BuiltContainers,
335) -> nodes.BaseContainer:
336 transform_func = partial(
337 _container_generic_transform,
338 context=context,
339 klass=klass,
340 iterables=iterables,
341 build_elts=build_elts,
342 )
343
344 return _container_generic_inference(node, context, klass, transform_func)
345
346
347# pylint: disable=invalid-name
348infer_tuple = partial(
349 _infer_builtin_container,
350 klass=nodes.Tuple,
351 iterables=(
352 nodes.List,
353 nodes.Set,
354 objects.FrozenSet,
355 objects.DictItems,
356 objects.DictKeys,
357 objects.DictValues,
358 ),
359 build_elts=tuple,
360)
361
362infer_list = partial(
363 _infer_builtin_container,
364 klass=nodes.List,
365 iterables=(
366 nodes.Tuple,
367 nodes.Set,
368 objects.FrozenSet,
369 objects.DictItems,
370 objects.DictKeys,
371 objects.DictValues,
372 ),
373 build_elts=list,
374)
375
376infer_set = partial(
377 _infer_builtin_container,
378 klass=nodes.Set,
379 iterables=(nodes.List, nodes.Tuple, objects.FrozenSet, objects.DictKeys),
380 build_elts=set,
381)
382
383infer_frozenset = partial(
384 _infer_builtin_container,
385 klass=objects.FrozenSet,
386 iterables=(nodes.List, nodes.Tuple, nodes.Set, objects.FrozenSet, objects.DictKeys),
387 build_elts=frozenset,
388)
389
390
391def _get_elts(arg, context):
392 def is_iterable(n) -> bool:
393 return isinstance(n, (nodes.List, nodes.Tuple, nodes.Set))
394
395 try:
396 inferred = next(arg.infer(context))
397 except (InferenceError, StopIteration) as exc:
398 raise UseInferenceDefault from exc
399 if isinstance(inferred, nodes.Dict):
400 items = inferred.items
401 elif is_iterable(inferred):
402 items = []
403 for elt in inferred.elts:
404 # If an item is not a pair of two items,
405 # then fallback to the default inference.
406 # Also, take in consideration only hashable items,
407 # tuples and consts. We are choosing Names as well.
408 if not is_iterable(elt):
409 raise UseInferenceDefault()
410 if len(elt.elts) != 2:
411 raise UseInferenceDefault()
412 if not isinstance(elt.elts[0], (nodes.Tuple, nodes.Const, nodes.Name)):
413 raise UseInferenceDefault()
414 items.append(tuple(elt.elts))
415 else:
416 raise UseInferenceDefault()
417 return items
418
419
420def infer_dict(node: nodes.Call, context: InferenceContext | None = None) -> nodes.Dict:
421 """Try to infer a dict call to a Dict node.
422
423 The function treats the following cases:
424
425 * dict()
426 * dict(mapping)
427 * dict(iterable)
428 * dict(iterable, **kwargs)
429 * dict(mapping, **kwargs)
430 * dict(**kwargs)
431
432 If a case can't be inferred, we'll fallback to default inference.
433 """
434 call = arguments.CallSite.from_call(node, context=context)
435 if call.has_invalid_arguments() or call.has_invalid_keywords():
436 raise UseInferenceDefault
437
438 args = call.positional_arguments
439 kwargs = list(call.keyword_arguments.items())
440
441 items: list[tuple[InferenceResult, InferenceResult]]
442 if not args and not kwargs:
443 # dict()
444 return nodes.Dict(
445 lineno=node.lineno,
446 col_offset=node.col_offset,
447 parent=node.parent,
448 end_lineno=node.end_lineno,
449 end_col_offset=node.end_col_offset,
450 )
451 if kwargs and not args:
452 # dict(a=1, b=2, c=4)
453 items = [(nodes.Const(key), value) for key, value in kwargs]
454 elif len(args) == 1 and kwargs:
455 # dict(some_iterable, b=2, c=4)
456 elts = _get_elts(args[0], context)
457 keys = [(nodes.Const(key), value) for key, value in kwargs]
458 items = elts + keys
459 elif len(args) == 1:
460 items = _get_elts(args[0], context)
461 else:
462 raise UseInferenceDefault()
463 value = nodes.Dict(
464 col_offset=node.col_offset,
465 lineno=node.lineno,
466 parent=node.parent,
467 end_lineno=node.end_lineno,
468 end_col_offset=node.end_col_offset,
469 )
470 value.postinit(items)
471 return value
472
473
474def _mro_owner(cls: nodes.ClassDef, context: InferenceContext | None) -> nodes.ClassDef:
475 """Return the class whose mro a ``super()`` call with no argument walks.
476
477 ``super()`` with no argument is ``super(__class__, self)``. It starts the
478 lookup after the class the method is written in, but it walks the mro of the
479 object the method was called on, which can be a subclass, or a class that
480 only meets the method's own class in the mro of that subclass (a mixin).
481 ``context.boundnode`` is that object when it is known.
482 """
483 bound = context.boundnode if context is not None else None
484 if isinstance(bound, Instance):
485 bound_cls = bound._proxied
486 elif isinstance(bound, nodes.ClassDef):
487 bound_cls = bound
488 else:
489 return cls
490 try:
491 if cls in bound_cls.mro():
492 return bound_cls
493 except MroError:
494 pass
495 return cls
496
497
498def infer_super(
499 node: nodes.Call, context: InferenceContext | None = None
500) -> objects.Super:
501 """Understand super calls.
502
503 There are some restrictions for what can be understood:
504
505 * unbounded super (one argument form) is not understood.
506
507 * if the super call is not inside a function (classmethod or method),
508 then the default inference will be used.
509
510 * if the super arguments can't be inferred, the default inference
511 will be used.
512 """
513 if len(node.args) == 1:
514 # Ignore unbounded super.
515 raise UseInferenceDefault
516
517 scope = node.scope()
518 if not isinstance(scope, nodes.FunctionDef):
519 # Ignore non-method uses of super.
520 raise UseInferenceDefault
521 if scope.type not in ("classmethod", "method"):
522 # Not interested in staticmethods.
523 raise UseInferenceDefault
524
525 cls = scoped_nodes.get_wrapping_class(scope)
526 if not node.args:
527 if cls is None:
528 # A ``classmethod`` or ``method`` that is not defined inside a
529 # class, e.g. a module level function decorated with
530 # ``@classmethod``: there is nothing for the zero argument
531 # form to refer to.
532 raise UseInferenceDefault
533 mro_pointer = cls
534 mro_owner = _mro_owner(cls, context)
535 # In we are in a classmethod, the interpreter will fill
536 # automatically the class as the second argument, not an instance.
537 if scope.type == "classmethod":
538 mro_type = mro_owner
539 else:
540 mro_type = mro_owner.instantiate_class()
541 else:
542 try:
543 mro_pointer = next(node.args[0].infer(context=context))
544 except (InferenceError, StopIteration) as exc:
545 raise UseInferenceDefault from exc
546 try:
547 mro_type = next(node.args[1].infer(context=context))
548 except (InferenceError, StopIteration) as exc:
549 raise UseInferenceDefault from exc
550
551 if isinstance(mro_pointer, util.UninferableBase) or isinstance(
552 mro_type, util.UninferableBase
553 ):
554 # No way we could understand this.
555 raise UseInferenceDefault
556
557 super_obj = objects.Super(
558 mro_pointer=mro_pointer,
559 mro_type=mro_type,
560 self_class=cls,
561 scope=scope,
562 call=node,
563 )
564 super_obj.parent = node
565 return super_obj
566
567
568def _infer_getattr_args(node, context):
569 if len(node.args) not in (2, 3):
570 # Not a valid getattr call.
571 raise UseInferenceDefault
572
573 try:
574 obj = next(node.args[0].infer(context=context))
575 attr = next(node.args[1].infer(context=context))
576 except (InferenceError, StopIteration) as exc:
577 raise UseInferenceDefault from exc
578
579 if isinstance(obj, util.UninferableBase) or isinstance(attr, util.UninferableBase):
580 # If one of the arguments is something we can't infer,
581 # then also make the result of the getattr call something
582 # which is unknown.
583 return util.Uninferable, util.Uninferable
584
585 is_string = isinstance(attr, nodes.Const) and isinstance(attr.value, str)
586 if not is_string:
587 raise UseInferenceDefault
588
589 return obj, attr.value
590
591
592def infer_getattr(node, context: InferenceContext | None = None):
593 """Understand getattr calls.
594
595 If one of the arguments is an Uninferable object, then the
596 result will be an Uninferable object. Otherwise, the normal attribute
597 lookup will be done.
598 """
599 obj, attr = _infer_getattr_args(node, context)
600 if (
601 isinstance(obj, util.UninferableBase)
602 or isinstance(attr, util.UninferableBase)
603 or not hasattr(obj, "igetattr")
604 ):
605 return util.Uninferable
606
607 try:
608 return next(obj.igetattr(attr, context=context))
609 except (StopIteration, InferenceError, AttributeInferenceError):
610 if len(node.args) == 3:
611 # Try to infer the default and return it instead.
612 try:
613 return next(node.args[2].infer(context=context))
614 except (StopIteration, InferenceError) as exc:
615 raise UseInferenceDefault from exc
616
617 raise UseInferenceDefault
618
619
620def infer_hasattr(node, context: InferenceContext | None = None):
621 """Understand hasattr calls.
622
623 This always guarantees three possible outcomes for calling
624 hasattr: Const(False) when we are sure that the object
625 doesn't have the intended attribute, Const(True) when
626 we know that the object has the attribute and Uninferable
627 when we are unsure of the outcome of the function call.
628 """
629 try:
630 obj, attr = _infer_getattr_args(node, context)
631 if (
632 isinstance(obj, util.UninferableBase)
633 or isinstance(attr, util.UninferableBase)
634 or not hasattr(obj, "getattr")
635 ):
636 return util.Uninferable
637 obj.getattr(attr, context=context)
638 except UseInferenceDefault:
639 # Can't infer something from this function call.
640 return util.Uninferable
641 except AttributeInferenceError:
642 # Doesn't have it.
643 return nodes.Const(False)
644 return nodes.Const(True)
645
646
647def infer_callable(node, context: InferenceContext | None = None):
648 """Understand callable calls.
649
650 This follows Python's semantics, where an object
651 is callable if it provides an attribute __call__,
652 even though that attribute is something which can't be
653 called.
654 """
655 if len(node.args) != 1:
656 # Invalid callable call.
657 raise UseInferenceDefault
658
659 argument = node.args[0]
660 try:
661 inferred = next(argument.infer(context=context))
662 except (InferenceError, StopIteration):
663 return util.Uninferable
664 if isinstance(inferred, util.UninferableBase):
665 return util.Uninferable
666 return nodes.Const(inferred.callable())
667
668
669def infer_property(
670 node: nodes.Call, context: InferenceContext | None = None
671) -> objects.Property:
672 """Understand `property` class.
673
674 This only infers the output of `property`
675 call, not the arguments themselves.
676 """
677 if len(node.args) < 1:
678 # Invalid property call.
679 raise UseInferenceDefault
680
681 getter = node.args[0]
682 try:
683 inferred = next(getter.infer(context=context))
684 except (InferenceError, StopIteration) as exc:
685 raise UseInferenceDefault from exc
686
687 if not isinstance(inferred, (nodes.FunctionDef, nodes.Lambda)):
688 raise UseInferenceDefault
689
690 prop_func = objects.Property(
691 function=inferred,
692 name="<property>",
693 lineno=node.lineno,
694 col_offset=node.col_offset,
695 # ↓ semantically, the definition of the class of property isn't within
696 # node.frame. It's somewhere in the builtins module, but we are special
697 # casing it for each "property()" call, so we are making up the
698 # definition on the spot, ad-hoc.
699 parent=scoped_nodes.SYNTHETIC_ROOT,
700 )
701 prop_func.postinit(
702 body=[],
703 args=inferred.args,
704 doc_node=getattr(inferred, "doc_node", None),
705 )
706 return prop_func
707
708
709def infer_bool(node, context: InferenceContext | None = None):
710 """Understand bool calls."""
711 if len(node.args) > 1:
712 # Invalid bool call.
713 raise UseInferenceDefault
714
715 if not node.args:
716 return nodes.Const(False)
717
718 argument = node.args[0]
719 try:
720 inferred = next(argument.infer(context=context))
721 except (InferenceError, StopIteration):
722 return util.Uninferable
723 if isinstance(inferred, util.UninferableBase):
724 return util.Uninferable
725
726 bool_value = inferred.bool_value(context=context)
727 if isinstance(bool_value, util.UninferableBase):
728 return util.Uninferable
729 return nodes.Const(bool_value)
730
731
732def infer_type(node, context: InferenceContext | None = None):
733 """Understand the one-argument form of *type*."""
734 if len(node.args) != 1:
735 raise UseInferenceDefault
736
737 return helpers.object_type(node.args[0], context)
738
739
740def infer_slice(node, context: InferenceContext | None = None):
741 """Understand `slice` calls."""
742 args = node.args
743 if not 0 < len(args) <= 3:
744 raise UseInferenceDefault
745
746 infer_func = partial(util.safe_infer, context=context)
747 args = [infer_func(arg) for arg in args]
748 for arg in args:
749 if not arg or isinstance(arg, util.UninferableBase):
750 raise UseInferenceDefault
751 if not isinstance(arg, nodes.Const):
752 raise UseInferenceDefault
753 if not isinstance(arg.value, (type(None), int)):
754 raise UseInferenceDefault
755
756 if len(args) < 3:
757 # Make sure we have 3 arguments.
758 args.extend([None] * (3 - len(args)))
759
760 slice_node = nodes.Slice(
761 lineno=node.lineno,
762 col_offset=node.col_offset,
763 parent=node.parent,
764 end_lineno=node.end_lineno,
765 end_col_offset=node.end_col_offset,
766 )
767 slice_node.postinit(*args)
768 return slice_node
769
770
771def _infer_object__new__decorator(
772 node: nodes.ClassDef,
773 context: InferenceContext | None = None,
774) -> Iterator[Instance]:
775 # Instantiate class immediately
776 # since that's what @object.__new__ does
777 return iter((node.instantiate_class(),))
778
779
780def _infer_object__new__decorator_check(node) -> bool:
781 """Predicate before inference_tip.
782
783 Check if the given ClassDef has an @object.__new__ decorator
784 """
785 if not node.decorators:
786 return False
787
788 for decorator in node.decorators.nodes:
789 if isinstance(decorator, nodes.Attribute):
790 if decorator.as_string() == OBJECT_DUNDER_NEW:
791 return True
792 return False
793
794
795def infer_issubclass(
796 callnode: nodes.Call, context: InferenceContext | None = None
797) -> nodes.Const:
798 """Infer issubclass() calls.
799
800 :param callnode: an `issubclass` call
801 :param context: the context for the inference
802 :returns: Boolean Const value of the `issubclass` call
803 :raises UseInferenceDefault: If the node cannot be inferred
804 """
805 call = arguments.CallSite.from_call(callnode, context=context)
806 if call.keyword_arguments:
807 # issubclass doesn't support keyword arguments
808 raise UseInferenceDefault("TypeError: issubclass() takes no keyword arguments")
809 if len(call.positional_arguments) != 2:
810 raise UseInferenceDefault(
811 f"Expected two arguments, got {len(call.positional_arguments)}"
812 )
813 # The left hand argument is the obj to be checked
814 obj_node, class_or_tuple_node = call.positional_arguments
815
816 try:
817 obj_type = next(obj_node.infer(context=context))
818 except (InferenceError, StopIteration) as exc:
819 raise UseInferenceDefault from exc
820 if not isinstance(obj_type, nodes.ClassDef):
821 raise UseInferenceDefault(
822 f"TypeError: arg 1 must be class, not {type(obj_type)!r}"
823 )
824
825 # The right hand argument is the class(es) that the given
826 # object is to be checked against.
827 try:
828 class_container = helpers.class_or_tuple_to_container(
829 class_or_tuple_node, context=context
830 )
831 except InferenceError as exc:
832 raise UseInferenceDefault from exc
833 try:
834 issubclass_bool = helpers.object_issubclass(obj_type, class_container, context)
835 except AstroidTypeError as exc:
836 raise UseInferenceDefault("TypeError: " + str(exc)) from exc
837 except MroError as exc:
838 raise UseInferenceDefault from exc
839 return nodes.Const(issubclass_bool)
840
841
842def infer_isinstance(
843 callnode: nodes.Call, context: InferenceContext | None = None
844) -> nodes.Const:
845 """Infer isinstance calls.
846
847 :param callnode: an isinstance call
848 :raises UseInferenceDefault: If the node cannot be inferred
849 """
850 call = arguments.CallSite.from_call(callnode, context=context)
851 if call.keyword_arguments:
852 # isinstance doesn't support keyword arguments
853 raise UseInferenceDefault("TypeError: isinstance() takes no keyword arguments")
854 if len(call.positional_arguments) != 2:
855 raise UseInferenceDefault(
856 f"Expected two arguments, got {len(call.positional_arguments)}"
857 )
858 # The left hand argument is the obj to be checked
859 obj_node, class_or_tuple_node = call.positional_arguments
860 # The right hand argument is the class(es) that the given
861 # obj is to be check is an instance of
862 try:
863 class_container = helpers.class_or_tuple_to_container(
864 class_or_tuple_node, context=context
865 )
866 except InferenceError as exc:
867 raise UseInferenceDefault from exc
868 try:
869 isinstance_bool = helpers.object_isinstance(obj_node, class_container, context)
870 except AstroidTypeError as exc:
871 raise UseInferenceDefault("TypeError: " + str(exc)) from exc
872 except MroError as exc:
873 raise UseInferenceDefault from exc
874 if isinstance(isinstance_bool, util.UninferableBase):
875 raise UseInferenceDefault
876 return nodes.Const(isinstance_bool)
877
878
879def infer_len(node: nodes.Call, context: InferenceContext | None = None) -> nodes.Const:
880 """Infer length calls.
881
882 :param node: len call to infer
883 :param context: node context
884 :returns: a Const node with the inferred length, if possible
885 """
886 call = arguments.CallSite.from_call(node, context=context)
887 if call.keyword_arguments:
888 raise UseInferenceDefault("TypeError: len() must take no keyword arguments")
889 if len(call.positional_arguments) != 1:
890 raise UseInferenceDefault(
891 "TypeError: len() must take exactly one argument "
892 f"({len(call.positional_arguments)}) given"
893 )
894 [argument_node] = call.positional_arguments
895
896 try:
897 return nodes.Const(helpers.object_len(argument_node, context=context))
898 except (AstroidTypeError, InferenceError) as exc:
899 raise UseInferenceDefault(str(exc)) from exc
900
901
902def infer_str(node: nodes.Call, context: InferenceContext | None = None) -> nodes.Const:
903 """Infer str() calls.
904
905 :param node: str() call to infer
906 :param context: node context
907 :returns:
908 a Const containing a stringified value of str() call if possible, else an empty string
909 """
910 call = arguments.CallSite.from_call(node, context=context)
911 if call.keyword_arguments:
912 raise UseInferenceDefault("TypeError: str() must take no keyword arguments")
913
914 fallback = nodes.Const("")
915
916 if not call.positional_arguments:
917 return fallback
918
919 # Accept only if all inferred values resolve to the same string
920 candidates: set[str] = set()
921 try:
922 for inferred in call.positional_arguments[0].infer(context=context):
923 if not isinstance(inferred, nodes.Const):
924 return fallback
925
926 try:
927 candidates.add(str(inferred.value))
928 except ValueError:
929 return fallback
930 except InferenceError:
931 return fallback
932
933 if len(candidates) == 1:
934 return nodes.Const(next(iter(candidates)))
935 return fallback
936
937
938def infer_int(node: nodes.Call, context: InferenceContext | None = None) -> nodes.Const:
939 """Infer int() calls.
940
941 :param node: int() call to infer
942 :param context: node context
943 :returns: a Const containing the integer value of the int() call
944 """
945 call = arguments.CallSite.from_call(node, context=context)
946 if call.keyword_arguments:
947 raise UseInferenceDefault("TypeError: int() must take no keyword arguments")
948
949 if call.positional_arguments:
950 try:
951 first_value = next(call.positional_arguments[0].infer(context=context))
952 except (InferenceError, StopIteration) as exc:
953 raise UseInferenceDefault(str(exc)) from exc
954
955 if isinstance(first_value, util.UninferableBase):
956 raise UseInferenceDefault
957
958 if isinstance(first_value, nodes.Const) and isinstance(
959 first_value.value, (int, str)
960 ):
961 try:
962 actual_value = int(first_value.value)
963 except ValueError:
964 return nodes.Const(0)
965 return nodes.Const(actual_value)
966
967 return nodes.Const(0)
968
969
970def infer_dict_fromkeys(
971 node: nodes.Call, context: InferenceContext | None = None
972) -> nodes.Dict:
973 """Infer dict.fromkeys.
974
975 :param node: dict.fromkeys() call to infer
976 :param context: node context
977 :returns:
978 a Dictionary containing the values that astroid was able to infer.
979 In case the inference failed for any reason, an empty dictionary
980 will be inferred instead.
981 """
982
983 def _build_dict_with_elements(elements: list) -> nodes.Dict:
984 new_node = nodes.Dict(
985 col_offset=node.col_offset,
986 lineno=node.lineno,
987 parent=node.parent,
988 end_lineno=node.end_lineno,
989 end_col_offset=node.end_col_offset,
990 )
991 new_node.postinit(elements)
992 return new_node
993
994 def _unique_const_keys(keys: Iterable[nodes.Const]) -> list[nodes.Const]:
995 # dict.fromkeys deduplicates its keys, so keep only the first Const seen
996 # for a given value. Emitting one entry per element is wrong
997 # (dict.fromkeys("aab") has keys "a", "b") and lets a repeated string
998 # balloon the inferred dict.
999 seen: dict[object, nodes.Const] = {}
1000 for key in keys:
1001 seen.setdefault(key.value, key)
1002 return list(seen.values())
1003
1004 call = arguments.CallSite.from_call(node, context=context)
1005 if call.keyword_arguments:
1006 raise UseInferenceDefault("TypeError: int() must take no keyword arguments")
1007 if len(call.positional_arguments) not in {1, 2}:
1008 raise UseInferenceDefault(
1009 "TypeError: Needs between 1 and 2 positional arguments"
1010 )
1011
1012 default = nodes.Const(None)
1013 values = call.positional_arguments[0]
1014 try:
1015 inferred_values = next(values.infer(context=context))
1016 except (InferenceError, StopIteration):
1017 return _build_dict_with_elements([])
1018 if inferred_values is util.Uninferable:
1019 return _build_dict_with_elements([])
1020
1021 # Limit to a couple of potential values, as this can become pretty complicated
1022 accepted_iterable_elements = (nodes.Const,)
1023 if isinstance(inferred_values, (nodes.List, nodes.Set, nodes.Tuple)):
1024 elements = inferred_values.elts
1025 for element in elements:
1026 if not isinstance(element, accepted_iterable_elements):
1027 # Fallback to an empty dict
1028 return _build_dict_with_elements([])
1029
1030 elements_with_value = [
1031 (element, default) for element in _unique_const_keys(elements)
1032 ]
1033 return _build_dict_with_elements(elements_with_value)
1034 if isinstance(inferred_values, nodes.Const) and isinstance(
1035 inferred_values.value, (str, bytes)
1036 ):
1037 # Same cap as the container builders above.
1038 if len(inferred_values.value) > _MAX_INFERABLE_STR_LEN:
1039 return _build_dict_with_elements([])
1040 # Deduplicate the characters/bytes before building Const nodes so that a
1041 # compact but large string, e.g. dict.fromkeys("x" * 10**8), doesn't
1042 # materialize one node per character for what is a single-key dict.
1043 elements_with_value = [
1044 (nodes.Const(element), default)
1045 for element in dict.fromkeys(inferred_values.value)
1046 ]
1047 return _build_dict_with_elements(elements_with_value)
1048 if isinstance(inferred_values, nodes.Dict):
1049 keys = inferred_values.itered()
1050 for key in keys:
1051 if not isinstance(key, accepted_iterable_elements):
1052 # Fallback to an empty dict
1053 return _build_dict_with_elements([])
1054
1055 elements_with_value = [
1056 (element, default) for element in _unique_const_keys(keys)
1057 ]
1058 return _build_dict_with_elements(elements_with_value)
1059
1060 # Fallback to an empty dictionary
1061 return _build_dict_with_elements([])
1062
1063
1064def _infer_copy_method(
1065 node: nodes.Call, context: InferenceContext | None = None
1066) -> Iterator[CopyResult]:
1067 assert isinstance(node.func, nodes.Attribute)
1068 inferred_orig, inferred_copy = itertools.tee(node.func.expr.infer(context=context))
1069 if all(
1070 isinstance(
1071 inferred_node, (nodes.Dict, nodes.List, nodes.Set, objects.FrozenSet)
1072 )
1073 for inferred_node in inferred_orig
1074 ):
1075 return cast(Iterator[CopyResult], inferred_copy)
1076
1077 raise UseInferenceDefault
1078
1079
1080def _is_str_format_call(node: nodes.Call) -> bool:
1081 """Catch calls to str.format()."""
1082 if not (isinstance(node.func, nodes.Attribute) and node.func.attrname == "format"):
1083 return False
1084
1085 if isinstance(node.func.expr, nodes.Name):
1086 value = util.safe_infer(node.func.expr)
1087 else:
1088 value = node.func.expr
1089
1090 return isinstance(value, nodes.Const) and isinstance(value.value, str)
1091
1092
1093def _infer_str_format_call(
1094 node: nodes.Call, context: InferenceContext | None = None
1095) -> Iterator[ConstFactoryResult | util.UninferableBase]:
1096 """Return a Const node based on the template and passed arguments."""
1097 call = arguments.CallSite.from_call(node, context=context)
1098 assert isinstance(node.func, (nodes.Attribute, nodes.AssignAttr, nodes.DelAttr))
1099
1100 value: nodes.Const
1101 if isinstance(node.func.expr, nodes.Name):
1102 if not (
1103 (inferred := util.safe_infer(node.func.expr))
1104 and isinstance(inferred, nodes.Const)
1105 ):
1106 return iter([util.Uninferable])
1107 value = inferred
1108 elif isinstance(node.func.expr, nodes.Const):
1109 value = node.func.expr
1110 else: # pragma: no cover
1111 return iter([util.Uninferable])
1112
1113 format_template = value.value
1114
1115 # Get the positional arguments passed
1116 inferred_positional: list[nodes.Const] = []
1117 for i in call.positional_arguments:
1118 one_inferred = util.safe_infer(i, context)
1119 if not isinstance(one_inferred, nodes.Const):
1120 return iter([util.Uninferable])
1121 inferred_positional.append(one_inferred)
1122
1123 pos_values: list[str] = [i.value for i in inferred_positional]
1124
1125 # Get the keyword arguments passed
1126 inferred_keyword: dict[str, nodes.Const] = {}
1127 for k, v in call.keyword_arguments.items():
1128 one_inferred = util.safe_infer(v, context)
1129 if not isinstance(one_inferred, nodes.Const):
1130 return iter([util.Uninferable])
1131 inferred_keyword[k] = one_inferred
1132
1133 keyword_values: dict[str, str] = {k: v.value for k, v in inferred_keyword.items()}
1134
1135 formatter = _get_bounded_formatter()
1136 try:
1137 fields = list(formatter.parse(format_template))
1138 except ValueError:
1139 return iter([util.Uninferable])
1140 if any(spec and util.format_spec_too_large(spec) for _, _, spec, _ in fields):
1141 return iter([util.Uninferable])
1142
1143 try:
1144 formatted_string = formatter.format(
1145 format_template, *pos_values, **keyword_values
1146 )
1147 except (AttributeError, IndexError, KeyError, TypeError, ValueError, OverflowError):
1148 # AttributeError: named field in format string was not found in the arguments
1149 # IndexError: there are too few arguments to interpolate
1150 # TypeError: Unsupported format string
1151 # ValueError: Unknown format code
1152 # OverflowError: "c" with an out-of-range code point, e.g. "{:c}".format(-1)
1153 return iter([util.Uninferable])
1154
1155 return iter([nodes.const_factory(formatted_string)])
1156
1157
1158# Mapping of builtin name → inference function, consumed by the single
1159# dispatcher transform registered for ``nodes.Call``. One transform-list entry
1160# per builtin would run its own predicate on every Call node; the dispatcher
1161# does the ``isinstance``/name lookup once and routes via this dict.
1162_BuiltinInferFn = Callable[
1163 [nodes.Call, InferenceContext | None], SuccessfulInferenceResult | None
1164]
1165_BUILTIN_INFERENCE_FUNCS: dict[str, _BuiltinInferFn] = {
1166 "bool": infer_bool,
1167 "super": infer_super,
1168 "callable": infer_callable,
1169 "property": infer_property,
1170 "getattr": infer_getattr,
1171 "hasattr": infer_hasattr,
1172 "tuple": infer_tuple,
1173 "set": infer_set,
1174 "list": infer_list,
1175 "dict": infer_dict,
1176 "frozenset": infer_frozenset,
1177 "type": infer_type,
1178 "slice": infer_slice,
1179 "isinstance": infer_isinstance,
1180 "issubclass": infer_issubclass,
1181 "len": infer_len,
1182 "str": infer_str,
1183 "int": infer_int,
1184 "dict.fromkeys": infer_dict_fromkeys,
1185}
1186
1187
1188def register(manager: AstroidManager) -> None:
1189 # Builtins inference, through a single dispatcher (#1115)
1190 manager.register_transform(
1191 nodes.Call,
1192 inference_tip(_builtin_dispatch_transform),
1193 _builtin_dispatch_predicate,
1194 )
1195
1196 # Infer object.__new__ calls
1197 manager.register_transform(
1198 nodes.ClassDef,
1199 inference_tip(_infer_object__new__decorator),
1200 _infer_object__new__decorator_check,
1201 )
1202
1203 manager.register_transform(
1204 nodes.Call,
1205 inference_tip(_infer_copy_method),
1206 lambda node: isinstance(node.func, nodes.Attribute)
1207 and node.func.attrname == "copy",
1208 )
1209
1210 manager.register_transform(
1211 nodes.Call,
1212 inference_tip(_infer_str_format_call),
1213 _is_str_format_call,
1214 )