"""Plugin that provides support for dataclasses."""

from __future__ import annotations

from typing import TYPE_CHECKING, Final, Iterator, Literal

from mypy import errorcodes, message_registry
from mypy.expandtype import expand_type, expand_type_by_instance
from mypy.meet import meet_types
from mypy.messages import format_type_bare
from mypy.nodes import (
    ARG_NAMED,
    ARG_NAMED_OPT,
    ARG_OPT,
    ARG_POS,
    ARG_STAR,
    ARG_STAR2,
    MDEF,
    Argument,
    AssignmentStmt,
    Block,
    CallExpr,
    ClassDef,
    Context,
    DataclassTransformSpec,
    Decorator,
    EllipsisExpr,
    Expression,
    FuncDef,
    FuncItem,
    IfStmt,
    JsonDict,
    NameExpr,
    Node,
    PlaceholderNode,
    RefExpr,
    Statement,
    SymbolTableNode,
    TempNode,
    TypeAlias,
    TypeInfo,
    TypeVarExpr,
    Var,
)
from mypy.plugin import ClassDefContext, FunctionSigContext, SemanticAnalyzerPluginInterface
from mypy.plugins.common import (
    _get_callee_type,
    _get_decorator_bool_argument,
    add_attribute_to_class,
    add_method_to_class,
    deserialize_and_fixup_type,
)
from mypy.semanal_shared import find_dataclass_transform_spec, require_bool_literal_argument
from mypy.server.trigger import make_wildcard_trigger
from mypy.state import state
from mypy.typeops import map_type_from_supertype, try_getting_literals_from_type
from mypy.types import (
    AnyType,
    CallableType,
    FunctionLike,
    Instance,
    LiteralType,
    NoneType,
    ProperType,
    TupleType,
    Type,
    TypeOfAny,
    TypeVarId,
    TypeVarType,
    UninhabitedType,
    UnionType,
    get_proper_type,
)
from mypy.typevars import fill_typevars

if TYPE_CHECKING:
    from mypy.checker import TypeChecker

# The set of decorators that generate dataclasses.
dataclass_makers: Final = {"dataclass", "dataclasses.dataclass"}

SELF_TVAR_NAME: Final = "_DT"
_TRANSFORM_SPEC_FOR_DATACLASSES: Final = DataclassTransformSpec(
    eq_default=True,
    order_default=False,
    kw_only_default=False,
    frozen_default=False,
    field_specifiers=("dataclasses.Field", "dataclasses.field"),
)
_INTERNAL_REPLACE_SYM_NAME: Final = "__mypy-replace"
_INTERNAL_POST_INIT_SYM_NAME: Final = "__mypy-post_init"

class DataclassAttribute:
    def __init__(
        self,
        name: str,
        alias: str | None,
        is_in_init: bool,
        is_init_var: bool,
        has_default: bool,
        line: int,
        column: int,
        type: Type | None,
        info: TypeInfo,
        kw_only: bool,
        is_neither_frozen_nor_nonfrozen: bool,
        api: SemanticAnalyzerPluginInterface,
    ) -> None:
        self.name = name
        self.alias = alias
        self.is_in_init = is_in_init
        self.is_init_var = is_init_var
        self.has_default = has_default
        self.line = line
        self.column = column
        self.type = type  # Type as __init__ argument
        self.info = info
        self.kw_only = kw_only
        self.is_neither_frozen_nor_nonfrozen = is_neither_frozen_nor_nonfrozen
        self._api = api

    def to_argument(
        self, current_info: TypeInfo, *, of: Literal["__init__", "replace", "__post_init__"]
    ) -> Argument:
        if of == "__init__":
            arg_kind = ARG_POS
            if self.kw_only and self.has_default:
                arg_kind = ARG_NAMED_OPT
            elif self.kw_only and not self.has_default:
                arg_kind = ARG_NAMED
            elif not self.kw_only and self.has_default:
                arg_kind = ARG_OPT
        elif of == "replace":
            arg_kind = ARG_NAMED if self.is_init_var and not self.has_default else ARG_NAMED_OPT
        elif of == "__post_init__":
            # We always use `ARG_POS` without a default value, because it is practical.
            # Consider this case:
            #
            # @dataclass
            # class My:
            #     y: dataclasses.InitVar[str] = 'a'
            #     def __post_init__(self, y: str) -> None: ...
            #
            # We would be *required* to specify `y: str = ...` if default is added here.
            # But, most people won't care about adding default values to `__post_init__`,
            # because it is not designed to be called directly, and duplicating default values
            # for the sake of type-checking is unpleasant.
            arg_kind = ARG_POS
        return Argument(
            variable=self.to_var(current_info),
            type_annotation=self.expand_type(current_info),
            initializer=EllipsisExpr() if self.has_default else None,  # Only used by stubgen
            kind=arg_kind,
        )

    def expand_type(self, current_info: TypeInfo) -> Type | None:
        if self.type is not None and self.info.self_type is not None:
            # In general, it is not safe to call `expand_type()` during semantic analysis,
            # however this plugin is called very late, so all types should be fully ready.
            # Also, it is tricky to avoid eager expansion of Self types here (e.g. because
            # we serialize attributes).
            with state.strict_optional_set(self._api.options.strict_optional):
                return expand_type(
                    self.type, {self.info.self_type.id: fill_typevars(current_info)}
                )
        return self.type

    def to_var(self, current_info: TypeInfo) -> Var:
        return Var(self.alias or self.name, self.expand_type(current_info))

    def serialize(self) -> JsonDict:
        assert self.type
        return {
            "name": self.name,
            "alias": self.alias,
            "is_in_init": self.is_in_init,
            "is_init_var": self.is_init_var,
            "has_default": self.has_default,
            "line": self.line,
            "column": self.column,
            "type": self.type.serialize(),
            "kw_only": self.kw_only,
            "is_neither_frozen_nor_nonfrozen": self.is_neither_frozen_nor_nonfrozen,
        }

    @classmethod
    def deserialize(
        cls, info: TypeInfo, data: JsonDict, api: SemanticAnalyzerPluginInterface
    ) -> DataclassAttribute:
        data = data.copy()
        typ = deserialize_and_fixup_type(data.pop("type"), api)
        return cls(type=typ, info=info, **data, api=api)

    def expand_typevar_from_subtype(self, sub_type: TypeInfo) -> None:
        """Expands type vars in the context of a subtype when an attribute is inherited
        from a generic super type."""
        if self.type is not None:
            with state.strict_optional_set(self._api.options.strict_optional):
                self.type = map_type_from_supertype(self.type, sub_type, self.info)

