sealmap-rust 0.1.0

Pure-Rust (syn) frontend for sealmap: extracts symbols, relations and ordered call flows from Rust workspaces
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
//! Pass 2: resolve raw paths against the whole workspace and build the model.

use std::collections::{BTreeMap, BTreeSet};

use sealmap_frontend::{aggregate_calls, ids, lower};
use sealmap_model::{
    Call, Codebase, Confidence, Flow, Member, Relation, RelationKind, SourceFile, Symbol, SymbolId, SymbolKind,
};

use crate::raw::*;
use crate::{Diagnostic, RustOptions};

/// Crates whose items are never interesting as relation targets.
const STD_ROOTS: &[&str] = &["std", "core", "alloc"];

/// Names that resolve to the std prelude or primitives when not shadowed.
const PRELUDE: &[&str] = &[
    "Option",
    "Some",
    "None",
    "Result",
    "Ok",
    "Err",
    "Vec",
    "String",
    "Box",
    "ToString",
    "ToOwned",
    "Into",
    "From",
    "TryFrom",
    "TryInto",
    "Iterator",
    "IntoIterator",
    "DoubleEndedIterator",
    "ExactSizeIterator",
    "Extend",
    "Fn",
    "FnMut",
    "FnOnce",
    "Send",
    "Sync",
    "Sized",
    "Unpin",
    "Copy",
    "Clone",
    "Default",
    "Drop",
    "PartialEq",
    "Eq",
    "PartialOrd",
    "Ord",
    "AsRef",
    "AsMut",
    "Debug",
    "Display",
    "Hash",
    "Self",
    "self",
    "bool",
    "char",
    "str",
    "u8",
    "u16",
    "u32",
    "u64",
    "u128",
    "usize",
    "i8",
    "i16",
    "i32",
    "i64",
    "i128",
    "isize",
    "f32",
    "f64",
    "drop",
    "panic",
];

/// Method names so common in std that an unknown receiver must not be
/// matched to an internal method of the same name.
const COMMON_METHODS: &[&str] = &[
    "new",
    "default",
    "clone",
    "get",
    "get_mut",
    "insert",
    "remove",
    "push",
    "pop",
    "len",
    "is_empty",
    "iter",
    "iter_mut",
    "into_iter",
    "map",
    "and_then",
    "unwrap",
    "expect",
    "ok",
    "err",
    "collect",
    "to_string",
    "to_owned",
    "into",
    "from",
    "as_ref",
    "as_str",
    "contains",
    "extend",
    "join",
    "split",
    "parse",
    "write",
    "read",
    "send",
    "recv",
    "lock",
    "fmt",
    "eq",
    "cmp",
    "hash",
    "next",
    "take",
    "filter",
    "find",
    "first",
    "last",
    "clear",
    "entry",
    "keys",
    "values",
    "run",
    "start",
    "stop",
    "close",
    "open",
    "flush",
    "build",
    "update",
    "apply",
    "file_name",
    "extension",
    "path",
    "exists",
    "display",
    "to_str",
    "as_bytes",
    "trim",
    "lines",
    "chars",
    "bytes",
    "starts_with",
    "ends_with",
    "replace",
    "find_map",
    "position",
    "max",
    "min",
    "sum",
    "count",
    "rev",
    "zip",
    "skip",
    "chain",
    "flatten",
    "cloned",
    "copied",
    "sort",
    "dedup",
    "retain",
    "drain",
    "truncate",
    "with_capacity",
    "capacity",
    "reserve",
    "as_slice",
    "to_vec",
    "borrow",
    "borrow_mut",
    "set",
    "reset",
    "load",
    "store",
    "call",
    "handle",
    "process",
    "execute",
    "connect",
    "kind",
    "name",
    "id",
    "value",
    "key",
    "data",
    "size",
    "is_some",
    "is_none",
    "is_ok",
    "is_err",
    "map_err",
    "or_else",
    "unwrap_or",
    "unwrap_or_default",
    "unwrap_or_else",
    "as_mut",
];

