nornir 0.5.0

Companion to cargo: dependency tracking, release gating, deploy, benchmarks, and documentation assembly. Project-agnostic.
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
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
//! RESOLVED knowledge map — ingest of a `rust-analyzer scip` index (task #24).
//!
//! `rust-analyzer scip .` resolves *everything* the syntactic `syn` scan in
//! [`super::symbols`] cannot: trait-method dispatch, macro-generated items,
//! type-directed method resolution, re-exports and generic-impl expansion. It
//! emits a portable **SCIP** (`index.scip`) protobuf — a list of `Document`s,
//! each with `Occurrence`s (every defs/refs token, with a globally-unique
//! RESOLVED `symbol` moniker + a role bitset) and `SymbolInformation` (the
//! definitions, with kind + display name).
//!
//! This module reads that index (via the `scip` crate's protobuf types) into
//! flat [`ScipRow`]s and persists them to the `scip_occurrences` warehouse
//! table **SHA-keyed** — so the resolved map is HISTORIZED (which r-a never is),
//! giving find-usages that are both IDE-precise *and* time-travelable.
//!
//! Gated behind the `scip` cargo feature so default builds pay nothing.

use std::path::Path;

use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use scip::types::{symbol_information, Index, SymbolRole};
use uuid::Uuid;

/// One ingested SCIP occurrence — a single resolved defs/ref token.
#[derive(Debug, Clone, serde::Serialize, PartialEq, Eq)]
pub struct ScipRow {
    /// The RESOLVED SCIP symbol moniker (globally unique). For a local symbol
    /// it is `local N`; for a global it encodes scheme + package + descriptors.
    pub symbol: String,
    /// Decoded role label(s) — `definition`, `reference`, `import`, `write`,
    /// `read`, `generated`, `test` — joined by `+` when several bits are set.
    pub role: String,
    /// `true` when the `Definition` role bit is set (the defining occurrence).
    pub is_definition: bool,
    /// Short display name from the matching `SymbolInformation`, when present.
    pub display_name: String,
    /// SCIP `SymbolInformation.Kind` (`Function`, `Method`, `Struct`, `Trait`,
    /// …) when the symbol is defined in this index; `""` for refs to externals.
    pub kind: String,
    /// Document-relative source path (forward-slashed).
    pub file: String,
    /// 1-based line of the occurrence start (SCIP ranges are 0-based).
    pub start_line: u32,
    /// 1-based column of the occurrence start.
    pub start_col: u32,
    /// 1-based START line of this occurrence's `enclosing_range` — the span of
    /// the whole defining item (fn/method body). Only meaningful for DEFINITION
    /// occurrences of a Function/Method (else `0`). This is what lets us decide
    /// WHICH function CONTAINS a reference (i.e. who the caller is) — see
    /// [`scip_call_edges`].
    pub enc_start_line: u32,
    /// 1-based END line of the `enclosing_range` (inclusive in our containment
    /// test); `0` when absent.
    pub enc_end_line: u32,
}

/// A whole ingested SCIP index, ready to persist.
#[derive(Debug, Default)]
pub struct ScipScan {
    pub snapshot_id: Uuid,
    pub ts: DateTime<Utc>,
    pub repo: String,
    pub git_sha: String,
    pub rows: Vec<ScipRow>,
}

/// Decode the SCIP `symbol_roles` bitset into a human label.
fn decode_roles(bits: i32) -> (String, bool) {
    let mut labels = Vec::new();
    let is_def = bits & SymbolRole::Definition as i32 != 0;
    if is_def {
        labels.push("definition");
    }
    if bits & SymbolRole::Import as i32 != 0 {
        labels.push("import");
    }
    if bits & SymbolRole::WriteAccess as i32 != 0 {
        labels.push("write");
    }
    if bits & SymbolRole::ReadAccess as i32 != 0 {
        labels.push("read");
    }
    if bits & SymbolRole::Generated as i32 != 0 {
        labels.push("generated");
    }
    if bits & SymbolRole::Test as i32 != 0 {
        labels.push("test");
    }
    if labels.is_empty() {
        // No role bit set ⇒ a plain reference (the common case for usages).
        labels.push("reference");
    }
    (labels.join("+"), is_def)
}

