Skip to main content

psync_graph/
lib.rs

1//! Dependency analysis and code generation behind `#[psync::graph]`.
2//!
3//! This is Phase I step 2 of the psync proposal: a source-level pass that finds the awaits of an
4//! async function which do not depend on each other and runs them concurrently. It sees tokens
5//! only, so it is deliberately conservative, and the Rust compiler still type- and borrow-checks
6//! everything it generates (two branches that both need `&mut x` fail to compile; they never race).
7//!
8//! # Pipeline
9//!
10//! For every block of async code, innermost first (`rewrite.rs`):
11//!
12//! 1. **Classify** each statement (`classify.rs`) as a movable *node* or a *barrier* that stays in
13//!    place. Nodes are bindings, awaits, and ordinary statements (*effects*, kept in order with
14//!    each other). Barriers are block values, lock acquisitions, sleeps, and code psync cannot
15//!    rewrite (exits hidden in macros, `yield`).
16//! 2. **Expose** awaits hidden inside larger statements by hoisting them into bindings, in
17//!    evaluation order (`hoist.rs`).
18//! 3. **Graph** each run of nodes between barriers (`schedule.rs`): an edge where one node reads a
19//!    binding another defines, where their accesses to a variable or field conflict
20//!    (`access.rs`), where their effects on files, services, the network, processes or the
21//!    environment conflict (`effects.rs`), before a write that an earlier exit could skip, and
22//!    between ordinary statements.
23//! 4. **Schedule**: single-predecessor runs fuse into chains; the chains of each level run
24//!    concurrently, and their bindings are handed back in program order.
25//! 5. **Loops** (`loops.rs`): iterations' awaited prefixes run up to `bound` ahead while the rest of
26//!    each body runs in order; loop-carried state is split into a first pass (*fission*); work
27//!    behind an early-exit guard runs ahead when the guard would not exit.
28//!
29//! # What stays the same
30//!
31//! Results, bindings and early exits. A `?`, `return`, `break` or `continue` inside a node stops
32//! that node's chain and is performed after the join in program order (`exits.rs`), so the
33//! function exits from the same place with the same value. Recognized writes (`fs::write`,
34//! `api.delete`, `s3.put_object`, processes) never start before an earlier exit, and operations on
35//! one file or service keep their order (`effects.rs`). What can still differ is unclassified
36//! awaited work that sequential code would have skipped after an exit: by adding the attribute,
37//! the programmer asserts that such calls tolerate running speculatively; `explain` lists them and
38//! `strict` treats them as writes. Ordinary statements never move past each other, and locks,
39//! permits, transactions, sleeps and order-sensitive calls (`send`, `write`, `recv`, ...) keep
40//! their order.
41//!
42//! # Hints
43//!
44//! Where tokens cannot show what the programmer knows:
45//!
46//! - `#[psync::seq]` on a statement keeps it in place.
47//! - `#[psync::fresh]` on a `let` makes each concurrent branch evaluate the initializer again
48//!   (`let pool = &mut context.pool();` gives every query its own connection).
49//! - `#[psync::independent]` on a loop asserts that iterations do not depend on each other
50//!   (needed for `while` loops, whose condition psync cannot reason about); on a statement, that
51//!   its effects commute with those around it.
52//! - `#[psync::speculate]` on a statement or loop asserts that its writes may run although
53//!   sequential code would have exited first (idempotent uploads, cache fills).
54//!
55//! Function options: `bound = N`, `explain`, `off`, `strict` (unclassified awaited calls are
56//! writes), `speculate`, `effects(read(..), write(..), ordered(..))` (extra verbs), `crate = path`.
57//!
58//! `#[psync::graph(off)]` compiles the function as written, for comparisons; building with the
59//! environment variable `PSYNC_GRAPH=off` does the same for every annotated function.
60
61mod access;
62mod classify;
63#[cfg(feature = "cli")]
64pub mod cli;
65mod effects;
66mod facts;
67mod gates;
68
69extern crate proc_macro;
70mod exits;
71mod hoist;
72mod loops;
73pub mod predict;
74mod profile;
75mod rewrite;
76mod schedule;
77
78use classify::{Scope, is_psync_attr, pat_idents};
79pub use effects::Config as EffectConfig;
80pub use effects::{Calls, Verb, fs_reads, verb_of};
81use proc_macro2::TokenStream;
82use quote::{ToTokens, quote};
83use syn::{
84    Expr, ItemFn, Local, parse::Parser, punctuated::Punctuated, visit::Visit, visit_mut::VisitMut,
85};
86
87/// Options from `#[psync::graph(bound = N, explain, off, crate = path)]`.
88#[derive(Clone, Debug)]
89pub struct Options {
90    /// Compile the function as written (hints are only removed), for comparisons.
91    pub off: bool,
92    /// Maximum loop iterations running ahead at once (default 16).
93    pub bound: usize,
94    /// Print the dependency graph to stderr at expansion time.
95    pub explain: bool,
96    /// Path to the psync crate in generated code (default `::psync`).
97    pub krate: TokenStream,
98    /// `strict`, `speculate` and `effects(read(..), write(..), ordered(..))`.
99    pub effects: EffectConfig,
100    /// `yield_every = N`: every loop of async code yields to the executor every `N` iterations.
101    pub yield_every: Option<u32>,
102    /// Compile the function as written, timing every statement that awaits (`psync::profile`).
103    pub profile: bool,
104    /// Files are compared by what they are (device and inode, resolved path) at run time, not by
105    /// how their paths are spelled. On by default; `path_text` turns it off.
106    pub owned_files: bool,
107    /// `baseline = resync`: schedule the way an earlier tool would, for comparisons only.
108    pub baseline: Option<Baseline>,
109}
110
111/// Earlier tools' rules, applied to the same code so their speedups can be measured against
112/// psync's (book: *What is new, and what is not*).
113#[derive(Clone, Copy, Debug, PartialEq, Eq)]
114pub enum Baseline {
115    /// ReSynchronizer (Arteca, Tip and Schäfer, ECOOP 2021): awaits are started early and awaited
116    /// late within one block, never across a loop or a branch; effects are one per environment
117    /// (all files, all network), so any write orders every access to its environment; no
118    /// run-time checks and no hints.
119    Resync,
120}
121
122impl Default for Options {
123    fn default() -> Self {
124        Self {
125            off: false,
126            bound: 16,
127            explain: false,
128            krate: quote!(::psync),
129            effects: EffectConfig::default(),
130            yield_every: None,
131            profile: false,
132            owned_files: true,
133            baseline: None,
134        }
135    }
136}
137
138impl Options {
139    /// Parse the attribute's arguments.
140    pub fn parse(attr: TokenStream) -> syn::Result<Self> {
141        let mut options = Options::default();
142        let metas = Punctuated::<syn::Meta, syn::Token![,]>::parse_terminated.parse2(attr)?;
143        for meta in metas {
144            match &meta {
145                syn::Meta::Path(p) if p.is_ident("explain") => options.explain = true,
146                syn::Meta::Path(p) if p.is_ident("off") => options.off = true,
147                syn::Meta::Path(p) if p.is_ident("profile") => options.profile = true,
148                syn::Meta::Path(p) if p.is_ident("owned_files") => options.owned_files = true,
149                syn::Meta::Path(p) if p.is_ident("path_text") => options.owned_files = false,
150                syn::Meta::Path(p) if p.is_ident("strict") => options.effects.strict = true,
151                syn::Meta::Path(p) if p.is_ident("speculate") => options.effects.speculate = true,
152                syn::Meta::List(list) if list.path.is_ident("effects") => {
153                    list.parse_nested_meta(|kind| {
154                        let target = if kind.path.is_ident("read") {
155                            &mut options.effects.reads
156                        } else if kind.path.is_ident("write") {
157                            &mut options.effects.writes
158                        } else if kind.path.is_ident("ordered") {
159                            &mut options.effects.ordered
160                        } else {
161                            return Err(
162                                kind.error("expected `read(..)`, `write(..)` or `ordered(..)`")
163                            );
164                        };
165                        kind.parse_nested_meta(|verb| {
166                            let name = verb
167                                .path
168                                .get_ident()
169                                .ok_or_else(|| verb.error("expected a method or function name"))?;
170                            target.push(name.to_string());
171                            Ok(())
172                        })
173                    })?;
174                }
175                syn::Meta::NameValue(nv) if nv.path.is_ident("calls") => {
176                    use crate::effects::Calls;
177                    let name = match &nv.value {
178                        Expr::Path(p) => p.path.get_ident().map(|i| i.to_string()),
179                        _ => None,
180                    };
181                    options.effects.calls = Some(match name.as_deref() {
182                        Some("read") => Calls::Read,
183                        Some("write") => Calls::Write,
184                        Some("write_independent") => Calls::WriteIndependent,
185                        Some("independent") => Calls::Independent,
186                        _ => {
187                            return Err(syn::Error::new_spanned(
188                                &nv.value,
189                                "expected `calls = read`, `write`, `write_independent` or \
190                                 `independent`",
191                            ));
192                        }
193                    });
194                }
195                syn::Meta::NameValue(nv) if nv.path.is_ident("baseline") => match &nv.value {
196                    Expr::Path(p) if p.path.is_ident("resync") => {
197                        options.baseline = Some(Baseline::Resync);
198                    }
199                    _ => {
200                        return Err(syn::Error::new_spanned(
201                            &nv.value,
202                            "expected `baseline = resync`",
203                        ));
204                    }
205                },
206                syn::Meta::NameValue(nv) if nv.path.is_ident("bound") => {
207                    let Expr::Lit(syn::ExprLit {
208                        lit: syn::Lit::Int(n),
209                        ..
210                    }) = &nv.value
211                    else {
212                        return Err(syn::Error::new_spanned(
213                            &nv.value,
214                            "bound must be an integer",
215                        ));
216                    };
217                    options.bound = n.base10_parse()?;
218                    if options.bound == 0 {
219                        return Err(syn::Error::new_spanned(n, "bound must be at least 1"));
220                    }
221                }
222                syn::Meta::NameValue(nv) if nv.path.is_ident("yield_every") => {
223                    let Expr::Lit(syn::ExprLit {
224                        lit: syn::Lit::Int(n),
225                        ..
226                    }) = &nv.value
227                    else {
228                        return Err(syn::Error::new_spanned(
229                            &nv.value,
230                            "yield_every must be an integer",
231                        ));
232                    };
233                    let n: u32 = n.base10_parse()?;
234                    if n == 0 {
235                        return Err(syn::Error::new_spanned(
236                            nv,
237                            "yield_every must be at least 1",
238                        ));
239                    }
240                    options.yield_every = Some(n);
241                }
242                syn::Meta::NameValue(nv) if nv.path.is_ident("crate") => {
243                    options.krate = nv.value.to_token_stream();
244                }
245                _ => {
246                    return Err(syn::Error::new_spanned(
247                        meta,
248                        "expected `bound = N`, `explain`, `off`, `strict`, `speculate`, `effects(..)`, \
249                         `calls = ..`, `yield_every = N`, `profile`, `owned_files`, `path_text` or `crate = path`",
250                    ));
251                }
252            }
253        }
254        Ok(options)
255    }
256}
257
258/// What the analysis found, for `explain` and external tooling (`psync-expand`).
259#[derive(Clone, Debug, Default)]
260#[cfg_attr(feature = "cli", derive(serde::Serialize))]
261pub struct Report {
262    /// Every region with two or more awaits that was analyzed.
263    pub regions: Vec<RegionReport>,
264    /// Every `for` loop considered for prefetching.
265    pub loops: Vec<LoopReport>,
266    /// Await-containing statements kept in place, with the reason.
267    pub barriers: Vec<String>,
268    /// Unclassified calls were taken as writes (`strict`, or `calls = write..`).
269    pub unclassified_writes: bool,
270}
271
272/// The graph and schedule of one region.
273#[derive(Clone, Debug, Default)]
274#[cfg_attr(feature = "cli", derive(serde::Serialize))]
275pub struct RegionReport {
276    pub nodes: Vec<NodeReport>,
277    /// `(from, to, reason)`: `to` waits for `from`.
278    pub edges: Vec<(usize, usize, String)>,
279    /// Fused chains: node indices in program order.
280    pub chains: Vec<Vec<usize>>,
281    /// Chain indices that run concurrently, level by level.
282    pub levels: Vec<Vec<usize>>,
283    /// Some level runs two or more chains concurrently.
284    pub changed: bool,
285    /// `(line, call)`: awaited calls whose effect psync could not tell from their names. They are
286    /// assumed to read, unless the function is `strict`.
287    pub unclassified: Vec<(usize, String)>,
288    /// The certificate of this region's schedule: each node's places (see `verify/Cert.lean`).
289    /// With `chains` and `levels`, `psync-cert` turns it into a Lean check.
290    pub cert: Vec<CertNode>,
291    /// Pairs of chains that run concurrently because their computed file paths differ when
292    /// written, and that are ordered at run time if the paths turn out to overlap.
293    pub runtime_checks: usize,
294}
295
296/// One node as a certificate describes it: the places it may read and write, each a path of
297/// segments. Two nodes are independent when neither writes a place the other reads or writes, and
298/// places overlap when one is a prefix of the other.
299#[derive(Clone, Debug, Default, PartialEq, Eq)]
300#[cfg_attr(feature = "cli", derive(serde::Serialize))]
301pub struct CertNode {
302    pub reads: Vec<Vec<String>>,
303    pub writes: Vec<Vec<String>>,
304}
305
306/// One node of a region.
307#[derive(Clone, Debug, Default)]
308#[cfg_attr(feature = "cli", derive(serde::Serialize))]
309pub struct NodeReport {
310    pub label: String,
311    pub awaits: bool,
312    /// Synchronous code: it blocks, and may run on another thread.
313    pub blocks: bool,
314    pub effect: bool,
315    pub exits: bool,
316    pub line: usize,
317    /// The statement's last line (`line` for one on a single line).
318    pub end_line: usize,
319    /// Its effects on files, the network, services, processes and the environment.
320    pub effects: Vec<String>,
321    /// Its writes may run ahead of earlier exits (`#[psync::speculate]`).
322    pub speculate: bool,
323}
324
325impl From<&classify::Node> for NodeReport {
326    fn from(n: &classify::Node) -> Self {
327        Self {
328            label: n.label.clone(),
329            awaits: n.awaits,
330            blocks: n.blocks,
331            effect: n.effect,
332            exits: n.exits,
333            line: n.line,
334            end_line: n.end_line,
335            effects: n.effects.iter().map(effects::Effect::describe).collect(),
336            speculate: n.speculate,
337        }
338    }
339}
340
341/// One `for` loop and whether its iterations were prefetched.
342#[derive(Clone, Debug, Default)]
343#[cfg_attr(feature = "cli", derive(serde::Serialize))]
344pub struct LoopReport {
345    pub label: String,
346    /// Labels of the statements run ahead for each iteration.
347    pub prefetched: Vec<String>,
348    /// Their first and last source lines (0 when spans carry no location).
349    pub prefetched_lines: Vec<(usize, usize)>,
350    pub bound: usize,
351    pub changed: bool,
352    /// Why the loop was left alone.
353    pub reason: String,
354    /// For a prefetched loop whose items name their own files: `checked at run time`, or why
355    /// that could not be checked and distinct items are assumed.
356    pub check: String,
357    /// First and last source line of the loop (0 when spans carry no location).
358    pub line: usize,
359    pub end_line: usize,
360}
361
362/// Expand `#[psync::graph(attr)] item`.
363pub fn expand(attr: TokenStream, item: TokenStream) -> syn::Result<TokenStream> {
364    let mut options = Options::parse(attr)?;
365    let mut function: ItemFn = syn::parse2(item)?;
366    // `PSYNC_GRAPH=off` at build time compiles every annotated function as written, so one
367    // source tree can be built both ways for comparison.
368    if std::env::var("PSYNC_GRAPH").is_ok_and(|v| v == "off") {
369        options.off = true;
370    }
371    if options.off || options.profile {
372        function.attrs.retain(|a| !is_psync_attr(a, "graph"));
373        schedule::StripHints.visit_block_mut(&mut function.block);
374        if options.profile {
375            profile::instrument(&mut function.block, &options.krate);
376        }
377        return Ok(function.into_token_stream());
378    }
379    let report = transform_fn(&mut function, &options);
380    if options.explain {
381        eprintln!(
382            "psync::graph `{}`:\n{}",
383            function.sig.ident,
384            explain(&report)
385        );
386    }
387    Ok(function.into_token_stream())
388}
389
390/// Rewrite every async block in `function` (its body if it is `async`, and any async blocks or
391/// closures inside), returning what was found.
392pub fn transform_fn(function: &mut ItemFn, options: &Options) -> Report {
393    let mut scope = Scope {
394        mutable: Default::default(),
395        handles: Default::default(),
396        fresh: Default::default(),
397        effects: options.effects.clone(),
398        sync: function.sig.asyncness.is_none(),
399    };
400    for input in &function.sig.inputs {
401        match input {
402            // `&mut self` is a unique handle; `mut self` is an owned mutable binding.
403            syn::FnArg::Receiver(r) if r.mutability.is_some() => {
404                let set = if r.reference.is_some() {
405                    &mut scope.handles
406                } else {
407                    &mut scope.mutable
408                };
409                set.insert("self".into());
410            }
411            syn::FnArg::Typed(t) => {
412                let mut ids = Vec::new();
413                pat_idents(&t.pat, &mut ids);
414                let mut_ref = matches!(&*t.ty, syn::Type::Reference(r) if r.mutability.is_some());
415                for (id, is_mut) in ids {
416                    if mut_ref {
417                        scope.handles.insert(id.to_string());
418                    } else if is_mut {
419                        scope.mutable.insert(id.to_string());
420                    }
421                }
422            }
423            _ => {}
424        }
425    }
426    Declarations(&mut scope).visit_block(&function.block);
427    let mut rewriter = rewrite::Rewriter {
428        options,
429        scope,
430        report: Report::default(),
431        // In a synchronous function the body itself is rewritten (Phase II).
432        in_async: true,
433        fresh: 0,
434        refusal: None,
435        loop_check: String::new(),
436        loop_lines: Vec::new(),
437    };
438    rewriter.visit_block_mut(&mut function.block);
439    if let Some(every) = options.yield_every {
440        YieldInjector {
441            krate: &options.krate,
442            every,
443            in_async: function.sig.asyncness.is_some(),
444        }
445        .visit_block_mut(&mut function.block);
446    }
447    // Marks the function for `cargo psync`'s driver (which records facts about its calls), and
448    // makes cargo rebuild it when the facts change (`option_env!` is tracked).
449    function.block.stmts.insert(
450        0,
451        syn::parse_quote! {
452            #[allow(dead_code)]
453            const __PSYNC_GRAPH: ::core::option::Option<&str> =
454                ::core::option_env!("PSYNC_FACTS_STAMP");
455        },
456    );
457    function.attrs.retain(|a| !is_psync_attr(a, "graph"));
458    schedule::StripHints.visit_block_mut(&mut function.block);
459    let mut report = rewriter.report;
460    report.unclassified_writes = options.effects.unclassified_writes();
461    report
462}
463
464/// `yield_every = N`: at the start of every loop body in async code, yield to the executor on
465/// every `N`-th iteration. A cooperative executor cannot interrupt a task that does not await;
466/// these yields are preemption points the compiler inserts, so a long loop no longer holds
467/// back higher-priority tasks. They change timing only, never results.
468struct YieldInjector<'a> {
469    krate: &'a TokenStream,
470    every: u32,
471    in_async: bool,
472}
473
474impl YieldInjector<'_> {
475    fn inject(&self, body: &mut syn::Block) {
476        let (krate, every) = (self.krate, self.every);
477        body.stmts.insert(
478            0,
479            syn::parse_quote! {
480                if #krate::__private::tick(
481                    {
482                        static __PSYNC_TICKS: ::core::sync::atomic::AtomicU32 =
483                            ::core::sync::atomic::AtomicU32::new(0);
484                        &__PSYNC_TICKS
485                    },
486                    #every,
487                ) {
488                    #krate::__private::yield_now().await;
489                }
490            },
491        );
492    }
493}
494
495impl VisitMut for YieldInjector<'_> {
496    fn visit_expr_async_mut(&mut self, e: &mut syn::ExprAsync) {
497        let outer = std::mem::replace(&mut self.in_async, true);
498        syn::visit_mut::visit_expr_async_mut(self, e);
499        self.in_async = outer;
500    }
501    fn visit_expr_closure_mut(&mut self, e: &mut syn::ExprClosure) {
502        let outer = std::mem::replace(&mut self.in_async, e.asyncness.is_some());
503        syn::visit_mut::visit_expr_closure_mut(self, e);
504        self.in_async = outer;
505    }
506    fn visit_item_mut(&mut self, _: &mut syn::Item) {}
507    fn visit_expr_for_loop_mut(&mut self, e: &mut syn::ExprForLoop) {
508        syn::visit_mut::visit_expr_for_loop_mut(self, e);
509        if self.in_async {
510            self.inject(&mut e.body);
511        }
512    }
513    fn visit_expr_while_mut(&mut self, e: &mut syn::ExprWhile) {
514        syn::visit_mut::visit_expr_while_mut(self, e);
515        if self.in_async {
516            self.inject(&mut e.body);
517        }
518    }
519    fn visit_expr_loop_mut(&mut self, e: &mut syn::ExprLoop) {
520        syn::visit_mut::visit_expr_loop_mut(self, e);
521        if self.in_async {
522            self.inject(&mut e.body);
523        }
524    }
525}
526
527/// Collects `let mut` bindings, bindings to `&mut` expressions, and `#[psync::fresh]` bindings
528/// anywhere in the function.
529struct Declarations<'a>(&'a mut Scope);
530impl<'ast> Visit<'ast> for Declarations<'_> {
531    fn visit_local(&mut self, local: &'ast Local) {
532        let mut ids = Vec::new();
533        pat_idents(&local.pat, &mut ids);
534        if local.attrs.iter().any(|a| is_psync_attr(a, "fresh"))
535            && let ([(id, _)], Some(init)) = (&ids[..], &local.init)
536        {
537            self.0
538                .fresh
539                .insert(id.to_string(), (id.clone(), init.expr.to_token_stream()));
540            return;
541        }
542        let handle = local
543            .init
544            .as_ref()
545            .is_some_and(|i| matches!(&*i.expr, Expr::Reference(r) if r.mutability.is_some()));
546        for (id, is_mut) in ids {
547            if handle {
548                self.0.handles.insert(id.to_string());
549            } else if is_mut {
550                self.0.mutable.insert(id.to_string());
551            }
552        }
553        syn::visit::visit_local(self, local);
554    }
555    fn visit_pat_ident(&mut self, p: &'ast syn::PatIdent) {
556        if p.mutability.is_some() {
557            self.0.mutable.insert(p.ident.to_string());
558        }
559        syn::visit::visit_pat_ident(self, p);
560    }
561}
562
563/// Human-readable summary of a report (what `explain` prints).
564pub fn explain(report: &Report) -> String {
565    let mut out = String::new();
566    for (r, region) in report.regions.iter().enumerate() {
567        out += &format!(
568            "  region {r}{}:\n",
569            if region.changed { "" } else { " (unchanged)" }
570        );
571        for (i, n) in region.nodes.iter().enumerate() {
572            out += &format!(
573                "    n{i}: {}{}{}\n",
574                n.label,
575                if n.blocks {
576                    " [blocks]"
577                } else if n.awaits {
578                    " [await]"
579                } else {
580                    ""
581                },
582                if n.effects.is_empty() {
583                    String::new()
584                } else {
585                    format!(" {{{}}}", n.effects.join("; "))
586                }
587            );
588        }
589        for (a, b, why) in &region.edges {
590            out += &format!("    n{a} -> n{b} ({why})\n");
591        }
592        for (l, level) in region.levels.iter().enumerate() {
593            let chains: Vec<String> = level
594                .iter()
595                .map(|c| {
596                    region.chains[*c]
597                        .iter()
598                        .map(|n| format!("n{n}"))
599                        .collect::<Vec<_>>()
600                        .join("->")
601                })
602                .collect();
603            out += &format!("    level {l}: {}\n", chains.join(" || "));
604        }
605        if region.runtime_checks > 0 {
606            out += &format!(
607                "    targets compared at run time: {} pair(s) of chains wait for each other if \
608                 their files, URLs or keys overlap\n",
609                region.runtime_checks
610            );
611        }
612    }
613    for l in &report.loops {
614        let what = if l.changed {
615            let check = if l.check.is_empty() {
616                String::new()
617            } else {
618                format!("; per-item targets {}", l.check)
619            };
620            format!(
621                "prefetch [{}], {} at a time{check}",
622                l.prefetched.join(", "),
623                l.bound
624            )
625        } else {
626            l.reason.clone()
627        };
628        out += &format!("  loop `{}`: {what}\n", l.label);
629    }
630    let mut unclassified: Vec<String> = Vec::new();
631    for region in &report.regions {
632        for (_, call) in &region.unclassified {
633            if !unclassified.contains(call) {
634                unclassified.push(call.clone());
635            }
636        }
637    }
638    if !unclassified.is_empty() {
639        let how = if report.unclassified_writes {
640            "taken as writes"
641        } else {
642            "assumed to read; `strict` treats them as writes"
643        };
644        out += &format!("  unclassified ({how}): {}\n", unclassified.join(", "));
645    }
646    for b in &report.barriers {
647        out += &format!("  barrier: {b}\n");
648    }
649    out
650}
651
652#[cfg(test)]
653mod tests {
654    /// The certificate is never more lenient than psync: every edge psync draws is a conflict
655    /// between the two nodes' places, so `verify/Cert.lean` can only reject what psync accepted,
656    /// not accept what psync would not. Checked over every annotated function of the graph
657    /// tests, the driver fixture and `graph_suite`.
658    /// Synchronous code (Phase II): a blocking call is classified by its verb as an awaited one is,
659    /// so a delete and a get of one name keep their order; a receiver bound inside a statement is
660    /// that statement's own, so two downloads over their own sockets do not conflict.
661    #[test]
662    fn synchronous_calls_have_effects() {
663        let r = report(
664            Options::default(),
665            syn::parse_quote! {
666                fn recreate(client: &Client, name: &str) -> Result<u32, E> {
667                    #[psync::par]
668                    client.delete(name)?;
669                    #[psync::par]
670                    let v = client.get(name)?;
671                    Ok(v)
672                }
673            },
674        );
675        assert!(
676            edges(&r).iter().any(|e| e.contains("delete")),
677            "{:?}",
678            edges(&r)
679        );
680        assert!(!r.regions[0].changed);
681        let r = report(
682            Options::default(),
683            syn::parse_quote! {
684                fn two(addr: Addr) -> std::io::Result<usize> {
685                    let a = { let mut s = TcpStream::connect(addr)?; s.read_to_end(&mut v1)? };
686                    let b = { let mut s = TcpStream::connect(addr)?; s.read_to_end(&mut v2)? };
687                    Ok(a + b)
688                }
689            },
690        );
691        assert!(edges(&r).is_empty(), "{:?}", edges(&r));
692        assert!(r.regions[0].changed);
693    }
694
695    /// rustic's `diff`: `let path2 = path2.unwrap_or(path1);` sits between the two lookups and feeds
696    /// the second. `unwrap_or` was unclassified, so the statement was its own chain and delayed
697    /// the second lookup by a level; with pure arguments it is pure.
698    #[test]
699    fn cheap_statements_do_not_delay_waits() {
700        let mut f: ItemFn = syn::parse_quote! {
701            fn diff(repo: &Repo, path1: Option<&str>, path2: Option<&str>) -> Result<()> {
702                let snaps = repo.get_snapshots(&[1, 2])?;
703                let snap1 = &snaps[0];
704                let snap2 = &snaps[1];
705                let path1 = path1.unwrap_or("");
706                let path2 = path2.unwrap_or(path1);
707                info!("{path1} {path2}");
708                #[psync::par]
709                let node1 = repo.node(snap1, path1)?;
710                #[psync::par]
711                let node2 = repo.node(snap2, path2)?;
712                show(node1, node2)
713            }
714        };
715        let report = transform_fn(&mut f, &Options::default());
716        let r = &report.regions[0];
717        let level_of = |name: &str| {
718            let n = r
719                .nodes
720                .iter()
721                .position(|n| n.label.starts_with(name))
722                .unwrap();
723            let c = r.chains.iter().position(|c| c.contains(&n)).unwrap();
724            r.levels.iter().position(|l| l.contains(&c)).unwrap()
725        };
726        assert_eq!(level_of("node1"), level_of("node2"), "{:?}", r.levels);
727    }
728
729    /// tauri-bundler's `prepare_tools`: three cached downloads, with path joins and a choice
730    /// between two string literals in between. Those bindings are pure, and a node whose edges all
731    /// come from one chain joins that chain, so the three downloads start together.
732    #[test]
733    fn path_joins_and_pure_ifs_do_not_delay_downloads() {
734        let mut f: ItemFn = syn::parse_quote! {
735            fn prepare_tools(tools_path: &Path, arch: &str) -> Result<PathBuf> {
736                let apprun = tools_path.join(format!("AppRun-{arch}"));
737                #[psync::par]
738                #[psync::independent]
739                if !apprun.exists() {
740                    let data = download("apprun")?;
741                    write_and_make_executable(&apprun, &data)?;
742                }
743                let linuxdeploy_arch = if arch == "i686" { "i386" } else { arch };
744                let linuxdeploy = tools_path.join(format!("linuxdeploy-{linuxdeploy_arch}"));
745                #[psync::par]
746                #[psync::independent]
747                #[psync::speculate]
748                if !linuxdeploy.exists() {
749                    let data = download(&format!("linuxdeploy-{linuxdeploy_arch}"))?;
750                    write_and_make_executable(&linuxdeploy, &data)?;
751                }
752                Ok(linuxdeploy)
753            }
754        };
755        let report = transform_fn(&mut f, &Options::default());
756        let r = &report.regions[0];
757        let downloads: Vec<usize> = (0..r.nodes.len())
758            .filter(|&n| r.nodes[n].label.contains("psync :: par"))
759            .map(|n| {
760                let c = r.chains.iter().position(|c| c.contains(&n)).unwrap();
761                r.levels.iter().position(|l| l.contains(&c)).unwrap()
762            })
763            .collect();
764        assert_eq!(downloads, [0, 0], "{:?}", r.levels);
765    }
766
767    /// `p.exists()` reads the file system at `p`: in synchronous code it must not overlap a write
768    /// to `p` (it was a read of a service named `p`, which no file write conflicts with).
769    #[test]
770    fn path_exists_reads_the_file_system() {
771        let mut f: ItemFn = syn::parse_quote! {
772            fn f(p: &Path) -> std::io::Result<bool> {
773                #[psync::par]
774                let there = p.exists();
775                #[psync::par]
776                std::fs::write(p, "x")?;
777                Ok(there)
778            }
779        };
780        let report = transform_fn(&mut f, &Options::default());
781        let r = &report.regions[0];
782        assert!(
783            r.edges.iter().any(|(a, b, _)| (*a, *b) == (0, 1)),
784            "{:?}",
785            r.levels
786        );
787    }
788
789    /// `let a = dir.join("a.json")`: a write to `&a` is a write to the file `dir/a.json`, which a
790    /// write to `dir/b-{x}` does not touch. A name that may be absolute (`/a`, a hole first, `C:`)
791    /// or a base that may change (`mut`) leaves the target unknown.
792    #[test]
793    fn owned_files_compares_even_literal_paths_at_run_time() {
794        // (chains, run-time checks) under the given options; two chains run side by side.
795        let plan = |options: &Options| {
796            let mut f: ItemFn = syn::parse_quote! {
797                fn f() -> std::io::Result<()> {
798                    #[psync::par]
799                    let old = std::fs::read_to_string("current.json")?;
800                    #[psync::par]
801                    std::fs::write("data/v2.json", fetch()?)?;
802                    Ok(())
803                }
804            };
805            let report = transform_fn(&mut f, options);
806            let r = &report.regions[0];
807            (r.chains.len(), r.runtime_checks)
808        };
809        // By text the two paths differ: side by side, nothing checked.
810        let mut text = Options {
811            owned_files: false,
812            ..Options::default()
813        };
814        text.effects.speculate = true;
815        assert_eq!(plan(&text), (2, 0));
816        // `current.json` may be a symlink to `data/v2.json`: still side by side, but gated.
817        let owned = Options {
818            owned_files: true,
819            ..text
820        };
821        assert_eq!(plan(&owned), (2, 1));
822        // A directory and a file in it overlap by their text: an edge, not a gate that always
823        // waits. Text that differs is compared by identity.
824        let mut f: ItemFn = syn::parse_quote! {
825            async fn f() -> std::io::Result<()> {
826                tokio::fs::remove_dir_all("out").await?;
827                let a = tokio::fs::read("out/a.txt").await?;
828                let b = tokio::fs::read("cfg.toml").await?;
829                Ok(())
830            }
831        };
832        let report = transform_fn(&mut f, &owned);
833        let r = &report.regions[0];
834        assert!(
835            r.edges.iter().any(|e| (e.0, e.1) == (0, 1)),
836            "{:?}",
837            r.edges
838        );
839        assert_eq!(r.runtime_checks, 1);
840    }
841
842    #[test]
843    fn joined_paths_name_their_files() {
844        // The levels of the two `par` statements, and the region's run-time checks.
845        fn levels(b: syn::Stmt, base_mut: bool) -> (Vec<usize>, usize) {
846            let first: syn::Stmt = if base_mut {
847                syn::parse_quote!(let mut dir = root.to_path_buf();)
848            } else {
849                syn::parse_quote!(let dir = root;)
850            };
851            let mut f: ItemFn = syn::parse_quote! {
852                fn f(root: &Path, x: &str) -> std::io::Result<()> {
853                    #first
854                    let a = dir.join("a.json");
855                    #b
856                    #[psync::par]
857                    if !a.exists() {
858                        std::fs::write(&a, fetch("a")?)?;
859                    }
860                    #[psync::par]
861                    #[psync::speculate]
862                    if !b.exists() {
863                        std::fs::write(&b, fetch("b")?)?;
864                    }
865                    Ok(())
866                }
867            };
868            let text = Options {
869                owned_files: false,
870                ..Options::default()
871            };
872            let report = transform_fn(&mut f, &text);
873            let r = &report.regions[0];
874            let levels = (0..r.nodes.len())
875                .filter(|&n| r.nodes[n].label.contains("psync :: par"))
876                .map(|n| {
877                    let c = r.chains.iter().position(|c| c.contains(&n)).unwrap();
878                    r.levels.iter().position(|l| l.contains(&c)).unwrap()
879                })
880                .collect();
881            (levels, r.runtime_checks)
882        }
883        let apart: syn::Stmt = syn::parse_quote!(let b = dir.join(format!("b-{x}")););
884        // Side by side with nothing to check at run time: the tokens show the files differ.
885        let together = |(l, checks): (Vec<usize>, usize)| l[0] == l[1] && checks == 0;
886        assert!(together(levels(apart.clone(), false)));
887        assert!(!together(levels(apart, true)), "a `mut` base");
888        for b in [
889            syn::parse_quote!(let b = dir.join("a.json");),
890            syn::parse_quote!(let b = dir.join(format!("{x}"));),
891            syn::parse_quote!(let b = dir.join("/b");),
892            syn::parse_quote!(let b = dir.join("C:b");),
893            syn::parse_quote!(let mut b = dir.join("b");),
894        ] {
895            let shown = quote::quote!(#b).to_string();
896            assert!(!together(levels(b, false)), "{shown}");
897        }
898        // `format!("{x}")` may be `a.json`: the two run side by side only behind a check of the
899        // paths when the function runs.
900        let (l, checks) = levels(syn::parse_quote!(let b = dir.join(format!("{x}"));), false);
901        assert_eq!((l[0] == l[1], checks), (true, 1));
902    }
903
904    /// `handle.join()` waits for a thread: unlike `path.join(name)`, it is not a pure value.
905    #[test]
906    fn thread_join_is_not_pure() {
907        let e: syn::Expr = syn::parse_quote!(handle.join());
908        assert!(!classify::is_pure(&e));
909        let e: syn::Expr = syn::parse_quote!(dir.join("a"));
910        assert!(classify::is_pure(&e));
911        let e: syn::Expr = syn::parse_quote!(if a == 1 { "x" } else { b });
912        assert!(classify::is_pure(&e));
913        let e: syn::Expr = syn::parse_quote!(if a == 1 { f() } else { b });
914        assert!(!classify::is_pure(&e));
915    }
916
917    /// A loop body may end in an await without `;` (`api.put(x).await`, as in DataFusion's join
918    /// fuzz tests and greptimedb's `wait_datanodes_alive`): the generated code was invalid and the
919    /// macro panicked. Found by `psync-scan` over the audit corpus.
920    #[test]
921    fn loop_bodies_ending_in_an_await_without_semicolon() {
922        for f in [
923            syn::parse_quote! {
924                async fn each(api: &Api, xs: Vec<u32>) {
925                    for x in xs {
926                        api.put(x).await
927                    }
928                }
929            },
930            syn::parse_quote! {
931                async fn poll(api: &Api) {
932                    for _ in 0..100 {
933                        let n = api.count().await.unwrap();
934                        if n == 3 {
935                            return;
936                        }
937                        tokio::time::sleep(D).await
938                    }
939                }
940            },
941        ] {
942            let mut f: ItemFn = f;
943            transform_fn(&mut f, &Options::default());
944        }
945    }
946
947    /// `let x: u32 = ..` inside a statement binds `x`; it does not write `u32` (a false edge
948    /// between every two statements with such an annotation).
949    #[test]
950    fn annotated_bindings_are_not_assignments() {
951        let r = report(
952            Options::default(),
953            syn::parse_quote! {
954                async fn f(api: &Api) -> u32 {
955                    let a = { let x: u32 = api.one().await; x };
956                    let b = { let y: u32 = api.two().await; y };
957                    a + b
958                }
959            },
960        );
961        assert!(edges(&r).is_empty(), "{:?}", edges(&r));
962        assert!(r.regions[0].changed);
963    }
964
965    #[test]
966    fn certificates_cover_every_edge() {
967        use proc_macro2::TokenTree;
968        // As `overlap` in `verify/Cert.lean`: agree until one ends, or first differ at a hole.
969        let overlap = |p: &Vec<String>, q: &Vec<String>| {
970            p.iter()
971                .zip(q)
972                .find(|(a, b)| a != b)
973                .is_none_or(|(a, b)| a.starts_with("$hole:") || b.starts_with("$hole:"))
974        };
975        let touches = |ws: &[Vec<String>], others: &[Vec<String>]| {
976            ws.iter().any(|w| others.iter().any(|o| overlap(w, o)))
977        };
978        let conflict = |a: &CertNode, b: &CertNode| {
979            let b_all: Vec<Vec<String>> = b.reads.iter().chain(&b.writes).cloned().collect();
980            touches(&a.writes, &b_all) || touches(&b.writes, &a.reads)
981        };
982        let root = concat!(env!("CARGO_MANIFEST_DIR"), "/..");
983        let mut files = vec![
984            format!("{root}/tests/graph.rs"),
985            format!("{root}/tests/sync.rs"),
986            format!("{root}/psync-check/tests/fixtures/hidden/app/src/lib.rs"),
987        ];
988        for f in std::fs::read_dir(format!("{root}/examples/graph_suite")).unwrap() {
989            files.push(f.unwrap().path().display().to_string());
990        }
991        let is_graph = |attrs: &[syn::Attribute]| {
992            attrs
993                .iter()
994                .any(|a| a.path().segments.last().is_some_and(|s| s.ident == "graph"))
995        };
996        let (mut functions, mut checked) = (0, 0);
997        for file in files {
998            let parsed = syn::parse_file(&std::fs::read_to_string(&file).unwrap()).unwrap();
999            let mut fns: Vec<(Options, ItemFn)> = Vec::new();
1000            let opts = |attrs: &[syn::Attribute]| match attrs
1001                .iter()
1002                .find(|a| a.path().segments.last().is_some_and(|s| s.ident == "graph"))
1003                .map(|a| &a.meta)
1004            {
1005                Some(syn::Meta::List(l)) => Options::parse(l.tokens.clone()).unwrap(),
1006                _ => Options::default(),
1007            };
1008            for item in &parsed.items {
1009                match item {
1010                    syn::Item::Fn(f) if is_graph(&f.attrs) => fns.push((opts(&f.attrs), f.clone())),
1011                    syn::Item::Macro(m) if m.mac.path.is_ident("example") => {
1012                        let tts: Vec<TokenTree> = m.mac.tokens.clone().into_iter().collect();
1013                        let at = tts.windows(2).position(|w| {
1014                            matches!((&w[0], &w[1]), (TokenTree::Ident(a), TokenTree::Ident(f)) if a == "async" && f == "fn")
1015                        });
1016                        let options = tts
1017                            .windows(3)
1018                            .find_map(|w| match (&w[0], &w[2]) {
1019                                (TokenTree::Ident(i), TokenTree::Group(g)) if i == "options" => {
1020                                    Some(Options::parse(g.stream()).unwrap())
1021                                }
1022                                _ => None,
1023                            })
1024                            .unwrap_or_default();
1025                        if let Some(at) = at {
1026                            let body: TokenStream = tts[at..].iter().cloned().collect();
1027                            fns.push((options, syn::parse2(body).unwrap()));
1028                        }
1029                    }
1030                    _ => {}
1031                }
1032            }
1033            for (options, f) in fns {
1034                functions += 1;
1035                // Under its own options, and under the defaults (which keep more edges).
1036                let runs = [report(options, f.clone()), report(Options::default(), f)];
1037                for region in runs.iter().flat_map(|r| &r.regions) {
1038                    for (i, j, why) in &region.edges {
1039                        checked += 1;
1040                        assert!(
1041                            conflict(&region.cert[*i], &region.cert[*j]),
1042                            "{file}: edge n{i} -> n{j} ({why}) has no conflict in the certificate"
1043                        );
1044                    }
1045                }
1046            }
1047        }
1048        assert!(
1049            functions > 40 && checked > 120,
1050            "{functions} functions, {checked} edges"
1051        );
1052    }
1053
1054    use super::*;
1055
1056    fn report(options: Options, f: ItemFn) -> Report {
1057        let mut f = f;
1058        transform_fn(&mut f, &options)
1059    }
1060
1061    fn resync() -> Options {
1062        Options::parse(quote!(baseline = resync)).expect("baseline parses")
1063    }
1064
1065    #[test]
1066    fn baseline_option_parses_and_rejects_unknown_tools() {
1067        assert_eq!(resync().baseline, Some(Baseline::Resync));
1068        assert_eq!(Options::default().baseline, None);
1069        assert!(Options::parse(quote!(baseline = haxl)).is_err());
1070    }
1071
1072    #[test]
1073    fn baseline_keeps_loops_as_written() {
1074        let f: ItemFn = syn::parse_quote! {
1075            async fn sizes(client: &Client, keys: &[String]) -> Result<Vec<u64>, E> {
1076                let mut out = Vec::new();
1077                for key in keys {
1078                    out.push(client.size(key).await?);
1079                }
1080                Ok(out)
1081            }
1082        };
1083        assert!(!report(Options::default(), f.clone()).loops.is_empty());
1084        assert!(report(resync(), f).loops.is_empty());
1085    }
1086
1087    #[test]
1088    fn baseline_orders_writes_per_environment() {
1089        let f: ItemFn = syn::parse_quote! {
1090            async fn save(a: &[u8]) -> std::io::Result<Vec<u8>> {
1091                tokio::fs::write("a.json", a).await?;
1092                let b = tokio::fs::read("b.json").await?;
1093                Ok(b)
1094            }
1095        };
1096        // A write and a read of different files overlap under psync (a read may run ahead of
1097        // the write's `?`); one "file system" orders them.
1098        assert!(
1099            report(Options::default(), f.clone())
1100                .regions
1101                .iter()
1102                .any(|r| r.changed)
1103        );
1104        assert!(!report(resync(), f).regions.iter().any(|r| r.changed));
1105    }
1106
1107    #[test]
1108    fn baseline_moves_nothing_across_a_loop() {
1109        // zed's `fetch_extensions_from_blob_store`: the database read needs nothing from the loop,
1110        // but starting it earlier means moving it above the loop.
1111        let f: ItemFn = syn::parse_quote! {
1112            async fn fetch(store: &Store, db: &Db) -> Result<Vec<String>, E> {
1113                let keys = store.list().await?;
1114                let mut manifests = Vec::new();
1115                for key in keys {
1116                    manifests.push(store.get(&key).await?);
1117                }
1118                let known = db.known().await?;
1119                Ok(filter(manifests, known))
1120            }
1121        };
1122        assert!(
1123            report(Options::default(), f.clone())
1124                .regions
1125                .iter()
1126                .any(|r| r.changed)
1127        );
1128        assert!(!report(resync(), f).regions.iter().any(|r| r.changed));
1129    }
1130
1131    fn edges(r: &Report) -> Vec<String> {
1132        r.regions
1133            .iter()
1134            .flat_map(|g| g.edges.iter().map(|e| e.2.clone()))
1135            .collect()
1136    }
1137
1138    #[test]
1139    fn clock_and_tail_loop_barriers_report_their_lines() {
1140        // A clock read splits the awaits around it; it is reported although it does not await.
1141        let r = report(
1142            Options::default(),
1143            syn::parse_quote! {
1144                async fn f(api: &Api) -> u64 {
1145                    let a = api.get_a().await;
1146                    let t = Instant::now();
1147                    let b = api.get_b().await;
1148                    a + b
1149                }
1150            },
1151        );
1152        assert!(
1153            r.barriers.iter().any(|b| b.contains("reads the clock")),
1154            "{:?}",
1155            r.barriers
1156        );
1157        // A prefetched loop that is the block's value is reported as a loop, not as a barrier
1158        // at a line its generated tokens do not have.
1159        let r = report(
1160            Options::default(),
1161            syn::parse_quote! {
1162                async fn g(api: &Api, ids: &[u64], out: &mut Vec<u64>) {
1163                    let first = api.get_first().await;
1164                    out.push(first);
1165                    for id in ids {
1166                        let v = api.fetch(*id).await;
1167                        out.push(v);
1168                    }
1169                }
1170            },
1171        );
1172        assert!(
1173            r.loops[0].changed && r.barriers.is_empty(),
1174            "{:?}",
1175            r.barriers
1176        );
1177    }
1178
1179    #[test]
1180    fn awaiting_macros_are_barriers() {
1181        // `select!` awaits `put_object` with no `.await` in sight. Before, the statement was an
1182        // ordinary one with no effects, and ran beside the `get_object` of the key it writes.
1183        let r = report(
1184            Options::default(),
1185            syn::parse_quote! {
1186                async fn f(store: &Store, key: &str) -> Result<Obj, E> {
1187                    let done = tokio::select! {
1188                        r = store.put_object(key) => r,
1189                        _ = tokio::time::sleep(T) => Err(Timeout),
1190                    };
1191                    let obj = store.get_object(key).await?;
1192                    let other = store.get_other(key).await?;
1193                    Ok(obj)
1194                }
1195            },
1196        );
1197        assert!(
1198            r.barriers.iter().any(|b| b.contains("`select!` awaits")),
1199            "{:?}",
1200            r.barriers
1201        );
1202        // Only the two reads after it are a region; the `select!` is not in it.
1203        assert!(
1204            r.regions
1205                .iter()
1206                .all(|g| g.nodes.iter().all(|n| !n.label.contains("select")))
1207        );
1208        // In a loop body its effects are unknown writes, so the loop is not prefetched.
1209        let r = report(
1210            Options::default(),
1211            syn::parse_quote! {
1212                async fn g(store: &Store, keys: &[Key]) {
1213                    for k in keys {
1214                        let v = store.get_object(k).await;
1215                        futures::join!(store.put_object(k, v), log.append(k));
1216                    }
1217                }
1218            },
1219        );
1220        assert!(!r.loops[0].changed, "{:?}", r.loops[0]);
1221    }
1222
1223    #[test]
1224    fn calls_marks_the_whole_function() {
1225        // n0 may exit; n1 and n2 say nothing; n3 and n4 write one key of one service.
1226        let has = |attr: proc_macro2::TokenStream| {
1227            let r = report(
1228                Options::parse(attr).unwrap(),
1229                syn::parse_quote! {
1230                    async fn f(api: &Api) -> Result<(), E> {
1231                        let a = api.first().await?;
1232                        api.zorp(1).await;
1233                        api.blit(2).await;
1234                        self.db.put("k", 1).await;
1235                        self.db.put("k", 2).await;
1236                        Ok(())
1237                    }
1238                },
1239            );
1240            let e: Vec<(usize, usize)> = r.regions[0].edges.iter().map(|e| (e.0, e.1)).collect();
1241            move |i: usize, j: usize| e.contains(&(i, j))
1242        };
1243        // Unmarked and lax: n1 and n2 read, run ahead of n0's `?` and beside each other. The
1244        // puts write, so they wait for the `?` and for each other.
1245        let e = has(quote!());
1246        assert!(!e(0, 1) && !e(1, 2) && e(0, 3) && e(3, 4));
1247        // `strict` and `calls = write`: n1 and n2 write; they wait for the `?` and each other.
1248        for attr in [quote!(strict), quote!(calls = write)] {
1249            let e = has(attr);
1250            assert!(e(0, 1) && e(0, 2) && e(1, 2));
1251        }
1252        // `calls = read` wins over `strict`.
1253        let e = has(quote!(strict, calls = read));
1254        assert!(!e(0, 1) && !e(1, 2));
1255        // `calls = write_independent`: writes, so behind the `?`; but they commute, so no
1256        // edges between them, nor between the two puts.
1257        let e = has(quote!(calls = write_independent));
1258        assert!(e(0, 1) && e(0, 2) && !e(1, 2) && e(0, 3) && !e(3, 4));
1259        // `calls = independent`: n1 and n2 read; nothing is ordered by effects. The puts are
1260        // still writes, held behind the `?`.
1261        let e = has(quote!(calls = independent));
1262        assert!(!e(0, 1) && !e(1, 2) && e(0, 3) && !e(3, 4));
1263        assert!(Options::parse(quote!(calls = sometimes)).is_err());
1264    }
1265
1266    #[test]
1267    fn files_and_services_order_conflicting_awaits() {
1268        let r = report(
1269            Options::parse(quote!(path_text)).unwrap(),
1270            syn::parse_quote! {
1271                async fn f(api: &Api) -> Result<(), E> {
1272                    tokio::fs::write("cfg.toml", b"x").await?;
1273                    let s = tokio::fs::read_to_string("cfg.toml").await?;
1274                    let o = tokio::fs::read_to_string("other.toml").await?;
1275                    api.delete(name).await?;
1276                    Ok(())
1277                }
1278            },
1279        );
1280        let e = edges(&r);
1281        assert!(
1282            e.iter().any(|w| w.starts_with("write file \"cfg.toml\"")),
1283            "{e:?}"
1284        );
1285        assert!(
1286            e.iter().any(|w| w.starts_with("may exit before `delete`")),
1287            "{e:?}"
1288        );
1289        // `other.toml` neither conflicts with the write nor is a write: it overlaps.
1290        assert!(r.regions[0].levels[0].len() >= 2);
1291    }
1292
1293    #[test]
1294    fn literal_paths_are_compared_when_compiling() {
1295        let region = |f: ItemFn| {
1296            let r = report(Options::parse(quote!(speculate, path_text)).unwrap(), f);
1297            r.regions[0].clone()
1298        };
1299        // Two literals are compared exactly: a directory and a file inside it stay ordered by an
1300        // edge, with nothing left to compare at run time, and the labels keep their paths.
1301        let r = region(syn::parse_quote! {
1302            async fn f() -> std::io::Result<()> {
1303                tokio::fs::remove_dir_all("out").await?;
1304                let a = tokio::fs::read("out/a.txt").await?;
1305                let b = tokio::fs::read("cfg.toml").await?;
1306                Ok(())
1307            }
1308        });
1309        assert_eq!(r.runtime_checks, 0);
1310        assert!(
1311            r.edges.iter().any(|e| (e.0, e.1) == (0, 1)),
1312            "{:?}",
1313            r.edges
1314        );
1315        assert!(!format!("{:?}", r.nodes).contains("compared at run time"));
1316        // A literal against a computed path is still compared at run time.
1317        let r = region(syn::parse_quote! {
1318            async fn f(p: &Path) -> std::io::Result<()> {
1319                tokio::fs::remove_dir_all("out").await?;
1320                let a = tokio::fs::read(p).await?;
1321                Ok(())
1322            }
1323        });
1324        assert_eq!(r.runtime_checks, 1);
1325    }
1326
1327    #[test]
1328    fn computed_paths_are_compared_at_run_time() {
1329        let checks = |f: ItemFn| {
1330            let r = report(Options::parse(quote!(speculate)).unwrap(), f);
1331            (r.regions[0].runtime_checks, r.regions[0].changed)
1332        };
1333        // Two parameters: concurrent, ordered at run time if they name one file.
1334        assert_eq!(
1335            checks(syn::parse_quote! {
1336                async fn f(a: &Path, b: &Path) -> Result<(), E> {
1337                    let s = tokio::fs::read_to_string(a).await?;
1338                    tokio::fs::write(b, b"x").await?;
1339                    Ok(())
1340                }
1341            }),
1342            (1, true)
1343        );
1344        // A path bound in the region to a total value is substituted.
1345        assert_eq!(
1346            checks(syn::parse_quote! {
1347                async fn f(dir: &Path, name: &str) -> Result<(), E> {
1348                    let p = dir.join(name);
1349                    let s = tokio::fs::read_to_string(&p).await?;
1350                    tokio::fs::write(dir.join("out"), b"x").await?;
1351                    Ok(())
1352                }
1353            })
1354            .0,
1355            1
1356        );
1357        // The same expression is the same file: it stays ordered.
1358        let same = |f: ItemFn| assert_eq!(checks(f).0, 0);
1359        same(syn::parse_quote! {
1360            async fn f(a: &Path) -> Result<(), E> {
1361                let s = tokio::fs::read_to_string(a).await?;
1362                tokio::fs::write(a, b"x").await?;
1363                Ok(())
1364            }
1365        });
1366        // A path from awaited work, or from a `mut` binding, cannot be evaluated at the start.
1367        same(syn::parse_quote! {
1368            async fn f(api: &Api, a: &Path) -> Result<(), E> {
1369                let b = api.locate().await?;
1370                let s = tokio::fs::read_to_string(a).await?;
1371                tokio::fs::write(&b, b"x").await?;
1372                Ok(())
1373            }
1374        });
1375        same(syn::parse_quote! {
1376            async fn f(a: &Path, mut b: PathBuf) -> Result<(), E> {
1377                let s = tokio::fs::read_to_string(a).await?;
1378                tokio::fs::write(&b, b"x").await?;
1379                Ok(())
1380            }
1381        });
1382    }
1383
1384    #[test]
1385    fn urls_and_redis_keys_are_compared_at_run_time() {
1386        let checks = |f: ItemFn| {
1387            let r = report(Options::parse(quote!(speculate)).unwrap(), f);
1388            (r.regions[0].runtime_checks, r.regions[0].changed)
1389        };
1390        // A GET of one computed URL and a PUT of another: concurrent, ordered if they overlap.
1391        assert_eq!(
1392            checks(syn::parse_quote! {
1393                async fn f(client: &Client, a: &str, b: &str) -> Result<(), E> {
1394                    let r = client.request(Method::GET, a).send().await?;
1395                    client.request(Method::PUT, b).send().await?;
1396                    Ok(())
1397                }
1398            }),
1399            (1, true)
1400        );
1401        // A POST may change anything: no URL makes it safe, so it stays in order.
1402        assert_eq!(
1403            checks(syn::parse_quote! {
1404                async fn f(client: &Client, a: &str, b: &str) -> Result<(), E> {
1405                    let r = client.request(Method::GET, a).send().await?;
1406                    client.request(Method::POST, b).send().await?;
1407                    Ok(())
1408                }
1409            }),
1410            (0, false)
1411        );
1412        // Redis: a GET and a SET of computed keys, each on a connection of its own (through one
1413        // `&mut con`, the borrow already orders them).
1414        assert_eq!(
1415            checks(syn::parse_quote! {
1416                async fn f(pool: &Pool, a: &str, b: &str) -> Result<(), E> {
1417                    let v: String = redis::cmd("GET").arg(a).query_async(&mut pool.get()).await?;
1418                    redis::cmd("SET").arg(b).arg(1).query_async::<()>(&mut pool.get()).await?;
1419                    Ok(())
1420                }
1421            }),
1422            (1, true)
1423        );
1424    }
1425
1426    #[test]
1427    fn per_item_files_are_checked_at_run_time() {
1428        let check = |f: ItemFn| {
1429            let r = report(Options::parse(quote!(speculate)).unwrap(), f);
1430            assert!(r.loops[0].changed, "{:?}", r.loops);
1431            r.loops[0].check.clone()
1432        };
1433        // The path is computed from the item: evaluated ahead for every item.
1434        let checked = |c: String| assert_eq!(c, "checked at run time");
1435        checked(check(syn::parse_quote! {
1436            async fn f(dir: &Path, names: &[String]) -> Result<(), E> {
1437                for name in names {
1438                    let path = dir.join(name);
1439                    let old = tokio::fs::read_to_string(&path).await?;
1440                    std::fs::write(&path, old)?;
1441                }
1442                Ok(())
1443            }
1444        }));
1445        checked(check(syn::parse_quote! {
1446            async fn f(names: &[String]) -> Result<(), E> {
1447                for (i, name) in names.iter().enumerate() {
1448                    tokio::fs::write(format!("{name}.json"), b"x").await?;
1449                }
1450                Ok(())
1451            }
1452        }));
1453        // URLs and Redis keys are checked like files: a PUT per item, to the item's own URL.
1454        checked(check(syn::parse_quote! {
1455            async fn f(client: &Client, ids: &[u64]) -> Result<(), E> {
1456                for id in ids {
1457                    let url = format!("/items/{id}");
1458                    let old = client.request(Method::GET, &url).send().await?;
1459                    client.request(Method::PUT, &url).send().await?;
1460                }
1461                Ok(())
1462            }
1463        }));
1464        // Only reads: nothing to check.
1465        assert_eq!(
1466            check(syn::parse_quote! {
1467                async fn f(names: &[String]) -> Result<(), E> {
1468                    for name in names {
1469                        let s = tokio::fs::read_to_string(format!("{name}.json")).await?;
1470                    }
1471                    Ok(())
1472                }
1473            }),
1474            ""
1475        );
1476        // Paths that cannot be evaluated ahead keep the assumption, and say why.
1477        let assumed = |c: String, why: &str| {
1478            assert!(c.starts_with("assumed distinct") && c.contains(why), "{c}")
1479        };
1480        assumed(
1481            check(syn::parse_quote! {
1482                async fn f(api: &Api, names: &[String]) -> Result<(), E> {
1483                    for name in names {
1484                        let path = api.locate(name).await?;
1485                        tokio::fs::write(&path, b"x").await?;
1486                    }
1487                    Ok(())
1488                }
1489            }),
1490            "computed in the body",
1491        );
1492        assumed(
1493            check(syn::parse_quote! {
1494                async fn f(paths: &[PathBuf]) -> Result<(), E> {
1495                    for i in 0..paths.len() {
1496                        tokio::fs::write(&paths[i], b"x").await?;
1497                    }
1498                    Ok(())
1499                }
1500            }),
1501            "may panic",
1502        );
1503        assumed(
1504            check(syn::parse_quote! {
1505                async fn f(pairs: Vec<(String, u8)>) -> Result<(), E> {
1506                    for (mut name, n) in pairs {
1507                        tokio::fs::write(&name, [n]).await?;
1508                    }
1509                    Ok(())
1510                }
1511            }),
1512            "`mut`",
1513        );
1514        // `independent` is the programmer's word for it.
1515        assert_eq!(
1516            check(syn::parse_quote! {
1517                async fn f(names: &[String]) -> Result<(), E> {
1518                    #[psync::independent]
1519                    for name in names {
1520                        tokio::fs::write(format!("{name}.json"), b"x").await?;
1521                    }
1522                    Ok(())
1523                }
1524            }),
1525            ""
1526        );
1527    }
1528
1529    #[test]
1530    fn loop_writes_past_exits_are_refused_unless_speculative() {
1531        let f: ItemFn = syn::parse_quote! {
1532            async fn f(store: &Store, keys: &[String]) -> Result<(), E> {
1533                for k in keys {
1534                    store.upload(k).await?;
1535                }
1536                Ok(())
1537            }
1538        };
1539        let r = report(Options::default(), f.clone());
1540        assert!(
1541            !r.loops[0].changed && r.loops[0].reason.contains("speculate"),
1542            "{:?}",
1543            r.loops
1544        );
1545        let options = Options::parse(quote!(speculate)).unwrap();
1546        assert!(report(options, f).loops[0].changed);
1547    }
1548
1549    #[test]
1550    fn same_target_every_iteration_is_refused() {
1551        let r = report(
1552            Options::default(),
1553            syn::parse_quote! {
1554                async fn f(store: &Store, keys: &[String]) {
1555                    for k in keys {
1556                        let _ = store.put("counter", k).await;
1557                    }
1558                }
1559            },
1560        );
1561        assert!(
1562            r.loops[0].reason.contains("every iteration"),
1563            "{:?}",
1564            r.loops
1565        );
1566    }
1567
1568    #[test]
1569    fn effect_options_parse() {
1570        let o = Options::parse(quote!(
1571            strict,
1572            effects(write(bump), read(peek_all), ordered(log_line))
1573        ))
1574        .unwrap();
1575        assert!(
1576            o.effects.strict && o.effects.writes == ["bump"] && o.effects.ordered == ["log_line"]
1577        );
1578        assert!(Options::parse(quote!(effects(maybe(x)))).is_err());
1579    }
1580}