Skip to main content

psync_driver/driver/
analysis.rs

1//! Effect summaries from MIR, and the checks of `#[psync::graph]` rewrites.
2
3use psync_check::{
4    Access, CallFact, CrateFindings, CrateSummaries, Domain, Effect, Finding, FnSummary, Resolved,
5    Severity, conflict, env,
6};
7use rustc_hir::def::DefKind;
8use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
9use rustc_middle::mir::{self, AggregateKind, Operand, Rvalue, StatementKind, TerminatorKind};
10use rustc_middle::ty::{self, GenericArgs, Instance, InstanceKind, Ty, TyCtxt, TypingEnv};
11use rustc_span::Span;
12use std::collections::BTreeMap;
13use std::collections::{HashMap, HashSet};
14use std::path::PathBuf;
15use std::rc::Rc;
16
17/// The label of each value a switch compares against (`None`: its `otherwise` edge).
18type Labels<'a> = Box<dyn Fn(Option<u128>) -> String + 'a>;
19
20/// An effect inside one body, with the span of the call in that body that leads to it.
21#[derive(Clone, Debug)]
22pub struct Located {
23    pub effect: Effect,
24    pub span: Span,
25}
26
27#[derive(Clone, Debug, Default)]
28pub struct Summary {
29    pub effects: Vec<Located>,
30    pub opaque: Vec<String>,
31    /// May panic explicitly in the user's code.
32    pub panics: bool,
33    /// Trait methods reached through `dyn` or unresolved generics (keys), for the link step.
34    pub deferred: Vec<String>,
35}
36
37impl Summary {
38    /// Grows whenever an absorb adds anything (effects, opaque callees, panics, deferred calls).
39    fn size(&self) -> (usize, usize, bool, usize) {
40        (
41            self.effects.len(),
42            self.opaque.len(),
43            self.panics,
44            self.deferred.len(),
45        )
46    }
47
48    /// Add a callee's summary. `srcs` says what the call passes as each parameter; without it
49    /// (or for a parameter it cannot follow) an effect on a parameter is on anything.
50    fn absorb(&mut self, other: &Summary, span: Span, via: Option<&str>, srcs: Option<&[Src]>) {
51        for l in &other.effects {
52            let mut effect = at_call(&l.effect, srcs);
53            if let Some(v) = via {
54                effect.via.insert(0, v.to_string());
55            }
56            self.add(effect, span);
57        }
58        self.opaque.extend(other.opaque.iter().cloned());
59        self.panics |= other.panics;
60        for d in &other.deferred {
61            if !self.deferred.contains(d) {
62                self.deferred.push(d.clone());
63            }
64        }
65    }
66
67    fn add(&mut self, effect: Effect, span: Span) {
68        let same = |l: &Located| {
69            l.effect.domain == effect.domain
70                && l.effect.access == effect.access
71                && l.effect.target == effect.target
72                && l.effect.arg == effect.arg
73        };
74        if !self.effects.iter().any(same) {
75            self.effects.push(Located { effect, span });
76        }
77    }
78}
79
80/// What a call passes as one argument, followed back through the caller's body.
81#[derive(Clone, Debug, PartialEq)]
82pub enum Src {
83    /// The caller's own parameter, unchanged.
84    Param(usize),
85    /// A string constant.
86    Const(String),
87    Unknown,
88}
89
90/// `effect` as seen by a caller that passes `srcs`: an effect on parameter `j` becomes one on
91/// what the call passes there.
92fn at_call(effect: &Effect, srcs: Option<&[Src]>) -> Effect {
93    let mut e = effect.clone();
94    if let Some(j) = e.arg.take() {
95        match srcs.and_then(|s| s.get(j)) {
96            Some(Src::Param(k)) => e.arg = Some(*k),
97            Some(Src::Const(c)) => e.target = Some(c.clone()),
98            _ => {}
99        }
100    }
101    e
102}
103
104/// Standard-library conversions that keep the path or string they are given
105/// (`<PathBuf as Deref>::deref`, `AsRef::<Path>::as_ref`, `Path::to_path_buf`).
106const SAME_VALUE: &[&str] = &[
107    "as_ref",
108    "deref",
109    "borrow",
110    "as_path",
111    "as_os_str",
112    "as_str",
113    "to_path_buf",
114    "to_owned",
115    "to_string",
116    "clone",
117    "into",
118    "from",
119];
120
121/// Where a value lives in a body: a local, or, in a closure or coroutine, one of its captured
122/// values (upvar `k`) or a slot of a suspended coroutine's state (variant, field), where locals
123/// live across an `await`.
124#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
125enum Root {
126    Local(mir::Local),
127    Upvar(usize),
128    Slot(usize, usize),
129}
130
131/// What the values of one body hold, as [`Src`]s.
132///
133/// In a function, `Param(k)` is its parameter `k`. In a closure or coroutine, it is the captured
134/// value `k`, which is what the body that creates it passes ([`Analyzer::local`] records the
135/// captures as the edge's sources); its own parameters (the closure or `Pin<&mut Self>`, the
136/// context, a closure's arguments) are unknown.
137///
138/// A parameter or capture is followed only if it is never assigned or borrowed mutably. A local
139/// or slot is followed only if it is assigned once, from a copy, move or shared borrow of a
140/// followed value (through `*`), a string constant, or a [`SAME_VALUE`] call of the standard
141/// library on one. Everything else is `Unknown`.
142struct Held {
143    srcs: HashMap<Root, Src>,
144    /// The local function whose call produced the value (a future returned by an `async fn`),
145    /// followed through moves, borrows, `into_future` and `Pin::new_unchecked`.
146    origin: HashMap<Root, DefId>,
147    /// Locals that hold the closure or coroutine itself (`_7 = copy (_1.0)` of `Pin<&mut _>`).
148    selves: HashSet<mir::Local>,
149    nested: bool,
150    coroutine: bool,
151}
152
153impl Held {
154    fn new<'tcx>(
155        tcx: TyCtxt<'tcx>,
156        def_id: DefId,
157        body: &mir::Body<'tcx>,
158        constant: impl Fn(&Operand<'tcx>) -> Option<String>,
159    ) -> Self {
160        #[derive(Clone)]
161        enum Def {
162            Alias(Root),
163            Const(String),
164            Other,
165        }
166        let mut held = Held {
167            srcs: HashMap::new(),
168            origin: HashMap::new(),
169            selves: HashSet::new(),
170            nested: tcx.is_closure_like(def_id),
171            coroutine: tcx.is_coroutine(def_id),
172        };
173        // The locals that hold the coroutine: copies of `_1.0` (the pointer in the `Pin`).
174        if held.coroutine {
175            for data in body.basic_blocks.iter() {
176                for stmt in &data.statements {
177                    if let StatementKind::Assign(a) = &stmt.kind
178                        && let (place, Rvalue::Use(Operand::Copy(p) | Operand::Move(p), _)) = &**a
179                        && place.projection.is_empty()
180                        && p.local.as_usize() == 1
181                        && matches!(p.projection[..], [mir::ProjectionElem::Field(f, _)] if f.as_usize() == 0)
182                    {
183                        held.selves.insert(place.local);
184                    }
185                }
186            }
187        }
188        let mut defs: HashMap<Root, Vec<Def>> = HashMap::new();
189        let mut tainted: HashSet<Root> = HashSet::new();
190        #[derive(Clone, Copy)]
191        enum From {
192            Root(Root),
193            Call(DefId),
194            Other,
195        }
196        let mut froms: HashMap<Root, Vec<From>> = HashMap::new();
197        let of_place = |p: &mir::Place<'tcx>| held.root(p).map_or(Def::Other, Def::Alias);
198        let of_operand = |op: &Operand<'tcx>| match op {
199            Operand::Copy(p) | Operand::Move(p) => of_place(p),
200            c => constant(c).map_or(Def::Other, Def::Const),
201        };
202        // An assignment to a whole local or slot defines it; to anything else (a field, through
203        // a pointer, a capture) it changes what the root holds.
204        let assign = |place: &mir::Place<'tcx>,
205                      def: Def,
206                      defs: &mut HashMap<Root, Vec<Def>>,
207                      tainted: &mut HashSet<Root>| {
208            match held.target_root(place) {
209                Some(r @ (Root::Local(_) | Root::Slot(..))) => defs.entry(r).or_default().push(def),
210                Some(r) => {
211                    tainted.insert(r);
212                }
213                None => {
214                    tainted.insert(held.base(place));
215                }
216            }
217        };
218        for data in body.basic_blocks.iter() {
219            for stmt in &data.statements {
220                match &stmt.kind {
221                    StatementKind::Assign(a) => {
222                        let (place, rv) = &**a;
223                        let def = match rv {
224                            Rvalue::Use(op, _) => of_operand(op),
225                            Rvalue::CopyForDeref(p) => of_place(p),
226                            Rvalue::Ref(
227                                _,
228                                mir::BorrowKind::Shared | mir::BorrowKind::Fake(_),
229                                p,
230                            ) => of_place(p),
231                            _ => Def::Other,
232                        };
233                        if let Rvalue::Ref(_, mir::BorrowKind::Mut { .. }, p)
234                        | Rvalue::RawPtr(mir::RawPtrKind::Mut, p) = rv
235                        {
236                            tainted.insert(held.root(p).unwrap_or_else(|| held.base(p)));
237                        }
238                        assign(place, def, &mut defs, &mut tainted);
239                        if let Some(r) = held.target_root(place) {
240                            let from = match rv {
241                                Rvalue::Use(Operand::Copy(p) | Operand::Move(p), _)
242                                | Rvalue::CopyForDeref(p)
243                                | Rvalue::Ref(_, _, p) => {
244                                    held.root(p).map_or(From::Other, From::Root)
245                                }
246                                _ => From::Other,
247                            };
248                            froms.entry(r).or_default().push(from);
249                        }
250                    }
251                    StatementKind::SetDiscriminant { place, .. } => {
252                        // The coroutine's own state change is not a change of its values.
253                        if !held.selves.contains(&place.local) {
254                            tainted.insert(held.base(place));
255                        }
256                    }
257                    _ => {}
258                }
259            }
260            if let TerminatorKind::Call {
261                func,
262                args,
263                destination,
264                ..
265            } = &data.terminator().kind
266            {
267                let same = func.const_fn_def().is_some_and(|(callee, _)| {
268                    matches!(
269                        tcx.crate_name(callee.krate).as_str(),
270                        "std" | "core" | "alloc"
271                    ) && tcx
272                        .opt_item_name(callee)
273                        .is_some_and(|n| SAME_VALUE.contains(&n.as_str()))
274                });
275                let def = match args.first() {
276                    Some(a) if same && args.len() == 1 => of_operand(&a.node),
277                    _ => Def::Other,
278                };
279                assign(destination, def, &mut defs, &mut tainted);
280                if let Some(r) = held.target_root(destination) {
281                    let from = match func.const_fn_def() {
282                        Some((callee, _)) if callee.is_local() => From::Call(callee),
283                        Some((callee, _))
284                            if matches!(tcx.crate_name(callee.krate).as_str(), "core" | "std")
285                                && tcx.opt_item_name(callee).is_some_and(|n| {
286                                    matches!(n.as_str(), "into_future" | "new_unchecked" | "new")
287                                })
288                                && args.len() == 1 =>
289                        {
290                            match &args[0].node {
291                                Operand::Copy(p) | Operand::Move(p) => {
292                                    held.root(p).map_or(From::Other, From::Root)
293                                }
294                                _ => From::Other,
295                            }
296                        }
297                        _ => From::Other,
298                    };
299                    froms.entry(r).or_default().push(from);
300                }
301            }
302        }
303        let arg_count = body.arg_count;
304        let nested = held.nested;
305        let resolve = |r: Root| -> Src {
306            let mut r = r;
307            for _ in 0..64 {
308                if tainted.contains(&r) {
309                    return Src::Unknown;
310                }
311                let d = defs.get(&r).map(Vec::as_slice).unwrap_or(&[]);
312                match r {
313                    Root::Upvar(k) => {
314                        return if d.is_empty() {
315                            Src::Param(k)
316                        } else {
317                            Src::Unknown
318                        };
319                    }
320                    Root::Local(l) if (1..=arg_count).contains(&l.as_usize()) => {
321                        return if nested || !d.is_empty() {
322                            Src::Unknown
323                        } else {
324                            Src::Param(l.as_usize() - 1)
325                        };
326                    }
327                    _ => {}
328                }
329                match d {
330                    [Def::Alias(x)] => r = *x,
331                    [Def::Const(c)] => return Src::Const(c.clone()),
332                    _ => return Src::Unknown,
333                }
334            }
335            Src::Unknown
336        };
337        let mut roots: Vec<Root> = (0..body.local_decls.len())
338            .map(|l| Root::Local(mir::Local::from_usize(l)))
339            .collect();
340        roots.extend(defs.keys().copied());
341        roots.extend(tainted.iter().copied());
342        let srcs = roots.into_iter().map(|r| (r, resolve(r))).collect();
343        // Every assignment of the root must lead to the same call.
344        let origin_of = |r: Root| -> Option<DefId> {
345            let mut r = r;
346            for _ in 0..64 {
347                match froms.get(&r).map(Vec::as_slice).unwrap_or(&[]) {
348                    [From::Root(x)] => r = *x,
349                    [From::Call(f)] => return Some(*f),
350                    _ => return None,
351                }
352            }
353            None
354        };
355        let origin = froms
356            .keys()
357            .filter_map(|r| origin_of(*r).map(|f| (*r, f)))
358            .collect();
359        Held {
360            srcs,
361            origin,
362            ..held
363        }
364    }
365
366    /// The root a place's value is read from: a local through `*`, a capture or a slot of the
367    /// coroutine through `*`. `None` for anything else (a field of a local, an index).
368    fn root(&self, p: &mir::Place<'_>) -> Option<Root> {
369        use mir::ProjectionElem::{Deref, Downcast, Field};
370        let proj = &p.projection[..];
371        let derefs = |rest: &[mir::PlaceElem<'_>]| rest.iter().all(|e| matches!(e, Deref));
372        let after_self = if self.coroutine && self.selves.contains(&p.local) {
373            Some(match proj.first() {
374                Some(Deref) => &proj[1..],
375                _ => return None,
376            })
377        } else if self.nested && !self.coroutine && p.local.as_usize() == 1 {
378            // A closure: `_1` is the closure, by value or behind a reference.
379            Some(match proj.first() {
380                Some(Deref) => &proj[1..],
381                _ => proj,
382            })
383        } else {
384            None
385        };
386        match after_self {
387            None => derefs(proj).then_some(Root::Local(p.local)),
388            Some(rest) => match rest {
389                [Field(k, _), tail @ ..] if derefs(tail) => Some(Root::Upvar(k.as_usize())),
390                [Downcast(_, v), Field(f, _), tail @ ..] if derefs(tail) => {
391                    Some(Root::Slot(v.as_usize(), f.as_usize()))
392                }
393                _ => None,
394            },
395        }
396    }
397
398    /// The root an assignment to `p` defines (a whole local or slot) or changes (a capture).
399    fn target_root(&self, p: &mir::Place<'_>) -> Option<Root> {
400        match self.root(p)? {
401            // `*_5 = ..` changes what `_5` points to; `*(slot) = ..` likewise.
402            Root::Local(_) if !p.projection.is_empty() => None,
403            Root::Slot(..)
404                if p.projection
405                    .iter()
406                    .filter(|e| matches!(e, mir::ProjectionElem::Deref))
407                    .count()
408                    > 1 =>
409            {
410                None
411            }
412            r => Some(r),
413        }
414    }
415
416    /// The root whose value a write to `p` may change: its capture or slot, or its local.
417    fn base(&self, p: &mir::Place<'_>) -> Root {
418        use mir::ProjectionElem::{Deref, Downcast, Field};
419        let proj = &p.projection[..];
420        if (self.coroutine && self.selves.contains(&p.local))
421            || (self.nested && !self.coroutine && p.local.as_usize() == 1)
422        {
423            let rest = match proj.first() {
424                Some(Deref) => &proj[1..],
425                _ => proj,
426            };
427            match rest {
428                [Field(k, _), ..] => return Root::Upvar(k.as_usize()),
429                [Downcast(_, v), Field(f, _), ..] => return Root::Slot(v.as_usize(), f.as_usize()),
430                _ => {}
431            }
432        }
433        Root::Local(p.local)
434    }
435
436    /// The local function whose call produced an operand's value, if one did.
437    fn origin_of(&self, op: &Operand<'_>) -> Option<DefId> {
438        match op {
439            Operand::Copy(p) | Operand::Move(p) => self.origin.get(&self.root(p)?).copied(),
440            _ => None,
441        }
442    }
443
444    /// What an operand of this body holds.
445    fn of<'tcx>(
446        &self,
447        op: &Operand<'tcx>,
448        constant: impl Fn(&Operand<'tcx>) -> Option<String>,
449    ) -> Src {
450        match op {
451            Operand::Copy(p) | Operand::Move(p) => self
452                .root(p)
453                .and_then(|r| self.srcs.get(&r).cloned())
454                .unwrap_or(Src::Unknown),
455            c => constant(c).map_or(Src::Unknown, Src::Const),
456        }
457    }
458}
459
460/// A call from one body to a local body: a function, or a closure or coroutine it creates.
461#[derive(Clone, Debug)]
462pub struct Edge {
463    callee: DefId,
464    /// What the call passes as each of the callee's parameters.
465    srcs: Vec<Src>,
466    span: Span,
467    /// The callee's path, recorded in the effects' call chains (`None` for nested bodies).
468    via: Option<String>,
469}
470
471/// One body's own effects (everything but its calls of local bodies), and those calls.
472#[derive(Debug)]
473pub struct Local {
474    own: Summary,
475    calls: Vec<Edge>,
476}
477
478/// The state of Tarjan's algorithm.
479#[derive(Default)]
480struct Tarjan {
481    next: usize,
482    index: HashMap<DefId, usize>,
483    low: HashMap<DefId, usize>,
484    stack: Vec<DefId>,
485    on_stack: HashSet<DefId>,
486}
487
488/// A definition's path for people: `load` rather than `load::{closure#0}`.
489fn display_path(tcx: TyCtxt<'_>, def_id: DefId) -> String {
490    let path = tcx.def_path_str(def_id);
491    let mut out = String::with_capacity(path.len());
492    let mut rest = path.as_str();
493    while let Some(at) = rest.find("::{") {
494        out.push_str(&rest[..at]);
495        rest = match rest[at..].find('}') {
496            Some(end) => &rest[at + end + 1..],
497            None => "",
498        };
499    }
500    out.push_str(rest);
501    out
502}
503
504/// The span of the first call in `def_id`'s body (or the closures and coroutines it creates)
505/// written by the user rather than generated by the macro, to point at a chain's own statements.
506fn user_span(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Span> {
507    if !def_id.is_local() || !tcx.is_mir_available(def_id) {
508        return None;
509    }
510    let body = tcx.optimized_mir(def_id);
511    let own = body.basic_blocks.iter().find_map(|data| {
512        let t = data.terminator();
513        let span = t.source_info.span;
514        (matches!(t.kind, TerminatorKind::Call { .. }) && !span.from_expansion()).then_some(span)
515    });
516    own.or_else(|| {
517        body.basic_blocks
518            .iter()
519            .flat_map(|d| &d.statements)
520            .find_map(|stmt| {
521                if let StatementKind::Assign(assign) = &stmt.kind
522                    && let Rvalue::Aggregate(kind, _) = &assign.1
523                    && let AggregateKind::Closure(nested, _)
524                    | AggregateKind::Coroutine(nested, _)
525                    | AggregateKind::CoroutineClosure(nested, _) = **kind
526                {
527                    user_span(tcx, nested)
528                } else {
529                    None
530                }
531            })
532    })
533}
534
535/// Crates whose functions are never followed: their I/O is recognized by path instead.
536const OPAQUE_STD: &[&str] = &["std", "core", "alloc", "proc_macro", "test"];
537/// Async runtimes and file helpers whose I/O is recognized by path, like std's.
538const IO_CRATES: &[&str] = &[
539    "tokio",
540    "async_std",
541    "smol",
542    "async_fs",
543    "async_process",
544    "fs_err",
545];
546
547pub struct Analyzer<'tcx> {
548    tcx: TyCtxt<'tcx>,
549    memo: HashMap<DefId, Rc<Summary>>,
550    /// Each body's own effects and its calls of local bodies, read from MIR once.
551    locals: HashMap<DefId, Rc<Local>>,
552    external: Option<HashMap<String, FnSummary>>,
553    /// Stable ids of crates the driver summarized.
554    summarized: HashSet<String>,
555    summary_dir: Option<PathBuf>,
556    /// The crate being compiled comes from crates.io or git (not the user's workspace): its
557    /// summaries keep only real I/O, never verbs of the APIs it calls internally.
558    library: bool,
559    /// Deferred trait methods resolved over the whole build by a previous run's link step.
560    linked: BTreeMap<String, Resolved>,
561}
562
563impl<'tcx> Analyzer<'tcx> {
564    pub fn new(tcx: TyCtxt<'tcx>) -> Self {
565        Self {
566            tcx,
567            memo: HashMap::new(),
568            locals: HashMap::new(),
569            external: None,
570            summarized: HashSet::new(),
571            summary_dir: std::env::var_os(env::SUMMARIES).map(PathBuf::from),
572            library: is_registry(tcx, rustc_hir::def_id::CRATE_DEF_ID.to_def_id()),
573            linked: std::env::var_os(env::LINKED)
574                .and_then(|p| std::fs::read_to_string(p).ok())
575                .and_then(|t| serde_json::from_str(&t).ok())
576                .unwrap_or_default(),
577        }
578    }
579
580    fn has_body(&self, def_id: DefId) -> bool {
581        def_id.is_local()
582            && matches!(
583                self.tcx.def_kind(def_id),
584                DefKind::Fn | DefKind::AssocFn | DefKind::Closure
585            )
586            && self.tcx.is_mir_available(def_id)
587    }
588
589    /// The effects of a local function, closure or coroutine, including the closures and
590    /// coroutines it creates (an `async fn`'s body is a coroutine it returns), through every
591    /// local callee.
592    ///
593    /// A summary is the least fixed point of `S(f) = own(f) ∪ ⋃ S(g)` over the local calls
594    /// `f → g`. Recursive functions make the call graph cyclic, so the bodies are grouped into
595    /// strongly connected components (Tarjan's algorithm, callees before callers), and each
596    /// component is iterated until its summaries stop growing. Every member of a cycle then gets
597    /// the effects of the whole cycle, whichever member is asked for first.
598    pub fn summarize(&mut self, def_id: DefId) -> Rc<Summary> {
599        if let Some(s) = self.memo.get(&def_id) {
600            return s.clone();
601        }
602        if !self.has_body(def_id) {
603            return Rc::new(Summary::default());
604        }
605        let mut walk = Tarjan::default();
606        self.component(def_id, &mut walk);
607        self.memo[&def_id].clone()
608    }
609
610    /// Tarjan's strongly connected components over local calls, from `v`. When `v` closes a
611    /// component, its members' summaries are computed together and memoized.
612    fn component(&mut self, v: DefId, t: &mut Tarjan) {
613        let index = t.next;
614        t.next += 1;
615        t.index.insert(v, index);
616        t.low.insert(v, index);
617        t.stack.push(v);
618        t.on_stack.insert(v);
619        let local = self.local(v);
620        for edge in &local.calls {
621            let w = edge.callee;
622            if self.memo.contains_key(&w) || !self.has_body(w) {
623                continue;
624            }
625            if !t.index.contains_key(&w) {
626                self.component(w, t);
627                let low = t.low[&v].min(t.low[&w]);
628                t.low.insert(v, low);
629            } else if t.on_stack.contains(&w) {
630                let low = t.low[&v].min(t.index[&w]);
631                t.low.insert(v, low);
632            }
633        }
634        if t.low[&v] != index {
635            return;
636        }
637        // `v` is the root of a component: its members are on the stack above it.
638        let mut members = Vec::new();
639        while let Some(w) = t.stack.pop() {
640            t.on_stack.remove(&w);
641            members.push(w);
642            if w == v {
643                break;
644            }
645        }
646        let locals: Vec<Rc<Local>> = members.iter().map(|m| self.local(*m)).collect();
647        let mut current: HashMap<DefId, Summary> = members
648            .iter()
649            .zip(&locals)
650            .map(|(m, l)| (*m, l.own.clone()))
651            .collect();
652        // Summaries only grow, and there are finitely many distinct effects: this terminates.
653        // A component without a cycle (one member, not calling itself) takes one round.
654        loop {
655            let mut changed = false;
656            for (m, local) in members.iter().zip(&locals) {
657                for edge in &local.calls {
658                    let callee = match self.memo.get(&edge.callee) {
659                        Some(done) => (**done).clone(),
660                        None => current.get(&edge.callee).cloned().unwrap_or_default(),
661                    };
662                    let summary = current.get_mut(m).expect("member");
663                    let before = summary.size();
664                    summary.absorb(&callee, edge.span, edge.via.as_deref(), Some(&edge.srcs));
665                    summary.opaque.sort();
666                    summary.opaque.dedup();
667                    changed |= summary.size() != before;
668                }
669            }
670            if !changed {
671                break;
672            }
673        }
674        for (m, summary) in current {
675            self.memo.insert(m, Rc::new(summary));
676        }
677    }
678
679    /// What one body does by itself, and which local bodies it calls, read from its MIR.
680    fn local(&mut self, def_id: DefId) -> Rc<Local> {
681        if let Some(l) = self.locals.get(&def_id) {
682            return l.clone();
683        }
684        let tcx = self.tcx;
685        let body = tcx.optimized_mir(def_id);
686        let typing_env = TypingEnv::post_analysis(tcx, def_id);
687        let mut own = Summary::default();
688        let mut calls = Vec::new();
689        let held = Held::new(tcx, def_id, body, |op| self.string_constant(op));
690        for data in body.basic_blocks.iter() {
691            for stmt in &data.statements {
692                if let StatementKind::Assign(assign) = &stmt.kind
693                    && let Rvalue::Aggregate(kind, operands) = &assign.1
694                    && let AggregateKind::Closure(nested, _)
695                    | AggregateKind::Coroutine(nested, _)
696                    | AggregateKind::CoroutineClosure(nested, _) = **kind
697                {
698                    // A closure's or coroutine's captures, in order: what `Param(k)` means in its
699                    // body. (An async closure's body is another coroutine: not followed.)
700                    let srcs = match **kind {
701                        AggregateKind::CoroutineClosure(..) => Vec::new(),
702                        _ => operands
703                            .iter()
704                            .map(|op| held.of(op, |c| self.string_constant(c)))
705                            .collect(),
706                    };
707                    calls.push(Edge {
708                        callee: nested,
709                        srcs,
710                        span: stmt.source_info.span,
711                        via: None,
712                    });
713                }
714            }
715            let terminator = data.terminator();
716            if let TerminatorKind::Call { func, args, .. } = &terminator.kind {
717                let span = terminator.source_info.span;
718                match func.const_fn_def() {
719                    Some((callee, gargs)) => {
720                        let args: Vec<&Operand<'tcx>> = args.iter().map(|a| &a.node).collect();
721                        let srcs: Vec<Src> = args
722                            .iter()
723                            .map(|a| held.of(a, |c| self.string_constant(c)))
724                            .collect();
725                        let origin = args.first().and_then(|a| held.origin_of(a));
726                        self.call(
727                            &mut own,
728                            Some(&mut calls),
729                            typing_env,
730                            callee,
731                            gargs,
732                            &args,
733                            &srcs,
734                            origin,
735                            span,
736                        );
737                    }
738                    None => own.opaque.push("call through a function pointer".into()),
739                }
740            }
741        }
742        own.opaque.sort();
743        own.opaque.dedup();
744        let local = Rc::new(Local { own, calls });
745        self.locals.insert(def_id, local.clone());
746        local
747    }
748
749    /// Add the effects of calling `callee` to `summary`. With `calls`, a call of a local body is
750    /// recorded there instead of followed (for [`Self::component`]).
751    #[allow(clippy::too_many_arguments)]
752    fn call(
753        &mut self,
754        summary: &mut Summary,
755        calls: Option<&mut Vec<Edge>>,
756        typing_env: TypingEnv<'tcx>,
757        callee: DefId,
758        gargs: GenericArgs<'tcx>,
759        args: &[&Operand<'tcx>],
760        srcs: &[Src],
761        origin: Option<DefId>,
762        span: Span,
763    ) {
764        let tcx = self.tcx;
765        let instance = Instance::try_resolve(tcx, typing_env, callee, gargs)
766            .ok()
767            .flatten();
768        let resolved = instance.map(|i| i.def_id()).unwrap_or(callee);
769        // A trait method called through `dyn`, or on a generic the compiler cannot resolve here:
770        // its implementations may be anywhere in the build, so the link step resolves it.
771        let unresolved = match instance {
772            Some(i) => matches!(i.def, InstanceKind::Virtual(..)),
773            None => true,
774        };
775        if unresolved
776            && let Some(trait_id) = tcx.trait_of_assoc(callee)
777            && !self.library
778            && !is_registry(tcx, trait_id)
779            && !OPAQUE_STD.contains(&tcx.crate_name(trait_id.krate).as_str())
780        {
781            let key = format!("{:?}", tcx.def_path_hash(callee));
782            let path = display_path(tcx, callee);
783            if let Some(r) = self.linked.get(&key) {
784                for e in &r.effects {
785                    let mut e = at_call(e, None);
786                    e.via.insert(0, path.clone());
787                    summary.add(e, span);
788                }
789                summary.panics |= r.panics;
790            }
791            if !summary.deferred.contains(&key) {
792                summary.deferred.push(key);
793            }
794            return;
795        }
796        // Through `dyn` or a generic, a trait of another published crate (`AsyncWrite`,
797        // `tower::Service`) may be implemented by anything: unknown, not "no effects".
798        if unresolved
799            && !self.library
800            && let Some(trait_id) = tcx.trait_of_assoc(callee)
801            && !OPAQUE_STD.contains(&tcx.crate_name(trait_id.krate).as_str())
802        {
803            summary
804                .opaque
805                .push(format!("dyn {}", display_path(tcx, callee)));
806        }
807        let path = display_path(tcx, resolved);
808        let krate = tcx.crate_name(resolved.krate);
809        let krate = krate.as_str();
810        let name = tcx
811            .opt_item_name(resolved)
812            .map(|n| n.to_string())
813            .unwrap_or_default();
814        let target = args.first().and_then(|a| self.string_constant(a));
815        // The target of an operation on the call's argument `j`: a constant, or the caller's
816        // parameter it holds.
817        let on = |j: usize| match srcs.get(j) {
818            Some(Src::Const(c)) => (Some(c.clone()), None),
819            Some(Src::Param(k)) => (None, Some(*k)),
820            _ => (None, None),
821        };
822        let mut add = |domain, access, (target, arg): (Option<String>, Option<usize>)| {
823            summary.add(
824                Effect {
825                    domain,
826                    access,
827                    target,
828                    via: vec![path.clone()],
829                    arg,
830                },
831                span,
832            )
833        };
834        let library = self.library;
835        // psync's own runtime helpers are the generated code's plumbing.
836        if krate == "psync" {
837            return;
838        }
839        // Explicit panics in the user's code are exits too: a write must not run before them.
840        if !library && panicking(krate, &path, &name) {
841            summary.panics = true;
842            return;
843        }
844        if OPAQUE_STD.contains(&krate) || IO_CRATES.contains(&krate) {
845            // Generic I/O helpers (`AsyncWriteExt::shutdown`, `Write::write_all`) act on whatever
846            // writer they are given: the receiver's type is the resource.
847            let self_ty = tcx
848                .trait_of_assoc(callee)
849                .and_then(|_| gargs.types().next())
850                .map(|t| format!("{t}"));
851            if !library
852                && let Some((domain, access)) = io_trait_effect(&path, &name, self_ty.as_deref())
853            {
854                add(domain, access, (None, None));
855                return;
856            }
857            if let Some((domain, access, keeps_target)) = io_effect(&path, &name)
858                // Inside libraries, socket traffic is transport, not meaning: every request
859                // writes to a socket.
860                && !(library && domain == Domain::Net)
861            {
862                // `copy(from, to)`, `rename(from, to)`, `hard_link(original, link)`,
863                // `symlink(original, link)`: the second path is written too. `copy` only reads
864                // its source.
865                let second = (domain == Domain::Fs && keeps_target)
866                    .then(|| two_path_fs(&name))
867                    .flatten();
868                match second {
869                    Some(first_access) => {
870                        add(Domain::Fs, first_access, on(0));
871                        add(Domain::Fs, Access::Write, on(1));
872                    }
873                    None => add(
874                        domain,
875                        access,
876                        if keeps_target { on(0) } else { (None, None) },
877                    ),
878                }
879            }
880            return;
881        }
882        if resolved.is_local() {
883            // Polling the future that a call of `async fn f` in this body returned: its effects
884            // came with that call, with its arguments substituted. Followed again here, the
885            // captures would be unknown.
886            if tcx.is_coroutine(resolved) && origin.is_some_and(|f| tcx.parent(resolved) == f) {
887                return;
888            }
889            match calls {
890                Some(calls) if self.has_body(resolved) => calls.push(Edge {
891                    callee: resolved,
892                    srcs: srcs.to_vec(),
893                    span,
894                    via: Some(path.clone()),
895                }),
896                _ => {
897                    let inner = self.summarize(resolved);
898                    summary.absorb(&inner, span, Some(&path), Some(srcs));
899                }
900            }
901            if !self.has_body(resolved) && !library {
902                self.by_name(summary, &path, &name, target, span);
903            }
904            return;
905        }
906        // Another crate. Its summary says what its body does; at the boundary between the user's
907        // code and a published API, the API's verb says what the call means.
908        let key = format!("{:?}", tcx.def_path_hash(resolved));
909        let external = self.external().get(&key).cloned();
910        let use_verb = !library
911            && is_registry(tcx, resolved)
912            && returns_future(tcx, resolved)
913            && psync_graph::verb_of(&name).is_some()
914            && !is_plumbing(&name);
915        let summarized = self
916            .summarized
917            .contains(&format!("{:?}", tcx.stable_crate_id(resolved.krate)));
918        match external {
919            // Summarized, without effects.
920            None if summarized && !use_verb => {}
921            Some(s) if !use_verb => {
922                for effect in s.effects {
923                    let mut effect = at_call(&effect, Some(srcs));
924                    effect.via.insert(0, path.clone());
925                    summary.add(effect, span);
926                }
927                summary.opaque.extend(s.opaque);
928                summary.panics |= s.panics;
929                for d in s.deferred {
930                    if !summary.deferred.contains(&d) {
931                        summary.deferred.push(d);
932                    }
933                }
934            }
935            _ if library || !returns_future(tcx, resolved) => {}
936            _ => self.by_name(summary, &path, &name, target, span),
937        }
938    }
939
940    /// Classify a call into another crate's API by the verb its name starts with.
941    fn by_name(
942        &self,
943        summary: &mut Summary,
944        path: &str,
945        name: &str,
946        target: Option<String>,
947        span: Span,
948    ) {
949        let verb = if is_plumbing(name) {
950            None
951        } else {
952            psync_graph::verb_of(name)
953        };
954        let Some(verb) = verb else {
955            // Functions without a verb in crates without a summary (proc macros, build-only
956            // crates) are usually helpers; record them for `cargo psync summaries`.
957            if !name.is_empty() && !is_plumbing(name) {
958                summary.opaque.push(path.to_string());
959            }
960            return;
961        };
962        let access = match verb {
963            psync_graph::Verb::Read => Access::Read,
964            psync_graph::Verb::Write => Access::Write,
965            psync_graph::Verb::Ordered => Access::Ordered,
966        };
967        // The domain is what the function belongs to: `kube::Api::<K>` for `kube::Api::<K>::list`.
968        let domain = path.rsplit_once("::").map_or(path, |(owner, _)| owner);
969        summary.add(
970            Effect {
971                domain: Domain::Service(domain.to_string()),
972                access,
973                target,
974                via: vec![path.to_string()],
975                arg: None,
976            },
977            span,
978        );
979    }
980
981    fn external(&mut self) -> &HashMap<String, FnSummary> {
982        if self.external.is_none() {
983            let mut map = HashMap::new();
984            if let Some(dir) = &self.summary_dir {
985                for krate in psync_check::read_all::<CrateSummaries>(dir) {
986                    self.summarized.insert(krate.crate_id.clone());
987                    map.extend(krate.functions);
988                }
989            }
990            self.external = Some(map);
991        }
992        self.external.as_ref().expect("loaded")
993    }
994
995    /// The value of a `&str` constant operand.
996    fn string_constant(&self, op: &Operand<'tcx>) -> Option<String> {
997        let Operand::Constant(c) = op else {
998            return None;
999        };
1000        let mir::Const::Val(value, ty) = c.const_ else {
1001            return None;
1002        };
1003        if !matches!(ty.kind(), ty::Ref(_, inner, _) if inner.is_str()) {
1004            return None;
1005        }
1006        let bytes = value.try_get_slice_bytes_for_diagnostics(self.tcx)?;
1007        String::from_utf8(bytes.to_vec()).ok()
1008    }
1009
1010    /// The functions `#[psync::graph]` annotated: each contains the item `__PSYNC_GRAPH`.
1011    fn annotated(&self) -> Vec<DefId> {
1012        let tcx = self.tcx;
1013        tcx.hir_body_owners()
1014            .filter(|o| {
1015                tcx.def_kind(*o) == DefKind::Const
1016                    && tcx
1017                        .opt_item_name(o.to_def_id())
1018                        .is_some_and(|n| n.as_str() == "__PSYNC_GRAPH")
1019            })
1020            .map(|o| tcx.parent(o.to_def_id()))
1021            .collect()
1022    }
1023
1024    /// Facts about every call in the annotated functions (and the closures and async blocks in
1025    /// them), keyed by the source location of the callee's name, for the macro's next expansion.
1026    fn call_facts(&mut self) -> BTreeMap<String, CallFact> {
1027        let tcx = self.tcx;
1028        let mut out = BTreeMap::new();
1029        let mut bodies = self.annotated();
1030        let mut seen = HashSet::new();
1031        while let Some(def_id) = bodies.pop() {
1032            if !seen.insert(def_id) || !self.has_body(def_id) {
1033                continue;
1034            }
1035            let body = tcx.optimized_mir(def_id);
1036            let typing_env = TypingEnv::post_analysis(tcx, def_id);
1037            for data in body.basic_blocks.iter() {
1038                for stmt in &data.statements {
1039                    if let StatementKind::Assign(assign) = &stmt.kind
1040                        && let Rvalue::Aggregate(kind, _) = &assign.1
1041                        && let AggregateKind::Closure(nested, _)
1042                        | AggregateKind::Coroutine(nested, _)
1043                        | AggregateKind::CoroutineClosure(nested, _) = **kind
1044                    {
1045                        bodies.push(nested);
1046                    }
1047                }
1048                let terminator = data.terminator();
1049                let TerminatorKind::Call {
1050                    func,
1051                    args,
1052                    fn_span,
1053                    ..
1054                } = &terminator.kind
1055                else {
1056                    continue;
1057                };
1058                let Some((callee, gargs)) = func.const_fn_def() else {
1059                    continue;
1060                };
1061                if fn_span.from_expansion() || tcx.crate_name(callee.krate).as_str() == "psync" {
1062                    continue;
1063                }
1064                let Some(site) = site_key(tcx, *fn_span) else {
1065                    continue;
1066                };
1067                let args: Vec<&Operand<'tcx>> = args.iter().map(|a| &a.node).collect();
1068                let mut one = Summary::default();
1069                // In terms of the call's own arguments: the macro reads them at the call site.
1070                let srcs: Vec<Src> = (0..args.len()).map(Src::Param).collect();
1071                self.call(
1072                    &mut one, None, typing_env, callee, gargs, &args, &srcs, None, *fn_span,
1073                );
1074                let name = tcx
1075                    .opt_item_name(callee)
1076                    .map(|n| n.to_string())
1077                    .unwrap_or_default();
1078                out.insert(
1079                    site,
1080                    CallFact {
1081                        callee: display_path(tcx, callee),
1082                        name,
1083                        effects: one.effects.into_iter().map(|l| l.effect).collect(),
1084                        panics: one.panics,
1085                        deferred: one.deferred,
1086                        opaque: !one.opaque.is_empty(),
1087                    },
1088                );
1089            }
1090        }
1091        out
1092    }
1093
1094    /// The dependence graph of every annotated function and local `async fn`, and of the closures
1095    /// and async blocks in them: their calls with effects (or into this crate) and their awaits,
1096    /// each with the branches that decide whether it runs.
1097    fn pdg(&mut self) -> psync_check::pdg::CratePdg {
1098        let tcx = self.tcx;
1099        let mut bodies = self.annotated();
1100        for owner in tcx.hir_body_owners() {
1101            let d = owner.to_def_id();
1102            if matches!(tcx.def_kind(d), DefKind::Fn | DefKind::AssocFn)
1103                && tcx.asyncness(d).is_async()
1104            {
1105                bodies.push(d);
1106            }
1107        }
1108        let mut seen = HashSet::new();
1109        let mut functions = Vec::new();
1110        while let Some(def_id) = bodies.pop() {
1111            if !seen.insert(def_id) || !self.has_body(def_id) {
1112                continue;
1113            }
1114            let body = tcx.optimized_mir(def_id);
1115            for data in body.basic_blocks.iter() {
1116                for stmt in &data.statements {
1117                    if let StatementKind::Assign(assign) = &stmt.kind
1118                        && let Rvalue::Aggregate(kind, _) = &assign.1
1119                        && let AggregateKind::Closure(nested, _)
1120                        | AggregateKind::Coroutine(nested, _)
1121                        | AggregateKind::CoroutineClosure(nested, _) = **kind
1122                    {
1123                        bodies.push(nested);
1124                    }
1125                }
1126            }
1127            let mut f = self.body_pdg(def_id, body);
1128            // What the macro made concurrent here, by the bodies whose graphs follow.
1129            let (levels, prefixes) = markers(tcx, def_id);
1130            let name = |d: DefId| {
1131                if tcx.is_closure_like(d) {
1132                    tcx.def_path_str(d)
1133                } else {
1134                    display_path(tcx, d)
1135                }
1136            };
1137            f.joins = levels
1138                .into_iter()
1139                .map(|(level, chains)| psync_check::pdg::PdgJoin {
1140                    level,
1141                    chains: chains
1142                        .iter()
1143                        .map(|c| psync_check::pdg::PdgChain {
1144                            path: name(c.body),
1145                            first: c.order,
1146                            last: c.last,
1147                            exits: c.exits,
1148                            speculate: c.spec,
1149                            independent: c.indep,
1150                            sync: c.sync,
1151                        })
1152                        .collect(),
1153                })
1154                .collect();
1155            f.prefetches = prefixes
1156                .iter()
1157                .map(|p| psync_check::pdg::PdgPrefetch {
1158                    path: name(p.body),
1159                    terminates: p.terminates,
1160                    speculate: p.spec,
1161                })
1162                .collect();
1163            if !f.nodes.is_empty() || !f.joins.is_empty() || !f.prefetches.is_empty() {
1164                functions.push(f);
1165            }
1166        }
1167        functions.sort_by(|a, b| a.path.cmp(&b.path));
1168        psync_check::pdg::CratePdg {
1169            crate_name: tcx.crate_name(LOCAL_CRATE).to_string(),
1170            functions,
1171            entries: self.entries(),
1172        }
1173    }
1174
1175    /// The crate's entry points: `main`, and every local function or closure handed to a web
1176    /// framework's registering call (axum's `get(h)`, `MethodRouter::post(h)`, ...; actix-web's
1177    /// `to(h)`, which its `#[get("/x")]` macros also expand to), with the route a string literal
1178    /// gives it. axum names the route downstream (`.route("/x", get(h))`), actix-web upstream
1179    /// (`Resource::new("/x")...to(h)`) or downstream (`.route("/x", web::get().to(h))`): both
1180    /// directions are followed through the framework's own calls.
1181    fn entries(&self) -> Vec<psync_check::pdg::PdgEntry> {
1182        const AXUM: &[&str] = &[
1183            "get", "post", "put", "delete", "patch", "head", "options", "trace", "connect", "any",
1184        ];
1185        let tcx = self.tcx;
1186        let line = |span: Span| {
1187            tcx.sess
1188                .source_map()
1189                .lookup_char_pos(span.source_callsite().lo())
1190                .line
1191        };
1192        let mut out = Vec::new();
1193        // A build script's `main` runs at build time, not when the program does.
1194        let build_script = tcx
1195            .crate_name(LOCAL_CRATE)
1196            .as_str()
1197            .starts_with("build_script_");
1198        if let Some((main, _)) = tcx.entry_fn(())
1199            && !build_script
1200        {
1201            out.push(psync_check::pdg::PdgEntry {
1202                framework: "main".into(),
1203                handler: display_path(tcx, main),
1204                line: line(tcx.def_span(main)),
1205                ..Default::default()
1206            });
1207        }
1208        for owner in tcx.hir_body_owners() {
1209            let d = owner.to_def_id();
1210            if !self.has_body(d) {
1211                continue;
1212            }
1213            let body = tcx.optimized_mir(d);
1214            // Every call to a crate's function: its callee, crate, arguments and destination.
1215            struct Call<'a, 'tcx> {
1216                callee: DefId,
1217                krate: String,
1218                args: Vec<&'a Operand<'tcx>>,
1219                dest: mir::Local,
1220                span: Span,
1221            }
1222            let mut calls: Vec<Call<'_, 'tcx>> = Vec::new();
1223            // `_7 = move _5`: what a local's value moves on to.
1224            let mut moves: HashMap<mir::Local, Vec<mir::Local>> = HashMap::new();
1225            // `_3 = const "/users"`: the string a local holds, when a literal is put in it.
1226            let mut strings: HashMap<mir::Local, String> = HashMap::new();
1227            for data in body.basic_blocks.iter() {
1228                for stmt in &data.statements {
1229                    if let StatementKind::Assign(assign) = &stmt.kind
1230                        && let Rvalue::Use(op @ Operand::Constant(_), ..) = &assign.1
1231                        && assign.0.projection.is_empty()
1232                        && let Some(text) = self.string_constant(op)
1233                    {
1234                        strings.insert(assign.0.local, text);
1235                    }
1236                    if let StatementKind::Assign(assign) = &stmt.kind
1237                        && let Rvalue::Use(Operand::Move(p) | Operand::Copy(p), ..) = &assign.1
1238                        && p.projection.is_empty()
1239                        && assign.0.projection.is_empty()
1240                    {
1241                        moves.entry(p.local).or_default().push(assign.0.local);
1242                    }
1243                }
1244                if let TerminatorKind::Call {
1245                    func,
1246                    args,
1247                    destination,
1248                    fn_span,
1249                    ..
1250                } = &data.terminator().kind
1251                    && let Some((callee, _)) = func.const_fn_def()
1252                {
1253                    calls.push(Call {
1254                        callee,
1255                        krate: tcx.crate_name(callee.krate).to_string(),
1256                        args: args.iter().map(|a| &a.node).collect(),
1257                        dest: destination.local,
1258                        span: *fn_span,
1259                    });
1260                }
1261            }
1262            let local_of = |op: &Operand<'tcx>| match op {
1263                Operand::Move(p) | Operand::Copy(p) if p.projection.is_empty() => Some(p.local),
1264                _ => None,
1265            };
1266            let literal = |c: &Call<'_, 'tcx>| {
1267                c.args.iter().find_map(|a| {
1268                    self.string_constant(a)
1269                        .or_else(|| local_of(a).and_then(|l| strings.get(&l).cloned()))
1270                })
1271            };
1272            // Downstream: the calls the value of `local` reaches, through moves and the
1273            // framework's calls, until one named `route` with a literal path.
1274            let downstream = |from: mir::Local, fw: &str| -> Option<String> {
1275                let mut todo = vec![from];
1276                let mut seen = HashSet::new();
1277                while let Some(l) = todo.pop() {
1278                    if !seen.insert(l) || seen.len() > 32 {
1279                        continue;
1280                    }
1281                    todo.extend(moves.get(&l).into_iter().flatten().copied());
1282                    for c in calls.iter().filter(|c| c.krate == fw) {
1283                        if !c.args.iter().any(|a| local_of(a) == Some(l)) {
1284                            continue;
1285                        }
1286                        let name = tcx.item_name(c.callee);
1287                        if matches!(name.as_str(), "route" | "resource" | "route_service")
1288                            && let Some(r) = literal(c)
1289                        {
1290                            return Some(r);
1291                        }
1292                        todo.push(c.dest);
1293                    }
1294                }
1295                None
1296            };
1297            // Upstream: the receiver's value, through the framework's calls, back to one that
1298            // names a path (`Resource::new("/x")`, `web::resource("/x")`, `web::scope("/x")`).
1299            let upstream = |from: mir::Local, fw: &str| -> Option<String> {
1300                let mut todo = vec![from];
1301                let mut seen = HashSet::new();
1302                while let Some(l) = todo.pop() {
1303                    if !seen.insert(l) || seen.len() > 32 {
1304                        continue;
1305                    }
1306                    for (src, dsts) in &moves {
1307                        if dsts.contains(&l) {
1308                            todo.push(*src);
1309                        }
1310                    }
1311                    for c in calls.iter().filter(|c| c.krate == fw && c.dest == l) {
1312                        let name = tcx.item_name(c.callee);
1313                        if matches!(name.as_str(), "new" | "resource" | "scope")
1314                            && let Some(r) = literal(c)
1315                        {
1316                            return Some(r);
1317                        }
1318                        if let Some(recv) = c.args.first().and_then(|a| local_of(a)) {
1319                            todo.push(recv);
1320                        }
1321                    }
1322                }
1323                None
1324            };
1325            for c in &calls {
1326                let method = tcx.item_name(c.callee).to_string();
1327                let registers = match c.krate.as_str() {
1328                    "axum" => AXUM.contains(&method.as_str()),
1329                    "actix_web" => method == "to",
1330                    _ => false,
1331                };
1332                if !registers {
1333                    continue;
1334                }
1335                for a in &c.args {
1336                    let handler = match a.ty(body, tcx).kind() {
1337                        ty::FnDef(h, _) | ty::Closure(h, _) if h.is_local() => *h,
1338                        _ => continue,
1339                    };
1340                    let route = downstream(c.dest, &c.krate)
1341                        .or_else(|| {
1342                            c.args
1343                                .first()
1344                                .and_then(|r| local_of(r))
1345                                .and_then(|r| upstream(r, &c.krate))
1346                        })
1347                        .unwrap_or_default();
1348                    out.push(psync_check::pdg::PdgEntry {
1349                        framework: c.krate.clone(),
1350                        method: method.clone(),
1351                        route,
1352                        handler: if tcx.is_closure_like(handler) {
1353                            tcx.def_path_str(handler)
1354                        } else {
1355                            display_path(tcx, handler)
1356                        },
1357                        line: line(tcx.def_span(handler)),
1358                        registered_at: line(c.span),
1359                    });
1360                }
1361            }
1362        }
1363        out.sort_by(|a, b| (a.registered_at, &a.handler).cmp(&(b.registered_at, &b.handler)));
1364        out.dedup();
1365        out
1366    }
1367
1368    #[allow(clippy::too_many_lines)]
1369    fn body_pdg(&mut self, def_id: DefId, body: &'tcx mir::Body<'tcx>) -> psync_check::pdg::FnPdg {
1370        use psync_check::pdg::{Cfg, FnPdg, PdgBranch, PdgNode, control_dependence};
1371        let tcx = self.tcx;
1372        let typing_env = TypingEnv::post_analysis(tcx, def_id);
1373        let held = Held::new(tcx, def_id, body, |op| self.string_constant(op));
1374        let blocks = &body.basic_blocks;
1375        let line = |span: Span| {
1376            let span = span.source_callsite();
1377            tcx.sess.source_map().lookup_char_pos(span.lo()).line
1378        };
1379        // Is `place` the coroutine's own state, `*_1` (or `*(_1.0)`, through a `Pin`)?
1380        let state = |place: &mir::Place<'tcx>| {
1381            place.local.as_usize() == 1
1382                || {
1383                    // `_7 = copy (_1.0)` then `(*_7)`: follow the copy in the first block.
1384                    blocks[mir::START_BLOCK].statements.iter().any(|st| {
1385                matches!(&st.kind, StatementKind::Assign(a)
1386                    if a.0.local == place.local
1387                        && matches!(&a.1, Rvalue::Use(Operand::Copy(p) | Operand::Move(p), ..) if p.local.as_usize() == 1))
1388            })
1389                }
1390        };
1391        // A suspended coroutine resumes through a switch on its state in the first block. Undo
1392        // that: the switch is not a branch, and each suspension (`state = k; return`) continues
1393        // at the block the switch sends state `k` to.
1394        let mut dispatch: HashMap<u128, mir::BasicBlock> = HashMap::new();
1395        if tcx.is_coroutine(def_id)
1396            && let TerminatorKind::SwitchInt { discr, targets } =
1397                &blocks[mir::START_BLOCK].terminator().kind
1398            && let Some(local) = discr.place().map(|p| p.local)
1399            && blocks[mir::START_BLOCK].statements.iter().any(|st| {
1400                matches!(&st.kind, StatementKind::Assign(a)
1401                    if a.0.local == local && matches!(&a.1, Rvalue::Discriminant(p) if state(p)))
1402            })
1403        {
1404            dispatch = targets.iter().collect();
1405        }
1406        let suspends_to = |b: mir::BasicBlock| -> Option<mir::BasicBlock> {
1407            let data = &blocks[b];
1408            if !matches!(data.terminator().kind, TerminatorKind::Return) {
1409                return None;
1410            }
1411            data.statements.iter().rev().find_map(|st| match &st.kind {
1412                StatementKind::SetDiscriminant {
1413                    place,
1414                    variant_index,
1415                } if state(place) => {
1416                    let v = variant_index.as_u32() as u128;
1417                    (v >= 3).then(|| dispatch.get(&v).copied()).flatten()
1418                }
1419                _ => None,
1420            })
1421        };
1422        // What a switch tests, and the label of each of its values.
1423        let switch = |b: mir::BasicBlock| -> Option<(String, Labels<'_>)> {
1424            let data = &blocks[b];
1425            let TerminatorKind::SwitchInt { discr, .. } = &data.terminator().kind else {
1426                return None;
1427            };
1428            let local = discr.place().map(|p| p.local);
1429            let of = local.and_then(|l| {
1430                data.statements.iter().rev().find_map(|st| match &st.kind {
1431                    StatementKind::Assign(a) if a.0.local == l => match &a.1 {
1432                        Rvalue::Discriminant(p) => Some(p.ty(&body.local_decls, tcx).ty),
1433                        _ => None,
1434                    },
1435                    _ => None,
1436                })
1437            });
1438            // `x?`: continues when it holds a value, leaves when it holds an error.
1439            if data
1440                .terminator()
1441                .source_info
1442                .span
1443                .is_desugaring(rustc_span::DesugaringKind::QuestionMark)
1444                && of.is_some_and(|t| {
1445                    matches!(t.kind(), ty::Adt(adt, _) if tcx.item_name(adt.did()).as_str() == "ControlFlow")
1446                })
1447            {
1448                return Some((
1449                    "`?`".into(),
1450                    Box::new(|v| match v {
1451                        Some(0) => "ok".into(),
1452                        _ => "exits".into(),
1453                    }),
1454                ));
1455            }
1456            match of.map(|t| t.kind()) {
1457                Some(ty::Adt(adt, _)) if adt.is_enum() => {
1458                    let adt = *adt;
1459                    let name = tcx.item_name(adt.did()).to_string();
1460                    Some((
1461                        format!("match on `{name}`"),
1462                        Box::new(move |v| match v {
1463                            Some(v) => adt
1464                                .discriminants(tcx)
1465                                .find(|(_, d)| d.val == v)
1466                                .map(|(i, _)| adt.variant(i).name.to_string())
1467                                .unwrap_or_else(|| v.to_string()),
1468                            None => "otherwise".into(),
1469                        }),
1470                    ))
1471                }
1472                _ if discr.ty(&body.local_decls, tcx).is_bool() => Some((
1473                    "if".into(),
1474                    Box::new(|v| match v {
1475                        Some(0) => "false".into(),
1476                        Some(_) | None => "true".into(),
1477                    }),
1478                )),
1479                _ => Some((
1480                    "switch".into(),
1481                    Box::new(|v| v.map_or("otherwise".into(), |v| v.to_string())),
1482                )),
1483            }
1484        };
1485        let mut cfg = Cfg {
1486            succ: vec![Vec::new(); blocks.len()],
1487        };
1488        for (b, data) in blocks.iter_enumerated() {
1489            if data.is_cleanup {
1490                continue;
1491            }
1492            let succ = &mut cfg.succ[b.as_usize()];
1493            if b == mir::START_BLOCK && !dispatch.is_empty() {
1494                if let Some(start) = dispatch.get(&0) {
1495                    succ.push((start.as_usize(), String::new()));
1496                }
1497                continue;
1498            }
1499            if let Some(resume) = suspends_to(b) {
1500                succ.push((resume.as_usize(), String::new()));
1501                continue;
1502            }
1503            // `.await` polls in a loop until `Ready`; that loop is not a branch of the program.
1504            if let TerminatorKind::SwitchInt { targets, .. } = &data.terminator().kind
1505                && data
1506                    .terminator()
1507                    .source_info
1508                    .span
1509                    .is_desugaring(rustc_span::DesugaringKind::Await)
1510                && let Some((test, _)) = switch(b)
1511                && test == "match on `Poll`"
1512            {
1513                if let Some(ready) = targets.iter().find(|(v, _)| *v == 0).map(|(_, t)| t) {
1514                    succ.push((ready.as_usize(), String::new()));
1515                }
1516                continue;
1517            }
1518            if let TerminatorKind::SwitchInt { targets, .. } = &data.terminator().kind
1519                && let Some((_, label)) = switch(b)
1520            {
1521                let mut by_target: Vec<(usize, Vec<String>)> = Vec::new();
1522                let all = targets
1523                    .iter()
1524                    .map(|(v, t)| (Some(v), t))
1525                    .chain([(None, targets.otherwise())]);
1526                for (v, t) in all {
1527                    if blocks[t].is_cleanup {
1528                        continue;
1529                    }
1530                    match by_target.iter_mut().find(|(x, _)| *x == t.as_usize()) {
1531                        Some((_, ls)) => ls.push(label(v)),
1532                        None => by_target.push((t.as_usize(), vec![label(v)])),
1533                    }
1534                }
1535                succ.extend(by_target.into_iter().map(|(t, ls)| (t, ls.join(" | "))));
1536                continue;
1537            }
1538            for t in data.terminator().successors() {
1539                if !blocks[t].is_cleanup && !succ.iter().any(|(x, _)| *x == t.as_usize()) {
1540                    succ.push((t.as_usize(), String::new()));
1541                }
1542            }
1543        }
1544        let guards = control_dependence(&cfg);
1545        let mut nodes = Vec::new();
1546        for (b, data) in blocks.iter_enumerated() {
1547            if data.is_cleanup || guards.get(b.as_usize()).is_none() {
1548                continue;
1549            }
1550            let terminator = data.terminator();
1551            let (kind, callee, effects) = if suspends_to(b).is_some() {
1552                ("await", String::new(), Vec::new())
1553            } else if let TerminatorKind::Call {
1554                func,
1555                args,
1556                fn_span,
1557                ..
1558            } = &terminator.kind
1559                && let Some((callee, gargs)) = func.const_fn_def()
1560                && !fn_span.from_expansion()
1561                && tcx.crate_name(callee.krate).as_str() != "psync"
1562            {
1563                let args: Vec<&Operand<'tcx>> = args.iter().map(|a| &a.node).collect();
1564                let mut one = Summary::default();
1565                // In terms of this body's parameters (a closure's or async block's: its captures).
1566                let srcs: Vec<Src> = args
1567                    .iter()
1568                    .map(|a| held.of(a, |c| self.string_constant(c)))
1569                    .collect();
1570                self.call(
1571                    &mut one, None, typing_env, callee, gargs, &args, &srcs, None, *fn_span,
1572                );
1573                if one.effects.is_empty() && !callee.is_local() {
1574                    continue;
1575                }
1576                let effects = one
1577                    .effects
1578                    .iter()
1579                    .map(|l| match l.effect.arg {
1580                        Some(k) => format!("{} (parameter {k})", l.effect.describe()),
1581                        None => l.effect.describe(),
1582                    })
1583                    .collect();
1584                ("call", display_path(tcx, callee), effects)
1585            } else {
1586                continue;
1587            };
1588            // An await is reached through its poll loop, which is not a branch: it runs when the
1589            // poll before it runs.
1590            let mut at = b;
1591            if kind == "await" {
1592                for _ in 0..16 {
1593                    match blocks.predecessors()[at].as_slice() {
1594                        [p] => {
1595                            at = *p;
1596                            if matches!(
1597                                blocks[at].terminator().kind,
1598                                TerminatorKind::SwitchInt { .. }
1599                            ) {
1600                                break;
1601                            }
1602                        }
1603                        _ => break,
1604                    }
1605                }
1606            }
1607            nodes.push(PdgNode {
1608                block: b.as_usize(),
1609                line: line(terminator.source_info.span),
1610                kind: kind.into(),
1611                callee,
1612                effects,
1613                guards: guards[at.as_usize()].clone(),
1614                uses: Vec::new(),
1615            });
1616        }
1617        // Data edges: which calls' results each value holds, through assignments, borrows, moves,
1618        // slots kept across awaits and calls that are not points (`?`, `unwrap`, `into_future`),
1619        // flow-insensitively.
1620        let points: HashSet<usize> = nodes
1621            .iter()
1622            .filter(|n| n.kind == "call")
1623            .map(|n| n.block)
1624            .collect();
1625        let base = |p: &mir::Place<'tcx>| held.root(p).unwrap_or(Root::Local(p.local));
1626        let of_op = |op: &Operand<'tcx>| match op {
1627            Operand::Copy(p) | Operand::Move(p) => Some(base(p)),
1628            _ => None,
1629        };
1630        let rvalue_roots = |rv: &Rvalue<'tcx>| -> Vec<Root> {
1631            match rv {
1632                Rvalue::Use(op, ..)
1633                | Rvalue::Cast(_, op, _)
1634                | Rvalue::UnaryOp(_, op)
1635                | Rvalue::Repeat(op, _) => of_op(op).into_iter().collect(),
1636                Rvalue::Ref(_, _, p)
1637                | Rvalue::CopyForDeref(p)
1638                | Rvalue::Discriminant(p)
1639                | Rvalue::RawPtr(_, p) => vec![base(p)],
1640                Rvalue::BinaryOp(_, ops) => {
1641                    [&ops.0, &ops.1].into_iter().filter_map(of_op).collect()
1642                }
1643                Rvalue::Aggregate(_, ops) => ops.iter().filter_map(of_op).collect(),
1644                _ => Vec::new(),
1645            }
1646        };
1647        type Holds = HashMap<Root, std::collections::BTreeSet<usize>>;
1648        let mut holds: Holds = HashMap::new();
1649        let add = |holds: &mut Holds, dst: Root, from: Vec<usize>| -> bool {
1650            let set = holds.entry(dst).or_default();
1651            let mut changed = false;
1652            for f in from {
1653                changed |= set.insert(f);
1654            }
1655            changed
1656        };
1657        let held_by = |holds: &Holds, roots: &[Root]| -> Vec<usize> {
1658            roots
1659                .iter()
1660                .flat_map(|r| holds.get(r).into_iter().flatten().copied())
1661                .collect()
1662        };
1663        for _ in 0..64 {
1664            let mut changed = false;
1665            for (b, data) in blocks.iter_enumerated() {
1666                if data.is_cleanup {
1667                    continue;
1668                }
1669                for st in &data.statements {
1670                    if let StatementKind::Assign(a) = &st.kind {
1671                        let from = held_by(&holds, &rvalue_roots(&a.1));
1672                        changed |= add(&mut holds, base(&a.0), from);
1673                    }
1674                }
1675                if let TerminatorKind::Call {
1676                    args, destination, ..
1677                } = &data.terminator().kind
1678                {
1679                    let from = if points.contains(&b.as_usize()) {
1680                        vec![b.as_usize()]
1681                    } else {
1682                        let roots: Vec<Root> = args.iter().filter_map(|a| of_op(&a.node)).collect();
1683                        held_by(&holds, &roots)
1684                    };
1685                    changed |= add(&mut holds, base(destination), from);
1686                }
1687            }
1688            if !changed {
1689                break;
1690            }
1691        }
1692        let uses_of = |roots: &[Root], own: Option<usize>| -> Vec<usize> {
1693            let mut out: Vec<usize> = held_by(&holds, roots)
1694                .into_iter()
1695                .filter(|b| Some(*b) != own)
1696                .collect();
1697            out.sort_unstable();
1698            out.dedup();
1699            out
1700        };
1701        for n in &mut nodes {
1702            if n.kind != "call" {
1703                continue;
1704            }
1705            let bb = mir::BasicBlock::from_usize(n.block);
1706            if let TerminatorKind::Call { args, .. } = &blocks[bb].terminator().kind {
1707                let roots: Vec<Root> = args.iter().filter_map(|a| of_op(&a.node)).collect();
1708                n.uses = uses_of(&roots, Some(n.block));
1709            }
1710        }
1711        let mut branches: Vec<PdgBranch> = Vec::new();
1712        for n in &nodes {
1713            for g in &n.guards {
1714                if branches.iter().any(|x| x.block == g.branch) {
1715                    continue;
1716                }
1717                let bb = mir::BasicBlock::from_usize(g.branch);
1718                // The calls whose results the switched value holds.
1719                let roots: Vec<Root> = match &blocks[bb].terminator().kind {
1720                    TerminatorKind::SwitchInt { discr, .. } => of_op(discr).into_iter().collect(),
1721                    _ => Vec::new(),
1722                };
1723                branches.push(PdgBranch {
1724                    block: g.branch,
1725                    line: line(blocks[bb].terminator().source_info.span),
1726                    uses: uses_of(&roots, None),
1727                    test: switch(bb)
1728                        .map(|(t, _)| t)
1729                        .unwrap_or_else(|| "branch".into()),
1730                });
1731            }
1732        }
1733        branches.sort_by_key(|b| b.block);
1734        nodes.sort_by_key(|n| (n.line, n.block));
1735        // `select!` and `join!`: an await whose code a macro of that name wrote. The calls the
1736        // user wrote inside the macro's call either build its futures, and run before the await,
1737        // or are handlers, and run only after it: no path from the start reaches them around it.
1738        let mut selects: Vec<psync_check::pdg::PdgSelect> = Vec::new();
1739        for (b, data) in blocks.iter_enumerated() {
1740            if data.is_cleanup || suspends_to(b).is_none() {
1741                continue;
1742            }
1743            let Some((name, call_site)) = awaiting_macro(data.terminator().source_info.span) else {
1744                continue;
1745            };
1746            if selects
1747                .iter()
1748                .any(|x| x.line == line(call_site) && x.name == name)
1749            {
1750                continue;
1751            }
1752            // The await is its whole poll loop: a poll that is `Ready` at once never yields. Every
1753            // block of this `.await` (its desugaring, inside this macro's call) is cut.
1754            let this_await = |bb: mir::BasicBlock| {
1755                let span = blocks[bb].terminator().source_info.span;
1756                span.is_desugaring(rustc_span::DesugaringKind::Await)
1757                    && awaiting_macro(span).is_some_and(|(_, c)| c == call_site)
1758            };
1759            let mut seen = vec![false; cfg.succ.len()];
1760            let mut stack = vec![mir::START_BLOCK.as_usize()];
1761            while let Some(n) = stack.pop() {
1762                let bb = mir::BasicBlock::from_usize(n);
1763                if n == b.as_usize() || this_await(bb) || std::mem::replace(&mut seen[n], true) {
1764                    continue;
1765                }
1766                stack.extend(cfg.succ[n].iter().map(|(t, _)| *t));
1767            }
1768            let (mut futures, mut handlers) = (Vec::new(), Vec::new());
1769            for n in nodes.iter().filter(|n| n.kind == "call") {
1770                let span = blocks[mir::BasicBlock::from_usize(n.block)]
1771                    .terminator()
1772                    .source_info
1773                    .span;
1774                if span.from_expansion() || !call_site.contains(span) {
1775                    continue;
1776                }
1777                if seen[n.block] {
1778                    futures.push(n.block);
1779                } else {
1780                    handlers.push(n.block);
1781                }
1782            }
1783            selects.push(psync_check::pdg::PdgSelect {
1784                name,
1785                line: line(call_site),
1786                at: b.as_usize(),
1787                futures,
1788                handlers,
1789            });
1790        }
1791        // Loops: how often each body runs, what runs in it, and where it is left.
1792        let natural = psync_check::pdg::natural_loops(&cfg, mir::START_BLOCK.as_usize());
1793        let mut loops = Vec::new();
1794        for (k, l) in natural.iter().enumerate() {
1795            let inside_loop = |b: usize| l.blocks.binary_search(&b).is_ok();
1796            // `for x in it` calls `Iterator::next` on `it` in the loop: once per item.
1797            let next = l.blocks.iter().find_map(|&b| {
1798                let bb = mir::BasicBlock::from_usize(b);
1799                let TerminatorKind::Call { func, fn_span, .. } = &blocks[bb].terminator().kind
1800                else {
1801                    return None;
1802                };
1803                let (callee, gargs) = func.const_fn_def()?;
1804                let is_next = tcx.item_name(callee).as_str() == "next"
1805                    && tcx
1806                        .trait_of_assoc(callee)
1807                        .is_some_and(|t| tcx.is_diagnostic_item(rustc_span::sym::Iterator, t));
1808                is_next.then(|| (gargs.type_at(0).peel_refs().to_string(), line(*fn_span)))
1809            });
1810            let header_line = line(
1811                blocks[mir::BasicBlock::from_usize(l.header)]
1812                    .terminator()
1813                    .source_info
1814                    .span,
1815            );
1816            let mut exits = Vec::new();
1817            for &b in &l.blocks {
1818                if cfg.succ[b].len() < 2 {
1819                    continue;
1820                }
1821                for (t, label) in &cfg.succ[b] {
1822                    // An edge to `unreachable` (a match's impossible `otherwise`) leaves nothing.
1823                    let dead = matches!(
1824                        blocks[mir::BasicBlock::from_usize(*t)].terminator().kind,
1825                        TerminatorKind::Unreachable
1826                    );
1827                    let g = psync_check::pdg::Guard {
1828                        branch: b,
1829                        label: label.clone(),
1830                    };
1831                    if !inside_loop(*t) && !dead && !exits.contains(&g) {
1832                        exits.push(g);
1833                    }
1834                }
1835            }
1836            // The innermost loop around this one: the smallest earlier loop holding its header.
1837            let inside = natural[..k]
1838                .iter()
1839                .rev()
1840                .find(|o| o.blocks.binary_search(&l.header).is_ok())
1841                .map(|o| o.header);
1842            loops.push(psync_check::pdg::PdgLoop {
1843                header: l.header,
1844                line: next.as_ref().map_or(header_line, |(_, ln)| *ln),
1845                per_item_of: next.map(|(t, _)| t).unwrap_or_default(),
1846                nodes: nodes
1847                    .iter()
1848                    .filter(|n| inside_loop(n.block))
1849                    .map(|n| n.block)
1850                    .collect(),
1851                exits,
1852                inside,
1853            });
1854        }
1855        FnPdg {
1856            path: if tcx.is_closure_like(def_id) {
1857                tcx.def_path_str(def_id)
1858            } else {
1859                display_path(tcx, def_id)
1860            },
1861            nodes,
1862            branches,
1863            joins: Vec::new(),
1864            prefetches: Vec::new(),
1865            loops,
1866            selects,
1867        }
1868    }
1869
1870    /// Write the summaries of every local function for crates that depend on this one.
1871    pub fn write_summaries(&mut self) {
1872        let Some(dir) = self.summary_dir.clone() else {
1873            return;
1874        };
1875        let tcx = self.tcx;
1876        let mut out = CrateSummaries {
1877            crate_name: tcx.crate_name(LOCAL_CRATE).to_string(),
1878            crate_id: format!("{:?}", tcx.stable_crate_id(LOCAL_CRATE)),
1879            ..Default::default()
1880        };
1881        let owners: Vec<LocalDefId> = tcx.hir_body_owners().collect();
1882        for owner in owners {
1883            let def_id = owner.to_def_id();
1884            if !matches!(tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn) {
1885                continue;
1886            }
1887            let key = format!("{:?}", tcx.def_path_hash(def_id));
1888            // Methods implementing a trait method, for the link step's resolution of `dyn` calls.
1889            if tcx.def_kind(def_id) == DefKind::AssocFn
1890                && let Some(trait_item) = tcx.associated_item(def_id).trait_item_def_id()
1891                && !OPAQUE_STD.contains(&tcx.crate_name(trait_item.krate).as_str())
1892            {
1893                out.impls
1894                    .entry(format!("{:?}", tcx.def_path_hash(trait_item)))
1895                    .or_default()
1896                    .push(key.clone());
1897            }
1898            let s = self.summarize(def_id);
1899            if s.effects.is_empty() && s.opaque.is_empty() && !s.panics && s.deferred.is_empty() {
1900                continue;
1901            }
1902            out.functions.insert(
1903                key,
1904                FnSummary {
1905                    path: display_path(tcx, def_id),
1906                    effects: s.effects.iter().map(|l| l.effect.clone()).collect(),
1907                    opaque: s.opaque.clone(),
1908                    panics: s.panics,
1909                    deferred: s.deferred.clone(),
1910                },
1911            );
1912        }
1913        out.calls = self.call_facts();
1914        let _ = std::fs::create_dir_all(&dir);
1915        let file = dir.join(format!(
1916            "{}-{:?}.json",
1917            out.crate_name,
1918            tcx.stable_crate_id(LOCAL_CRATE)
1919        ));
1920        if let Ok(json) = serde_json::to_string(&out) {
1921            let _ = std::fs::write(file, json);
1922        }
1923        // Next to the summaries: `target/psync/pdg`, for `cargo psync pdg`.
1924        if let Some(parent) = dir.parent() {
1925            let pdg = self.pdg();
1926            let pdg_dir = parent.join("pdg");
1927            let _ = std::fs::create_dir_all(&pdg_dir);
1928            let file = pdg_dir.join(format!(
1929                "{}-{:?}.json",
1930                pdg.crate_name,
1931                tcx.stable_crate_id(LOCAL_CRATE)
1932            ));
1933            if let Ok(json) = serde_json::to_string(&pdg) {
1934                let _ = std::fs::write(file, json);
1935            }
1936        }
1937    }
1938}
1939
1940/// Insert `#[psync::seq]` before the statement containing `span` (or, for a loop prefix, before
1941/// the `for` loop around it), on its own line with the statement's indentation.
1942fn seq_fix(tcx: TyCtxt<'_>, span: Span, enclosing_loop: bool) -> Option<psync_check::Fix> {
1943    let sm = tcx.sess.source_map();
1944    let pos = sm.lookup_byte_offset(span.lo());
1945    let src = pos.sf.src.as_ref()?;
1946    let rustc_span::FileName::Real(real) = &pos.sf.name else {
1947        return None;
1948    };
1949    let path = real.local_path()?;
1950    let file = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
1951    let bytes = src.as_bytes();
1952    let mut at = pos.pos.0 as usize;
1953    // Walk back to the start of the statement: the previous `;`, `{` or `}` outside brackets.
1954    let mut depth = 0i32;
1955    let start = loop {
1956        if at == 0 {
1957            break 0;
1958        }
1959        at -= 1;
1960        match bytes[at] {
1961            b')' | b']' => depth += 1,
1962            b'(' | b'[' => depth -= 1,
1963            b'}' if depth == 0 => break at + 1,
1964            b'{' | b';' if depth == 0 => break at + 1,
1965            b'}' => depth += 1,
1966            b'{' => depth -= 1,
1967            _ => {}
1968        }
1969    };
1970    let mut start = start;
1971    // For a loop, the statement found is inside the body: continue to the `for` that opens it.
1972    if enclosing_loop {
1973        let before = &src[..start];
1974        let header = before.rfind("for ")?;
1975        start = before[..header].rfind('\n').map_or(0, |i| i + 1);
1976    }
1977    while start < bytes.len() && bytes[start].is_ascii_whitespace() {
1978        start += 1;
1979    }
1980    let line_start = src[..start].rfind('\n').map_or(0, |i| i + 1);
1981    let indent: String = src[line_start..start]
1982        .chars()
1983        .take_while(|c| c.is_whitespace())
1984        .collect();
1985    Some(psync_check::Fix {
1986        file: file.display().to_string(),
1987        offset: start,
1988        insert: format!("#[psync::seq]\n{indent}"),
1989    })
1990}
1991
1992/// `/abs/path/file.rs:line:column` of a span's start (column counted in characters, from 1), the
1993/// key the macro computes from its tokens' spans.
1994fn site_key(tcx: TyCtxt<'_>, span: Span) -> Option<String> {
1995    let loc = tcx.sess.source_map().lookup_char_pos(span.lo());
1996    let rustc_span::FileName::Real(real) = &loc.file.name else {
1997        return None;
1998    };
1999    let path = real.local_path()?;
2000    let path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
2001    Some(format!("{}:{}:{}", path.display(), loc.line, loc.col.0 + 1))
2002}
2003
2004/// Calls that panic on purpose: `panic!`, `assert!`, `unreachable!`, `todo!`, `unwrap`, `expect`.
2005fn panicking(krate: &str, path: &str, name: &str) -> bool {
2006    if !OPAQUE_STD.contains(&krate) {
2007        return false;
2008    }
2009    path.contains("::panicking::")
2010        || matches!(
2011            name,
2012            "begin_panic" | "panic_fmt" | "panic_display" | "assert_failed"
2013        )
2014        || ((path.contains("Option") || path.contains("Result"))
2015            && matches!(name, "unwrap" | "expect" | "unwrap_err" | "expect_err"))
2016}
2017
2018/// Whether calling `def_id` returns a future: an `async fn`, or a function or method returning
2019/// `impl Future`, `Pin<Box<dyn Future>>` or a named future type. Like the macro, the driver reads
2020/// verbs only on awaited calls: `HashMap::insert` and `Serializer::append_pair` are not I/O.
2021fn returns_future(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2022    if !matches!(tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn) {
2023        return false;
2024    }
2025    if tcx.asyncness(def_id).is_async() {
2026        return true;
2027    }
2028    let output = tcx.fn_sig(def_id).skip_binder().output().skip_binder();
2029    let shown = format!("{output:?}");
2030    shown.contains("Future") || shown.contains("Fut") || {
2031        // `impl Future` and named futures: ask whether the type implements `Future`.
2032        let future = tcx.lang_items().future_trait();
2033        future.is_some_and(|trait_id| {
2034            tcx.explicit_item_bounds(match output.kind() {
2035                ty::Alias(_, alias) => match alias.kind {
2036                    ty::AliasTyKind::Opaque { def_id } => def_id,
2037                    _ => return false,
2038                },
2039                _ => return false,
2040            })
2041            .skip_binder()
2042            .iter()
2043            .any(|(clause, _)| {
2044                clause
2045                    .as_trait_clause()
2046                    .is_some_and(|t| t.def_id() == trait_id)
2047            })
2048        })
2049    }
2050}
2051
2052/// Whether `def_id` is defined in a crate from crates.io or a git dependency, rather than in the
2053/// user's workspace or a path dependency.
2054fn is_registry(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
2055    let file = tcx.sess.source_map().span_to_filename(tcx.def_span(def_id));
2056    let name = format!("{file:?}");
2057    name.contains("/.cargo/registry/") || name.contains("/.cargo/git/")
2058}
2059
2060/// Glue that is neither I/O nor an API call: conversions, builders, iterators, formatting.
2061fn is_plumbing(name: &str) -> bool {
2062    matches!(
2063        name,
2064        "new"
2065            | "from"
2066            | "into"
2067            | "default"
2068            | "clone"
2069            | "build"
2070            | "with"
2071            | "map"
2072            | "and_then"
2073            | "unwrap"
2074            | "expect"
2075            | "as_ref"
2076            | "as_mut"
2077            | "deref"
2078            | "deref_mut"
2079            | "drop"
2080            | "fmt"
2081            | "eq"
2082            | "ne"
2083            | "cmp"
2084            | "partial_cmp"
2085            | "hash"
2086            | "poll"
2087            | "into_future"
2088            | "call"
2089            | "call_mut"
2090            | "call_once"
2091            | "branch"
2092            | "from_residual"
2093            | "next"
2094            | "into_iter"
2095    ) || name.starts_with("with_")
2096        || name.starts_with("to_")
2097        || name.starts_with("as_")
2098        || name.starts_with("into_")
2099        || name.starts_with("from_")
2100}
2101
2102/// Methods of the I/O traits (`AsyncWrite`/`AsyncWriteExt`, `io::Write`, `AsyncRead`, `io::Read`)
2103/// on a writer or reader that is not an in-memory buffer: a write or read of that object, named
2104/// by its type. Files are classified by [`io_effect`].
2105fn io_trait_effect(path: &str, name: &str, self_ty: Option<&str>) -> Option<(Domain, Access)> {
2106    let ty = self_ty?;
2107    let in_memory = [
2108        "Vec<",
2109        "Cursor<",
2110        "String",
2111        "Sink",
2112        "Empty",
2113        "&mut [u8]",
2114        "[u8]",
2115        "Repeat",
2116    ]
2117    .iter()
2118    .any(|m| ty.contains(m));
2119    if in_memory || ty.contains("fs::File") {
2120        return None;
2121    }
2122    let writes = (path.contains("AsyncWrite") || path.contains("io::Write"))
2123        && [
2124            "write",
2125            "flush",
2126            "shutdown",
2127            "poll_write",
2128            "poll_flush",
2129            "poll_shutdown",
2130        ]
2131        .iter()
2132        .any(|p| name.starts_with(p));
2133    let reads =
2134        (path.contains("AsyncRead") || path.contains("io::Read") || path.contains("BufRead"))
2135            && (name.starts_with("read")
2136                || name.starts_with("poll_read")
2137                || name.starts_with("fill_buf"));
2138    let domain = || Domain::Service(format!("io {ty}"));
2139    match (writes, reads) {
2140        (true, _) => Some((domain(), Access::Write)),
2141        (false, true) => Some((domain(), Access::Read)),
2142        _ => None,
2143    }
2144}
2145
2146/// File operations on two paths, which write the second: the access to the first.
2147fn two_path_fs(name: &str) -> Option<Access> {
2148    match name {
2149        "copy" => Some(Access::Read),
2150        "rename" | "hard_link" | "symlink" | "soft_link" | "symlink_file" | "symlink_dir" => {
2151            Some(Access::Write)
2152        }
2153        _ => None,
2154    }
2155}
2156
2157/// File, socket, process, environment and output operations of std and the async runtimes,
2158/// recognized by path: `(domain, access, whether the first argument is the target)`.
2159fn io_effect(path: &str, name: &str) -> Option<(Domain, Access, bool)> {
2160    // File operations: free functions of an `fs` module, and methods of open files, directory
2161    // builders and directory listings. `Metadata`, `Permissions` and `FileType` are plain values.
2162    let segments: Vec<&str> = path.split("::").collect();
2163    let free_fs_fn = segments.len() >= 2 && segments[segments.len() - 2] == "fs";
2164    let handle = ["File", "OpenOptions", "DirBuilder", "ReadDir", "DirEntry"]
2165        .iter()
2166        .any(|t| path.contains(&format!("fs::{t}")));
2167    if free_fs_fn || handle {
2168        if matches!(
2169            name,
2170            "new"
2171                | "options"
2172                | "file_name"
2173                | "path"
2174                | "file_type"
2175                | "try_clone"
2176                | "lock"
2177                | "unlock"
2178                | "try_lock"
2179        ) {
2180            return None;
2181        }
2182        // Moving the cursor changes no file content.
2183        if name.starts_with("seek") || matches!(name, "rewind" | "stream_position") {
2184            return Some((Domain::Fs, Access::Read, false));
2185        }
2186        let reads = psync_graph::fs_reads(name)
2187            || name.starts_with("read")
2188            || name.starts_with("metadata")
2189            || name == "exists"
2190            || name == "try_exists"
2191            || name == "next"
2192            || name == "next_entry";
2193        let access = if path.contains("OpenOptions") && name == "open" {
2194            // Unknown flags: may create or truncate.
2195            Access::Write
2196        } else if reads {
2197            Access::Read
2198        } else {
2199            Access::Write
2200        };
2201        // Free functions and constructors name the file in their first argument; methods of an
2202        // open file act on that file, whatever their argument.
2203        let named = free_fs_fn || matches!(name, "open" | "create" | "create_new");
2204        return Some((Domain::Fs, access, named));
2205    }
2206    if path.contains("::net::") {
2207        let writes = name.starts_with("send") || name.starts_with("write") || name == "shutdown";
2208        let reads = name.starts_with("recv")
2209            || name.starts_with("read")
2210            || name.starts_with("peek")
2211            || name.starts_with("connect")
2212            || name.starts_with("accept")
2213            || name == "bind";
2214        return match (writes, reads) {
2215            (true, _) => Some((Domain::Net, Access::Write, false)),
2216            (false, true) => Some((Domain::Net, Access::Read, false)),
2217            _ => None,
2218        };
2219    }
2220    if path.contains("process::Command") || path.contains("process::Child") {
2221        return matches!(name, "output" | "status" | "spawn" | "kill" | "wait").then_some((
2222            Domain::Process,
2223            Access::Write,
2224            false,
2225        ));
2226    }
2227    if path.contains("process::exit") || path.contains("process::abort") {
2228        return Some((Domain::Process, Access::Write, false));
2229    }
2230    if path.contains("::env::") {
2231        return match name {
2232            "set_var" | "remove_var" | "set_current_dir" => {
2233                Some((Domain::Env, Access::Write, true))
2234            }
2235            "var" | "var_os" | "vars" | "vars_os" | "current_dir" => {
2236                Some((Domain::Env, Access::Read, true))
2237            }
2238            _ => None,
2239        };
2240    }
2241    if path.ends_with("io::_print") || path.ends_with("io::_eprint") {
2242        return Some((Domain::Output, Access::Ordered, false));
2243    }
2244    None
2245}
2246
2247/// One chain of a concurrent level, as the macro tagged it.
2248struct Chain {
2249    body: DefId,
2250    /// Its first and last statements, in program order within the region.
2251    order: u64,
2252    last: u64,
2253    exits: bool,
2254    /// Its first statement that may exit early (when `exits`).
2255    exit_at: u64,
2256    spec: bool,
2257    indep: bool,
2258    /// A job of synchronous code (`job_at`), not a future: it cannot be dropped halfway.
2259    sync: bool,
2260    span: Span,
2261    /// The chains (by first statement) it waits for at run time when their file paths overlap
2262    /// (`gated_by::<ON>()` in its body).
2263    gated_by: Vec<u64>,
2264}
2265
2266/// A prefetched loop prefix, as the macro tagged it.
2267struct Prefix {
2268    body: DefId,
2269    terminates: bool,
2270    spec: bool,
2271}
2272
2273pub struct Checker<'a, 'tcx> {
2274    pub analyzer: &'a mut Analyzer<'tcx>,
2275    pub findings: CrateFindings,
2276    notes: bool,
2277    deny: bool,
2278}
2279
2280impl<'a, 'tcx> Checker<'a, 'tcx> {
2281    pub fn new(analyzer: &'a mut Analyzer<'tcx>) -> Self {
2282        let tcx = analyzer.tcx;
2283        Self {
2284            analyzer,
2285            findings: CrateFindings {
2286                crate_name: tcx.crate_name(LOCAL_CRATE).to_string(),
2287                ..Default::default()
2288            },
2289            notes: std::env::var(env::NOTES).is_ok_and(|v| v == "1"),
2290            deny: std::env::var(env::DENY).is_ok_and(|v| v == "1"),
2291        }
2292    }
2293
2294    /// Check every rewritten function of the crate.
2295    pub fn run(&mut self) {
2296        let tcx = self.analyzer.tcx;
2297        let owners: Vec<LocalDefId> = tcx.hir_body_owners().collect();
2298        for owner in owners {
2299            let def_id = owner.to_def_id();
2300            if !self.analyzer.has_body(def_id) {
2301                continue;
2302            }
2303            let (levels, prefixes) = self.markers(def_id);
2304            if !levels.is_empty() || !prefixes.is_empty() {
2305                let entry = self
2306                    .findings
2307                    .functions
2308                    .entry(display_path(tcx, def_id))
2309                    .or_default();
2310                entry.0 += levels.len();
2311                entry.1 += prefixes.len();
2312            }
2313            for (_, chains) in levels {
2314                self.findings.checked_levels += 1;
2315                self.check_level(def_id, &chains);
2316            }
2317            for prefix in prefixes {
2318                self.findings.checked_loops += 1;
2319                self.check_prefix(def_id, &prefix);
2320            }
2321        }
2322    }
2323
2324    /// The tagged levels and loop prefixes in one body.
2325    fn markers(&self, def_id: DefId) -> (Vec<(u64, Vec<Chain>)>, Vec<Prefix>) {
2326        markers(self.analyzer.tcx, def_id)
2327    }
2328}
2329
2330/// What the macro made concurrent in one body, read back from its markers: each join's chains
2331/// (`maybe_done_at`, `job_at`), by level, and each prefetched loop prefix (`over_at`).
2332fn markers(tcx: TyCtxt<'_>, def_id: DefId) -> (Vec<(u64, Vec<Chain>)>, Vec<Prefix>) {
2333    {
2334        let body = tcx.optimized_mir(def_id);
2335        let mut levels: Vec<(u64, Vec<Chain>)> = Vec::new();
2336        let mut prefixes = Vec::new();
2337        for data in body.basic_blocks.iter() {
2338            let terminator = data.terminator();
2339            let TerminatorKind::Call { func, .. } = &terminator.kind else {
2340                continue;
2341            };
2342            let Some((callee, gargs)) = func.const_fn_def() else {
2343                continue;
2344            };
2345            if tcx.crate_name(callee.krate).as_str() != "psync" {
2346                continue;
2347            }
2348            let name = tcx.item_name(callee);
2349            let span = terminator.source_info.span;
2350            let value = |i: usize| match gargs.const_at(i).kind() {
2351                ty::ConstKind::Value(v) => Some(v),
2352                _ => None,
2353            };
2354            let usize_at = |i: usize| value(i)?.try_to_target_usize(tcx);
2355            let bool_at = |i: usize| value(i)?.try_to_bool();
2356            match name.as_str() {
2357                // A future of an async level, or a job of a synchronous one.
2358                "maybe_done_at" | "job_at" => {
2359                    let (
2360                        Some(level),
2361                        Some(order),
2362                        Some(last),
2363                        Some(exits),
2364                        Some(exit_at),
2365                        Some(spec),
2366                        Some(indep),
2367                    ) = (
2368                        usize_at(0),
2369                        usize_at(1),
2370                        usize_at(2),
2371                        bool_at(3),
2372                        usize_at(4),
2373                        bool_at(5),
2374                        bool_at(6),
2375                    )
2376                    else {
2377                        continue;
2378                    };
2379                    let Some(body) = coroutine_of(gargs.type_at(7)) else {
2380                        continue;
2381                    };
2382                    let gated_by = gated_by_of(tcx, body);
2383                    let chain = Chain {
2384                        gated_by,
2385                        body,
2386                        order,
2387                        last,
2388                        exits,
2389                        exit_at,
2390                        spec,
2391                        indep,
2392                        sync: name.as_str() == "job_at",
2393                        span,
2394                    };
2395                    match levels.iter_mut().find(|(l, _)| *l == level) {
2396                        Some((_, chains)) => chains.push(chain),
2397                        None => levels.push((level, vec![chain])),
2398                    }
2399                }
2400                "over_at" => {
2401                    let (Some(terminates), Some(spec)) = (bool_at(1), bool_at(2)) else {
2402                        continue;
2403                    };
2404                    let Some(body) = coroutine_of(gargs.type_at(5)) else {
2405                        continue;
2406                    };
2407                    prefixes.push(Prefix {
2408                        body,
2409                        terminates,
2410                        spec,
2411                    });
2412                }
2413                _ => {}
2414            }
2415        }
2416        for (_, chains) in &mut levels {
2417            chains.sort_by_key(|c| c.order);
2418        }
2419        (levels, prefixes)
2420    }
2421}
2422
2423impl<'a, 'tcx> Checker<'a, 'tcx> {
2424    fn check_level(&mut self, function: DefId, chains: &[Chain]) {
2425        let summaries: Vec<Rc<Summary>> = chains
2426            .iter()
2427            .map(|c| self.analyzer.summarize(c.body))
2428            .collect();
2429        for (j, later) in chains.iter().enumerate() {
2430            for (i, earlier) in chains[..j].iter().enumerate() {
2431                // Two chains touch the same resource, at least one writing.
2432                if !(earlier.indep || later.indep) {
2433                    // A gate orders the pair at run time when the files they name overlap, so
2434                    // the file effects it compares are not a conflict; everything else is.
2435                    let gated = later.gated_by.contains(&earlier.order)
2436                        || earlier.gated_by.contains(&later.order);
2437                    let pair = summaries[i].effects.iter().find_map(|a| {
2438                        summaries[j]
2439                            .effects
2440                            .iter()
2441                            .find(|b| {
2442                                conflict(&a.effect, &b.effect)
2443                                    && !(gated && direct_fs(&a.effect) && direct_fs(&b.effect))
2444                            })
2445                            .map(|b| (a, b))
2446                    });
2447                    if let Some((a, b)) = pair {
2448                        let output = a.effect.domain == Domain::Output;
2449                        self.report(
2450                            if output {
2451                                Severity::Note
2452                            } else {
2453                                Severity::Warning
2454                            },
2455                            if output { "output-order" } else { "conflict" },
2456                            function,
2457                            b.span,
2458                            format!(
2459                                "psync runs this concurrently with other work that has a \
2460                                 conflicting effect: this does `{}` (via {}), the other does `{}` \
2461                                 (via {})",
2462                                b.effect.describe(),
2463                                b.effect.path(),
2464                                a.effect.describe(),
2465                                a.effect.path()
2466                            ),
2467                            Some((a.span, "the conflicting effect".to_string())),
2468                        );
2469                    }
2470                }
2471            }
2472        }
2473        // A write runs before a statement that may exit, earlier in program order, is known not
2474        // to: sequential code would not have run it. That needs a member of the writing chain
2475        // after the exit (chains are interleaved in program order, so either may come first). A
2476        // panic in a chain's callees (`unwrap`, `expect`, `panic!` in the user's code) is an exit
2477        // too, although the macro's tokens do not show it, from any of its statements.
2478        for (j, later) in chains.iter().enumerate() {
2479            for (i, earlier) in chains.iter().enumerate() {
2480                if i == j {
2481                    continue;
2482                }
2483                let panics = summaries[i].panics;
2484                let leaves_at = match (earlier.exits, panics) {
2485                    (_, true) => earlier.order,
2486                    (true, false) => earlier.exit_at,
2487                    (false, false) => continue,
2488                };
2489                if later.last <= leaves_at {
2490                    continue;
2491                }
2492                let panics = !earlier.exits && panics;
2493                if !later.spec
2494                    && let Some(w) = summaries[j]
2495                        .effects
2496                        .iter()
2497                        .find(|l| l.effect.writes() && l.effect.domain != Domain::Output)
2498                {
2499                    let how = if panics { "may panic" } else { "exits early" };
2500                    self.report(
2501                        Severity::Warning,
2502                        "speculative-write",
2503                        function,
2504                        w.span,
2505                        format!(
2506                            "psync starts this before knowing whether an earlier statement {how}, \
2507                             and it does `{}` (via {}); sequential code would not have done it \
2508                             after that exit. Mark it `#[psync::speculate]` if that is harmless, \
2509                             or `#[psync::seq]`",
2510                            w.effect.describe(),
2511                            w.effect.path()
2512                        ),
2513                        Some((
2514                            user_span(self.analyzer.tcx, earlier.body).unwrap_or(earlier.span),
2515                            "the earlier work that may exit".to_string(),
2516                        )),
2517                    );
2518                }
2519            }
2520        }
2521        self.check_interior(function, chains);
2522        // Cancellation: dropping the function's future mid-join interrupts every chain at once.
2523        let writers: Vec<usize> = summaries
2524            .iter()
2525            .enumerate()
2526            .filter(|(_, s)| {
2527                s.effects
2528                    .iter()
2529                    .any(|l| l.effect.writes() && l.effect.domain != Domain::Output)
2530            })
2531            .map(|(k, _)| k)
2532            .collect();
2533        // A synchronous function is not cancelled: its jobs run to the end.
2534        if writers.len() >= 2 && !chains.iter().all(|c| c.sync) {
2535            let tcx = self.analyzer.tcx;
2536            let span = |k: usize| user_span(tcx, chains[k].body).unwrap_or(chains[k].span);
2537            self.report(
2538                Severity::Note,
2539                "cancellation",
2540                function,
2541                span(writers[1]),
2542                format!(
2543                    "psync runs {} chains that write concurrently: if this function's future is \
2544                     dropped (a timeout, `select!`), each may stop halfway, where sequential code \
2545                     had at most one write in progress",
2546                    writers.len()
2547                ),
2548                Some((span(writers[0]), "another chain that writes".to_string())),
2549            );
2550        }
2551    }
2552
2553    fn check_prefix(&mut self, function: DefId, prefix: &Prefix) {
2554        if !prefix.terminates || prefix.spec {
2555            return;
2556        }
2557        let summary = self.analyzer.summarize(prefix.body);
2558        if let Some(w) = summary
2559            .effects
2560            .iter()
2561            .find(|l| l.effect.writes() && l.effect.domain != Domain::Output)
2562        {
2563            let tcx = self.analyzer.tcx;
2564            let primary = if w.span.from_expansion() {
2565                user_span(tcx, prefix.body).unwrap_or(w.span)
2566            } else {
2567                w.span
2568            };
2569            self.report(
2570                Severity::Warning,
2571                "loop-speculative-write",
2572                function,
2573                primary,
2574                format!(
2575                    "psync runs this loop's prefix for every item before the loop body runs, \
2576                     and the body can end the loop early, but the prefix does `{}` (via {}). \
2577                     Sequential code would not do it for items after the exit. Mark the loop \
2578                     `#[psync::speculate]` if that is harmless",
2579                    w.effect.describe(),
2580                    w.effect.path()
2581                ),
2582                None,
2583            );
2584        }
2585    }
2586
2587    /// Two chains that share a `Cell`, `RefCell`, `Mutex` or atomic interleave their updates.
2588    fn check_interior(&mut self, function: DefId, chains: &[Chain]) {
2589        let tcx = self.analyzer.tcx;
2590        let mut seen: HashMap<rustc_hir::HirId, (usize, Span)> = HashMap::new();
2591        for (k, chain) in chains.iter().enumerate() {
2592            let Some(local) = chain.body.as_local() else {
2593                continue;
2594            };
2595            for captured in tcx.closure_captures(local) {
2596                let var = captured.get_root_variable();
2597                let ty = captured.place.ty();
2598                let Some(kind) = interior_kind(tcx, ty) else {
2599                    continue;
2600                };
2601                match seen.get(&var) {
2602                    Some((other, other_span)) if *other != k => {
2603                        let name = tcx.hir_name(var);
2604                        let other_span = *other_span;
2605                        self.report(
2606                            Severity::Note,
2607                            "interior-mutability",
2608                            function,
2609                            captured.get_path_span(tcx),
2610                            format!(
2611                                "psync runs concurrent chains that both use `{name}`, a `{kind}`: their reads and \
2612                                 updates now interleave instead of happening in program order"
2613                            ),
2614                            Some((other_span, "also used here".to_string())),
2615                        );
2616                    }
2617                    Some(_) => {}
2618                    None => {
2619                        seen.insert(var, (k, captured.get_path_span(tcx)));
2620                    }
2621                }
2622            }
2623        }
2624    }
2625
2626    fn report(
2627        &mut self,
2628        severity: Severity,
2629        kind: &str,
2630        function: DefId,
2631        span: Span,
2632        message: String,
2633        secondary: Option<(Span, String)>,
2634    ) {
2635        if severity == Severity::Note && !self.notes {
2636            return;
2637        }
2638        let tcx = self.analyzer.tcx;
2639        let dcx = tcx.dcx();
2640        let mut diag = match severity {
2641            Severity::Warning if self.deny => dcx.struct_span_err(span, message.clone()),
2642            Severity::Warning => dcx.struct_span_warn(span, message.clone()),
2643            Severity::Note => dcx.struct_span_note(span, message.clone()),
2644        };
2645        if let Some((s, label)) = &secondary {
2646            diag.span_note(*s, label.clone());
2647        }
2648        diag.note(format!(
2649            "in the code `#[psync::graph]` generated for `{}`",
2650            display_path(tcx, function)
2651        ));
2652        diag.emit();
2653        let location = tcx.sess.source_map().span_to_diagnostic_string(span);
2654        let fix = (severity == Severity::Warning)
2655            .then(|| seq_fix(tcx, span, kind == "loop-speculative-write"))
2656            .flatten();
2657        self.findings.findings.push(Finding {
2658            severity,
2659            kind: kind.to_string(),
2660            message,
2661            location,
2662            function: display_path(tcx, function),
2663            fix,
2664        });
2665    }
2666
2667    pub fn write_findings(&self) {
2668        let Some(dir) = std::env::var_os(env::FINDINGS).map(PathBuf::from) else {
2669            return;
2670        };
2671        let file = dir.join(format!("{}.json", self.findings.crate_name));
2672        // A crate with nothing concurrent left must not keep findings from an earlier run.
2673        if self.findings.checked_levels == 0 && self.findings.checked_loops == 0 {
2674            let _ = std::fs::remove_file(file);
2675            return;
2676        }
2677        let _ = std::fs::create_dir_all(&dir);
2678        if let Ok(json) = serde_json::to_string_pretty(&self.findings) {
2679            let _ = std::fs::write(file, json);
2680        }
2681    }
2682}
2683
2684/// The body of an `async` block or async closure passed to a marker.
2685/// The `ON` of every `psync::__private::gated_by::<ON>()` call in a chain's body.
2686fn gated_by_of(tcx: TyCtxt<'_>, body: DefId) -> Vec<u64> {
2687    if !tcx.is_mir_available(body) {
2688        return Vec::new();
2689    }
2690    let mir = tcx.optimized_mir(body);
2691    mir.basic_blocks
2692        .iter()
2693        .filter_map(|data| {
2694            let TerminatorKind::Call { func, .. } = &data.terminator().kind else {
2695                return None;
2696            };
2697            let (callee, gargs) = func.const_fn_def()?;
2698            (tcx.crate_name(callee.krate).as_str() == "psync"
2699                && tcx.item_name(callee).as_str() == "gated_by")
2700                .then_some(())?;
2701            match gargs.const_at(0).kind() {
2702                ty::ConstKind::Value(v) => v.try_to_target_usize(tcx),
2703                _ => None,
2704            }
2705        })
2706        .collect()
2707}
2708
2709/// A file effect made by a call into a `fs` module from the chain itself (`fs::write(dst, ..)`,
2710/// `tokio::fs::read(src)`): what the macro saw in the tokens and compares at run time for a gate.
2711/// An effect reached through another function (a helper writing some other file) is not.
2712fn direct_fs(effect: &Effect) -> bool {
2713    effect.domain == Domain::Fs
2714        && effect
2715            .via
2716            .first()
2717            .is_some_and(|f| f.rsplit("::").nth(1) == Some("fs"))
2718}
2719
2720fn coroutine_of(ty: Ty<'_>) -> Option<DefId> {
2721    match ty.kind() {
2722        ty::Coroutine(def_id, _) | ty::CoroutineClosure(def_id, _) | ty::Closure(def_id, _) => {
2723            Some(*def_id)
2724        }
2725        _ => None,
2726    }
2727}
2728
2729/// `Some("RefCell")` when `ty`, behind references and shared pointers, is a cell, lock or atomic.
2730fn interior_kind<'tcx>(tcx: TyCtxt<'tcx>, mut ty: Ty<'tcx>) -> Option<String> {
2731    loop {
2732        match ty.kind() {
2733            ty::Ref(_, inner, _) => ty = *inner,
2734            ty::Adt(def, args) => {
2735                let path = tcx.def_path_str(def.did());
2736                let last = path.rsplit("::").next().unwrap_or(&path).to_string();
2737                if matches!(last.as_str(), "Rc" | "Arc" | "Box") && !args.is_empty() {
2738                    ty = args.type_at(0);
2739                    continue;
2740                }
2741                let interior = matches!(
2742                    last.as_str(),
2743                    "Cell" | "RefCell" | "OnceCell" | "UnsafeCell" | "Mutex" | "RwLock"
2744                ) || last.starts_with("Atomic");
2745                return interior.then_some(last);
2746            }
2747            _ => return None,
2748        }
2749    }
2750}
2751
2752/// The outermost `select!`-like macro (the names of `AWAITING_MACROS` in psync-graph's classify.rs) whose
2753/// expansion wrote `span`, with the span of its call.
2754fn awaiting_macro(mut span: Span) -> Option<(String, Span)> {
2755    const NAMES: &[&str] = &["select", "select_biased", "join", "try_join"];
2756    let mut found = None;
2757    for _ in 0..64 {
2758        let data = span.ctxt().outer_expn_data();
2759        if data.is_root() {
2760            break;
2761        }
2762        if let rustc_span::ExpnKind::Macro(rustc_span::MacroKind::Bang, name) = data.kind
2763            && NAMES.contains(&name.as_str())
2764        {
2765            found = Some((name.to_string(), data.call_site));
2766        }
2767        span = data.call_site;
2768    }
2769    found
2770}