/// SCIP `SymbolInformation.Kind` enum → a short string for the warehouse.
fn kind_label(kind: symbol_information::Kind) -> &'static str {
    use symbol_information::Kind::*;
    match kind {
        Function => "Function",
        Method => "Method",
        StaticMethod => "StaticMethod",
        Struct => "Struct",
        Trait => "Trait",
        TraitMethod => "TraitMethod",
        Enum => "Enum",
        EnumMember => "EnumMember",
        Field => "Field",
        Module => "Module",
        Macro => "Macro",
        TypeAlias => "TypeAlias",
        Constant => "Constant",
        Variable => "Variable",
        Parameter => "Parameter",
        TypeParameter => "TypeParameter",
        AssociatedType => "AssociatedType",
        SelfParameter => "SelfParameter",
        _ => "Other",
    }
}

/// Parse a SCIP index file (`index.scip`) into flat rows, tagged with `repo`
/// and `git_sha`. This is the BUILD-FREE half: it does not run rust-analyzer,
/// it only reads the protobuf the (separately invoked) `rust-analyzer scip`
/// produced — so the parse path is unit-testable against a hand-made index.
pub fn ingest_index_file(
    index_path: &Path,
    repo: &str,
    git_sha: &str,
    snapshot_id: Uuid,
    ts: DateTime<Utc>,
) -> Result<ScipScan> {
    let bytes = std::fs::read(index_path)
        .with_context(|| format!("reading SCIP index {}", index_path.display()))?;
    let index: Index = protobuf_parse(&bytes)?;
    Ok(ingest_index(index, repo, git_sha, snapshot_id, ts))
}

/// Resolve a cargo workspace at `repo_root` into a [`ScipScan`] by spawning
/// `rust-analyzer scip` (the subprocess path) and parsing the emitted index.
///
/// This is the plain-`scip`-feature resolve path (no `ra-ingest` in-process
/// linkage): it shells out to the `rust-analyzer` rustup proxy, which COMPILES
/// the workspace and writes `index.scip`, then reads it back via
/// [`ingest_index_file`]. Used by the monitor's resolved-ingest step when the
/// faster in-process `ra_ingest::ingest_in_process` is not compiled in. The
/// emitted `index.scip` is written into the OS temp dir and removed after parse.
pub fn ingest_via_rust_analyzer(
    repo_root: &Path,
    repo: &str,
    git_sha: &str,
    snapshot_id: Uuid,
    ts: DateTime<Utc>,
) -> Result<ScipScan> {
    let out = std::env::temp_dir().join(format!("nornir-scip-{snapshot_id}.scip"));
    let status = std::process::Command::new("rust-analyzer")
        .arg("scip")
        .arg(repo_root)
        .arg("--output")
        .arg(&out)
        .status()
        .context("spawning rust-analyzer (install: `rustup component add rust-analyzer`)")?;
    if !status.success() {
        let _ = std::fs::remove_file(&out);
        anyhow::bail!("rust-analyzer scip failed ({status})");
    }
    let scan = ingest_index_file(&out, repo, git_sha, snapshot_id, ts);
    let _ = std::fs::remove_file(&out);
    scan
}

/// Decode the protobuf `Index` message from raw bytes.
fn protobuf_parse(bytes: &[u8]) -> Result<Index> {
    use protobuf::Message;
    Index::parse_from_bytes(bytes).context("parsing SCIP protobuf Index")
}

