Skip to content

Commit

Permalink
Avoid inferring invalid expr types for string annotation
Browse files Browse the repository at this point in the history
  • Loading branch information
dhruvmanila committed Nov 19, 2024
1 parent d8538d8 commit 8d9888f
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -189,3 +189,31 @@ reveal_type(d) # revealed: Foo
## Parameter

TODO: Add tests once parameter inference is supported

## Invalid expressions

The expressions in these string annotations aren't valid expressions in this
context but we shouldn't panic.

```py
a: "1 or 2"
b: "(x := 1)"
c: "1 + 2"
d: "lambda x: x"
e: "x if True else y"
f: "{'a': 1, 'b': 2}"
g: "{1, 2}"
h: "[i for i in range(5)]"
i: "{i for i in range(5)}"
j: "{i: i for i in range(5)}"
k: "(i for i in range(5))"
l: "await 1"
# error: [forward-annotation-syntax-error]
m: "yield 1"
# error: [forward-annotation-syntax-error]
n: "yield from 1"
o: "1 < 2"
p: "call()"
r: "[1, 2]"
s: "(1, 2)"
```
5 changes: 4 additions & 1 deletion crates/red_knot_python_semantic/src/types/infer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4302,6 +4302,10 @@ impl<'db> TypeInferenceBuilder<'db> {
Type::Todo
}

// Avoid inferring the types of invalid type expressions that have been parsed from a
// string annotation, as they are not present in the semantic index.
_ if self.deferred_state.in_string_annotation() => Type::Unknown,

// Forms which are invalid in the context of annotation expressions: we infer their
// nested expressions as normal expressions, but the type of the top-level expression is
// always `Type::Unknown` in these cases.
Expand Down Expand Up @@ -4385,7 +4389,6 @@ impl<'db> TypeInferenceBuilder<'db> {
self.infer_slice_expression(slice);
Type::Unknown
}

ast::Expr::IpyEscapeCommand(_) => todo!("Implement Ipy escape command support"),
}
}
Expand Down

0 comments on commit 8d9888f

Please sign in to comment.