Skip to content

Commit 7efe1c6

Browse files
committed
Auto merge of #64525 - nikomatsakis:issue-64512-drop-order-tail-temp, r=davidtwco
adjust desugaring for async fn to correct drop order Old desugaring, given a user function body `{ $stmts; $expr }` ``` { let $param_pattern0 = $raw_param0; ... let $param_patternN = $raw_paramN; $stmts; $expr } ``` New desugaring: ``` { let $param_pattern0 = $raw_param0; ... let $param_patternN = $raw_paramN; drop-temps { $stmts; $expr } } ``` The drop-temps is an internal bit of HIR that drops temporaries from the resulting expression, but it should be equivalent to `return { $stmts; $expr }`. Fixes #64512 Fixes #64391
2 parents 9150f84 + 2d8b10f commit 7efe1c6

File tree

5 files changed

+161
-26
lines changed

5 files changed

+161
-26
lines changed

src/librustc/hir/lowering.rs

+7-8
Original file line numberDiff line numberDiff line change
@@ -2682,12 +2682,8 @@ impl<'a> LoweringContext<'a> {
26822682
bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
26832683
}
26842684

2685-
fn lower_block_with_stmts(
2686-
&mut self,
2687-
b: &Block,
2688-
targeted_by_break: bool,
2689-
mut stmts: Vec<hir::Stmt>,
2690-
) -> P<hir::Block> {
2685+
fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2686+
let mut stmts = vec![];
26912687
let mut expr = None;
26922688

26932689
for (index, stmt) in b.stmts.iter().enumerate() {
@@ -2712,8 +2708,11 @@ impl<'a> LoweringContext<'a> {
27122708
})
27132709
}
27142710

2715-
fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
2716-
self.lower_block_with_stmts(b, targeted_by_break, vec![])
2711+
/// Lowers a block directly to an expression, presuming that it
2712+
/// has no attributes and is not targeted by a `break`.
2713+
fn lower_block_expr(&mut self, b: &Block) -> hir::Expr {
2714+
let block = self.lower_block(b, false);
2715+
self.expr_block(block, ThinVec::new())
27172716
}
27182717

27192718
fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {

src/librustc/hir/lowering/expr.rs

+5-10
Original file line numberDiff line numberDiff line change
@@ -90,10 +90,7 @@ impl LoweringContext<'_> {
9090
),
9191
ExprKind::Async(capture_clause, closure_node_id, ref block) => {
9292
self.make_async_expr(capture_clause, closure_node_id, None, block.span, |this| {
93-
this.with_new_scopes(|this| {
94-
let block = this.lower_block(block, false);
95-
this.expr_block(block, ThinVec::new())
96-
})
93+
this.with_new_scopes(|this| this.lower_block_expr(block))
9794
})
9895
}
9996
ExprKind::Await(ref expr) => self.lower_expr_await(e.span, expr),
@@ -284,8 +281,7 @@ impl LoweringContext<'_> {
284281
let else_arm = self.arm(hir_vec![else_pat], P(else_expr));
285282