/// Map an in-memory [`Index`] to rows. Split out from file reading so the parse
/// → rows mapping is testable against a programmatically-built index.
pub fn ingest_index(
    index: Index,
    repo: &str,
    git_sha: &str,
    snapshot_id: Uuid,
    ts: DateTime<Utc>,
) -> ScipScan {
    let mut rows = Vec::new();
    for doc in &index.documents {
        // Build a per-document symbol → (kind, display_name) lookup from the
        // document's `SymbolInformation` (the definitions live here).
        let mut info: std::collections::HashMap<&str, (&'static str, &str)> =
            std::collections::HashMap::new();
        for si in &doc.symbols {
            let kind = si
                .kind
                .enum_value()
                .map(kind_label)
                .unwrap_or("Other");
            info.insert(si.symbol.as_str(), (kind, si.display_name.as_str()));
        }

        for occ in &doc.occurrences {
            // SCIP range is [startLine, startCol, endLine, endCol] or a
            // 3-element [startLine, startCol, endCol] when single-line.
            let (line, col) = match occ.range.as_slice() {
                [l, c, ..] => (*l, *c),
                _ => continue,
            };
            let (role, is_definition) = decode_roles(occ.symbol_roles);
            let (kind, display_name) = info
                .get(occ.symbol.as_str())
                .map(|(k, d)| ((*k).to_string(), (*d).to_string()))
                .unwrap_or_default();
            // Capture the enclosing-range span ONLY for the DEFINITION occurrence
            // of a Function/Method — that span is the caller's body, the basis for
            // the resolved containment-based call-edge build in `scip_call_edges`.
            // SCIP `enclosing_range` is `[startLine, startCol, endLine, endCol]`
            // (or a 3-elem `[startLine, startCol, endCol]` single-line form). We
            // keep only the line bounds, 1-based; `0` when absent / not a fn-def.
            let (enc_start_line, enc_end_line) = if is_definition
                && matches!(kind.as_str(), "Function" | "Method" | "StaticMethod" | "TraitMethod")
            {
                match occ.enclosing_range.as_slice() {
                    // [startLine, startCol, endLine, endCol] (multi-line form).
                    [sl, _sc, el, _ec, ..] => (
                        (*sl).max(0) as u32 + 1,
                        (*el).max(0) as u32 + 1,
                    ),
                    // [startLine, startCol, endCol] — single-line body.
                    [sl, _sc, _ec] => {
                        let l = (*sl).max(0) as u32 + 1;
                        (l, l)
                    }
                    _ => (0, 0),
                }
            } else {
                (0, 0)
            };
            rows.push(ScipRow {
                symbol: occ.symbol.clone(),
                role,
                is_definition,
                display_name,
                kind,
                file: doc.relative_path.clone(),
                // SCIP positions are 0-based; present 1-based like syn rows.
                start_line: (line.max(0) as u32).saturating_add(1),
                start_col: (col.max(0) as u32).saturating_add(1),
                enc_start_line,
                enc_end_line,
            });
        }
    }
    ScipScan {
        snapshot_id,
        ts,
        repo: repo.to_string(),
        git_sha: git_sha.to_string(),
        rows,
    }
}

/// In-memory queries over an ingested SCIP scan — the RESOLVED counterpart to
/// [`super::query::KnowledgeView`]. Because every reference carries the *same*
/// resolved `symbol` moniker as its definition, find-usages is an exact symbol
/// match (no last-segment name heuristic, no cross-name collisions).
impl ScipScan {
    /// The defining occurrence(s) of every symbol whose display name or symbol
    /// moniker contains `pattern` (case-insensitive).
    pub fn definitions_matching<'a>(&'a self, pattern: &str) -> Vec<&'a ScipRow> {
        let p = pattern.to_lowercase();
        self.rows
            .iter()
            .filter(|r| r.is_definition)
            .filter(|r| {
                r.display_name.to_lowercase().contains(&p)
                    || r.symbol.to_lowercase().contains(&p)
            })
            .collect()
    }

    /// Resolve `pattern` to the unique symbol moniker(s) it *defines*. Used to
    /// turn a human name into the precise key for [`Self::usages_of`].
    pub fn resolve_symbols(&self, pattern: &str) -> Vec<String> {
        let mut syms: Vec<String> =
            self.definitions_matching(pattern).iter().map(|r| r.symbol.clone()).collect();
        syms.sort();
        syms.dedup();
        syms
    }

    /// Every *reference* occurrence of an exact resolved `symbol` — IDE-grade
    /// find-usages. Excludes the definition itself.
    pub fn usages_of<'a>(&'a self, symbol: &str) -> Vec<&'a ScipRow> {
        self.rows
            .iter()
            .filter(|r| r.symbol == symbol && !r.is_definition)
            .collect()
    }

    /// All occurrences (defs + refs) of an exact resolved `symbol`.
    pub fn occurrences_of<'a>(&'a self, symbol: &str) -> Vec<&'a ScipRow> {
        self.rows.iter().filter(|r| r.symbol == symbol).collect()
    }
}

/// Build RESOLVED caller → callee call edges from an ingested SCIP scan.
///
/// This is the FULL-WIRING half of the resolved knowledge map: where the syn
/// [`super::query::KnowledgeView::call_path`] records callees as bare *idents*
/// (which collide across name-sharing functions, and miss cross-crate bin→lib
/// calls entirely), SCIP gives every reference its globally-unique RESOLVED
/// `symbol` moniker. We turn those references into edges by *containment*:
///
///  1. Index every Function/Method DEFINITION occurrence that carries an
///     `enclosing_range` (its body span) by file.
///  2. For every NON-definition REFERENCE occurrence to a Function/Method
///     symbol, find the def in the SAME `file` whose `[enc_start_line,
///     enc_end_line]` CONTAINS the reference's `start_line`. That def is the
///     CALLER; the referenced symbol is the CALLEE. We pick the INNERMOST
///     containing def (smallest span) so nested fns/closures attribute the call
///     to the tightest enclosing body.
///
/// The caller is recorded by its resolved `display_name` (falling back to the
/// moniker) and the callee likewise — both keyed off the resolved symbol, so a
/// query of `name` cannot fold an unrelated `Config#name` field into the same
/// bucket (the syn last-segment match's flaw).
///
/// LIMITATION: containment is necessarily SAME-FILE. SCIP's `enclosing_range`
/// is local to the document the def lives in, so a reference whose enclosing
/// def is in *another file* cannot be attributed here (it produces no edge
/// rather than a wrong one). In practice a call site and its enclosing fn are
/// always in the same file, so this only drops references that appear outside
/// any fn body (e.g. module-level), which are not calls anyway.
///
/// SAME-SCAN only: see [`scip_call_edges_with`] for the cross-binary (cross-repo
/// / cross-scan) MONIKER JOIN that resolves a callee DEFINED IN ANOTHER scan.
#[cfg(feature = "scip")]
pub fn scip_call_edges(scan: &ScipScan) -> Vec<super::symbols::CallEdgeRow> {
    scip_call_edges_with(scan, &std::collections::HashMap::new())
}