class DataclassTransformer:
    """Implement the behavior of @dataclass.

    Note that this may be executed multiple times on the same class, so
    everything here must be idempotent.

    This runs after the main semantic analysis pass, so you can assume that
    there are no placeholders.
    """

    def __init__(
        self,
        cls: ClassDef,
        # Statement must also be accepted since class definition itself may be passed as the reason
        # for subclass/metaclass-based uses of `typing.dataclass_transform`
        reason: Expression | Statement,
        spec: DataclassTransformSpec,
        api: SemanticAnalyzerPluginInterface,
    ) -> None:
        self._cls = cls
        self._reason = reason
        self._spec = spec
        self._api = api

    def transform(self) -> bool:
        """Apply all the necessary transformations to the underlying
        dataclass so as to ensure it is fully type checked according
        to the rules in PEP 557.
        """
        info = self._cls.info
        attributes = self.collect_attributes()
        if attributes is None:
            # Some definitions are not ready. We need another pass.
            return False
        for attr in attributes:
            if attr.type is None:
                return False
        decorator_arguments = {
            "init": self._get_bool_arg("init", True),
            "eq": self._get_bool_arg("eq", self._spec.eq_default),
            "order": self._get_bool_arg("order", self._spec.order_default),
            "frozen": self._get_bool_arg("frozen", self._spec.frozen_default),
            "slots": self._get_bool_arg("slots", False),
            "match_args": self._get_bool_arg("match_args", True),
        }
        py_version = self._api.options.python_version

        # If there are no attributes, it may be that the semantic analyzer has not
        # processed them yet. In order to work around this, we can simply skip generating
        # __init__ if there are no attributes, because if the user truly did not define any,
        # then the object default __init__ with an empty signature will be present anyway.
        if (
            decorator_arguments["init"]
            and ("__init__" not in info.names or info.names["__init__"].plugin_generated)
            and attributes
        ):
            args = [
                attr.to_argument(info, of="__init__")
                for attr in attributes
                if attr.is_in_init and not self._is_kw_only_type(attr.type)
            ]

            if info.fallback_to_any:
                # Make positional args optional since we don't know their order.
                # This will at least allow us to typecheck them if they are called
                # as kwargs
                for arg in args:
                    if arg.kind == ARG_POS:
                        arg.kind = ARG_OPT

                existing_args_names = {arg.variable.name for arg in args}
                gen_args_name = "generated_args"
                while gen_args_name in existing_args_names:
                    gen_args_name += "_"
                gen_kwargs_name = "generated_kwargs"
                while gen_kwargs_name in existing_args_names:
                    gen_kwargs_name += "_"
                args = [
                    Argument(Var(gen_args_name), AnyType(TypeOfAny.explicit), None, ARG_STAR),
                    *args,
                    Argument(Var(gen_kwargs_name), AnyType(TypeOfAny.explicit), None, ARG_STAR2),
                ]

            add_method_to_class(
                self._api, self._cls, "__init__", args=args, return_type=NoneType()
            )

        if (
            decorator_arguments["eq"]
            and info.get("__eq__") is None
            or decorator_arguments["order"]
        ):
            # Type variable for self types in generated methods.
            obj_type = self._api.named_type("builtins.object")
            self_tvar_expr = TypeVarExpr(
                SELF_TVAR_NAME,
                info.fullname + "." + SELF_TVAR_NAME,
                [],
                obj_type,
                AnyType(TypeOfAny.from_omitted_generics),
            )
            info.names[SELF_TVAR_NAME] = SymbolTableNode(MDEF, self_tvar_expr)

        # Add <, >, <=, >=, but only if the class has an eq method.
        if decorator_arguments["order"]:
            if not decorator_arguments["eq"]:
                self._api.fail('"eq" must be True if "order" is True', self._reason)

            for method_name in ["__lt__", "__gt__", "__le__", "__ge__"]:
                # Like for __eq__ and __ne__, we want "other" to match
                # the self type.
                obj_type = self._api.named_type("builtins.object")
                order_tvar_def = TypeVarType(
                    SELF_TVAR_NAME,
                    f"{info.fullname}.{SELF_TVAR_NAME}",
                    id=TypeVarId(-1, namespace=f"{info.fullname}.{method_name}"),
                    values=[],
                    upper_bound=obj_type,
                    default=AnyType(TypeOfAny.from_omitted_generics),
                )
                order_return_type = self._api.named_type("builtins.bool")
                order_args = [
                    Argument(Var("other", order_tvar_def), order_tvar_def, None, ARG_POS)
                ]

                existing_method = info.get(method_name)
                if existing_method is not None and not existing_method.plugin_generated:
                    assert existing_method.node
                    self._api.fail(
                        f'You may not have a custom "{method_name}" method when "order" is True',
                        existing_method.node,
                    )

                add_method_to_class(
                    self._api,
                    self._cls,
                    method_name,
                    args=order_args,
                    return_type=order_return_type,
                    self_type=order_tvar_def,
                    tvar_def=order_tvar_def,
                )

        parent_decorator_arguments = []
        for parent in info.mro[1:-1]:
            parent_args = parent.metadata.get("dataclass")

            # Ignore parent classes that directly specify a dataclass transform-decorated metaclass
            # when searching for usage of the frozen parameter. PEP 681 states that a class that
            # directly specifies such a metaclass must be treated as neither frozen nor non-frozen.
            if parent_args and not _has_direct_dataclass_transform_metaclass(parent):
                parent_decorator_arguments.append(parent_args)

        if decorator_arguments["frozen"]:
            if any(not parent["frozen"] for parent in parent_decorator_arguments):
                self._api.fail("Cannot inherit frozen dataclass from a non-frozen one", info)
            self._propertize_callables(attributes, settable=False)
            self._freeze(attributes)
        else:
            if any(parent["frozen"] for parent in parent_decorator_arguments):
                self._api.fail("Cannot inherit non-frozen dataclass from a frozen one", info)
            self._propertize_callables(attributes)

        if decorator_arguments["slots"]:
            self.add_slots(info, attributes, correct_version=py_version >= (3, 10))

        self.reset_init_only_vars(info, attributes)

        if (
            decorator_arguments["match_args"]
            and (
                "__match_args__" not in info.names or info.names["__match_args__"].plugin_generated
            )
            and py_version >= (3, 10)
        ):
            str_type = self._api.named_type("builtins.str")
            literals: list[Type] = [
                LiteralType(attr.name, str_type) for attr in attributes if attr.is_in_init
            ]
            match_args_type = TupleType(literals, self._api.named_type("builtins.tuple"))
            add_attribute_to_class(self._api, self._cls, "__match_args__", match_args_type)

        self._add_dataclass_fields_magic_attribute()
        self._add_internal_replace_method(attributes)
        if self._api.options.python_version >= (3, 13):
            self._add_dunder_replace(attributes)

        if "__post_init__" in info.names:
            self._add_internal_post_init_method(attributes)

        info.metadata["dataclass"] = {
            "attributes": [attr.serialize() for attr in attributes],
            "frozen": decorator_arguments["frozen"],
        }

        return True

    def _add_dunder_replace(self, attributes: list[DataclassAttribute]) -> None:
        """Add a `__replace__` method to the class, which is used to replace attributes in the `copy` module."""
        args = [attr.to_argument(self._cls.info, of="replace") for attr in attributes]
        type_vars = [tv for tv in self._cls.type_vars]
        add_method_to_class(
            self._api,
            self._cls,
            "__replace__",
            args=args,
            return_type=Instance(self._cls.info, type_vars),
        )

    def _add_internal_replace_method(self, attributes: list[DataclassAttribute]) -> None:
        """
        Stashes the signature of 'dataclasses.replace(...)' for this specific dataclass
        to be used later whenever 'dataclasses.replace' is called for this dataclass.
        """
        add_method_to_class(
            self._api,
            self._cls,
            _INTERNAL_REPLACE_SYM_NAME,
            args=[attr.to_argument(self._cls.info, of="replace") for attr in attributes],
            return_type=NoneType(),
            is_staticmethod=True,
        )

    def _add_internal_post_init_method(self, attributes: list[DataclassAttribute]) -> None:
        add_method_to_class(
            self._api,
            self._cls,
            _INTERNAL_POST_INIT_SYM_NAME,
            args=[
                attr.to_argument(self._cls.info, of="__post_init__")
                for attr in attributes
                if attr.is_init_var
            ],
            return_type=NoneType(),
        )

    def add_slots(
        self, info: TypeInfo, attributes: list[DataclassAttribute], *, correct_version: bool
    ) -> None:
        if not correct_version:
            # This means that version is lower than `3.10`,
            # it is just a non-existent argument for `dataclass` function.
            self._api.fail(
                'Keyword argument "slots" for "dataclass" '
                "is only valid in Python 3.10 and higher",
                self._reason,
            )
            return

        generated_slots = {attr.name for attr in attributes}
        if (info.slots is not None and info.slots != generated_slots) or info.names.get(
            "__slots__"
        ):
            # This means we have a slots conflict.
            # Class explicitly specifies a different `__slots__` field.
            # And `@dataclass(slots=True)` is used.
            # In runtime this raises a type error.
            self._api.fail(
                '"{}" both defines "__slots__" and is used with "slots=True"'.format(
                    self._cls.name
                ),
                self._cls,
            )
            return

        if any(p.slots is None for p in info.mro[1:-1]):
            # At least one type in mro (excluding `self` and `object`)
            # does not have concrete `__slots__` defined. Ignoring.
            return

        info.slots = generated_slots

        # Now, insert `.__slots__` attribute to class namespace:
        slots_type = TupleType(
            [self._api.named_type("builtins.str") for _ in generated_slots],
            self._api.named_type("builtins.tuple"),
        )
        add_attribute_to_class(self._api, self._cls, "__slots__", slots_type)

    def reset_init_only_vars(self, info: TypeInfo, attributes: list[DataclassAttribute]) -> None:
        """Remove init-only vars from the class and reset init var declarations."""
        for attr in attributes:
            if attr.is_init_var:
                if attr.name in info.names:
                    del info.names[attr.name]
                else:
                    # Nodes of superclass InitVars not used in __init__ cannot be reached.
                    assert attr.is_init_var
                for stmt in info.defn.defs.body:
                    if isinstance(stmt, AssignmentStmt) and stmt.unanalyzed_type:
                        lvalue = stmt.lvalues[0]
                        if isinstance(lvalue, NameExpr) and lvalue.name == attr.name:
                            # Reset node so that another semantic analysis pass will
                            # recreate a symbol node for this attribute.
                            lvalue.node = None

    def _get_assignment_statements_from_if_statement(
        self, stmt: IfStmt
    ) -> Iterator[AssignmentStmt]:
        for body in stmt.body:
            if not body.is_unreachable:
                yield from self._get_assignment_statements_from_block(body)
        if stmt.else_body is not None and not stmt.else_body.is_unreachable:
            yield from self._get_assignment_statements_from_block(stmt.else_body)

    def _get_assignment_statements_from_block(self, block: Block) -> Iterator[AssignmentStmt]:
        for stmt in block.body:
            if isinstance(stmt, AssignmentStmt):
                yield stmt
            elif isinstance(stmt, IfStmt):
                yield from self._get_assignment_statements_from_if_statement(stmt)

    def collect_attributes(self) -> list[DataclassAttribute] | None:
        """Collect all attributes declared in the dataclass and its parents.

        All assignments of the form

          a: SomeType
          b: SomeOtherType = ...

        are collected.

        Return None if some dataclass base class hasn't been processed
        yet and thus we'll need to ask for another pass.
        """
        cls = self._cls

        # First, collect attributes belonging to any class in the MRO, ignoring duplicates.
        #
        # We iterate through the MRO in reverse because attrs defined in the parent must appear
        # earlier in the attributes list than attrs defined in the child. See:
        # https://docs.python.org/3/library/dataclasses.html#inheritance
        #
        # However, we also want attributes defined in the subtype to override ones defined
        # in the parent. We can implement this via a dict without disrupting the attr order
        # because dicts preserve insertion order in Python 3.7+.
        found_attrs: dict[str, DataclassAttribute] = {}
        found_dataclass_supertype = False
        for info in reversed(cls.info.mro[1:-1]):
            if "dataclass_tag" in info.metadata and "dataclass" not in info.metadata:
                # We haven't processed the base class yet. Need another pass.
                return None
            if "dataclass" not in info.metadata:
                continue

            # Each class depends on the set of attributes in its dataclass ancestors.
            self._api.add_plugin_dependency(make_wildcard_trigger(info.fullname))
            found_dataclass_supertype = True

            for data in info.metadata["dataclass"]["attributes"]:
                name: str = data["name"]

                attr = DataclassAttribute.deserialize(info, data, self._api)
                # TODO: We shouldn't be performing type operations during the main
                #       semantic analysis pass, since some TypeInfo attributes might
                #       still be in flux. This should be performed in a later phase.
                attr.expand_typevar_from_subtype(cls.info)
                found_attrs[name] = attr

                sym_node = cls.info.names.get(name)
                if sym_node and sym_node.node and not isinstance(sym_node.node, Var):
                    self._api.fail(
                        "Dataclass attribute may only be overridden by another attribute",
                        sym_node.node,
                    )

        # Second, collect attributes belonging to the current class.
        current_attr_names: set[str] = set()
        kw_only = self._get_bool_arg("kw_only", self._spec.kw_only_default)
        for stmt in self._get_assignment_statements_from_block(cls.defs):
            # Any assignment that doesn't use the new type declaration
            # syntax can be ignored out of hand.
            if not stmt.new_syntax:
                continue

            # a: int, b: str = 1, 'foo' is not supported syntax so we
            # don't have to worry about it.
            lhs = stmt.lvalues[0]
            if not isinstance(lhs, NameExpr):
                continue

            sym = cls.info.names.get(lhs.name)
            if sym is None:
                # There was probably a semantic analysis error.
                continue

            node = sym.node
            assert not isinstance(node, PlaceholderNode)

            if isinstance(node, TypeAlias):
                self._api.fail(
                    ("Type aliases inside dataclass definitions are not supported at runtime"),
                    node,
                )
                # Skip processing this node. This doesn't match the runtime behaviour,
                # but the only alternative would be to modify the SymbolTable,
                # and it's a little hairy to do that in a plugin.
                continue
            if isinstance(node, Decorator):
                # This might be a property / field name clash.
                # We will issue an error later.
                continue

            assert isinstance(node, Var)

            # x: ClassVar[int] is ignored by dataclasses.
            if node.is_classvar:
                continue

            # x: InitVar[int] is turned into x: int and is removed from the class.
            is_init_var = False
            node_type = get_proper_type(node.type)
            if (
                isinstance(node_type, Instance)
                and node_type.type.fullname == "dataclasses.InitVar"
            ):
                is_init_var = True
                node.type = node_type.args[0]

            if self._is_kw_only_type(node_type):
                kw_only = True

            has_field_call, field_args = self._collect_field_args(stmt.rvalue)

            is_in_init_param = field_args.get("init")
            if is_in_init_param is None:
                is_in_init = self._get_default_init_value_for_field_specifier(stmt.rvalue)
            else:
                is_in_init = bool(self._api.parse_bool(is_in_init_param))

            has_default = False
            # Ensure that something like x: int = field() is rejected
            # after an attribute with a default.
            if has_field_call:
                has_default = (
                    "default" in field_args
                    or "default_factory" in field_args
                    # alias for default_factory defined in PEP 681
                    or "factory" in field_args
                )

            # All other assignments are already type checked.
            elif not isinstance(stmt.rvalue, TempNode):
                has_default = True

            if not has_default and self._spec is _TRANSFORM_SPEC_FOR_DATACLASSES:
                # Make all non-default dataclass attributes implicit because they are de-facto
                # set on self in the generated __init__(), not in the class body. On the other
                # hand, we don't know how custom dataclass transforms initialize attributes,
                # so we don't treat them as implicit. This is required to support descriptors
                # (https://github.com/python/mypy/issues/14868).
                sym.implicit = True

            is_kw_only = kw_only
            # Use the kw_only field arg if it is provided. Otherwise use the
            # kw_only value from the decorator parameter.
            field_kw_only_param = field_args.get("kw_only")
            if field_kw_only_param is not None:
                value = self._api.parse_bool(field_kw_only_param)
                if value is not None:
                    is_kw_only = value
                else:
                    self._api.fail('"kw_only" argument must be a boolean literal', stmt.rvalue)

            if sym.type is None and node.is_final and node.is_inferred:
                # This is a special case, assignment like x: Final = 42 is classified
                # annotated above, but mypy strips the `Final` turning it into x = 42.
                # We do not support inferred types in dataclasses, so we can try inferring
                # type for simple literals, and otherwise require an explicit type
                # argument for Final[...].
                typ = self._api.analyze_simple_literal_type(stmt.rvalue, is_final=True)
                if typ:
                    node.type = typ
                else:
                    self._api.fail(
                        "Need type argument for Final[...] with non-literal default in dataclass",
                        stmt,
                    )
                    node.type = AnyType(TypeOfAny.from_error)

            alias = None
            if "alias" in field_args:
                alias = self._api.parse_str_literal(field_args["alias"])
                if alias is None:
                    self._api.fail(
                        message_registry.DATACLASS_FIELD_ALIAS_MUST_BE_LITERAL,
                        stmt.rvalue,
                        code=errorcodes.LITERAL_REQ,
                    )

            current_attr_names.add(lhs.name)
            with state.strict_optional_set(self._api.options.strict_optional):
                init_type = self._infer_dataclass_attr_init_type(sym, lhs.name, stmt)
            found_attrs[lhs.name] = DataclassAttribute(
                name=lhs.name,
                alias=alias,
                is_in_init=is_in_init,
                is_init_var=is_init_var,
                has_default=has_default,
                line=stmt.line,
                column=stmt.column,
                type=init_type,
                info=cls.info,
                kw_only=is_kw_only,
                is_neither_frozen_nor_nonfrozen=_has_direct_dataclass_transform_metaclass(
                    cls.info
                ),
                api=self._api,
            )

        all_attrs = list(found_attrs.values())
        if found_dataclass_supertype:
            all_attrs.sort(key=lambda a: a.kw_only)

        # Third, ensure that arguments without a default don't follow
        # arguments that have a default and that the KW_ONLY sentinel
        # is only provided once.
        found_default = False
        found_kw_sentinel = False
        for attr in all_attrs:
            # If we find any attribute that is_in_init, not kw_only, and that
            # doesn't have a default after one that does have one,
            # then that's an error.
            if found_default and attr.is_in_init and not attr.has_default and not attr.kw_only:
                # If the issue comes from merging different classes, report it
                # at the class definition point.
                context: Context = cls
                if attr.name in current_attr_names:
                    context = Context(line=attr.line, column=attr.column)
                self._api.fail(
                    "Attributes without a default cannot follow attributes with one", context
                )

            found_default = found_default or (attr.has_default and attr.is_in_init)
            if found_kw_sentinel and self._is_kw_only_type(attr.type):
                context = cls
                if attr.name in current_attr_names:
                    context = Context(line=attr.line, column=attr.column)
                self._api.fail(
                    "There may not be more than one field with the KW_ONLY type", context
                )
            found_kw_sentinel = found_kw_sentinel or self._is_kw_only_type(attr.type)
        return all_attrs

    def _freeze(self, attributes: list[DataclassAttribute]) -> None:
        """Converts all attributes to @property methods in order to
        emulate frozen classes.
        """
        info = self._cls.info
        for attr in attributes:
            # Classes that directly specify a dataclass_transform metaclass must be neither frozen
            # non non-frozen per PEP681. Though it is surprising, this means that attributes from
            # such a class must be writable even if the rest of the class hierarchy is frozen. This
            # matches the behavior of Pyright (the reference implementation).
            if attr.is_neither_frozen_nor_nonfrozen:
                continue

            sym_node = info.names.get(attr.name)
            if sym_node is not None:
                var = sym_node.node
                if isinstance(var, Var):
                    var.is_property = True
            else:
                var = attr.to_var(info)
                var.info = info
                var.is_property = True
                var._fullname = info.fullname + "." + var.name
                info.names[var.name] = SymbolTableNode(MDEF, var)

    def _propertize_callables(
        self, attributes: list[DataclassAttribute], settable: bool = True
    ) -> None:
        """Converts all attributes with callable types to @property methods.

        This avoids the typechecker getting confused and thinking that
        `my_dataclass_instance.callable_attr(foo)` is going to receive a
        `self` argument (it is not).

        """
        info = self._cls.info
        for attr in attributes:
            if isinstance(get_proper_type(attr.type), CallableType):
                var = attr.to_var(info)
                var.info = info
                var.is_property = True
                var.is_settable_property = settable
                var._fullname = info.fullname + "." + var.name
                info.names[var.name] = SymbolTableNode(MDEF, var)

    def _is_kw_only_type(self, node: Type | None) -> bool:
        """Checks if the type of the node is the KW_ONLY sentinel value."""
        if node is None:
            return False
        node_type = get_proper_type(node)
        if not isinstance(node_type, Instance):
            return False
        return node_type.type.fullname == "dataclasses.KW_ONLY"

    def _add_dataclass_fields_magic_attribute(self) -> None:
        attr_name = "__dataclass_fields__"
        any_type = AnyType(TypeOfAny.explicit)
        # For `dataclasses`, use the type `dict[str, Field[Any]]` for accuracy. For dataclass
        # transforms, it's inaccurate to use `Field` since a given transform may use a completely
        # different type (or none); fall back to `Any` there.
        #
        # In either case, we're aiming to match the Typeshed stub for `is_dataclass`, which expects
        # the instance to have a `__dataclass_fields__` attribute of type `dict[str, Field[Any]]`.
        if self._spec is _TRANSFORM_SPEC_FOR_DATACLASSES:
            field_type = self._api.named_type_or_none("dataclasses.Field", [any_type]) or any_type
        else:
            field_type = any_type
        attr_type = self._api.named_type(
            "builtins.dict", [self._api.named_type("builtins.str"), field_type]
        )
        var = Var(name=attr_name, type=attr_type)
        var.info = self._cls.info
        var._fullname = self._cls.info.fullname + "." + attr_name
        var.is_classvar = True
        self._cls.info.names[attr_name] = SymbolTableNode(
            kind=MDEF, node=var, plugin_generated=True
        )

    def _collect_field_args(self, expr: Expression) -> tuple[bool, dict[str, Expression]]:
        """Returns a tuple where the first value represents whether or not
        the expression is a call to dataclass.field and the second is a
        dictionary of the keyword arguments that field() was called with.
        """
        if (
            isinstance(expr, CallExpr)
            and isinstance(expr.callee, RefExpr)
            and expr.callee.fullname in self._spec.field_specifiers
        ):
            # field() only takes keyword arguments.
            args = {}
            for name, arg, kind in zip(expr.arg_names, expr.args, expr.arg_kinds):
                if not kind.is_named():
                    if kind.is_named(star=True):
                        # This means that `field` is used with `**` unpacking,
                        # the best we can do for now is not to fail.
                        # TODO: we can infer what's inside `**` and try to collect it.
                        message = 'Unpacking **kwargs in "field()" is not supported'
                    elif self._spec is not _TRANSFORM_SPEC_FOR_DATACLASSES:
                        # dataclasses.field can only be used with keyword args, but this
                        # restriction is only enforced for the *standardized* arguments to
                        # dataclass_transform field specifiers. If this is not a
                        # dataclasses.dataclass class, we can just skip positional args safely.
                        continue
                    else:
                        message = '"field()" does not accept positional arguments'
                    self._api.fail(message, expr)
                    return True, {}
                assert name is not None
                args[name] = arg
            return True, args
        return False, {}

    def _get_bool_arg(self, name: str, default: bool) -> bool:
        # Expressions are always CallExprs (either directly or via a wrapper like Decorator), so
        # we can use the helpers from common
        if isinstance(self._reason, Expression):
            return _get_decorator_bool_argument(
                ClassDefContext(self._cls, self._reason, self._api), name, default
            )

        # Subclass/metaclass use of `typing.dataclass_transform` reads the parameters from the
        # class's keyword arguments (ie `class Subclass(Parent, kwarg1=..., kwarg2=...)`)
        expression = self._cls.keywords.get(name)
        if expression is not None:
            return require_bool_literal_argument(self._api, expression, name, default)
        return default

    def _get_default_init_value_for_field_specifier(self, call: Expression) -> bool:
        """
        Find a default value for the `init` parameter of the specifier being called. If the
        specifier's type signature includes an `init` parameter with a type of `Literal[True]` or
        `Literal[False]`, return the appropriate boolean value from the literal. Otherwise,
        fall back to the standard default of `True`.
        """
        if not isinstance(call, CallExpr):
            return True

        specifier_type = _get_callee_type(call)
        if specifier_type is None:
            return True

        parameter = specifier_type.argument_by_name("init")
        if parameter is None:
            return True

        literals = try_getting_literals_from_type(parameter.typ, bool, "builtins.bool")
        if literals is None or len(literals) != 1:
            return True

        return literals[0]

    def _infer_dataclass_attr_init_type(
        self, sym: SymbolTableNode, name: str, context: Context
    ) -> Type | None:
        """Infer __init__ argument type for an attribute.

        In particular, possibly use the signature of __set__.
        """
        default = sym.type
        if sym.implicit:
            return default
        t = get_proper_type(sym.type)

        # Perform a simple-minded inference from the signature of __set__, if present.
        # We can't use mypy.checkmember here, since this plugin runs before type checking.
        # We only support some basic scanerios here, which is hopefully sufficient for
        # the vast majority of use cases.
        if not isinstance(t, Instance):
            return default
        setter = t.type.get("__set__")
        if setter:
            if isinstance(setter.node, FuncDef):
                super_info = t.type.get_containing_type_info("__set__")
                assert super_info
                if setter.type:
                    setter_type = get_proper_type(
                        map_type_from_supertype(setter.type, t.type, super_info)
                    )
                else:
                    return AnyType(TypeOfAny.unannotated)
                if isinstance(setter_type, CallableType) and setter_type.arg_kinds == [
                    ARG_POS,
                    ARG_POS,
                    ARG_POS,
                ]:
                    return expand_type_by_instance(setter_type.arg_types[2], t)
                else:
                    self._api.fail(
                        f'Unsupported signature for "__set__" in "{t.type.name}"', context
                    )
            else:
                self._api.fail(f'Unsupported "__set__" in "{t.type.name}"', context)

        return default

