Skip to main content

psync_graph/
schedule.rs

1//! Building the dependency graph of a region and generating its concurrent schedule.
2//!
3//! A *region* is a run of nodes between barriers. Its graph has an edge `u -> v` whenever `v`
4//! must wait for `u` ([`depends`]). Nodes with a single predecessor whose predecessor has a single
5//! successor are fused into *chains*, so per-item pipelines (`a1 -> b1`, `a2 -> b2`) proceed
6//! independently. Chains are then leveled; each level with two or more chains becomes one join of
7//! their futures, and the results are bound in program order.
8
9use crate::RegionReport;
10use crate::access::{Set, conflict};
11use crate::classify::{HINTS, Node, is_psync_attr};
12use crate::exits::{ExitRewriter, Slots};
13use proc_macro2::{Ident, Span, TokenStream};
14use quote::{ToTokens, format_ident, quote};
15use std::collections::HashMap;
16use syn::{Stmt, visit_mut::VisitMut};
17
18/// Why `b` (later in the program) must wait for `a` (earlier), if it must.
19pub(crate) fn depends(a: &Node, b: &Node) -> Option<String> {
20    let names = |n: &Node| -> Set { n.defs.iter().map(|(i, _)| i.to_string()).collect() };
21    let (a_defs, b_defs) = (names(a), names(b));
22    // Data flow: `b` reads a binding `a` creates.
23    if let Some(x) = a_defs.intersection(&b.acc.uses).next() {
24        return Some(format!("reads `{x}`"));
25    }
26    // Shadowing: both bind the name, or `b` rebinds a name `a` still reads.
27    if let Some(x) = a_defs.intersection(&b_defs).next() {
28        return Some(format!("rebinds `{x}`"));
29    }
30    if let Some(x) = a.acc.uses.intersection(&b_defs).next() {
31        return Some(format!("shadows `{x}`"));
32    }
33    // Conflicting accesses to the same place.
34    let b_all: Set = b.acc.rpaths.union(&b.acc.wpaths).cloned().collect();
35    if let Some(x) =
36        conflict(&a.acc.wpaths, &b_all).or_else(|| conflict(&b.acc.wpaths, &a.acc.rpaths))
37    {
38        return Some(format!("writes `{x}`"));
39    }
40    // ANCHOR: hint_edges
41    // Effects on the same file, service or other outside resource keep their order.
42    if !(a.independent || b.independent)
43        && let Some(why) = crate::effects::conflicts(&a.effects, &b.effects)
44    {
45        return Some(why);
46    }
47    // A write is not performed before an earlier statement that may leave: sequential code
48    // would not have performed it at all.
49    if (a.exits || a.panics)
50        && !b.speculate
51        && let Some(w) = b.effects.iter().find(|e| e.writes())
52    {
53        // The call's name; where the effect came from is said with the effect itself.
54        let op = w.op.strip_suffix(", per the compiler").unwrap_or(&w.op);
55        return Some(format!("may exit before `{op}` runs"));
56    }
57    // ANCHOR_END: hint_edges
58    // Ordinary statements keep their order relative to each other. A binding or await may still
59    // run ahead of one that might leave the block: that is the speculation the attribute allows,
60    // and the exit is still performed in program order.
61    if a.effect && b.effect {
62        return Some("effect order".into());
63    }
64    None
65}
66
67/// The schedule of one region.
68pub(crate) struct Plan {
69    /// Fused chains: node indices in program order.
70    pub chains: Vec<Vec<usize>>,
71    /// Chain indices that run concurrently, level by level.
72    pub levels: Vec<Vec<usize>>,
73    /// Per chain, the level after which its exits are replayed and its bindings handed back: its
74    /// own level, or later when a statement before one of its exits runs in a later level.
75    pub release: Vec<usize>,
76    pub report: RegionReport,
77}
78
79/// Build the graph, fuse chains and level them.
80pub(crate) fn plan(nodes: &[Node]) -> Plan {
81    let n = nodes.len();
82    let mut preds = vec![Vec::new(); n];
83    let mut succs = vec![Vec::new(); n];
84    let mut edges = Vec::new();
85    for j in 0..n {
86        for i in 0..j {
87            if let Some(why) = depends(&nodes[i], &nodes[j]) {
88                preds[j].push(i);
89                succs[i].push(j);
90                edges.push((i, j, why));
91            }
92        }
93    }
94    // Fuse `u -> v` when every edge into `v` comes from the chain that ends in `u` (members of a
95    // chain run in order, so `u` running means they all have), and either that is the only way
96    // out of `u`, or `u` does not wait and everything else after `u` waits for `v` anyway
97    // (`let key = ..;` read by a request and by what uses its response): fusing then delays
98    // nothing.
99    let mut chain_of = vec![usize::MAX; n];
100    let mut chains: Vec<Vec<usize>> = Vec::new();
101    for v in 0..n {
102        if let Some(&u) = preds[v].iter().max()
103            && chains[chain_of[u]].last() == Some(&u)
104            && preds[v].iter().all(|p| chain_of[*p] == chain_of[u])
105            && (succs[u].len() == 1
106                || !nodes[u].awaits && {
107                    let after_v = reachable(&succs, v);
108                    succs[u].iter().all(|w| *w == v || after_v[*w])
109                })
110        {
111            let c = chain_of[u];
112            chains[c].push(v);
113            chain_of[v] = c;
114        } else {
115            chain_of[v] = chains.len();
116            chains.push(vec![v]);
117        }
118    }
119    // A chain's level is one past the release of the deepest chain it waits for. A chain's exits
120    // are replayed only once every statement before them in program order has run, as sequential
121    // code would run those first (and an exit of theirs would win). Until then the chain's
122    // bindings are not handed back, so what waits for it starts after its release. Chains are in
123    // topological order (only a chain's first member has edges from other chains), and levels
124    // only grow, so this settles.
125    let mut level = vec![0usize; chains.len()];
126    let mut release = vec![0usize; chains.len()];
127    loop {
128        let mut changed = false;
129        for (c, members) in chains.iter().enumerate() {
130            let mut l = level[c];
131            for &v in members {
132                for &p in &preds[v] {
133                    if chain_of[p] != c {
134                        l = l.max(release[chain_of[p]] + 1);
135                    }
136                }
137            }
138            changed |= l != level[c];
139            level[c] = l;
140        }
141        for (c, members) in chains.iter().enumerate() {
142            let mut r = level[c];
143            for &v in members.iter().filter(|&&v| nodes[v].exits) {
144                for u in 0..v {
145                    r = r.max(level[chain_of[u]]);
146                }
147            }
148            changed |= r != release[c];
149            release[c] = r;
150        }
151        if !changed {
152            break;
153        }
154    }
155    let depth = level.iter().max().map_or(0, |m| m + 1);
156    let levels: Vec<Vec<usize>> = (0..depth)
157        .map(|l| (0..chains.len()).filter(|c| level[*c] == l).collect())
158        .collect();
159    let report = RegionReport {
160        nodes: nodes.iter().map(crate::NodeReport::from).collect(),
161        unclassified: nodes
162            .iter()
163            .flat_map(|n| n.unclassified.iter().map(move |u| (n.line, u.clone())))
164            .collect(),
165        edges,
166        chains: chains.clone(),
167        levels: levels.clone(),
168        changed: levels.iter().any(|l| l.len() > 1),
169        cert: cert_nodes(nodes),
170        runtime_checks: 0,
171    };
172    Plan {
173        chains,
174        levels,
175        release,
176        report,
177    }
178}
179
180/// Each node's places, for the region's certificate: one place per reason `depends` can give,
181/// so that two nodes have no edge only if neither writes a place the other touches (the checker
182/// in `verify/Cert.lean` may be stricter than `depends`, never more lenient).
183fn cert_nodes(nodes: &[Node]) -> Vec<crate::CertNode> {
184    let one = |ns: &str, rest: &[&str]| -> Vec<String> {
185        std::iter::once(ns)
186            .chain(rest.iter().copied())
187            .map(str::to_string)
188            .collect()
189    };
190    let path = |p: &str| -> Vec<String> {
191        std::iter::once("p")
192            .chain(p.split('.'))
193            .map(str::to_string)
194            .collect()
195    };
196    nodes
197        .iter()
198        .enumerate()
199        .map(|(j, n)| {
200            let mut c = crate::CertNode::default();
201            for (d, _) in &n.defs {
202                c.writes.push(one("n", &[&d.to_string()]));
203            }
204            for u in &n.acc.uses {
205                c.reads.push(one("n", &[u]));
206            }
207            for p in &n.acc.rpaths {
208                c.reads.push(path(p));
209            }
210            for p in &n.acc.wpaths {
211                c.writes.push(path(p));
212            }
213            // ANCHOR: hint_footprint
214            if !n.independent {
215                for e in &n.effects {
216                    if e.writes() {
217                        c.writes.push(e.place());
218                    } else {
219                        c.reads.push(e.place());
220                    }
221                }
222            }
223            if n.exits || n.panics {
224                c.writes.push(one("x", &[&j.to_string()]));
225            }
226            if !n.speculate && n.effects.iter().any(|e| e.writes()) {
227                for (i, m) in nodes[..j].iter().enumerate() {
228                    if m.exits || m.panics {
229                        c.reads.push(one("x", &[&i.to_string()]));
230                    }
231                }
232            }
233            // ANCHOR_END: hint_footprint
234            if n.effect {
235                c.writes.push(one("e", &[]));
236            }
237            c
238        })
239        .collect()
240}
241
242/// The nodes that (transitively) depend on `from`; nodes are in program order, so edges go forward.
243fn reachable(succs: &[Vec<usize>], from: usize) -> Vec<bool> {
244    let mut seen = vec![false; succs.len()];
245    for v in from..succs.len() {
246        if v == from || seen[v] {
247            for &w in &succs[v] {
248                seen[w] = true;
249            }
250        }
251    }
252    seen
253}
254
255/// Generated code for one chain.
256pub(crate) struct ChainCode {
257    /// The chain's body: evaluates to `(slots..., Option<(bindings...)>)`.
258    pub body: TokenStream,
259    /// Exit slots per member, in program order.
260    pub slots: Vec<Slots>,
261    /// Bindings handed back to the enclosing scope, with their `mut` flag.
262    pub bindings: Vec<(Ident, bool)>,
263}
264
265impl ChainCode {
266    /// All slot variables, matching the order of the body's result tuple.
267    pub fn slot_idents(&self) -> Vec<Ident> {
268        self.slots.iter().flat_map(Slots::idents).collect()
269    }
270    /// `(mut a, b,)`: the pattern that rebinds the handed-back values.
271    pub fn binding_pattern(&self) -> TokenStream {
272        let pats = self
273            .bindings
274            .iter()
275            .map(|(id, m)| if *m { quote!(mut #id) } else { quote!(#id) });
276        quote!((#(#pats,)*))
277    }
278}
279
280/// Generate a chain body: the members' statements in order, with early exits recorded instead of
281/// taken. `needed` lists names used after the chain; `extra` adds bindings defined outside the
282/// members (a loop's pattern) that should be handed back too.
283pub(crate) fn chain_code(
284    krate: &TokenStream,
285    fresh: &std::collections::BTreeMap<String, (Ident, TokenStream)>,
286    members: &[&Node],
287    needed: &Set,
288    k: usize,
289    extra: &[(Ident, bool)],
290) -> ChainCode {
291    chain_code_with(krate, fresh, members, needed, k, extra, None)
292}
293
294/// [`chain_code`], optionally storing the index of the member about to run in the atomic
295/// `progress` (synchronous code: a panic is replayed at the member that raised it).
296pub(crate) fn chain_code_with(
297    krate: &TokenStream,
298    fresh: &std::collections::BTreeMap<String, (Ident, TokenStream)>,
299    members: &[&Node],
300    needed: &Set,
301    k: usize,
302    extra: &[(Ident, bool)],
303    progress: Option<&Ident>,
304) -> ChainCode {
305    let label = syn::Lifetime::new(&format!("'__psync_chain{k}"), Span::call_site());
306    // Bindings are only mutated after the chain hands them back, so `mut` is dropped inside the
307    // chain unless the chain itself writes them (the handed-back binding keeps it).
308    let written: Set = members
309        .iter()
310        .flat_map(|n| n.acc.writes.iter().cloned())
311        .collect();
312    let mut stmts = Vec::new();
313    let mut slots = Vec::new();
314    for (m, node) in members.iter().enumerate() {
315        let mut stmt = node.stmt.clone();
316        StripHints.visit_stmt_mut(&mut stmt);
317        if let Stmt::Local(l) = &mut stmt {
318            DropMut(&written).visit_pat_mut(&mut l.pat);
319        }
320        let mut rewriter = ExitRewriter::new(&label, format!("{k}_{m}"), krate);
321        rewriter.visit_stmt_mut(&mut stmt);
322        // A loop body may end in `api.put(x).await` with no `;` (its value is `()`). In a chain the
323        // member is followed by more code, so it needs one.
324        if let Stmt::Expr(e, semi @ None) = &mut stmt
325            && !matches!(
326                e,
327                syn::Expr::If(_)
328                    | syn::Expr::Match(_)
329                    | syn::Expr::Block(_)
330                    | syn::Expr::ForLoop(_)
331                    | syn::Expr::While(_)
332                    | syn::Expr::Loop(_)
333                    | syn::Expr::Unsafe(_)
334            )
335        {
336            *semi = Some(Default::default());
337        }
338        if let Some(p) = progress {
339            let m = proc_macro2::Literal::usize_unsuffixed(m);
340            stmts.push(quote!(#p.store(#m, ::core::sync::atomic::Ordering::Relaxed);));
341        }
342        stmts.push(stmt.into_token_stream());
343        slots.push(rewriter.slots);
344    }
345    // The last binding of each name wins, as shadowing does in the original.
346    let mut bindings: Vec<(Ident, bool)> = Vec::new();
347    let mut seen: HashMap<String, usize> = HashMap::new();
348    for (id, m) in extra
349        .iter()
350        .cloned()
351        .chain(members.iter().flat_map(|n| n.defs.iter().cloned()))
352    {
353        let name = id.to_string();
354        if !needed.contains(&name) {
355            continue;
356        }
357        match seen.get(&name) {
358            Some(&at) => bindings[at] = (id, m),
359            None => {
360                seen.insert(name, bindings.len());
361                bindings.push((id, m));
362            }
363        }
364    }
365    let names: Vec<&Ident> = bindings.iter().map(|(i, _)| i).collect();
366    let slot_idents: Vec<Ident> = slots.iter().flat_map(Slots::idents).collect();
367    // Each chain makes its own copy of the `#[psync::fresh]` bindings it uses.
368    // The binding reuses the original identifier so macro hygiene resolves uses to it.
369    let fresh_lets = fresh
370        .iter()
371        .filter(|(name, _)| members.iter().any(|n| n.acc.uses.contains(*name)))
372        .map(|(_, (id, init))| quote!(let #id = #init;));
373    let body = quote! {
374        #(#fresh_lets)*
375        #(let mut #slot_idents = ::core::option::Option::None;)*
376        #[allow(unused_labels, unreachable_code, clippy::let_unit_value)]
377        let __psync_out = #label: {
378            #(#stmts)*
379            ::core::option::Option::Some((#(#names,)*))
380        };
381        (#(#slot_idents,)* __psync_out)
382    };
383    ChainCode {
384        body,
385        slots,
386        bindings,
387    }
388}
389
390/// Generate a region's statements from its plan. `positions` are the nodes' statement indices
391/// in the block and `mentions` what each statement of the block mentions.
392#[allow(clippy::too_many_arguments)]
393pub(crate) fn emit(
394    sync: bool,
395    krate: &TokenStream,
396    fresh: &std::collections::BTreeMap<String, (Ident, TokenStream)>,
397    nodes: Vec<Node>,
398    plan: &Plan,
399    positions: &[usize],
400    mentions: &[Set],
401    ids: &mut usize,
402    gates: &[crate::gates::Gate],
403) -> Vec<Stmt> {
404    let mut out = Vec::new();
405    // Exit replays and bindings deferred to a later level: (level, position, tokens).
406    let mut late_reraises: Vec<(usize, usize, TokenStream)> = Vec::new();
407    let mut late_binds: Vec<(usize, TokenStream)> = Vec::new();
408    // Chains are numbered across the region, so a deferred chain's slots are not shadowed.
409    let mut chain_no = 0usize;
410    for (l, level) in plan.levels.iter().enumerate() {
411        let mut reraises: Vec<(usize, TokenStream)> = Vec::new();
412        let mut binds = Vec::new();
413        for (at, pos, r) in std::mem::take(&mut late_reraises) {
414            if at == l {
415                reraises.push((pos, r))
416            } else {
417                late_reraises.push((at, pos, r))
418            }
419        }
420        for (at, b) in std::mem::take(&mut late_binds) {
421            if at == l {
422                binds.push(b)
423            } else {
424                late_binds.push((at, b))
425            }
426        }
427        // A level with one chain runs exactly as written.
428        if let [only] = level[..]
429            && plan.release[only] == l
430        {
431            out.extend(plan.chains[only].iter().map(|&v| nodes[v].stmt.clone()));
432            reraises.sort_by_key(|(p, _)| *p);
433            let (r, b) = (reraises.into_iter().map(|(_, r)| r), binds);
434            let block: syn::Block = syn::parse2(quote!({ #(#r)* #(#b)* }))
435                .expect("psync::graph generated an invalid level");
436            out.extend(block.stmts);
437            continue;
438        }
439        let mut futures = Vec::new();
440        let mut takes = Vec::new();
441        *ids += 1;
442        let level_id = proc_macro2::Literal::usize_unsuffixed(*ids);
443        let gate_of = |c: usize| format_ident!("__psync_gate{}_{}", *ids, c);
444        for &c in level {
445            if gates.iter().any(|g| g.on == c) {
446                let g = gate_of(c);
447                if sync {
448                    futures.push(quote!(let #g = #krate::__private::SyncGate::new();));
449                } else {
450                    futures.push(quote!(let #g = #krate::__private::Gate::new();));
451                }
452            }
453        }
454        for (k, &c) in level.iter().enumerate() {
455            let members: Vec<&Node> = plan.chains[c].iter().map(|&v| &nodes[v]).collect();
456            let chain_positions: Vec<usize> =
457                plan.chains[c].iter().map(|&v| positions[v]).collect();
458            // Bindings needed later: mentioned by any later statement outside this chain.
459            let needed: Set = mentions
460                .iter()
461                .enumerate()
462                .filter(|(i, _)| *i > chain_positions[0] && !chain_positions.contains(i))
463                .flat_map(|(_, m)| m.iter().cloned())
464                .collect();
465            let progress = format_ident!("__psync_at{}", chain_no);
466            let code = chain_code_with(
467                krate,
468                fresh,
469                &members,
470                &needed,
471                chain_no,
472                &[],
473                sync.then_some(&progress),
474            );
475            let (f, out_k) = (
476                format_ident!("__psync_f{}", k),
477                format_ident!("__psync_out{}", chain_no),
478            );
479            let panic = format_ident!("__psync_panic{}", chain_no);
480            chain_no += 1;
481            let at = plan.release[c];
482            let body = &code.body;
483            // `maybe_done_at` is `maybe_done` plus what the analysis assumed, as const generics,
484            // for `cargo psync check` to verify against the compiled callees.
485            let order = proc_macro2::Literal::usize_unsuffixed(chain_positions[0]);
486            let last = proc_macro2::Literal::usize_unsuffixed(*chain_positions.last().unwrap());
487            let exits = members.iter().any(|n| n.exits);
488            // Where the chain's first early exit is, in program order (0 when it has none).
489            let exit_at = proc_macro2::Literal::usize_unsuffixed(
490                members
491                    .iter()
492                    .zip(&chain_positions)
493                    .find(|(n, _)| n.exits)
494                    .map_or(0, |(_, p)| *p),
495            );
496            let spec = members.iter().any(|n| n.speculate);
497            let indep = members.iter().any(|n| n.independent);
498            let slot_idents = code.slot_idents();
499            let taken = format_ident!("__psync_taken{}", k);
500            // Gated: wait for an earlier chain whose targets turned out to overlap this one's,
501            // and let later chains waiting for this one go when it ends. `gated_by::<ORDER>()`
502            // names the chain waited on (by its first statement) for `cargo psync check`, which
503            // then knows the pair's targets are compared.
504            let waits: Vec<TokenStream> = gates
505                .iter()
506                .filter(|g| g.waits == c)
507                .map(|g| {
508                    let (gate, cond) = (gate_of(g.on), &g.cond);
509                    let on =
510                        proc_macro2::Literal::usize_unsuffixed(positions[plan.chains[g.on][0]]);
511                    let wait = if sync {
512                        quote!(#gate.wait();)
513                    } else {
514                        quote!(#gate.wait().await;)
515                    };
516                    quote! {
517                        #krate::__private::gated_by::<#on>();
518                        if #cond { #wait }
519                    }
520                })
521                .collect();
522            let opens = gates.iter().any(|g| g.on == c);
523            if sync {
524                // A job: the chain as a closure, run once, its panic caught with the member
525                // that raised it. A gate it opens is opened by a guard, so a panic opens it too.
526                let opener = opens.then(|| {
527                    let gate = gate_of(c);
528                    quote!(let __psync_opener = #gate.opener();)
529                });
530                futures.push(quote!(let mut #f = ::core::option::Option::Some(
531                    #krate::__private::job_at::<#level_id, #order, #last, #exits, #exit_at, #spec, #indep, _>(|| {
532                        #(#waits)*
533                        #opener
534                        #body
535                    })
536                );));
537                let nones = slot_idents
538                    .iter()
539                    .map(|_| quote!(::core::option::Option::None));
540                takes.push(quote! {
541                    let mut #panic = ::core::option::Option::None;
542                    let (#(#slot_idents,)* #out_k) = match #taken {
543                        (::core::result::Result::Ok(v), _) => v,
544                        (::core::result::Result::Err(p), at) => {
545                            #panic = ::core::option::Option::Some((at, p));
546                            (#(#nones,)* ::core::option::Option::None)
547                        }
548                    };
549                });
550            } else {
551                let opens = opens.then(|| {
552                    let gate = gate_of(c);
553                    quote!(#gate.open();)
554                });
555                let body = quote! {
556                    #(#waits)*
557                    let __psync_r = { #body };
558                    #opens
559                    __psync_r
560                };
561                futures.push(quote!(let mut #f = #krate::__private::maybe_done_at::<#level_id, #order, #last, #exits, #exit_at, #spec, #indep, _>(async { #body });));
562                takes.push(quote!(let (#(#slot_idents,)* #out_k) = #taken;));
563            }
564            // In synchronous code a panic is replayed like an exit, at the member that raised it.
565            let panic_at = |m: usize| {
566                let m = proc_macro2::Literal::usize_unsuffixed(m);
567                quote! {
568                    if ::core::matches!(&#panic, ::core::option::Option::Some((#m, _))) {
569                        ::std::panic::resume_unwind(#panic.take().unwrap().1);
570                    }
571                }
572            };
573            let pattern = code.binding_pattern();
574            let bind = quote!(#[allow(unused_mut)] let #pattern = #out_k.unwrap(););
575            for (m, (slots, pos)) in code.slots.iter().zip(chain_positions).enumerate() {
576                let mut r = TokenStream::new();
577                if sync {
578                    r.extend(panic_at(m));
579                }
580                r.extend(slots.reraise(krate));
581                if at == l {
582                    reraises.push((pos, r));
583                } else {
584                    late_reraises.push((at, pos, r));
585                }
586            }
587            if at == l {
588                binds.push(bind);
589            } else {
590                late_binds.push((at, bind));
591            }
592        }
593        // Exits are performed in program order, so the first one sequential code would hit wins.
594        reraises.sort_by_key(|(p, _)| *p);
595        let reraises = reraises.into_iter().map(|(_, r)| r);
596        let fs = (0..level.len()).map(|k| format_ident!("__psync_f{}", k));
597        let done: Vec<Ident> = (0..level.len())
598            .map(|k| format_ident!("__psync_done{}", k))
599            .collect();
600        let fs: Vec<Ident> = fs.collect();
601        let taken = (0..level.len()).map(|k| format_ident!("__psync_taken{}", k));
602        let progress: Vec<Ident> = (chain_no - level.len()..chain_no)
603            .map(|c| format_ident!("__psync_at{}", c))
604            .collect();
605        // Synchronous code: the chains run as jobs, the first on this thread and the others on
606        // psync's pool; each job's result and the member it reached are taken in an inner block,
607        // so the closures' borrows end with it.
608        let tokens = if sync {
609            let results: Vec<Ident> = (0..level.len())
610                .map(|k| format_ident!("__psync_r{}", k))
611                .collect();
612            quote! {{
613                let (#(#taken,)*) = {
614                    #(let #progress = ::core::sync::atomic::AtomicUsize::new(0);)*
615                    #(#futures)*
616                    #(let mut #results = ::core::option::Option::None;)*
617                    #krate::__private::par_run(&mut [#(
618                        &mut || {
619                            #results = ::core::option::Option::Some(::std::panic::catch_unwind(
620                                ::core::panic::AssertUnwindSafe(#fs.take().unwrap()),
621                            ));
622                        }
623                    ),*]);
624                    (#((
625                        #results.unwrap(),
626                        #progress.load(::core::sync::atomic::Ordering::Relaxed),
627                    ),)*)
628                };
629                #(#takes)*
630                #(#reraises)*
631                #(#binds)*
632            }}
633        } else {
634            // The futures live in an inner block: they (and whatever they borrow) are dropped as
635            // soon as their outputs are taken, so later statements may move what they borrowed.
636            quote! {{
637                let (#(#taken,)*) = {
638                    #(#futures)*
639                    ::core::future::poll_fn(|__psync_cx| {
640                        #(let #done = #fs.poll_step(__psync_cx);)*
641                        if true #(&& #done)* { ::core::task::Poll::Ready(()) } else { ::core::task::Poll::Pending }
642                    }).await;
643                    (#(#fs.take(),)*)
644                };
645                #(#takes)*
646                #(#reraises)*
647                #(#binds)*
648            }}
649        };
650        let block: syn::Block =
651            syn::parse2(tokens).expect("psync::graph generated an invalid level");
652        out.extend(block.stmts);
653    }
654    out
655}
656
657/// Drops `mut` from bindings the chain does not write.
658pub(crate) struct DropMut<'a>(pub &'a Set);
659impl VisitMut for DropMut<'_> {
660    fn visit_pat_ident_mut(&mut self, p: &mut syn::PatIdent) {
661        if !self.0.contains(&p.ident.to_string()) {
662            p.mutability = None;
663        }
664        syn::visit_mut::visit_pat_ident_mut(self, p);
665    }
666}
667
668/// Removes psync's hint attributes (`seq`, `fresh`, `independent`), which only guide the analysis.
669pub(crate) struct StripHints;
670impl VisitMut for StripHints {
671    fn visit_attributes_mut(&mut self, attrs: &mut Vec<syn::Attribute>) {
672        // Branches use their own copy of a `fresh` binding, so the original may go unused.
673        for a in attrs.iter_mut().filter(|a| is_psync_attr(a, "fresh")) {
674            *a = syn::parse_quote!(#[allow(unused_variables)]);
675        }
676        attrs.retain(|a| !HINTS.iter().any(|h| is_psync_attr(a, h)));
677    }
678    fn visit_expr_for_loop_mut(&mut self, f: &mut syn::ExprForLoop) {
679        self.visit_attributes_mut(&mut f.attrs);
680        syn::visit_mut::visit_expr_for_loop_mut(self, f);
681    }
682    fn visit_local_mut(&mut self, l: &mut syn::Local) {
683        self.visit_attributes_mut(&mut l.attrs);
684        syn::visit_mut::visit_local_mut(self, l);
685    }
686    fn visit_stmt_mut(&mut self, s: &mut Stmt) {
687        if let Stmt::Expr(e, _) = s {
688            strip_expr_hints(e);
689        }
690        syn::visit_mut::visit_stmt_mut(self, s);
691    }
692    fn visit_expr_while_mut(&mut self, w: &mut syn::ExprWhile) {
693        self.visit_attributes_mut(&mut w.attrs);
694        syn::visit_mut::visit_expr_while_mut(self, w);
695    }
696    fn visit_stmt_macro_mut(&mut self, m: &mut syn::StmtMacro) {
697        self.visit_attributes_mut(&mut m.attrs);
698    }
699}
700
701/// Removes hints from an expression statement's own attributes.
702fn strip_expr_hints(e: &mut syn::Expr) {
703    use syn::Expr::*;
704    let attrs = match e {
705        Try(t) => &mut t.attrs,
706        Await(a) => &mut a.attrs,
707        MethodCall(m) => &mut m.attrs,
708        Call(c) => &mut c.attrs,
709        If(i) => &mut i.attrs,
710        Match(m) => &mut m.attrs,
711        Assign(a) => &mut a.attrs,
712        Block(b) => &mut b.attrs,
713        _ => return,
714    };
715    attrs.retain(|a| !HINTS.iter().any(|h| is_psync_attr(a, h)));
716}