#[cfg(feature = "scip")]
fn is_callable_kind(kind: &str) -> bool {
    matches!(kind, "Function" | "Method" | "StaticMethod" | "TraitMethod")
}

/// Build a GLOBAL moniker → (kind, display-name) table across MANY ingested
/// scans — the key to the cross-binary call join. Because a SCIP global moniker
/// (`rust-analyzer cargo <pkg> <ver> <descriptors>`) is identical between the
/// reference occurrence in the CALLING crate's index and the definition
/// occurrence in the DEFINING crate's index, joining on it lets a reference in
/// scan A resolve to a callable DEFINED in scan B. Only callable definitions are
/// indexed; the first def wins (defs are globally unique by moniker anyway).
///
/// CAVEAT (documented for reviewers): the join is sound only when the two
/// indexes agree on the moniker, i.e. were produced by the same rust-analyzer
/// for the same crate name + version. A version skew between two snapshots would
/// make the monikers differ and the call would (conservatively) fall back to
/// unresolved rather than mis-resolve — never a WRONG edge, only a missing one.
#[cfg(feature = "scip")]
pub fn global_symbol_table(
    scans: &[&ScipScan],
) -> std::collections::HashMap<String, (String, String)> {
    let mut map: std::collections::HashMap<String, (String, String)> =
        std::collections::HashMap::new();
    for scan in scans {
        for r in &scan.rows {
            if r.is_definition && is_callable_kind(&r.kind) {
                let name = if r.display_name.is_empty() {
                    r.symbol.clone()
                } else {
                    r.display_name.clone()
                };
                map.entry(r.symbol.clone()).or_insert((r.kind.clone(), name));
            }
        }
    }
    map
}