pub(crate) fn build(name: &str, files: Vec<RawFile>, opts: &RustOptions) -> (Codebase, Vec<Diagnostic>) {
    let r = Resolver::new(&files);
    let mut cb = Codebase::new(name);
    let mut diags = Vec::new();

    for f in &files {
        if let Some(e) = &f.error {
            diags.push(Diagnostic { file: f.path.clone(), message: e.clone() });
        }
    }

    // Modules and items first, so field types are resolved before flows.
    for f in &files {
        cb.add_file(SourceFile {
            path: f.path.clone(),
            language: "rust".into(),
            module: ids::module_id(&f.role.module),
            hash: f.hash.clone(),
            lines: f.text_lines,
        });
        for m in &f.modules {
            let id = ids::module_id(&m.path);
            let mut s =
                Symbol::new(id.clone(), m.path.last().cloned().unwrap_or_default(), SymbolKind::Module, f.path.clone());
            s.parent = ids::parent_module_id(&m.path);
            s.span = m.span;
            s.doc = m.doc.clone();
            s.visibility = m.vis.clone();
            s.tags = m.tags.clone();
            cb.add_symbol(s);
            let module = ids::module_path(&m.path);
            for u in &m.uses {
                if u.alias == "*" {
                    if let Some(t) = r.resolve_internal(&module, &u.target, None) {
                        cb.add_relation(Relation::new(id.clone(), t, RelationKind::Imports, Confidence::Exact));
                    }
                    continue;
                }
                let (t, c) = r.resolve(&module, &u.target, None);
                if keep_ref(&t) {
                    cb.add_relation(Relation::new(id.clone(), t, RelationKind::Imports, c));
                }
            }
        }
        for it in &f.items {
            let module = ids::module_path(&it.module);
            let id = ids::item_id(&module, &it.name);
            let mut s = Symbol::new(id.clone(), &it.name, it.kind, f.path.clone());
            s.visibility = it.vis.clone();
            s.span = it.span;
            s.signature = it.signature.clone();
            s.doc = it.doc.clone();
            s.generics = it.generics.clone();
            s.tags = it.tags.clone();
            s.members = it.members.iter().map(|m| r.member(&module, m, Some(&id))).collect();
            for m in &s.members {
                for t in &m.refs {
                    let c = if cb_has(&r, t) { Confidence::Exact } else { Confidence::External };
                    cb.add_relation(Relation::new(id.clone(), t.clone(), RelationKind::FieldType, c));
                }
            }
            for st in &it.supertraits {
                let (t, c) = r.resolve(&module, st, None);
                if keep_ref(&t) {
                    cb.add_relation(Relation::new(id.clone(), t, RelationKind::Extends, c));
                }
            }
            r.add_uses(&mut cb, &id, &module, &it.sig_refs, Some(&id));
            let ctx = FlowCtx { module: &module, self_ty: (it.kind == SymbolKind::Trait).then_some(&id) };
            if !it.flow.is_empty() {
                s.flow = r.flow(&ctx, &it.flow, opts);
            }
            for m in &it.methods {
                let mid = ids::method_id(&id, None, &m.name);
                let ms = r.method_symbol(&mid, &id, m, f, &ctx, opts, &mut cb);
                cb.add_symbol(ms);
            }
            cb.add_symbol(s);
        }
        for imp in &f.impls {
            let module = ids::module_path(&imp.module);
            let Some(self_segs) = &imp.self_ty else { continue };
            let (ty, _) = r.resolve(&module, self_segs, None);
            let trait_seg = imp.trait_.as_ref().map(|(segs, disp)| {
                let (t, c) = r.resolve(&module, segs, Some(&ty));
                if keep_ref(&t) || r.internal.contains(&t) {
                    cb.add_relation(Relation::new(ty.clone(), t, RelationKind::Implements, c));
                }
                ids::trait_impl_segment(disp)
            });
            let ctx = FlowCtx { module: &module, self_ty: Some(&ty) };
            for m in &imp.methods {
                let mid = ids::method_id(&ty, trait_seg.as_deref(), &m.name);
                let mut ms = r.method_symbol(&mid, &ty, m, f, &ctx, opts, &mut cb);
                if let Some((_, disp)) = &imp.trait_ {
                    ms.tags.insert(0, format!("impl {disp}"));
                }
                cb.add_symbol(ms);
            }
        }
    }

    aggregate_calls(&mut cb);
    (cb, diags)
}

fn cb_has(r: &Resolver, id: &SymbolId) -> bool {
    r.internal.contains(id)
}

/// Keep a resolved reference as a relation target? Drops std and prelude.
fn keep_ref(id: &SymbolId) -> bool {
    let first = id.as_str().split("::").next().unwrap_or("");
    !STD_ROOTS.contains(&first) && !PRELUDE.contains(&first)
}

struct FlowCtx<'a> {
    module: &'a str,
    self_ty: Option<&'a SymbolId>,
}

/// Lookup tables built from all raw files before any resolution.
struct Resolver {
    crates: BTreeSet<String>,
    /// module id → item name → id (items, submodules).
    items: BTreeMap<String, BTreeMap<String, SymbolId>>,
    /// module id → `use` entries.
    uses: BTreeMap<String, Vec<RawUse>>,
    /// Every internal symbol id that will exist (types, fns, modules, methods).
    internal: BTreeSet<SymbolId>,
    /// type id → field name → raw refs with defining module.
    fields: BTreeMap<SymbolId, (String, BTreeMap<String, Vec<Segs>>)>,
    /// type id → method name → method id (inherent first).
    methods: BTreeMap<SymbolId, BTreeMap<String, SymbolId>>,
    /// method name → ids, for unknown receivers.
    by_name: BTreeMap<String, BTreeSet<SymbolId>>,
    /// type id → implemented trait ids.
    impls: BTreeMap<SymbolId, BTreeSet<SymbolId>>,
    /// trait id → method names (required and provided).
    trait_methods: BTreeMap<SymbolId, BTreeSet<String>>,
    /// module id → internal modules it glob-imports (`use a::b::*`), in
    /// source order. Resolved once, without consulting globs, so a name
    /// lookup never re-enters glob resolution.
    globs: BTreeMap<String, Vec<String>>,
}

impl Resolver {
    fn new(files: &[RawFile]) -> Self {
        let mut r = Resolver {
            crates: files.iter().map(|f| f.role.crate_name.clone()).collect(),
            items: BTreeMap::new(),
            uses: BTreeMap::new(),
            internal: BTreeSet::new(),
            fields: BTreeMap::new(),
            methods: BTreeMap::new(),
            by_name: BTreeMap::new(),
            impls: BTreeMap::new(),
            trait_methods: BTreeMap::new(),
            globs: BTreeMap::new(),
        };
        for f in files {
            for m in &f.modules {
                let id = ids::module_path(&m.path);
                r.internal.insert(SymbolId::new(&id));
                r.uses.entry(id.clone()).or_default().extend(m.uses.iter().cloned());
                if m.path.len() > 1 {
                    let parent = ids::module_path(&m.path[..m.path.len() - 1]);
                    r.items
                        .entry(parent)
                        .or_default()
                        .insert(m.path.last().cloned().unwrap_or_default(), SymbolId::new(&id));
                }
            }
            for it in &f.items {
                let module = ids::module_path(&it.module);
                let id = ids::item_id(&module, &it.name);
                r.internal.insert(id.clone());
                r.items.entry(module.clone()).or_default().entry(it.name.clone()).or_insert(id.clone());
                if matches!(it.kind, SymbolKind::Struct | SymbolKind::Union | SymbolKind::Enum) {
                    let f = it.members.iter().map(|m| (m.name.clone(), m.refs.clone())).collect();
                    r.fields.insert(id.clone(), (module.clone(), f));
                }
                if it.kind == SymbolKind::Trait {
                    let names = r.trait_methods.entry(id.clone()).or_default();
                    for m in &it.members {
                        names.insert(m.name.clone());
                    }
                    for m in &it.methods {
                        names.insert(m.name.clone());
                        let mid = ids::method_id(&id, None, &m.name);
                        r.internal.insert(mid.clone());
                        r.methods.entry(id.clone()).or_default().insert(m.name.clone(), mid.clone());
                        r.by_name.entry(m.name.clone()).or_default().insert(mid);
                    }
                }
            }
        }
        // Glob targets are resolved up front into a table, so a name lookup
        // is a bounded graph search (`glob`) instead of a re-entrant `walk`,
        // which was exponential in the number of globs per module. Round 0
        // resolves targets without globs; round 1 lets a glob target itself
        // be found through round-0 globs (`use super::*; use inner::*;`).
        for round in 0..2 {
            let mut globs: BTreeMap<String, Vec<String>> = BTreeMap::new();
            for (module, uses) in &r.uses {
                for u in uses.iter().filter(|u| u.alias == "*") {
                    if let Some(t) = r.walk(module, &u.target, None, 0, round > 0) {
                        let t = t.as_str().to_owned();
                        if r.items.contains_key(&t) && !globs.get(module).is_some_and(|v| v.contains(&t)) {
                            globs.entry(module.clone()).or_default().push(t);
                        }
                    }
                }
            }
            r.globs = globs;
        }
        // Impl methods need item tables to resolve self types; do inherent
        // impls before trait impls so inherent methods win name lookups.
        for pass_trait in [false, true] {
            for f in files {
                for imp in &f.impls {
                    if imp.trait_.is_some() != pass_trait {
                        continue;
                    }
                    let module = ids::module_path(&imp.module);
                    let Some(segs) = &imp.self_ty else { continue };
                    let (ty, _) = r.resolve(&module, segs, None);
                    let tseg = imp.trait_.as_ref().map(|(segs, disp)| {
                        let (t, _) = r.resolve(&module, segs, Some(&ty));
                        r.impls.entry(ty.clone()).or_default().insert(t);
                        ids::trait_impl_segment(disp)
                    });
                    for m in &imp.methods {
                        let mid = ids::method_id(&ty, tseg.as_deref(), &m.name);
                        r.internal.insert(mid.clone());
                        r.methods.entry(ty.clone()).or_default().entry(m.name.clone()).or_insert(mid.clone());
                        r.by_name.entry(m.name.clone()).or_default().insert(mid);
                    }
                }
            }
        }
        r
    }

