Skip to main content

psync_graph/
hoist.rs

1//! Exposing awaits that sit inside larger statements.
2//!
3//! An await in a `match` scrutinee, an `if` condition, or a call argument is evaluated before the
4//! rest of its statement anyway. Hoisting it into its own binding (`let __psync_s1 = x.await;`)
5//! keeps the evaluation order but turns it into a node that can overlap with other work, while
6//! the remainder of the statement stays where it was.
7
8use crate::classify::{Exits, is_place, is_pure};
9use proc_macro2::Ident;
10use quote::{ToTokens, format_ident};
11use syn::{Expr, Local, LocalInit, Stmt, parse::Parser, punctuated::Punctuated, spanned::Spanned};
12
13fn awaits(e: &Expr) -> bool {
14    Exits::of(e).awaits
15}
16
17/// Split `match e.await {..}`, `if let p = e.await {..}`, `if e.await {..}`, the same forms as a
18/// `let` initializer, and `let p = e.await else {..}` into `let __psync_sN = e.await;` and the
19/// statement reading `__psync_sN`.
20pub(crate) fn scrutinee(stmt: &Stmt, n: usize) -> Option<(Stmt, Stmt)> {
21    let name = format_ident!("__psync_s{}", n);
22    let take = |e: &mut Expr| -> Option<Expr> {
23        let slot = match e {
24            Expr::Match(m) => &mut m.expr,
25            Expr::If(i) => match &mut *i.cond {
26                Expr::Let(l) => &mut l.expr,
27                _ => &mut i.cond,
28            },
29            _ => return None,
30        };
31        awaits(slot).then(|| std::mem::replace(&mut **slot, syn::parse_quote!(#name)))
32    };
33    let mut rewritten = stmt.clone();
34    let value = match &mut rewritten {
35        Stmt::Expr(e, _) => take(e)?,
36        Stmt::Local(Local {
37            init:
38                Some(LocalInit {
39                    expr,
40                    diverge: None,
41                    ..
42                }),
43            ..
44        }) => take(expr)?,
45        // `let p = e.await else { .. };`: the initializer is the scrutinee.
46        Stmt::Local(Local {
47            init:
48                Some(LocalInit {
49                    expr,
50                    diverge: Some(_),
51                    ..
52                }),
53            ..
54        }) if awaits(expr) => std::mem::replace(&mut **expr, syn::parse_quote!(#name)),
55        _ => return None,
56    };
57    Some((
58        syn::parse_quote_spanned!(stmt.span()=> let #name = #value;),
59        rewritten,
60    ))
61}
62
63/// For loop fission: split `if c {..}` / `if let p = c {..}` / `match c {..}` whose branches
64/// await but whose condition `c` does not into `let __psync_cN = c;` and the statement reading it.
65pub(crate) fn condition(stmt: &Stmt, n: usize) -> Option<(Stmt, Stmt)> {
66    let name = format_ident!("__psync_c{}", n);
67    let Stmt::Expr(e, semi) = stmt else {
68        return None;
69    };
70    let mut e = e.clone();
71    let slot = match &mut e {
72        Expr::Match(m) => &mut m.expr,
73        Expr::If(i) => match &mut *i.cond {
74            Expr::Let(l) => &mut l.expr,
75            _ => &mut i.cond,
76        },
77        _ => return None,
78    };
79    if awaits(slot) || is_pure(slot) {
80        return None;
81    }
82    let value = std::mem::replace(&mut **slot, syn::parse_quote!(#name));
83    Some((
84        syn::parse_quote_spanned!(stmt.span()=> let #name = #value;),
85        Stmt::Expr(e, *semi),
86    ))
87}
88
89fn is_compound_assign(op: &syn::BinOp) -> bool {
90    use syn::BinOp::*;
91    matches!(
92        op,
93        AddAssign(_)
94            | SubAssign(_)
95            | MulAssign(_)
96            | DivAssign(_)
97            | RemAssign(_)
98            | BitXorAssign(_)
99            | BitAndAssign(_)
100            | BitOrAssign(_)
101            | ShlAssign(_)
102            | ShrAssign(_)
103    )
104}
105
106/// Hoist the awaited operands of a call, method call, assignment, array, tuple or `vec!` into
107/// bindings, together with any earlier operands that are not pure, so they still evaluate in
108/// order. Also hoists an awaited method receiver (`x.await?.items()`), which evaluates first.
109/// `fresh` numbers the new bindings.
110pub(crate) fn operands(stmt: &Stmt, fresh: &mut usize) -> Option<(Vec<Stmt>, Stmt)> {
111    let mut rewritten = stmt.clone();
112    let mut target: &mut Expr = match &mut rewritten {
113        Stmt::Expr(e, _) => e,
114        Stmt::Local(Local {
115            init:
116                Some(LocalInit {
117                    expr,
118                    diverge: None,
119                    ..
120                }),
121            ..
122        }) => expr,
123        _ => return None,
124    };
125    if let Expr::Try(t) = target {
126        target = &mut t.expr;
127    }
128    let mut vec_args: Option<Punctuated<Expr, syn::Token![,]>> = None;
129    let operands: Vec<&mut Expr> = match target {
130        Expr::MethodCall(m) if !is_place(&m.receiver) && awaits(&m.receiver) => {
131            vec![&mut *m.receiver]
132        }
133        Expr::MethodCall(m) if is_place(&m.receiver) => m.args.iter_mut().collect(),
134        Expr::Call(c) if matches!(&*c.func, Expr::Path(_)) => c.args.iter_mut().collect(),
135        Expr::Assign(a) if is_place(&a.left) => vec![&mut *a.right],
136        // `x += y`: with a side-effect-free place on the left, `y` may be evaluated first.
137        Expr::Binary(b) if is_compound_assign(&b.op) && is_place(&b.left) => vec![&mut *b.right],
138        Expr::Array(a) => a.elems.iter_mut().collect(),
139        Expr::Tuple(t) => t.elems.iter_mut().collect(),
140        Expr::Macro(m) if m.mac.path.is_ident("vec") => {
141            vec_args = Punctuated::parse_terminated
142                .parse2(m.mac.tokens.clone())
143                .ok();
144            vec_args.as_mut()?.iter_mut().collect()
145        }
146        _ => return None,
147    };
148    let last = operands.iter().rposition(|e| awaits(e))?;
149    let mut lets = Vec::new();
150    for e in operands.into_iter().take(last + 1) {
151        if is_pure(e) && !awaits(e) {
152            continue;
153        }
154        *fresh += 1;
155        let h: Ident = format_ident!("__psync_h{}", *fresh);
156        let value = std::mem::replace(e, syn::parse_quote!(#h));
157        lets.push(syn::parse_quote_spanned!(stmt.span()=> let #h = #value;));
158    }
159    if lets.is_empty() {
160        return None;
161    }
162    if let (Some(args), Expr::Macro(m)) = (vec_args, &mut *target) {
163        m.mac.tokens = args.to_token_stream();
164    }
165    Some((lets, rewritten))
166}