/// Like [`scip_call_edges`] but resolves a callee whose definition is NOT in
/// THIS scan by joining on a `globals` moniker table built from OTHER scans
/// (see [`global_symbol_table`]) — the cross-binary / cross-repo call join.
///
/// Pass an empty `globals` for the single-scan behaviour. The CALLER is still
/// attributed by same-file containment (a call site always sits inside its
/// enclosing fn's body in the same document); only the CALLEE identity crosses
/// the binary boundary, which is exactly what the moniker carries.
#[cfg(feature = "scip")]
pub fn scip_call_edges_with(
    scan: &ScipScan,
    globals: &std::collections::HashMap<String, (String, String)>,
) -> Vec<super::symbols::CallEdgeRow> {
    use super::symbols::CallEdgeRow;

    fn is_callable(kind: &str) -> bool {
        is_callable_kind(kind)
    }

    // 1. Index Function/Method definitions that carry an enclosing range, by file.
    //    Each entry: (enc_start, enc_end, caller-name, defining symbol).
    struct Def<'a> {
        start: u32,
        end: u32,
        name: &'a str,
        symbol: &'a str,
    }
    let mut defs_by_file: std::collections::HashMap<&str, Vec<Def<'_>>> =
        std::collections::HashMap::new();
    for r in &scan.rows {
        if r.is_definition
            && is_callable(&r.kind)
            && r.enc_start_line != 0
            && r.enc_end_line >= r.enc_start_line
        {
            let name = if r.display_name.is_empty() { r.symbol.as_str() } else { r.display_name.as_str() };
            defs_by_file.entry(r.file.as_str()).or_default().push(Def {
                start: r.enc_start_line,
                end: r.enc_end_line,
                name,
                symbol: r.symbol.as_str(),
            });
        }
    }

    // A resolved symbol → its kind, so a reference can be filtered to calls
    // (refs to Function/Method symbols) and given the callee's display name.
    let mut sym_kind: std::collections::HashMap<&str, (&str, &str)> = std::collections::HashMap::new();
    for r in &scan.rows {
        if r.is_definition && is_callable(&r.kind) {
            let name = if r.display_name.is_empty() { r.symbol.as_str() } else { r.display_name.as_str() };
            sym_kind.entry(r.symbol.as_str()).or_insert((r.kind.as_str(), name));
        }
    }

    // 2. For every reference occurrence to a callable symbol, attribute it to the
    //    innermost containing def in the same file.
    let mut edges = Vec::new();
    for r in &scan.rows {
        if r.is_definition {
            continue;
        }
        // The reference's callee. Resolution order:
        //  1. a locally-resolved def in THIS scan (same crate),
        //  2. the GLOBAL moniker table — a def in ANOTHER scan (cross-binary
        //     join: the bin→lib / cross-repo call the single-scan build drops),
        //  3. the ref's own display_name as a last resort.
        let local = sym_kind.get(r.symbol.as_str()).map(|(_k, name)| *name);
        let global = globals.get(r.symbol.as_str()).map(|(_k, name)| name.as_str());
        let (callee_name, is_call) = match local.or(global) {
            Some(name) => (name, true),
            None => {
                // No def anywhere we ingested — fall back to the ref's own
                // display_name when it looks like a call site (name present).
                (r.display_name.as_str(), !r.display_name.is_empty())
            }
        };
        if !is_call {
            continue;
        }
        let Some(defs) = defs_by_file.get(r.file.as_str()) else { continue };
        // innermost = the smallest containing span.
        let mut best: Option<&Def<'_>> = None;
        for d in defs {
            if d.start <= r.start_line && r.start_line <= d.end {
                // Skip the def attributing a call to ITSELF (the def's own name
                // occurrence): a reference at the def's own start line whose
                // symbol equals the def's symbol is the definition token, already
                // filtered by `is_definition`; a recursive self-call is a real
                // edge and kept.
                let span = d.end - d.start;
                if best.map(|b| span < (b.end - b.start)).unwrap_or(true) {
                    best = Some(d);
                }
            }
        }
        let Some(caller) = best else { continue };
        // Don't emit the trivial self-loop produced by a def's own name token
        // landing inside its own body when symbols match AND it's the same name
        // at the body start (not a recursive call). We keep recursion: only drop
        // when the callee symbol IS the caller symbol AND the ref sits on the
        // caller's first line (the signature ident), which is the def token.
        if caller.symbol == r.symbol && r.start_line == caller.start {
            continue;
        }
        edges.push(CallEdgeRow {
            crate_name: String::new(),
            caller_path: caller.name.to_string(),
            callee_ident: callee_name.to_string(),
            call_kind: "call".to_string(),
            file: r.file.clone(),
            line: r.start_line,
        });
    }
    edges
}

#[cfg(test)]
mod tests {
    use super::*;
    use scip::types::{Document, Occurrence, SymbolInformation};

    /// Build a tiny hand-made SCIP index with one trait, two impls of its
    /// method `name()`, and two call sites — the canonical case syn's
    /// name-match mis-attributes (it cannot tell which `name` is called).
    fn sample_index() -> Index {
        let mut idx = Index::new();
        let mut doc = Document::new();
        doc.relative_path = "src/lib.rs".into();

        // SymbolInformation: the trait method definition.
        let mut si = SymbolInformation::new();
        si.symbol = "rust-analyzer cargo demo 0.1.0 Greet#name().".into();
        si.display_name = "name".into();
        si.kind = symbol_information::Kind::TraitMethod.into();
        doc.symbols.push(si.clone());

        // A definition occurrence (role = Definition) for Greet::name.
        let mut def = Occurrence::new();
        def.range = vec![10, 4, 10, 8];
        def.symbol = si.symbol.clone();
        def.symbol_roles = SymbolRole::Definition as i32;
        doc.occurrences.push(def);

        // Two RESOLVED reference occurrences of the SAME trait method — what an
        // IDE find-usages returns. syn would only see the bare ident `name`.
        for line in [20, 30] {
            let mut r = Occurrence::new();
            r.range = vec![line, 8, line, 12];
            r.symbol = si.symbol.clone();
            r.symbol_roles = 0; // plain reference
            doc.occurrences.push(r);
        }

        // A DIFFERENT, unrelated `name` (a struct field) at the same bare ident
        // — syn's name match would wrongly fold this into the same bucket.
        let mut other = Occurrence::new();
        other.range = vec![40, 8, 40, 12];
        other.symbol = "rust-analyzer cargo demo 0.1.0 Config#name.".into();
        other.symbol_roles = SymbolRole::ReadAccess as i32;
        doc.occurrences.push(other);

        idx.documents.push(doc);
        idx
    }

