Skip to content

[red-knot] Ban most Type::Instance types in type expressions #16851

@AlexWaygood

Description

@AlexWaygood

If a symbol that we infer as having an instance type appears in a type expression, we should almost always emit a diagnostic saying that it's an invalid type expression. For example:

def f(x: int):
    def g(y: x): ...  # the annotation for `y` here is invalid:
                      # `x` has a `Type::Instance` type.
                      # We need to emit a diagnostic for type expressions like this

Making this change involves changing this branch of Type::in_type_expression() so that it returns an Err() in most cases:

Type::Instance(_) => Ok(todo_type!(
"Invalid or unsupported `Instance` in `Type::to_type_expression`"
)),

But we need to make sure we avoid emitting an error if an instance of a TypeVar, TypeVarTuple or ParamSpec is used in a type expression, e.g.

from typing import TypeVar

T = TypeVar("T")

def f(x: T) -> T: ...  # annotation for `x` is valid here,
                       # despite the fact that we currently infer it as a `Type::Instance` type

To avoid these false positives, we should probably do something like this for the branch:

            Type::Instance(InstanceType { class }) => match class.known(db) {
                Some(KnownClass::TypeVar) => Ok(todo_type!("Support for `typing.TypeVar` instances in type expressions")),
                Some(KnownClass::ParamSpec) => Ok(todo_type!("Support for `typing.ParamSpec` instances in type expressions")),
                Some(KnownClass::TypeVarTuple) => Ok(todo_type!("Support for `typing.TypeVarTuple` instances in type expressions")),
                _ => Err(...)
            }

Note that we do not yet have ParamSpec and TypeVarTuple variants in our KnownClass enum, but they probably need to be added in order to complete this task.

Metadata

Metadata

Assignees

No one assigned

    Labels

    help wantedContributions especially welcometyMulti-file analysis & type inference

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions