Skip to main content

psync_graph/
effects.rs

1//! Effects on the world outside the function: files, the network, other services, processes and
2//! the environment.
3//!
4//! The access analysis ([`crate::access`]) sees the function's own variables and fields. It cannot
5//! see that `api.delete(name).await` and `api.create(obj).await` touch the same object on a
6//! server, or that `fs::write("a", ..)` and `fs::read("a")` touch the same file: neither statement
7//! writes a variable the other reads. This module gives every statement a list of [`Effect`]s,
8//! each one an operation of some [`Kind`] on a target in a [`Domain`], recognized from the call:
9//!
10//! - **Files**: path-qualified calls into a file-system module (`std::fs::write`,
11//!   `tokio::fs::read_to_string`, `fs::remove_file`), `File::create`/`File::open`, `OpenOptions`.
12//!   The target is the path argument.
13//! - **Network**: `TcpStream::connect`, `UdpSocket::bind`, `send_to`, ... on the `net` types.
14//! - **Processes**: `Command::new`, `process::exit`, `kill`. A child process may touch anything,
15//!   so a process effect conflicts with every other domain.
16//! - **Environment**: `env::set_var`, `env::remove_var`, `set_current_dir` write it; `env::var`
17//!   reads it.
18//! - **Services**: any other awaited call, classified by the verb its name starts with
19//!   (`delete_object`, `create`, `post`, `put`, `upload`, `send` write; `get`, `list`, `head`,
20//!   `fetch` read). The target domain is the receiver (`self.s3`, `api`), and the target is the
21//!   verb's first argument. An awaited free function (`delete_user(id).await`) reaches an unknown
22//!   service, which may be any receiver.
23//!
24//! Two effects **conflict** when one writes, their domains may be the same resource, and their
25//! targets may be the same: two distinct string literals (`"a.toml"`, `"b.toml"`) are known to
26//! differ, and in a loop two targets computed from the loop item are assumed to differ between
27//! iterations (each item names its own object); anything else may be the same. Conflicting
28//! statements keep their order.
29//!
30//! A write is also **irreversible**: psync does not run it ahead of an earlier statement that may
31//! leave the function or loop (`?`, `return`, `break`), because sequential code would then not
32//! have performed it. `#[psync::speculate]` on the statement (or loop, or `speculate` on the
33//! whole function) asserts that running it anyway is harmless, for idempotent operations.
34//!
35//! An awaited call whose name has no known verb (`client.request(req)`, `do_work(x)`) is
36//! *unclassified*. By default it is assumed to read (the behavior before effects existed), and
37//! reported. Under `#[psync::graph(strict)]` it is a write to an unknown resource, which
38//! conflicts with every effect and never runs speculatively.
39
40use crate::access::{Set, mentions, overlaps};
41use proc_macro2::TokenStream;
42use quote::ToTokens;
43use syn::{Expr, spanned::Spanned, visit::Visit};
44
45/// Where an effect lands.
46#[derive(Clone, Debug, PartialEq, Eq)]
47pub(crate) enum Domain {
48    Fs,
49    Net,
50    Env,
51    /// A child process, which may touch any other domain.
52    Process,
53    /// A service reached through a receiver path (`self.client`, `api`); `None` is a service
54    /// reached by a free function, which may be behind any receiver.
55    Service(Option<String>),
56    /// An unclassified call under `strict`: anything.
57    Unknown,
58}
59
60impl Domain {
61    fn may_alias(&self, other: &Domain) -> bool {
62        use Domain::*;
63        match (self, other) {
64            (Process | Unknown, _) | (_, Process | Unknown) => true,
65            (Service(a), Service(b)) => match (a, b) {
66                // A service the compiler named by its type (`type:kube::Api::<K>`) may be behind
67                // any receiver variable; two types are the same service only if equal.
68                (Some(a), Some(b)) if a.starts_with("type:") != b.starts_with("type:") => true,
69                (Some(a), Some(b)) => overlaps(a, b),
70                _ => true,
71            },
72            (a, b) => a == b,
73        }
74    }
75
76    fn name(&self) -> String {
77        match self {
78            Domain::Fs => "file".into(),
79            Domain::Net => "network".into(),
80            Domain::Env => "environment".into(),
81            Domain::Process => "process".into(),
82            Domain::Service(Some(r)) => format!("`{r}`"),
83            Domain::Service(None) => "service".into(),
84            Domain::Unknown => "unknown".into(),
85        }
86    }
87}
88
89#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub(crate) enum Kind {
91    Read,
92    Write,
93}
94
95/// What an effect acts on inside its domain.
96#[derive(Clone, Debug)]
97pub(crate) enum Target {
98    /// A string literal (a file path, a key).
99    Literal(String),
100    /// `format!("prefix{x}..")`: a computed string that starts with known text.
101    Prefixed(String, Set),
102    /// `format!("{dir}/cache.json")`: text with holes, each a plain expression (a name or a
103    /// field), and the names it mentions. Within one region an expression has one value, so two
104    /// templates that agree piece by piece and then differ in their text name different strings.
105    Template(Vec<Piece>, Set),
106    /// A computed value: its tokens and the names it mentions.
107    Expr(String, Set),
108    /// Unknown: the whole domain.
109    Any,
110}
111
112/// One piece of a [`Target::Template`].
113#[derive(Clone, Debug, PartialEq, Eq)]
114pub(crate) enum Piece {
115    Char(char),
116    /// A placeholder: the expression and its format spec (`dir:?`).
117    Hole(String),
118}
119
120/// A template's pieces, ended as a place ends: a file path with `/` (a directory overlaps the
121/// files in it), any other string with an end marker (it overlaps only itself).
122fn ended(pieces: &[Piece], fs: bool) -> Vec<Option<Piece>> {
123    let mut v: Vec<Option<Piece>> = pieces.iter().cloned().map(Some).collect();
124    if fs {
125        while matches!(v.last(), Some(Some(Piece::Char('/')))) {
126            v.pop();
127        }
128        v.push(Some(Piece::Char('/')));
129    } else {
130        v.push(None);
131    }
132    v
133}
134
135/// Two ended templates may name the same string: they agree until one runs out (one is a prefix
136/// of the other), or they first differ where either has a hole (a hole may be any text).
137fn templates_alias(a: &[Option<Piece>], b: &[Option<Piece>]) -> bool {
138    for (x, y) in a.iter().zip(b) {
139        if x != y {
140            return matches!(x, Some(Piece::Hole(_))) || matches!(y, Some(Piece::Hole(_)));
141        }
142    }
143    true
144}
145
146/// `format!("..", args..)` as a template, if every placeholder is a plain expression.
147fn template(tokens: TokenStream) -> Option<Vec<Piece>> {
148    use syn::punctuated::Punctuated;
149    let args =
150        syn::parse::Parser::parse2(Punctuated::<Expr, syn::Token![,]>::parse_terminated, tokens)
151            .ok()?;
152    let mut args = args.into_iter();
153    let Some(Expr::Lit(syn::ExprLit {
154        lit: syn::Lit::Str(text),
155        ..
156    })) = args.next()
157    else {
158        return None;
159    };
160    /// A name or a field path, which has one value within a region.
161    fn plain(e: &Expr) -> Option<String> {
162        match e {
163            Expr::Path(p) if p.qself.is_none() => Some(p.to_token_stream().to_string()),
164            Expr::Field(f) => {
165                plain(&f.base)?;
166                Some(f.to_token_stream().to_string())
167            }
168            Expr::Reference(r) => plain(&r.expr),
169            Expr::Paren(p) => plain(&p.expr),
170            _ => None,
171        }
172    }
173    let (mut positional, mut named) = (Vec::new(), std::collections::HashMap::new());
174    for a in args {
175        match a {
176            Expr::Assign(x) => {
177                let Expr::Path(name) = &*x.left else {
178                    return None;
179                };
180                named.insert(name.to_token_stream().to_string(), plain(&x.right)?);
181            }
182            e => positional.push(plain(&e)?),
183        }
184    }
185    let (mut pieces, mut next) = (Vec::new(), 0usize);
186    let mut chars = text
187        .value()
188        .chars()
189        .collect::<Vec<_>>()
190        .into_iter()
191        .peekable();
192    while let Some(c) = chars.next() {
193        match c {
194            '{' | '}' if chars.peek() == Some(&c) => {
195                chars.next();
196                pieces.push(Piece::Char(c));
197            }
198            '{' => {
199                let inner: String = chars.by_ref().take_while(|&c| c != '}').collect();
200                let (arg, spec) = inner.split_once(':').unwrap_or((&inner, ""));
201                // Widths and precisions taken from arguments are not followed.
202                if spec.contains('$') || spec.contains('*') {
203                    return None;
204                }
205                let expr = if arg.is_empty() {
206                    next += 1;
207                    positional.get(next - 1)?.clone()
208                } else if let Ok(n) = arg.parse::<usize>() {
209                    positional.get(n)?.clone()
210                } else if let Some(e) = named.get(arg) {
211                    e.clone()
212                } else if arg.chars().all(|c| c.is_alphanumeric() || c == '_') {
213                    arg.to_string()
214                } else {
215                    return None;
216                };
217                pieces.push(Piece::Hole(format!("{expr}:{spec}")));
218            }
219            '}' => return None,
220            c => pieces.push(Piece::Char(c)),
221        }
222    }
223    Some(pieces)
224}
225
226impl Target {
227    /// A template as the coarser target it refines: the text before its first hole.
228    fn coarse(&self) -> Target {
229        match self {
230            Target::Template(pieces, names) => {
231                let prefix: String = pieces
232                    .iter()
233                    .map_while(|p| match p {
234                        Piece::Char(c) => Some(*c),
235                        Piece::Hole(_) => None,
236                    })
237                    .collect();
238                if prefix.is_empty() {
239                    Target::Expr(String::new(), names.clone())
240                } else {
241                    Target::Prefixed(prefix, names.clone())
242                }
243            }
244            t => t.clone(),
245        }
246    }
247
248    fn may_alias(&self, other: &Target, fs: bool) -> bool {
249        match (self, other) {
250            (Target::Template(a, _), Target::Template(b, _)) => {
251                return templates_alias(&ended(a, fs), &ended(b, fs));
252            }
253            (Target::Template(..), _) | (_, Target::Template(..)) => {
254                return self.coarse().may_alias(&other.coarse(), fs);
255            }
256            _ => {}
257        }
258        match (self, other) {
259            // Known text that cannot start the same way names different strings.
260            (Target::Prefixed(p, _), Target::Literal(l))
261            | (Target::Literal(l), Target::Prefixed(p, _)) => l.starts_with(p.as_str()),
262            (Target::Prefixed(a, _), Target::Prefixed(b, _)) => {
263                a.starts_with(b.as_str()) || b.starts_with(a.as_str())
264            }
265            (Target::Literal(a), Target::Literal(b)) => {
266                if fs {
267                    let (a, b) = (a.trim_end_matches('/'), b.trim_end_matches('/'));
268                    a == b
269                        || b.starts_with(a) && b[a.len()..].starts_with('/')
270                        || a.starts_with(b) && a[b.len()..].starts_with('/')
271                } else {
272                    a == b
273                }
274            }
275            _ => true,
276        }
277    }
278
279    /// The target as reports show it: `"cfg.toml"`, `` `path` ``, `"out/"…`; empty for any.
280    pub fn shown(&self) -> String {
281        match self {
282            Target::Literal(l) => format!("{l:?}"),
283            Target::Expr(e, _) => format!("`{}`", short(e)),
284            Target::Prefixed(p, _) => format!("{p:?}…"),
285            Target::Template(pieces, _) => {
286                let text: String = pieces
287                    .iter()
288                    .map(|p| match p {
289                        Piece::Char(c) => c.to_string(),
290                        Piece::Hole(h) => format!("{{{}}}", h.trim_end_matches(':')),
291                    })
292                    .collect();
293                format!("{text:?}")
294            }
295            Target::Any => String::new(),
296        }
297    }
298
299    /// The target is computed from one of `names` (per-iteration bindings).
300    pub fn mentions_any(&self, names: &Set) -> bool {
301        matches!(self, Target::Expr(_, m) | Target::Prefixed(_, m) | Target::Template(_, m) if m.iter().any(|n| names.contains(n)))
302    }
303}
304
305/// One operation on the outside world.
306#[derive(Clone, Debug)]
307pub(crate) struct Effect {
308    pub domain: Domain,
309    pub kind: Kind,
310    pub target: Target,
311    /// The call, for reports (`fs::write`, `delete`).
312    pub op: String,
313    /// The order of these operations is observable even on different targets (`send`, `append`,
314    /// `publish`): two of them on one domain never reorder.
315    pub ordered: bool,
316    /// The target's expression as written in the call (a file path), when there is one: the
317    /// runtime check of a loop's targets evaluates it for each item.
318    pub source: Option<String>,
319}
320
321impl Effect {
322    pub fn writes(&self) -> bool {
323        self.kind == Kind::Write
324    }
325
326    /// The place this effect touches, for certificates: `w/<domain>/<target..>`. Places overlap
327    /// by prefix, so where `conflict` is finer than a prefix (string-prefix and computed targets,
328    /// services named by type, ordered writes that conflict on any target), the place is cut
329    /// short, which only adds conflicts.
330    pub fn place(&self) -> Vec<String> {
331        let mut place = vec!["w".to_string()];
332        let svc = |r: &str| -> Vec<String> {
333            let mut v = vec!["svc".to_string()];
334            if !r.starts_with("type:") {
335                v.extend(r.split('.').map(str::to_string));
336            }
337            v
338        };
339        match &self.domain {
340            Domain::Process | Domain::Unknown => return place,
341            Domain::Fs => place.push("fs".into()),
342            Domain::Net => place.push("net".into()),
343            Domain::Env => place.push("env".into()),
344            // A service reached by a free function (`redis::cmd(..)`) may be behind any
345            // receiver: a hole where the receiver goes, which overlaps every receiver, and then
346            // its target as usual, so two different keys still differ.
347            Domain::Service(None) => {
348                place.push("svc".into());
349                place.push("$hole:receiver".into());
350            }
351            Domain::Service(Some(r)) => {
352                // A service is the receiver; a typed service may be behind any receiver.
353                place.extend(svc(r));
354                if r.starts_with("type:") {
355                    return place;
356                }
357            }
358        }
359        if self.ordered {
360            return place;
361        }
362        // Targets as characters, so that a prefix of the place is a prefix of the string: a
363        // literal ends with a marker (two different literals never overlap), a `format!` prefix
364        // has none (it overlaps every string that starts with it), and a file path ends with `/`
365        // (a directory overlaps the files in it).
366        let chars = |t: &str| t.chars().map(String::from).collect::<Vec<_>>();
367        match &self.target {
368            Target::Literal(l) if self.domain == Domain::Fs => {
369                place.push("t".into());
370                place.extend(chars(&format!("{}/", l.trim_end_matches('/'))));
371            }
372            Target::Literal(l) => {
373                place.push("t".into());
374                place.extend(chars(l));
375                place.push("$end".into());
376            }
377            Target::Prefixed(p, _) => {
378                place.push("t".into());
379                place.extend(chars(p));
380            }
381            // Holes are marked, for the checker: places that first differ at a hole overlap.
382            Target::Template(pieces, _) => {
383                place.push("t".into());
384                for p in ended(pieces, self.domain == Domain::Fs) {
385                    place.push(match p {
386                        Some(Piece::Char(c)) => c.to_string(),
387                        Some(Piece::Hole(h)) => format!("$hole:{h}"),
388                        None => "$end".into(),
389                    });
390                }
391            }
392            Target::Expr(..) | Target::Any => {}
393        }
394        place
395    }
396
397    /// For reports: `write file "cfg.toml" (fs::write)`.
398    pub fn describe(&self) -> String {
399        let kind = match self.kind {
400            Kind::Read => "read",
401            Kind::Write => "write",
402        };
403        let target = match self.target.shown() {
404            t if t.is_empty() => t,
405            t => format!(" {t}"),
406        };
407        format!("{kind} {}{target} ({})", self.domain.name(), self.op)
408    }
409}
410
411fn short(s: &str) -> String {
412    match s.char_indices().nth(30) {
413        Some((cut, _)) => format!("{}…", &s[..cut]),
414        None => s.to_string(),
415    }
416}
417
418/// Why two effects conflict, if they do.
419pub(crate) fn conflict(a: &Effect, b: &Effect) -> Option<String> {
420    if !(a.writes() || b.writes()) || !a.domain.may_alias(&b.domain) {
421        return None;
422    }
423    // File paths, and URLs of HTTP requests (`world.md`'s HTTP specification: paths commute
424    // only when neither is a prefix of the other), compare as paths.
425    let http = |e: &Effect| e.op.starts_with("HTTP ");
426    let fs = (a.domain == Domain::Fs && b.domain == Domain::Fs) || http(a) || http(b);
427    // A process or unknown call may touch any target; ordered operations conflict on any target.
428    let anything = |d: &Domain| matches!(d, Domain::Process | Domain::Unknown);
429    let ordered = a.ordered && b.ordered;
430    if !ordered
431        && !anything(&a.domain)
432        && !anything(&b.domain)
433        && !a.target.may_alias(&b.target, fs)
434    {
435        return None;
436    }
437    let (w, o) = if a.writes() { (a, b) } else { (b, a) };
438    Some(format!("{} vs {}", w.describe(), o.describe()))
439}
440
441/// The first conflict between two effect lists.
442pub(crate) fn conflicts(a: &[Effect], b: &[Effect]) -> Option<String> {
443    a.iter().find_map(|x| b.iter().find_map(|y| conflict(x, y)))
444}
445
446/// Function-wide settings from `#[psync::graph(..)]`.
447#[derive(Clone, Debug, Default)]
448pub struct Config {
449    /// Unclassified awaited calls are writes to an unknown resource.
450    pub strict: bool,
451    /// Writes may run ahead of earlier exits everywhere in the function.
452    pub speculate: bool,
453    /// Extra verbs (whole names or first words) that read, from `effects(read(..))`.
454    pub reads: Vec<String>,
455    /// Extra verbs that write, from `effects(write(..))`.
456    pub writes: Vec<String>,
457    /// Extra verbs whose order is observable, from `effects(ordered(..))`.
458    pub ordered: Vec<String>,
459    /// `calls = ..`: how the function's calls are taken, overriding `strict`.
460    pub calls: Option<Calls>,
461}
462
463/// `#[psync::graph(calls = ..)]`: a function-wide mark for the calls psync cannot classify, and
464/// whether the function's statements commute.
465#[derive(Clone, Copy, Debug, PartialEq, Eq)]
466pub enum Calls {
467    /// `calls = read`: unclassified calls read, even with `strict`.
468    Read,
469    /// `calls = write`: unclassified calls write (what `strict` does).
470    Write,
471    /// `calls = write_independent`: unclassified calls write, so they never run ahead of an
472    /// earlier exit; but every statement's effects commute with the others'.
473    WriteIndependent,
474    /// `calls = independent`: unclassified calls read, and every statement's effects commute.
475    Independent,
476}
477
478impl Config {
479    /// Unclassified awaited calls are writes to an unknown resource.
480    pub fn unclassified_writes(&self) -> bool {
481        match self.calls {
482            Some(Calls::Write | Calls::WriteIndependent) => true,
483            Some(Calls::Read | Calls::Independent) => false,
484            None => self.strict,
485        }
486    }
487    /// Every statement is `#[psync::independent]`.
488    pub fn independent(&self) -> bool {
489        matches!(
490            self.calls,
491            Some(Calls::Independent | Calls::WriteIndependent)
492        )
493    }
494}
495
496// ANCHOR: read-verbs
497/// First words of names that read.
498const READ_VERBS: &[&str] = &[
499    "get",
500    "head",
501    "list",
502    "fetch",
503    "read",
504    "load",
505    "query",
506    "select",
507    "find",
508    "lookup",
509    "describe",
510    "stat",
511    "exists",
512    "search",
513    "resolve",
514    "download",
515    "retrieve",
516    "watch",
517    "scan",
518    "count",
519    "check",
520    "peek",
521    "options",
522    "metadata",
523    "open",
524    "inspect",
525    "show",
526    "info",
527    "status",
528    "health",
529    "ping",
530    "poll",
531    "receive",
532    "batch_get",
533    "is",
534    "has",
535    "try_exists",
536    "canonicalize",
537    "verify",
538    "validate",
539    "connect",
540    "probe",
541    "discover",
542];
543// ANCHOR_END: read-verbs
544
545// ANCHOR: write-verbs
546/// First words of names that write.
547const WRITE_VERBS: &[&str] = &[
548    "create",
549    "insert",
550    "put",
551    "post",
552    "patch",
553    "delete",
554    "del",
555    "remove",
556    "rm",
557    "update",
558    "replace",
559    "upsert",
560    "set",
561    "write",
562    "rename",
563    "copy",
564    "upload",
565    "execute",
566    "exec",
567    "commit",
568    "rollback",
569    "spawn",
570    "kill",
571    "apply",
572    "merge",
573    "truncate",
574    "drop",
575    "evict",
576    "invalidate",
577    "purge",
578    "register",
579    "unregister",
580    "grant",
581    "revoke",
582    "restart",
583    "scale",
584    "cancel",
585    "transfer",
586    "incr",
587    "increment",
588    "decr",
589    "decrement",
590    "save",
591    "store",
592    "persist",
593    "flush",
594    "sync",
595    "mark",
596    "reset",
597    "clear",
598    "add",
599    "modify",
600    "edit",
601    "approve",
602    "reject",
603    "submit",
604    "deploy",
605    "install",
606    "uninstall",
607    "mkdir",
608    "rmdir",
609    "unlink",
610    "chmod",
611    "chown",
612    "touch",
613    "link",
614    "symlink",
615    "compact",
616    "migrate",
617    "seed",
618    "move",
619    "mv",
620    "claim",
621    "release",
622    "renew",
623    "expire",
624    "lease",
625    "start",
626    "stop",
627    "terminate",
628    "shutdown",
629    "close",
630    "run",
631    "invoke",
632    "call",
633    "trigger",
634    "charge",
635    "refund",
636    "pay",
637    "mint",
638    "burn",
639    "sign",
640    "issue",
641    "reserve",
642    "allocate",
643    "free",
644    "destroy",
645    "provision",
646    "attach",
647    "detach",
648    "mount",
649    "unmount",
650    "bind",
651    "unbind",
652];
653// ANCHOR_END: write-verbs
654
655// ANCHOR: ordered-verbs
656/// First words of names whose relative order is observable on one domain.
657const ORDERED_VERBS: &[&str] = &[
658    "send",
659    "append",
660    "push",
661    "publish",
662    "enqueue",
663    "emit",
664    "notify",
665    "ack",
666    "nack",
667    "pop",
668    "dequeue",
669    "broadcast",
670    "log",
671    "produce",
672    "write_all",
673    "feed",
674];
675// ANCHOR_END: ordered-verbs
676
677// ANCHOR: fs-reads
678/// File-system functions (last path segment) that only read.
679const FS_READS: &[&str] = &[
680    "read",
681    "read_to_string",
682    "read_dir",
683    "metadata",
684    "symlink_metadata",
685    "canonicalize",
686    "read_link",
687    "try_exists",
688    "exists",
689    "open",
690];
691// ANCHOR_END: fs-reads
692
693// ANCHOR: path-fs-reads
694/// Methods of `std::path::Path` without arguments that read the file system at the path.
695const PATH_FS_READS: &[&str] = &[
696    "exists",
697    "try_exists",
698    "is_file",
699    "is_dir",
700    "is_symlink",
701    "metadata",
702    "symlink_metadata",
703    "read_dir",
704    "read_link",
705    "canonicalize",
706];
707// ANCHOR_END: path-fs-reads
708
709// ANCHOR: net-writes
710/// Network functions that write (send data); the rest of `net` only connects or reads.
711const NET_WRITES: &[&str] = &["send_to", "send", "write", "write_all"];
712// ANCHOR_END: net-writes
713
714// ANCHOR: redis
715/// Redis commands, as the `redis` crate names its methods (`con.hget(k, f)`, `con.get_del(k)`)
716/// and as `redis::cmd("HGET")` names them. Matched by the whole name or its first word, before
717/// the verbs: `get_del` deletes, though its first word reads.
718const REDIS_READS: &[&str] = &[
719    "hget",
720    "hgetall",
721    "hmget",
722    "hkeys",
723    "hvals",
724    "hlen",
725    "hexists",
726    "hstrlen",
727    "mget",
728    "lrange",
729    "llen",
730    "lindex",
731    "lpos",
732    "smembers",
733    "sismember",
734    "smismember",
735    "scard",
736    "srandmember",
737    "sdiff",
738    "sinter",
739    "sunion",
740    "zrange",
741    "zrevrange",
742    "zrangebyscore",
743    "zrevrangebyscore",
744    "zscore",
745    "zmscore",
746    "zcard",
747    "zrank",
748    "zrevrank",
749    "zcount",
750    "zlexcount",
751    "ttl",
752    "pttl",
753    "strlen",
754    "getrange",
755    "keys",
756    "xrange",
757    "xrevrange",
758    "xlen",
759    "xread",
760    "pfcount",
761    "bitcount",
762    "getbit",
763    "geopos",
764    "geodist",
765    "georadius",
766    "dbsize",
767    "randomkey",
768];
769const REDIS_WRITES: &[&str] = &[
770    "hset",
771    "hsetnx",
772    "hmset",
773    "hdel",
774    "hincr",
775    "hincrby",
776    "mset",
777    "msetnx",
778    "setex",
779    "setnx",
780    "psetex",
781    "getset",
782    "getdel",
783    "get_del",
784    "getex",
785    "get_ex",
786    "setrange",
787    "setbit",
788    "sadd",
789    "srem",
790    "spop",
791    "smove",
792    "sdiffstore",
793    "sinterstore",
794    "sunionstore",
795    "zadd",
796    "zrem",
797    "zincr",
798    "zincrby",
799    "zpopmin",
800    "zpopmax",
801    "zremrangebyscore",
802    "zremrangebyrank",
803    "lset",
804    "ltrim",
805    "linsert",
806    "lrem",
807    "pexpire",
808    "expireat",
809    "pexpireat",
810    "pfadd",
811    "pfmerge",
812    "geoadd",
813    "xtrim",
814    "xdel",
815    "xgroup",
816    "flushdb",
817    "flushall",
818    "renamenx",
819];
820/// Commands whose order on one key is visible: list pushes and pops, stream appends.
821const REDIS_ORDERED: &[&str] = &[
822    "lpush",
823    "rpush",
824    "lpushx",
825    "rpushx",
826    "lpop",
827    "rpop",
828    "blpop",
829    "brpop",
830    "rpoplpush",
831    "brpoplpush",
832    "lmove",
833    "blmove",
834    "xadd",
835    "xack",
836    "xreadgroup",
837];
838// ANCHOR_END: redis
839
840/// What a function or method name says about the operation, for tools outside the macro
841/// (`cargo psync check` classifies calls into other crates with the same lists).
842#[derive(Clone, Copy, Debug, PartialEq, Eq)]
843pub enum Verb {
844    Read,
845    Write,
846    /// A write whose order relative to others on the same resource is observable.
847    Ordered,
848}
849
850/// The verb a name starts with, if psync knows it.
851pub fn verb_of(name: &str) -> Option<Verb> {
852    Config::default()
853        .verb(name)
854        .map(|(kind, ordered)| match (kind, ordered) {
855            (Kind::Read, _) => Verb::Read,
856            (Kind::Write, true) => Verb::Ordered,
857            (Kind::Write, false) => Verb::Write,
858        })
859}
860
861/// True for file-system functions that only read (`read_to_string`, `metadata`, `open`, ...).
862pub fn fs_reads(name: &str) -> bool {
863    FS_READS.contains(&name)
864}
865
866fn first_word(name: &str) -> &str {
867    let name = name.trim_start_matches("try_").trim_start_matches("async_");
868    name.split('_').next().unwrap_or(name)
869}
870
871impl Config {
872    /// How a call named `name` acts on a service, if its name says.
873    fn verb(&self, name: &str) -> Option<(Kind, bool)> {
874        let word = first_word(name);
875        let is = |list: &[&str]| list.contains(&name) || list.contains(&word);
876        let user = |list: &[String]| list.iter().any(|v| v == name || v == word);
877        if user(&self.ordered) {
878            Some((Kind::Write, true))
879        } else if user(&self.writes) {
880            Some((Kind::Write, false))
881        } else if user(&self.reads) {
882            Some((Kind::Read, false))
883        } else if is(REDIS_ORDERED) {
884            Some((Kind::Write, true))
885        } else if is(REDIS_WRITES) {
886            Some((Kind::Write, false))
887        } else if is(REDIS_READS) {
888            Some((Kind::Read, false))
889        } else if is(ORDERED_VERBS) {
890            Some((Kind::Write, true))
891        } else if is(WRITE_VERBS) {
892            Some((Kind::Write, false))
893        } else if is(READ_VERBS) {
894            Some((Kind::Read, false))
895        } else {
896            None
897        }
898    }
899}
900
901fn target_of(arg: Option<&Expr>) -> Target {
902    match arg {
903        Some(Expr::Lit(syn::ExprLit {
904            lit: syn::Lit::Str(s),
905            ..
906        })) => Target::Literal(s.value()),
907        Some(Expr::Reference(r)) => target_of(Some(&r.expr)),
908        Some(Expr::Paren(p)) => target_of(Some(&p.expr)),
909        // `Path::new(&format!(..))`, `PathBuf::from("a")`: the same text as a path.
910        Some(Expr::Call(c))
911            if c.args.len() == 1
912                && matches!(&*c.func, Expr::Path(p) if {
913                    let s: Vec<String> =
914                        p.path.segments.iter().map(|s| s.ident.to_string()).collect();
915                    matches!(
916                        s.iter().map(String::as_str).collect::<Vec<_>>()[..],
917                        [.., "Path" | "OsStr", "new"] | [.., "PathBuf" | "OsString" | "String", "from"]
918                    )
919                }) =>
920        {
921            target_of(c.args.first())
922        }
923        // `&format!("key.{id}")`: keep the literal text before the first placeholder.
924        Some(Expr::Macro(m)) if m.mac.path.is_ident("format") => {
925            let tokens = m.mac.tokens.clone();
926            if let Some(pieces) = template(tokens.clone()) {
927                return if pieces.iter().any(|p| matches!(p, Piece::Hole(_))) {
928                    Target::Template(pieces, mentions(tokens))
929                } else {
930                    Target::Literal(
931                        pieces
932                            .iter()
933                            .map(|p| match p {
934                                Piece::Char(c) => *c,
935                                Piece::Hole(_) => unreachable!(),
936                            })
937                            .collect(),
938                    )
939                };
940            }
941            let first = syn::parse2::<syn::LitStr>(tokens.clone().into_iter().take(1).collect());
942            let names = mentions(tokens.clone());
943            match first {
944                Ok(lit) => {
945                    let text = lit.value();
946                    let prefix: String = text.split('{').next().unwrap_or_default().into();
947                    if prefix.is_empty() {
948                        Target::Expr(tokens.to_string(), names)
949                    } else {
950                        Target::Prefixed(prefix, names)
951                    }
952                }
953                Err(_) => Target::Expr(tokens.to_string(), names),
954            }
955        }
956        Some(e) => {
957            let tokens = e.to_token_stream();
958            Target::Expr(tokens.to_string(), mentions(tokens))
959        }
960        None => Target::Any,
961    }
962}
963
964/// The target named by the value of a binding's initializer: `target_of`, and also
965/// `base.join(name)` with `base` a name or field and `name` a string literal or `format!` whose
966/// text starts with a character that cannot make it absolute: the path `base/name`, as a
967/// template whose first hole is `base`. (`Path::join` with an absolute `name` replaces `base`;
968/// `/`, `\` and a drive letter `C:` are refused.)
969pub(crate) fn value_target(e: &Expr) -> Target {
970    if let Expr::MethodCall(m) = e
971        && m.method == "join"
972        && m.args.len() == 1
973        && let Some(base) = plain_place(&m.receiver)
974    {
975        let rest = match target_of(m.args.first()) {
976            Target::Literal(l) => Some(l.chars().map(Piece::Char).collect::<Vec<_>>()),
977            Target::Template(p, _) => Some(p),
978            _ => None,
979        };
980        if let Some(rest) = rest
981            && let Some(Piece::Char(c)) = rest.first()
982            && !matches!(c, '/' | '\\')
983            && rest.get(1) != Some(&Piece::Char(':'))
984        {
985            let mut pieces = vec![Piece::Hole(format!("{base}:")), Piece::Char('/')];
986            pieces.extend(rest);
987            let names = mentions(e.to_token_stream());
988            return Target::Template(pieces, names);
989        }
990        return target_of(Some(e));
991    }
992    target_of(Some(e))
993}
994
995/// A name or a field path (`dir`, `self.root`), as tokens.
996fn plain_place(e: &Expr) -> Option<String> {
997    match e {
998        Expr::Path(p) if p.qself.is_none() && p.path.segments.len() == 1 => {
999            Some(p.to_token_stream().to_string())
1000        }
1001        Expr::Field(f) => {
1002            plain_place(&f.base)?;
1003            Some(f.to_token_stream().to_string())
1004        }
1005        Expr::Reference(r) if r.mutability.is_none() => plain_place(&r.expr),
1006        Expr::Paren(p) => plain_place(&p.expr),
1007        _ => None,
1008    }
1009}
1010
1011impl Target {
1012    /// The binding a computed target is, when it is just a name (`path`, `&path`).
1013    pub fn single_name(&self) -> Option<&str> {
1014        match self {
1015            Target::Expr(tokens, names) if names.len() == 1 => {
1016                let name = names.iter().next()?;
1017                let t = tokens.replace(' ', "");
1018                (t == *name || t == format!("&{name}")).then_some(name.as_str())
1019            }
1020            _ => None,
1021        }
1022    }
1023
1024    /// Says more than "anything": a literal, a known prefix or a template.
1025    pub fn informative(&self) -> bool {
1026        matches!(
1027            self,
1028            Target::Literal(_) | Target::Prefixed(..) | Target::Template(..)
1029        )
1030    }
1031
1032    /// The names its value depends on.
1033    pub fn names(&self) -> Option<&Set> {
1034        match self {
1035            Target::Prefixed(_, n) | Target::Template(_, n) | Target::Expr(_, n) => Some(n),
1036            _ => None,
1037        }
1038    }
1039}
1040
1041/// The dotted path of a receiver (`self.client`), or `None` when it is computed.
1042fn receiver_path(e: &Expr) -> Option<String> {
1043    match e {
1044        Expr::Path(p) if p.path.segments.len() == 1 => Some(p.path.segments[0].ident.to_string()),
1045        Expr::Field(f) => {
1046            let base = receiver_path(&f.base)?;
1047            match &f.member {
1048                syn::Member::Named(n) => Some(format!("{base}.{n}")),
1049                syn::Member::Unnamed(i) => Some(format!("{base}.{}", i.index)),
1050            }
1051        }
1052        Expr::Reference(r) => receiver_path(&r.expr),
1053        Expr::Paren(p) => receiver_path(&p.expr),
1054        Expr::Unary(u) => receiver_path(&u.expr),
1055        // `self.client()`, `api.clone()`: a handle derived from the receiver.
1056        Expr::MethodCall(m) if m.args.is_empty() => receiver_path(&m.receiver),
1057        _ => None,
1058    }
1059}
1060
1061/// The effects of a statement or expression, and the awaited calls psync could not classify.
1062#[derive(Default)]
1063pub(crate) struct Found {
1064    pub effects: Vec<Effect>,
1065    pub unclassified: Vec<String>,
1066    /// The compiler says a call here panics on purpose (only with facts, see [`crate::facts`]).
1067    pub panics: bool,
1068}
1069
1070/// Find the effects in `node` (a statement's tokens, parsed by the caller).
1071pub(crate) fn of_stmt(stmt: &syn::Stmt, config: &Config) -> Found {
1072    of_stmt_in(stmt, config, false)
1073}
1074
1075/// [`of_stmt`], in synchronous code when `sync` is set (Phase II): there a call blocks instead of
1076/// being awaited, so every method chain and free function is classified by its verb as an awaited
1077/// one is. A call without a known verb has no effect, and is not reported: in synchronous code
1078/// most calls are computations (`len`, `Vec::new`).
1079pub(crate) fn of_stmt_in(stmt: &syn::Stmt, config: &Config, sync: bool) -> Found {
1080    let mut v = Finder {
1081        config,
1082        found: Found::default(),
1083        awaited: 0,
1084        sync,
1085        quiet: false,
1086        chained: Default::default(),
1087    };
1088    v.visit_stmt(stmt);
1089    v.found
1090}
1091
1092struct Finder<'a> {
1093    config: &'a Config,
1094    found: Found,
1095    /// Depth of `.await` bases being visited: method chains count as service calls only there.
1096    awaited: usize,
1097    /// Synchronous code: method chains and free functions count as service calls everywhere.
1098    sync: bool,
1099    /// Classifying a synchronous call: a call without a verb is no effect and no report.
1100    quiet: bool,
1101    /// Method calls already classified as part of a longer chain (by address).
1102    chained: std::collections::HashSet<usize>,
1103}
1104
1105impl Finder<'_> {
1106    /// Use the compiler's facts for the call of `ident` at `span`, if there are any. Returns
1107    /// true when they are complete (the compiler saw through every callee), so the name's guess
1108    /// is not needed.
1109    /// `args` are the call's arguments as written, a method's receiver first: an effect the
1110    /// compiler found on the callee's parameter `j` acts on what `args[j]` names.
1111    fn fact(&mut self, span: proc_macro2::Span, ident: &str, args: &[&Expr]) -> bool {
1112        let Some(fact) = crate::facts::at(span, ident) else {
1113            return false;
1114        };
1115        for (e, arg) in fact.effects.iter().zip(&fact.on_arg) {
1116            let mut e = e.clone();
1117            if let Some(j) = arg {
1118                e.target = args.get(*j).map_or(Target::Any, |a| target_of(Some(a)));
1119                e.source = args.get(*j).map(|a| a.to_token_stream().to_string());
1120            }
1121            self.found.effects.push(e);
1122        }
1123        self.found.panics |= fact.panics;
1124        !fact.opaque
1125    }
1126
1127    /// Like [`Self::fact`], but distinguishes "no fact" (`None`) from "opaque fact"
1128    /// (`Some(false)`).
1129    fn fact_full(&mut self, span: proc_macro2::Span, ident: &str, args: &[&Expr]) -> Option<bool> {
1130        crate::facts::at(span, ident)?;
1131        Some(self.fact(span, ident, args))
1132    }
1133
1134    /// The last identifier of a called path (`stamp` in `helpers::stamp(..)`).
1135    fn callee_name(c: &syn::ExprCall) -> Option<String> {
1136        match &*c.func {
1137            Expr::Path(p) => p.path.segments.last().map(|s| s.ident.to_string()),
1138            _ => None,
1139        }
1140    }
1141
1142    fn push(&mut self, domain: Domain, kind: Kind, target: Target, op: String, ordered: bool) {
1143        self.found.effects.push(Effect {
1144            domain,
1145            kind,
1146            target,
1147            op,
1148            ordered,
1149            source: None,
1150        });
1151    }
1152
1153    /// Record the expression the last effect's target was taken from.
1154    fn sourced(&mut self, arg: Option<&Expr>) {
1155        if let (Some(e), Some(a)) = (self.found.effects.last_mut(), arg) {
1156            e.source = Some(a.to_token_stream().to_string());
1157        }
1158    }
1159
1160    /// `std::fs::write(p, ..)`, `File::create(p)`, `env::set_var(..)`, `Command::new(..)`, and
1161    /// awaited free functions named by a verb.
1162    fn path_call(&mut self, c: &syn::ExprCall) -> bool {
1163        let Expr::Path(p) = &*c.func else {
1164            return false;
1165        };
1166        if let Some(name) = Self::callee_name(c)
1167            && self.fact(c.func.span(), &name, &c.args.iter().collect::<Vec<_>>())
1168        {
1169            return true;
1170        }
1171        let segs: Vec<String> = p
1172            .path
1173            .segments
1174            .iter()
1175            .map(|s| s.ident.to_string())
1176            .collect();
1177        let Some(last) = segs.last().cloned() else {
1178            return false;
1179        };
1180        let has = |s: &str| segs[..segs.len() - 1].iter().any(|x| x == s);
1181        let op = segs[segs.len().saturating_sub(2)..].join("::");
1182        let arg0 = c.args.first();
1183        if has("fs") || has("File") || has("OpenOptions") || has("DirBuilder") {
1184            let kind = if FS_READS.contains(&last.as_str()) && !has("OpenOptions") {
1185                Kind::Read
1186            } else {
1187                Kind::Write
1188            };
1189            self.push(Domain::Fs, kind, target_of(arg0), op.clone(), false);
1190            self.sourced(arg0);
1191            // `rename(from, to)`, `copy(from, to)`, `hard_link(src, dst)` also touch the second.
1192            if kind == Kind::Write
1193                && c.args.len() >= 2
1194                && matches!(
1195                    last.as_str(),
1196                    "rename" | "copy" | "hard_link" | "symlink" | "soft_link"
1197                )
1198            {
1199                self.push(
1200                    Domain::Fs,
1201                    Kind::Write,
1202                    target_of(c.args.iter().nth(1)),
1203                    op,
1204                    false,
1205                );
1206                self.sourced(c.args.iter().nth(1));
1207            }
1208            return true;
1209        }
1210        if has("env") {
1211            let kind = if last.starts_with("set") || last.starts_with("remove") {
1212                Kind::Write
1213            } else {
1214                Kind::Read
1215            };
1216            self.push(Domain::Env, kind, target_of(arg0), op, false);
1217            return true;
1218        }
1219        if has("Command") || has("process") {
1220            self.push(Domain::Process, Kind::Write, target_of(arg0), op, true);
1221            return true;
1222        }
1223        if has("TcpStream")
1224            || has("UdpSocket")
1225            || has("TcpListener")
1226            || has("UnixStream")
1227            || has("net")
1228        {
1229            let kind = if NET_WRITES.contains(&last.as_str()) {
1230                Kind::Write
1231            } else {
1232                Kind::Read
1233            };
1234            self.push(Domain::Net, kind, target_of(arg0), op, false);
1235            return true;
1236        }
1237        if has("set_current_dir") || last == "set_current_dir" {
1238            self.push(Domain::Env, Kind::Write, Target::Any, op, false);
1239            return true;
1240        }
1241        if self.awaited > 0 {
1242            // An awaited free function or associated function: a service behind any receiver.
1243            match self.config.verb(&last) {
1244                Some((kind, ordered)) => {
1245                    self.push(Domain::Service(None), kind, target_of(arg0), op, ordered)
1246                }
1247                None => self.unclassified(op),
1248            }
1249            return true;
1250        }
1251        false
1252    }
1253
1254    fn unclassified(&mut self, op: String) {
1255        if self.quiet {
1256            return;
1257        }
1258        if self.config.unclassified_writes() {
1259            self.push(Domain::Unknown, Kind::Write, Target::Any, op.clone(), true);
1260        }
1261        self.found.unclassified.push(op);
1262    }
1263
1264    /// An awaited method chain `recv.a(..).b(..).c(..)`: the first method with a known verb
1265    /// decides, so `client.get(url).send()` reads and `s3.put_object().key(k).send()` writes.
1266    fn awaited_chain(&mut self, base: &Expr) {
1267        let mut calls = Vec::new();
1268        let mut e = base;
1269        loop {
1270            match e {
1271                Expr::MethodCall(m) => {
1272                    calls.push(m);
1273                    e = &m.receiver;
1274                }
1275                Expr::Try(t) => e = &t.expr,
1276                Expr::Paren(p) => e = &p.expr,
1277                _ => break,
1278            }
1279        }
1280        // Facts from the compiler for any call of the chain replace the names' guesses.
1281        // A chain counts as known when at least one call has a fact and none is opaque.
1282        let mut any = false;
1283        let mut complete = true;
1284        let mut note = |found: Option<bool>| {
1285            if let Some(full) = found {
1286                any = true;
1287                complete &= full;
1288            }
1289        };
1290        for m in &calls {
1291            let args: Vec<&Expr> = std::iter::once(&*m.receiver).chain(&m.args).collect();
1292            note(self.fact_full(m.method.span(), &m.method.to_string(), &args));
1293        }
1294        if let Expr::Call(c) = e
1295            && let Some(name) = Self::callee_name(c)
1296        {
1297            note(self.fact_full(c.func.span(), &name, &c.args.iter().collect::<Vec<_>>()));
1298        }
1299        if any && complete {
1300            return;
1301        }
1302        // A Redis command named by a literal decides: `redis::cmd("HGET").arg(k)` reads `k`.
1303        if let Some((kind, ordered, what, target, key)) = self.redis_of_chain(e, &calls) {
1304            self.push(Domain::Service(None), kind, target, what, ordered);
1305            self.sourced(key);
1306            return;
1307        }
1308        // An HTTP method decides by RFC 9110, not the names around it:
1309        // `client.request(Method::GET, url).send()` reads, although `send` is an ordered verb.
1310        if let Some((kind, what, target, url)) = http_of_chain(&calls) {
1311            self.push(Domain::Service(receiver_path(e)), kind, target, what, false);
1312            self.sourced(url);
1313            return;
1314        }
1315        // SQL decides by its statement, not by the method's name: `query("DELETE ..")` writes.
1316        if let Some((kind, what)) = sql_of_chain(e, &calls) {
1317            self.push(Domain::Service(None), kind, Target::Any, what, false);
1318            return;
1319        }
1320        // `e` is the chain's root; a root that is itself a call (`Command::new(..)`,
1321        // `File::open(..)`, `fetch(x)`) is classified by `visit_expr_call`.
1322        if let Expr::Call(c) = e
1323            && matches!(&*c.func, Expr::Path(_))
1324        {
1325            let before = self.found.effects.len() + self.found.unclassified.len();
1326            self.path_call(c);
1327            let classified = self.found.effects.len() + self.found.unclassified.len() > before;
1328            if classified {
1329                return;
1330            }
1331        }
1332        calls.reverse();
1333        if calls.is_empty() {
1334            return;
1335        }
1336        // `path.exists()`, `dir.join("a").is_file()`: methods of `std::path::Path` that read the
1337        // file system at the receiver. Another type may have a method of that name, so the
1338        // service read below is kept as well: both are reads, and an extra one only adds
1339        // conflicts.
1340        for m in &calls {
1341            if m.args.is_empty() && PATH_FS_READS.contains(&m.method.to_string().as_str()) {
1342                let target = target_of(Some(&m.receiver));
1343                self.push(Domain::Fs, Kind::Read, target, m.method.to_string(), false);
1344                self.sourced(Some(&m.receiver));
1345            }
1346        }
1347        let domain = Domain::Service(receiver_path(e));
1348        for m in &calls {
1349            let name = m.method.to_string();
1350            if let Some((kind, ordered)) = self.config.verb(&name) {
1351                self.push(domain, kind, target_of(m.args.first()), name, ordered);
1352                return;
1353            }
1354        }
1355        let names: Vec<String> = calls.iter().map(|m| m.method.to_string()).collect();
1356        self.unclassified(names.join("."));
1357    }
1358}
1359
1360impl<'ast> Visit<'ast> for Finder<'_> {
1361    fn visit_expr_await(&mut self, e: &'ast syn::ExprAwait) {
1362        self.awaited += 1;
1363        self.awaited_chain(&e.base);
1364        // Calls nested in the chain's arguments are visited for their own effects.
1365        match &*e.base {
1366            Expr::MethodCall(_) | Expr::Try(_) | Expr::Paren(_) => {
1367                let mut x = &*e.base;
1368                loop {
1369                    match x {
1370                        Expr::MethodCall(m) => {
1371                            for a in &m.args {
1372                                self.visit_expr(a);
1373                            }
1374                            x = &m.receiver;
1375                        }
1376                        Expr::Try(t) => x = &t.expr,
1377                        Expr::Paren(p) => x = &p.expr,
1378                        Expr::Call(c) => {
1379                            for a in &c.args {
1380                                self.visit_expr(a);
1381                            }
1382                            break;
1383                        }
1384                        other => {
1385                            self.visit_expr(other);
1386                            break;
1387                        }
1388                    }
1389                }
1390            }
1391            Expr::Call(c) => {
1392                for a in &c.args {
1393                    self.visit_expr(a);
1394                }
1395            }
1396            other => self.visit_expr(other),
1397        }
1398        self.awaited -= 1;
1399    }
1400
1401    fn visit_expr_method_call(&mut self, m: &'ast syn::ExprMethodCall) {
1402        if self.sync && self.awaited == 0 {
1403            // The outermost call of a chain classifies the whole chain, as an await would.
1404            if self.chained.insert(m as *const _ as usize) {
1405                let mut r = &*m.receiver;
1406                loop {
1407                    match r {
1408                        Expr::MethodCall(inner) => {
1409                            self.chained.insert(inner as *const _ as usize);
1410                            r = &inner.receiver;
1411                        }
1412                        Expr::Try(t) => r = &t.expr,
1413                        Expr::Paren(p) => r = &p.expr,
1414                        _ => break,
1415                    }
1416                }
1417                let quiet = std::mem::replace(&mut self.quiet, true);
1418                self.awaited += 1;
1419                self.awaited_chain(&Expr::MethodCall(m.clone()));
1420                self.awaited -= 1;
1421                self.quiet = quiet;
1422            }
1423        } else {
1424            // Synchronous method calls in async code only have effects psync knows of through
1425            // the compiler.
1426            let args: Vec<&Expr> = std::iter::once(&*m.receiver).chain(&m.args).collect();
1427            self.fact(m.method.span(), &m.method.to_string(), &args);
1428        }
1429        syn::visit::visit_expr_method_call(self, m);
1430    }
1431
1432    fn visit_expr_call(&mut self, c: &'ast syn::ExprCall) {
1433        // Awaited free functions are handled by `awaited_chain`; plain calls only count when they
1434        // reach a known domain (`std::fs::write`), so `HashMap::new()` stays effect-free. In
1435        // synchronous code a free function named by a verb is a service call too.
1436        if self.sync && self.awaited == 0 {
1437            let quiet = std::mem::replace(&mut self.quiet, true);
1438            self.awaited = 1;
1439            self.path_call(c);
1440            self.awaited = 0;
1441            self.quiet = quiet;
1442        } else {
1443            let saved = std::mem::replace(&mut self.awaited, 0);
1444            self.path_call(c);
1445            self.awaited = saved;
1446        }
1447        syn::visit::visit_expr_call(self, c);
1448    }
1449
1450    fn visit_macro(&mut self, m: &'ast syn::Macro) {
1451        let name = crate::classify::macro_name(m);
1452        // `select!`, `join!`: the futures they await are hidden in the tokens, so their effects
1453        // may be anything.
1454        if crate::classify::AWAITING_MACROS.contains(&name.as_str()) {
1455            let op = format!("{name}!");
1456            if !self.quiet {
1457                self.push(Domain::Unknown, Kind::Write, Target::Any, op.clone(), true);
1458                self.found.unclassified.push(op);
1459            }
1460            return;
1461        }
1462        // Macro bodies are not parsed; an await inside one is unclassified.
1463        if contains_await(m.tokens.clone())
1464            && !matches!(
1465                name.as_str(),
1466                "format"
1467                    | "vec"
1468                    | "println"
1469                    | "eprintln"
1470                    | "debug"
1471                    | "info"
1472                    | "warn"
1473                    | "error"
1474                    | "trace"
1475            )
1476        {
1477            self.unclassified(format!("{name}!"));
1478        }
1479    }
1480
1481    // Items inside the statement are separate code.
1482    fn visit_item(&mut self, _: &'ast syn::Item) {}
1483}
1484
1485// ANCHOR: sql-reads
1486/// Statements that only read, by their first word. `EXPLAIN` without `ANALYZE` only plans.
1487const SQL_READS: &[&str] = &[
1488    "SELECT", "SHOW", "EXPLAIN", "DESCRIBE", "DESC", "VALUES", "TABLE", "PRAGMA",
1489];
1490// ANCHOR_END: sql-reads
1491
1492// ANCHOR: sql-writes
1493/// Statements that change the database or the session, by their first word.
1494const SQL_WRITES: &[&str] = &[
1495    "INSERT",
1496    "UPDATE",
1497    "DELETE",
1498    "MERGE",
1499    "UPSERT",
1500    "REPLACE",
1501    "CREATE",
1502    "DROP",
1503    "ALTER",
1504    "TRUNCATE",
1505    "GRANT",
1506    "REVOKE",
1507    "COPY",
1508    "CALL",
1509    "EXEC",
1510    "EXECUTE",
1511    "DO",
1512    "LOCK",
1513    "BEGIN",
1514    "START",
1515    "COMMIT",
1516    "ROLLBACK",
1517    "SAVEPOINT",
1518    "RELEASE",
1519    "SET",
1520    "RESET",
1521    "VACUUM",
1522    "ANALYZE",
1523    "REINDEX",
1524    "CLUSTER",
1525    "REFRESH",
1526    "COMMENT",
1527    "DISCARD",
1528    "LISTEN",
1529    "NOTIFY",
1530    "UNLISTEN",
1531    "PREPARE",
1532    "DEALLOCATE",
1533    "ATTACH",
1534    "DETACH",
1535    "LOAD",
1536    "IMPORT",
1537];
1538// ANCHOR_END: sql-writes
1539
1540// ANCHOR: sql-write-words
1541/// Words that make a reading statement write or lock: `SELECT .. FOR UPDATE`, `SELECT .. INTO`,
1542/// `nextval(..)`, a data-modifying `WITH`, `EXPLAIN ANALYZE` (which runs the statement).
1543const SQL_WRITE_WORDS: &[&str] = &[
1544    "INSERT",
1545    "UPDATE",
1546    "DELETE",
1547    "MERGE",
1548    "INTO",
1549    "NEXTVAL",
1550    "SETVAL",
1551    "LOCK",
1552    "ANALYZE",
1553    "PG_ADVISORY_LOCK",
1554    "PG_ADVISORY_XACT_LOCK",
1555    "GET_LOCK",
1556];
1557// ANCHOR_END: sql-write-words
1558
1559/// Read or write, if `text` is an SQL statement: its first word is a statement keyword and
1560/// more follows. `None` for any other string.
1561pub(crate) fn sql_kind(text: &str) -> Option<Kind> {
1562    let words: Vec<String> = text
1563        .split(|c: char| !(c.is_alphanumeric() || c == '_'))
1564        .filter(|w| !w.is_empty())
1565        .map(str::to_ascii_uppercase)
1566        .collect();
1567    let first = words.first()?;
1568    if words.len() < 2 {
1569        return None;
1570    }
1571    let writes_inside = || {
1572        words[1..]
1573            .iter()
1574            .any(|w| SQL_WRITE_WORDS.contains(&w.as_str()))
1575    };
1576    if first == "WITH" {
1577        // A common table expression reads unless it modifies data.
1578        return Some(if writes_inside() {
1579            Kind::Write
1580        } else {
1581            Kind::Read
1582        });
1583    }
1584    if SQL_READS.contains(&first.as_str()) {
1585        return Some(if writes_inside() {
1586            Kind::Write
1587        } else {
1588            Kind::Read
1589        });
1590    }
1591    SQL_WRITES.contains(&first.as_str()).then_some(Kind::Write)
1592}
1593
1594/// RFC 9110: GET, HEAD, OPTIONS and TRACE are *safe* (they behave as reads); every other method
1595/// may change the server.
1596pub(crate) fn http_kind(method: &str) -> Kind {
1597    match method.to_ascii_uppercase().as_str() {
1598        "GET" | "HEAD" | "OPTIONS" | "TRACE" => Kind::Read,
1599        _ => Kind::Write,
1600    }
1601}
1602
1603/// The HTTP method a chain names, if any, with the URL it goes to: `request(Method::PUT, url)`
1604/// (`reqwest`, `http`, `hyper`, any path ending in `Method::X`), or a builder's
1605/// `.method(Method::PUT)` / `.method("PUT")` with the URL from `.uri(..)` or `.url(..)`.
1606/// The last element is the URL's expression, when the target was taken from it (a gate may
1607/// compare it at run time).
1608fn http_of_chain<'a>(
1609    calls: &[&'a syn::ExprMethodCall],
1610) -> Option<(Kind, String, Target, Option<&'a Expr>)> {
1611    let method = |e: &Expr| match e {
1612        Expr::Path(p)
1613            if p.path.segments.len() >= 2
1614                && p.path.segments[p.path.segments.len() - 2].ident == "Method" =>
1615        {
1616            p.path.segments.last().map(|s| s.ident.to_string())
1617        }
1618        Expr::Lit(syn::ExprLit {
1619            lit: syn::Lit::Str(s),
1620            ..
1621        }) => Some(s.value()),
1622        _ => None,
1623    };
1624    for m in calls {
1625        let name = m.method.to_string();
1626        let found = match (name.as_str(), m.args.first()) {
1627            // A literal counts only as the argument of `.method(..)`; in `request(..)` the
1628            // method must be a `Method::X` path.
1629            ("method", Some(a)) => method(a),
1630            (_, Some(a @ Expr::Path(_))) => method(a),
1631            _ => None,
1632        };
1633        let Some(verb) = found else { continue };
1634        let url = if name == "method" {
1635            calls
1636                .iter()
1637                .find(|c| c.method == "uri" || c.method == "url")
1638                .and_then(|c| c.args.first())
1639        } else {
1640            m.args.iter().nth(1)
1641        };
1642        let verb = verb.to_ascii_uppercase();
1643        // GET, HEAD, OPTIONS and TRACE read their URL; PUT, DELETE and PATCH change it. A POST
1644        // (or a method psync does not know) does whatever the server does with it: anything.
1645        let (target, url) = match verb.as_str() {
1646            "GET" | "HEAD" | "OPTIONS" | "TRACE" | "PUT" | "DELETE" | "PATCH" => {
1647                (target_of(url), url)
1648            }
1649            _ => (Target::Any, None),
1650        };
1651        return Some((http_kind(&verb), format!("HTTP {verb}"), target, url));
1652    }
1653    None
1654}
1655
1656impl Finder<'_> {
1657    /// `redis::cmd("HGET").arg(key)..`: the command's kind, whether its order is visible, and the
1658    /// first `.arg(..)` as the target, with its expression. An unknown command may do anything,
1659    /// so it writes.
1660    fn redis_of_chain<'a>(
1661        &self,
1662        root: &Expr,
1663        calls: &[&'a syn::ExprMethodCall],
1664    ) -> Option<(Kind, bool, String, Target, Option<&'a Expr>)> {
1665        let Expr::Call(c) = root else { return None };
1666        let Expr::Path(p) = &*c.func else { return None };
1667        let segs: Vec<String> = p
1668            .path
1669            .segments
1670            .iter()
1671            .map(|s| s.ident.to_string())
1672            .collect();
1673        if !(segs.len() >= 2 && segs[segs.len() - 2] == "redis" && segs[segs.len() - 1] == "cmd") {
1674            return None;
1675        }
1676        let command = match c.args.first() {
1677            Some(Expr::Lit(syn::ExprLit {
1678                lit: syn::Lit::Str(s),
1679                ..
1680            })) => s.value(),
1681            _ => {
1682                return Some((
1683                    Kind::Write,
1684                    false,
1685                    "redis::cmd: command not known".into(),
1686                    Target::Any,
1687                    None,
1688                ));
1689            }
1690        };
1691        let name = command.to_ascii_lowercase();
1692        let (kind, ordered) = self.config.verb(&name).unwrap_or((Kind::Write, false));
1693        // `.arg(k)` in program order: the outermost call is first in `calls`.
1694        let key = calls
1695            .iter()
1696            .rev()
1697            .find(|m| m.method == "arg")
1698            .and_then(|m| m.args.first());
1699        Some((
1700            kind,
1701            ordered,
1702            format!("redis {command}"),
1703            target_of(key),
1704            key,
1705        ))
1706    }
1707}
1708
1709/// The SQL statement in an awaited chain, if any: a string literal argument of its root call
1710/// (`sqlx::query("..")`), its root macro (`sqlx::query!("..")`) or one of its methods
1711/// (`client.execute("..", &[])`). A statement psync cannot read in a call it knows is SQL
1712/// (`sqlx::query(&sql)`, `diesel::sql_query(s)`) may be anything, so it writes.
1713fn sql_of_chain(root: &Expr, calls: &[&syn::ExprMethodCall]) -> Option<(Kind, String)> {
1714    let literal = |e: &Expr| match e {
1715        Expr::Lit(syn::ExprLit {
1716            lit: syn::Lit::Str(s),
1717            ..
1718        }) => Some(s.value()),
1719        _ => None,
1720    };
1721    let found = |text: String, op: &str| {
1722        let kind = sql_kind(&text)?;
1723        let first = text
1724            .split_whitespace()
1725            .next()
1726            .unwrap_or("")
1727            .to_ascii_uppercase();
1728        Some((kind, format!("{op}: {first}")))
1729    };
1730    match root {
1731        Expr::Call(c) => {
1732            if let Expr::Path(p) = &*c.func {
1733                let segs: Vec<String> = p
1734                    .path
1735                    .segments
1736                    .iter()
1737                    .map(|s| s.ident.to_string())
1738                    .collect();
1739                let op = segs[segs.len().saturating_sub(2)..].join("::");
1740                if let Some(r) = c
1741                    .args
1742                    .iter()
1743                    .find_map(|a| literal(a).and_then(|t| found(t, &op)))
1744                {
1745                    return Some(r);
1746                }
1747                let sql_fn = (segs.iter().any(|s| s == "sqlx")
1748                    && segs.last().is_some_and(|l| l.starts_with("query")))
1749                    || segs.last().is_some_and(|l| l == "sql_query");
1750                if sql_fn && c.args.first().is_some_and(|a| literal(a).is_none()) {
1751                    return Some((Kind::Write, format!("{op}: statement not known")));
1752                }
1753            }
1754        }
1755        Expr::Macro(m) => {
1756            let name = m.mac.path.segments.last().map(|s| s.ident.to_string())?;
1757            let first = m.mac.tokens.clone().into_iter().find_map(|t| match t {
1758                proc_macro2::TokenTree::Literal(l) => syn::parse_str::<syn::LitStr>(&l.to_string())
1759                    .ok()
1760                    .map(|s| s.value()),
1761                _ => None,
1762            });
1763            if let Some(r) = first.and_then(|t| found(t, &format!("{name}!"))) {
1764                return Some(r);
1765            }
1766        }
1767        _ => {}
1768    }
1769    calls.iter().find_map(|m| {
1770        m.args
1771            .iter()
1772            .find_map(|a| literal(a).and_then(|t| found(t, &m.method.to_string())))
1773    })
1774}
1775
1776fn contains_await(ts: TokenStream) -> bool {
1777    ts.into_iter().any(|t| match t {
1778        proc_macro2::TokenTree::Ident(i) => i == "await",
1779        proc_macro2::TokenTree::Group(g) => contains_await(g.stream()),
1780        _ => false,
1781    })
1782}
1783
1784/// `baseline = resync`: effects as ReSynchronizer (ECOOP 2021, §4.4) models them, one
1785/// pseudo-variable per environment. Every file effect acts on "the file system" and every network
1786/// or service effect on "the network", whatever its target, so a write orders every other access
1787/// to its environment.
1788pub(crate) fn per_environment(nodes: &mut [crate::classify::Node]) {
1789    for effect in nodes.iter_mut().flat_map(|n| n.effects.iter_mut()) {
1790        if matches!(effect.domain, Domain::Service(_)) {
1791            effect.domain = Domain::Net;
1792        }
1793        effect.target = Target::Any;
1794        effect.source = None;
1795    }
1796}
1797
1798#[cfg(test)]
1799mod tests {
1800    use super::*;
1801    use syn::parse_quote;
1802
1803    fn effects(stmt: syn::Stmt) -> Vec<Effect> {
1804        of_stmt(&stmt, &Config::default()).effects
1805    }
1806
1807    #[test]
1808    fn http_methods_decide_by_rfc_9110() {
1809        let one = |stmt: syn::Stmt| {
1810            let e = effects(stmt);
1811            assert_eq!(e.len(), 1, "{e:?}");
1812            e[0].clone()
1813        };
1814        // `send` is an ordered verb; the method decides instead.
1815        let get = one(parse_quote!(let r = client.request(Method::GET, url).send().await?;));
1816        assert!(get.kind == Kind::Read && !get.ordered, "{get:?}");
1817        let head = one(parse_quote!(let r = c.request(reqwest::Method::HEAD, url).send().await?;));
1818        assert_eq!(head.kind, Kind::Read);
1819        let put = one(parse_quote!(client.request(http::Method::PUT, url).send().await?;));
1820        assert!(put.kind == Kind::Write && !put.ordered);
1821        // A builder's `.method(..)`, with a path or a literal; the URL from `.uri(..)`.
1822        let b = one(parse_quote!(api.builder().method("DELETE").uri("https://h/a").send().await?;));
1823        assert_eq!(b.kind, Kind::Write);
1824        let opts = one(parse_quote!(api.builder().method(Method::OPTIONS).send().await?;));
1825        assert_eq!(opts.kind, Kind::Read);
1826        // Targets: the URL. Two GETs never conflict; a GET and a PUT of one URL do, of two
1827        // literal URLs do not.
1828        let g = effects(parse_quote!(let r = c.request(Method::GET, "https://h/a").send().await?;));
1829        let p = effects(parse_quote!(c.request(Method::PUT, "https://h/a").send().await?;));
1830        let q = effects(parse_quote!(c.request(Method::PUT, "https://h/b").send().await?;));
1831        assert!(conflicts(&g, &g).is_none());
1832        assert!(conflicts(&g, &p).is_some());
1833        assert!(conflicts(&g, &q).is_none());
1834        // URLs compare as paths: a DELETE of a collection conflicts with a GET inside it.
1835        let d = effects(parse_quote!(c.request(Method::DELETE, "https://h/a").send().await?;));
1836        let inside =
1837            effects(parse_quote!(let r = c.request(Method::GET, "https://h/a/x").send().await?;));
1838        assert!(conflicts(&d, &inside).is_some());
1839        // A POST may do anything to the service, whatever its URL.
1840        let post = effects(parse_quote!(c.request(Method::POST, "https://h/b").send().await?;));
1841        assert!(conflicts(&post, &g).is_some());
1842        // A string literal as the first argument of anything but `.method` is no method.
1843        let e = one(parse_quote!(let r = client.get("POST").send().await?;));
1844        assert_eq!(e.kind, Kind::Read);
1845    }
1846
1847    #[test]
1848    fn redis_commands_classify() {
1849        let one = |stmt: syn::Stmt| {
1850            let e = effects(stmt);
1851            assert_eq!(e.len(), 1, "{e:?}");
1852            (e[0].kind, e[0].ordered)
1853        };
1854        assert_eq!(
1855            one(parse_quote!(let v: String = con.hget("k", "f").await?;)),
1856            (Kind::Read, false)
1857        );
1858        assert_eq!(
1859            one(parse_quote!(con.hset("k", "f", 1).await?;)),
1860            (Kind::Write, false)
1861        );
1862        // `get_del` deletes, though its first word reads.
1863        assert_eq!(
1864            one(parse_quote!(let v: String = con.get_del("k").await?;)),
1865            (Kind::Write, false)
1866        );
1867        assert_eq!(
1868            one(parse_quote!(con.lpush("q", 1).await?;)),
1869            (Kind::Write, true)
1870        );
1871        assert_eq!(
1872            one(parse_quote!(let n: u64 = con.zcard("z").await?;)),
1873            (Kind::Read, false)
1874        );
1875        // `redis::cmd("..")`: the command decides, and the first `.arg(..)` is the target.
1876        let get = effects(
1877            parse_quote!(let v: String = redis::cmd("GET").arg("a").query_async(&mut con).await?;),
1878        );
1879        assert_eq!((get[0].kind, get.len()), (Kind::Read, 1));
1880        let set_a =
1881            effects(parse_quote!(redis::cmd("SET").arg("a").arg(1).query_async(&mut con).await?;));
1882        let set_b =
1883            effects(parse_quote!(redis::cmd("SET").arg("b").arg(1).query_async(&mut con).await?;));
1884        assert_eq!(set_a[0].kind, Kind::Write);
1885        assert!(conflicts(&get, &set_a).is_some());
1886        assert!(conflicts(&get, &set_b).is_none());
1887        // A command psync cannot read may be anything.
1888        let any = effects(parse_quote!(redis::cmd(name).arg("a").query_async(&mut con).await?;));
1889        assert_eq!(any[0].kind, Kind::Write);
1890        assert!(conflicts(&any, &get).is_some());
1891    }
1892
1893    #[test]
1894    fn sql_statements_decide_read_or_write() {
1895        let kind = |stmt: syn::Stmt| {
1896            let e = effects(stmt);
1897            assert_eq!(e.len(), 1, "{e:?}");
1898            e[0].kind
1899        };
1900        // `query` is a read verb, but the statement decides.
1901        assert_eq!(
1902            kind(parse_quote!(let r = sqlx::query("SELECT * FROM t").fetch_all(db).await?;)),
1903            Kind::Read
1904        );
1905        assert_eq!(
1906            kind(parse_quote!(sqlx::query("DELETE FROM t").execute(db).await?;)),
1907            Kind::Write
1908        );
1909        assert_eq!(
1910            kind(
1911                parse_quote!(let r = sqlx::query!("insert into t values ($1)", x).execute(db).await?;)
1912            ),
1913            Kind::Write
1914        );
1915        assert_eq!(
1916            kind(parse_quote!(let r = client.query("SELECT 1", &[]).await?;)),
1917            Kind::Read
1918        );
1919        assert_eq!(
1920            kind(parse_quote!(client.execute("UPDATE t SET a = 1", &[]).await?;)),
1921            Kind::Write
1922        );
1923        // Reading statements that write or lock.
1924        assert_eq!(
1925            kind(parse_quote!(let r = client.query("SELECT * FROM t FOR UPDATE", &[]).await?;)),
1926            Kind::Write
1927        );
1928        assert_eq!(
1929            kind(parse_quote!(let r = client.query("SELECT nextval('s')", &[]).await?;)),
1930            Kind::Write
1931        );
1932        assert_eq!(
1933            kind(
1934                parse_quote!(let r = client.query("WITH d AS (DELETE FROM t RETURNING *) SELECT * FROM d", &[]).await?;)
1935            ),
1936            Kind::Write
1937        );
1938        assert_eq!(
1939            kind(
1940                parse_quote!(let r = client.query("WITH x AS (SELECT 1) SELECT * FROM x", &[]).await?;)
1941            ),
1942            Kind::Read
1943        );
1944        // A statement psync cannot read, in a call it knows runs SQL.
1945        assert_eq!(
1946            kind(parse_quote!(sqlx::query(&sql).execute(db).await?;)),
1947            Kind::Write
1948        );
1949        // Ordinary strings are not SQL.
1950        assert_eq!(sql_kind("select"), None);
1951        assert_eq!(sql_kind("https://example.com/select"), None);
1952        // Two reads overlap; a read and a write keep their order.
1953        let clash = |a: syn::Stmt, b: syn::Stmt| conflicts(&effects(a), &effects(b)).is_some();
1954        assert!(!clash(
1955            parse_quote!(let a = sqlx::query("SELECT a FROM t").fetch_one(db).await?;),
1956            parse_quote!(let b = sqlx::query("SELECT b FROM u").fetch_one(db).await?;),
1957        ));
1958        assert!(clash(
1959            parse_quote!(let a = sqlx::query("SELECT a FROM t").fetch_one(db).await?;),
1960            parse_quote!(sqlx::query("DELETE FROM t").execute(db).await?;),
1961        ));
1962    }
1963
1964    #[test]
1965    fn format_templates_with_the_same_holes() {
1966        let clash = |a: syn::Stmt, b: syn::Stmt| conflicts(&effects(a), &effects(b)).is_some();
1967        // Same placeholders, then different text: different files.
1968        assert!(!clash(
1969            parse_quote!(std::fs::write(format!("{dir}/AppRun"), a)?;),
1970            parse_quote!(std::fs::write(format!("{dir}/linuxdeploy"), b)?;),
1971        ));
1972        // Positional and named arguments name the same placeholder.
1973        assert!(!clash(
1974            parse_quote!(std::fs::write(format!("{}/a", self.dir), a)?;),
1975            parse_quote!(std::fs::write(format!("{d}/b", d = self.dir), b)?;),
1976        ));
1977        // Keys of a service: different fields of one user.
1978        assert!(!clash(
1979            parse_quote!(kv.set(&format!("user.{id}.name"), n).await?;),
1980            parse_quote!(kv.set(&format!("user.{id}.email"), e).await?;),
1981        ));
1982        // Still conflicts: a different placeholder may hold the same text,
1983        assert!(clash(
1984            parse_quote!(std::fs::write(format!("{dir}/a"), a)?;),
1985            parse_quote!(std::fs::write(format!("{other}/a"), b)?;),
1986        ));
1987        // a directory and a file in it,
1988        assert!(clash(
1989            parse_quote!(std::fs::remove_dir_all(format!("{dir}/a"))?;),
1990            parse_quote!(std::fs::write(format!("{dir}/a/b"), b)?;),
1991        ));
1992        // the same template,
1993        assert!(clash(
1994            parse_quote!(std::fs::write(format!("{dir}/a"), a)?;),
1995            parse_quote!(std::fs::write(format!("{dir}/a"), b)?;),
1996        ));
1997        // a different format spec (`{dir:?}` is not `{dir}`),
1998        assert!(clash(
1999            parse_quote!(std::fs::write(format!("{dir:?}/a"), a)?;),
2000            parse_quote!(std::fs::write(format!("{dir}/b"), b)?;),
2001        ));
2002        // a computed placeholder, which may differ between calls,
2003        assert!(clash(
2004            parse_quote!(std::fs::write(format!("{}/a", self.base()), a)?;),
2005            parse_quote!(std::fs::write(format!("{}/b", self.base()), b)?;),
2006        ));
2007        // and a placeholder against text it may contain.
2008        assert!(clash(
2009            parse_quote!(std::fs::write(format!("{dir}/a"), a)?;),
2010            parse_quote!(std::fs::write("out/a", b)?;),
2011        ));
2012    }
2013
2014    #[test]
2015    fn service_verbs_on_receivers() {
2016        let d = effects(parse_quote!(api.delete(name).await?;));
2017        assert_eq!(d.len(), 1);
2018        assert!(d[0].writes() && d[0].domain == Domain::Service(Some("api".into())));
2019        let c = effects(parse_quote!(api.create(&obj).await?;));
2020        assert!(conflicts(&d, &c).is_some());
2021        // Reads commute.
2022        let g1 = effects(parse_quote!(let a = api.get("a").await?;));
2023        let g2 = effects(parse_quote!(let b = api.list().await?;));
2024        assert!(!g1[0].writes() && conflicts(&g1, &g2).is_none());
2025        // Different receivers are different services.
2026        let other = effects(parse_quote!(cache.put(k, v).await;));
2027        assert!(conflicts(&g1, &other).is_none());
2028    }
2029
2030    #[test]
2031    fn first_verb_in_a_chain_decides() {
2032        let get = effects(parse_quote!(let r = client.get(url).header(a, b).send().await?;));
2033        assert_eq!(get[0].kind, Kind::Read);
2034        let put = effects(parse_quote!(s3.put_object().bucket(b).key(k).send().await?;));
2035        assert_eq!(put[0].kind, Kind::Write);
2036        let tx = effects(parse_quote!(tx.send(v).await?;));
2037        assert!(tx[0].writes() && tx[0].ordered);
2038    }
2039
2040    #[test]
2041    fn files_by_path() {
2042        let w = effects(parse_quote!(tokio::fs::write("cfg.toml", b"x").await?;));
2043        let r = effects(parse_quote!(let s = tokio::fs::read_to_string("cfg.toml").await?;));
2044        let other = effects(parse_quote!(let s = tokio::fs::read_to_string("other.toml").await?;));
2045        let inside = effects(parse_quote!(let s = std::fs::read("out/a.txt")?;));
2046        let dir = effects(parse_quote!(std::fs::remove_dir_all("out")?;));
2047        assert!(w[0].domain == Domain::Fs && w[0].writes());
2048        assert!(conflicts(&w, &r).is_some());
2049        assert!(conflicts(&w, &other).is_none());
2050        assert!(conflicts(&dir, &inside).is_some());
2051        let unknown = effects(parse_quote!(let s = fs::read(&path).await?;));
2052        assert!(conflicts(&w, &unknown).is_some());
2053    }
2054
2055    #[test]
2056    fn processes_touch_everything() {
2057        let p = effects(parse_quote!(let out = Command::new("git").arg("pull").output().await?;));
2058        let r = effects(parse_quote!(let s = tokio::fs::read_to_string("x").await?;));
2059        assert!(p[0].domain == Domain::Process, "{p:?}");
2060        assert!(conflicts(&p, &r).is_some());
2061    }
2062
2063    #[test]
2064    fn unclassified_calls() {
2065        let s: syn::Stmt = parse_quote!(let r = client.request(req).await?;);
2066        let lax = of_stmt(&s, &Config::default());
2067        assert!(lax.effects.is_empty() && lax.unclassified == ["request"]);
2068        let strict = of_stmt(
2069            &s,
2070            &Config {
2071                strict: true,
2072                ..Default::default()
2073            },
2074        );
2075        assert!(strict.effects[0].domain == Domain::Unknown);
2076        // Plain constructors are not effects at all.
2077        assert!(effects(parse_quote!(let m = HashMap::new();)).is_empty());
2078    }
2079
2080    #[test]
2081    fn format_prefixes_separate_keys() {
2082        let a = effects(parse_quote!(client.set_account_data("m.megolm_backup.v1", "{}").await?;));
2083        let b = effects(
2084            parse_quote!(client.set_account_data(&format!("m.secret_storage.key.{id}"), "{}").await?;),
2085        );
2086        let c =
2087            effects(parse_quote!(client.set_account_data("m.secret_storage.key.k1", "{}").await?;));
2088        assert!(conflicts(&a, &b).is_none());
2089        assert!(conflicts(&b, &c).is_some());
2090    }
2091
2092    #[test]
2093    fn user_verbs() {
2094        let config = Config {
2095            writes: vec!["bump".into()],
2096            ..Default::default()
2097        };
2098        let s: syn::Stmt = parse_quote!(counter.bump_hits(1).await;);
2099        assert!(of_stmt(&s, &config).effects[0].writes());
2100    }
2101}