1use proc_macro2::{Delimiter, Spacing, TokenStream, TokenTree};
10use std::collections::BTreeSet;
11
12pub(crate) type Set = BTreeSet<String>;
14
15#[derive(Default, Clone, Debug)]
17pub(crate) struct Access {
18 pub uses: Set,
20 pub writes: Set,
22 pub rpaths: Set,
24 pub wpaths: Set,
26}
27
28const 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
35pub(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];
57const 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];
98const 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];
124fn reads_only(method: &str) -> bool {
128 PURE_METHODS.contains(&method) || READ_PREFIXES.iter().any(|p| method.starts_with(p))
129}
130
131pub(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
137pub(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
145pub(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
154pub(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 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 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 let after_dot = i > 0
180 && is_punct(tts.get(i - 1), '.')
181 && !(i > 1 && is_punct(tts.get(i - 2), '.'));
182 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 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 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 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 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 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
268fn 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
294pub(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}