Repository navigation
check: a reference that a call stores in a loop stays borrowed in the next pass - #4462
KrispWaffle wants to merge 23 commits into
Conversation
…t changes the Vec In a loop, a call such as `keep(&mut h, v.get_ref(0))` can store a reference to an element of `v` in `h`. The next pass can call `v.push(..)` before the call runs again. The push can move the elements of `v`, so `h` then points at freed memory. The checker accepts these loops. The program in vx-lang#4413 printed a different large number on each run. a_reference_that_a_call_stores_in_a_loop_keeps_the_vec_borrowed.vx fails on this commit. Its six functions compile with no error. The next commit fixes the checker. a_call_in_a_loop_that_stores_no_reference_lets_the_vec_change.vx passes on this commit and must keep passing. In each of its loops, the call cannot store a reference to a variable from before the loop. Refs: vx-lang#4413
… next pass At the start of a loop body, the checker adds the borrows that the previous pass can leave. It found them only in assignments such as `r = v.get_ref(0)`, and not in calls. So `keep(&mut h, v.get_ref(0))` in one pass did not keep `v` borrowed in the next pass. A `v.push(..)` before the call compiled, and the program read freed memory. The checker now also reads each call in the loop body as the assignments that the call can make. A call can store a value through each `&mut` argument, or method receiver, whose target can hold a reference. So `keep(&mut h, x)` counts as `h = x`. A value does not count when its type cannot hold a reference, or when its parameter says `!keeps`. The checker uses the same rule for a call outside a loop. The checker has not checked the loop body yet at this point. So it gets the type of a value such as `v.len()` from a check of a copy, and it drops the messages of that check. A loop that calls `keep(&mut h, v.get_ref(0))` on every pass, after `v.push(..)`, now gets E4003 too. Rust also refuses this loop, because `keep` can read `h` before it stores the new reference. Fixes: vx-lang#4413
A review of the previous commit found loops that the checker got wrong.
Some compiled although a call left a reference for the next pass. Others
failed to compile although no reference reached the next pass.
a_reference_that_a_call_stores_in_a_loop_keeps_the_variable_borrowed.vx
fails on this commit. Its four functions compile with no error:
- `n.save_in(&mut h)` stores a reference to its receiver `n`.
- `keep_wrapped(&mut h, Wrapped { value : n.view() })` passes the
reference inside a struct.
- A `continue` after the call starts a next pass, although the body ends
in `break`.
- A `continue` after the call skips `h = ..` at the end of the pass.
These loops must compile, and they get an error on this commit:
- a_call_in_a_loop_that_stores_no_reference_lets_the_vec_change.vx gets a
method that takes `&self`, and a method whose parameter says `!keeps`.
- a_loop_pass_that_leaves_no_borrow_lets_the_next_pass_change_the_variable.vx
has five loops: a number made from `&x`, a holder that gets a new value
later in the pass, a store only in the pass that leaves the loop, and a
holder or a variable that the loop declares with the name of an outer
variable.
The next commit fixes the checker.
Refs: vx-lang#4413
The previous commit made the loop check read each call in the loop body as the assignments that the call can make. It read the arguments before the checker checked the body, and this went wrong in several ways: - A method that takes `&self`, or whose parameter says `!keeps`, counted as able to store in its receiver. - A number such as `times_two(&x) + 1` got an unknown type, so `&x` counted as stored. - The trial type check of an argument used a variable from before the loop when the loop declared one with the same name. It could report an error for a generic call that the program does not make. - `n.save_in(&mut h)` did not count the reference to the receiver `n`. The check now takes the parameters from the declaration of the function, or of the method of the receiver's type. An argument is a place for a store when its parameter is `&mut T` and `T` can hold a reference. It is a value for a store when its parameter type can hold a reference and does not say `!keeps`. A method that takes `&self` gets `&n` as a value. A callee that the check cannot find yet keeps the old rule, without the trial type check. These changes apply to assignments and calls alike: - A name that the loop body declares is not a variable from before the loop. - A method call in a field of a struct literal counts, as one that is the whole value does. - A store in an `if` block that ends in `break` or `return` reaches no next pass. - A store reaches no next pass when a later statement of the body assigns its variable again. - A body that ends in `break` has a next pass when it has a `continue`. The rule before this one does not apply then. Fixes: vx-lang#4413
In this loop, `keep(&mut h, &x)` stores `&x` in `h`. Later in the same
pass, `h = Holder { r : h.r }` gives `h` a new value. The new value copies
the reference out of `h`, so `h` still holds `&x` in the next pass. The
`x = 7i64` at the start of the next pass must get E4009.
The checker drops a store when a later statement of the body assigns `h`
again. It does not look at the value of that statement. So this loop
compiles with no error on this commit, and the new function in
a_reference_that_a_call_stores_in_a_loop_keeps_the_variable_borrowed.vx
fails. The next commit fixes the checker.
Refs: vx-lang#4413
The loop check drops a store into `h` when a later statement of the body
assigns `h` again. It did not look at the new value. So the checker
dropped the store of `&x` in `keep(&mut h, &x)` when a later statement
was `h = Holder { r : h.r }`.
The new value copies the reference out of `h`, so `h` still holds `&x` in
the next pass. A change to `x` at the start of the next pass compiled.
An assignment to `h` now replaces the store only when its value does not
read `h`. A name in the value that the loop body declares is a different
variable, so it does not count.
Fixes: vx-lang#4413
A call can store a reference through a local reference such as `hr` after `let hr = &mut h`, as PR vx-lang#4441 checked outside loops. In a loop, the checker missed this store, and the test program read freed memory. a_reference_that_a_call_stores_in_a_loop_keeps_the_vec_borrowed.vx gets four new functions that compile with no error on this commit: - `let hr = &mut h` before the loop, then `keep(hr, v.get_ref(0))` - `let hr = &mut h` inside the loop, then `keep(hr, v.get_ref(0))` - `let mut hr = &mut h` before the loop, then `hr = other` after the call - `let hr = &mut *p` inside the loop for a `&mut` parameter `p` a_call_in_a_loop_that_stores_no_reference_lets_the_vec_change.vx gets a loop that calls `out.push(v.get(0))` on `out : &mut Vec<i64>` and `v : &mut Vec<i64>`. That loop must keep compiling. The next commit fixes the checker. Refs: vx-lang#4413
A call in a loop can store a reference into a holder through a local reference `hr`, declared before or inside the loop. The checker missed this for three reasons: - `carried_borrow_seeds` skipped a `&mut` parameter such as `v` as the borrowed variable. - A loop-local reference such as `let hr = &mut h` did not map to the outer holder `h`. - A reference declared before the loop did not follow `mut_borrowed_by` to `h`, so `hr = other` later in the pass dropped the borrow even though `h` still held the reference. The check now resolves each store place through both `mut_borrowed_by` and loop-local `let hr = &mut ..` bindings (including `&mut *p`), and keeps `&mut` parameters as borrowable bases. For a generic method such as `Vec<T>::push`, it uses the argument's concrete target type when known, so `out.push(v.get(0))` on `out : &mut Vec<i64>` does not count as a store of a reference. It also keeps the carried borrow shared when the holder is a `&mut` to a type that can hold a reference. Fixes: vx-lang#4413
In each new case, one pass of a loop stores a reference, and the next pass changes what the reference points at. The compiler accepted all of these loops, and the programs read freed memory. The new cases in the two fail fixtures: - The holder gets a new value at the end of the pass. But before that, a statement copies the stored reference out of the holder. - The stored reference comes from a local variable, from a function or a method that returns its argument, or from an enum value. - The call stores through a local reference. That reference comes from a function, from an if, from a struct field or from a parameter. - The loop points an outer reference at a second holder. - The holder is a parameter that the function does not read after the loop. The caller can still read the stored reference. - The loop body declares a reference with the name of an outer variable. The outer variable is a number, or a struct with a method of the same name. The pass fixture gets a loop where the result of `v.len()` is only the index of the stored reference. So the next pass can still change `v`. Refs: vx-lang#4413
At the start of a loop body, the checker adds the borrows that a store in the previous pass can leave. It missed four kinds of stores, so it accepted loops that read freed memory. 1. A new value `h = ..` later in the pass ends what a store left in `h`. The checker used this rule also when a statement between the two read `h`, as `let t = h.r` does. Now the new value ends the borrow only when no statement reads `h` before it. 2. The checker looked for the stored reference only in `&x` and in the receiver of a method call at the top of the value. Now it also looks into the arguments of calls, into struct, enum and array values, and into the branches of an if or a match. It follows a variable of the loop body to the value that the body gives it. It skips a part whose type cannot hold a reference, such as the result of `v.len()`. 3. A store through a local reference reached its holder only after `let r = &mut h`. Now it also does after `r = &mut h`, after `let r = p`, after `let r = links.left`, after a call that returns `&mut`, and after an if or a match that gives one of these. When the holder is a `&mut` parameter, the caller can read the stored reference after the function returns. So the borrow lasts until then. 4. A variable of the loop body can have the name of a variable from before the loop. The checker used the type of the outer variable for it. Now it treats the type of the loop variable as unknown. The full corpus of .vx files gives the same errors as before, except in the fixtures of this issue. Fixes: vx-lang#4413
In each new case of the fail fixture, one pass of a loop stores a reference to an element of `v`. The next pass changes `v`. The compiler accepted these loops, and the programs read freed memory. - An `if` or an inner loop stores the reference in `g` and copies it into `h`. A later statement gives `g` a new value. - A loop variable gets the reference from an `if`, from an enum value or from the static method `Holder::make`. - A call or an assignment puts the reference in a holder `g` that the loop body declares. Then `h = g` copies the holder. - A local reference comes from the generic function `id(&mut h)`, or from the method `pair.first_mut()` on the struct `pair`. The pass fixture gets four valid loops that the compiler rejects with E4003. In three loops, a number from `items` or `idx` picks the element of `w` that `h` keeps. In the fourth loop, a method call through the local reference `hr` gets the number `v.len()`. Refs: vx-lang#4413
…loops The loop check missed some references that one pass of a loop keeps for the next pass. It also rejected some valid loops. This commit fixes four problems. 1. A new value `g = ..` later in the pass ended a store into `g`. The check looked for reads of `g` only in the statements after the store. But an `if` or an inner loop can store into `g` and then read `g`. Now the new value ends the store only when the statement that makes the store names `g` once. 2. The check did not know the type of an `if` value, of an enum value or of a static method call such as `Holder::make(x)`. So it did not look for references in a loop variable with such a value. Now it knows these types. A call or an assignment that fills a part of a loop variable, such as `keep(&mut g, x)`, now also gives a value to that variable. 3. A local reference from `id(&mut h)` did not reach `h`, because the result type `T` cannot write a reference. Now a result of type `T` can be each argument whose parameter has type `T`. A method result such as `pair.first_mut()` now reaches its receiver `pair`, also when `pair` is not a reference. 4. The check did not know the type of `items.get_ref(0).id`, of `*idx.get_ref(0)` or of a loop variable. So it treated an index as a reference into `items` or `idx`, and rejected valid loops. Now it finds these types from the struct field, from the reference and from the values that the loop gives the variable. A type check of all 3,059 .vx files gives the same errors as before this commit, except in the fixtures of this issue. Fixes: vx-lang#4413
The fail fixture gets six new loops. In each loop, one pass stores a
reference to an element of `v`, and the next pass changes `v`. The
compiler accepted four of these loops, and the programs read freed
memory:
- `let hr = &mut *pick(&mut h)` points at `h` through a call.
- `let q = &mut *p` with `p = &mut pair`, then `q.first_mut()`.
- `let links = Links { left : &mut h }`, then `keep(links.left, ..)`.
- Two blocks of the loop body declare `p`. The first `p` points at
`pair`, and the second `p` is a number.
In the other two loops, the loop body declares a holder `g`. It stores
the reference in `g` and copies `g.r` into `h`. One loop does this in an
inner loop. The other loop copies `g.r` before and after the store. The
compiler rejects both loops already. They show where the fix in the
next commit must stop.
The pass fixture gets six valid loops. The compiler on main accepts
them, but this branch rejects each of them with E4003:
- The loop calls a method that takes `&self` through `let hr = &mut h`.
- Two loops call `e.position()` on `e = items.get_ref(0)`.
- A closure reads a number from `e`.
- Two blocks of the loop body declare `x`. Only the second `x` goes
into `h`, and it points into `w`.
- `h.r = g.r` comes before `g.r = v.get_ref(0)`, and each pass makes a
new `g`.
Refs: vx-lang#4413
…oops
The loop check missed some references that one pass of a loop keeps
for the next pass. It also rejected some valid loops that main accepts.
And it was slow on a long chain of assignments. This commit fixes these
problems. Below, a local variable is a variable that the loop body
declares.
1. A local reference from `&mut *pick(&mut h)`, from `&mut *p` or from
`Links { left : &mut h }` did not reach `h`. Now the check looks
through the dereference of a call. It knows the type of `&mut *p`.
And it looks into the fields of a struct value.
2. The check did not know the parameters of a method that the loop
calls on a local variable. So `e.position()` counted as a store of
`e` into `e`, and the type of `e` became unknown. Now the check
finds the method from the type of `e`. A call that the check cannot
look into, such as a closure call, can still store `e` into `e`.
That store no longer adds a value to `e`.
3. Two local variables with one name shared their values. Now each
`let` makes a separate variable.
4. A store into a local variable `g` counted for every read of `g`. Now
it does not count for a read in an earlier statement of the block
that declares `g`. Each run of that block gives `g` a new value
before that read.
5. The check found the type of a local variable again for each use.
This took exponential time on a chain such as `x2 = x1; x3 = x2`.
Now it finds each type once, so the time grows linearly.
A type check of all 3,059 .vx files gives the same errors as before
this commit, except in the fixtures of this issue.
Fixes: vx-lang#4413
Replace the pre-pass syntax walk in `src/hir/stmt.rs` with a post-pass borrow replay in `src/hir/check/loop_borrows.rs`. Pass one now records borrow checks, branch frames, holder overwrites, borrow copies, and stores through mutable references. At the end of the loop body, the checker collects outer borrows from the body end and each `continue`, forwards stores through retargeted mutable references, propagates carried borrows across copy chains, and replays the recorded checks. Also tighten the shared borrow and escape helpers so they handle: - reborrowed elements, fields, method results, casts, and `unsafe` blocks - direct call, method, branch, struct, and indirect-call store targets - mutable borrows returned by methods and `match` arm pattern bindings - non-reference sub-expressions in arguments and `if` / `match` exits - consistent one-based borrow scope depth across shadowed local holders Add fail and pass tests for aliased targets, chains, `unsafe`, `match`, mutable borrows, generic methods, `while` loops, and `loop` statements. Refs: vx-lang#4413
Remove non-essential comments from the loop-borrow replay diff and the added test fixtures. Replace the tuple in `stores_through_refs` with `StoreThroughRef`, and split `finish_loop_borrow_log` into named phase helpers so the code reads without inline comments. Refs: vx-lang#4413
Bind `let z : &i64 = &zero;` so flat code generation can infer the
branch type of `if has_items(&v) { z } else { z }` when
`VX_NO_AST_FALLBACK` is set.
Refs: vx-lang#4413
|
A note for the merge: #4502 has a small text conflict with this PR in #4502 changes let Some(note) = shared else {
self.refuse_assigning_what_a_call_holds(..);
return;
};This PR adds an |
…er (#4501) The test read the coarse clock, then the precise clock, and required the difference to be at most two ticks (2 ms on a 1000 Hz kernel). The time between the two readings counted as lag too. Under QEMU, some of the 100000 passes went over the limit, and the aarch64 CI job failed on pull requests that do not change the runtime (#4462, #4498). Now the test reads the precise clock before and after the coarse one. It checks the lag against the reading before, and "ahead" against the reading after. Worst lag in 2 million passes of a C program, on this machine: precise after precise before x86-64, native 1.95 ms 1.52 ms aarch64, QEMU 10.2.1 2.64 ms 1.48 ms The test under qemu-aarch64: 4 failures in 35 runs before, none in 60 runs after. Natively: none in 30 runs, before and after. A coarse clock 1 ms ahead fails the "ahead" check, and one 5 ms behind fails the lag check. Fixes: #4500 Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
A note on a text conflict, so that it is quick to resolve. #4502 (with #4520 on top, a stack that fixes #4493) changes let Some(note) = shared else {
self.refuse_assigning_what_a_call_holds(&root, &path, &place, &lhs.span());
return;
};This PR adds an } else {
self.refuse_assigning_what_a_call_holds(&root, &path, &place, &lhs.span());
self.record_loop_access(&root, &path, LoopAccessKind::Assign { place, joined: joined.to_vec() }, &lhs.span());
}Whichever PR merges second needs this edit. Generated With Claude Code |
|
I haven't done a manual review yet. The below findings are from agents. I found four issues at
No builds, tests, or project scripts ran. Nothing was posted, and your checkout remains unchanged. |
…pies Address four findings in loop-borrow replay: - Wrap nested loop bodies in a non-exhaustive branch in enclosing loop logs so a skipped inner loop never clears an outer carried borrow. - Collect outer borrows from both active and shadowed entries using outer scope depths so shadowing a borrowed variable or outer holder inside the loop body does not drop carried borrows. - Record forwarded retargeted-reference stores into `self.borrow` so they stay active after the loop ends. - Record `LoopEvent::Continue` and `LoopEvent::Break` and collect copied outer borrows only at loop back-edges and exits so an overwritten copy does not stay borrowed after the loop. Add fail and pass regression tests for all four cases. Refs: vx-lang#4413
|
Pushed requested fixes |
minzyfox
left a comment
There was a problem hiding this comment.
I built this PR merged into latest main (ea0d9e8), and latest main itself. On both, I ran the five new fixtures, the four findings from my earlier comment, about 30 extra programs and two compile-time tests. CI had not run the tests on 8c8f532 yet.
Summary. The PR fixes #4413, but it adds a new hole: it accepts a program that reads freed memory, and latest main refuses that program. See my comment on (true, false) => {} in control.rs. I also found two new false errors and a compile time that grows about as the cube of the input size. The larger problem is the design: the replay is a second copy of the borrow rules. Details are in the inline comments.
What works.
a_reference_that_a_call_stores_in_a_loop_keeps_the_variable_borrowed.vx: latestmainaccepts all 6 programs, and this PR reports all 6. That is the fix for #4413.- This PR fixes findings 1 and 2 of my earlier comment: an inner
forloop that runs no times, and alet vat the end of the body. Latestmainmisses both, and this PR reports both. For finding 3, both compilers report the error. For finding 4, both accept the valid program. - A
matchon a number with no arm for some values, inside a loop: latestmainmisses the error, and this PR reports it. - The PR also fixes a crash on latest
main. See my comment ona_copied_borrow_that_exits_at_break_stays_borrowed.
The PR description. It says that 3,071 files gave "0 regressions". The programs in my inline comments are not among those files, so please drop that claim. Please also mention the crash that the PR fixes, and the changes outside loops (see my comment in escape.rs).
This PR and #4474. Both rewrite the same code in different ways. This PR deletes carried_borrow_seeds, seed_carried and forget_carried, and #4474 edits them. Both change the if and match borrow joins in control.rs, differently. Please choose one design, and make the other PR a stacked PR on top of it, or merge the two.
Docs. docs/discussions/borrow_checker_architecture.md ("When a borrow ends") still describes the syntax-based seeds. Please describe the event log and the replay there.
Tests. The five fixtures have 2,673 lines and 152 functions, but no header and no comment. The function names are good. A one-line comment on each function would tell the reader which case it covers. Please also split the two large fail files (782 and 943 lines) by topic: aliases, while, stores through calls and shadowing. Then a failure points to one small file.
Compile time. Programs with many reads in nested loops take the same time as on main. A chain of copies does not. In this body, each pass moves the borrow one step down the chain:
for i in 0..3 {
a800 = a799;
// ...
a1 = a0;
a0 = &x;
}
| links | latest main |
this PR |
|---|---|---|
| 200 | 0.19 s | 0.49 s |
| 400 | 0.47 s | 2.14 s |
| 800 | 2.08 s | 12.5 s |
The extra time grows about 6 times each time the chain doubles. See my comment on let mut changed = true.
Note: in my local run of the frontend fixtures, 63 fixtures failed because my build had no solver library. Latest main gives the same output as this PR on each of them that does not name the solver. So I found no fixture that this PR breaks, but CI must show it.
| self.borrow.restore(HashMap::new()); | ||
| self.borrow.add_back(then_borrows); | ||
| } | ||
| (true, false) => {} |
There was a problem hiding this comment.
This change makes the checker accept a program that reads freed memory. Latest main refuses this program:
import std::vec;
fn one(x : i64) -> Vec<i64> {
let mut v = Vec<i64>::new();
v.push(x);
return v;
}
fn while_continue(c : bool) -> i64 {
let mut v = one(5i64);
let w = one(7i64);
let mut r = w.get_ref(0);
let mut k = 2;
while k > 0 {
k = k - 1;
r = v.get_ref(0);
if c {
continue;
}
r = w.get_ref(0);
}
for i in 0..1000 {
v.push(i as i64); // latest main: E4003. This PR: no error.
}
return *r;
}
fn main() -> i32 {
println!("{}", while_continue(true));
return 0;
}
This PR compiles it. Two runs printed 6694 and 6981, not 5. The same loop written with for k in 0..2 also compiles. Latest main misses that one too, and #4474 fixes it.
The cause, as I read it: before this PR, only a then branch that returns dropped its borrows at the join. Now a branch that ends in continue drops them too. Those borrows go only to borrows_at_continue, and from there only into the replay of the body. They never reach the code after the loop. So the path where the loop ends right after a continue is lost. For a while, that is its else { break }. For a for, it is the end of the range.
Please add both loops to the fail fixtures.
| self.consteval.uncertain_branch_depth -= uncertain; | ||
| } | ||
| self.pop_branch_scope(&if_expr.then_block); | ||
| let then_ends_early_for_loop = self.branch_ends_early(&if_expr.then_block); |
There was a problem hiding this comment.
Two new false errors. Latest main accepts these two functions. This PR reports E4009 at x = 5; in both:
fn break_in_if_false() -> i32 {
let mut x = 1;
let y = 2;
let mut r = &x;
loop {
if false {
break;
}
r = &y;
break;
}
x = 5;
return *r + x;
}
const NEVER : bool = false;
// The same function, with `if NEVER` in place of `if false`.
The break in if false never runs. I did not find the exact cause. My guess is that the replay sees the Break event of a branch that the normal check knows it can skip. That is one example of the two copies of the rules disagreeing (see my comment on replay_loop_access).
| let depth = self.scopes.len(); | ||
| let mut made = Vec::new(); | ||
| let mut vars = Vec::new(); | ||
| crate::syntax::visit_expr_pruned(scrutinee, &mut |e| { |
There was a problem hiding this comment.
This changes the borrows of every match binding, inside and outside loops. The change is not limited to the loop case that #4413 is about. The same is true for hold_borrows_of_a_field_read (it now follows if, match and unsafe) and for the changes in escape.rs. Each of these changes which programs compile everywhere. Please move them into a separate PR, with tests outside loops.
| Move, | ||
| } | ||
|
|
||
| pub(crate) enum LoopEvent { |
There was a problem hiding this comment.
This file has 845 lines and no comments apart from the license header. The title of commit d8e3c39 is "strip comments". The design needs some explanation for the next reader:
- pass one writes a log of events
- a fixed point moves the carried borrows through copies
- a replay checks the logged accesses again
Please add a module comment with that outline. Please also add a doc comment to each type and function. Some points need one most: what a HolderKey is, what liveness_tail holds, and why KillHolder and Copy go to every enclosing loop's log but Break goes only to the innermost one.
| let Some(log) = self.borrow.loop_logs.pop() else { | ||
| return; | ||
| }; | ||
| debug_assert_eq!(log.root, root); |
There was a problem hiding this comment.
debug_assert_eq! does not run in a release build. AGENTS.md asks for an assert in place of a silent failure, so please use assert_eq!.
| /// to be one, since the method may borrow it mutably. | ||
| /// The parameter types of the function that `call` calls, in the order of its arguments. A | ||
| /// method's receiver comes first. `None` when the callee is not known here. | ||
| fn parameter_types_of_call(&mut self, call: &Expr) -> Option<Vec<Type>> { |
There was a problem hiding this comment.
This PR deleted the doc comment of mutable_reference_target. It started "The type a mutable reference argument points at, when it is one". On main it sat above parameter_types_of_call by mistake. Please put it back above mutable_reference_target.
| return *h2.r; | ||
| } | ||
|
|
||
| fn a_copied_borrow_that_exits_at_break_stays_borrowed() -> i64 { |
There was a problem hiding this comment.
Latest main (ea0d9e8) crashes on this function with "index out of bounds: the len is 1 but the index is 1" at src/hir/borrow_cx.rs:309. This function alone in a file is enough. This PR reports E4009 correctly. So the PR also fixes a crash, which the description does not mention. Please mention it. Please also give this function a comment that says it once crashed the compiler, or move it to a fixture of its own.
| // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | ||
| // | ||
| //===----------------------------------------------------------------------===// | ||
| // RUN: not vxc %s 2>&1 | FileCheck %s --implicit-check-not=Error |
There was a problem hiding this comment.
This file has 782 lines and 43 functions with no header and no comments. Please add a header that says what the file tests. Please also add a one-line comment above each function with the special case it covers. Splitting the file by topic would help as well.
| // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | ||
| // | ||
| //===----------------------------------------------------------------------===// | ||
| // RUN: not vxc %s 2>&1 | FileCheck %s --implicit-check-not=Error |
There was a problem hiding this comment.
The same request as for the aliases fixture: 943 lines, 50 functions and no comments. Latest main reports 3 of the 43 errors that this file checks. A header that names which functions show the fix for #4413 would help a reviewer.
| // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | ||
| // | ||
| //===----------------------------------------------------------------------===// | ||
| // RUN: vxc %s 2>&1 | FileCheck %s --implicit-check-not=Error |
There was a problem hiding this comment.
Thank you for running these programs with both code generators. Please add a short header that says what the pass fixture shows: a call in a loop that cannot store a reference must not keep the Vec borrowed.
Problem
In a loop, a call can store a reference through a
&mutargument, askeep(&mut h, v.get_ref(0))does. The checker kept borrows across loop passes only for plain assignments such asr = v.get_ref(0), and missed calls. Av.push(..)at the top of the loop body compiled, moved the buffer ofv, and a later read of*h.rread freed memory.Fix
This change removes the pre-pass syntax walk from
src/hir/stmt.rsand replaces it with a post-pass borrow replay insrc/hir/check/loop_borrows.rs. Pass one runs the real type and borrow checker on everyfor,while, andloopbody.ifandmatchbranch frame, holder overwrites, borrow copies, and stores through mutable references.continue.&mutstruct fields. It then propagates carried borrows across copy chains to a fixed point.escape.rs,control.rs,calls.rs,stmt.rs, andborrow_cx.rsnow handle reborrowed elements, fields, method results, casts,unsafeblocks, andmatcharm bindings. They also handle direct call, method, branch, struct, and indirect-call store targets, and mutable borrows returned by methods. They prune non-reference sub-expressions in arguments, drop early-endingifandmatchbranches, and use one-based borrow scope depth for shadowed locals.Verification
origin/mainat0919472bwith no conflicts.a_reference_that_a_call_stores_in_a_loop_keeps_the_vec_borrowed.vx,a_reference_that_a_call_stores_in_a_loop_keeps_the_variable_borrowed.vx, anda_call_in_a_loop_with_aliases_or_while_keeps_the_vec_borrowed.vx.a_call_in_a_loop_that_stores_no_reference_lets_the_vec_change.vxanda_loop_pass_that_leaves_no_borrow_lets_the_next_pass_change_the_variable.vx.#4409,#4413,#4441,#4449, and#4451, plus--legacy-codegenon all pass fixtures. All 20 runs passed.vxc -a print-astagainstorigin/mainat0919472bacross 3,071 tracked.vxfiles and 297 machine-file runs with 0 regressions.test_frontend_fail,test_frontend_pass,test_frontend_fail_formal_verification,test_frontend_pass_formal_verification,test_frontend_pass_modules,test_frontend_pass_packages, andborrow_testwith 11 passed and 0 failed.cargo test --libwith 1,159 passed and 0 failed,cargo fmt --all -- --check,vx-format,gen_error_index.py --check, andcargo clippy --workspace --all-targets --all-features -- -D warnings.Fixes: #4413