Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Type-narrowing for
if
blocks (#1313)
Closes #1267 Use the `Scope` machinery in the jinja static analyzer to narrow the types of values that have been used in the predicate expression of an `if` block. For example: ``` class Foo { x int } function UseOptionalFoo(inp: Foo?) { client ... prompt #" {% if inp %} {{ inp.x }} {%endif %} "# } ``` Since `inp` has been checked for existence, we would like `inp.x` not to raise a warning. We know it has an `x` fielde because `inp` can no longer be null, because we are in a scope in which `inp == true`. This PR does some basic analysis on predicates to update the typing context with these narrowed types. The following scenarios are supported: - `if foo` narrows `Foo | None` to `Foo` in the if body. - `if not foo` narrows in the else body. - `if foo and bar` narrows `foo` and `bar` - `if not foo and bar` narrows `foo` in else and `bar` in the if body The screenshot shows a combination of these effects: <img width="573" alt="Screenshot 2025-01-11 at 12 01 05 AM" src="https://github.com/user-attachments/assets/2f458f9f-035f-40f2-9956-42b9961ce426" /> <!-- ELLIPSIS_HIDDEN --> ---- > [!IMPORTANT] > Implements type-narrowing for `if` blocks in Jinja static analyzer using `Scope` machinery to update typing context based on predicate truthiness. > > - **Behavior**: > - Implements type-narrowing for `if` blocks in `stmt.rs` using `Scope` machinery. > - Handles scenarios: `if foo`, `if not foo`, `if foo and bar`, `if not foo and bar`. > - **Functions**: > - Adds `predicate_implications()` to determine type implications based on predicates. > - Adds `truthy()` to derive truthy type versions. > - **Tests**: > - Adds tests for `truthy_union` and `implication_from_nullable` in `stmt.rs`. > > <sup>This description was created by </sup>[<img alt="Ellipsis" src="https://img.shields.io/badge/Ellipsis-blue?color=175173">](https://www.ellipsis.dev?ref=BoundaryML%2Fbaml&utm_source=github&utm_medium=referral)<sup> for e6ce8f4. It will automatically update as commits are pushed.</sup> <!-- ELLIPSIS_HIDDEN --> --------- Co-authored-by: aaronvg <[email protected]>
- Loading branch information