    /// Resolve `segs` as written in `module`. Returns the canonical id and how
    /// sure we are. Unresolvable paths come back as their literal text with
    /// [`Confidence::External`].
    fn resolve(&self, module: &str, segs: &[String], self_ty: Option<&SymbolId>) -> (SymbolId, Confidence) {
        match self.walk(module, segs, self_ty, 0, true) {
            Some(id) if self.internal.contains(&id) => (id, Confidence::Exact),
            Some(id) => {
                let root = id.as_str().split("::").next().unwrap_or("");
                if self.crates.contains(root) { (id, Confidence::Inferred) } else { (id, Confidence::External) }
            }
            None => (ids::path_id(segs), Confidence::External),
        }
    }

    fn resolve_internal(&self, module: &str, segs: &[String], self_ty: Option<&SymbolId>) -> Option<SymbolId> {
        self.walk(module, segs, self_ty, 0, true).filter(|id| self.internal.contains(id))
    }

    /// `use_globs` is false only while the glob table itself is being built.
    fn walk(
        &self,
        module: &str,
        segs: &[String],
        self_ty: Option<&SymbolId>,
        depth: u8,
        use_globs: bool,
    ) -> Option<SymbolId> {
        if depth > 8 || segs.is_empty() {
            return None;
        }
        let first = segs[0].as_str();
        let mut rest = &segs[1..];
        let base: SymbolId = match first {
            "crate" => SymbolId::new(module.split("::").next().unwrap_or(module)),
            "self" => SymbolId::new(module),
            "super" => {
                let mut m = SymbolId::new(module).parent().unwrap_or_else(|| SymbolId::new(module));
                while rest.first().map(String::as_str) == Some("super") {
                    m = m.parent().unwrap_or(m);
                    rest = &rest[1..];
                }
                m
            }
            "Self" => self_ty?.clone(),
            name => {
                if let Some(id) = self.items.get(module).and_then(|m| m.get(name)) {
                    id.clone()
                } else if let Some(u) = self
                    .uses
                    .get(module)
                    .and_then(|us| us.iter().find(|u| u.alias == name && u.target.as_slice() != [name]))
                {
                    // Re-resolve the import target, then append the rest.
                    // (`use foo;` — target == alias — would only re-enter
                    // itself; it falls through to the crate check below.)
                    let mut full = u.target.clone();
                    full.extend(rest.iter().cloned());
                    return self
                        .walk(module, &full, self_ty, depth + 1, use_globs)
                        .or_else(|| Some(ids::path_id(&full)));
                } else if let Some(id) = use_globs.then(|| self.glob(module, name)).flatten() {
                    id
                } else if self.crates.contains(name) {
                    SymbolId::new(name)
                } else {
                    return Some(ids::path_id(segs));
                }
            }
        };
        let mut cur = base;
        for (i, seg) in rest.iter().enumerate() {
            let key = cur.as_str().to_owned();
            if let Some(id) = self.items.get(&key).and_then(|m| m.get(seg)) {
                cur = id.clone();
            } else if let Some(id) = self.methods.get(&cur).and_then(|m| m.get(seg)) {
                cur = id.clone();
            } else if self.uses.get(&key).is_some_and(|us| us.iter().any(|u| &u.alias == seg)) {
                // `pub use` re-export inside an internal module.
                return self.walk(&key, &rest[i..], self_ty, depth + 1, use_globs);
            } else {
                cur = cur.child(seg);
            }
        }
        Some(cur)
    }

