[ty] Eagerly simplify 'True' and 'False' constraints (#18998)

## Summary

Simplifies literal `True` and `False` conditions to `ALWAYS_TRUE` /
`ALWAYS_FALSE` during semantic index building. This allows us to eagerly
evaluate more constraints, which should help with performance (looks
like there is a tiny 1% improvement in instrumented benchmarks), but
also allows us to eliminate definitely-unreachable branches in
control-flow merging. This can lead to better type inference in some
cases because it allows us to retain narrowing constraints without
solving https://github.com/astral-sh/ty/issues/690 first:
```py
def _(c: int | None):
    if c is None:
        assert False
    
    reveal_type(c)  # int, previously: int | None
```

closes https://github.com/astral-sh/ty/issues/713

## Test Plan

* Regression test for https://github.com/astral-sh/ty/issues/713
* Made sure that all ecosystem diffs trace back to removed false
positives
This commit is contained in:
David Peter 2025-06-30 13:11:52 +02:00 committed by GitHub
parent 54769ac9f9
commit db3dcd8ad6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 129 additions and 43 deletions

View file

@ -388,12 +388,18 @@ impl ReachabilityConstraintsBuilder {
&mut self,
predicate: ScopedPredicateId,
) -> ScopedReachabilityConstraintId {
self.add_interior(InteriorNode {
atom: predicate,
if_true: ALWAYS_TRUE,
if_ambiguous: AMBIGUOUS,
if_false: ALWAYS_FALSE,
})
if predicate == ScopedPredicateId::ALWAYS_FALSE {
ScopedReachabilityConstraintId::ALWAYS_FALSE
} else if predicate == ScopedPredicateId::ALWAYS_TRUE {
ScopedReachabilityConstraintId::ALWAYS_TRUE
} else {
self.add_interior(InteriorNode {
atom: predicate,
if_true: ALWAYS_TRUE,
if_ambiguous: AMBIGUOUS,
if_false: ALWAYS_FALSE,
})
}
}
/// Adds a new reachability constraint that is the ternary NOT of an existing one.