Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adjust desugaring for async fn to correct drop order #64525

Merged
merged 7 commits into from
Sep 17, 2019
Merged
Show file tree
Hide file tree
Changes from 3 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
12 changes: 2 additions & 10 deletions src/librustc/hir/lowering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2682,12 +2682,8 @@ impl<'a> LoweringContext<'a> {
bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect()
}

fn lower_block_with_stmts(
&mut self,
b: &Block,
targeted_by_break: bool,
mut stmts: Vec<hir::Stmt>,
) -> P<hir::Block> {
fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
let mut stmts = vec![];
let mut expr = None;

for (index, stmt) in b.stmts.iter().enumerate() {
Expand All @@ -2712,10 +2708,6 @@ impl<'a> LoweringContext<'a> {
})
}

fn lower_block(&mut self, b: &Block, targeted_by_break: bool) -> P<hir::Block> {
self.lower_block_with_stmts(b, targeted_by_break, vec![])
}

fn lower_pat(&mut self, p: &Pat) -> P<hir::Pat> {
let node = match p.node {
PatKind::Wild => hir::PatKind::Wild,
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/hir/lowering/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1310,7 +1310,7 @@ impl LoweringContext<'_> {
/// `{ let _t = $expr; _t }` but should provide better compile-time performance.
///
/// The drop order can be important in e.g. `if expr { .. }`.
fn expr_drop_temps(
pub(super) fn expr_drop_temps(
&mut self,
span: Span,
expr: P<hir::Expr>,
Expand Down
40 changes: 38 additions & 2 deletions src/librustc/hir/lowering/item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1219,8 +1219,44 @@ impl LoweringContext<'_> {
let async_expr = this.make_async_expr(
CaptureBy::Value, closure_id, None, body.span,
|this| {
let body = this.lower_block_with_stmts(body, false, statements);
this.expr_block(body, ThinVec::new())
// Create a block from the user's function body:
let user_body = this.lower_block(body, false);
let user_body = this.expr_block(user_body, ThinVec::new());
nikomatsakis marked this conversation as resolved.
Show resolved Hide resolved

// Transform into `drop-temps { <user-body> }`, an expression:
let desugared_span = this.mark_span_with_reason(
DesugaringKind::Async,
user_body.span,
None,
);
let user_body = this.expr_drop_temps(
desugared_span,
P(user_body),
ThinVec::new(),
);

// Create a block like
nikomatsakis marked this conversation as resolved.
Show resolved Hide resolved
//
// ```
// {
// let $param_pattern = $raw_param;
// ...
// drop-temps { <user-body> }
nikomatsakis marked this conversation as resolved.
Show resolved Hide resolved
// }
// ```
//
// This construction is carefully calibrated to
// get the drop-order correct. In particular, the
// drop-temps ensures that any temporaries in the
// tail expression of `<user-body>` are dropped
// *before* the parameters are dropped (see
// rust-lang/rust#64512).
let body = this.block_all(
desugared_span,
statements.into(),
Some(P(user_body)),
);
this.expr_block(P(body), ThinVec::new())
});
(HirVec::from(parameters), this.expr(body.span, async_expr, ThinVec::new()))
})
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// aux-build:arc_wake.rs
// edition:2018
// run-pass

#![allow(unused_variables)]

// Test that the drop order for parameters in a fn and async fn matches up. Also test that
nikomatsakis marked this conversation as resolved.
Show resolved Hide resolved
// parameters (used or unused) are not dropped until the async fn completes execution.
nikomatsakis marked this conversation as resolved.
Show resolved Hide resolved
// See also #54716.

extern crate arc_wake;

use arc_wake::ArcWake;
use std::cell::RefCell;
use std::future::Future;
use std::sync::Arc;
use std::rc::Rc;
use std::task::Context;

struct EmptyWaker;

impl ArcWake for EmptyWaker {
fn wake(self: Arc<Self>) {}
}

#[derive(Debug, Eq, PartialEq)]
enum DropOrder {
Function,
Val(&'static str),
}

type DropOrderListPtr = Rc<RefCell<Vec<DropOrder>>>;

struct D(&'static str, DropOrderListPtr);

impl Drop for D {
fn drop(&mut self) {
self.1.borrow_mut().push(DropOrder::Val(self.0));
}
}

/// Check drop order of temporary "temp" as compared to x, y, and z.
nikomatsakis marked this conversation as resolved.
Show resolved Hide resolved
///
/// Expected order:
/// - z
nikomatsakis marked this conversation as resolved.
Show resolved Hide resolved
/// - temp
/// - y
nikomatsakis marked this conversation as resolved.
Show resolved Hide resolved
/// - x
nikomatsakis marked this conversation as resolved.
Show resolved Hide resolved
async fn foo_async(x: D, _y: D) {
let l = x.1.clone();
let z = D("z", l.clone());
l.borrow_mut().push(DropOrder::Function);
helper_async(&D("temp", l)).await
}

async fn helper_async(v: &D) { }

fn foo_sync(x: D, _y: D) {
let l = x.1.clone();
let z = D("z", l.clone());
l.borrow_mut().push(DropOrder::Function);
helper_sync(&D("temp", l))
}

fn helper_sync(v: &D) { }

fn assert_drop_order_after_poll<Fut: Future<Output = ()>>(
f: impl FnOnce(DropOrderListPtr) -> Fut,
g: impl FnOnce(DropOrderListPtr),
) {
let empty = Arc::new(EmptyWaker);
let waker = ArcWake::into_waker(empty);
let mut cx = Context::from_waker(&waker);

let actual_order = Rc::new(RefCell::new(Vec::new()));
let mut fut = Box::pin(f(actual_order.clone()));
let r = fut.as_mut().poll(&mut cx);

assert!(match r {
std::task::Poll::Ready(()) => true,
_ => false,
});

let expected_order = Rc::new(RefCell::new(Vec::new()));
g(expected_order.clone());

assert_eq!(*actual_order.borrow(), *expected_order.borrow());
}

fn main() {
// Free functions (see doc comment on function for what it tests).
assert_drop_order_after_poll(|l| foo_async(D("x", l.clone()), D("_y", l.clone())),
|l| foo_sync(D("x", l.clone()), D("_y", l.clone())));
}
14 changes: 14 additions & 0 deletions src/test/ui/async-await/issue-64391.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Regression test for Issue #64391. The goal here is that this
// function compiles. In the past, due to incorrect drop order for
// temporaries in the tail expression, we failed to compile this
// example. The drop order itself is directly tested in
// `drop-order/drop-order-for-temporary-in-tail-return-expr.rs`.
//
// check-pass
// edition:2018

async fn add(x: u32, y: u32) -> u32 {
async { x + y }.await
}

fn main() { }