    /// Find `name` through `module`'s glob imports, following glob chains
    /// (`pub use inner::*` re-exports) breadth-first. Each module is visited
    /// at most once, so cyclic globs (`a: use b::*`, `b: use a::*`) are
    /// harmless and the cost is linear in the glob graph.
    fn glob(&self, module: &str, name: &str) -> Option<SymbolId> {
        let mut queue: std::collections::VecDeque<&str> = self.globs.get(module)?.iter().map(String::as_str).collect();
        let mut seen: BTreeSet<&str> = BTreeSet::from([module]);
        while let Some(m) = queue.pop_front() {
            if !seen.insert(m) {
                continue;
            }
            if let Some(id) = self.items.get(m).and_then(|items| items.get(name)) {
                return Some(id.clone());
            }
            if let Some(next) = self.globs.get(m) {
                queue.extend(next.iter().map(String::as_str));
            }
        }
        None
    }

    /// Resolve a list of raw type refs to kept relation targets.
    fn refs(&self, module: &str, raw: &[Segs], self_ty: Option<&SymbolId>) -> Vec<SymbolId> {
        let mut out = Vec::new();
        for segs in raw {
            // Associated types (`Self::Error`, `T::Output`) are not symbols.
            if segs.len() > 1 && (segs[0] == "Self" || is_generic_param(&segs[0])) {
                continue;
            }
            if segs.len() == 1
                && (PRELUDE.contains(&segs[0].as_str()) || is_generic_param(&segs[0]))
                && !self.local(module, &segs[0])
            {
                continue;
            }
            let (id, _) = self.resolve(module, segs, self_ty);
            if (keep_ref(&id) || self.internal.contains(&id)) && Some(&id) != self_ty && !out.contains(&id) {
                out.push(id);
            }
        }
        out
    }

    /// `true` if `name` is defined or imported in `module`.
    fn local(&self, module: &str, name: &str) -> bool {
        self.items.get(module).is_some_and(|m| m.contains_key(name))
            || self.uses.get(module).is_some_and(|us| us.iter().any(|u| u.alias == name))
    }

    fn member(&self, module: &str, m: &RawMember, owner: Option<&SymbolId>) -> Member {
        Member {
            name: m.name.clone(),
            kind: m.kind,
            ty: m.ty.clone(),
            visibility: m.vis.clone(),
            span: m.span,
            refs: self.refs(module, &m.refs, owner),
        }
    }

