Skip to main content

psync_graph/
rewrite.rs

1//! The rewriting pass.
2//!
3//! [`Rewriter`] walks the function with `syn`'s `VisitMut`, innermost blocks first. In every block
4//! of async code it
5//!
6//! 1. hands `for` and `while` loops to [`crate::loops`],
7//! 2. exposes awaits hidden inside larger statements ([`Rewriter::expose_awaits`]),
8//! 3. splits the block into regions at barriers and schedules each region
9//!    ([`crate::schedule`]).
10//!
11//! A block whose regions all stay sequential is emitted exactly as written.
12
13use crate::access::{Set, mentions};
14use crate::classify::{Class, Exits, Node, Scope, classify, line_of};
15use crate::effects::{Target, value_target};
16use crate::schedule::{emit, plan};
17use crate::{Options, Report, hoist};
18use quote::{ToTokens, format_ident};
19use syn::{Block, Expr, Local, Stmt, spanned::Spanned, visit_mut::VisitMut};
20
21/// How many times a statement may be split while exposing nested awaits.
22const MAX_HOIST_DEPTH: usize = 8;
23
24/// The state of one `#[psync::graph]` expansion.
25pub(crate) struct Rewriter<'a> {
26    pub options: &'a Options,
27    /// Mutability facts and hints for the whole function.
28    pub scope: Scope,
29    /// Everything analyzed so far, for `explain` and tooling.
30    pub report: Report,
31    /// Inside an `async fn`, async block or async closure: only there do awaits occur.
32    pub in_async: bool,
33    /// Counter that keeps generated names unique within the function.
34    pub fresh: usize,
35    /// Why the last loop statement could not run ahead, for the loop's report.
36    pub refusal: Option<String>,
37    /// How the last prefetched loop's per-item files are kept apart, for its report.
38    pub loop_check: String,
39    /// The source lines of the last prefetched loop's prefix, for its report.
40    pub loop_lines: Vec<(usize, usize)>,
41}
42
43impl VisitMut for Rewriter<'_> {
44    fn visit_expr_async_mut(&mut self, e: &mut syn::ExprAsync) {
45        // Inside an async block, even one in a synchronous function, awaits are what overlap.
46        let outer = std::mem::replace(&mut self.in_async, true);
47        let outer_sync = std::mem::replace(&mut self.scope.sync, false);
48        syn::visit_mut::visit_expr_async_mut(self, e);
49        self.in_async = outer;
50        self.scope.sync = outer_sync;
51    }
52
53    fn visit_expr_closure_mut(&mut self, e: &mut syn::ExprClosure) {
54        let outer = std::mem::replace(&mut self.in_async, e.asyncness.is_some());
55        let outer_sync = std::mem::replace(&mut self.scope.sync, false);
56        syn::visit_mut::visit_expr_closure_mut(self, e);
57        self.in_async = outer;
58        self.scope.sync = outer_sync;
59    }
60
61    // Nested functions are separate code; they need their own attribute.
62    fn visit_item_mut(&mut self, _: &mut syn::Item) {}
63
64    fn visit_block_mut(&mut self, block: &mut Block) {
65        let mut stmts = Vec::with_capacity(block.stmts.len());
66        for mut stmt in std::mem::take(&mut block.stmts) {
67            match &mut stmt {
68                // Loops are rewritten from their original bodies (the loop code visits the parts
69                // it keeps); other statements have their inner blocks rewritten first.
70                // Loops of synchronous code are not prefetched yet.
71                // A baseline that does not rewrite loops keeps them as written (a barrier).
72                Stmt::Expr(Expr::ForLoop(f), semi)
73                    if self.in_async && !self.scope.sync && self.rewrites_loops() =>
74                {
75                    self.visit_expr_mut(&mut f.expr);
76                    if let Some(rewritten) = self.rewrite_loop(f) {
77                        stmts.push(Stmt::Expr(rewritten, *semi));
78                        continue;
79                    }
80                    self.visit_block_mut(&mut f.body);
81                }
82                Stmt::Expr(Expr::While(w), semi)
83                    if self.in_async && !self.scope.sync && self.rewrites_loops() =>
84                {
85                    if let Some(rewritten) = self.rewrite_while(w) {
86                        stmts.push(Stmt::Expr(rewritten, *semi));
87                        continue;
88                    }
89                    self.visit_stmt_mut(&mut stmt);
90                }
91                _ => self.visit_stmt_mut(&mut stmt),
92            }
93            stmts.push(stmt);
94        }
95        block.stmts = if self.in_async {
96            self.rewrite_stmts(stmts)
97        } else {
98            stmts
99        };
100    }
101}
102
103impl Rewriter<'_> {
104    /// Whether loops are rewritten: always, except under `baseline = resync`.
105    fn rewrites_loops(&self) -> bool {
106        self.options.baseline != Some(crate::Baseline::Resync)
107    }
108
109    /// A fresh number for generated names.
110    pub(crate) fn next(&mut self) -> usize {
111        self.fresh += 1;
112        self.fresh
113    }
114
115    /// Rewrite one block's statements, or return them unchanged if nothing becomes concurrent.
116    fn rewrite_stmts(&mut self, stmts: Vec<Stmt>) -> Vec<Stmt> {
117        let tail_hoisted = self.hoist_tail(stmts.clone());
118        let exposed = self.expose_awaits(tail_hoisted);
119        let before = self.report.regions.len();
120        let out = self.schedule_block(exposed);
121        if self.report.regions[before..].iter().any(|r| r.changed) {
122            out
123        } else {
124            stmts
125        }
126    }
127
128    /// An awaited block value (`foo().await?` last) becomes `let t = foo().await?; t`, so the await
129    /// can overlap earlier work while the value still comes last.
130    fn hoist_tail(&mut self, mut stmts: Vec<Stmt>) -> Vec<Stmt> {
131        let Some(Stmt::Expr(tail, None)) = stmts.last() else {
132            return stmts;
133        };
134        let as_statement = Stmt::Expr(tail.clone(), Some(Default::default()));
135        let movable =
136            matches!(classify(&as_statement, &self.scope, false), Class::Node(ref n) if !n.effect);
137        if Exits::of(tail).awaits && movable {
138            let value = tail.clone();
139            let name = format_ident!("__psync_t{}", self.next());
140            stmts.pop();
141            stmts.push(syn::parse_quote_spanned!(value.span()=> let #name = #value;));
142            stmts.push(Stmt::Expr(syn::parse_quote!(#name), None));
143        }
144        stmts
145    }
146
147    /// Split statements that hide an await inside other work (a `match` scrutinee, a call
148    /// argument, a method receiver, the leading work of an `if` branch) into a binding of the
149    /// awaited value and the rest of the statement, repeatedly, since a hoisted value may itself
150    /// hide an await.
151    fn expose_awaits(&mut self, stmts: Vec<Stmt>) -> Vec<Stmt> {
152        let mut out = Vec::with_capacity(stmts.len());
153        let mut work: Vec<(Stmt, usize)> = stmts.into_iter().rev().map(|s| (s, 0)).collect();
154        while let Some((stmt, depth)) = work.pop() {
155            let hides_await = match classify(&stmt, &self.scope, false) {
156                // A binding hides an await when its value only contains one: in
157                // `let t = combine(a, f().await);` the await need not wait for `a`.
158                Class::Node(n) => n.awaits && (n.effect || !awaited_value(&stmt)),
159                Class::Barrier(_) => Exits::of_stmt(&stmt).awaits,
160            };
161            if hides_await && depth < MAX_HOIST_DEPTH {
162                let n = self.next();
163                let split = hoist::scrutinee(&stmt, n)
164                    .map(|(value, rest)| (vec![value], rest))
165                    .or_else(|| hoist::operands(&stmt, &mut self.fresh))
166                    // Work moved out of an `if` crosses a branch, which a baseline does not.
167                    .or_else(|| {
168                        self.rewrites_loops()
169                            .then(|| self.hoist_branch(&stmt))
170                            .flatten()
171                            .map(|(g, rest)| (vec![g], rest))
172                    });
173                if let Some((values, rest)) = split {
174                    work.push((rest, depth + 1));
175                    work.extend(values.into_iter().rev().map(|v| (v, depth + 1)));
176                    continue;
177                }
178            }
179            out.push(stmt);
180        }
181        out
182    }
183
184    /// Split a block into regions at barriers and schedule each region.
185    fn schedule_block(&mut self, stmts: Vec<Stmt>) -> Vec<Stmt> {
186        let mentions: Vec<Set> = stmts
187            .iter()
188            .map(|s| mentions(s.to_token_stream()))
189            .collect();
190        let mut out = Vec::new();
191        let mut region: Vec<(usize, Node)> = Vec::new();
192        let last = stmts.len().saturating_sub(1);
193        // What the block's immutable bindings name, for effects whose target is a binding:
194        // `let p = dir.join("a.json"); .. fs::write(&p, ..)` writes the file `dir/a.json`.
195        let mut values: std::collections::HashMap<String, Target> = Default::default();
196        for (index, stmt) in stmts.into_iter().enumerate() {
197            // The block's final expression is its value, so it stays last.
198            let class = if index == last && matches!(stmt, Stmt::Expr(_, None)) {
199                // A loop psync already rewrote is reported as a loop, and its generated tokens
200                // carry no line of their own.
201                let generated = stmt.to_token_stream().to_string().contains("__psync");
202                let awaits = Exits::of_stmt(&stmt).awaits && !generated;
203                Class::Barrier(
204                    awaits.then(|| format!("line {}: the block's value", line_of(stmt.span()))),
205                )
206            } else {
207                classify(&stmt, &self.scope, false)
208            };
209            let class = match class {
210                Class::Node(mut n) => {
211                    let inner = crate::classify::inner_bindings(&n.stmt);
212                    for e in &mut n.effects {
213                        if let Some(name) = e.target.single_name()
214                            && !inner.contains(name)
215                            && let Some(t) = values.get(name)
216                        {
217                            e.target = t.clone();
218                        }
219                    }
220                    Class::Node(n)
221                }
222                barrier => barrier,
223            };
224            // ReSynchronizer moves nothing across a control-flow construct (its ยง4.6): under the
225            // baseline, an `if`, `match` or loop is a barrier even when psync could order it.
226            let class = match class {
227                Class::Node(_) if !self.rewrites_loops() && is_control_flow(&stmt) => {
228                    Class::Barrier(None)
229                }
230                class => class,
231            };
232            bind_values(&mut values, &stmt, &self.scope.mutable);
233            match class {
234                Class::Node(n) => region.push((index, *n)),
235                Class::Barrier(why) => {
236                    // Generated code (already-rewritten loops) is not worth reporting again.
237                    if let Some(why) = why.filter(|w| !w.contains("__psync")) {
238                        self.report.barriers.push(why);
239                    }
240                    out.extend(self.schedule_region(std::mem::take(&mut region), &mentions));
241                    out.push(stmt);
242                }
243            }
244        }
245        out.extend(self.schedule_region(region, &mentions));
246        out
247    }
248
249    /// Schedule one region; a region with fewer than two awaits has nothing to overlap.
250    fn schedule_region(&mut self, region: Vec<(usize, Node)>, mentions: &[Set]) -> Vec<Stmt> {
251        if region.iter().filter(|(_, n)| n.awaits).count() < 2 {
252            return region.into_iter().map(|(_, n)| n.stmt).collect();
253        }
254        let (positions, mut nodes): (Vec<usize>, Vec<Node>) = region.into_iter().unzip();
255        let baseline = self.options.baseline == Some(crate::Baseline::Resync);
256        if baseline {
257            crate::effects::per_environment(&mut nodes);
258        }
259        // What must stay ordered: under `owned_files`, any two file effects (one file may have
260        // two spellings); otherwise, what the tokens show.
261        let strict = match self.options.owned_files {
262            true => crate::gates::widen_files(&nodes),
263            false => nodes.clone(),
264        };
265        // Computed targets the tokens cannot tell apart are compared at run time instead, in
266        // asynchronous code (a `Gate`) and in synchronous code (a `SyncGate`, which blocks).
267        let relaxed = (!baseline)
268            .then(|| {
269                crate::gates::relax(
270                    &nodes,
271                    &strict,
272                    &self.scope.mutable,
273                    &mut self.fresh,
274                    &crate::gates::Compare {
275                        krate: &self.options.krate,
276                        owned_files: self.options.owned_files,
277                    },
278                )
279            })
280            .flatten();
281        let (plan, gates, prelude) = match relaxed {
282            Some((plan, gates, prelude)) => (plan, gates, prelude),
283            None => (plan(&strict), Vec::new(), Vec::new()),
284        };
285        let mut report = plan.report.clone();
286        report.runtime_checks = gates.len();
287        self.report.regions.push(report);
288        if !plan.report.changed {
289            return nodes.into_iter().map(|n| n.stmt).collect();
290        }
291        let mut out = prelude;
292        out.extend(emit(
293            self.scope.sync,
294            &self.options.krate,
295            &self.scope.fresh,
296            nodes,
297            &plan,
298            &positions,
299            mentions,
300            &mut self.fresh,
301            &gates,
302        ));
303        out
304    }
305}
306
307/// A statement that is, or binds, a branch or a loop.
308fn is_control_flow(stmt: &Stmt) -> bool {
309    let expr = match stmt {
310        Stmt::Expr(e, _) => e,
311        Stmt::Local(Local {
312            init: Some(init), ..
313        }) => &init.expr,
314        _ => return false,
315    };
316    matches!(
317        expr,
318        Expr::If(_) | Expr::Match(_) | Expr::ForLoop(_) | Expr::While(_) | Expr::Loop(_)
319    )
320}
321
322/// Record what `stmt`'s bindings name. A `let` of one immutable name binds the target its value
323/// names, if that says more than "anything" and depends on no `mut` binding (so it is the same
324/// value wherever the name is used). Any binding forgets what was known of its name, and of the
325/// values computed from it (they were computed from the shadowed one).
326fn bind_values(values: &mut std::collections::HashMap<String, Target>, stmt: &Stmt, mutable: &Set) {
327    let Stmt::Local(local) = stmt else {
328        return;
329    };
330    let mut bound = Vec::new();
331    crate::classify::pat_idents(&local.pat, &mut bound);
332    for (name, _) in &bound {
333        let name = name.to_string();
334        values.remove(&name);
335        values.retain(|_, t| t.names().is_none_or(|n| !n.contains(&name)));
336    }
337    let syn::Pat::Ident(p) = &local.pat else {
338        return;
339    };
340    let Some(init) = &local.init else {
341        return;
342    };
343    if p.mutability.is_some() || p.by_ref.is_some() || p.subpat.is_some() || init.diverge.is_some()
344    {
345        return;
346    }
347    let t = value_target(&init.expr);
348    if t.informative() && t.names().is_none_or(|n| n.is_disjoint(mutable)) {
349        values.insert(p.ident.to_string(), t);
350    }
351}
352
353/// Whether a `let`'s value is itself awaited (`x.await`, `x.await?`, `x.await.len()`), so the
354/// binding is already a node of its own await and there is nothing to expose.
355fn awaited_value(stmt: &Stmt) -> bool {
356    let Stmt::Local(syn::Local {
357        init: Some(init), ..
358    }) = stmt
359    else {
360        return true;
361    };
362    let mut e = &*init.expr;
363    loop {
364        match e {
365            Expr::Await(_) => return true,
366            Expr::Try(t) => e = &t.expr,
367            Expr::Paren(p) => e = &p.expr,
368            Expr::MethodCall(m) => e = &m.receiver,
369            Expr::Field(f) => e = &f.base,
370            _ => return false,
371        }
372    }
373}