Skip to main content

psync_graph/
loops.rs

1//! Running loop iterations ahead.
2//!
3//! **Prefetch.** When the awaited statements at the front of a `for` loop body (its *prefix*) only
4//! touch per-iteration data, psync starts the prefixes of up to `bound` later iterations while the
5//! rest of the body still runs in order:
6//!
7//! ```text
8//! for x in xs { let y = fetch(x).await?; out.push(y); }
9//! // becomes
10//! let each = over(&xs, async |x| { <prefix, exits recorded> });
11//! let items = join_all_bounded(xs.into_iter().map(|x| each(x)).collect::<Vec<_>>(), bound).await;
12//! for (exits.., bindings) in items { <re-raise exits>; let (x, y) = bindings; out.push(y); }
13//! ```
14//!
15//! **Guards.** `if c { .. }` around awaited work becomes a prefix binding
16//! `let g = if c { Some(<work>) } else { None };`, and an early exit `if c { ..; continue; }`
17//! followed by awaited work becomes `let g = if c { None } else { Some(<work>) };` (with `c`
18//! pure), so the work runs ahead exactly for the items that reach it.
19//!
20//! **Fission.** When the body starts with statements that update loop-carried state without
21//! awaiting (dedupe sets, map removals, permit reservations), those run first for every item in a
22//! plain loop, and the remaining body is prefetched. Exits in that first loop that would end the
23//! whole loop (`return`, `?`, `break` to an outer loop) are deferred until the items before them
24//! have been processed, which is where sequential code performs them.
25
26use crate::access::{Access, Set, conflict, mentions, root, scan};
27use crate::classify::{
28    Class, Exits, Node, bindings_in, classify, is_psync_attr, line_of, pat_has_ref, pat_idents,
29};
30use crate::effects::{self, Effect};
31use crate::exits::ExitRewriter;
32use crate::rewrite::Rewriter;
33use crate::schedule::chain_code;
34use crate::{LoopReport, hoist};
35use proc_macro2::{Ident, TokenStream};
36use quote::{ToTokens, format_ident, quote};
37use syn::{Block, Expr, ExprForLoop, Stmt, spanned::Spanned, visit_mut::VisitMut};
38
39/// What a loop's prefix may touch.
40struct LoopScope {
41    /// Per-iteration names: the loop pattern and everything bound inside the body.
42    local: Set,
43    /// Places the body writes that outlive an iteration.
44    carried: Set,
45    /// `#[psync::independent]`: the programmer asserts iterations do not depend on each other.
46    independent: bool,
47    /// The body may end the whole loop (`?`, `return`, `break`): later iterations that run ahead
48    /// may be ones sequential code never reaches.
49    terminates: bool,
50    /// `#[psync::speculate]` on the loop (or `speculate` on the function): writes may run ahead
51    /// anyway.
52    speculate: bool,
53    /// Writes in the body whose target is the same in every iteration (not computed from the
54    /// item): they order every effect on the same resource across iterations.
55    carried_effects: Vec<Effect>,
56}
57
58impl LoopScope {
59    fn new(
60        rw: &Rewriter,
61        pattern: &[(Ident, bool)],
62        body: &Block,
63        attrs: &[syn::Attribute],
64    ) -> Self {
65        let mut local: Set = pattern.iter().map(|(i, _)| i.to_string()).collect();
66        local.extend(bindings_in(body));
67        let mut acc = Access::default();
68        scan(
69            body.to_token_stream(),
70            &rw.scope.mutable,
71            &rw.scope.handles,
72            &mut acc,
73        );
74        let carried = acc
75            .wpaths
76            .into_iter()
77            .filter(|p| !is_local(&local, p))
78            .collect();
79        let independent = attrs.iter().any(|a| is_psync_attr(a, "independent"));
80        let speculate =
81            rw.scope.effects.speculate || attrs.iter().any(|a| is_psync_attr(a, "speculate"));
82        let carried_effects = body_effects(&body.stmts, &rw.scope.effects)
83            .into_iter()
84            .filter(|e| e.writes() && !e.target.mentions_any(&local))
85            .collect();
86        Self {
87            local,
88            carried,
89            independent,
90            // A panic ends the loop too (facts from the compiler).
91            terminates: terminates(body)
92                || body
93                    .stmts
94                    .iter()
95                    .any(|s| effects::of_stmt(s, &rw.scope.effects).panics),
96            speculate,
97            carried_effects,
98        }
99    }
100
101    /// The scope of straight-line code: there are no earlier iterations to run ahead of, so only
102    /// the order within the block (which the scheduler and `take_prefix` keep) matters.
103    fn straight() -> Self {
104        Self {
105            local: Set::new(),
106            carried: Set::new(),
107            independent: true,
108            terminates: false,
109            speculate: true,
110            carried_effects: Vec::new(),
111        }
112    }
113
114    /// Why `n` cannot run ahead of earlier iterations, if it cannot.
115    fn refuses(&self, n: &Node) -> Option<String> {
116        // Later items' writes would run before an earlier item ends the loop.
117        if self.terminates
118            && !self.speculate
119            && !n.speculate
120            && let Some(w) = n.effects.iter().find(|e| e.writes())
121        {
122            return Some(format!(
123                "would {} for later items before knowing whether an earlier item ends the loop \
124                 (`#[psync::speculate]` allows it)",
125                w.describe()
126            ));
127        }
128        if self.independent {
129            return None;
130        }
131        // A write whose target does not depend on the item hits the same resource every time.
132        if let Some(w) = n
133            .effects
134            .iter()
135            .find(|e| e.writes() && !e.target.mentions_any(&self.local))
136        {
137            return Some(format!("would {} in every iteration at once", w.describe()));
138        }
139        if let Some(why) = crate::effects::conflicts(&n.effects, &self.carried_effects) {
140            return Some(format!("{why}, which every iteration performs"));
141        }
142        if let Some(w) = n.acc.wpaths.iter().find(|p| !is_local(&self.local, p)) {
143            return Some(format!("writes `{w}`, which outlives the iteration"));
144        }
145        conflict(&self.carried, &n.acc.rpaths)
146            .map(|c| format!("reads `{c}`, which the loop body writes"))
147    }
148}
149
150/// The effects of a run of statements.
151fn body_effects(stmts: &[Stmt], config: &effects::Config) -> Vec<Effect> {
152    stmts
153        .iter()
154        .flat_map(|s| effects::of_stmt(s, config).effects)
155        .collect()
156}
157
158/// True when `body` may end the loop it belongs to: a `?` or `return` anywhere outside closures
159/// and async blocks, a `break` that leaves it, or a `continue` aimed at an outer loop.
160fn terminates(body: &Block) -> bool {
161    struct V {
162        depth: usize,
163        labels: Vec<String>,
164        found: bool,
165    }
166    impl V {
167        fn leaves(&self, label: Option<&syn::Lifetime>) -> bool {
168            match label {
169                Some(l) => !self.labels.contains(&l.ident.to_string()),
170                None => self.depth == 0,
171            }
172        }
173        fn nested(&mut self, label: Option<&syn::Label>, f: impl FnOnce(&mut Self)) {
174            if let Some(l) = label {
175                self.labels.push(l.name.ident.to_string());
176            }
177            self.depth += 1;
178            f(self);
179            self.depth -= 1;
180            if label.is_some() {
181                self.labels.pop();
182            }
183        }
184    }
185    impl<'ast> syn::visit::Visit<'ast> for V {
186        fn visit_expr_try(&mut self, e: &'ast syn::ExprTry) {
187            self.found = true;
188            syn::visit::visit_expr_try(self, e);
189        }
190        fn visit_expr_return(&mut self, _: &'ast syn::ExprReturn) {
191            self.found = true;
192        }
193        fn visit_expr_break(&mut self, e: &'ast syn::ExprBreak) {
194            self.found |= self.leaves(e.label.as_ref());
195        }
196        fn visit_expr_continue(&mut self, e: &'ast syn::ExprContinue) {
197            // A plain `continue` only ends its own iteration.
198            self.found |= e.label.is_some() && self.leaves(e.label.as_ref());
199        }
200        fn visit_expr_for_loop(&mut self, e: &'ast ExprForLoop) {
201            self.visit_expr(&e.expr);
202            self.nested(e.label.as_ref(), |v| v.visit_block(&e.body));
203        }
204        fn visit_expr_while(&mut self, e: &'ast syn::ExprWhile) {
205            self.visit_expr(&e.cond);
206            self.nested(e.label.as_ref(), |v| v.visit_block(&e.body));
207        }
208        fn visit_expr_loop(&mut self, e: &'ast syn::ExprLoop) {
209            self.nested(e.label.as_ref(), |v| v.visit_block(&e.body));
210        }
211        fn visit_expr_closure(&mut self, _: &'ast syn::ExprClosure) {}
212        fn visit_expr_async(&mut self, _: &'ast syn::ExprAsync) {}
213        fn visit_item(&mut self, _: &'ast syn::Item) {}
214        fn visit_macro(&mut self, m: &'ast syn::Macro) {
215            // `bail!`, `ensure!` and `?` inside macros return early too.
216            let name = crate::classify::macro_name(m);
217            self.found |= matches!(
218                name.as_str(),
219                "bail" | "ensure" | "try" | "return_err" | "fail"
220            );
221        }
222    }
223    let mut v = V {
224        depth: 0,
225        labels: Vec::new(),
226        found: false,
227    };
228    syn::visit::Visit::visit_block(&mut v, body);
229    v.found
230}
231
232/// Whether a branch ends in a value (`if c { f().await } else { x }`), which cannot be moved into
233/// a hoisted chain. Loops and `if`s without `else` at the end are statements of type `()`.
234fn yields_value(branch: &Block) -> bool {
235    match branch.stmts.last() {
236        Some(Stmt::Expr(Expr::ForLoop(_) | Expr::While(_), None)) => false,
237        Some(Stmt::Expr(Expr::If(i), None)) => i.else_branch.is_some(),
238        Some(Stmt::Expr(_, None)) => true,
239        _ => false,
240    }
241}
242
243fn is_local(local: &Set, path: &str) -> bool {
244    local.contains(root(path)) || root(path).starts_with("__psync")
245}
246
247/// `for a in xs { for b in f(a) { body } }` as `for (a, b) in <pairs> { body }`, when that is the
248/// same loop: the outer body is only the inner loop, neither loop is labeled, `body` has no
249/// `break` (which would end only the inner loop), and the outer item is a plain binding (it is
250/// paired with every inner item, so it must be `Copy`, such as a reference; otherwise the
251/// generated code does not compile rather than changing meaning).
252fn flatten(f: &ExprForLoop) -> Option<ExprForLoop> {
253    let [Stmt::Expr(Expr::ForLoop(inner), _)] = &f.body.stmts[..] else {
254        return None;
255    };
256    let syn::Pat::Ident(outer) = &*f.pat else {
257        return None;
258    };
259    if f.label.is_some() || inner.label.is_some() || outer.by_ref.is_some() || breaks(&inner.body) {
260        return None;
261    }
262    let (a, xs, b, ys, body) = (&outer.ident, &f.expr, &inner.pat, &inner.expr, &inner.body);
263    let attrs = &f.attrs;
264    let pairs: Expr = syn::parse_quote! {
265        ::core::iter::IntoIterator::into_iter(#xs).flat_map(move |#a| {
266            ::core::iter::IntoIterator::into_iter(#ys).map(move |__psync_inner| (#a, __psync_inner))
267        })
268    };
269    // Bind the outer item only if the body uses it.
270    let outer_pat = if mentions(body.to_token_stream()).contains(&a.to_string()) {
271        quote!(#a)
272    } else {
273        quote!(_)
274    };
275    Some(syn::parse_quote!(#(#attrs)* for (#outer_pat, #b) in #pairs #body))
276}
277
278/// True when `body` contains a `break` that would leave it (not one inside a nested loop).
279fn breaks(body: &Block) -> bool {
280    struct V(usize, bool);
281    impl<'ast> syn::visit::Visit<'ast> for V {
282        fn visit_expr_break(&mut self, _: &'ast syn::ExprBreak) {
283            self.1 |= self.0 == 0;
284        }
285        fn visit_expr_for_loop(&mut self, e: &'ast ExprForLoop) {
286            self.0 += 1;
287            syn::visit::visit_expr_for_loop(self, e);
288            self.0 -= 1;
289        }
290        fn visit_expr_while(&mut self, e: &'ast syn::ExprWhile) {
291            self.0 += 1;
292            syn::visit::visit_expr_while(self, e);
293            self.0 -= 1;
294        }
295        fn visit_expr_loop(&mut self, e: &'ast syn::ExprLoop) {
296            self.0 += 1;
297            syn::visit::visit_expr_loop(self, e);
298            self.0 -= 1;
299        }
300        fn visit_expr_closure(&mut self, _: &'ast syn::ExprClosure) {}
301    }
302    let mut v = V(0, false);
303    syn::visit::Visit::visit_block(&mut v, body);
304    v.1
305}
306
307/// The condition of `if c { ..; continue | break | return .. }` (no `else`) when `c` is pure.
308fn exit_guard(stmt: &Stmt) -> Option<&Expr> {
309    let Stmt::Expr(Expr::If(i), _) = stmt else {
310        return None;
311    };
312    let ends_in_exit = matches!(
313        i.then_branch.stmts.last(),
314        Some(Stmt::Expr(
315            Expr::Continue(_) | Expr::Break(_) | Expr::Return(_),
316            _
317        ))
318    );
319    (i.else_branch.is_none()
320        && ends_in_exit
321        && !matches!(&*i.cond, Expr::Let(_))
322        && crate::classify::is_pure(&i.cond))
323    .then_some(&*i.cond)
324}
325
326fn describe(f: &ExprForLoop) -> String {
327    format!(
328        "for {} in {}",
329        f.pat.to_token_stream(),
330        f.expr.to_token_stream()
331    )
332    .chars()
333    .take(60)
334    .collect()
335}
336
337impl Rewriter<'_> {
338    /// Rewrite a `for` loop by prefetching or by fission then prefetching; `None` (recorded in
339    /// the report) leaves it as written.
340    pub(crate) fn rewrite_loop(&mut self, f: &ExprForLoop) -> Option<Expr> {
341        let (label, line, end_line) = (
342            describe(f),
343            line_of(f.for_token.span()),
344            crate::classify::end_line_of(f.span()),
345        );
346        // `#[psync::seq]` keeps the loop as written (its body is still rewritten inside).
347        if f.attrs.iter().any(|a| is_psync_attr(a, "seq")) {
348            self.report.loops.push(LoopReport {
349                label,
350                line,
351                end_line,
352                reason: "marked #[psync::seq]".into(),
353                ..Default::default()
354            });
355            return None;
356        }
357        // A loop whose body is only another loop is treated as one loop over the pairs, so the
358        // awaited work of later outer items can run ahead too.
359        let flat = flatten(f);
360        let f = flat.as_ref().unwrap_or(f);
361        let outcome = self.prefetch(f).or_else(|why| self.fission(f).ok_or(why));
362        match outcome {
363            Ok((expr, prefetched)) => {
364                let bound = self.options.bound;
365                self.report.loops.push(LoopReport {
366                    label,
367                    line,
368                    end_line,
369                    prefetched,
370                    bound,
371                    changed: true,
372                    reason: String::new(),
373                    check: std::mem::take(&mut self.loop_check),
374                    prefetched_lines: std::mem::take(&mut self.loop_lines),
375                });
376                Some(expr)
377            }
378            Err(reason) => {
379                self.report.loops.push(LoopReport {
380                    label,
381                    line,
382                    end_line,
383                    reason,
384                    ..Default::default()
385                });
386                None
387            }
388        }
389    }
390
391    /// Rewrite a `while`/`while let` loop by fission. Only with `#[psync::independent]`: the
392    /// condition must be driven by the statements before the first await, which tokens cannot show.
393    pub(crate) fn rewrite_while(&mut self, w: &syn::ExprWhile) -> Option<Expr> {
394        if !w.attrs.iter().any(|a| is_psync_attr(a, "independent")) {
395            return None;
396        }
397        let cond = &w.cond;
398        let head = quote!(while #cond);
399        let label = format!("while {}", cond.to_token_stream())
400            .chars()
401            .take(60)
402            .collect();
403        let (line, end_line) = (
404            line_of(w.while_token.span()),
405            crate::classify::end_line_of(w.span()),
406        );
407        match self.fission_with(head, &w.label, &w.attrs, &[], &w.body) {
408            Some((expr, prefetched)) => {
409                let bound = self.options.bound;
410                self.report.loops.push(LoopReport {
411                    label,
412                    line,
413                    end_line,
414                    prefetched,
415                    bound,
416                    changed: true,
417                    reason: String::new(),
418                    check: std::mem::take(&mut self.loop_check),
419                    prefetched_lines: std::mem::take(&mut self.loop_lines),
420                });
421                Some(expr)
422            }
423            None => {
424                let reason = "no awaited work can run ahead after the statements before it".into();
425                self.report.loops.push(LoopReport {
426                    label,
427                    line,
428                    end_line,
429                    reason,
430                    ..Default::default()
431                });
432                None
433            }
434        }
435    }
436
437    /// Prefetch the loop's awaited prefix. Returns the replacement and the prefetched labels.
438    fn prefetch(&mut self, f: &ExprForLoop) -> Result<(Expr, Vec<String>), String> {
439        if pat_has_ref(&f.pat) {
440            return Err("`ref` in the loop pattern".into());
441        }
442        let mut pattern = Vec::new();
443        pat_idents(&f.pat, &mut pattern);
444        let scope = LoopScope::new(self, &pattern, &f.body, &f.attrs);
445        self.refusal = None;
446        let (prefix, rest) = self.take_prefix(f.body.stmts.clone(), true, &scope);
447        if prefix.is_empty() {
448            return Err(self
449                .refusal
450                .take()
451                .unwrap_or_else(|| "no awaited statement can run ahead".into()));
452        }
453        let check = target_check(
454            &crate::gates::Compare {
455                krate: &self.options.krate,
456                owned_files: self.options.owned_files,
457            },
458            f,
459            &pattern,
460            &prefix,
461            &rest,
462            &scope,
463            &self.scope.effects,
464        );
465        self.loop_check = match &check {
466            Ok(Some(_)) => "checked at run time".into(),
467            Ok(None) => String::new(),
468            Err(why) => format!("assumed distinct: {why}"),
469        };
470        // The prefix runs as one chain per item; its bindings flow into the rest of the body.
471        let krate = self.options.krate.clone();
472        let rest_mentions: Set = rest
473            .iter()
474            .flat_map(|s| mentions(s.to_token_stream()))
475            .collect();
476        let members: Vec<&Node> = prefix.iter().collect();
477        let k = self.next();
478        let code = chain_code(
479            &krate,
480            &self.scope.fresh,
481            &members,
482            &rest_mentions,
483            k,
484            &pattern,
485        );
486        let mut rest_block = Block {
487            brace_token: f.body.brace_token,
488            stmts: rest,
489        };
490        self.visit_block_mut(&mut rest_block);
491
492        let (pat, iter, bound) = (&f.pat, &f.expr, self.options.bound);
493        let attrs = f.attrs.iter().filter(|a| !is_psync_attr(a, "independent"));
494        let loop_label = &f.label;
495        let (chain, slot_idents, bindings) =
496            (&code.body, code.slot_idents(), code.binding_pattern());
497        let reraise = code.slots.iter().map(|s| s.reraise(&krate));
498        let rest_stmts = &rest_block.stmts;
499        let loop_id = proc_macro2::Literal::usize_unsuffixed(self.next());
500        let (terminates, speculate, independent) =
501            (scope.terminates, scope.speculate, scope.independent);
502        let prefetched_tokens = quote! {{
503            let __psync_each = #krate::__private::over_at::<#loop_id, #terminates, #speculate, #independent, _, _, _>(&__psync_iter, async |#pat| { #chain });
504            // The futures are created here, not in a generic helper, and before the await: rustc
505            // can then prove the state held across the await `Send` even when items carry
506            // lifetimes (`Box<dyn Trait + Send>`), which it cannot for an iterator adapter or a
507            // helper's future.
508            let __psync_futures: #krate::__private::Vec<_> = ::core::iter::IntoIterator::into_iter(__psync_iter)
509                .map(|__psync_item| __psync_each(__psync_item))
510                .collect();
511            let __psync_items = #krate::__private::join_all_bounded(__psync_futures.into_iter(), #bound).await;
512            #(#attrs)* #loop_label for (#(#slot_idents,)* __psync_out) in __psync_items {
513                #(#reraise)*
514                #[allow(unused_mut)] let #bindings = __psync_out.unwrap();
515                #(#rest_stmts)*
516            }
517        }};
518        let tokens = match check {
519            // Two items share a file one of them writes: the loop as written.
520            Ok(Some(distinct)) => {
521                let mut original = f.clone();
522                original.expr = syn::parse_quote!(__psync_iter);
523                original.attrs.retain(|a| !is_psync_attr(a, "independent"));
524                quote! {{
525                    let __psync_iter: #krate::__private::Vec<_> =
526                        ::core::iter::IntoIterator::into_iter(#iter).collect();
527                    let __psync_distinct: bool = #distinct;
528                    if __psync_distinct #prefetched_tokens else { #original }
529                }}
530            }
531            _ => quote! {{
532                let __psync_iter = #iter;
533                #prefetched_tokens
534            }},
535        };
536        let prefetched = prefix.iter().map(|n| n.label.clone()).collect();
537        self.loop_lines = prefix.iter().map(|n| (n.line, n.end_line)).collect();
538        Ok((
539            syn::parse2(tokens).expect("psync::graph generated an invalid loop"),
540            prefetched,
541        ))
542    }
543
544    /// Split off the leading non-awaiting statements into a first loop, then prefetch the rest.
545    fn fission(&mut self, f: &ExprForLoop) -> Option<(Expr, Vec<String>)> {
546        if pat_has_ref(&f.pat) {
547            return None;
548        }
549        let (pat, iter) = (&f.pat, &f.expr);
550        let mut pattern = Vec::new();
551        pat_idents(&f.pat, &mut pattern);
552        self.fission_with(
553            quote!(for #pat in #iter),
554            &f.label,
555            &f.attrs,
556            &pattern,
557            &f.body,
558        )
559    }
560
561    /// Fission for a loop with the given header (`for p in e` or `while c`).
562    fn fission_with(
563        &mut self,
564        head: TokenStream,
565        loop_label: &Option<syn::Label>,
566        attrs: &[syn::Attribute],
567        pattern: &[(Ident, bool)],
568        body: &Block,
569    ) -> Option<(Expr, Vec<String>)> {
570        // The first loop takes every statement before the first await; a leading `if`/`match`
571        // whose branches await contributes just its condition.
572        let mut stmts = body.stmts.clone();
573        let mut first = Vec::new();
574        let mut at = 0;
575        while at < stmts.len() {
576            let x = Exits::of_stmt(&stmts[at]);
577            if x.blocker.is_some() {
578                return None;
579            }
580            if x.awaits {
581                let n = self.next();
582                if let Some((cond, rewritten)) = hoist::condition(&stmts[at], n) {
583                    first.push(cond);
584                    stmts[at] = rewritten;
585                }
586                break;
587            }
588            first.push(stmts[at].clone());
589            at += 1;
590        }
591        let rest: Vec<Stmt> = stmts.split_off(at);
592        if first.is_empty() || rest.is_empty() {
593            return None;
594        }
595        // The first loop now runs before the rest of every iteration, so the two parts must not
596        // touch the same carried state (per-iteration names flow from one to the other).
597        let mut local: Set = pattern.iter().map(|(i, _)| i.to_string()).collect();
598        local.extend(bindings_in(body));
599        let access = |stmts: &[Stmt]| {
600            let mut acc = Access::default();
601            for s in stmts {
602                scan(
603                    s.to_token_stream(),
604                    &self.scope.mutable,
605                    &self.scope.handles,
606                    &mut acc,
607                );
608            }
609            acc.rpaths.retain(|p| !is_local(&local, p));
610            acc.wpaths.retain(|p| !is_local(&local, p));
611            acc
612        };
613        let (a, b) = (access(&first), access(&rest));
614        let b_all: Set = b.rpaths.union(&b.wpaths).cloned().collect();
615        let independent = attrs.iter().any(|a| is_psync_attr(a, "independent"));
616        if !independent
617            && (conflict(&a.wpaths, &b_all).is_some() || conflict(&b.wpaths, &a.rpaths).is_some())
618        {
619            return None;
620        }
621        // The first part runs for every item before the rest of any: its writes must not run for
622        // items sequential code would not reach, nor touch what the rest touches on a shared target.
623        let (fa, fb) = (
624            body_effects(&first, &self.scope.effects),
625            body_effects(&rest, &self.scope.effects),
626        );
627        let speculate =
628            self.scope.effects.speculate || attrs.iter().any(|a| is_psync_attr(a, "speculate"));
629        if !speculate && terminates(body) && fa.iter().any(|e| e.writes()) {
630            return None;
631        }
632        let shared = |es: &[Effect]| -> Vec<Effect> {
633            es.iter()
634                .filter(|e| !e.target.mentions_any(&local))
635                .cloned()
636                .collect()
637        };
638        if !independent
639            && (crate::effects::conflicts(&shared(&fa), &fb).is_some()
640                || crate::effects::conflicts(&fa, &shared(&fb)).is_some())
641        {
642            return None;
643        }
644
645        // Values the rest needs from each item: the pattern's bindings and the first part's.
646        let mut defined: Vec<(Ident, bool)> = pattern.to_vec();
647        for s in &first {
648            if let Stmt::Local(l) = s {
649                pat_idents(&l.pat, &mut defined);
650            }
651        }
652        let needed: Set = rest
653            .iter()
654            .flat_map(|s| mentions(s.to_token_stream()))
655            .collect();
656        let mut carry: Vec<(Ident, bool)> = Vec::new();
657        for (id, m) in defined
658            .into_iter()
659            .filter(|(id, _)| needed.contains(&id.to_string()))
660        {
661            match carry.iter_mut().find(|(c, _)| *c == id) {
662                Some(slot) => *slot = (id, m),
663                None => carry.push((id, m)),
664            }
665        }
666
667        // First loop: exits that end the whole loop stop it and are performed afterwards.
668        let k = self.next();
669        let pre_label = loop_label
670            .as_ref()
671            .map(|l| l.name.clone())
672            .unwrap_or_else(|| {
673                syn::Lifetime::new(&format!("'__psync_pre{k}"), proc_macro2::Span::call_site())
674            });
675        let krate = self.options.krate.clone();
676        let mut rewriter = ExitRewriter::deferring(&pre_label, format!("p{k}"), &krate);
677        for s in &mut first {
678            rewriter.visit_stmt_mut(s);
679        }
680        let slots = rewriter.slots;
681        let slot_idents = slots.idents();
682        let names: Vec<&Ident> = carry.iter().map(|(i, _)| i).collect();
683        let pats = carry
684            .iter()
685            .map(|(i, m)| if *m { quote!(mut #i) } else { quote!(#i) });
686        let items = format_ident!("__psync_first{}", k);
687
688        // Second loop: over the first loop's results; prefetch it like any `for` loop.
689        let attrs: Vec<&syn::Attribute> = attrs.iter().collect();
690        let second: ExprForLoop = syn::parse_quote! {
691            #(#attrs)* #loop_label for (#(#pats,)*) in #items { #(#rest)* }
692        };
693        let (second, prefetched) = self.prefetch(&second).ok()?;
694        let reraise = slots.reraise(&krate);
695        let tokens = quote! {{
696            #(let mut #slot_idents = ::core::option::Option::None;)*
697            let #items = {
698                let mut __psync_v = #krate::__private::Vec::new();
699                #pre_label: #head {
700                    #(#first)*
701                    __psync_v.push((#(#names,)*));
702                }
703                __psync_v
704            };
705            #second
706            #reraise
707        }};
708        Some((
709            syn::parse2(tokens).expect("psync::graph generated an invalid loop fission"),
710            prefetched,
711        ))
712    }
713
714    /// Split a loop body (or a guarded branch) into the statements that may run ahead of earlier
715    /// iterations and the rest.
716    ///
717    /// Bindings and awaits are taken from the front of the body. Further on, an awaited statement
718    /// may still join if nothing left behind before it could exit the iteration or touches what it
719    /// touches. Awaits inside a scrutinee, call arguments or an `if` branch are hoisted out first.
720    fn take_prefix(
721        &mut self,
722        body: Vec<Stmt>,
723        allow_guard: bool,
724        scope: &LoopScope,
725    ) -> (Vec<Node>, Vec<Stmt>) {
726        let mut prefix: Vec<Node> = Vec::new();
727        let mut rest: Vec<Stmt> = Vec::new();
728        let mut behind = Vec::<Node>::new();
729        let mut blocked = false;
730        let mut body = body.into_iter();
731        while let Some(stmt) = body.next() {
732            // `if c { ..; continue; }` then awaited work: run that work ahead when `!c`.
733            if !blocked
734                && allow_guard
735                && let Some(c) = exit_guard(&stmt)
736                && behind.is_empty()
737            {
738                let after: Vec<Stmt> = body.by_ref().collect();
739                match self.invert_guard(c, after.clone(), scope) {
740                    Some((guard, unpack))
741                        if scope
742                            .refuses(&guard)
743                            .map(|why| self.refusal.get_or_insert(why))
744                            .is_none() =>
745                    {
746                        prefix.push(guard);
747                        rest.push(stmt);
748                        rest.extend(unpack);
749                    }
750                    _ => {
751                        rest.push(stmt);
752                        rest.extend(after);
753                    }
754                }
755                break;
756            }
757            if !blocked
758                && let Some((nodes, replacement)) = self.prefix_candidate(&stmt, allow_guard, scope)
759                && nodes.iter().all(|n| match scope.refuses(n) {
760                    Some(why) => {
761                        self.refusal.get_or_insert(why);
762                        false
763                    }
764                    None => true,
765                })
766                && nodes.iter().all(|n| {
767                    behind
768                        .iter()
769                        .all(|b| crate::schedule::depends(b, n).is_none())
770                })
771                && (rest.is_empty() || nodes.iter().any(|n| n.awaits))
772            {
773                prefix.extend(nodes);
774                rest.extend(replacement);
775                continue;
776            }
777            match classify(&stmt, &self.scope, false) {
778                Class::Node(n) => {
779                    blocked |= n.exits;
780                    behind.push(*n);
781                }
782                Class::Barrier(_) => blocked = true,
783            }
784            rest.push(stmt);
785        }
786        // Cheap leading bindings only belong in the prefix if an await there needs them.
787        while prefix.last().is_some_and(|n| !n.awaits) {
788            let n = prefix.pop().expect("non-empty");
789            rest.insert(0, n.stmt);
790        }
791        (prefix, rest)
792    }
793
794    /// For an exit guard `if c { ..; continue; }` with pure `c`, take the awaited prefix of the
795    /// statements after it, guarded by `!c`: returns the prefix node
796    /// `let g = if c { None } else { Some(<prefix chain>) };` and the statements that replace
797    /// `after` (unpacking `g`, which is `Some` once the guard has not exited).
798    fn invert_guard(
799        &mut self,
800        cond: &Expr,
801        after: Vec<Stmt>,
802        scope: &LoopScope,
803    ) -> Option<(Node, Vec<Stmt>)> {
804        let (inner, inner_rest) = self.take_prefix(after, false, scope);
805        if inner.is_empty() {
806            return None;
807        }
808        let needed: Set = inner_rest
809            .iter()
810            .flat_map(|s| mentions(s.to_token_stream()))
811            .collect();
812        let k = self.next();
813        let krate = self.options.krate.clone();
814        let members: Vec<&Node> = inner.iter().collect();
815        let code = chain_code(&krate, &self.scope.fresh, &members, &needed, k, &[]);
816        let (g, gout) = (
817            format_ident!("__psync_g{}", k),
818            format_ident!("__psync_gout{}", k),
819        );
820        let body = &code.body;
821        let guard: Stmt = syn::parse_quote_spanned! {cond.span()=>
822            let #g = if #cond { ::core::option::Option::None } else { ::core::option::Option::Some({ #body }) };
823        };
824        let mut node = match classify(&guard, &self.scope, true) {
825            Class::Node(n) if !n.effect && n.awaits => *n,
826            _ => return None,
827        };
828        // The node stands for the guard and the statements it took, so it spans them all.
829        node.end_line = inner
830            .iter()
831            .map(|n| n.end_line)
832            .fold(node.end_line, usize::max);
833        let slot_idents = code.slot_idents();
834        let reraise = code.slots.iter().map(|s| s.reraise(&krate));
835        let bindings = code.binding_pattern();
836        let mut unpack: Vec<Stmt> = syn::parse_quote! {
837            let ::core::option::Option::Some((#(#slot_idents,)* #gout)) = #g else {
838                unreachable!("the guard did not exit, so its condition was false")
839            };
840            #(#reraise)*
841            #[allow(unused_mut)] let #bindings = #gout.unwrap();
842        };
843        unpack.extend(inner_rest);
844        Some((node, unpack))
845    }
846
847    /// The prefix nodes a statement contributes, and what stays in the body in its place.
848    fn prefix_candidate(
849        &mut self,
850        stmt: &Stmt,
851        allow_guard: bool,
852        scope: &LoopScope,
853    ) -> Option<(Vec<Node>, Option<Stmt>)> {
854        let movable = |class: Class| match class {
855            Class::Node(n) if !n.effect => Some(*n),
856            _ => None,
857        };
858        if let Some(n) = movable(classify(stmt, &self.scope, true)) {
859            return Some((vec![n], None));
860        }
861        let n = self.next();
862        if let Some((value, rewritten)) = hoist::scrutinee(stmt, n) {
863            let node = movable(classify(&value, &self.scope, true)).filter(|n| n.awaits)?;
864            return Some((vec![node], Some(rewritten)));
865        }
866        if let Some((values, rewritten)) = hoist::operands(stmt, &mut self.fresh) {
867            let nodes: Option<Vec<Node>> = values
868                .iter()
869                .map(|v| movable(classify(v, &self.scope, true)))
870                .collect();
871            return nodes
872                .filter(|ns| ns.iter().any(|n| n.awaits))
873                .map(|ns| (ns, Some(rewritten)));
874        }
875        if allow_guard && let Some((guard, rewritten)) = self.hoist_guard(stmt, scope) {
876            let node = movable(classify(&guard, &self.scope, true)).filter(|n| n.awaits)?;
877            return Some((vec![node], Some(rewritten)));
878        }
879        None
880    }
881
882    /// `if c { <awaited prefix>; rest } else { .. }` becomes a prefix binding
883    /// `let g = if c { Some(<prefix chain>) } else { None };` and the statement
884    /// `if let Some(..) = g { <re-raise exits>; rest } else { .. }`.
885    /// Outside loops: split `if c { let x = f.await?; rest }` into a guarded statement running the
886    /// branch's leading awaited work (`let g = if c { Some(..) } else { None };`) and the branch's
887    /// remainder, so that work can overlap with the statements before the `if`.
888    pub(crate) fn hoist_branch(&mut self, stmt: &Stmt) -> Option<(Stmt, Stmt)> {
889        self.hoist_guard(stmt, &LoopScope::straight())
890    }
891
892    fn hoist_guard(&mut self, stmt: &Stmt, scope: &LoopScope) -> Option<(Stmt, Stmt)> {
893        let Stmt::Expr(Expr::If(i), semi) = stmt else {
894            return None;
895        };
896        let cond = Exits::of(&i.cond);
897        if cond.awaits || cond.exits || cond.blocker.is_some() || yields_value(&i.then_branch) {
898            return None;
899        }
900        let (inner, inner_rest) = self.take_prefix(i.then_branch.stmts.clone(), false, scope);
901        if inner.is_empty() {
902            return None;
903        }
904        let mut bound_by_cond = Vec::new();
905        if let Expr::Let(l) = &*i.cond {
906            pat_idents(&l.pat, &mut bound_by_cond);
907        }
908        let needed: Set = inner_rest
909            .iter()
910            .flat_map(|s| mentions(s.to_token_stream()))
911            .collect();
912        let k = self.next();
913        let krate = self.options.krate.clone();
914        let members: Vec<&Node> = inner.iter().collect();
915        let code = chain_code(
916            &krate,
917            &self.scope.fresh,
918            &members,
919            &needed,
920            k,
921            &bound_by_cond,
922        );
923        let (g, gout) = (
924            format_ident!("__psync_g{}", k),
925            format_ident!("__psync_gout{}", k),
926        );
927        let (cond, body) = (&i.cond, &code.body);
928        let guard: Stmt = syn::parse_quote_spanned! {stmt.span()=>
929            let #g = if #cond { ::core::option::Option::Some({ #body }) } else { ::core::option::Option::None };
930        };
931        let slot_idents = code.slot_idents();
932        let reraise = code.slots.iter().map(|s| s.reraise(&krate));
933        let bindings = code.binding_pattern();
934        let else_branch = i.else_branch.as_ref().map(|(_, e)| quote!(else #e));
935        let rewritten: Expr = syn::parse_quote! {
936            if let ::core::option::Option::Some((#(#slot_idents,)* #gout)) = #g {
937                #(#reraise)*
938                #[allow(unused_mut)] let #bindings = #gout.unwrap();
939                #(#inner_rest)*
940            } #else_branch
941        };
942        Some((guard, Stmt::Expr(rewritten, *semi)))
943    }
944}
945
946// ANCHOR: total-methods
947/// Methods whose call on a total receiver neither panics nor touches anything: what a file
948/// path is usually built with.
949const TOTAL_METHODS: &[&str] = &[
950    "clone",
951    "to_string",
952    "to_owned",
953    "as_ref",
954    "as_str",
955    "as_path",
956    "as_os_str",
957    "to_path_buf",
958    "join",
959    "with_extension",
960    "with_file_name",
961    "path",
962];
963// ANCHOR_END: total-methods
964
965/// An expression that can be evaluated once more, ahead of the loop, for every item: it has no
966/// effect and cannot panic (no indexing, no arithmetic, no unknown call).
967pub(crate) fn total(e: &Expr) -> bool {
968    match e {
969        Expr::Lit(_) | Expr::Path(_) => true,
970        Expr::Field(f) => total(&f.base),
971        Expr::Reference(r) => r.mutability.is_none() && total(&r.expr),
972        Expr::Paren(p) => total(&p.expr),
973        Expr::Group(g) => total(&g.expr),
974        Expr::MethodCall(m) => {
975            TOTAL_METHODS.contains(&m.method.to_string().as_str())
976                && total(&m.receiver)
977                && m.args.iter().all(total)
978        }
979        Expr::Call(c) => {
980            let Expr::Path(p) = &*c.func else {
981                return false;
982            };
983            let s: Vec<String> = p
984                .path
985                .segments
986                .iter()
987                .map(|s| s.ident.to_string())
988                .collect();
989            matches!(
990                s.iter().map(String::as_str).collect::<Vec<_>>()[..],
991                [.., "Path" | "OsStr", "new"] | [.., "PathBuf" | "OsString" | "String", "from"]
992            ) && c.args.len() == 1
993                && c.args.iter().all(total)
994        }
995        Expr::Macro(m) if m.mac.path.is_ident("format") => {
996            use syn::parse::Parser;
997            let Ok(args) = syn::punctuated::Punctuated::<Expr, syn::Token![,]>::parse_terminated
998                .parse2(m.mac.tokens.clone())
999            else {
1000                return false;
1001            };
1002            let mut args = args.iter();
1003            matches!(
1004                args.next(),
1005                Some(Expr::Lit(syn::ExprLit {
1006                    lit: syn::Lit::Str(_),
1007                    ..
1008                }))
1009            ) && args.all(|a| match a {
1010                Expr::Assign(a) => total(&a.right),
1011                a => total(a),
1012            })
1013        }
1014        _ => false,
1015    }
1016}
1017
1018/// Replace the names bound by `lets` in `tokens` with their values, in parentheses.
1019pub(crate) fn substitute(
1020    tokens: TokenStream,
1021    lets: &std::collections::HashMap<String, TokenStream>,
1022) -> TokenStream {
1023    use proc_macro2::{Delimiter, Group, TokenTree};
1024    let trees: Vec<TokenTree> = tokens.into_iter().collect();
1025    let punct =
1026        |t: Option<&TokenTree>, c: char| matches!(t, Some(TokenTree::Punct(p)) if p.as_char() == c);
1027    let mut out = TokenStream::new();
1028    for (i, t) in trees.iter().enumerate() {
1029        let (prev, next) = (
1030            i.checked_sub(1).and_then(|j| trees.get(j)),
1031            trees.get(i + 1),
1032        );
1033        match t {
1034            TokenTree::Ident(id)
1035                if lets.contains_key(&id.to_string())
1036                    && !punct(prev, '.')
1037                    && !punct(prev, ':')
1038                    && !punct(next, ':')
1039                    && !punct(next, '!')
1040                    && (!punct(next, '=') || punct(trees.get(i + 2), '=')) =>
1041            {
1042                out.extend([TokenTree::Group(Group::new(
1043                    Delimiter::Parenthesis,
1044                    lets[&id.to_string()].clone(),
1045                ))]);
1046            }
1047            TokenTree::Group(g) => {
1048                let mut ng = Group::new(g.delimiter(), substitute(g.stream(), lets));
1049                ng.set_span(g.span());
1050                out.extend([TokenTree::Group(ng)]);
1051            }
1052            t => out.extend([t.clone()]),
1053        }
1054    }
1055    out
1056}
1057
1058/// Every name a pattern binds, with repetitions (`visit` sees each binding once).
1059fn binding_counts(
1060    body: &Block,
1061    pattern: &[(Ident, bool)],
1062) -> std::collections::HashMap<String, usize> {
1063    struct V(std::collections::HashMap<String, usize>);
1064    impl<'ast> syn::visit::Visit<'ast> for V {
1065        fn visit_pat_ident(&mut self, p: &'ast syn::PatIdent) {
1066            *self.0.entry(p.ident.to_string()).or_default() += 1;
1067            syn::visit::visit_pat_ident(self, p);
1068        }
1069    }
1070    let mut v = V(Default::default());
1071    for (i, _) in pattern {
1072        *v.0.entry(i.to_string()).or_default() += 1;
1073    }
1074    syn::visit::Visit::visit_block(&mut v, body);
1075    v.0
1076}
1077
1078/// The runtime check that the items of a prefetched loop name different files.
1079///
1080/// Prefetching runs the prefix of later items before the rest of earlier ones, which is safe when
1081/// each item touches its own files. When the files depend on the item (`fs::write(dir.join(name))`),
1082/// the generated code first evaluates every such path for every item and runs the loop as
1083/// written when two items share one and either writes it. `Ok(None)`: nothing to check;
1084/// `Err(why)`: a path cannot be evaluated ahead, so distinct items are assumed, as before.
1085fn target_check(
1086    compare: &crate::gates::Compare,
1087    f: &ExprForLoop,
1088    pattern: &[(Ident, bool)],
1089    prefix: &[Node],
1090    rest: &[Stmt],
1091    scope: &LoopScope,
1092    config: &effects::Config,
1093) -> Result<Option<TokenStream>, String> {
1094    let (pat, body, krate) = (&*f.pat, &f.body, compare.krate);
1095    if scope.independent {
1096        return Ok(None);
1097    }
1098    // Files, HTTP URLs and Redis keys: the targets the runtime can compare.
1099    let per_item =
1100        |e: &&Effect| crate::gates::how(e).is_some() && e.target.mentions_any(&scope.local);
1101    let ahead: Vec<&Effect> = prefix
1102        .iter()
1103        .flat_map(|n| &n.effects)
1104        .filter(per_item)
1105        .collect();
1106    let rest_effects = body_effects(rest, config);
1107    let behind: Vec<&Effect> = rest_effects
1108        .iter()
1109        .filter(per_item)
1110        .filter(|e| e.writes())
1111        .collect();
1112    let keyed: Vec<&Effect> = ahead.iter().chain(&behind).copied().collect();
1113    if ahead.is_empty() || !keyed.iter().any(|e| e.writes()) {
1114        return Ok(None);
1115    }
1116    // In a pattern that is not a plain name, `mut` cannot bind through the reference the check
1117    // matches against.
1118    if !matches!(pat, syn::Pat::Ident(_)) && pattern.iter().any(|(_, m)| *m) {
1119        return Err("the loop pattern binds `mut`".into());
1120    }
1121    // `let p = dir.join(name);` in the body: `p` stands for its value, if it is bound only there.
1122    let counts = binding_counts(body, pattern);
1123    let mut lets: std::collections::HashMap<String, TokenStream> = Default::default();
1124    for s in &body.stmts {
1125        let Stmt::Local(l) = s else { continue };
1126        let p = match &l.pat {
1127            syn::Pat::Type(t) => &*t.pat,
1128            p => p,
1129        };
1130        if let (syn::Pat::Ident(id), Some(init)) = (p, &l.init)
1131            && id.by_ref.is_none()
1132            && id.subpat.is_none()
1133            && init.diverge.is_none()
1134            && counts.get(&id.ident.to_string()) == Some(&1)
1135        {
1136            let value = substitute(init.expr.to_token_stream(), &lets);
1137            if syn::parse2::<Expr>(value.clone()).is_ok_and(|e| total(&e)) {
1138                lets.insert(id.ident.to_string(), value);
1139            }
1140        }
1141    }
1142    let names: Set = pattern.iter().map(|(i, _)| i.to_string()).collect();
1143    let mut keys = Vec::new();
1144    for e in keyed {
1145        let Some(source) = &e.source else {
1146            return Err(format!("the path of `{}` is not in the source", e.op));
1147        };
1148        let Ok(tokens) = source.parse::<TokenStream>() else {
1149            return Err(format!("the path `{source}` does not parse"));
1150        };
1151        let value = substitute(tokens, &lets);
1152        let Ok(expr) = syn::parse2::<Expr>(value) else {
1153            return Err(format!("the path `{source}` does not parse"));
1154        };
1155        if !total(&expr) {
1156            return Err(format!(
1157                "the path `{source}` may panic or have effects when evaluated ahead"
1158            ));
1159        }
1160        let used = mentions(expr.to_token_stream());
1161        if let Some(n) = used
1162            .iter()
1163            .find(|n| scope.local.contains(*n) && !names.contains(*n))
1164        {
1165            return Err(format!(
1166                "the path `{source}` depends on `{n}`, computed in the body"
1167            ));
1168        }
1169        let writes = e.writes();
1170        let how = crate::gates::how(e).unwrap_or(crate::gates::How::Key);
1171        let target = compare.item(&expr, how);
1172        keys.push(quote!((#target, #writes)));
1173    }
1174    let keys = keys.into_iter();
1175    // Each item's targets are compared with every earlier item's: two overlap, and either
1176    // writes, and the loop runs as written. Targets of one item never conflict with each other
1177    // here: an item runs in order.
1178    Ok(Some(quote! {{
1179        let mut __psync_seen =
1180            ::std::vec::Vec::<(#krate::__private::ItemTarget, bool)>::new();
1181        __psync_iter.iter().all(|__psync_r| {
1182            #[allow(unused_variables, unused_mut)]
1183            let #pat = __psync_r;
1184            let __psync_mine = [#(#keys),*];
1185            let __psync_ok = __psync_mine.iter().all(|(k, w)| {
1186                __psync_seen
1187                    .iter()
1188                    .all(|(s, sw)| !((*w || *sw) && k.overlaps(s)))
1189            });
1190            __psync_seen.extend(__psync_mine);
1191            __psync_ok
1192        })
1193    }}))
1194}