ruff
7e315717 - [ty] Propagate narrowing through statically known branches (#27752)

Commit
95 days ago
[ty] Propagate narrowing through statically known branches (#27752) ## Summary Previously, narrowing was lost after a statically known branch because the unreachable control-flow path still contributed its original type: ```python def narrow(value: int | None) -> None: if 1 + 1 == 2: if value is None: return reveal_type(value) # Previously: int | None; now: int ``` We now gate narrowing constraints with their corresponding reachability conditions and reuse predicate identities across both analyses. This allows narrowing to propagate through constant conditions, short-circuit expressions, match guards, and statically non-empty `range()` loops while preserving ambiguous branches. Statement-level calls now participate in normal reachability analysis in every scope, replacing the separate scope-wide narrowing machinery for module- and class-level calls. As a result, the improved narrowing also works inside module- and class-level loops, while preserving terminal-call analysis, overload selection, and loop-carried forward references. Because these calls now contribute to reachability graphs, we raise the nested-binding cutoff from 2,048 to 4,096 to preserve precision in call-heavy scopes. The loop-reachability and loop-inference cutoffs remain unchanged to protect performance on loop-heavy projects such as isort and parso. We also track the places each predicate can narrow, avoiding unnecessary constraint inference and preventing unrelated reachability gates from introducing cycles through deferred annotations. Lambda and generator conditions are resolved without inferring their bodies, avoiding recursive-callable inference cycles. This also fixes exhaustive nested checks where proving that an outer branch terminates depends on narrowing a separate inner value, preventing spurious `assert_never` errors. Based on @mtshiba's work in #27207 and #23201. Closes https://github.com/astral-sh/ty/issues/4240. --------- Co-authored-by: Shunsuke Shibayama <sbym1346@gmail.com>
Author
Parents
Loading