Skip implicit-return reachability checks for literal None annotations

This commit is contained in:
Charlie Marsh
2026-11-26 20:17:07 -05:00
parent 8f0189e0e9
commit 2228011385
2 changed files with 30 additions and 1 deletions
@@ -299,6 +299,24 @@ def f(cond: bool) -> int:
return 2
```
With a literal `None` annotation, ty permits an implicit return and still checks the body, explicit
returns, and generator annotations.
```py
def ordinary(flag: bool) -> None:
if flag:
return 1 # error: [invalid-explicit-return]
def implicit() -> None:
x: str = 1 # error: [invalid-assignment]
def generator() -> None: # error: [invalid-generator-return-type]
yield
async def async_generator() -> None: # error: [invalid-generator-return-type]
yield
```
## Invalid return type
<!-- snapshot-diagnostics -->
@@ -199,6 +199,16 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
self.infer_scope_body(&function.body);
if let Some(returns) = function.returns.as_deref() {
// An implicit return already satisfies a literal None annotation, regardless
// of whether control flow reaches the end of the function.
let accepts_implicit_return = returns.is_none_literal_expr();
if accepts_implicit_return
&& self.return_types_and_ranges.is_empty()
&& !scope.is_generator_function(self.index)
{
return;
}
let has_empty_body = self.return_types_and_ranges.is_empty()
&& function_body_kind(db, env, function, |expr| self.expression_type(expr))
== FunctionBodyKind::Stub;
@@ -374,7 +384,8 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
}
}
if is_end_of_scope_reachable(db, self.scope())
if !accepts_implicit_return
&& is_end_of_scope_reachable(db, self.scope())
&& !Type::none(db, env).is_assignable_to(db, env, *public)
{
let no_return = self.return_types_and_ranges.is_empty();