From 00e00b9ad6b3cac84fab44ab4337098b047eb877 Mon Sep 17 00:00:00 2001 From: David Peter Date: Wed, 9 Apr 2025 11:45:42 +0200 Subject: [PATCH] [red-knot] Add new 'unreachable code' test case (#17306) ## Summary This is a new test case that I don't know how to handle yet. It leads to many false positives in `rich/tests/test_win32_console.py`, which does something like: ```py if sys.platform == "win32": from windows_only_module import some_symbol some_other_symbol = 1 def some_test_case(): use(some_symbol) # Red Knot: unresolved-reference use(some_other_symbol) # Red Knot: unresolved-reference ``` Also adds a test for using unreachable symbols in type annotations or as class bases. --- .../resources/mdtest/unreachable.md | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/crates/red_knot_python_semantic/resources/mdtest/unreachable.md b/crates/red_knot_python_semantic/resources/mdtest/unreachable.md index fce99d51ce..3f56372d97 100644 --- a/crates/red_knot_python_semantic/resources/mdtest/unreachable.md +++ b/crates/red_knot_python_semantic/resources/mdtest/unreachable.md @@ -432,6 +432,44 @@ if sys.version_info >= (3, 11): import wsgiref.types ``` +### Nested scopes + +When we have nested scopes inside the unreachable section, we should not emit diagnostics either: + +```py +if False: + x = 1 + + def f(): + # TODO + # error: [unresolved-reference] + print(x) + + class C: + def __init__(self): + # TODO + # error: [unresolved-reference] + print(x) +``` + +### Use of unreachable symbols in type annotations, or as class bases + +We should not show any diagnostics in type annotations inside unreachable sections. + +```py +def _(): + class C: ... + return + + # TODO + # error: [invalid-type-form] "Variable of type `Never` is not allowed in a type expression" + c: C = C() + + # TODO + # error: [invalid-base] "Invalid class base with type `Never` (all bases must be a class, `Any`, `Unknown` or `Todo`)" + class Sub(C): ... +``` + ### Emit diagnostics for definitely wrong code Even though the expressions in the snippet below are unreachable, we still emit diagnostics for