Skip to content

Commit a7d4cc9

Browse files
Destroy for-loop body locals before the increment (#681)
Programs with RAII objects in a `for`-loop body run the increment before those objects’ destructors in both translation models. This reverses observable side effects and can keep guards alive longer than in C++. The body now has its own drop scope, including when it exits through `continue`. --- Made by [Perfloop](https://app.perfloop.ai). Human sponsor: [Tomás Senart](https://github.com/tsenart). --------- Signed-off-by: Perfloop Agent <agent@perfloop.ai>
1 parent f434fbf commit a7d4cc9

191 files changed

Lines changed: 5373 additions & 3949 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎cpp2rust/converter/converter.cpp‎

Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1576,9 +1576,9 @@ bool Converter::VisitAttributedStmt(clang::AttributedStmt *stmt) {
15761576
}
15771577

15781578
bool Converter::VisitWhileStmt(clang::WhileStmt *stmt) {
1579-
ScopedValue break_loop(break_switch_, false);
1579+
ScopedValue break_loop(break_label_, "");
15801580
StrCat("'loop_:");
1581-
ScopedValue no_inc(curr_for_inc_, nullptr);
1581+
ScopedValue no_inc(continue_for_, false);
15821582
if (auto *cond_var = stmt->getConditionVariableDeclStmt()) {
15831583
StrCat(keyword::kLoop);
15841584
PushBrace loop_brace(*this);
@@ -1605,7 +1605,7 @@ void Converter::ConvertConditionVariableTest(clang::DeclStmt *cond_var,
16051605
}
16061606

16071607
bool Converter::VisitDoStmt(clang::DoStmt *stmt) {
1608-
ScopedValue break_loop(break_switch_, false);
1608+
ScopedValue break_loop(break_label_, "");
16091609
const char *control_var = "__do_while";
16101610
StrCat(keyword::kLet, "mut", control_var, token::kAssign, keyword::kTrue,
16111611
token::kSemiColon);
@@ -1617,14 +1617,14 @@ bool Converter::VisitDoStmt(clang::DoStmt *stmt) {
16171617
{
16181618
PushBrace loop_brace(*this);
16191619
StrCat(control_var, token::kAssign, keyword::kFalse, token::kSemiColon);
1620-
ScopedValue no_inc(curr_for_inc_, nullptr);
1620+
ScopedValue no_inc(continue_for_, false);
16211621
ConvertBodyStmts(stmt->getBody());
16221622
}
16231623
return false;
16241624
}
16251625

16261626
bool Converter::VisitForStmt(clang::ForStmt *stmt) {
1627-
ScopedValue break_loop(break_switch_, false);
1627+
ScopedValue break_loop(break_label_, stmt->getInc() ? "'loop_" : "");
16281628
// The variables of the init statement are only visible in the for.
16291629
PushBrace scope(*this, stmt->getInit() &&
16301630
clang::isa<clang::DeclStmt>(stmt->getInit()));
@@ -1647,7 +1647,14 @@ bool Converter::VisitForStmt(clang::ForStmt *stmt) {
16471647
ConvertConditionVariableTest(cond_var, stmt->getCond());
16481648
}
16491649
{
1650-
ScopedValue inc(curr_for_inc_, stmt->getInc());
1650+
ScopedValue inc(continue_for_, stmt->getInc() != nullptr);
1651+
// Leaving the body, including via continue, destroys its locals before
1652+
// the increment. The condition variable stays alive through the
1653+
// increment.
1654+
if (continue_for_) {
1655+
StrCat("'for_body:");
1656+
}
1657+
PushBrace body(*this, continue_for_);
16511658
ConvertBodyStmts(stmt->getBody());
16521659
}
16531660
Convert(stmt->getInc());
@@ -1657,7 +1664,7 @@ bool Converter::VisitForStmt(clang::ForStmt *stmt) {
16571664
}
16581665

16591666
bool Converter::VisitCXXForRangeStmt(clang::CXXForRangeStmt *stmt) {
1660-
ScopedValue break_loop(break_switch_, false);
1667+
ScopedValue break_loop(break_label_, "");
16611668
Convert(stmt->getInit());
16621669
Convert(stmt->getRangeStmt());
16631670
auto *begin =
@@ -1672,28 +1679,24 @@ bool Converter::VisitCXXForRangeStmt(clang::CXXForRangeStmt *stmt) {
16721679
ConvertFreshRValue(end->getInit()), ')');
16731680
{
16741681
PushBrace brace(*this);
1675-
ScopedValue no_inc(curr_for_inc_, nullptr);
1682+
ScopedValue no_inc(continue_for_, false);
16761683
Convert(stmt->getLoopVarStmt());
16771684
ConvertBodyStmts(stmt->getBody());
16781685
}
16791686
return false;
16801687
}
16811688

16821689
bool Converter::VisitBreakStmt([[maybe_unused]] clang::BreakStmt *stmt) {
1683-
StrCat(keyword::kBreak);
1684-
if (break_switch_) {
1685-
StrCat("'switch");
1686-
}
1690+
StrCat(keyword::kBreak, break_label_);
16871691
return false;
16881692
}
16891693

16901694
bool Converter::VisitContinueStmt([[maybe_unused]] clang::ContinueStmt *stmt) {
1691-
if (curr_for_inc_) {
1692-
Convert(curr_for_inc_);
1693-
StrCat(token::kSemiColon);
1695+
if (continue_for_) {
1696+
StrCat(keyword::kBreak, "'for_body");
1697+
} else {
1698+
StrCat(keyword::kContinue, "'loop_");
16941699
}
1695-
StrCat(keyword::kContinue);
1696-
StrCat("'loop_");
16971700
return false;
16981701
}
16991702

@@ -4524,7 +4527,7 @@ bool Converter::VisitSwitchStmt(clang::SwitchStmt *stmt) {
45244527
return !arm.label.empty() || arm.has_fallthrough;
45254528
});
45264529

4527-
ScopedValue break_switch(break_switch_, !needs_switch_macro);
4530+
ScopedValue break_switch(break_label_, needs_switch_macro ? "" : "'switch");
45284531

45294532
// The variables of the init statement and of the condition are only
45304533
// visible in the switch.

‎cpp2rust/converter/converter.h‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1066,16 +1066,16 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
10661066
bool constant_evaluated_ = false;
10671067
std::optional<bool> autoref_mut_;
10681068

1069-
// The increment of the innermost loop, which continue runs.
1070-
clang::Expr *curr_for_inc_ = nullptr;
1069+
// Whether continue exits 'for_body to run the for-loop increment.
1070+
bool continue_for_ = false;
10711071
// The names of the iterators of range-based for loops.
10721072
std::unordered_map<const clang::ValueDecl *, std::string>
10731073
range_iterator_names_;
10741074
std::vector<clang::QualType> curr_init_type_;
10751075

1076-
// Whether break exits a switch labeled 'switch, rather than a loop or a
1077-
// switch! macro, which a plain break exits.
1078-
bool break_switch_ = false;
1076+
// Breaks in a for body must leave the loop, not just the labeled body.
1077+
// A switch! macro owns plain breaks; a plain match uses 'switch.
1078+
const char *break_label_ = "";
10791079

10801080
// Local variables hoisted outside a goto_block so that all labels can see and
10811081
// use the variables.

‎tests/std/basic/basic.scope/out/refcount/basic.scope.block.rs‎

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -133,8 +133,10 @@ pub fn test_8() {
133133
{
134134
let mut index: i32 = 0;
135135
'loop_: while (index < 3) {
136-
iterations.prefix_inc();
137-
sum += index;
136+
'for_body: {
137+
iterations.prefix_inc();
138+
sum += index;
139+
}
138140
index.prefix_inc();
139141
}
140142
}
@@ -151,9 +153,11 @@ pub fn test_9() {
151153
{
152154
let mut index: i32 = 0;
153155
'loop_: while (index < 3) {
154-
let scoped: Value<LifetimeTracked> = Rc::new(RefCell::new(LifetimeTracked::new()));
155-
let _dtor_scoped =
156-
std::mem::DropGuard::new(scoped.clone(), |__p| __p.as_pointer().destructor());
156+
'for_body: {
157+
let scoped: Value<LifetimeTracked> = Rc::new(RefCell::new(LifetimeTracked::new()));
158+
let _dtor_scoped =
159+
std::mem::DropGuard::new(scoped.clone(), |__p| __p.as_pointer().destructor());
160+
}
157161
index.prefix_inc();
158162
}
159163
}
@@ -224,12 +228,16 @@ pub fn test_12() {
224228
{
225229
let mut index: i32 = 0;
226230
'loop_: while (index < 2) {
227-
{
228-
let mut index: i32 = 10;
229-
'loop_: while (index < 13) {
230-
inner_iterations.prefix_inc();
231-
sum += index;
232-
index.prefix_inc();
231+
'for_body: {
232+
{
233+
let mut index: i32 = 10;
234+
'loop_: while (index < 13) {
235+
'for_body: {
236+
inner_iterations.prefix_inc();
237+
sum += index;
238+
}
239+
index.prefix_inc();
240+
}
233241
}
234242
}
235243
{

‎tests/std/basic/basic.scope/out/unsafe/basic.scope.block.rs‎

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -121,8 +121,10 @@ pub unsafe fn test_8() {
121121
{
122122
let mut index: i32 = 0;
123123
'loop_: while ((index) < (3)) {
124-
iterations.prefix_inc();
125-
sum += index;
124+
'for_body: {
125+
iterations.prefix_inc();
126+
sum += index;
127+
}
126128
index.prefix_inc();
127129
}
128130
}
@@ -139,9 +141,11 @@ pub unsafe fn test_9() {
139141
{
140142
let mut index: i32 = 0;
141143
'loop_: while ((index) < (3)) {
142-
let mut scoped: LifetimeTracked = LifetimeTracked::new();
143-
let _dtor_scoped =
144-
std::mem::DropGuard::new(&raw mut scoped, |__p| unsafe { (*__p).destructor() });
144+
'for_body: {
145+
let mut scoped: LifetimeTracked = LifetimeTracked::new();
146+
let _dtor_scoped =
147+
std::mem::DropGuard::new(&raw mut scoped, |__p| unsafe { (*__p).destructor() });
148+
}
145149
index.prefix_inc();
146150
}
147151
}
@@ -208,12 +212,16 @@ pub unsafe fn test_12() {
208212
{
209213
let mut index: i32 = 0;
210214
'loop_: while ((index) < (2)) {
211-
{
212-
let mut index: i32 = 10;
213-
'loop_: while ((index) < (13)) {
214-
inner_iterations.prefix_inc();
215-
sum += index;
216-
index.prefix_inc();
215+
'for_body: {
216+
{
217+
let mut index: i32 = 10;
218+
'loop_: while ((index) < (13)) {
219+
'for_body: {
220+
inner_iterations.prefix_inc();
221+
sum += index;
222+
}
223+
index.prefix_inc();
224+
}
217225
}
218226
}
219227
{

‎tests/std/expr/expr.compound/expr.unary/out/refcount/expr.pre.incr.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,9 @@ pub fn test_0() {
6363
{
6464
let mut k: i32 = 0;
6565
'loop_: while (k < 3) {
66-
sum += (*y.prefix_inc());
66+
'for_body: {
67+
sum += (*y.prefix_inc());
68+
}
6769
k.prefix_inc();
6870
}
6971
}

‎tests/std/expr/expr.compound/expr.unary/out/unsafe/expr.pre.incr.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,9 @@ pub unsafe fn test_0() {
4343
{
4444
let mut k: i32 = 0;
4545
'loop_: while ((k) < (3)) {
46-
sum += (*y.prefix_inc());
46+
'for_body: {
47+
sum += (*y.prefix_inc());
48+
}
4749
k.prefix_inc();
4850
}
4951
}

‎tests/ub/out/refcount/ub6.rs‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,10 +41,13 @@ pub fn any_2(arr: Ptr<Option<Value<Box<[Ptr<i32>]>>>>, n1: Ptr<i32>) -> bool {
4141
{
4242
let mut i: i32 = 0;
4343
'loop_: while ({ i } < { (n1.read()) }) {
44-
let __rhs = (out)
45-
|| (((({ (*arr.upgrade().deref()).decay().offset((i as usize)) }).read()).read())
46-
== 0);
47-
out = __rhs;
44+
'for_body: {
45+
let __rhs = (out)
46+
|| (((({ (*arr.upgrade().deref()).decay().offset((i as usize)) }).read())
47+
.read())
48+
== 0);
49+
out = __rhs;
50+
}
4851
i.prefix_inc();
4952
}
5053
}

‎tests/ub/out/unsafe/ub6.rs‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -36,12 +36,14 @@ pub unsafe fn any_2(arr: *mut Option<Box<[*mut i32]>>, n1: *mut i32) -> bool {
3636
{
3737
let mut i: i32 = 0;
3838
'loop_: while ((i) < (*n1)) {
39-
out = (out)
40-
|| ((*(*(*arr)
41-
.as_deref()
42-
.map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut *mut i32)
43-
.add((i as usize))))
44-
== (0));
39+
'for_body: {
40+
out = (out)
41+
|| ((*(*(*arr)
42+
.as_deref()
43+
.map_or(::std::ptr::null_mut(), |s| s.as_ptr() as *mut *mut i32)
44+
.add((i as usize))))
45+
== (0));
46+
}
4547
i.prefix_inc();
4648
}
4749
}

‎tests/unit/for_body_destructor.cpp‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
#include <cstdio>
2+
3+
struct Guard {
4+
int digit;
5+
~Guard() { std::printf("%d ", digit); }
6+
explicit operator bool() const { return digit != 0; }
7+
};
8+
9+
void step(int &i) {
10+
std::printf("9 ");
11+
++i;
12+
}
13+
14+
int main() {
15+
std::printf("normal/continue: ");
16+
for (int i = 0; i < 2; step(i)) {
17+
Guard first{1};
18+
Guard second{2};
19+
if (i == 0)
20+
continue;
21+
}
22+
23+
std::printf("\nbreak: ");
24+
for (int i = 0; i < 2; step(i)) {
25+
Guard g{3};
26+
break;
27+
}
28+
29+
std::printf("\nnested for: ");
30+
for (int i = 0; i < 1; step(i)) {
31+
Guard outer{4};
32+
for (int j = 0; j < 2; step(j)) {
33+
Guard inner{5};
34+
if (j == 0)
35+
continue;
36+
break;
37+
}
38+
continue;
39+
}
40+
41+
std::printf("\ninner while/do/range: ");
42+
for (int i = 0; i < 1; step(i)) {
43+
Guard outer{4};
44+
int j = 0;
45+
while (++j < 3) {
46+
Guard inner{5};
47+
if (j == 1)
48+
continue;
49+
break;
50+
}
51+
do {
52+
Guard inner{6};
53+
continue;
54+
} while (false);
55+
int values[] = {1, 2};
56+
for (int value : values) {
57+
Guard inner{value};
58+
if (value == 1)
59+
continue;
60+
break;
61+
}
62+
continue;
63+
}
64+
65+
std::printf("\ncondition: ");
66+
for (int i = 2; Guard condition{i};
67+
--i, std::printf("inc%d ", condition.digit)) {
68+
Guard body{4};
69+
if (i == 2)
70+
continue;
71+
}
72+
73+
std::printf("\ninit/noncompound: ");
74+
int i = 0;
75+
for (Guard init{5}; i < 2; step(i))
76+
Guard body{6};
77+
78+
std::printf("\nno increment: ");
79+
for (int j = 0; j < 2;) {
80+
Guard g{++j};
81+
continue;
82+
}
83+
84+
std::printf("\n");
85+
return 0;
86+
}

‎tests/unit/out/refcount/alloc_array.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@ pub fn All_0(arr: Ptr<Option<Value<Box<[i32]>>>>, mut N: i32, mut element: i32)
1313
{
1414
let mut i: i32 = 0;
1515
'loop_: while (i < N) {
16-
all.decay().offset((i as usize)).write(element);
16+
'for_body: {
17+
all.decay().offset((i as usize)).write(element);
18+
}
1719
i.prefix_inc();
1820
}
1921
}

0 commit comments

Comments
 (0)