    #[test]
    fn ingest_maps_roles_and_resolves_exact_symbol() {
        let scan = ingest_index(
            sample_index(),
            "demo",
            "deadbeef",
            Uuid::nil(),
            Utc::now(),
        );

        // 4 occurrences total (1 def + 2 refs of Greet::name + 1 Config.name).
        assert_eq!(scan.rows.len(), 4);

        // Resolve the human name "name" to its DEFINING moniker — there is
        // exactly one trait-method definition (Config#name. has no def occ here).
        let syms = scan.resolve_symbols("name");
        assert_eq!(syms, vec!["rust-analyzer cargo demo 0.1.0 Greet#name().".to_string()]);

        // find-usages on the resolved symbol returns EXACTLY the two true call
        // sites — and crucially NOT the unrelated `Config#name.` field access,
        // which a syn last-segment name match ("name") would wrongly include.
        let usages = scan.usages_of(&syms[0]);
        assert_eq!(usages.len(), 2);
        let lines: Vec<u32> = usages.iter().map(|r| r.start_line).collect();
        assert_eq!(lines, vec![21, 31]); // 0-based 20/30 → 1-based.

        // The definition occurrence carries the resolved kind + 1-based pos.
        let def: Vec<&ScipRow> = scan.rows.iter().filter(|r| r.is_definition).collect();
        assert_eq!(def.len(), 1);
        assert_eq!(def[0].kind, "TraitMethod");
        assert_eq!(def[0].role, "definition");
        assert_eq!(def[0].start_line, 11);
    }

    /// Build the CALLING binary's scan: a `main()` whose body calls a function
    /// `helper` DEFINED IN ANOTHER CRATE — so this scan carries the *reference*
    /// occurrence (with the global cross-crate moniker) but NOT helper's
    /// definition (that lives in the lib's own index). This is exactly the shape
    /// `rust-analyzer scip` emits per-crate: the ref to a dependency's item keeps
    /// the dependency's resolved moniker, the def row is in the dependency's index.
    #[cfg(feature = "scip")]
    fn bin_scan() -> ScipScan {
        let mut idx = Index::new();
        let mut doc = Document::new();
        doc.relative_path = "src/main.rs".into();

        // main(): body [10,20] (0-based), calls the lib's `helper`.
        let mut main_si = SymbolInformation::new();
        main_si.symbol = "rust-analyzer cargo demo_bin 0.1.0 main().".into();
        main_si.display_name = "main".into();
        main_si.kind = symbol_information::Kind::Function.into();
        doc.symbols.push(main_si.clone());
        let mut main_def = Occurrence::new();
        main_def.range = vec![10, 3, 10, 7];
        main_def.enclosing_range = vec![10, 0, 20, 1];
        main_def.symbol = main_si.symbol.clone();
        main_def.symbol_roles = SymbolRole::Definition as i32;
        doc.occurrences.push(main_def);

        // A REFERENCE to the LIB's `helper` — note the moniker names the OTHER
        // crate (`demo_lib`), and there is NO SymbolInformation/def for it here.
        let mut ref_helper = Occurrence::new();
        ref_helper.range = vec![13, 8, 13, 14];
        ref_helper.symbol = "rust-analyzer cargo demo_lib 0.1.0 helper().".into();
        ref_helper.symbol_roles = 0; // plain reference
        doc.occurrences.push(ref_helper);

        idx.documents.push(doc);
        ingest_index(idx, "demo_bin", "binsha", Uuid::nil(), Utc::now())
    }

    /// Build the DEFINING library's scan: the `helper()` DEFINITION, carrying the
    /// SAME global moniker the bin's reference uses.
    #[cfg(feature = "scip")]
    fn lib_scan() -> ScipScan {
        let mut idx = Index::new();
        let mut doc = Document::new();
        doc.relative_path = "src/lib.rs".into();

        let mut helper_si = SymbolInformation::new();
        helper_si.symbol = "rust-analyzer cargo demo_lib 0.1.0 helper().".into();
        helper_si.display_name = "helper".into();
        helper_si.kind = symbol_information::Kind::Function.into();
        doc.symbols.push(helper_si.clone());
        let mut helper_def = Occurrence::new();
        helper_def.range = vec![5, 7, 5, 13];
        helper_def.enclosing_range = vec![5, 0, 9, 1];
        helper_def.symbol = helper_si.symbol.clone();
        helper_def.symbol_roles = SymbolRole::Definition as i32;
        doc.occurrences.push(helper_def);

        idx.documents.push(doc);
        ingest_index(idx, "demo_lib", "libsha", Uuid::nil(), Utc::now())
    }

