Skip to main content

psync_graph/
exits.rs

1//! Deferring early exits.
2//!
3//! When a node runs inside a concurrent chain, its `?`, `return`, `break` and `continue` cannot
4//! leave the function or loop from inside the chain's future. [`ExitRewriter`] replaces each one
5//! with "record the exit in a slot, then stop this chain" (`break '__psync_chainN None`), and
6//! [`Slots::reraise`] performs the recorded exit after the join. Re-raising node by node in
7//! program order makes the function exit exactly where sequential code would have, with the same
8//! error value (the original `?` conversion happens at the re-raise).
9
10use proc_macro2::{Ident, TokenStream};
11use quote::{format_ident, quote};
12use syn::{Expr, visit_mut::VisitMut};
13
14/// The exit slots of one node, declared as `let mut slot = None;` before its chain runs.
15#[derive(Default)]
16pub(crate) struct Slots {
17    /// One per `?`: holds the residual (`Err` or `None`) if that `?` failed.
18    tries: Vec<Ident>,
19    /// Holds the value of a `return`.
20    ret: Option<Ident>,
21    /// Holds which `break`/`continue` was taken, as an index into `ctl_targets`.
22    ctl: Option<Ident>,
23    /// The statements that re-perform each recorded `break`/`continue`.
24    ctl_targets: Vec<TokenStream>,
25}
26
27impl Slots {
28    /// All slot variables, in declaration order.
29    pub fn idents(&self) -> Vec<Ident> {
30        self.tries
31            .iter()
32            .chain(&self.ret)
33            .chain(&self.ctl)
34            .cloned()
35            .collect()
36    }
37
38    /// Statements that perform the recorded exit, if any, through `krate`'s runtime helpers.
39    pub fn reraise(&self, krate: &TokenStream) -> TokenStream {
40        let tries = &self.tries;
41        let ret = self.ret.iter();
42        let ctl = self.ctl.iter().map(|c| {
43            let arms = self
44                .ctl_targets
45                .iter()
46                .enumerate()
47                .map(|(k, t)| quote!(::core::option::Option::Some(#k) => { #t; }));
48            quote!(match #c { #(#arms)* _ => {} })
49        });
50        quote! {
51            #(if let ::core::option::Option::Some(r) = #tries { #krate::__private::Rethrow::rethrow(r)?; })*
52            #(if let ::core::option::Option::Some(v) = #ret { return v; })*
53            #(#ctl)*
54        }
55    }
56}
57
58/// Rewrites the early exits of one node to record-and-stop. Closures, async blocks and nested
59/// items keep their own exits; loops and labeled blocks inside the node keep exits aimed at them.
60pub(crate) struct ExitRewriter<'a> {
61    /// The chain's label, the target of every rewritten exit.
62    chain: &'a syn::Lifetime,
63    /// Unique prefix for this node's slot names.
64    tag: String,
65    krate: &'a TokenStream,
66    pub slots: Slots,
67    local_labels: Vec<String>,
68    loop_depth: usize,
69    /// Rewriting statements of a loop's first part (fission): `chain` labels that loop, which is
70    /// stopped with a plain `break`, and exits aimed at it stay as written.
71    deferring: bool,
72}
73
74impl<'a> ExitRewriter<'a> {
75    /// Exits stop the chain labeled `chain` (`break 'chain None`).
76    pub fn new(chain: &'a syn::Lifetime, tag: String, krate: &'a TokenStream) -> Self {
77        Self {
78            chain,
79            tag,
80            krate,
81            slots: Slots::default(),
82            local_labels: Vec::new(),
83            loop_depth: 0,
84            deferring: false,
85        }
86    }
87
88    /// Exits that leave the loop labeled `chain` stop it and are recorded; `continue` and
89    /// `break` aimed at that loop stay as written.
90    pub fn deferring(chain: &'a syn::Lifetime, tag: String, krate: &'a TokenStream) -> Self {
91        Self {
92            deferring: true,
93            ..Self::new(chain, tag, krate)
94        }
95    }
96
97    /// True when a `break`/`continue` targets the loop being split, so it stays as written.
98    fn targets_own_loop(&self, label: Option<&syn::Lifetime>) -> bool {
99        self.deferring
100            && label.is_none_or(|l| l.ident == self.chain.ident)
101            && (label.is_some() || self.loop_depth == 0)
102    }
103
104    fn leaves(&self, label: Option<&syn::Lifetime>) -> bool {
105        match label {
106            Some(l) => {
107                let name = l.ident.to_string();
108                !name.starts_with("__psync") && !self.local_labels.contains(&name)
109            }
110            None => self.loop_depth == 0,
111        }
112    }
113
114    fn nested(&mut self, label: Option<String>, f: impl FnOnce(&mut Self)) {
115        let labeled = label.is_some();
116        if let Some(l) = label {
117            self.local_labels.push(l);
118        }
119        self.loop_depth += 1;
120        f(self);
121        self.loop_depth -= 1;
122        if labeled {
123            self.local_labels.pop();
124        }
125    }
126
127    /// `{ slot = Some(value); break 'chain None }` (a plain `break 'chain` when deferring).
128    fn record(&self, slot: &Ident, value: TokenStream) -> Expr {
129        let chain = self.chain;
130        let stop = if self.deferring {
131            quote!(break #chain)
132        } else {
133            quote!(break #chain (::core::option::Option::None))
134        };
135        syn::parse_quote!({
136            #slot = ::core::option::Option::Some(#value);
137            #stop
138        })
139    }
140
141    fn ctl(&mut self, target: TokenStream) -> Expr {
142        let slot = self
143            .slots
144            .ctl
145            .get_or_insert_with(|| format_ident!("__psync_c{}", self.tag))
146            .clone();
147        let index = self.slots.ctl_targets.len();
148        self.slots.ctl_targets.push(target);
149        self.record(&slot, quote!(#index))
150    }
151}
152
153impl VisitMut for ExitRewriter<'_> {
154    fn visit_expr_closure_mut(&mut self, _: &mut syn::ExprClosure) {}
155    fn visit_expr_async_mut(&mut self, _: &mut syn::ExprAsync) {}
156    fn visit_item_mut(&mut self, _: &mut syn::Item) {}
157
158    fn visit_expr_mut(&mut self, e: &mut Expr) {
159        match e {
160            Expr::ForLoop(f) => {
161                self.visit_expr_mut(&mut f.expr);
162                let label = f.label.as_ref().map(|l| l.name.ident.to_string());
163                self.nested(label, |s| s.visit_block_mut(&mut f.body));
164                return;
165            }
166            Expr::While(w) => {
167                self.visit_expr_mut(&mut w.cond);
168                let label = w.label.as_ref().map(|l| l.name.ident.to_string());
169                self.nested(label, |s| s.visit_block_mut(&mut w.body));
170                return;
171            }
172            Expr::Loop(l) => {
173                let label = l.label.as_ref().map(|l| l.name.ident.to_string());
174                self.nested(label, |s| s.visit_block_mut(&mut l.body));
175                return;
176            }
177            Expr::Block(b) if b.label.is_some() => {
178                let label = b.label.as_ref().map(|l| l.name.ident.to_string());
179                // A labeled block is not a loop: unlabeled `break`s inside still leave it.
180                if let Some(l) = label {
181                    self.local_labels.push(l);
182                    self.visit_block_mut(&mut b.block);
183                    self.local_labels.pop();
184                }
185                return;
186            }
187            _ => {}
188        }
189        // Rewrite inner exits first, so `a.await?.b()?` records both.
190        syn::visit_mut::visit_expr_mut(self, e);
191        let krate = self.krate;
192        let replacement: Option<Expr> = match e {
193            Expr::Try(t) => {
194                let slot = format_ident!("__psync_e{}_{}", self.tag, self.slots.tries.len());
195                self.slots.tries.push(slot.clone());
196                let inner = &t.expr;
197                let stop = self.record(&slot, quote!(r));
198                Some(syn::parse_quote! {
199                    match #krate::__private::Branch::branch(#inner) {
200                        ::core::result::Result::Ok(v) => v,
201                        ::core::result::Result::Err(r) => #stop,
202                    }
203                })
204            }
205            Expr::Return(r) => {
206                let slot = self
207                    .slots
208                    .ret
209                    .get_or_insert_with(|| format_ident!("__psync_r{}", self.tag))
210                    .clone();
211                let value = r.expr.as_ref().map(|v| quote!(#v)).unwrap_or(quote!(()));
212                Some(self.record(&slot, value))
213            }
214            Expr::Continue(c)
215                if self.leaves(c.label.as_ref()) && !self.targets_own_loop(c.label.as_ref()) =>
216            {
217                let label = &c.label;
218                Some(self.ctl(quote!(continue #label)))
219            }
220            Expr::Break(b)
221                if b.expr.is_none()
222                    && self.leaves(b.label.as_ref())
223                    && !self.targets_own_loop(b.label.as_ref()) =>
224            {
225                let label = &b.label;
226                Some(self.ctl(quote!(break #label)))
227            }
228            _ => None,
229        };
230        if let Some(r) = replacement {
231            *e = r;
232        }
233    }
234}