def add_dataclass_tag(info: TypeInfo) -> None:
    # The value is ignored, only the existence matters.
    info.metadata["dataclass_tag"] = {}

def dataclass_tag_callback(ctx: ClassDefContext) -> None:
    """Record that we have a dataclass in the main semantic analysis pass.

    The later pass implemented by DataclassTransformer will use this
    to detect dataclasses in base classes.
    """
    add_dataclass_tag(ctx.cls.info)

def dataclass_class_maker_callback(ctx: ClassDefContext) -> bool:
    """Hooks into the class typechecking process to add support for dataclasses."""
    transformer = DataclassTransformer(
        ctx.cls, ctx.reason, _get_transform_spec(ctx.reason), ctx.api
    )
    return transformer.transform()

def _get_transform_spec(reason: Expression) -> DataclassTransformSpec:
    """Find the relevant transform parameters from the decorator/parent class/metaclass that
    triggered the dataclasses plugin.

    Although the resulting DataclassTransformSpec is based on the typing.dataclass_transform
    function, we also use it for traditional dataclasses.dataclass classes as well for simplicity.
    In those cases, we return a default spec rather than one based on a call to
    `typing.dataclass_transform`.
    """
    if _is_dataclasses_decorator(reason):
        return _TRANSFORM_SPEC_FOR_DATACLASSES

    spec = find_dataclass_transform_spec(reason)
    assert spec is not None, (
        "trying to find dataclass transform spec, but reason is neither dataclasses.dataclass nor "
        "decorated with typing.dataclass_transform"
    )
    return spec

