Skip to main content

psync_graph/
access.rs

1//! Token-level read/write analysis.
2//!
3//! Without type information, the analysis approximates what a statement touches from its tokens:
4//! every identifier it mentions, and every *access path* (`x`, `self.groups`, `conn.inner`) it
5//! reads or writes. A path is written by assignment, `&mut path`, a mutating method call on a
6//! `mut` binding or `&mut` handle, or an order-sensitive call (`send`, `write`, `recv`, ...) on any
7//! receiver. Two statements conflict when one writes a path that overlaps a path the other touches.
8
9use proc_macro2::{Delimiter, Spacing, TokenStream, TokenTree};
10use std::collections::BTreeSet;
11
12/// A set of identifier names or dotted access paths.
13pub(crate) type Set = BTreeSet<String>;
14
15/// What one statement touches.
16#[derive(Default, Clone, Debug)]
17pub(crate) struct Access {
18    /// Every variable-like identifier mentioned (drives def-use edges).
19    pub uses: Set,
20    /// Root identifiers of written paths.
21    pub writes: Set,
22    /// Access paths read, such as `self.client`.
23    pub rpaths: Set,
24    /// Access paths written, such as `self.groups`.
25    pub wpaths: Set,
26}
27
28/// Keywords and names that never denote a variable.
29const KEYWORDS: &[&str] = &[
30    "let", "mut", "await", "match", "if", "else", "fn", "move", "async", "as", "in", "for",
31    "while", "loop", "return", "break", "continue", "true", "false", "ref", "where", "impl", "dyn",
32    "unsafe", "struct", "enum", "type", "use", "crate", "super", "Self",
33];
34
35// ANCHOR: pure-methods
36/// Methods assumed not to mutate their receiver.
37pub(crate) const PURE_METHODS: &[&str] = &[
38    "clone",
39    "to_string",
40    "to_owned",
41    "into",
42    "as_ref",
43    "as_str",
44    "as_slice",
45    "len",
46    "is_empty",
47    "unwrap_or",
48    "unwrap_or_default",
49    "as_deref",
50    "iter",
51    "to_vec",
52    "copied",
53    "cloned",
54    "is_some",
55    "is_none",
56];
57// ANCHOR_END: pure-methods
58
59// ANCHOR: read-prefixes
60/// Prefixes of further read-only method names (`is_*`, `get*`, `as_*`, ...).
61const READ_PREFIXES: &[&str] = &[
62    "is_",
63    "has_",
64    "get",
65    "as_",
66    "to_",
67    "contains",
68    "len",
69    "iter",
70    "keys",
71    "values",
72    "first",
73    "last",
74    "count",
75    "unwrap",
76    "expect",
77    "starts_with",
78    "ends_with",
79    "clone",
80    "map",
81    "ok",
82    "err",
83    "list",
84    "fetch",
85    "find",
86    "load",
87    "query",
88    "lookup",
89    "describe",
90    "stat",
91    "head",
92    "exists",
93    "search",
94    "resolve",
95    "download",
96    "retrieve",
97];
98// ANCHOR_END: read-prefixes
99
100// ANCHOR: ordered-methods
101/// Calls whose relative order is observable even through `&self`: channel, stream and I/O
102/// operations on one receiver must stay in program order.
103const ORDERED_METHODS: &[&str] = &[
104    "send",
105    "send_all",
106    "try_send",
107    "recv",
108    "try_recv",
109    "next",
110    "try_next",
111    "feed",
112    "write",
113    "write_all",
114    "flush",
115    "read_exact",
116    "read_to_end",
117    "read_to_string",
118    "shutdown",
119    "close",
120    "execute",
121    "commit",
122    "rollback",
123];
124// ANCHOR_END: ordered-methods
125
126/// True when `method` is assumed not to mutate its receiver.
127fn reads_only(method: &str) -> bool {
128    PURE_METHODS.contains(&method) || READ_PREFIXES.iter().any(|p| method.starts_with(p))
129}
130
131/// True when two access paths overlap: equal, or one is a field prefix of the other.
132pub(crate) fn overlaps(a: &str, b: &str) -> bool {
133    let (short, long) = if a.len() <= b.len() { (a, b) } else { (b, a) };
134    long == short || long.starts_with(short) && long[short.len()..].starts_with('.')
135}
136
137/// The first path in `writes` that overlaps a path in `other`.
138pub(crate) fn conflict(writes: &Set, other: &Set) -> Option<String> {
139    writes
140        .iter()
141        .find(|w| other.iter().any(|o| overlaps(w, o)))
142        .cloned()
143}
144
145/// The identifier a dotted path starts from.
146pub(crate) fn root(path: &str) -> &str {
147    path.split('.').next().unwrap_or_default()
148}
149
150fn is_punct(tt: Option<&TokenTree>, c: char) -> bool {
151    matches!(tt, Some(TokenTree::Punct(p)) if p.as_char() == c)
152}
153
154/// Record what `tokens` touch into `acc`.
155///
156/// `mutable` holds `mut` bindings and `handles` holds bindings to `&mut` values (including
157/// `&mut self`): method calls on them are writes unless the method looks read-only, and a handle
158/// passed along whole may be used for anything.
159pub(crate) fn scan(tokens: TokenStream, mutable: &Set, handles: &Set, acc: &mut Access) {
160    let tts: Vec<TokenTree> = tokens.into_iter().collect();
161    for (i, tt) in tts.iter().enumerate() {
162        match tt {
163            // `#[attr(..)]` contents are not code.
164            TokenTree::Group(g)
165                if g.delimiter() == Delimiter::Bracket
166                    && i > 0
167                    && is_punct(tts.get(i - 1), '#') => {}
168            TokenTree::Group(g) => scan(g.stream(), mutable, handles, acc),
169            // `format!("{name}")` captures `name` implicitly.
170            TokenTree::Literal(lit) => {
171                for name in format_captures(&lit.to_string()) {
172                    acc.rpaths.insert(name.clone());
173                    acc.uses.insert(name);
174                }
175            }
176            TokenTree::Ident(id) => {
177                let name = id.to_string();
178                // `.field` and `.method` are not variables; `..x` (range, struct update) is.
179                let after_dot = i > 0
180                    && is_punct(tts.get(i - 1), '.')
181                    && !(i > 1 && is_punct(tts.get(i - 2), '.'));
182                // `Type::item` and `module::item` name items, not variables.
183                let path_prefix = is_punct(tts.get(i + 1), ':') && is_punct(tts.get(i + 2), ':');
184                let lifetime = i > 0 && is_punct(tts.get(i - 1), '\'');
185                if after_dot || path_prefix || lifetime || KEYWORDS.contains(&name.as_str()) {
186                    continue;
187                }
188                acc.uses.insert(name.clone());
189
190                // Follow `.field` and `[index]` to the place being accessed.
191                let mut path = name.clone();
192                let mut j = i + 1;
193                loop {
194                    match tts.get(j) {
195                        Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Bracket => j += 1,
196                        Some(TokenTree::Punct(p))
197                            if p.as_char() == '.' && !is_punct(tts.get(j + 1), '.') =>
198                        {
199                            let Some(TokenTree::Ident(field)) = tts.get(j + 1) else {
200                                break;
201                            };
202                            let call = matches!(tts.get(j + 2), Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Parenthesis)
203                                || is_punct(tts.get(j + 2), ':');
204                            if call || field == "await" {
205                                break;
206                            }
207                            path = format!("{path}.{field}");
208                            j += 2;
209                        }
210                        _ => break,
211                    }
212                }
213                let method = match (tts.get(j), tts.get(j + 1)) {
214                    (Some(TokenTree::Punct(p)), Some(TokenTree::Ident(m)))
215                        if p.as_char() == '.' && m != "await" =>
216                    {
217                        Some(m.to_string())
218                    }
219                    _ => None,
220                };
221
222                // Write forms: `&mut path`, `path = ..` / `path += ..`, mutating method calls.
223                let amp_mut = i >= 2
224                    && matches!(&tts[i - 1], TokenTree::Ident(m) if m == "mut")
225                    && is_punct(tts.get(i - 2), '&');
226                let mut op = String::new();
227                let mut k = j;
228                while let Some(TokenTree::Punct(p)) = tts.get(k) {
229                    op.push(p.as_char());
230                    k += 1;
231                    if p.spacing() == Spacing::Alone {
232                        break;
233                    }
234                }
235                // `let x = ..` and `let mut x = ..` introduce a binding; they do not write one.
236                let binding = (i >= 1 && matches!(&tts[i - 1], TokenTree::Ident(k) if k == "let"))
237                    || (i >= 2
238                        && matches!(&tts[i - 1], TokenTree::Ident(m) if m == "mut")
239                        && matches!(&tts[i - 2], TokenTree::Ident(k) if k == "let"));
240                // `let x: u32 = ..`: the type of an annotation is not assigned.
241                let annotation = i >= 1
242                    && is_punct(tts.get(i - 1), ':')
243                    && !(i >= 2 && is_punct(tts.get(i - 2), ':'));
244                let assign = !binding
245                    && !annotation
246                    && method.is_none()
247                    && op.ends_with('=')
248                    && !matches!(op.as_str(), "==" | "<=" | ">=" | "!=" | "=>");
249                let mut_root = mutable.contains(&name) || handles.contains(&name);
250                let mutating_call = method
251                    .as_deref()
252                    .is_some_and(|m| ORDERED_METHODS.contains(&m) || (mut_root && !reads_only(m)));
253                let handle_passed = handles.contains(&name) && path == name && method.is_none();
254
255                // `&mut x.f()` borrows the call's result, not `x`.
256                let amp_mut = amp_mut && method.is_none();
257                acc.rpaths.insert(path.clone());
258                if amp_mut || assign || mutating_call || handle_passed {
259                    acc.wpaths.insert(path);
260                    acc.writes.insert(name);
261                }
262            }
263            _ => {}
264        }
265    }
266}
267
268/// Names captured by `{name}` / `{name:spec}` in a string literal (format-string arguments).
269fn format_captures(literal: &str) -> Vec<String> {
270    if !literal.ends_with('"') {
271        return Vec::new();
272    }
273    let mut out = Vec::new();
274    let mut rest = literal;
275    while let Some(open) = rest.find('{') {
276        rest = &rest[open + 1..];
277        if rest.starts_with('{') {
278            rest = &rest[1..];
279            continue;
280        }
281        let name: String = rest
282            .chars()
283            .take_while(|c| c.is_alphanumeric() || *c == '_')
284            .collect();
285        if name.starts_with(|c: char| c.is_alphabetic() || c == '_')
286            && rest[name.len()..].starts_with(['}', ':'])
287        {
288            out.push(name);
289        }
290    }
291    out
292}
293
294/// Identifiers mentioned by `tokens`, ignoring mutability.
295pub(crate) fn mentions(tokens: TokenStream) -> Set {
296    let mut acc = Access::default();
297    scan(tokens, &Set::new(), &Set::new(), &mut acc);
298    acc.uses
299}
300
301#[cfg(test)]
302mod tests {
303    use super::*;
304    use quote::quote;
305
306    fn access(tokens: TokenStream, mutable: &[&str]) -> Access {
307        let mutable = mutable.iter().map(|s| s.to_string()).collect();
308        let mut acc = Access::default();
309        scan(tokens, &mutable, &Set::new(), &mut acc);
310        acc
311    }
312
313    #[test]
314    fn fields_are_tracked_separately() {
315        let acc = access(
316            quote!(self.groups.insert(k, query(&self.client, g).await)),
317            &["self"],
318        );
319        assert!(acc.wpaths.contains("self.groups"));
320        assert!(acc.rpaths.contains("self.client"));
321        assert!(conflict(&acc.wpaths, &["self.client".to_string()].into()).is_none());
322        assert!(overlaps("self", "self.groups") && !overlaps("self.group", "self.groups"));
323    }
324
325    #[test]
326    fn format_strings_capture_names() {
327        assert_eq!(format_captures(r#""{a} {b:?} {{c}} {0} {}""#), ["a", "b"]);
328        assert!(access(quote!(format!("{file}")), &[]).uses.contains("file"));
329    }
330
331    #[test]
332    fn assignment_and_ordered_calls_write() {
333        let acc = access(
334            quote!({
335                total += x;
336                tx.send(v).await;
337            }),
338            &[],
339        );
340        assert!(acc.wpaths.contains("total") && acc.wpaths.contains("tx"));
341        assert!(!acc.wpaths.contains("x"));
342        assert!(access(quote!(a == b), &[]).wpaths.is_empty());
343    }
344}