Skip to main content

psync_check/
lib.rs

1//! `cargo psync check`: verifies `#[psync::graph]` rewrites against the compiled bodies of callees.
2//!
3//! `#[psync::graph]` sees only the tokens of the function it rewrites. It judges every call by its
4//! name: `api.get(..)` reads, `store.put(..)` writes, `do_work(x)` is unknown. `cargo psync check`
5//! runs the compiler with a custom driver (`psync-driver`, like `clippy-driver`) that sees the
6//! program after type checking, as MIR:
7//!
8//! 1. **Summaries.** For every function of every crate in the build, the driver computes which
9//!    effects on the outside world the function performs: file reads and writes (`std::fs`,
10//!    `tokio::fs`, ...), sockets, processes, environment variables, and calls into other crates'
11//!    APIs, classified by their verbs (`delete`, `list`, ...). Calls are resolved exactly (trait
12//!    methods to their impls), callees in the same crate are followed into their bodies, and
13//!    summaries of dependencies are read from files the driver wrote when it compiled them.
14//! 2. **Checks.** In every function `#[psync::graph]` rewrote, the generated code marks each
15//!    concurrent level and each prefetched loop (`maybe_done_at`, `over_at`) with what the macro
16//!    assumed. The driver compares those assumptions with the summaries and warns where the
17//!    rewrite runs two conflicting effects at once, performs a write before an earlier exit, or
18//!    shares interior-mutable state between concurrent chains.
19//!
20//! This library holds the parts shared by the driver and the `cargo psync` front end: the effect
21//! model, summary files and findings. It does not link the compiler.
22
23use serde::{Deserialize, Serialize};
24use std::collections::BTreeMap;
25use std::path::Path;
26
27/// Where an effect lands.
28#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
29pub enum Domain {
30    /// The file system.
31    Fs,
32    /// Sockets used directly (`std::net`, `tokio::net`).
33    Net,
34    /// Environment variables and the working directory.
35    Env,
36    /// A child process: it may touch anything.
37    Process,
38    /// Standard output and error: the order of writes is visible.
39    Output,
40    /// Another crate's API, named by the type or module it belongs to (`kube::Api::<K>`).
41    Service(String),
42}
43
44/// How an effect touches its domain.
45#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
46pub enum Access {
47    Read,
48    Write,
49    /// A write whose order relative to others on the same domain is visible (`send`, `append`).
50    Ordered,
51}
52
53/// One effect of a function, with the calls through which it happens.
54#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
55pub struct Effect {
56    pub domain: Domain,
57    pub access: Access,
58    /// A constant target (a file path or key), when the call's argument is a string literal.
59    pub target: Option<String>,
60    /// Without a constant target: the target is the value of this parameter of the summarized
61    /// function (`fs::write(path, ..)` in `fn save(path: &Path, ..)` writes parameter 0). A caller
62    /// replaces it by what it passes there (its own parameter, a constant, or anything).
63    #[serde(default, skip_serializing_if = "Option::is_none")]
64    pub arg: Option<usize>,
65    /// The call chain from the summarized function to the operation, outermost first.
66    pub via: Vec<String>,
67}
68
69impl Effect {
70    pub fn writes(&self) -> bool {
71        self.access != Access::Read
72    }
73
74    /// `write file "cfg.toml"` / `read kube::Api::<K>`.
75    pub fn describe(&self) -> String {
76        let access = match self.access {
77            Access::Read => "read",
78            Access::Write => "write",
79            Access::Ordered => "ordered write",
80        };
81        let domain = match &self.domain {
82            Domain::Fs => "file".to_string(),
83            Domain::Net => "socket".to_string(),
84            Domain::Env => "environment".to_string(),
85            Domain::Process => "process".to_string(),
86            Domain::Output => "standard output".to_string(),
87            Domain::Service(s) => format!("`{s}`"),
88        };
89        match &self.target {
90            Some(t) => format!("{access} {domain} {t:?}"),
91            None => format!("{access} {domain}"),
92        }
93    }
94
95    /// `helper -> std::fs::write`.
96    pub fn path(&self) -> String {
97        self.via.join(" -> ")
98    }
99}
100
101/// Whether two effects may not run concurrently: one writes, they may reach the same resource,
102/// and their targets may be the same (or both are ordered writes on one domain).
103pub fn conflict(a: &Effect, b: &Effect) -> bool {
104    if !(a.writes() || b.writes()) {
105        return false;
106    }
107    let same_domain = match (&a.domain, &b.domain) {
108        // A child process cannot change this process's environment, but may touch anything else.
109        (Domain::Process, Domain::Env) | (Domain::Env, Domain::Process) => {
110            return a.domain == Domain::Env && a.writes() || b.domain == Domain::Env && b.writes();
111        }
112        (Domain::Process, _) | (_, Domain::Process) => return true,
113        (x, y) => x == y,
114    };
115    if !same_domain {
116        return false;
117    }
118    if a.access == Access::Ordered && b.access == Access::Ordered {
119        return true;
120    }
121    match (&a.target, &b.target) {
122        (Some(x), Some(y)) if a.domain == Domain::Fs => paths_overlap(x, y),
123        (Some(x), Some(y)) => x == y,
124        _ => true,
125    }
126}
127
128/// Equal paths, or one is a directory containing the other.
129pub fn paths_overlap(a: &str, b: &str) -> bool {
130    let (a, b) = (a.trim_end_matches('/'), b.trim_end_matches('/'));
131    a == b
132        || b.strip_prefix(a).is_some_and(|r| r.starts_with('/'))
133        || a.strip_prefix(b).is_some_and(|r| r.starts_with('/'))
134}
135
136/// The summary of one function, as stored for other crates.
137#[derive(Clone, Debug, Default, Serialize, Deserialize)]
138pub struct FnSummary {
139    /// The function's path, for people.
140    pub path: String,
141    pub effects: Vec<Effect>,
142    /// Calls the driver could not see through (function pointers, `dyn` methods without a
143    /// verb, other crates' functions without a summary).
144    pub opaque: Vec<String>,
145    /// It may panic explicitly (`unwrap`, `expect`, `panic!`, `assert!`) in the user's code,
146    /// directly or through the user's own functions.
147    #[serde(default)]
148    pub panics: bool,
149    /// Trait methods it calls through `dyn` or an unresolved generic, by key: their effects
150    /// are the union over every implementation in the build, resolved by [`link`].
151    #[serde(default)]
152    pub deferred: Vec<String>,
153}
154
155/// What one call in a `#[psync::graph]` function does, for the macro.
156#[derive(Clone, Debug, Default, Serialize, Deserialize)]
157pub struct CallFact {
158    /// The callee's path, as resolved by the compiler.
159    pub callee: String,
160    /// The callee's name as written at the call site, to detect stale facts.
161    pub name: String,
162    pub effects: Vec<Effect>,
163    pub panics: bool,
164    pub deferred: Vec<String>,
165    /// Some of its callees could not be seen through.
166    pub opaque: bool,
167}
168
169/// Every summary of one crate, keyed by the stable hash of each function's definition path.
170#[derive(Clone, Debug, Default, Serialize, Deserialize)]
171pub struct CrateSummaries {
172    pub crate_name: String,
173    /// The compiler's stable id of the crate: a function of a summarized crate that is missing
174    /// from `functions` has no effects.
175    #[serde(default)]
176    pub crate_id: String,
177    pub functions: BTreeMap<String, FnSummary>,
178    /// Trait method key -> keys of this crate's methods implementing it.
179    #[serde(default)]
180    pub impls: BTreeMap<String, Vec<String>>,
181    /// Call sites in `#[psync::graph]` functions, by `file:line:column` of the callee's name.
182    #[serde(default)]
183    pub calls: BTreeMap<String, CallFact>,
184}
185
186/// The effects of a deferred trait method: the union over its implementations in the build.
187#[derive(Clone, Debug, Default, Serialize, Deserialize)]
188pub struct Resolved {
189    pub effects: Vec<Effect>,
190    pub panics: bool,
191    /// Implementations found.
192    pub impls: usize,
193}
194
195/// Link-time resolution of `dyn` and generic trait calls over the whole build (closed world):
196/// every deferred trait method's effects are the union of its implementations' effects, and
197/// of what those call through `dyn` in turn.
198pub fn link(crates: &[CrateSummaries]) -> BTreeMap<String, Resolved> {
199    let mut functions: BTreeMap<&str, &FnSummary> = BTreeMap::new();
200    let mut impls: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
201    for c in crates {
202        for (k, f) in &c.functions {
203            functions.insert(k, f);
204        }
205        for (t, is) in &c.impls {
206            impls
207                .entry(t)
208                .or_default()
209                .extend(is.iter().map(String::as_str));
210        }
211    }
212    let mut out: BTreeMap<String, Resolved> = BTreeMap::new();
213    let mut traits: Vec<&str> = impls.keys().copied().collect();
214    for f in functions.values() {
215        traits.extend(f.deferred.iter().map(String::as_str));
216    }
217    traits.sort();
218    traits.dedup();
219    for t in traits {
220        let mut resolved = Resolved::default();
221        let mut stack = vec![t];
222        let mut seen = std::collections::BTreeSet::new();
223        while let Some(t) = stack.pop() {
224            if !seen.insert(t) {
225                continue;
226            }
227            for i in impls.get(t).into_iter().flatten() {
228                resolved.impls += 1;
229                // An implementation without a summary has no effects (summaries omit those).
230                let Some(f) = functions.get(i) else { continue };
231                resolved.panics |= f.panics;
232                for e in &f.effects {
233                    // A parameter of the implementation, not of the call site: unknown here.
234                    let e = Effect {
235                        arg: None,
236                        ..e.clone()
237                    };
238                    if !resolved.effects.iter().any(|x| same_effect(x, &e)) {
239                        resolved.effects.push(e);
240                    }
241                }
242                stack.extend(f.deferred.iter().map(String::as_str));
243            }
244        }
245        out.insert(t.to_string(), resolved);
246    }
247    out
248}
249
250fn same_effect(a: &Effect, b: &Effect) -> bool {
251    a.domain == b.domain && a.access == b.access && a.target == b.target && a.arg == b.arg
252}
253
254/// The final effects of a call site: its own, and those of the trait methods it reaches
255/// through `dyn`.
256pub fn resolve_call(
257    fact: &CallFact,
258    linked: &BTreeMap<String, Resolved>,
259) -> (Vec<Effect>, bool, bool) {
260    let mut effects = fact.effects.clone();
261    let mut panics = fact.panics;
262    let mut opaque = fact.opaque;
263    for t in &fact.deferred {
264        // No implementation in the build: one may exist outside it.
265        opaque |= linked.get(t).is_none_or(|r| r.impls == 0);
266        if let Some(r) = linked.get(t) {
267            panics |= r.panics;
268            for e in &r.effects {
269                let e = &Effect {
270                    arg: None,
271                    ..e.clone()
272                };
273                if !effects.iter().any(|x| same_effect(x, e)) {
274                    let mut e = e.clone();
275                    e.via.insert(0, fact.callee.clone());
276                    effects.push(e);
277                }
278            }
279        }
280    }
281    (effects, panics, opaque)
282}
283
284/// The facts file the macro reads (`PSYNC_FACTS`): one call site per line,
285/// `site \t name \t panics \t opaque \t effects` (`opaque`: some callee could not be seen through), effects separated by `\x1e`, each
286/// `domain \x1f access \x1f target`. Domains: `fs`, `net`, `env`, `process`, `output`,
287/// `svc:<owner>`; accesses `r`, `w`, `o`. A line-based format keeps the macro free of a JSON
288/// dependency.
289pub fn facts_text(crates: &[CrateSummaries], linked: &BTreeMap<String, Resolved>) -> String {
290    // One site can be compiled more than once (a crate built with two feature sets): merge the
291    // facts conservatively.
292    let mut merged: BTreeMap<&str, (&CallFact, Vec<Effect>, bool, bool)> = BTreeMap::new();
293    for c in crates {
294        for (site, fact) in &c.calls {
295            let (effects, panics, opaque) = resolve_call(fact, linked);
296            let entry = merged
297                .entry(site)
298                .or_insert_with(|| (fact, Vec::new(), false, false));
299            for e in effects {
300                if !entry.1.iter().any(|x| same_effect(x, &e)) {
301                    entry.1.push(e);
302                }
303            }
304            entry.2 |= panics;
305            entry.3 |= opaque;
306        }
307    }
308    let mut out = String::new();
309    {
310        for (site, (fact, effects, panics, opaque)) in merged {
311            let (effects, panics, opaque) = (effects, panics, opaque);
312            let effects: Vec<String> = effects
313                .iter()
314                .map(|e| {
315                    let domain = match &e.domain {
316                        Domain::Fs => "fs".to_string(),
317                        Domain::Net => "net".to_string(),
318                        Domain::Env => "env".to_string(),
319                        Domain::Process => "process".to_string(),
320                        Domain::Output => "output".to_string(),
321                        Domain::Service(s) => format!("svc:{s}"),
322                    };
323                    let access = match e.access {
324                        Access::Read => "r",
325                        Access::Write => "w",
326                        Access::Ordered => "o",
327                    };
328                    // A fourth field: the target is the call's argument `j` (0 is the receiver of
329                    // a method call).
330                    let arg = e.arg.map(|j| format!("\x1f{j}")).unwrap_or_default();
331                    format!(
332                        "{domain}\x1f{access}\x1f{}{arg}",
333                        e.target.as_deref().unwrap_or("")
334                    )
335                })
336                .collect();
337            out += &format!(
338                "{site}\t{}\t{}\t{}\t{}\n",
339                fact.name,
340                u8::from(panics),
341                u8::from(opaque),
342                effects.join("\x1e")
343            );
344        }
345    }
346    out
347}
348
349/// How serious a finding is.
350#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
351pub enum Severity {
352    /// The rewrite changes what the program does to the outside world.
353    Warning,
354    /// The order of visible output, or of operations behind interior mutability, may change.
355    Note,
356}
357
358/// One problem found in a rewritten function.
359#[derive(Clone, Debug, Serialize, Deserialize)]
360pub struct Finding {
361    pub severity: Severity,
362    /// `conflict`, `speculative-write`, `loop-speculative-write`, `interior-mutability`,
363    /// `output-order`, `cancellation`.
364    pub kind: String,
365    pub message: String,
366    /// `file:line:column` of the primary location.
367    pub location: String,
368    /// The function the rewritten code is in.
369    pub function: String,
370    /// A machine-applicable fix: text to insert at a byte offset of a file (`cargo psync fix`).
371    #[serde(default)]
372    pub fix: Option<Fix>,
373}
374
375/// An insertion that fixes a finding: `#[psync::seq]` before the statement or loop.
376#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
377pub struct Fix {
378    pub file: String,
379    pub offset: usize,
380    pub insert: String,
381}
382
383/// The findings of one crate, as written by the driver.
384#[derive(Clone, Debug, Default, Serialize, Deserialize)]
385pub struct CrateFindings {
386    pub crate_name: String,
387    pub checked_levels: usize,
388    pub checked_loops: usize,
389    /// Per rewritten function: `(concurrent levels, prefetched loops)`.
390    #[serde(default)]
391    pub functions: BTreeMap<String, (usize, usize)>,
392    pub findings: Vec<Finding>,
393}
394
395/// Read every `*.json` file in `dir` as `T`, skipping files that do not parse.
396pub fn read_all<T: for<'de> Deserialize<'de>>(dir: &Path) -> Vec<T> {
397    let Ok(entries) = std::fs::read_dir(dir) else {
398        return Vec::new();
399    };
400    let mut out = Vec::new();
401    for entry in entries.flatten() {
402        let path = entry.path();
403        if path.extension().is_some_and(|e| e == "json")
404            && let Ok(text) = std::fs::read_to_string(&path)
405            && let Ok(value) = serde_json::from_str(&text)
406        {
407            out.push(value);
408        }
409    }
410    out
411}
412
413/// Environment variables the front end passes to the driver.
414pub mod pdg;
415
416pub mod env {
417    /// Directory of per-crate summary files.
418    pub const SUMMARIES: &str = "PSYNC_SUMMARY_DIR";
419    /// Directory of per-crate findings files.
420    pub const FINDINGS: &str = "PSYNC_FINDINGS_DIR";
421    /// Set to `1` to make findings errors.
422    pub const DENY: &str = "PSYNC_CHECK_DENY";
423    /// Set to `1` to also report notes (output order, interior mutability).
424    pub const NOTES: &str = "PSYNC_CHECK_NOTES";
425    /// The linked resolution of deferred trait methods (`linked.json`), when a previous run
426    /// produced one: the driver then checks `dyn` calls against every implementation.
427    pub const LINKED: &str = "PSYNC_LINKED";
428    /// Read by the macro: the facts file to schedule with.
429    pub const FACTS: &str = "PSYNC_FACTS";
430    /// Read by the macro (through `option_env!`, so cargo rebuilds when it changes): a hash of
431    /// the facts file.
432    pub const FACTS_STAMP: &str = "PSYNC_FACTS_STAMP";
433}
434
435#[cfg(test)]
436mod tests {
437    use super::*;
438
439    fn fx(domain: Domain, access: Access, target: Option<&str>) -> Effect {
440        Effect {
441            domain,
442            access,
443            target: target.map(Into::into),
444            via: vec![],
445            arg: None,
446        }
447    }
448
449    #[test]
450    fn conflicts() {
451        let w = fx(Domain::Fs, Access::Write, Some("out/a"));
452        assert!(conflict(&w, &fx(Domain::Fs, Access::Read, Some("out"))));
453        assert!(!conflict(&w, &fx(Domain::Fs, Access::Read, Some("other"))));
454        assert!(conflict(&w, &fx(Domain::Fs, Access::Read, None)));
455        assert!(!conflict(
456            &fx(Domain::Fs, Access::Read, None),
457            &fx(Domain::Fs, Access::Read, None)
458        ));
459        assert!(conflict(&fx(Domain::Process, Access::Write, None), &w));
460        let api = |a| fx(Domain::Service("kube::Api".into()), a, None);
461        assert!(conflict(&api(Access::Write), &api(Access::Read)));
462        assert!(!conflict(
463            &api(Access::Write),
464            &fx(Domain::Service("s3".into()), Access::Write, None)
465        ));
466    }
467}