    fn add_uses(&self, cb: &mut Codebase, from: &SymbolId, module: &str, raw: &[Segs], self_ty: Option<&SymbolId>) {
        for t in self.refs(module, raw, self_ty) {
            let c = if self.internal.contains(&t) { Confidence::Exact } else { Confidence::External };
            cb.add_relation(Relation::new(from.clone(), t, RelationKind::Uses, c));
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn method_symbol(
        &self,
        id: &SymbolId,
        parent: &SymbolId,
        m: &RawFn,
        f: &RawFile,
        ctx: &FlowCtx<'_>,
        opts: &RustOptions,
        cb: &mut Codebase,
    ) -> Symbol {
        let mut s = Symbol::new(id.clone(), &m.name, SymbolKind::Method, f.path.clone());
        s.parent = Some(parent.clone());
        s.visibility = m.vis.clone();
        s.span = m.span;
        s.signature = Some(m.signature.clone());
        s.doc = m.doc.clone();
        s.generics = m.generics.clone();
        s.tags = m.tags.clone();
        self.add_uses(cb, id, ctx.module, &m.sig_refs, ctx.self_ty);
        if !m.flow.is_empty() {
            s.flow = self.flow(ctx, &m.flow, opts);
        }
        s
    }

    fn flow(&self, ctx: &FlowCtx<'_>, raw: &[RawStep], opts: &RustOptions) -> Option<Flow> {
        lower::lower_flow(raw, &mut |c: &RawCall| self.call(ctx, c, opts))
    }

    fn call(&self, ctx: &FlowCtx<'_>, c: &RawCall, opts: &RustOptions) -> Option<Call> {
        let (target, confidence) = match &c.callee {
            Callee::Path(segs) => {
                // `drop(x)`, `Vec::new()`, `String::from(..)`: prelude, not code.
                if PRELUDE.contains(&segs[0].as_str()) && !self.local(ctx.module, &segs[0]) {
                    return None;
                }
                let (id, c) = self.resolve(ctx.module, segs, ctx.self_ty);
                // A bare name that is neither defined, imported nor a crate is
                // a local closure or function pointer: not a symbol.
                if segs.len() == 1 && c == Confidence::External && !self.local(ctx.module, &segs[0]) {
                    return None;
                }
                (id, c)
            }
            Callee::Method { recv, name } => self.method(ctx, recv, name)?,
        };
        let keep = opts.external_calls.keeps(confidence, || {
            let root = target.as_str().split("::").next().unwrap_or("");
            // External roots that look like crates (lower-case); unresolved
            // type names are not dependencies.
            keep_ref(&target) && root.starts_with(|c: char| c.is_ascii_lowercase()) && !self.crates.contains(root)
        });
        keep.then(|| c.to_call(target, confidence))
    }

    /// Resolve a method call. Returns `None` only when the call should be
    /// dropped outright.
    fn method(&self, ctx: &FlowCtx<'_>, recv: &Recv, name: &str) -> Option<(SymbolId, Confidence)> {
        let ty = match recv {
            Recv::SelfValue => ctx.self_ty.cloned(),
            Recv::SelfField(field) => {
                let found = ctx.self_ty.and_then(|ty| self.fields.get(ty)).and_then(|(m, f)| Some((m, f.get(field)?)));
                match found {
                    Some((module, refs)) => self.receiver_type(module, refs, None),
                    None => return Some(self.by_name_only(name)),
                }
            }
            Recv::Typed(refs) => self.receiver_type(ctx.module, refs, ctx.self_ty),
            Recv::Untyped => return Some(self.by_name_only(name)),
            Recv::Unknown => None,
        };
        let Some(ty) = ty else { return Some((ids::unresolved_method_id(name), Confidence::External)) };
        if let Some(id) = self.methods.get(&ty).and_then(|m| m.get(name)) {
            return Some((id.clone(), Confidence::Exact));
        }
        if self.trait_methods.get(&ty).is_some_and(|n| n.contains(name)) {
            return Some((ids::method_id(&ty, None, name), Confidence::Exact));
        }
        for tr in self.impls.get(&ty).into_iter().flatten() {
            if self.trait_methods.get(tr).is_some_and(|n| n.contains(name)) {
                return Some((ids::method_id(tr, None, name), Confidence::Exact));
            }
        }
        // Known type, method not defined in the codebase: a derived or std
        // trait method on an internal type, or a dependency's method.
        Some((ids::method_id(&ty, None, name), Confidence::External))
    }

    /// The type a method is called on, from the declared type's paths
    /// (outermost first). Smart pointers are looked through; any other
    /// wrapper (`Vec`, `Option`, `Mutex`, ...) *is* the receiver.
    fn receiver_type(&self, module: &str, refs: &[Segs], self_ty: Option<&SymbolId>) -> Option<SymbolId> {
        const DEREF: &[&str] =
            &["Box", "Arc", "Rc", "Cow", "Pin", "Ref", "RefMut", "MutexGuard", "RwLockReadGuard", "RwLockWriteGuard"];
        for segs in refs {
            let last = segs.last()?.as_str();
            if segs.len() == 1 && is_generic_param(last) {
                return None;
            }
            let (id, _) = self.resolve(module, segs, self_ty);
            if DEREF.contains(&last) && !self.internal.contains(&id) {
                continue;
            }
            return Some(id);
        }
        None
    }

    /// Unknown receiver: accept a unique, distinctive internal method name.
    fn by_name_only(&self, name: &str) -> (SymbolId, Confidence) {
        if !COMMON_METHODS.contains(&name) {
            if let Some(ids) = self.by_name.get(name) {
                if ids.len() == 1 {
                    let id = ids.iter().next().cloned().unwrap_or_else(|| SymbolId::new(name));
                    return (id, Confidence::Inferred);
                }
            }
        }
        (ids::unresolved_method_id(name), Confidence::External)
    }
}

/// Single upper-case letters (and `T1`-style names) are almost always generic
/// parameters.
fn is_generic_param(s: &str) -> bool {
    let mut cs = s.chars();
    matches!(cs.next(), Some(c) if c.is_ascii_uppercase()) && cs.all(|c| c.is_ascii_digit())
}