def _is_dataclasses_decorator(node: Node) -> bool:
    if isinstance(node, CallExpr):
        node = node.callee
    if isinstance(node, RefExpr):
        return node.fullname in dataclass_makers
    return False

def _has_direct_dataclass_transform_metaclass(info: TypeInfo) -> bool:
    return (
        info.declared_metaclass is not None
        and info.declared_metaclass.type.dataclass_transform_spec is not None
    )

def _get_expanded_dataclasses_fields(
    ctx: FunctionSigContext, typ: ProperType, display_typ: ProperType, parent_typ: ProperType
) -> list[CallableType] | None:
    """
    For a given type, determine what dataclasses it can be: for each class, return the field types.
    For generic classes, the field types are expanded.
    If the type contains Any or a non-dataclass, returns None; in the latter case, also reports an error.
    """
    if isinstance(typ, UnionType):
        ret: list[CallableType] | None = []
        for item in typ.relevant_items():
            item = get_proper_type(item)
            item_types = _get_expanded_dataclasses_fields(ctx, item, item, parent_typ)
            if ret is not None and item_types is not None:
                ret += item_types
            else:
                ret = None  # but keep iterating to emit all errors
        return ret
    elif isinstance(typ, TypeVarType):
        return _get_expanded_dataclasses_fields(
            ctx, get_proper_type(typ.upper_bound), display_typ, parent_typ
        )
    elif isinstance(typ, Instance):
        replace_sym = typ.type.get_method(_INTERNAL_REPLACE_SYM_NAME)
        if replace_sym is None:
            return None
        replace_sig = replace_sym.type
        assert isinstance(replace_sig, ProperType)
        assert isinstance(replace_sig, CallableType)
        return [expand_type_by_instance(replace_sig, typ)]
    else:
        return None

# TODO: we can potentially get the function signature hook to allow returning a union
#  and leave this to the regular machinery of resolving a union of callables
#  (https://github.com/python/mypy/issues/15457)
def _meet_replace_sigs(sigs: list[CallableType]) -> CallableType:
    """
    Produces the lowest bound of the 'replace' signatures of multiple dataclasses.
    """
    args = {
        name: (typ, kind)
        for name, typ, kind in zip(sigs[0].arg_names, sigs[0].arg_types, sigs[0].arg_kinds)
    }

    for sig in sigs[1:]:
        sig_args = {
            name: (typ, kind)
            for name, typ, kind in zip(sig.arg_names, sig.arg_types, sig.arg_kinds)
        }
        for name in (*args.keys(), *sig_args.keys()):
            sig_typ, sig_kind = args.get(name, (UninhabitedType(), ARG_NAMED_OPT))
            sig2_typ, sig2_kind = sig_args.get(name, (UninhabitedType(), ARG_NAMED_OPT))
            args[name] = (
                meet_types(sig_typ, sig2_typ),
                ARG_NAMED_OPT if sig_kind == sig2_kind == ARG_NAMED_OPT else ARG_NAMED,
            )

    return sigs[0].copy_modified(
        arg_names=list(args.keys()),
        arg_types=[typ for typ, _ in args.values()],
        arg_kinds=[kind for _, kind in args.values()],
    )

def replace_function_sig_callback(ctx: FunctionSigContext) -> CallableType:
    """
    Returns a signature for the 'dataclasses.replace' function that's dependent on the type
    of the first positional argument.
    """
    if len(ctx.args) != 2:
        # Ideally the name and context should be callee's, but we don't have it in FunctionSigContext.
        ctx.api.fail(f'"{ctx.default_signature.name}" has unexpected type annotation', ctx.context)
        return ctx.default_signature

    if len(ctx.args[0]) != 1:
        return ctx.default_signature  # leave it to the type checker to complain

    obj_arg = ctx.args[0][0]
    obj_type = get_proper_type(ctx.api.get_expression_type(obj_arg))
    inst_type_str = format_type_bare(obj_type, ctx.api.options)

    replace_sigs = _get_expanded_dataclasses_fields(ctx, obj_type, obj_type, obj_type)
    if replace_sigs is None:
        return ctx.default_signature
    replace_sig = _meet_replace_sigs(replace_sigs)

    return replace_sig.copy_modified(
        arg_names=[None, *replace_sig.arg_names],
        arg_kinds=[ARG_POS, *replace_sig.arg_kinds],
        arg_types=[obj_type, *replace_sig.arg_types],
        ret_type=obj_type,
        fallback=ctx.default_signature.fallback,
        name=f"{ctx.default_signature.name} of {inst_type_str}",
    )

def is_processed_dataclass(info: TypeInfo) -> bool:
    return bool(info) and "dataclass" in info.metadata

def check_post_init(api: TypeChecker, defn: FuncItem, info: TypeInfo) -> None:
    if defn.type is None:
        return
    assert isinstance(defn.type, FunctionLike)

    ideal_sig_method = info.get_method(_INTERNAL_POST_INIT_SYM_NAME)
    assert ideal_sig_method is not None and ideal_sig_method.type is not None
    ideal_sig = ideal_sig_method.type
    assert isinstance(ideal_sig, ProperType)  # we set it ourselves
    assert isinstance(ideal_sig, CallableType)
    ideal_sig = ideal_sig.copy_modified(name="__post_init__")

    api.check_override(
        override=defn.type,
        original=ideal_sig,
        name="__post_init__",
        name_in_super="__post_init__",
        supertype="dataclass",
        original_class_or_static=False,
        override_class_or_static=False,
        node=defn,
    )


from __future__ import annotations

from functools import partial
from typing import Callable, Final

import mypy.errorcodes as codes
from mypy import message_registry
from mypy.nodes import DictExpr, IntExpr, StrExpr, UnaryExpr
from mypy.plugin import (
    AttributeContext,
    ClassDefContext,
    FunctionContext,
    FunctionSigContext,
    MethodContext,
    MethodSigContext,
    Plugin,
)
from mypy.plugins.common import try_getting_str_literals
from mypy.subtypes import is_subtype
from mypy.typeops import is_literal_type_like, make_simplified_union
from mypy.types import (
    TPDICT_FB_NAMES,
    AnyType,
    CallableType,
    FunctionLike,
    Instance,
    LiteralType,
    NoneType,
    TupleType,
    Type,
    TypedDictType,
    TypeOfAny,
    TypeVarType,
    UnionType,
    get_proper_type,
    get_proper_types,
)

