Skip to main content

cargo_psync/
cargo-psync.rs

1//! `cargo psync`: the front end of psync's compiler-level checks.
2//!
3//! ```text
4//! cargo psync check [--deny] [--notes] [CARGO CHECK ARGS...]
5//! cargo psync build [--deny] [--notes] [CARGO BUILD ARGS...]
6//! cargo psync summaries [CRATE] [--all]
7//! cargo psync pdg [FUNCTION] [--entries] [--from HANDLER]
8//! ```
9//!
10//! `check` runs `cargo check` with `psync-driver` as `RUSTC_WRAPPER`, in its own target directory
11//! (`target/psync`), so the normal build is untouched. Every crate in the build gets effect
12//! summaries; crates with `#[psync::graph]` rewrites are checked against them.
13//! After every check, a link step resolves `dyn` and generic trait calls over the whole build and
14//! writes the facts the macro can schedule with; `build` does that, checks the schedule the macro
15//! builds from the facts, and runs `cargo build` with them.
16//! `summaries` prints the summaries the last `check` computed, and `pdg` the dependence graphs of
17//! the annotated functions and `async fn`s: their effects and awaits, each with the branches that
18//! decide whether it runs.
19
20use psync_check::{CrateFindings, CrateSummaries, Severity, env};
21use std::path::{Path, PathBuf};
22use std::process::{Command, ExitCode};
23
24const USAGE: &str = "\
25cargo psync: check #[psync::graph] rewrites against the compiled bodies of callees
26
27USAGE:
28    cargo psync check [--deny] [--notes] [--facts] [CARGO CHECK ARGS...]
29    cargo psync build [--deny] [--notes] [CARGO BUILD ARGS...]
30    cargo psync fix [CARGO CHECK ARGS...]
31    cargo psync summaries [CRATE] [--all]
32    cargo psync pdg [FUNCTION] [--entries] [--from HANDLER]
33
34check       run `cargo check` with psync's driver; warn where a rewrite runs conflicting
35            effects at once, writes before an earlier exit, or prefetches loop writes
36  --deny    make findings errors (exit status 1)
37  --notes   also report output order and shared interior-mutable state
38  --facts   then also check the schedule the macro builds from the compiler's facts
39build       compute the compiler's facts about every call in #[psync::graph] functions, let the
40            macro schedule with them (instead of judging calls by their names), check that
41            schedule, then `cargo build` with it
42fix         check, then insert `#[psync::seq]` before every statement or loop with a warning
43            (review the result: `#[psync::speculate]` may be the better hint for idempotent writes)
44pdg         print, for each #[psync::graph] function and `async fn` the last `check` saw, its
45            calls with effects and its awaits, each with the branches it depends on
46  FUNCTION  only functions whose path contains this text
47  --entries list the entry points instead: `main` and the handlers registered with axum or
48            actix-web, with their routes
49  --from H  the graph of handler H (a path, as --entries prints it) and of every function of
50            the crate it calls, transitively: what one request runs
51summaries   print each function's effects as computed by the last `check`
52  CRATE     only this crate (default: every crate with findings or rewrites)
53  --all     include functions without effects but with opaque calls
54";
55
56fn main() -> ExitCode {
57    // `cargo psync ...` runs `cargo-psync psync ...`.
58    let mut args: Vec<String> = std::env::args().skip(1).collect();
59    if args.first().is_some_and(|a| a == "psync") {
60        args.remove(0);
61    }
62    match args.first().map(String::as_str) {
63        Some("check") => check(&args[1..]),
64        Some("build") => build(&args[1..]),
65        Some("fix") => fix(&args[1..]),
66        Some("summaries") => summaries(&args[1..]),
67        Some("pdg") => pdg(&args[1..]),
68        Some("-h" | "--help") | None => {
69            print!("{USAGE}");
70            ExitCode::SUCCESS
71        }
72        Some(other) => {
73            eprintln!("cargo psync: unknown command `{other}`\n\n{USAGE}");
74            ExitCode::from(2)
75        }
76    }
77}
78
79/// `target/psync` under the project's target directory.
80fn psync_dir() -> PathBuf {
81    let target = std::env::var_os("CARGO_TARGET_DIR")
82        .map(PathBuf::from)
83        .or_else(target_dir_from_metadata)
84        .unwrap_or_else(|| PathBuf::from("target"));
85    target.join("psync")
86}
87
88fn target_dir_from_metadata() -> Option<PathBuf> {
89    let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".into());
90    let out = Command::new(cargo)
91        .args(["metadata", "--no-deps", "--format-version", "1"])
92        .output()
93        .ok()?;
94    let value: serde_json::Value = serde_json::from_slice(&out.stdout).ok()?;
95    value["target_directory"].as_str().map(PathBuf::from)
96}
97
98/// Options shared by `check` and `build`.
99struct Opts<'a> {
100    deny: bool,
101    notes: bool,
102    /// `check --facts`: also check the schedule the macro builds from the compiler's facts.
103    facts: bool,
104    passthrough: Vec<&'a String>,
105}
106
107fn opts(args: &[String]) -> Opts<'_> {
108    Opts {
109        deny: args.iter().any(|a| a == "--deny"),
110        notes: args.iter().any(|a| a == "--notes"),
111        facts: args.iter().any(|a| a == "--facts"),
112        passthrough: args
113            .iter()
114            .filter(|a| !matches!(a.as_str(), "--deny" | "--notes" | "--facts"))
115            .collect(),
116    }
117}
118
119/// A stable short hash of a file's contents (empty file: `none`).
120fn stamp(path: &Path) -> String {
121    use std::hash::{Hash, Hasher};
122    let Ok(bytes) = std::fs::read(path) else {
123        return "none".into();
124    };
125    let mut h = std::collections::hash_map::DefaultHasher::new();
126    bytes.hash(&mut h);
127    format!("{:016x}", h.finish())
128}
129
130/// One `cargo check` with the driver. `facts` makes the macro schedule with the compiler's facts.
131fn pass(opts: &Opts<'_>, dir: &Path, facts: bool) -> Result<bool, ExitCode> {
132    let driver = std::env::current_exe()
133        .ok()
134        .map(|exe| exe.with_file_name("psync-driver"))
135        .filter(|p| p.exists());
136    let Some(driver) = driver else {
137        eprintln!("cargo psync: `psync-driver` must be installed next to `cargo-psync`");
138        return Err(ExitCode::from(2));
139    };
140    // Findings persist across runs, one file per crate: cargo does not re-run the driver for a
141    // crate it considers unchanged, and that crate's findings must still count (a second
142    // `check`, `fix` or `--deny` would otherwise see none). The driver rewrites or removes a
143    // crate's file whenever it checks the crate.
144    let findings_dir = dir.join("findings");
145    let lib = Path::new(env!("PSYNC_SYSROOT")).join("lib");
146    // The driver links the toolchain's `librustc_driver`. On NixOS, the libraries that library
147    // needs (zlib) come from nix-ld's path, which only binaries using nix-ld's loader see.
148    let mut paths = vec![lib];
149    for var in ["LD_LIBRARY_PATH", "NIX_LD_LIBRARY_PATH"] {
150        if let Some(old) = std::env::var_os(var) {
151            paths.extend(std::env::split_paths(&old));
152        }
153    }
154    let library_path = std::env::join_paths(paths).expect("library path");
155    let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".into());
156    let linked = dir.join("linked.json");
157    let mut command = Command::new(cargo);
158    command
159        .arg("check")
160        .args(&opts.passthrough)
161        .env("RUSTC_WRAPPER", &driver)
162        .env("CARGO_TARGET_DIR", dir)
163        .env("LD_LIBRARY_PATH", &library_path)
164        .env("DYLD_FALLBACK_LIBRARY_PATH", &library_path)
165        .env(env::SUMMARIES, dir.join("summaries"))
166        .env(env::FINDINGS, &findings_dir)
167        .env(env::LINKED, &linked)
168        .env("PSYNC_LINKED_STAMP", stamp(&linked))
169        .env(env::DENY, if opts.deny { "1" } else { "0" })
170        .env(env::NOTES, if opts.notes { "1" } else { "0" });
171    if facts {
172        let file = dir.join("facts.tsv");
173        command
174            .env(env::FACTS, &file)
175            .env(env::FACTS_STAMP, stamp(&file));
176    } else {
177        command.env_remove(env::FACTS).env(env::FACTS_STAMP, "none");
178    }
179    match command.status() {
180        Ok(s) => Ok(s.success()),
181        Err(e) => {
182            eprintln!("cargo psync: could not run cargo: {e}");
183            Err(ExitCode::from(2))
184        }
185    }
186}
187
188/// Link every crate's summaries: resolve `dyn` and generic trait calls over the whole build and
189/// write `linked.json` (for the driver) and `facts.tsv` (for the macro). Returns whether the
190/// resolution changed since the last run.
191fn link(dir: &Path) -> bool {
192    let crates: Vec<CrateSummaries> = psync_check::read_all(&dir.join("summaries"));
193    let linked = psync_check::link(&crates);
194    let linked_file = dir.join("linked.json");
195    let before = stamp(&linked_file);
196    let _ = std::fs::write(
197        &linked_file,
198        serde_json::to_string(&linked).unwrap_or_default(),
199    );
200    let _ = std::fs::write(
201        dir.join("facts.tsv"),
202        psync_check::facts_text(&crates, &linked),
203    );
204    stamp(&linked_file) != before
205}
206
207/// Print the findings of the last pass; returns the number of warnings.
208fn report(dir: &Path, label: &str) -> usize {
209    let crates: Vec<CrateFindings> = psync_check::read_all(&dir.join("findings"));
210    let (levels, loops): (usize, usize) = crates.iter().fold((0, 0), |(l, p), c| {
211        (l + c.checked_levels, p + c.checked_loops)
212    });
213    let count = |sev| {
214        crates
215            .iter()
216            .flat_map(|c| &c.findings)
217            .filter(|f| f.severity == sev)
218            .count()
219    };
220    let (warnings, notes) = (count(Severity::Warning), count(Severity::Note));
221    eprintln!(
222        "psync {label}: {levels} concurrent level(s) and {loops} prefetched loop(s) checked in {} \
223         crate(s): {warnings} warning(s), {notes} note(s){}",
224        crates.len(),
225        if crates.is_empty() {
226            " (no `#[psync::graph]` code made anything concurrent)"
227        } else {
228            ""
229        }
230    );
231    warnings
232}
233
234/// Check, link, and check again if linking resolved new `dyn` calls (the driver recompiles the
235/// workspace's crates when `linked.json` changes).
236fn check_and_link(opts: &Opts<'_>, dir: &Path) -> Result<bool, ExitCode> {
237    let mut ok = pass(opts, dir, false)?;
238    if link(dir) && ok {
239        ok = pass(opts, dir, false)?;
240        link(dir);
241    }
242    Ok(ok)
243}
244
245fn check(args: &[String]) -> ExitCode {
246    let opts = opts(args);
247    let dir = psync_dir();
248    let mut ok = match check_and_link(&opts, &dir) {
249        Ok(ok) => ok,
250        Err(code) => return code,
251    };
252    let mut warnings = report(&dir, "check");
253    if opts.facts && ok {
254        ok = match pass(&opts, &dir, true) {
255            Ok(ok) => ok,
256            Err(code) => return code,
257        };
258        warnings = report(&dir, "check (with compiler facts)");
259    }
260    if !ok || (opts.deny && warnings > 0) {
261        ExitCode::from(1)
262    } else {
263        ExitCode::SUCCESS
264    }
265}
266
267/// `cargo psync build`: compute the compiler's facts, check the schedule the macro builds from
268/// them, then run the real `cargo build` with them.
269fn build(args: &[String]) -> ExitCode {
270    let opts = opts(args);
271    let dir = psync_dir();
272    match check_and_link(&opts, &dir) {
273        Ok(true) => {}
274        Ok(false) => return ExitCode::from(1),
275        Err(code) => return code,
276    }
277    // Schedule with the facts, and check that schedule.
278    match pass(&opts, &dir, true) {
279        Ok(true) => {}
280        Ok(false) => return ExitCode::from(1),
281        Err(code) => return code,
282    }
283    let warnings = report(&dir, "build (with compiler facts)");
284    if opts.deny && warnings > 0 {
285        return ExitCode::from(1);
286    }
287    let facts = dir.join("facts.tsv");
288    let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".into());
289    let status = Command::new(cargo)
290        .arg("build")
291        .args(&opts.passthrough)
292        .env(env::FACTS, &facts)
293        .env(env::FACTS_STAMP, stamp(&facts))
294        .status();
295    match status {
296        Ok(s) if s.success() => ExitCode::SUCCESS,
297        _ => ExitCode::from(1),
298    }
299}
300
301/// `cargo psync fix`: check, then apply every warning's fix.
302fn fix(args: &[String]) -> ExitCode {
303    let opts = opts(args);
304    let dir = psync_dir();
305    if let Err(code) = check_and_link(&opts, &dir) {
306        return code;
307    }
308    report(&dir, "check");
309    let crates: Vec<CrateFindings> = psync_check::read_all(&dir.join("findings"));
310    let mut fixes: Vec<psync_check::Fix> = crates
311        .iter()
312        .flat_map(|c| &c.findings)
313        .filter_map(|f| f.fix.clone())
314        .collect();
315    fixes.sort_by(|a, b| (&a.file, b.offset).cmp(&(&b.file, a.offset)));
316    fixes.dedup();
317    let mut applied = 0;
318    let mut files: std::collections::BTreeMap<String, String> = Default::default();
319    for f in &fixes {
320        let text = files
321            .entry(f.file.clone())
322            .or_insert_with(|| std::fs::read_to_string(&f.file).unwrap_or_default());
323        // Skip statements already marked.
324        let before = &text[..f.offset.min(text.len())];
325        if before.trim_end().ends_with("#[psync::seq]") || f.offset > text.len() {
326            continue;
327        }
328        text.insert_str(f.offset, &f.insert);
329        applied += 1;
330    }
331    for (file, text) in &files {
332        if let Err(e) = std::fs::write(file, text) {
333            eprintln!("cargo psync: could not write {file}: {e}");
334            return ExitCode::from(1);
335        }
336    }
337    eprintln!(
338        "psync fix: inserted {applied} `#[psync::seq]` hint(s) in {} file(s); run `cargo psync \
339         check` again to confirm",
340        files.len()
341    );
342    ExitCode::SUCCESS
343}
344
345fn summaries(args: &[String]) -> ExitCode {
346    let all = args.iter().any(|a| a == "--all");
347    let wanted = args
348        .iter()
349        .enumerate()
350        .find(|(i, a)| !a.starts_with("--") && (*i == 0 || args[i - 1] != "--from"))
351        .map(|(_, a)| a);
352    let dir = psync_dir();
353    let mut crates: Vec<CrateSummaries> = psync_check::read_all(&dir.join("summaries"));
354    if crates.is_empty() {
355        eprintln!(
356            "cargo psync: no summaries in {}; run `cargo psync check` first",
357            dir.display()
358        );
359        return ExitCode::from(1);
360    }
361    let checked: Vec<String> = psync_check::read_all::<CrateFindings>(&dir.join("findings"))
362        .into_iter()
363        .map(|c| c.crate_name)
364        .collect();
365    crates.sort_by(|a, b| a.crate_name.cmp(&b.crate_name));
366    for krate in crates {
367        let show = match wanted {
368            Some(w) => krate.crate_name == *w || krate.crate_name == w.replace('-', "_"),
369            None => checked.contains(&krate.crate_name),
370        };
371        if !show {
372            continue;
373        }
374        println!("crate {}", krate.crate_name);
375        let mut functions: Vec<_> = krate.functions.into_values().collect();
376        functions.sort_by(|a, b| a.path.cmp(&b.path));
377        for f in functions {
378            if f.effects.is_empty() && !all {
379                continue;
380            }
381            println!("  {}", f.path);
382            for e in &f.effects {
383                println!("    {:<40} via {}", e.describe(), e.path());
384            }
385            if all {
386                for o in &f.opaque {
387                    println!("    opaque: {o}");
388                }
389            }
390        }
391    }
392    ExitCode::SUCCESS
393}
394
395fn pdg(args: &[String]) -> ExitCode {
396    let wanted = args.iter().find(|a| !a.starts_with("--"));
397    let dir = psync_dir();
398    let mut crates: Vec<psync_check::pdg::CratePdg> = psync_check::read_all(&dir.join("pdg"));
399    if crates.is_empty() {
400        eprintln!(
401            "cargo psync: no dependence graphs in {}; run `cargo psync check` first",
402            dir.display()
403        );
404        return ExitCode::from(1);
405    }
406    crates.sort_by(|a, b| a.crate_name.cmp(&b.crate_name));
407    if args.iter().any(|a| a == "--entries") {
408        for krate in &crates {
409            for e in &krate.entries {
410                println!(
411                    "{}: {}",
412                    krate.crate_name,
413                    psync_check::pdg::render_entry(e)
414                );
415            }
416        }
417        return ExitCode::SUCCESS;
418    }
419    if let Some(at) = args.iter().position(|a| a == "--from") {
420        let Some(from) = args.get(at + 1) else {
421            eprintln!("cargo psync pdg: --from needs a handler");
422            return ExitCode::from(2);
423        };
424        // A function's graphs: its own body, and the async block or closure bodies under it.
425        let bodies = |name: &str| -> Vec<&psync_check::pdg::FnPdg> {
426            crates
427                .iter()
428                .flat_map(|k| &k.functions)
429                .filter(|f| f.path == name || f.path.starts_with(&format!("{name}::{{")))
430                .collect()
431        };
432        let mut todo = vec![from.clone()];
433        let mut seen = std::collections::HashSet::new();
434        let mut printed = 0;
435        while let Some(name) = todo.pop() {
436            if !seen.insert(name.clone()) {
437                continue;
438            }
439            for f in bodies(&name) {
440                print!("{}", psync_check::pdg::render(f));
441                printed += 1;
442                for n in f.nodes.iter().filter(|n| n.kind == "call") {
443                    todo.push(n.callee.clone());
444                }
445            }
446        }
447        if printed == 0 {
448            // A known entry with no graph: it neither awaits nor calls anything with effects or
449            // of the crate's own, so a request to it spends no time psync could overlap.
450            if crates
451                .iter()
452                .flat_map(|k| &k.entries)
453                .any(|e| &e.handler == from)
454            {
455                println!(
456                    "{from}: no awaits, no calls with effects, no calls of the crate's own \
457                     functions: nothing to overlap"
458                );
459                return ExitCode::SUCCESS;
460            }
461            eprintln!("cargo psync pdg: no graph for `{from}`; see --entries");
462            return ExitCode::from(1);
463        }
464        return ExitCode::SUCCESS;
465    }
466    for krate in crates {
467        for f in &krate.functions {
468            if wanted.is_some_and(|w| !f.path.contains(w.as_str())) {
469                continue;
470            }
471            print!("{}", psync_check::pdg::render(f));
472        }
473    }
474    ExitCode::SUCCESS
475}