Skip to content

[red-knot] Emit error if int/float/complex/bytes/boolean literals appear in type expressions outside typing.Literal[] #16765

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,10 @@ def _(c: Callable[42, str]):
Or, when one of the parameter type is invalid in the list:

```py
# error: [invalid-type-form] "Number Literal is not allowed in type expressions"
# error: [invalid-type-form] "Boolean Literal is not allowed in type expressions"
def _(c: Callable[[int, 42, str, False], None]):
# revealed: (int, @Todo(number literal in type expression), str, @Todo(boolean literal in type expression), /) -> None
# revealed: (int, Unknown, str, Unknown, /) -> None
reveal_type(c)
```

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,33 @@ def _(
reveal_type(q) # revealed: Unknown
reveal_type(r) # revealed: Unknown
```

## Number Literal

```py
# error: [invalid-type-form] "Number Literal is not allowed in type expressions"
def _(x: 1):
reveal_type(x) # revealed: Unknown
```

```py
# error: [invalid-type-form] "Number Literal is not allowed in type expressions"
def _(x: 1.1):
reveal_type(x) # revealed: Unknown
```

## Bytes Literal

```py
# error: [invalid-type-form] "Bytes Literal is not allowed in type expressions"
def _(x: int | b"a"):
reveal_type(x) # revealed: int | Unknown
```

## Boolean Literal

```py
# error: [invalid-type-form] "Boolean Literal is not allowed in type expressions"
def _(x: True):
reveal_type(x) # revealed: Unknown
```
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ Literal: _SpecialForm
```py
from other import Literal

# error: [invalid-type-form] "Number Literal is not allowed in type expressions"
a1: Literal[26]

def f():
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@ reveal_type(cast(int | str, 1)) # revealed: int | str
# error: [invalid-type-form]
reveal_type(cast(Literal, True)) # revealed: Unknown

# error: [invalid-type-form]
reveal_type(cast(1, True)) # revealed: Unknown

# TODO: These should be errors
cast(1)
cast(str)
cast(str, b"ar", "foo")

Expand Down
36 changes: 33 additions & 3 deletions crates/red_knot_python_semantic/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3170,12 +3170,9 @@ impl<'db> Type<'db> {
Ok(ty)
}
Type::SubclassOf(_)
| Type::BooleanLiteral(_)
| Type::BytesLiteral(_)
| Type::AlwaysTruthy
| Type::AlwaysFalsy
| Type::SliceLiteral(_)
| Type::IntLiteral(_)
| Type::LiteralString
| Type::ModuleLiteral(_)
| Type::StringLiteral(_)
Expand Down Expand Up @@ -3263,6 +3260,24 @@ impl<'db> Type<'db> {
],
fallback_type: Type::unknown(),
}),
Type::BooleanLiteral(_) => Err(InvalidTypeExpressionError {
invalid_expressions: smallvec::smallvec![
InvalidTypeExpression::BooleanLiteralInTypeExpression
],
fallback_type: Type::unknown(),
}),
Type::IntLiteral(_) => Err(InvalidTypeExpressionError {
invalid_expressions: smallvec::smallvec![
InvalidTypeExpression::NumberLiteralInTypeExpression
],
fallback_type: Type::unknown(),
}),
Type::BytesLiteral(_) => Err(InvalidTypeExpressionError {
invalid_expressions: smallvec::smallvec![
InvalidTypeExpression::BytesLiteralInTypeExpression
],
fallback_type: Type::unknown(),
}),
Type::KnownInstance(KnownInstanceType::Literal) => Err(InvalidTypeExpressionError {
invalid_expressions: smallvec::smallvec![InvalidTypeExpression::BareLiteral],
fallback_type: Type::unknown(),
Expand Down Expand Up @@ -3555,6 +3570,12 @@ enum InvalidTypeExpression<'db> {
ClassVarInTypeExpression,
/// The `Final` type qualifier was used in a type expression
FinalInTypeExpression,
/// Bytes Literal is not allowed in type expressions
BytesLiteralInTypeExpression,
/// Number Literal is not allowed in type expressions
NumberLiteralInTypeExpression,
/// Boolean Literal is not allowed in type expressions
BooleanLiteralInTypeExpression,
/// Some types are always invalid in type expressions
InvalidType(Type<'db>),
}
Expand All @@ -3581,6 +3602,15 @@ impl<'db> InvalidTypeExpression<'db> {
InvalidTypeExpression::FinalInTypeExpression => f.write_str(
"Type qualifier `typing.Final` is not allowed in type expressions (only in annotation expressions)"
),
InvalidTypeExpression::BytesLiteralInTypeExpression => f.write_str(
"Bytes Literal is not allowed in type expressions"
),
InvalidTypeExpression::NumberLiteralInTypeExpression => f.write_str(
"Number Literal is not allowed in type expressions"
),
InvalidTypeExpression::BooleanLiteralInTypeExpression => f.write_str(
"Boolean Literal is not allowed in type expressions"
),
InvalidTypeExpression::InvalidType(ty) => write!(
f,
"Variable of type `{ty}` is not allowed in a type expression",
Expand Down
27 changes: 24 additions & 3 deletions crates/red_knot_python_semantic/src/types/infer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6121,9 +6121,30 @@ impl<'db> TypeInferenceBuilder<'db> {
// Other literals do not have meaningful values in the annotation expression context.
// However, we will we want to handle these differently when working with special forms,
// since (e.g.) `123` is not valid in an annotation expression but `Literal[123]` is.
ast::Expr::BytesLiteral(_literal) => todo_type!("bytes literal in type expression"),
ast::Expr::NumberLiteral(_literal) => todo_type!("number literal in type expression"),
ast::Expr::BooleanLiteral(_literal) => todo_type!("boolean literal in type expression"),
ast::Expr::BytesLiteral(_literal) => {
self.context.report_lint(
&INVALID_TYPE_FORM,
expression,
format_args!("Bytes Literal is not allowed in type expressions"),
);
Type::unknown()
}
ast::Expr::NumberLiteral(_literal) => {
self.context.report_lint(
&INVALID_TYPE_FORM,
expression,
format_args!("Number Literal is not allowed in type expressions"),
);
Type::unknown()
}
ast::Expr::BooleanLiteral(_literal) => {
self.context.report_lint(
&INVALID_TYPE_FORM,
expression,
format_args!("Boolean Literal is not allowed in type expressions"),
);
Type::unknown()
}

ast::Expr::Subscript(subscript) => {
let ast::ExprSubscript {
Expand Down