class DefaultPlugin(Plugin):
    """Type checker plugin that is enabled by default."""

    def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None:
        from mypy.plugins import ctypes, enums, singledispatch

        if fullname == "_ctypes.Array":
            return ctypes.array_constructor_callback
        elif fullname == "functools.singledispatch":
            return singledispatch.create_singledispatch_function_callback
        elif fullname == "functools.partial":
            import mypy.plugins.functools

            return mypy.plugins.functools.partial_new_callback
        elif fullname == "enum.member":
            return enums.enum_member_callback

        return None

    def get_function_signature_hook(
        self, fullname: str
    ) -> Callable[[FunctionSigContext], FunctionLike] | None:
        from mypy.plugins import attrs, dataclasses

        if fullname in ("attr.evolve", "attrs.evolve", "attr.assoc", "attrs.assoc"):
            return attrs.evolve_function_sig_callback
        elif fullname in ("attr.fields", "attrs.fields"):
            return attrs.fields_function_sig_callback
        elif fullname == "dataclasses.replace":
            return dataclasses.replace_function_sig_callback
        return None

    def get_method_signature_hook(
        self, fullname: str
    ) -> Callable[[MethodSigContext], FunctionLike] | None:
        from mypy.plugins import ctypes, singledispatch

        if fullname == "typing.Mapping.get":
            return typed_dict_get_signature_callback
        elif fullname in {n + ".setdefault" for n in TPDICT_FB_NAMES}:
            return typed_dict_setdefault_signature_callback
        elif fullname in {n + ".pop" for n in TPDICT_FB_NAMES}:
            return typed_dict_pop_signature_callback
        elif fullname == "_ctypes.Array.__setitem__":
            return ctypes.array_setitem_callback
        elif fullname == singledispatch.SINGLEDISPATCH_CALLABLE_CALL_METHOD:
            return singledispatch.call_singledispatch_function_callback

        typed_dict_updates = set()
        for n in TPDICT_FB_NAMES:
            typed_dict_updates.add(n + ".update")
            typed_dict_updates.add(n + ".__or__")
            typed_dict_updates.add(n + ".__ror__")
            typed_dict_updates.add(n + ".__ior__")

        if fullname in typed_dict_updates:
            return typed_dict_update_signature_callback

        return None

    def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None:
        from mypy.plugins import ctypes, singledispatch

        if fullname == "typing.Mapping.get":
            return typed_dict_get_callback
        elif fullname == "builtins.int.__pow__":
            return int_pow_callback
        elif fullname == "builtins.int.__neg__":
            return int_neg_callback
        elif fullname == "builtins.int.__pos__":
            return int_pos_callback
        elif fullname in ("builtins.tuple.__mul__", "builtins.tuple.__rmul__"):
            return tuple_mul_callback
        elif fullname in {n + ".setdefault" for n in TPDICT_FB_NAMES}:
            return typed_dict_setdefault_callback
        elif fullname in {n + ".pop" for n in TPDICT_FB_NAMES}:
            return typed_dict_pop_callback
        elif fullname in {n + ".__delitem__" for n in TPDICT_FB_NAMES}:
            return typed_dict_delitem_callback
        elif fullname == "_ctypes.Array.__getitem__":
            return ctypes.array_getitem_callback
        elif fullname == "_ctypes.Array.__iter__":
            return ctypes.array_iter_callback
        elif fullname == singledispatch.SINGLEDISPATCH_REGISTER_METHOD:
            return singledispatch.singledispatch_register_callback
        elif fullname == singledispatch.REGISTER_CALLABLE_CALL_METHOD:
            return singledispatch.call_singledispatch_function_after_register_argument
        elif fullname == "functools.partial.__call__":
            import mypy.plugins.functools

            return mypy.plugins.functools.partial_call_callback
        return None

    def get_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None:
        from mypy.plugins import ctypes, enums

        if fullname == "_ctypes.Array.value":
            return ctypes.array_value_callback
        elif fullname == "_ctypes.Array.raw":
            return ctypes.array_raw_callback
        elif fullname in enums.ENUM_NAME_ACCESS:
            return enums.enum_name_callback
        elif fullname in enums.ENUM_VALUE_ACCESS:
            return enums.enum_value_callback
        return None

    def get_class_decorator_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:
        from mypy.plugins import attrs, dataclasses

        # These dataclass and attrs hooks run in the main semantic analysis pass
        # and only tag known dataclasses/attrs classes, so that the second
        # hooks (in get_class_decorator_hook_2) can detect dataclasses/attrs classes
        # in the MRO.
        if fullname in dataclasses.dataclass_makers:
            return dataclasses.dataclass_tag_callback
        if (
            fullname in attrs.attr_class_makers
            or fullname in attrs.attr_dataclass_makers
            or fullname in attrs.attr_frozen_makers
            or fullname in attrs.attr_define_makers
        ):
            return attrs.attr_tag_callback

        return None

    def get_class_decorator_hook_2(
        self, fullname: str
    ) -> Callable[[ClassDefContext], bool] | None:
        import mypy.plugins.functools
        from mypy.plugins import attrs, dataclasses

        if fullname in dataclasses.dataclass_makers:
            return dataclasses.dataclass_class_maker_callback
        elif fullname in mypy.plugins.functools.functools_total_ordering_makers:
            return mypy.plugins.functools.functools_total_ordering_maker_callback
        elif fullname in attrs.attr_class_makers:
            return attrs.attr_class_maker_callback
        elif fullname in attrs.attr_dataclass_makers:
            return partial(attrs.attr_class_maker_callback, auto_attribs_default=True)
        elif fullname in attrs.attr_frozen_makers:
            return partial(
                attrs.attr_class_maker_callback, auto_attribs_default=None, frozen_default=True
            )
        elif fullname in attrs.attr_define_makers:
            return partial(
                attrs.attr_class_maker_callback, auto_attribs_default=None, slots_default=True
            )

        return None

def typed_dict_get_signature_callback(ctx: MethodSigContext) -> CallableType:
    """Try to infer a better signature type for TypedDict.get.

    This is used to get better type context for the second argument that
    depends on a TypedDict value type.
    """
    signature = ctx.default_signature
    if (
        isinstance(ctx.type, TypedDictType)
        and len(ctx.args) == 2
        and len(ctx.args[0]) == 1
        and isinstance(ctx.args[0][0], StrExpr)
        and len(signature.arg_types) == 2
        and len(signature.variables) == 1
        and len(ctx.args[1]) == 1
    ):
        key = ctx.args[0][0].value
        value_type = get_proper_type(ctx.type.items.get(key))
        ret_type = signature.ret_type
        if value_type:
            default_arg = ctx.args[1][0]
            if (
                isinstance(value_type, TypedDictType)
                and isinstance(default_arg, DictExpr)
                and len(default_arg.items) == 0
            ):
                # Caller has empty dict {} as default for typed dict.
                value_type = value_type.copy_modified(required_keys=set())
            # Tweak the signature to include the value type as context. It's
            # only needed for type inference since there's a union with a type
            # variable that accepts everything.
            tv = signature.variables[0]
            assert isinstance(tv, TypeVarType)
            return signature.copy_modified(
                arg_types=[signature.arg_types[0], make_simplified_union([value_type, tv])],
                ret_type=ret_type,
            )
    return signature

def typed_dict_get_callback(ctx: MethodContext) -> Type:
    """Infer a precise return type for TypedDict.get with literal first argument."""
    if (
        isinstance(ctx.type, TypedDictType)
        and len(ctx.arg_types) >= 1
        and len(ctx.arg_types[0]) == 1
    ):
        keys = try_getting_str_literals(ctx.args[0][0], ctx.arg_types[0][0])
        if keys is None:
            return ctx.default_return_type

        output_types: list[Type] = []
        for key in keys:
            value_type = get_proper_type(ctx.type.items.get(key))
            if value_type is None:
                return ctx.default_return_type

            if len(ctx.arg_types) == 1:
                output_types.append(value_type)
            elif len(ctx.arg_types) == 2 and len(ctx.arg_types[1]) == 1 and len(ctx.args[1]) == 1:
                default_arg = ctx.args[1][0]
                if (
                    isinstance(default_arg, DictExpr)
                    and len(default_arg.items) == 0
                    and isinstance(value_type, TypedDictType)
                ):
                    # Special case '{}' as the default for a typed dict type.
                    output_types.append(value_type.copy_modified(required_keys=set()))
                else:
                    output_types.append(value_type)
                    output_types.append(ctx.arg_types[1][0])

        if len(ctx.arg_types) == 1:
            output_types.append(NoneType())

        return make_simplified_union(output_types)
    return ctx.default_return_type

def typed_dict_pop_signature_callback(ctx: MethodSigContext) -> CallableType:
    """Try to infer a better signature type for TypedDict.pop.

    This is used to get better type context for the second argument that
    depends on a TypedDict value type.
    """
    signature = ctx.default_signature
    str_type = ctx.api.named_generic_type("builtins.str", [])
    if (
        isinstance(ctx.type, TypedDictType)
        and len(ctx.args) == 2
        and len(ctx.args[0]) == 1
        and isinstance(ctx.args[0][0], StrExpr)
        and len(signature.arg_types) == 2
        and len(signature.variables) == 1
        and len(ctx.args[1]) == 1
    ):
        key = ctx.args[0][0].value
        value_type = ctx.type.items.get(key)
        if value_type:
            # Tweak the signature to include the value type as context. It's
            # only needed for type inference since there's a union with a type
            # variable that accepts everything.
            tv = signature.variables[0]
            assert isinstance(tv, TypeVarType)
            typ = make_simplified_union([value_type, tv])
            return signature.copy_modified(arg_types=[str_type, typ], ret_type=typ)
    return signature.copy_modified(arg_types=[str_type, signature.arg_types[1]])

def typed_dict_pop_callback(ctx: MethodContext) -> Type:
    """Type check and infer a precise return type for TypedDict.pop."""
    if (
        isinstance(ctx.type, TypedDictType)
        and len(ctx.arg_types) >= 1
        and len(ctx.arg_types[0]) == 1
    ):
        keys = try_getting_str_literals(ctx.args[0][0], ctx.arg_types[0][0])
        if keys is None:
            ctx.api.fail(
                message_registry.TYPEDDICT_KEY_MUST_BE_STRING_LITERAL,
                ctx.context,
                code=codes.LITERAL_REQ,
            )
            return AnyType(TypeOfAny.from_error)

        value_types = []
        for key in keys:
            if key in ctx.type.required_keys:
                ctx.api.msg.typeddict_key_cannot_be_deleted(ctx.type, key, ctx.context)

            value_type = ctx.type.items.get(key)
            if value_type:
                value_types.append(value_type)
            else:
                ctx.api.msg.typeddict_key_not_found(ctx.type, key, ctx.context)
                return AnyType(TypeOfAny.from_error)

        if len(ctx.args[1]) == 0:
            return make_simplified_union(value_types)
        elif len(ctx.arg_types) == 2 and len(ctx.arg_types[1]) == 1 and len(ctx.args[1]) == 1:
            return make_simplified_union([*value_types, ctx.arg_types[1][0]])
    return ctx.default_return_type

def typed_dict_setdefault_signature_callback(ctx: MethodSigContext) -> CallableType:
    """Try to infer a better signature type for TypedDict.setdefault.

    This is used to get better type context for the second argument that
    depends on a TypedDict value type.
    """
    signature = ctx.default_signature
    str_type = ctx.api.named_generic_type("builtins.str", [])
    if (
        isinstance(ctx.type, TypedDictType)
        and len(ctx.args) == 2
        and len(ctx.args[0]) == 1
        and isinstance(ctx.args[0][0], StrExpr)
        and len(signature.arg_types) == 2
        and len(ctx.args[1]) == 1
    ):
        key = ctx.args[0][0].value
        value_type = ctx.type.items.get(key)
        if value_type:
            return signature.copy_modified(arg_types=[str_type, value_type])
    return signature.copy_modified(arg_types=[str_type, signature.arg_types[1]])

def typed_dict_setdefault_callback(ctx: MethodContext) -> Type:
    """Type check TypedDict.setdefault and infer a precise return type."""
    if (
        isinstance(ctx.type, TypedDictType)
        and len(ctx.arg_types) == 2
        and len(ctx.arg_types[0]) == 1
        and len(ctx.arg_types[1]) == 1
    ):
        keys = try_getting_str_literals(ctx.args[0][0], ctx.arg_types[0][0])
        if keys is None:
            ctx.api.fail(
                message_registry.TYPEDDICT_KEY_MUST_BE_STRING_LITERAL,
                ctx.context,
                code=codes.LITERAL_REQ,
            )
            return AnyType(TypeOfAny.from_error)

        assigned_readonly_keys = ctx.type.readonly_keys & set(keys)
        if assigned_readonly_keys:
            ctx.api.msg.readonly_keys_mutated(assigned_readonly_keys, context=ctx.context)

        default_type = ctx.arg_types[1][0]

        value_types = []
        for key in keys:
            value_type = ctx.type.items.get(key)

            if value_type is None:
                ctx.api.msg.typeddict_key_not_found(ctx.type, key, ctx.context)
                return AnyType(TypeOfAny.from_error)

            # The signature_callback above can't always infer the right signature
            # (e.g. when the expression is a variable that happens to be a Literal str)
            # so we need to handle the check ourselves here and make sure the provided
            # default can be assigned to all key-value pairs we're updating.
            if not is_subtype(default_type, value_type):
                ctx.api.msg.typeddict_setdefault_arguments_inconsistent(
                    default_type, value_type, ctx.context
                )
                return AnyType(TypeOfAny.from_error)

            value_types.append(value_type)

        return make_simplified_union(value_types)
    return ctx.default_return_type

def typed_dict_delitem_callback(ctx: MethodContext) -> Type:
    """Type check TypedDict.__delitem__."""
    if (
        isinstance(ctx.type, TypedDictType)
        and len(ctx.arg_types) == 1
        and len(ctx.arg_types[0]) == 1
    ):
        keys = try_getting_str_literals(ctx.args[0][0], ctx.arg_types[0][0])
        if keys is None:
            ctx.api.fail(
                message_registry.TYPEDDICT_KEY_MUST_BE_STRING_LITERAL,
                ctx.context,
                code=codes.LITERAL_REQ,
            )
            return AnyType(TypeOfAny.from_error)

        for key in keys:
            if key in ctx.type.required_keys or key in ctx.type.readonly_keys:
                ctx.api.msg.typeddict_key_cannot_be_deleted(ctx.type, key, ctx.context)
            elif key not in ctx.type.items:
                ctx.api.msg.typeddict_key_not_found(ctx.type, key, ctx.context)
    return ctx.default_return_type

_TP_DICT_MUTATING_METHODS: Final = frozenset({"update of TypedDict", "__ior__ of TypedDict"})

def typed_dict_update_signature_callback(ctx: MethodSigContext) -> CallableType:
    """Try to infer a better signature type for methods that update `TypedDict`.

    This includes: `TypedDict.update`, `TypedDict.__or__`, `TypedDict.__ror__`,
    and `TypedDict.__ior__`.
    """
    signature = ctx.default_signature
    if isinstance(ctx.type, TypedDictType) and len(signature.arg_types) == 1:
        arg_type = get_proper_type(signature.arg_types[0])
        if not isinstance(arg_type, TypedDictType):
            return signature
        arg_type = arg_type.as_anonymous()
        arg_type = arg_type.copy_modified(required_keys=set())
        if ctx.args and ctx.args[0]:
            if signature.name in _TP_DICT_MUTATING_METHODS:
                # If we want to mutate this object in place, we need to set this flag,
                # it will trigger an extra check in TypedDict's checker.
                arg_type.to_be_mutated = True
            with ctx.api.msg.filter_errors(
                filter_errors=lambda name, info: info.code != codes.TYPEDDICT_READONLY_MUTATED,
                save_filtered_errors=True,
            ):
                inferred = get_proper_type(
                    ctx.api.get_expression_type(ctx.args[0][0], type_context=arg_type)
                )
            if arg_type.to_be_mutated:
                arg_type.to_be_mutated = False  # Done!
            possible_tds = []
            if isinstance(inferred, TypedDictType):
                possible_tds = [inferred]
            elif isinstance(inferred, UnionType):
                possible_tds = [
                    t
                    for t in get_proper_types(inferred.relevant_items())
                    if isinstance(t, TypedDictType)
                ]
            items = []
            for td in possible_tds:
                item = arg_type.copy_modified(
                    required_keys=(arg_type.required_keys | td.required_keys)
                    & arg_type.items.keys()
                )
                if not ctx.api.options.extra_checks:
                    item = item.copy_modified(item_names=list(td.items))
                items.append(item)
            if items:
                arg_type = make_simplified_union(items)
        return signature.copy_modified(arg_types=[arg_type])
    return signature

def int_pow_callback(ctx: MethodContext) -> Type:
    """Infer a more precise return type for int.__pow__."""
    # int.__pow__ has an optional modulo argument,
    # so we expect 2 argument positions
    if len(ctx.arg_types) == 2 and len(ctx.arg_types[0]) == 1 and len(ctx.arg_types[1]) == 0:
        arg = ctx.args[0][0]
        if isinstance(arg, IntExpr):
            exponent = arg.value
        elif isinstance(arg, UnaryExpr) and arg.op == "-" and isinstance(arg.expr, IntExpr):
            exponent = -arg.expr.value
        else:
            # Right operand not an int literal or a negated literal -- give up.
            return ctx.default_return_type
        if exponent >= 0:
            return ctx.api.named_generic_type("builtins.int", [])
        else:
            return ctx.api.named_generic_type("builtins.float", [])
    return ctx.default_return_type

def int_neg_callback(ctx: MethodContext, multiplier: int = -1) -> Type:
    """Infer a more precise return type for int.__neg__ and int.__pos__.

    This is mainly used to infer the return type as LiteralType
    if the original underlying object is a LiteralType object.
    """
    if isinstance(ctx.type, Instance) and ctx.type.last_known_value is not None:
        value = ctx.type.last_known_value.value
        fallback = ctx.type.last_known_value.fallback
        if isinstance(value, int):
            if is_literal_type_like(ctx.api.type_context[-1]):
                return LiteralType(value=multiplier * value, fallback=fallback)
            else:
                return ctx.type.copy_modified(
                    last_known_value=LiteralType(
                        value=multiplier * value,
                        fallback=fallback,
                        line=ctx.type.line,
                        column=ctx.type.column,
                    )
                )
    elif isinstance(ctx.type, LiteralType):
        value = ctx.type.value
        fallback = ctx.type.fallback
        if isinstance(value, int):
            return LiteralType(value=multiplier * value, fallback=fallback)
    return ctx.default_return_type

def int_pos_callback(ctx: MethodContext) -> Type:
    """Infer a more precise return type for int.__pos__.

    This is identical to __neg__, except the value is not inverted.
    """
    return int_neg_callback(ctx, +1)

def tuple_mul_callback(ctx: MethodContext) -> Type:
    """Infer a more precise return type for tuple.__mul__ and tuple.__rmul__.

    This is used to return a specific sized tuple if multiplied by Literal int
    """
    if not isinstance(ctx.type, TupleType):
        return ctx.default_return_type

    arg_type = get_proper_type(ctx.arg_types[0][0])
    if isinstance(arg_type, Instance) and arg_type.last_known_value is not None:
        value = arg_type.last_known_value.value
        if isinstance(value, int):
            return ctx.type.copy_modified(items=ctx.type.items * value)
    elif isinstance(ctx.type, LiteralType):
        value = arg_type.value
        if isinstance(value, int):
            return ctx.type.copy_modified(items=ctx.type.items * value)

    return ctx.default_return_type


"""
This file contains a variety of plugins for refining how mypy infers types of
expressions involving Enums.

Currently, this file focuses on providing better inference for expressions like
'SomeEnum.FOO.name' and 'SomeEnum.FOO.value'. Note that the type of both expressions
will vary depending on exactly which instance of SomeEnum we're looking at.

Note that this file does *not* contain all special-cased logic related to enums:
we actually bake some of it directly in to the semantic analysis layer (see
semanal_enum.py).
"""

from __future__ import annotations

from typing import Final, Iterable, Sequence, TypeVar, cast

import mypy.plugin  # To avoid circular imports.
from mypy.nodes import TypeInfo
from mypy.semanal_enum import ENUM_BASES
from mypy.subtypes import is_equivalent
from mypy.typeops import fixup_partial_type, make_simplified_union
from mypy.types import (
    CallableType,
    Instance,
    LiteralType,
    ProperType,
    Type,
    get_proper_type,
    is_named_instance,
)

ENUM_NAME_ACCESS: Final = {f"{prefix}.name" for prefix in ENUM_BASES} | {
    f"{prefix}._name_" for prefix in ENUM_BASES
}
ENUM_VALUE_ACCESS: Final = {f"{prefix}.value" for prefix in ENUM_BASES} | {
    f"{prefix}._value_" for prefix in ENUM_BASES
}

def enum_name_callback(ctx: mypy.plugin.AttributeContext) -> Type:
    """This plugin refines the 'name' attribute in enums to act as if
    they were declared to be final.

    For example, the expression 'MyEnum.FOO.name' normally is inferred
    to be of type 'str'.

    This plugin will instead make the inferred type be a 'str' where the
    last known value is 'Literal["FOO"]'. This means it would be legal to
    use 'MyEnum.FOO.name' in contexts that expect a Literal type, just like
    any other Final variable or attribute.

    This plugin assumes that the provided context is an attribute access
    matching one of the strings found in 'ENUM_NAME_ACCESS'.
    """
    enum_field_name = _extract_underlying_field_name(ctx.type)
    if enum_field_name is None:
        return ctx.default_attr_type
    else:
        str_type = ctx.api.named_generic_type("builtins.str", [])
        literal_type = LiteralType(enum_field_name, fallback=str_type)
        return str_type.copy_modified(last_known_value=literal_type)

