Skip to main content

psync_graph/
classify.rs

1//! Statement classification: which statements become graph nodes, and what each one does.
2//!
3//! A *node* is a statement psync may move: a binding of an awaited or pure value, an awaited
4//! expression statement, or an ordinary statement (an *effect*, kept in order with other effects).
5//! A *barrier* stays exactly where it is and splits the block into independent regions.
6//! Early exits (`?`, `return`, `break`, `continue`) inside a node are allowed: code generation
7//! records them and re-raises them in program order (see [`crate::exits`]).
8
9use crate::access::{Access, PURE_METHODS, Set, scan};
10use crate::effects::{self, Effect};
11use proc_macro2::{Delimiter, Ident, Span, TokenStream, TokenTree};
12use quote::ToTokens;
13use syn::{Attribute, Expr, Local, LocalInit, Pat, Stmt, spanned::Spanned, visit::Visit};
14
15/// Mutability facts about the enclosing function, needed to tell reads from writes.
16pub(crate) struct Scope {
17    /// `mut` bindings anywhere in the function.
18    pub mutable: Set,
19    /// Bindings that hold `&mut` values, including `&mut self`.
20    pub handles: Set,
21    /// `#[psync::fresh]` bindings and their initializers: each node that uses one evaluates the
22    /// initializer again instead of sharing the value (for example `&mut context.pool()`).
23    /// Keyed by name; holds the binding's own identifier (for hygiene) and its initializer.
24    pub fresh: std::collections::BTreeMap<String, (Ident, TokenStream)>,
25    /// Effect settings from the attribute (`strict`, `speculate`, `effects(..)`).
26    pub effects: effects::Config,
27    /// A synchronous function (Phase II): statements that block on the outside world, or carry
28    /// `#[psync::par]`, play the part of awaits, and levels run on threads.
29    pub sync: bool,
30}
31
32/// A movable statement and what the analysis knows about it.
33#[derive(Clone)]
34pub(crate) struct Node {
35    /// The statement as written.
36    pub stmt: Stmt,
37    /// Bindings it introduces, with their `mut` flag.
38    pub defs: Vec<(Ident, bool)>,
39    /// What it reads and writes.
40    pub acc: Access,
41    /// It awaits (outside nested closures and async blocks), or, in synchronous code, blocks.
42    pub awaits: bool,
43    /// Synchronous code: it blocks on the network or a process, or carries `#[psync::par]`.
44    pub blocks: bool,
45    /// An ordinary statement with possible side effects: it keeps its order relative to other
46    /// effects, and if it can exit early, later nodes wait for it.
47    pub effect: bool,
48    /// It contains `?`, `return`, `break` or `continue` that leave the statement.
49    pub exits: bool,
50    /// What it does to files, the network, services, processes and the environment.
51    pub effects: Vec<Effect>,
52    /// Awaited calls whose effect psync could not tell from their names.
53    pub unclassified: Vec<String>,
54    /// `#[psync::speculate]`: its writes may run ahead of earlier exits.
55    pub speculate: bool,
56    /// The compiler says it may panic on purpose: an exit for the speculation rule.
57    pub panics: bool,
58    /// `#[psync::independent]` on the statement: its effects commute with the others in its
59    /// region (two writes to different objects through one client).
60    pub independent: bool,
61    /// Short description for reports.
62    pub label: String,
63    /// Source line (0 when spans carry no location).
64    pub line: usize,
65    /// Last source line of the statement.
66    pub end_line: usize,
67}
68
69/// The outcome of classifying one statement.
70pub(crate) enum Class {
71    Node(Box<Node>),
72    /// Stays in place. Carries a reason when the statement awaits, for reports.
73    Barrier(Option<String>),
74}
75
76// ANCHOR: guard-awaits
77/// Awaited operations that acquire something held afterwards (a lock, permit or transaction).
78/// A statement that keeps the guard is a barrier; one that drops it inside a nested block (its own
79/// critical section) may still move, since the lock itself keeps mutual exclusion.
80const GUARD_AWAITS: &[&str] = &[
81    "lock",
82    "lock_owned",
83    "read",
84    "write",
85    "acquire",
86    "acquire_owned",
87    "acquire_many",
88    "begin",
89    "transaction",
90];
91// ANCHOR_END: guard-awaits
92
93// ANCHOR: delay-awaits
94/// Deliberate delays: their position is the point. Statements awaiting these are barriers.
95const DELAY_AWAITS: &[&str] = &["sleep", "sleep_until", "tick", "yield_now", "delay_for"];
96// ANCHOR_END: delay-awaits
97
98// ANCHOR: awaiting-macros
99/// Macros that await the futures they are given, with no `.await` in their tokens
100/// (`tokio::select!`, `futures::join!`). psync cannot see the calls inside them, so a statement
101/// using one is a barrier, and its effects are unknown writes.
102pub(crate) const AWAITING_MACROS: &[&str] = &["select", "select_biased", "join", "try_join"];
103// ANCHOR_END: awaiting-macros
104
105// ANCHOR: clock-calls
106/// Clock reads (`Instant::now()`, `started.elapsed()`): when they run relative to the waits
107/// around them is what they measure, so statements making them are barriers.
108const CLOCK_CALLS: &[&str] = &["now", "elapsed", "duration_since"];
109// ANCHOR_END: clock-calls
110
111/// Whether `tokens` call a clock function outside closures and async blocks (`f(..)`, `x.f(..)`).
112fn reads_clock(tokens: TokenStream) -> bool {
113    let tokens: Vec<TokenTree> = tokens.into_iter().collect();
114    tokens.iter().enumerate().any(|(i, t)| match t {
115        TokenTree::Ident(id) => {
116            CLOCK_CALLS.contains(&id.to_string().as_str())
117                && matches!(tokens.get(i + 1), Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Parenthesis)
118        }
119        // A closure or async block decides for itself when it runs.
120        TokenTree::Group(g) => {
121            let deferred = tokens[..i].iter().rev().take(2).any(|p| {
122                matches!(p, TokenTree::Punct(c) if c.as_char() == '|')
123                    || matches!(p, TokenTree::Ident(k) if k == "async" || k == "move")
124            });
125            !deferred && reads_clock(g.stream())
126        }
127        _ => false,
128    })
129}
130
131// ANCHOR: net-paths
132/// Synchronous calls that wait on the network or a process (Phase II): in a synchronous function,
133/// a statement making one plays the part of an await. A statement blocks when it names one of
134/// these paths *and* calls one of the methods that wait: `Command::new("git")` builds a command,
135/// `.output()` runs it, and `Command::Reply` or clap's `Command::parse_from` are no process at all.
136/// `reqwest` counts only through `reqwest::blocking`.
137const NET_PATHS: &[&str] = &["ureq", "TcpStream", "UdpSocket"];
138// ANCHOR_END: net-paths
139// ANCHOR: net-waits
140const NET_WAITS: &[&str] = &[
141    "connect",
142    "call",
143    "send",
144    "send_to",
145    "recv",
146    "recv_from",
147    "read_to_end",
148    "read_to_string",
149    "read_exact",
150];
151// ANCHOR_END: net-waits
152// ANCHOR: process-waits
153const PROCESS_WAITS: &[&str] = &["output", "status", "wait", "wait_with_output"];
154// ANCHOR_END: process-waits
155
156// ANCHOR: guard-methods
157/// Methods whose result, bound by a `let`, is a guard held afterwards (synchronous locks and
158/// `RefCell` borrows; `read` and `write` only without arguments, as on `RwLock`).
159const GUARD_METHODS: &[&str] = &["lock", "try_lock", "borrow", "borrow_mut", "read", "write"];
160// ANCHOR_END: guard-methods
161
162/// Scans tokens outside closures and async blocks, which decide for themselves when they run,
163/// and outside macro arguments, whose effects psync cannot see (`assert!(cmd.status()?..)` must
164/// not become a blocking statement with no effects).
165fn any_token(tokens: TokenStream, f: &dyn Fn(&[TokenTree], usize) -> bool) -> bool {
166    let tokens: Vec<TokenTree> = tokens.into_iter().collect();
167    tokens.iter().enumerate().any(|(i, t)| match t {
168        TokenTree::Group(g) => {
169            let deferred = tokens[..i].iter().rev().take(2).any(|p| {
170                matches!(p, TokenTree::Punct(c) if c.as_char() == '|')
171                    || matches!(p, TokenTree::Ident(k) if k == "async" || k == "move")
172            });
173            let macro_args =
174                i > 0 && matches!(&tokens[i - 1], TokenTree::Punct(c) if c.as_char() == '!');
175            !deferred && !macro_args && any_token(g.stream(), f)
176        }
177        _ => f(&tokens, i),
178    })
179}
180
181/// A synchronous call to the network or a process: a path that reaches one, and a method that
182/// waits for it.
183fn blocks_on_world(tokens: TokenStream) -> bool {
184    let named = |set: &'static [&'static str]| {
185        move |ts: &[TokenTree], i: usize| match &ts[i] {
186            TokenTree::Ident(id) if set.contains(&id.to_string().as_str()) => true,
187            TokenTree::Ident(id) if id == "reqwest" && set == NET_PATHS => {
188                matches!(ts.get(i + 3), Some(TokenTree::Ident(b)) if b == "blocking")
189            }
190            _ => false,
191        }
192    };
193    // `.output()` and `.call()`, and for the network also `TcpStream::connect(..)`.
194    let calls = |set: &'static [&'static str]| {
195        move |ts: &[TokenTree], i: usize| {
196            matches!(&ts[i], TokenTree::Ident(m) if set.contains(&m.to_string().as_str()))
197                && i > 0
198                && matches!(&ts[i - 1], TokenTree::Punct(p)
199                    if p.as_char() == '.' || (p.as_char() == ':' && set == NET_WAITS))
200                && matches!(ts.get(i + 1), Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Parenthesis)
201        }
202    };
203    let net = any_token(tokens.clone(), &named(NET_PATHS))
204        && any_token(tokens.clone(), &calls(NET_WAITS));
205    let process = any_token(
206        tokens.clone(),
207        &|ts, i| matches!(&ts[i], TokenTree::Ident(id) if id == "Command"),
208    ) && any_token(tokens, &calls(PROCESS_WAITS));
209    net || process
210}
211
212/// `.lock()`, `.borrow_mut()`, `.read()` and the like: the value may be a guard.
213fn takes_guard(tokens: TokenStream) -> bool {
214    any_token(tokens, &|ts, i| {
215        matches!(
216            (&ts[i], ts.get(i + 1), i.checked_sub(1).map(|p| &ts[p])),
217            (TokenTree::Ident(m), Some(TokenTree::Group(g)), Some(TokenTree::Punct(dot)))
218                if dot.as_char() == '.'
219                    && g.delimiter() == Delimiter::Parenthesis
220                    && g.stream().is_empty()
221                    && GUARD_METHODS.contains(&m.to_string().as_str())
222        )
223    })
224}
225
226// ANCHOR: log-macros
227/// Logging statements: treated as pure so they do not split regions.
228const LOG_MACROS: &[&str] = &["trace", "debug", "info", "warn", "error", "log"];
229// ANCHOR_END: log-macros
230
231// ANCHOR: pure-macros
232/// Macros that build values without side effects.
233const PURE_MACROS: &[&str] = &["format", "vec", "concat", "stringify"];
234// ANCHOR_END: pure-macros
235
236/// Finds awaits and early exits in an expression, without entering closures, async blocks or
237/// nested items (their awaits and exits belong to them).
238#[derive(Default)]
239pub(crate) struct Exits {
240    /// Labels of loops and blocks inside the expression; exits to them stay inside.
241    local_labels: Vec<String>,
242    /// Depth of unlabeled loops inside the expression.
243    loop_depth: usize,
244    pub awaits: bool,
245    pub exits: bool,
246    /// The awaited method or function names, to spot ordering-sensitive awaits.
247    pub awaited: Vec<String>,
248    /// The same names, only for awaits outside any nested block (a guard taken in a nested
249    /// block is released before the statement ends).
250    pub awaited_unscoped: Vec<String>,
251    /// Nesting depth of blocks inside the expression.
252    block_depth: usize,
253    /// Why the expression cannot be rewritten (an exit hidden in a macro, `yield`, ...).
254    pub blocker: Option<String>,
255}
256
257impl Exits {
258    pub fn of(e: &Expr) -> Self {
259        let mut x = Exits::default();
260        x.visit_expr(e);
261        x
262    }
263    pub fn of_stmt(s: &Stmt) -> Self {
264        let mut x = Exits::default();
265        x.visit_stmt(s);
266        x
267    }
268    fn leaves(&self, label: Option<&syn::Lifetime>) -> bool {
269        match label {
270            Some(l) => {
271                let name = l.ident.to_string();
272                !name.starts_with("__psync") && !self.local_labels.contains(&name)
273            }
274            None => self.loop_depth == 0,
275        }
276    }
277    fn in_loop(&mut self, label: Option<&syn::Label>, f: impl FnOnce(&mut Self)) {
278        match label {
279            Some(l) => {
280                self.local_labels.push(l.name.ident.to_string());
281                self.loop_depth += 1;
282                f(self);
283                self.loop_depth -= 1;
284                self.local_labels.pop();
285            }
286            None => {
287                self.loop_depth += 1;
288                f(self);
289                self.loop_depth -= 1;
290            }
291        }
292    }
293}
294
295impl<'ast> Visit<'ast> for Exits {
296    fn visit_expr_closure(&mut self, _: &'ast syn::ExprClosure) {}
297    fn visit_expr_async(&mut self, _: &'ast syn::ExprAsync) {}
298    fn visit_item(&mut self, _: &'ast syn::Item) {}
299    fn visit_block(&mut self, b: &'ast syn::Block) {
300        self.block_depth += 1;
301        syn::visit::visit_block(self, b);
302        self.block_depth -= 1;
303    }
304    fn visit_expr_await(&mut self, e: &'ast syn::ExprAwait) {
305        self.awaits = true;
306        self.awaited.push(callee(&e.base));
307        if self.block_depth == 0 {
308            self.awaited_unscoped.push(callee(&e.base));
309        }
310        syn::visit::visit_expr_await(self, e);
311    }
312    fn visit_expr_try(&mut self, e: &'ast syn::ExprTry) {
313        self.exits = true;
314        syn::visit::visit_expr_try(self, e);
315    }
316    fn visit_expr_return(&mut self, e: &'ast syn::ExprReturn) {
317        self.exits = true;
318        syn::visit::visit_expr_return(self, e);
319    }
320    fn visit_expr_yield(&mut self, e: &'ast syn::ExprYield) {
321        self.blocker.get_or_insert_with(|| "`yield`".into());
322        syn::visit::visit_expr_yield(self, e);
323    }
324    fn visit_expr_break(&mut self, e: &'ast syn::ExprBreak) {
325        if self.leaves(e.label.as_ref()) {
326            if e.expr.is_some() {
327                self.blocker
328                    .get_or_insert_with(|| "`break` with a value".into());
329            }
330            self.exits = true;
331        }
332        syn::visit::visit_expr_break(self, e);
333    }
334    fn visit_expr_continue(&mut self, e: &'ast syn::ExprContinue) {
335        if self.leaves(e.label.as_ref()) {
336            self.exits = true;
337        }
338    }
339    fn visit_expr_for_loop(&mut self, e: &'ast syn::ExprForLoop) {
340        self.visit_expr(&e.expr);
341        self.in_loop(e.label.as_ref(), |x| x.visit_block(&e.body));
342    }
343    fn visit_expr_while(&mut self, e: &'ast syn::ExprWhile) {
344        self.visit_expr(&e.cond);
345        self.in_loop(e.label.as_ref(), |x| x.visit_block(&e.body));
346    }
347    fn visit_expr_loop(&mut self, e: &'ast syn::ExprLoop) {
348        self.in_loop(e.label.as_ref(), |x| x.visit_block(&e.body));
349    }
350    fn visit_expr_block(&mut self, e: &'ast syn::ExprBlock) {
351        if let Some(l) = &e.label {
352            self.local_labels.push(l.name.ident.to_string());
353            self.visit_block(&e.block);
354            self.local_labels.pop();
355        } else {
356            self.visit_block(&e.block);
357        }
358    }
359    fn visit_macro(&mut self, m: &'ast syn::Macro) {
360        // Exits inside macro tokens cannot be rewritten, so they block the statement.
361        fn walk(ts: TokenStream, awaits: &mut bool, exits: &mut bool) {
362            for tt in ts {
363                match tt {
364                    TokenTree::Group(g) => walk(g.stream(), awaits, exits),
365                    TokenTree::Ident(i) if i == "await" => *awaits = true,
366                    TokenTree::Ident(i) if i == "return" => *exits = true,
367                    TokenTree::Punct(p) if p.as_char() == '?' => *exits = true,
368                    _ => {}
369                }
370            }
371        }
372        let name = macro_name(m);
373        let (mut awaits, mut exits) = (false, false);
374        walk(m.tokens.clone(), &mut awaits, &mut exits);
375        self.awaits |= awaits;
376        // `select!` and `join!` await what they are given; their calls are hidden in the tokens.
377        if AWAITING_MACROS.contains(&name.as_str()) {
378            self.awaits = true;
379            self.blocker.get_or_insert_with(|| {
380                format!("`{name}!` awaits calls psync cannot see inside the macro")
381            });
382        }
383        // Logging macros use `?x` and `%x` as field sigils, not as operators.
384        let exits = exits && !LOG_MACROS.contains(&name.as_str());
385        if exits
386            || matches!(
387                name.as_str(),
388                "bail" | "ensure" | "try" | "return_err" | "fail"
389            )
390        {
391            self.blocker
392                .get_or_insert_with(|| format!("`{name}!` may return early"));
393        }
394    }
395}
396
397pub(crate) fn macro_name(m: &syn::Macro) -> String {
398    m.path
399        .segments
400        .last()
401        .map(|s| s.ident.to_string())
402        .unwrap_or_default()
403}
404
405/// The name of an awaited call: `method` for `x.method(..)`, `Type::f` for `Type::f(..)`.
406fn callee(e: &Expr) -> String {
407    match e {
408        Expr::MethodCall(m) => m.method.to_string(),
409        Expr::Call(c) => match &*c.func {
410            Expr::Path(p) => {
411                let segs: Vec<String> = p
412                    .path
413                    .segments
414                    .iter()
415                    .map(|s| s.ident.to_string())
416                    .collect();
417                segs[segs.len().saturating_sub(2)..].join("::")
418            }
419            _ => "call".into(),
420        },
421        Expr::Macro(m) => format!("{}!", macro_name(&m.mac)),
422        Expr::Paren(p) => callee(&p.expr),
423        Expr::Try(t) => callee(&t.expr),
424        other => other
425            .to_token_stream()
426            .to_string()
427            .chars()
428            .take(18)
429            .collect(),
430    }
431}
432
433/// Cheap expressions without side effects, which may move freely relative to awaits.
434pub(crate) fn is_pure(e: &Expr) -> bool {
435    match e {
436        Expr::Lit(_) | Expr::Path(_) | Expr::Closure(_) | Expr::Range(_) => true,
437        Expr::Field(f) => is_pure(&f.base),
438        Expr::Reference(r) => r.mutability.is_none() && is_pure(&r.expr),
439        Expr::Paren(p) => is_pure(&p.expr),
440        Expr::Group(g) => is_pure(&g.expr),
441        Expr::Unary(u) => is_pure(&u.expr),
442        Expr::Binary(b) => is_pure(&b.left) && is_pure(&b.right),
443        Expr::Cast(c) => is_pure(&c.expr),
444        Expr::Index(i) => is_pure(&i.expr) && is_pure(&i.index),
445        Expr::Tuple(t) => t.elems.iter().all(is_pure),
446        Expr::Array(a) => a.elems.iter().all(is_pure),
447        Expr::Struct(s) => {
448            s.fields.iter().all(|f| is_pure(&f.expr)) && s.rest.as_ref().is_none_or(|r| is_pure(r))
449        }
450        // `if arch == "i686" { "i386" } else { arch }`: a choice between pure values.
451        Expr::If(i) => {
452            is_pure(&i.cond)
453                && pure_block(&i.then_branch)
454                && i.else_branch.as_ref().is_some_and(|(_, e)| match &**e {
455                    Expr::Block(b) => pure_block(&b.block),
456                    e => is_pure(e),
457                })
458        }
459        Expr::Block(b) if b.label.is_none() => pure_block(&b.block),
460        Expr::MethodCall(m) => {
461            // `path.join(name)`, `parts.join(", ")`; `handle.join()` (a thread) takes no argument.
462            (PURE_METHODS.contains(&m.method.to_string().as_str())
463                || (m.method == "join" && m.args.len() == 1))
464                && is_pure(&m.receiver)
465                && m.args.iter().all(is_pure)
466        }
467        Expr::Call(c) => {
468            // Constructors only: `T::new`, `T::from`, `Some(..)`, tuple structs.
469            let Expr::Path(p) = &*c.func else {
470                return false;
471            };
472            let last = p
473                .path
474                .segments
475                .last()
476                .map(|s| s.ident.to_string())
477                .unwrap_or_default();
478            let ctor = matches!(
479                last.as_str(),
480                "new" | "from" | "default" | "with_capacity" | "Some" | "Ok" | "Err"
481            ) || (p.path.segments.len() == 1 && last.starts_with(char::is_uppercase));
482            ctor && c.args.iter().all(is_pure)
483        }
484        Expr::Macro(m) => {
485            let e = Exits::of(&Expr::Macro(m.clone()));
486            PURE_MACROS.contains(&macro_name(&m.mac).as_str()) && !e.awaits && e.blocker.is_none()
487        }
488        _ => false,
489    }
490}
491
492/// A block that is a single pure expression.
493fn pure_block(b: &syn::Block) -> bool {
494    matches!(&b.stmts[..], [Stmt::Expr(e, None)] if is_pure(e))
495}
496
497/// A place expression whose evaluation has no side effects (a variable, field or pure index).
498pub(crate) fn is_place(e: &Expr) -> bool {
499    match e {
500        Expr::Path(_) => true,
501        Expr::Field(f) => is_place(&f.base),
502        Expr::Index(i) => is_place(&i.expr) && is_pure(&i.index),
503        Expr::Paren(p) => is_place(&p.expr),
504        Expr::Unary(u) => matches!(u.op, syn::UnOp::Deref(_)) && is_place(&u.expr),
505        _ => false,
506    }
507}
508
509/// Bindings introduced by a pattern, with their `mut` flag.
510pub(crate) fn pat_idents(pat: &Pat, out: &mut Vec<(Ident, bool)>) {
511    struct V<'a>(&'a mut Vec<(Ident, bool)>);
512    impl<'ast> Visit<'ast> for V<'_> {
513        fn visit_pat_ident(&mut self, p: &'ast syn::PatIdent) {
514            self.0.push((p.ident.clone(), p.mutability.is_some()));
515            syn::visit::visit_pat_ident(self, p);
516        }
517        // Enum variants and constants in patterns are not bindings.
518        fn visit_path(&mut self, _: &'ast syn::Path) {}
519    }
520    V(out).visit_pat(pat);
521}
522
523/// True when a pattern binds by reference (`ref x`), which cannot be handed between scopes.
524pub(crate) fn pat_has_ref(pat: &Pat) -> bool {
525    struct V(bool);
526    impl<'ast> Visit<'ast> for V {
527        fn visit_pat_ident(&mut self, p: &'ast syn::PatIdent) {
528            self.0 |= p.by_ref.is_some();
529            syn::visit::visit_pat_ident(self, p);
530        }
531    }
532    let mut v = V(false);
533    v.visit_pat(pat);
534    v.0
535}
536
537// ANCHOR: hints
538/// The hint attributes psync reads and removes from its output.
539pub(crate) const HINTS: &[&str] = &["seq", "fresh", "independent", "speculate", "par"];
540// ANCHOR_END: hints
541
542/// The attributes of an expression statement (`#[psync::speculate] api.delete(x).await?;`).
543pub(crate) fn expr_attrs(e: &Expr) -> &[Attribute] {
544    match e {
545        Expr::Try(t) => &t.attrs,
546        Expr::Await(a) => &a.attrs,
547        Expr::MethodCall(m) => &m.attrs,
548        Expr::Call(c) => &c.attrs,
549        Expr::If(i) => &i.attrs,
550        Expr::Match(m) => &m.attrs,
551        Expr::ForLoop(f) => &f.attrs,
552        Expr::While(w) => &w.attrs,
553        Expr::Assign(a) => &a.attrs,
554        Expr::Block(b) => &b.attrs,
555        _ => &[],
556    }
557}
558
559/// True for `#[psync::name]` (or a bare `#[graph]`).
560pub(crate) fn is_psync_attr(attr: &Attribute, name: &str) -> bool {
561    let segs: Vec<String> = attr
562        .path()
563        .segments
564        .iter()
565        .map(|s| s.ident.to_string())
566        .collect();
567    segs.last().is_some_and(|l| l == name)
568        && (segs.len() == 1 && name == "graph" || segs.first().is_some_and(|f| f == "psync"))
569}
570
571/// Last source line of a span (see [`line_of`]).
572pub(crate) fn end_line_of(span: Span) -> usize {
573    #[cfg(feature = "cli")]
574    {
575        span.end().line
576    }
577    #[cfg(not(feature = "cli"))]
578    {
579        let _ = span;
580        0
581    }
582}
583
584/// Source line of a span; only known when proc-macro2 tracks locations (the `cli` feature).
585pub(crate) fn line_of(span: Span) -> usize {
586    #[cfg(feature = "cli")]
587    {
588        span.start().line
589    }
590    #[cfg(not(feature = "cli"))]
591    {
592        let _ = span;
593        0
594    }
595}
596
597/// Every name bound by a pattern anywhere inside `block`.
598pub(crate) fn bindings_in(block: &syn::Block) -> Set {
599    struct V(Set);
600    impl<'ast> Visit<'ast> for V {
601        fn visit_pat_ident(&mut self, p: &'ast syn::PatIdent) {
602            self.0.insert(p.ident.to_string());
603            syn::visit::visit_pat_ident(self, p);
604        }
605    }
606    let mut v = V(Set::new());
607    v.visit_block(block);
608    v.0
609}
610
611/// Every name bound by a pattern anywhere inside `stmt`, except the statement's own bindings.
612pub(crate) fn inner_bindings(stmt: &Stmt) -> Set {
613    struct V(Set);
614    impl<'ast> Visit<'ast> for V {
615        fn visit_pat_ident(&mut self, p: &'ast syn::PatIdent) {
616            self.0.insert(p.ident.to_string());
617            syn::visit::visit_pat_ident(self, p);
618        }
619    }
620    let mut v = V(Set::new());
621    match stmt {
622        Stmt::Local(l) => {
623            if let Some(init) = &l.init {
624                v.visit_expr(&init.expr);
625                if let Some((_, d)) = &init.diverge {
626                    v.visit_expr(d);
627                }
628            }
629        }
630        other => v.visit_stmt(other),
631    }
632    v.0
633}
634
635/// Short label for reports: the bindings and the first awaited call.
636fn label_for(defs: &[(Ident, bool)], stmt: &Stmt, x: &Exits) -> String {
637    let rhs = match x.awaited.first() {
638        Some(c) if c.ends_with('!') => c.clone(),
639        Some(c) => format!("{c}()"),
640        None => match stmt {
641            Stmt::Macro(m) => format!("{}!", macro_name(&m.mac)),
642            // A binding of a computed value: show the value, not the whole statement.
643            Stmt::Local(Local {
644                init: Some(init), ..
645            }) => {
646                let text = init.expr.to_token_stream().to_string();
647                match text.char_indices().nth(23) {
648                    Some((cut, _)) => format!("{}…", &text[..cut]),
649                    None => text,
650                }
651            }
652            _ => stmt
653                .to_token_stream()
654                .to_string()
655                .chars()
656                .take(24)
657                .collect(),
658        },
659    };
660    let rhs = if x.exits { format!("{rhs}?") } else { rhs };
661    if defs.is_empty() {
662        rhs
663    } else {
664        let names: Vec<String> = defs.iter().map(|(i, _)| i.to_string()).collect();
665        format!("{} = {rhs}", names.join(", "))
666    }
667}
668
669/// Classify one statement.
670///
671/// `relaxed` admits bindings of non-pure, non-awaited values as movable (not effects); it is used
672/// for a loop iteration's leading statements, which the caller confines to per-iteration data.
673pub(crate) fn classify(stmt: &Stmt, scope: &Scope, relaxed: bool) -> Class {
674    let seq = |attrs: &[Attribute]| attrs.iter().any(|a| is_psync_attr(a, "seq"));
675    let x = Exits::of_stmt(stmt);
676    let describe = |why: &str| {
677        x.awaits.then(|| {
678            let text: String = stmt
679                .to_token_stream()
680                .to_string()
681                .chars()
682                .take(60)
683                .collect();
684            format!("line {}: `{text}`: {why}", line_of(stmt.span()))
685        })
686    };
687    // What kind of statement this is: `(attributes, pattern, value)` for bindings, and whether
688    // it is a binding/await of a value (`shaped`) or an ordinary statement.
689    let (attrs, pat, value, shaped): (&[Attribute], Option<&Pat>, Option<&Expr>, bool) = match stmt
690    {
691        Stmt::Local(Local {
692            attrs,
693            pat,
694            init: Some(LocalInit { expr, .. }),
695            ..
696        }) => (attrs, Some(pat), Some(expr), true),
697        Stmt::Local(_) => return Class::Barrier(None),
698        // Block-like statements (`if`, `match`, `for` without `;`) carry no semicolon even in the
699        // middle of a block; the caller keeps a block's final value expression in place.
700        Stmt::Expr(e, _) => {
701            let awaited = match e {
702                Expr::Await(_) => true,
703                Expr::Try(t) => matches!(&*t.expr, Expr::Await(_)),
704                _ => false,
705            };
706            (expr_attrs(e), None, Some(e), awaited)
707        }
708        Stmt::Macro(m) => (
709            &m.attrs,
710            None,
711            None,
712            LOG_MACROS.contains(&macro_name(&m.mac).as_str()),
713        ),
714        Stmt::Item(_) => return Class::Barrier(None),
715    };
716    if seq(attrs) {
717        return Class::Barrier(describe("marked #[psync::seq]"));
718    }
719    // A `#[psync::fresh]` binding stays where it is; nodes re-create it instead of sharing it.
720    if attrs.iter().any(|a| is_psync_attr(a, "fresh")) {
721        return Class::Barrier(None);
722    }
723    if let Some(why) = &x.blocker {
724        return Class::Barrier(describe(why));
725    }
726    if reads_clock(stmt.to_token_stream()) {
727        // Reported even without an await: it splits the awaits around it into two regions,
728        // which is worth knowing when they do not overlap.
729        let text: String = stmt
730            .to_token_stream()
731            .to_string()
732            .chars()
733            .take(60)
734            .collect();
735        return Class::Barrier(Some(format!(
736            "line {}: `{text}`: reads the clock, whose position is meaningful",
737            line_of(stmt.span())
738        )));
739    }
740    if pat.is_some_and(pat_has_ref) {
741        return Class::Barrier(describe("`ref` binding"));
742    }
743    let delay = x
744        .awaited
745        .iter()
746        .find(|m| DELAY_AWAITS.contains(&m.as_str()));
747    let guard = x
748        .awaited_unscoped
749        .iter()
750        .find(|m| GUARD_AWAITS.contains(&m.as_str()));
751    if let Some(m) = delay.or(guard) {
752        return Class::Barrier(describe(&format!(
753            "awaits `{m}`, whose position is meaningful"
754        )));
755    }
756    // Phase II: in synchronous code a blocking statement is what overlaps, as an await is in
757    // async code, and a guard held by a binding keeps its place as an awaited lock does.
758    let blocks = scope.sync
759        && (attrs.iter().any(|a| is_psync_attr(a, "par"))
760            || blocks_on_world(stmt.to_token_stream()));
761    if scope.sync
762        && let Stmt::Local(l) = stmt
763        && l.init
764            .as_ref()
765            .is_some_and(|i| takes_guard(i.expr.to_token_stream()))
766    {
767        return Class::Barrier(None);
768    }
769    let awaits = x.awaits || blocks;
770    let shaped = shaped || blocks;
771    let pure_value = value.is_some_and(is_pure) || matches!(stmt, Stmt::Macro(_));
772    let mut effect = !shaped || (!awaits && !relaxed && !pure_value);
773    let mut defs = Vec::new();
774    if let Some(p) = pat {
775        pat_idents(p, &mut defs);
776    }
777    let mut acc = Access::default();
778    let tokens = match (stmt, value) {
779        (Stmt::Local(l), _) => {
780            let mut tokens = TokenStream::new();
781            if let Some(init) = &l.init {
782                tokens.extend(init.expr.to_token_stream());
783                if let Some((_, diverge)) = &init.diverge {
784                    tokens.extend(diverge.to_token_stream());
785                }
786            }
787            tokens
788        }
789        (Stmt::Macro(m), _) => m.mac.tokens.clone(),
790        (_, Some(v)) => v.to_token_stream(),
791        _ => TokenStream::new(),
792    };
793    scan(tokens, &scope.mutable, &scope.handles, &mut acc);
794    // Variables bound inside the statement (match arms, nested `let`s) are its own business.
795    let inner = inner_bindings(stmt);
796    acc.wpaths
797        .retain(|p| !inner.contains(crate::access::root(p)));
798    acc.writes.retain(|w| !inner.contains(w));
799    // `#[psync::fresh]` bindings are re-created for each node, so using one is no conflict.
800    acc.wpaths
801        .retain(|p| !scope.fresh.contains_key(crate::access::root(p)));
802    acc.rpaths
803        .retain(|p| !scope.fresh.contains_key(crate::access::root(p)));
804    if relaxed && !shaped {
805        // In a loop prefix, an ordinary statement may join only if it writes nothing (a guard
806        // like `if done { continue; }`); its exits are replayed in order like any other.
807        if !acc.wpaths.is_empty() || matches!(stmt, Stmt::Macro(_)) {
808            return Class::Barrier(None);
809        }
810        effect = false;
811    }
812    let mut found = effects::of_stmt_in(stmt, &scope.effects, scope.sync);
813    // A blocking statement whose calls psync cannot classify is what an unclassified awaited call
814    // is in async code: reported, and under `strict` a write to anything.
815    if blocks && found.effects.is_empty() {
816        let mut v = value;
817        while let Some(e) = v {
818            v = match e {
819                Expr::Try(t) => Some(&*t.expr),
820                Expr::MethodCall(m)
821                    if matches!(m.method.to_string().as_str(), "unwrap" | "expect") =>
822                {
823                    Some(&*m.receiver)
824                }
825                _ => break,
826            };
827        }
828        let op = v.map_or_else(|| "statement".to_string(), callee);
829        if scope.effects.unclassified_writes() {
830            found.effects.push(effects::Effect {
831                domain: effects::Domain::Unknown,
832                kind: effects::Kind::Write,
833                target: effects::Target::Any,
834                op: op.clone(),
835                ordered: true,
836                source: None,
837            });
838        }
839        found.unclassified.push(op);
840    }
841    // A receiver bound inside the statement (`let mut s = TcpStream::connect(..)?; s.write_all(..)`)
842    // is that statement's own: different receivers are different services, so it is named
843    // apart from another statement's `s`. Identical statements keep the same name, and conflict.
844    for e in &mut found.effects {
845        if let effects::Domain::Service(Some(r)) = &mut e.domain
846            && inner.contains(crate::access::root(r))
847        {
848            use std::hash::{Hash, Hasher};
849            let mut h = std::collections::hash_map::DefaultHasher::new();
850            stmt.to_token_stream().to_string().hash(&mut h);
851            *r = format!("{r}@{:x}", h.finish() & 0xffff_ffff);
852        }
853    }
854    // ANCHOR: hint_flags
855    let speculate = scope.effects.speculate || attrs.iter().any(|a| is_psync_attr(a, "speculate"));
856    Class::Node(Box::new(Node {
857        effects: found.effects,
858        unclassified: found.unclassified,
859        panics: found.panics,
860        speculate,
861        independent: scope.effects.independent()
862            || attrs.iter().any(|a| is_psync_attr(a, "independent")),
863        // ANCHOR_END: hint_flags
864        stmt: stmt.clone(),
865        label: label_for(&defs, stmt, &x),
866        defs,
867        acc,
868        awaits,
869        blocks: blocks && !x.awaits,
870        effect,
871        exits: x.exits,
872        line: line_of(stmt.span()),
873        end_line: end_line_of(stmt.span()),
874    }))
875}