286283
// Handle then + scrutinee:
287-
let then_blk = self.lower_block(then, false);
288-
let then_expr = self.expr_block(then_blk, ThinVec::new());
284+
let then_expr = self.lower_block_expr(then);
289285
let (then_pat, scrutinee, desugar) = match cond.node {
290286
// `<pat> => <then>`:
291287
ExprKind::Let(ref pat, ref scrutinee) => {
@@ -335,8 +331,7 @@ impl LoweringContext<'_> {
335331
};
336332

337333
// Handle then + scrutinee:
338-
let then_blk = self.lower_block(body, false);
339-
let then_expr = self.expr_block(then_blk, ThinVec::new());
334+
let then_expr = self.lower_block_expr(body);
340335
let (then_pat, scrutinee, desugar, source) = match cond.node {
341336
ExprKind::Let(ref pat, ref scrutinee) => {
342337
// to:
@@ -356,7 +351,7 @@ impl LoweringContext<'_> {
356351
//
357352
// ```
358353
// 'label: loop {
359-
// match DropTemps($cond) {
354+
// match drop-temps { $cond } {
360355
// true => $body,
361356
// _ => break,
362357
// }
@@ -1310,7 +1305,7 @@ impl LoweringContext<'_> {
13101305
/// `{ let _t = $expr; _t }` but should provide better compile-time performance.
13111306
///
13121307
/// The drop order can be important in e.g. `if expr { .. }`.
1313-
fn expr_drop_temps(
1308+
pub(super) fn expr_drop_temps(
13141309
&mut self,
13151310
span: Span,
13161311
expr: P<hir::Expr>,

src/librustc/hir/lowering/item.rs

+40-8
Original file line numberDiff line numberDiff line change
@@ -1071,10 +1071,7 @@ impl LoweringContext<'_> {
10711071
}
10721072

10731073
fn lower_fn_body_block(&mut self, decl: &FnDecl, body: &Block) -> hir::BodyId {
1074-
self.lower_fn_body(decl, |this| {
1075-
let body = this.lower_block(body, false);
1076-
this.expr_block(body, ThinVec::new())
1077-
})
1074+
self.lower_fn_body(decl, |this| this.lower_block_expr(body))
10781075
}
10791076

10801077
pub(super) fn lower_const_body(&mut self, expr: &Expr) -> hir::BodyId {
@@ -1102,8 +1099,7 @@ impl LoweringContext<'_> {
11021099
// from:
11031100
//
11041101
// async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
1105-
// async move {
1106-
// }
1102+
// <body>
11071103
// }
11081104
//
11091105
// into:
@@ -1116,11 +1112,19 @@ impl LoweringContext<'_> {
11161112
// let <pattern> = __arg1;
11171113
// let __arg0 = __arg0;
11181114
// let <pattern> = __arg0;
1115+
// drop-temps { <body> } // see comments later in fn for details
11191116
// }
11201117
// }
11211118
//
11221119
// If `<pattern>` is a simple ident, then it is lowered to a single
11231120
// `let <pattern> = <pattern>;` statement as an optimization.
1121+
//
1122+
// Note that the body is embedded in `drop-temps`; an
1123+
// equivalent desugaring would be `return { <body>
1124+
// };`. The key point is that we wish to drop all the
1125+
// let-bound variables and temporaries created in the body
1126+
// (and its tail expression!) before we drop the
1127+
// parameters (c.f. rust-lang/rust#64512).
11241128
for (index, parameter) in decl.inputs.iter().enumerate() {
11251129
let parameter = this.lower_param(parameter);
11261130
let span = parameter.pat.span;
@@ -1219,8 +1223,36 @@ impl LoweringContext<'_> {
12191223
let async_expr = this.make_async_expr(
12201224
CaptureBy::Value, closure_id, None, body.span,
12211225
|this| {
1222-
let body = this.lower_block_with_stmts(body, false, statements);
1223-
this.expr_block(body, ThinVec::new())
1226+
// Create a block from the user's function body:
1227+
let user_body = this.lower_block_expr(body);
1228+
1229+
// Transform into `drop-temps { <user-body> }`, an expression:
1230+
let desugared_span = this.mark_span_with_reason(
1231+
DesugaringKind::Async,
1232+
user_body.span,
1233+
None,
1234+
);
1235+
let user_body = this.expr_drop_temps(
1236+
desugared_span,
1237+
P(user_body),
1238+
ThinVec::new(),
1239+
);
1240+
1241+
// As noted above, create the final block like
1242+
//
1243+
// ```
1244+
// {
1245+
// let $param_pattern = $raw_param;
1246+
// ...
1247+
// drop-temps { <user-body> }
1248+
// }
1249+
// ```
1250+
let body = this.block_all(
1251+
desugared_span,
1252+
statements.into(),
1253+
Some(P(user_body)),
1254+
);
1255+
this.expr_block(P(body), ThinVec::new())
12241256
});
12251257
(HirVec::from(parameters), this.expr(body.span, async_expr, ThinVec::new()))
12261258
})
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
// aux-build:arc_wake.rs
2+
// edition:2018
3+
// run-pass
4+
5+
#![allow(unused_variables)]
6+
7+
// Test the drop order for parameters relative to local variables and
8+
// temporaries created in the tail return expression of the function
9+
// body. In particular, check that this drop order is the same between
10+
// a `async fn` and an ordinary `fn`. See #64512.
11+
12+
extern crate arc_wake;
13+
14+
use arc_wake::ArcWake;
15+
use std::cell::RefCell;
16+
use std::future::Future;
17+
use std::sync::Arc;
18+
use std::rc::Rc;
19+
use std::task::Context;
20+
21+
struct EmptyWaker;
22+
23+
impl ArcWake for EmptyWaker {
24+
fn wake(self: Arc<Self>) {}
25+
}
26+
27+
#[derive(Debug, Eq, PartialEq)]
28+
enum DropOrder {
29+
Function,
30+
Val(&'static str),
31+
}
32+
33+
type DropOrderListPtr = Rc<RefCell<Vec<DropOrder>>>;
34+
35+
struct D(&'static str, DropOrderListPtr);
36+
37+
impl Drop for D {
38+
fn drop(&mut self) {
39+
self.1.borrow_mut().push(DropOrder::Val(self.0));
40+
}
41+
}
42+
43+
/// Check drop order of temporary "temp" as compared to `x`, `y`, and `z`.
44+
///
45+
/// Expected order:
46+
/// - `z`
47+
/// - temp
48+
/// - `y`
49+
/// - `x`
50+
async fn foo_async(x: D, _y: D) {
51+
let l = x.1.clone();
52+
let z = D("z", l.clone());
53+
l.borrow_mut().push(DropOrder::Function);
54+
helper_async(&D("temp", l)).await
55+
}
56+
57+
async fn helper_async(v: &D) { }
58+
59+
fn foo_sync(x: D, _y: D) {
60+
let l = x.1.clone();
61+
let z = D("z", l.clone());
62+
l.borrow_mut().push(DropOrder::Function);
63+
helper_sync(&D("temp", l))
64+
}
65+
66+
fn helper_sync(v: &D) { }
67+
68+
fn assert_drop_order_after_poll<Fut: Future<Output = ()>>(
69+
f: impl FnOnce(DropOrderListPtr) -> Fut,
70+
g: impl FnOnce(DropOrderListPtr),
71+
) {
72+
let empty = Arc::new(EmptyWaker);
73+
let waker = ArcWake::into_waker(empty);
74+
let mut cx = Context::from_waker(&waker);
75+
76+
let actual_order = Rc::new(RefCell::new(Vec::new()));
77+
let mut fut = Box::pin(f(actual_order.clone()));
78+
let r = fut.as_mut().poll(&mut cx);
79+
80+
assert!(match r {
81+
std::task::Poll::Ready(()) => true,
82+
_ => false,
83+
});
84+
85+
let expected_order = Rc::new(RefCell::new(Vec::new()));
86+
g(expected_order.clone());
87+
88+
assert_eq!(*actual_order.borrow(), *expected_order.borrow());
89+
}
90+
91+
fn main() {
92+
// Free functions (see doc comment on function for what it tests).
93+
assert_drop_order_after_poll(|l| foo_async(D("x", l.clone()), D("_y", l.clone())),
94+
|l| foo_sync(D("x", l.clone()), D("_y", l.clone())));
95+
}
+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// Regression test for Issue #64391. The goal here is that this
2+
// function compiles. In the past, due to incorrect drop order for
3+
// temporaries in the tail expression, we failed to compile this
4+
// example. The drop order itself is directly tested in
5+
// `drop-order/drop-order-for-temporary-in-tail-return-expr.rs`.
6+
//
7+
// check-pass
8+
// edition:2018
9+
10+
async fn add(x: u32, y: u32) -> u32 {
11+
async { x + y }.await
12+
}
13+
14+
fn main() { }

0 commit comments

Comments
 (0)