_T = TypeVar("_T")

def _first(it: Iterable[_T]) -> _T | None:
    """Return the first value from any iterable.

    Returns ``None`` if the iterable is empty.
    """
    for val in it:
        return val
    return None

def _infer_value_type_with_auto_fallback(
    ctx: mypy.plugin.AttributeContext, proper_type: ProperType | None
) -> Type | None:
    """Figure out the type of an enum value accounting for `auto()`.

    This method is a no-op for a `None` proper_type and also in the case where
    the type is not "enum.auto"
    """
    if proper_type is None:
        return None
    proper_type = get_proper_type(fixup_partial_type(proper_type))
    if not (isinstance(proper_type, Instance) and proper_type.type.fullname == "enum.auto"):
        if is_named_instance(proper_type, "enum.member") and proper_type.args:
            return proper_type.args[0]
        return proper_type
    assert isinstance(ctx.type, Instance), "An incorrect ctx.type was passed."
    info = ctx.type.type
    # Find the first _generate_next_value_ on the mro.  We need to know
    # if it is `Enum` because `Enum` types say that the return-value of
    # `_generate_next_value_` is `Any`.  In reality the default `auto()`
    # returns an `int` (presumably the `Any` in typeshed is to make it
    # easier to subclass and change the returned type).
    type_with_gnv = _first(ti for ti in info.mro if ti.names.get("_generate_next_value_"))
    if type_with_gnv is None:
        return ctx.default_attr_type

    stnode = type_with_gnv.names["_generate_next_value_"]

    # This should be a `CallableType`
    node_type = get_proper_type(stnode.type)
    if isinstance(node_type, CallableType):
        if type_with_gnv.fullname == "enum.Enum":
            int_type = ctx.api.named_generic_type("builtins.int", [])
            return int_type
        return get_proper_type(node_type.ret_type)
    return ctx.default_attr_type

def _implements_new(info: TypeInfo) -> bool:
    """Check whether __new__ comes from enum.Enum or was implemented in a
    subclass. In the latter case, we must infer Any as long as mypy can't infer
    the type of _value_ from assignments in __new__.
    """
    type_with_new = _first(
        ti
        for ti in info.mro
        if ti.names.get("__new__") and not ti.fullname.startswith("builtins.")
    )
    if type_with_new is None:
        return False
    return type_with_new.fullname not in ("enum.Enum", "enum.IntEnum", "enum.StrEnum")

def enum_member_callback(ctx: mypy.plugin.FunctionContext) -> Type:
    """By default `member(1)` will be infered as `member[int]`,
    we want to improve the inference to be `Literal[1]` here."""
    if ctx.arg_types or ctx.arg_types[0]:
        arg = get_proper_type(ctx.arg_types[0][0])
        proper_return = get_proper_type(ctx.default_return_type)
        if (
            isinstance(arg, Instance)
            and arg.last_known_value
            and isinstance(proper_return, Instance)
            and len(proper_return.args) == 1
        ):
            return proper_return.copy_modified(args=[arg])
    return ctx.default_return_type

def enum_value_callback(ctx: mypy.plugin.AttributeContext) -> Type:
    """This plugin refines the 'value' attribute in enums to refer to
    the original underlying value. For example, suppose we have the
    following:

        class SomeEnum:
            FOO = A()
            BAR = B()

    By default, mypy will infer that 'SomeEnum.FOO.value' and
    'SomeEnum.BAR.value' both are of type 'Any'. This plugin refines
    this inference so that mypy understands the expressions are
    actually of types 'A' and 'B' respectively. This better reflects
    the actual runtime behavior.

    This plugin works simply by looking up the original value assigned
    to the enum. For example, when this plugin sees 'SomeEnum.BAR.value',
    it will look up whatever type 'BAR' had in the SomeEnum TypeInfo and
    use that as the inferred type of the overall expression.

    This plugin assumes that the provided context is an attribute access
    matching one of the strings found in 'ENUM_VALUE_ACCESS'.
    """
    enum_field_name = _extract_underlying_field_name(ctx.type)
    if enum_field_name is None:
        # We do not know the enum field name (perhaps it was passed to a
        # function and we only know that it _is_ a member).  All is not lost
        # however, if we can prove that the all of the enum members have the
        # same value-type, then it doesn't matter which member was passed in.
        # The value-type is still known.
        if isinstance(ctx.type, Instance):
            info = ctx.type.type

            # As long as mypy doesn't understand attribute creation in __new__,
            # there is no way to predict the value type if the enum class has a
            # custom implementation
            if _implements_new(info):
                return ctx.default_attr_type

            stnodes = (info.get(name) for name in info.names)

            # Enums _can_ have methods, instance attributes, and `nonmember`s.
            # Omit methods and attributes created by assigning to self.*
            # for our value inference.
            node_types = (
                get_proper_type(n.type) if n else None
                for n in stnodes
                if n is None or not n.implicit
            )
            proper_types = [
                _infer_value_type_with_auto_fallback(ctx, t)
                for t in node_types
                if t is None
                or (not isinstance(t, CallableType) and not is_named_instance(t, "enum.nonmember"))
            ]
            underlying_type = _first(proper_types)
            if underlying_type is None:
                return ctx.default_attr_type

            # At first we try to predict future `value` type if all other items
            # have the same type. For example, `int`.
            # If this is the case, we simply return this type.
            # See https://github.com/python/mypy/pull/9443
            all_same_value_type = all(
                proper_type is not None and proper_type == underlying_type
                for proper_type in proper_types
            )
            if all_same_value_type:
                if underlying_type is not None:
                    return underlying_type

            # But, after we started treating all `Enum` values as `Final`,
            # we start to infer types in
            # `item = 1` as `Literal[1]`, not just `int`.
            # So, for example types in this `Enum` will all be different:
            #
            #  class Ordering(IntEnum):
            #      one = 1
            #      two = 2
            #      three = 3
            #
            # We will infer three `Literal` types here.
            # They are not the same, but they are equivalent.
            # So, we unify them to make sure `.value` prediction still works.
            # Result will be `Literal[1] | Literal[2] | Literal[3]` for this case.
            all_equivalent_types = all(
                proper_type is not None and is_equivalent(proper_type, underlying_type)
                for proper_type in proper_types
            )
            if all_equivalent_types:
                return make_simplified_union(cast(Sequence[Type], proper_types))
        return ctx.default_attr_type

    assert isinstance(ctx.type, Instance)
    info = ctx.type.type

    # As long as mypy doesn't understand attribute creation in __new__,
    # there is no way to predict the value type if the enum class has a
    # custom implementation
    if _implements_new(info):
        return ctx.default_attr_type

    stnode = info.get(enum_field_name)
    if stnode is None:
        return ctx.default_attr_type

    underlying_type = _infer_value_type_with_auto_fallback(ctx, get_proper_type(stnode.type))
    if underlying_type is None:
        return ctx.default_attr_type

    return underlying_type

def _extract_underlying_field_name(typ: Type) -> str | None:
    """If the given type corresponds to some Enum instance, returns the
    original name of that enum. For example, if we receive in the type
    corresponding to 'SomeEnum.FOO', we return the string "SomeEnum.Foo".

    This helper takes advantage of the fact that Enum instances are valid
    to use inside Literal[...] types. An expression like 'SomeEnum.FOO' is
    actually represented by an Instance type with a Literal enum fallback.

    We can examine this Literal fallback to retrieve the string.
    """
    typ = get_proper_type(typ)
    if not isinstance(typ, Instance):
        return None

    if not typ.type.is_enum:
        return None

    underlying_literal = typ.last_known_value
    if underlying_literal is None:
        return None

    # The checks above have verified this LiteralType is representing an enum value,
    # which means the 'value' field is guaranteed to be the name of the enum field
    # as a string.
    assert isinstance(underlying_literal.value, str)
    return underlying_literal.value


"""Plugin for supporting the functools standard library module."""

from __future__ import annotations

from typing import Final, NamedTuple

import mypy.checker
import mypy.plugin
import mypy.semanal
from mypy.argmap import map_actuals_to_formals
from mypy.nodes import ARG_POS, ARG_STAR2, ArgKind, Argument, CallExpr, FuncItem, Var
from mypy.plugins.common import add_method_to_class
from mypy.typeops import get_all_type_vars
from mypy.types import (
    AnyType,
    CallableType,
    Instance,
    Overloaded,
    Type,
    TypeOfAny,
    TypeVarType,
    UnboundType,
    UnionType,
    get_proper_type,
)

functools_total_ordering_makers: Final = {"functools.total_ordering"}

_ORDERING_METHODS: Final = {"__lt__", "__le__", "__gt__", "__ge__"}

PARTIAL: Final = "functools.partial"

class _MethodInfo(NamedTuple):
    is_static: bool
    type: CallableType

def functools_total_ordering_maker_callback(
    ctx: mypy.plugin.ClassDefContext, auto_attribs_default: bool = False
) -> bool:
    """Add dunder methods to classes decorated with functools.total_ordering."""
    comparison_methods = _analyze_class(ctx)
    if not comparison_methods:
        ctx.api.fail(
            'No ordering operation defined when using "functools.total_ordering": < > <= >=',
            ctx.reason,
        )
        return True

    # prefer __lt__ to __le__ to __gt__ to __ge__
    root = max(comparison_methods, key=lambda k: (comparison_methods[k] is None, k))
    root_method = comparison_methods[root]
    if not root_method:
        # None of the defined comparison methods can be analysed
        return True

    other_type = _find_other_type(root_method)
    bool_type = ctx.api.named_type("builtins.bool")
    ret_type: Type = bool_type
    if root_method.type.ret_type != ctx.api.named_type("builtins.bool"):
        proper_ret_type = get_proper_type(root_method.type.ret_type)
        if not (
            isinstance(proper_ret_type, UnboundType)
            and proper_ret_type.name.split(".")[-1] == "bool"
        ):
            ret_type = AnyType(TypeOfAny.implementation_artifact)
    for additional_op in _ORDERING_METHODS:
        # Either the method is not implemented
        # or has an unknown signature that we can now extrapolate.
        if not comparison_methods.get(additional_op):
            args = [Argument(Var("other", other_type), other_type, None, ARG_POS)]
            add_method_to_class(ctx.api, ctx.cls, additional_op, args, ret_type)

    return True