    /// PROOF (S6b cross-binary moniker join). RED-when-broken / GREEN-when-fixed:
    ///
    /// * WITHOUT the join (single-scan `scip_call_edges` over the bin alone) the
    ///   call `main → helper` is DROPPED: helper's def is in the lib's index, so
    ///   the bin scan cannot name the callee — the edge falls back to syn (none).
    /// * WITH the join (`scip_call_edges_with` + a `global_symbol_table` built
    ///   from BOTH scans) the reference's cross-crate moniker resolves to the
    ///   lib's def, so the resolved edge `main → helper` is produced.
    #[cfg(feature = "scip")]
    #[test]
    fn cross_binary_call_resolves_via_moniker_join() {
        let bin = bin_scan();
        let lib = lib_scan();

        // RED: the bin alone cannot resolve the cross-crate callee → no edge.
        let solo = scip_call_edges(&bin);
        assert!(
            !solo.iter().any(|e| e.callee_ident == "helper"),
            "single-scan build must NOT resolve the cross-binary call (it falls \
             back to syn); got {solo:?}"
        );

        // GREEN: join on the global moniker table built from BOTH binaries.
        let globals = global_symbol_table(&[&bin, &lib]);
        let joined = scip_call_edges_with(&bin, &globals);
        let helper_edges: Vec<_> =
            joined.iter().filter(|e| e.callee_ident == "helper").collect();
        assert_eq!(
            helper_edges.len(),
            1,
            "cross-binary call must resolve via moniker join; got {joined:?}"
        );
        assert_eq!(helper_edges[0].caller_path, "main", "caller by containment");
        assert_eq!(helper_edges[0].line, 14, "ref at 0-based 13 → 1-based 14");
    }

    #[test]
    fn protobuf_roundtrip_through_bytes() {
        use protobuf::Message;
        let idx = sample_index();
        let bytes = idx.write_to_bytes().expect("encode");
        let back = protobuf_parse(&bytes).expect("decode");
        assert_eq!(back.documents.len(), 1);
        assert_eq!(back.documents[0].occurrences.len(), 4);
    }

