Skip to main content

psync_graph/
facts.rs

1//! Facts from the compiler: what each call in an annotated function really does.
2//!
3//! The macro sees only tokens, so it judges calls by their names ([`crate::effects`]).
4//! `cargo psync build` first runs `psync-driver`, which reads the compiled bodies of every callee
5//! (MIR, across crates, with `dyn` calls resolved over the whole build) and writes one line per
6//! call site of every `#[psync::graph]` function. When the environment variable `PSYNC_FACTS`
7//! names that file, the macro looks each call up by the source location of the callee's name and
8//! schedules with the compiler's answer instead of the name:
9//!
10//! - its effects replace the guessed ones: `factory.create(..)` that only reads is a read, a
11//!   helper named `warm()` that writes `cache.json` is a write to that file;
12//! - a callee that panics on purpose (`unwrap`, `expect`, `panic!`, `assert!`) is an exit, so
13//!   writes after it wait for it.
14//!
15//! A fact is used only if the callee's name at that location still matches, so stale facts (from
16//! before an edit) are ignored rather than misapplied. The generated code reads
17//! `option_env!("PSYNC_FACTS_STAMP")`, which makes cargo rebuild annotated crates when the facts
18//! change.
19
20use crate::effects::{Domain, Effect, Kind, Target};
21use std::collections::HashMap;
22use std::sync::OnceLock;
23
24/// What the compiler found about one call.
25#[derive(Clone, Debug)]
26pub(crate) struct Fact {
27    /// The callee's name as written, to detect stale facts.
28    pub name: String,
29    pub panics: bool,
30    /// Some callee could not be seen through: the effects are a lower bound, so the name's guess
31    /// still applies too.
32    pub opaque: bool,
33    pub effects: Vec<Effect>,
34    /// For each effect: its target is the call's argument `j` (0 is a method's receiver).
35    pub on_arg: Vec<Option<usize>>,
36}
37
38fn table() -> &'static HashMap<String, Fact> {
39    static TABLE: OnceLock<HashMap<String, Fact>> = OnceLock::new();
40    TABLE.get_or_init(|| {
41        std::env::var_os("PSYNC_FACTS")
42            .and_then(|p| std::fs::read_to_string(p).ok())
43            .map(|text| parse(&text))
44            .unwrap_or_default()
45    })
46}
47
48/// Parse the facts file written by `cargo psync` (see `psync_check::facts_text`).
49pub(crate) fn parse(text: &str) -> HashMap<String, Fact> {
50    let mut out = HashMap::new();
51    for line in text.lines() {
52        let mut fields = line.splitn(5, '\t');
53        let (Some(site), Some(name), Some(panics), Some(opaque), effects) = (
54            fields.next(),
55            fields.next(),
56            fields.next(),
57            fields.next(),
58            fields.next(),
59        ) else {
60            continue;
61        };
62        let (effects, on_arg): (Vec<Effect>, Vec<Option<usize>>) = effects
63            .unwrap_or("")
64            .split('\x1e')
65            .filter(|e| !e.is_empty())
66            .filter_map(|e| {
67                let mut parts = e.splitn(4, '\x1f');
68                let (domain, access, target) = (parts.next()?, parts.next()?, parts.next()?);
69                // Malformed, it is ignored: the effect stays, on its target (empty: anything).
70                let arg = parts.next().and_then(|j| j.parse::<usize>().ok());
71                let (domain, ordered_domain) = match domain {
72                    "fs" => (Domain::Fs, false),
73                    "net" => (Domain::Net, false),
74                    "env" => (Domain::Env, false),
75                    "process" => (Domain::Process, false),
76                    "output" => (Domain::Service(Some("type:stdout".into())), true),
77                    svc => (
78                        Domain::Service(Some(format!("type:{}", svc.strip_prefix("svc:")?))),
79                        false,
80                    ),
81                };
82                let (kind, ordered) = match access {
83                    "r" => (Kind::Read, false),
84                    "w" => (Kind::Write, ordered_domain),
85                    "o" => (Kind::Write, true),
86                    _ => return None,
87                };
88                Some((
89                    Effect {
90                        domain,
91                        kind,
92                        target: if target.is_empty() {
93                            Target::Any
94                        } else {
95                            Target::Literal(target.to_string())
96                        },
97                        op: format!("{name}, per the compiler"),
98                        ordered,
99                        source: None,
100                    },
101                    arg,
102                ))
103            })
104            .unzip();
105        let fact = Fact {
106            name: name.to_string(),
107            panics: panics == "1",
108            opaque: opaque == "1",
109            effects,
110            on_arg,
111        };
112        // A site listed twice (two builds of one crate): keep everything either says.
113        match out.get_mut(site) {
114            Some(old) => {
115                let old: &mut Fact = old;
116                old.panics |= fact.panics;
117                old.opaque |= fact.opaque;
118                old.effects.extend(fact.effects);
119                old.on_arg.extend(fact.on_arg);
120            }
121            None => {
122                out.insert(site.to_string(), fact);
123            }
124        }
125    }
126    out
127}
128
129/// The fact for the call whose callee name is `ident` (a method name, or the last segment of a
130/// function path) starting at `span`, if the compiler recorded one there.
131pub(crate) fn at(span: proc_macro2::Span, ident: &str) -> Option<&'static Fact> {
132    let table = table();
133    if table.is_empty() {
134        return None;
135    }
136    let key = site_key(span)?;
137    table.get(&key).filter(|f| f.name == ident)
138}
139
140/// `/abs/path/file.rs:line:column` of a span's start, as the driver writes it. Only available
141/// inside a procedural macro.
142fn site_key(span: proc_macro2::Span) -> Option<String> {
143    if !proc_macro::is_available() {
144        return None;
145    }
146    let span = span.unwrap();
147    let path = span.local_file()?;
148    let path = std::fs::canonicalize(&path).unwrap_or(path);
149    Some(format!(
150        "{}:{}:{}",
151        path.display(),
152        span.line(),
153        span.column()
154    ))
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160
161    /// A fourth field: the effect's target is the call's argument `j`.
162    #[test]
163    fn parses_argument_targets() {
164        let t = parse("/a.rs:3:5\tstash\t0\t0\tfs\x1fw\x1f\x1f0\x1efs\x1fr\x1fa.json\n");
165        let f = &t["/a.rs:3:5"];
166        assert_eq!(f.on_arg, [Some(0), None]);
167        assert!(matches!(&f.effects[1].target, Target::Literal(l) if l == "a.json"));
168        // A malformed argument leaves the effect on anything: never fewer effects.
169        let f = &parse("/a.rs:1:1\tx\t0\t0\tfs\x1fw\x1f\x1fz\n")["/a.rs:1:1"];
170        assert_eq!(f.on_arg, [None]);
171        assert!(matches!(f.effects[0].target, Target::Any));
172    }
173
174    #[test]
175    fn parses_lines() {
176        let text = "/a.rs:3:5\tcreate\t1\t0\tfs\x1fw\x1fcache.json\x1esvc:kube::Api::<K>\x1fr\x1f\n\
177                    garbage\n";
178        let t = parse(text);
179        let f = &t["/a.rs:3:5"];
180        assert_eq!(f.name, "create");
181        assert!(f.panics);
182        assert_eq!(f.effects.len(), 2);
183        assert!(f.effects[0].writes() && f.effects[0].domain == Domain::Fs);
184        assert_eq!(
185            f.effects[1].domain,
186            Domain::Service(Some("type:kube::Api::<K>".into()))
187        );
188    }
189}