def _find_other_type(method: _MethodInfo) -> Type:
    """Find the type of the ``other`` argument in a comparison method."""
    first_arg_pos = 0 if method.is_static else 1
    cur_pos_arg = 0
    other_arg = None
    for arg_kind, arg_type in zip(method.type.arg_kinds, method.type.arg_types):
        if arg_kind.is_positional():
            if cur_pos_arg == first_arg_pos:
                other_arg = arg_type
                break

            cur_pos_arg += 1
        elif arg_kind != ARG_STAR2:
            other_arg = arg_type
            break

    if other_arg is None:
        return AnyType(TypeOfAny.implementation_artifact)

    return other_arg

def _analyze_class(ctx: mypy.plugin.ClassDefContext) -> dict[str, _MethodInfo | None]:
    """Analyze the class body, its parents, and return the comparison methods found."""
    # Traverse the MRO and collect ordering methods.
    comparison_methods: dict[str, _MethodInfo | None] = {}
    # Skip object because total_ordering does not use methods from object
    for cls in ctx.cls.info.mro[:-1]:
        for name in _ORDERING_METHODS:
            if name in cls.names and name not in comparison_methods:
                node = cls.names[name].node
                if isinstance(node, FuncItem) and isinstance(node.type, CallableType):
                    comparison_methods[name] = _MethodInfo(node.is_static, node.type)
                    continue

                if isinstance(node, Var):
                    proper_type = get_proper_type(node.type)
                    if isinstance(proper_type, CallableType):
                        comparison_methods[name] = _MethodInfo(node.is_staticmethod, proper_type)
                        continue

                comparison_methods[name] = None

    return comparison_methods

def partial_new_callback(ctx: mypy.plugin.FunctionContext) -> Type:
    """Infer a more precise return type for functools.partial"""
    if not isinstance(ctx.api, mypy.checker.TypeChecker):  # use internals
        return ctx.default_return_type
    if len(ctx.arg_types) != 3:  # fn, *args, **kwargs
        return ctx.default_return_type
    if len(ctx.arg_types[0]) != 1:
        return ctx.default_return_type

    if isinstance(get_proper_type(ctx.arg_types[0][0]), Overloaded):
        # TODO: handle overloads, just fall back to whatever the non-plugin code does
        return ctx.default_return_type
    return handle_partial_with_callee(ctx, callee=ctx.arg_types[0][0])

def handle_partial_with_callee(ctx: mypy.plugin.FunctionContext, callee: Type) -> Type:
    if not isinstance(ctx.api, mypy.checker.TypeChecker):  # use internals
        return ctx.default_return_type

    if isinstance(callee_proper := get_proper_type(callee), UnionType):
        return UnionType.make_union(
            [handle_partial_with_callee(ctx, item) for item in callee_proper.items]
        )

    fn_type = ctx.api.extract_callable_type(callee, ctx=ctx.default_return_type)
    if fn_type is None:
        return ctx.default_return_type

    # We must normalize from the start to have coherent view together with TypeChecker.
    fn_type = fn_type.with_unpacked_kwargs().with_normalized_var_args()

    last_context = ctx.api.type_context[-1]
    if not fn_type.is_type_obj():
        # We wrap the return type to get use of a possible type context provided by caller.
        # We cannot do this in case of class objects, since otherwise the plugin may get
        # falsely triggered when evaluating the constructed call itself.
        ret_type: Type = ctx.api.named_generic_type(PARTIAL, [fn_type.ret_type])
        wrapped_return = True
    else:
        ret_type = fn_type.ret_type
        # Instead, for class objects we ignore any type context to avoid spurious errors,
        # since the type context will be partial[X] etc., not X.
        ctx.api.type_context[-1] = None
        wrapped_return = False

    # Flatten actual to formal mapping, since this is what check_call() expects.
    actual_args = []
    actual_arg_kinds = []
    actual_arg_names = []
    actual_types = []
    seen_args = set()
    for i, param in enumerate(ctx.args[1:], start=1):
        for j, a in enumerate(param):
            if a in seen_args:
                # Same actual arg can map to multiple formals, but we need to include
                # each one only once.
                continue
            # Here we rely on the fact that expressions are essentially immutable, so
            # they can be compared by identity.
            seen_args.add(a)
            actual_args.append(a)
            actual_arg_kinds.append(ctx.arg_kinds[i][j])
            actual_arg_names.append(ctx.arg_names[i][j])
            actual_types.append(ctx.arg_types[i][j])

    formal_to_actual = map_actuals_to_formals(
        actual_kinds=actual_arg_kinds,
        actual_names=actual_arg_names,
        formal_kinds=fn_type.arg_kinds,
        formal_names=fn_type.arg_names,
        actual_arg_type=lambda i: actual_types[i],
    )

    # We need to remove any type variables that appear only in formals that have
    # no actuals, to avoid eagerly binding them in check_call() below.
    can_infer_ids = set()
    for i, arg_type in enumerate(fn_type.arg_types):
        if not formal_to_actual[i]:
            continue
        can_infer_ids.update({tv.id for tv in get_all_type_vars(arg_type)})

    defaulted = fn_type.copy_modified(
        arg_kinds=[
            (
                ArgKind.ARG_OPT
                if k == ArgKind.ARG_POS
                else (ArgKind.ARG_NAMED_OPT if k == ArgKind.ARG_NAMED else k)
            )
            for k in fn_type.arg_kinds
        ],
        ret_type=ret_type,
        variables=[
            tv
            for tv in fn_type.variables
            # Keep TypeVarTuple/ParamSpec to avoid spurious errors on empty args.
            if tv.id in can_infer_ids or not isinstance(tv, TypeVarType)
        ],
    )
    if defaulted.line < 0:
        # Make up a line number if we don't have one
        defaulted.set_line(ctx.default_return_type)

    # Create a valid context for various ad-hoc inspections in check_call().
    call_expr = CallExpr(
        callee=ctx.args[0][0],
        args=actual_args,
        arg_kinds=actual_arg_kinds,
        arg_names=actual_arg_names,
        analyzed=ctx.context.analyzed if isinstance(ctx.context, CallExpr) else None,
    )
    call_expr.set_line(ctx.context)

    _, bound = ctx.api.expr_checker.check_call(
        callee=defaulted,
        args=actual_args,
        arg_kinds=actual_arg_kinds,
        arg_names=actual_arg_names,
        context=call_expr,
    )
    if not wrapped_return:
        # Restore previously ignored context.
        ctx.api.type_context[-1] = last_context

    bound = get_proper_type(bound)
    if not isinstance(bound, CallableType):
        return ctx.default_return_type

    if wrapped_return:
        # Reverse the wrapping we did above.
        ret_type = get_proper_type(bound.ret_type)
        if not isinstance(ret_type, Instance) or ret_type.type.fullname != PARTIAL:
            return ctx.default_return_type
        bound = bound.copy_modified(ret_type=ret_type.args[0])

    partial_kinds = []
    partial_types = []
    partial_names = []
    # We need to fully apply any positional arguments (they cannot be respecified)
    # However, keyword arguments can be respecified, so just give them a default
    for i, actuals in enumerate(formal_to_actual):
        if len(bound.arg_types) == len(fn_type.arg_types):
            arg_type = bound.arg_types[i]
            if not mypy.checker.is_valid_inferred_type(arg_type):
                arg_type = fn_type.arg_types[i]  # bit of a hack
        else:
            # TODO: I assume that bound and fn_type have the same arguments. It appears this isn't
            # true when PEP 646 things are happening. See testFunctoolsPartialTypeVarTuple
            arg_type = fn_type.arg_types[i]

        if not actuals or fn_type.arg_kinds[i] in (ArgKind.ARG_STAR, ArgKind.ARG_STAR2):
            partial_kinds.append(fn_type.arg_kinds[i])
            partial_types.append(arg_type)
            partial_names.append(fn_type.arg_names[i])
        else:
            assert actuals
            if any(actual_arg_kinds[j] in (ArgKind.ARG_POS, ArgKind.ARG_STAR) for j in actuals):
                # Don't add params for arguments passed positionally
                continue
            # Add defaulted params for arguments passed via keyword
            kind = actual_arg_kinds[actuals[0]]
            if kind == ArgKind.ARG_NAMED or kind == ArgKind.ARG_STAR2:
                kind = ArgKind.ARG_NAMED_OPT
            partial_kinds.append(kind)
            partial_types.append(arg_type)
            partial_names.append(fn_type.arg_names[i])

    ret_type = bound.ret_type
    if not mypy.checker.is_valid_inferred_type(ret_type):
        ret_type = fn_type.ret_type  # same kind of hack as above

    partially_applied = fn_type.copy_modified(
        arg_types=partial_types,
        arg_kinds=partial_kinds,
        arg_names=partial_names,
        ret_type=ret_type,
    )

    ret = ctx.api.named_generic_type(PARTIAL, [ret_type])
    ret = ret.copy_with_extra_attr("__mypy_partial", partially_applied)
    return ret

def partial_call_callback(ctx: mypy.plugin.MethodContext) -> Type:
    """Infer a more precise return type for functools.partial.__call__."""
    if (
        not isinstance(ctx.api, mypy.checker.TypeChecker)  # use internals
        or not isinstance(ctx.type, Instance)
        or ctx.type.type.fullname != PARTIAL
        or not ctx.type.extra_attrs
        or "__mypy_partial" not in ctx.type.extra_attrs.attrs
    ):
        return ctx.default_return_type

    partial_type = ctx.type.extra_attrs.attrs["__mypy_partial"]
    if len(ctx.arg_types) != 2:  # *args, **kwargs
        return ctx.default_return_type

    # See comments for similar actual to formal code above
    actual_args = []
    actual_arg_kinds = []
    actual_arg_names = []
    seen_args = set()
    for i, param in enumerate(ctx.args):
        for j, a in enumerate(param):
            if a in seen_args:
                continue
            seen_args.add(a)
            actual_args.append(a)
            actual_arg_kinds.append(ctx.arg_kinds[i][j])
            actual_arg_names.append(ctx.arg_names[i][j])

    result = ctx.api.expr_checker.check_call(
        callee=partial_type,
        args=actual_args,
        arg_kinds=actual_arg_kinds,
        arg_names=actual_arg_names,
        context=ctx.context,
    )
    return result[0]