    /// FULL-WIRING (S6b) fixture: a function `outer` whose `enclosing_range`
    /// spans a CALL to `inner`, PLUS the cross-name-collision case syn gets
    /// wrong. We model two distinct functions named `name` — `Greet#name` (the
    /// one actually called from inside `outer`) and an unrelated `Config#name`
    /// defined elsewhere with its OWN body. syn's last-segment match on the bare
    /// ident `name` cannot tell them apart and would attribute the call to
    /// whichever it sorts first; SCIP resolves the exact moniker, so the edge
    /// `outer → Greet#name` is built and `Config#name` is never confused for it.
    fn wiring_index() -> Index {
        let mut idx = Index::new();
        let mut doc = Document::new();
        doc.relative_path = "src/lib.rs".into();

        // ── three function/method DEFINITIONS, each with a body span ──────────
        // outer(): body spans lines 10..20 (0-based), calls `inner` + `Greet::name`.
        let mut outer_si = SymbolInformation::new();
        outer_si.symbol = "rust-analyzer cargo demo 0.1.0 outer().".into();
        outer_si.display_name = "outer".into();
        outer_si.kind = symbol_information::Kind::Function.into();
        doc.symbols.push(outer_si.clone());
        let mut outer_def = Occurrence::new();
        outer_def.range = vec![10, 3, 10, 8];
        outer_def.enclosing_range = vec![10, 0, 20, 1]; // body span [10,20] 0-based
        outer_def.symbol = outer_si.symbol.clone();
        outer_def.symbol_roles = SymbolRole::Definition as i32;
        doc.occurrences.push(outer_def);

        // inner(): body spans lines 30..34 — a different function, no nesting.
        let mut inner_si = SymbolInformation::new();
        inner_si.symbol = "rust-analyzer cargo demo 0.1.0 inner().".into();
        inner_si.display_name = "inner".into();
        inner_si.kind = symbol_information::Kind::Function.into();
        doc.symbols.push(inner_si.clone());
        let mut inner_def = Occurrence::new();
        inner_def.range = vec![30, 3, 30, 8];
        inner_def.enclosing_range = vec![30, 0, 34, 1];
        inner_def.symbol = inner_si.symbol.clone();
        inner_def.symbol_roles = SymbolRole::Definition as i32;
        doc.occurrences.push(inner_def);

        // Greet::name(): the trait method actually called from outer; body 40..44.
        let mut greet_si = SymbolInformation::new();
        greet_si.symbol = "rust-analyzer cargo demo 0.1.0 Greet#name().".into();
        greet_si.display_name = "name".into();
        greet_si.kind = symbol_information::Kind::Method.into();
        doc.symbols.push(greet_si.clone());
        let mut greet_def = Occurrence::new();
        greet_def.range = vec![40, 7, 40, 11];
        greet_def.enclosing_range = vec![40, 0, 44, 1];
        greet_def.symbol = greet_si.symbol.clone();
        greet_def.symbol_roles = SymbolRole::Definition as i32;
        doc.occurrences.push(greet_def);

        // Config::name(): an UNRELATED method ALSO named `name`, defined with its
        // own body 50..54. The name-collision: bare ident `name` is ambiguous.
        let mut cfg_si = SymbolInformation::new();
        cfg_si.symbol = "rust-analyzer cargo demo 0.1.0 Config#name().".into();
        cfg_si.display_name = "name".into();
        cfg_si.kind = symbol_information::Kind::Method.into();
        doc.symbols.push(cfg_si.clone());
        let mut cfg_def = Occurrence::new();
        cfg_def.range = vec![50, 7, 50, 11];
        cfg_def.enclosing_range = vec![50, 0, 54, 1];
        cfg_def.symbol = cfg_si.symbol.clone();
        cfg_def.symbol_roles = SymbolRole::Definition as i32;
        doc.occurrences.push(cfg_def);

        // ── REFERENCES from inside outer()'s body (lines 12 & 15, 0-based) ─────
        // A call to inner().
        let mut ref_inner = Occurrence::new();
        ref_inner.range = vec![12, 8, 12, 13];
        ref_inner.symbol = inner_si.symbol.clone();
        ref_inner.symbol_roles = 0; // plain reference
        doc.occurrences.push(ref_inner);

        // A call to Greet::name() — the resolved moniker, NOT Config::name.
        let mut ref_greet = Occurrence::new();
        ref_greet.range = vec![15, 8, 15, 12];
        ref_greet.symbol = greet_si.symbol.clone();
        ref_greet.symbol_roles = 0;
        doc.occurrences.push(ref_greet);

        idx.documents.push(doc);
        idx
    }

    #[test]
    fn scip_call_edges_resolve_caller_by_containment() {
        let scan = ingest_index(wiring_index(), "demo", "deadbeef", Uuid::nil(), Utc::now());

        // The def occurrences carry the captured enclosing range (1-based).
        let outer_def = scan
            .rows
            .iter()
            .find(|r| r.is_definition && r.display_name == "outer")
            .expect("outer def present");
        assert_eq!((outer_def.enc_start_line, outer_def.enc_end_line), (11, 21));

        let edges = scip_call_edges(&scan);

        // Exactly two edges, BOTH attributed to the enclosing `outer` by
        // containment of the ref line in outer's [11,21] span.
        assert_eq!(edges.len(), 2, "{edges:?}");
        for e in &edges {
            assert_eq!(e.caller_path, "outer", "caller resolved by containment");
        }

        // outer → inner.
        assert!(
            edges.iter().any(|e| e.caller_path == "outer" && e.callee_ident == "inner"),
            "expected resolved edge outer → inner: {edges:?}"
        );

        // outer → name, RESOLVED to Greet#name. The callee display name is
        // `name`, but it was matched off the exact `Greet#name().` moniker — the
        // unrelated `Config#name().` (also display `name`) is NEVER the callee,
        // which a syn last-segment match could not guarantee.
        let name_edges: Vec<_> = edges.iter().filter(|e| e.callee_ident == "name").collect();
        assert_eq!(name_edges.len(), 1, "exactly one resolved `name` call: {edges:?}");
        assert_eq!(name_edges[0].caller_path, "outer");
        assert_eq!(name_edges[0].line, 16, "ref at 0-based line 15 → 1-based 16");

        // PROOF the collision is resolved: there is NO edge whose callee came
        // from the Config#name body, and NO edge mis-attributing a `name` call to
        // any caller other than `outer`. (syn would fold both `name` defs into one
        // ident bucket and could attribute the call ambiguously.)
        assert!(
            !edges.iter().any(|e| e.caller_path == "Config" || e.caller_path == "name"),
            "no edge mis-attributed to a name-collision peer: {edges:?}"
        );
    }
}