Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion pyrefly/lib/binding/scope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2729,7 +2729,19 @@ impl<'a> BindingsBuilder<'a> {
} else {
live_branches
};
let all_are_unreachable = flows.iter().all(|f| f.is_definitely_unreachable);
// Determine reachability of the merged flow.
// For Loop style with empty flows (all branches terminated), the loop body might
// never execute (empty iterable), so we use the base flow's reachability.
// For LoopDefinitelyRuns, the loop definitely runs, so if all branches terminated,
// the flow is unreachable.
let all_are_unreachable = if flows.is_empty() {
match merge_style {
MergeStyle::Loop => base.is_definitely_unreachable,
_ => true,
}
} else {
flows.iter().all(|f| f.is_definitely_unreachable)
};

// For a regular loop, we merge the base so there's one extra branch being merged.
// For LoopDefinitelyRuns, we don't count the base as an extra branch because we
Expand Down
22 changes: 22 additions & 0 deletions pyrefly/lib/test/flow_looping.rs
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,28 @@ def test2(match: float) -> float: # E: Function declared to return `float` but
"#,
);

testcase!(
test_for_else_return_in_body_else_reachable,
r#"
def foo(x: list[int]) -> int:
for _ in x:
return 1
else:
return 2 # No error - reachable when x is empty
"#,
);

testcase!(
test_for_definitely_runs_return_else_unreachable,
r#"
def foo() -> int:
for _ in range(3):
return 1
else:
return 2 # E: This `return` statement is unreachable
"#,
);

testcase!(
test_for_with_reassign,
r#"
Expand Down
Loading