meta-ast 0.7.0

Polyglot static-analysis engine: extract symbols and cross-language dependency graphs from 9 supported source languages, with optional MetaCall deployment manifest generation.
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
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
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
//! Reference resolution via FlattenedScopeCache.
//!
//! Pre-computes the visible scope per file by BFS-ing the import graph
//! once, then resolves references with O(1) lookups instead of
//! per-reference graph traversals.

use std::collections::{HashMap, HashSet, VecDeque};
use std::path::PathBuf;

use rayon::prelude::*;

use crate::error::{Diagnostic, Severity};
use crate::graph::edge::{
    CONFIDENCE_CROSS_LANGUAGE, CONFIDENCE_OWN_OR_DIRECT, CONFIDENCE_TRANSITIVE,
};
use crate::language::LangId;
use crate::model::{FileExtraction, FileId, SourceRange, SymbolId, Visibility};

pub type ScopeMap = HashMap<String, Vec<(SymbolId, f32)>>;
pub(crate) type SymbolIndexEntry = (SymbolId, String, LangId, Option<Visibility>);
pub(crate) type SymbolIndex = HashMap<FileId, Vec<SymbolIndexEntry>>;

/// One visible symbol candidate before shadowing and ranking.
struct Candidate {
    symbol: SymbolId,
    confidence: f32,
    rank: u8,
    path: PathBuf,
    name: String,
}

/// Bundles the data needed for scope resolution across files.
pub struct ResolutionContext {
    pub symbol_index: SymbolIndex,
    pub import_adjacency: HashMap<FileId, Vec<FileId>>,
    pub file_languages: HashMap<FileId, LangId>,
    pub file_paths: HashMap<FileId, PathBuf>,
}

impl ResolutionContext {
    /// Build a ResolutionContext from extraction results and graph data.
    pub fn from_extractions<F>(
        extractions: &[F],
        path_to_file_id: &HashMap<PathBuf, FileId>,
        import_adjacency: HashMap<FileId, Vec<FileId>>,
    ) -> Self
    where
        F: std::borrow::Borrow<FileExtraction>,
    {
        let symbol_index = build_symbol_index(extractions, path_to_file_id);
        let file_languages: HashMap<_, _> = extractions
            .iter()
            .filter_map(|f| {
                let f = f.borrow();
                Some((path_to_file_id.get(&f.path)?.to_owned(), f.lang))
            })
            .collect();
        let file_paths: HashMap<_, _> = path_to_file_id
            .iter()
            .map(|(path, &fid)| (fid, path.clone()))
            .collect();

        Self {
            symbol_index,
            import_adjacency,
            file_languages,
            file_paths,
        }
    }
}

/// Pre-computed visible scope for each file.
///
/// Scope = own symbols + public symbols from imported files transitively.
/// Local symbols take priority over imported (shadowing).
#[derive(Debug, Clone, Default)]
pub struct FlattenedScopeCache {
    scopes: HashMap<FileId, ScopeMap>,
}

impl FlattenedScopeCache {
    /// Build the scope cache from the file->symbols index and import adjacency.
    ///
    /// For each file, BFS over import edges, collecting public symbols from
    /// reachable files. Confidence decays with distance:
    /// - 1.0: own file or direct import, same language
    /// - 0.8: transitive import, same language
    /// - 0.6: cross-language imports
    pub fn build(ctx: &ResolutionContext, diagnostics: &mut Vec<Diagnostic>) -> Self {
        let mut results: Vec<(FileId, ScopeMap, Vec<Diagnostic>)> = ctx
            .symbol_index
            .par_iter()
            .map(|(&file_id, _)| {
                let (scope, diags) = Self::compute_scope(file_id, ctx);
                (file_id, scope, diags)
            })
            .collect();

        // The parallel pass returns in hash order; diagnostics must follow the
        // file path so two runs report the same sequence.
        results.sort_by(|a, b| ctx.file_paths.get(&a.0).cmp(&ctx.file_paths.get(&b.0)));

        let mut scopes = HashMap::with_capacity(results.len());
        for (file_id, scope, diags) in results {
            scopes.insert(file_id, scope);
            diagnostics.extend(diags);
        }

        Self { scopes }
    }

    fn compute_scope(file_id: FileId, ctx: &ResolutionContext) -> (ScopeMap, Vec<Diagnostic>) {
        let mut diagnostics = Vec::new();
        let source_lang = ctx.file_languages.get(&file_id).copied();
        let mut scope: ScopeMap = HashMap::new();
        let mut candidates: Vec<Candidate> = Vec::new();
        let mut visited: HashSet<FileId> = HashSet::new();
        let mut queue: VecDeque<(FileId, usize)> = VecDeque::new();

        queue.push_back((file_id, 0));

        while let Some((current, distance)) = queue.pop_front() {
            if !visited.insert(current) {
                continue;
            }

            if let Some(symbols) = ctx.symbol_index.get(&current) {
                let default_vis = ctx
                    .file_languages
                    .get(&current)
                    .map(|lang| lang.spec().default_visibility)
                    .unwrap_or(crate::language::DefaultVisibility::PublicByDefault);

                for (sym_id, name, sym_lang, visibility) in symbols {
                    let is_public = match visibility {
                        Some(Visibility::Public) => true,
                        Some(Visibility::Private) => current == file_id,
                        None => {
                            matches!(
                                default_vis,
                                crate::language::DefaultVisibility::PublicByDefault
                            ) || current == file_id
                        }
                    };

                    if !is_public {
                        continue;
                    }

                    let same_lang = source_lang.is_some() && source_lang == Some(*sym_lang);
                    let diff_lang = source_lang.is_some() && source_lang != Some(*sym_lang);

                    let confidence = if distance == 0 || (distance == 1 && same_lang) {
                        CONFIDENCE_OWN_OR_DIRECT
                    } else if diff_lang {
                        CONFIDENCE_CROSS_LANGUAGE
                    } else {
                        CONFIDENCE_TRANSITIVE
                    };

                    // Rank classes follow the shadowing rule: the own file wins,
                    // then a direct same-language import, then a transitive one,
                    // and a cross-language import comes last.
                    let rank = if distance == 0 {
                        0u8
                    } else if distance == 1 && same_lang {
                        1
                    } else if same_lang {
                        2
                    } else {
                        3
                    };

                    candidates.push(Candidate {
                        symbol: *sym_id,
                        name: name.clone(),
                        confidence,
                        rank,
                        path: ctx.file_paths.get(&current).cloned().unwrap_or_default(),
                    });
                }
            }

            if let Some(neighbors) = ctx.import_adjacency.get(&current) {
                for &neighbor in neighbors {
                    if !visited.contains(&neighbor) {
                        queue.push_back((neighbor, distance + 1));
                    } else if neighbor == file_id {
                        let path = ctx
                            .file_paths
                            .get(&current)
                            .cloned()
                            .unwrap_or_else(|| PathBuf::from("<unknown>"));
                        let root_path = ctx
                            .file_paths
                            .get(&file_id)
                            .map(|p| p.display().to_string())
                            .unwrap_or_else(|| "<unknown>".to_string());
                        diagnostics.push(Diagnostic {
                            path,
                            severity: Severity::Warning,
                            message: format!(
                                "circular import: {} -> {}",
                                current.to_raw(),
                                root_path
                            ),
                            source_range: None,
                        });
                    }
                }
            }
        }

        // Nearer definitions shadow farther ones. The remaining candidates keep
        // a total order: rank, confidence, path, then identifier. The raw
        // identifier comes last, because it is unique only inside a run.
        let mut grouped: HashMap<String, Vec<Candidate>> = HashMap::new();
        for candidate in candidates {
            grouped
                .entry(candidate.name.clone())
                .or_default()
                .push(candidate);
        }
        for (name, mut group) in grouped {
            let best = group.iter().map(|candidate| candidate.rank).min();
            if let Some(best) = best {
                group.retain(|candidate| candidate.rank == best);
            }
            group.sort_by(|a, b| {
                a.rank
                    .cmp(&b.rank)
                    .then(b.confidence.total_cmp(&a.confidence))
                    .then(a.path.cmp(&b.path))
                    .then(a.symbol.to_raw().cmp(&b.symbol.to_raw()))
            });
            scope.insert(
                name,
                group
                    .into_iter()
                    .map(|candidate| (candidate.symbol, candidate.confidence))
                    .collect(),
            );
        }

        (scope, diagnostics)
    }

    /// Look up a name in a file's flattened scope.
    ///
    /// Returns matching symbols with confidence scores, or None if not found.
    pub fn resolve(&self, file_id: FileId, name: &str) -> Option<&[(SymbolId, f32)]> {
        self.scopes
            .get(&file_id)
            .and_then(|s| s.get(name).map(|v| v.as_slice()))
    }

    /// Full scope for a file: name to candidates with confidence.
    pub fn scope(&self, file_id: FileId) -> Option<&ScopeMap> {
        self.scopes.get(&file_id)
    }

    /// Iterate over every file scope.
    pub fn iter_scopes(&self) -> impl Iterator<Item = (FileId, &ScopeMap)> {
        self.scopes.iter().map(|(&file_id, scope)| (file_id, scope))
    }

    /// Returns the number of scopes in the cache.
    pub fn len(&self) -> usize {
        self.scopes.len()
    }

    /// Returns true if the cache is empty.
    pub fn is_empty(&self) -> bool {
        self.scopes.is_empty()
    }
}

/// One resolved use of a name, with the site that produced it.
///
/// The graph edge alone names the source and target symbols; this record keeps
/// the reference range too, so a consumer can point at the exact use instead of
/// re-deriving the mapping from names.
#[derive(Debug, Clone, PartialEq)]
pub struct ResolvedReference {
    /// Path of the referencing file, as extracted.
    pub file_path: PathBuf,
    /// Range of the unresolved reference itself.
    pub range: SourceRange,
    /// Symbol that contains the reference.
    pub source: SymbolId,
    /// Symbol the name resolves to.
    pub target: SymbolId,
    /// Confidence threaded from the scope cache.
    pub confidence: f32,
}

/// Resolve every reference and keep its use site.
///
/// Records follow extraction order and, within one file, reference order. A
/// reference with no scope match emits one Warning and no record; the warnings
/// are appended to `diagnostics` exactly as `resolve_all_references` reports
/// them. Confidence is threaded from the `FlattenedScopeCache` (1.0
/// local/direct, 0.8 transitive, 0.6 cross-language).
///
/// A self-recursive reference, such as a function that calls itself, keeps
/// `source == target`. The record is a real use site; the graph folds it into a
/// self-loop `Reference` edge, which is what classifies a self-recursive unit
/// as a `SelfLoop` deployability hint.
pub fn resolve_references_detailed<F>(
    extractions: &[F],
    path_to_file_id: &HashMap<PathBuf, FileId>,
    scope_cache: &FlattenedScopeCache,
    diagnostics: &mut Vec<Diagnostic>,
) -> Vec<ResolvedReference>
where
    F: std::borrow::Borrow<FileExtraction> + Sync,
{
    #[allow(clippy::type_complexity)]
    let results: Vec<(Vec<ResolvedReference>, Vec<Diagnostic>)> = extractions
        .par_iter()
        .map(|file_ext| {
            let file_ext = file_ext.borrow();
            let mut local_refs = Vec::new();
            let mut local_diags = Vec::new();

            let file_id = match path_to_file_id.get(&file_ext.path) {
                Some(&id) => id,
                None => return (local_refs, local_diags),
            };

            let file_path = &file_ext.path;
            for ref_ in &file_ext.references {
                if let Some(matches) = scope_cache.resolve(file_id, &ref_.name) {
                    // Find the innermost source symbol that contains this reference range
                    // Pick the symbol with the smallest byte span length
                    let source_sym = file_ext
                        .symbols
                        .iter()
                        .filter(|s| {
                            s.source_range.byte_start <= ref_.range.byte_start
                                && s.source_range.byte_end >= ref_.range.byte_end
                        })
                        .min_by_key(|s| s.source_range.byte_end - s.source_range.byte_start);

                    if let Some(source) = source_sym {
                        for &(target_id, confidence) in matches {
                            local_refs.push(ResolvedReference {
                                file_path: file_path.clone(),
                                range: ref_.range.clone(),
                                source: source.id,
                                target: target_id,
                                confidence,
                            });
                        }
                    }
                } else {
                    local_diags.push(Diagnostic {
                        path: file_path.clone(),
                        severity: Severity::Warning,
                        message: format!("unresolved reference: '{}'", ref_.name),
                        source_range: Some(ref_.range.clone()),
                    });
                }
            }
            (local_refs, local_diags)
        })
        .collect();

    let mut resolved = Vec::new();
    for (mut local_refs, local_diags) in results {
        resolved.append(&mut local_refs);
        diagnostics.extend(local_diags);
    }
    resolved
}

/// Fold resolved use sites into one edge per `(source, target)` pair.
///
/// Duplicates max-merge their confidence and the result is ordered by symbol
/// id, so the edge list does not depend on discovery or resolution order. A
/// self-recursive use site folds into a self edge, which is intended: the SCC
/// pass reports such a unit as a `SelfLoop` hint.
pub fn reference_edges(resolved: &[ResolvedReference]) -> Vec<(SymbolId, SymbolId, f32)> {
    let mut seen: HashMap<(SymbolId, SymbolId), f32> = HashMap::with_capacity(resolved.len());
    for reference in resolved {
        seen.entry((reference.source, reference.target))
            .and_modify(|confidence| *confidence = confidence.max(reference.confidence))
            .or_insert(reference.confidence);
    }
    let mut edges: Vec<_> = seen
        .into_iter()
        .map(|((source, target), confidence)| (source, target, confidence))
        .collect();
    edges.sort_by_key(|(source, target, _)| (source.to_raw(), target.to_raw()));
    edges
}

/// Resolve all references across extracted files.
///
/// Returns a list of (source_symbol_id, target_symbol_id, confidence) triples
/// representing ReferenceEdges to add. Confidence is threaded from the
/// FlattenedScopeCache (1.0 local/direct, 0.8 transitive, 0.6 cross-language).
/// Warnings for unresolved references are appended to `diagnostics`.
pub fn resolve_all_references<F>(
    extractions: &[F],
    path_to_file_id: &HashMap<PathBuf, FileId>,
    scope_cache: &FlattenedScopeCache,
    diagnostics: &mut Vec<Diagnostic>,
) -> Vec<(SymbolId, SymbolId, f32)>
where
    F: std::borrow::Borrow<FileExtraction> + Sync,
{
    let resolved =
        resolve_references_detailed(extractions, path_to_file_id, scope_cache, diagnostics);
    reference_edges(&resolved)
}

/// Build a symbol index from extracted files and a path-to-FileId mapping.
///
/// Returns: SymbolIndex
pub fn build_symbol_index<F>(
    extractions: &[F],
    path_to_file_id: &HashMap<PathBuf, FileId>,
) -> SymbolIndex
where
    F: std::borrow::Borrow<FileExtraction>,
{
    let mut index: SymbolIndex = HashMap::new();

    for file_ext in extractions {
        let file_ext = file_ext.borrow();
        if let Some(&file_id) = path_to_file_id.get(&file_ext.path) {
            let entries: Vec<_> = file_ext
                .symbols
                .iter()
                .map(|s| (s.id, s.name.clone(), s.language, s.visibility))
                .collect();
            index.entry(file_id).or_default().extend(entries);
        }
    }

    index
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    #[test]
    fn empty_cache() {
        let cache = FlattenedScopeCache {
            scopes: HashMap::new(),
        };
        assert!(cache.is_empty());
        assert_eq!(cache.len(), 0);
        assert!(cache.resolve(FileId::new(1).unwrap(), "foo").is_none());
    }

    #[test]
    fn detailed_resolution_keeps_each_use_site_and_the_triples_are_unchanged() {
        use crate::model::{LineColumn, Symbol, SymbolKind, UnresolvedReference};

        fn range(start: usize, end: usize) -> SourceRange {
            SourceRange {
                byte_start: start,
                byte_end: end,
                start: LineColumn {
                    line: 0,
                    column: start,
                },
                end: LineColumn {
                    line: 0,
                    column: end,
                },
            }
        }

        fn symbol(id: u32, name: &str, start: usize, end: usize, path: &std::path::Path) -> Symbol {
            Symbol {
                id: SymbolId::new(id).unwrap(),
                name: name.to_string(),
                kind: SymbolKind::Function,
                language: LangId::Python,
                file_path: path.to_path_buf(),
                source_range: range(start, end),
                name_range: None,
                visibility: None,
                signature: None,
                docstring: None,
                is_async: false,
            }
        }

        let path = PathBuf::from("a.py");
        let file_id = FileId::new(1).unwrap();
        let mut file = FileExtraction::empty(path.clone(), LangId::Python);
        file.symbols = vec![
            symbol(1, "caller", 0, 100, &path),
            symbol(2, "helper", 200, 210, &path),
        ];
        file.references = vec![
            UnresolvedReference {
                name: "helper".into(),
                range: range(10, 16),
            },
            UnresolvedReference {
                name: "helper".into(),
                range: range(30, 36),
            },
        ];
        let mut symbol_index: SymbolIndex = HashMap::new();
        symbol_index.insert(
            file_id,
            vec![
                (
                    SymbolId::new(1).unwrap(),
                    "caller".into(),
                    LangId::Python,
                    None,
                ),
                (
                    SymbolId::new(2).unwrap(),
                    "helper".into(),
                    LangId::Python,
                    None,
                ),
            ],
        );
        let ctx = ResolutionContext {
            symbol_index,
            import_adjacency: HashMap::new(),
            file_languages: HashMap::from([(file_id, LangId::Python)]),
            file_paths: HashMap::from([(file_id, path.clone())]),
        };
        let cache = FlattenedScopeCache::build(&ctx, &mut Vec::new());
        let extractions = vec![file];
        let paths = HashMap::from([(path, file_id)]);

        let mut diagnostics = Vec::new();
        let resolved = resolve_references_detailed(&extractions, &paths, &cache, &mut diagnostics);

        assert!(diagnostics.is_empty());
        assert_eq!(resolved.len(), 2, "one record per use site");
        assert_eq!(resolved[0].range.byte_start, 10);
        assert_eq!(resolved[1].range.byte_start, 30);
        assert!(
            resolved
                .iter()
                .all(|record| record.source == SymbolId::new(1).unwrap())
        );
        assert!(
            resolved.iter().all(
                |record| record.target == SymbolId::new(2).unwrap() && record.confidence == 1.0
            )
        );

        let mut wrapper_diagnostics = Vec::new();
        let triples =
            resolve_all_references(&extractions, &paths, &cache, &mut wrapper_diagnostics);
        assert!(wrapper_diagnostics.is_empty());
        assert_eq!(
            triples,
            vec![(SymbolId::new(1).unwrap(), SymbolId::new(2).unwrap(), 1.0)],
            "the wrapper max-merges the two use sites into one edge"
        );
    }

    #[test]
    fn scope_cache_resolve_own_file() {
        let mut symbol_index: SymbolIndex = HashMap::new();
        symbol_index.insert(
            FileId::new(1).unwrap(),
            vec![(
                SymbolId::new(10).unwrap(),
                "main".into(),
                LangId::Python,
                None,
            )],
        );

        let ctx = ResolutionContext {
            symbol_index,
            import_adjacency: HashMap::new(),
            file_languages: HashMap::from([(FileId::new(1).unwrap(), LangId::Python)]),
            file_paths: HashMap::new(),
        };

        let cache = FlattenedScopeCache::build(&ctx, &mut Vec::new());
        let result = cache.resolve(FileId::new(1).unwrap(), "main");
        assert!(result.is_some());
        let matches = result.unwrap();
        assert_eq!(matches.len(), 1);
        assert_eq!(matches[0].0, SymbolId::new(10).unwrap());
        assert_eq!(matches[0].1, 1.0);
    }

    #[test]
    fn scope_cache_resolve_imported_symbol() {
        let mut symbol_index = HashMap::new();
        symbol_index.insert(FileId::new(1).unwrap(), vec![]);
        symbol_index.insert(
            FileId::new(2).unwrap(),
            vec![(
                SymbolId::new(20).unwrap(),
                "helper".into(),
                LangId::Python,
                Some(Visibility::Public),
            )],
        );

        let ctx = ResolutionContext {
            symbol_index,
            import_adjacency: HashMap::from([(
                FileId::new(1).unwrap(),
                vec![FileId::new(2).unwrap()],
            )]),
            file_languages: HashMap::from([
                (FileId::new(1).unwrap(), LangId::Python),
                (FileId::new(2).unwrap(), LangId::Python),
            ]),
            file_paths: HashMap::new(),
        };

        let cache = FlattenedScopeCache::build(&ctx, &mut Vec::new());
        let result = cache.resolve(FileId::new(1).unwrap(), "helper");
        assert!(result.is_some());
        let matches = result.unwrap();
        assert_eq!(matches.len(), 1);
        assert_eq!(matches[0].0, SymbolId::new(20).unwrap());
        assert_eq!(matches[0].1, 1.0);
    }

    #[test]
    fn scope_cache_missing_symbol() {
        let mut symbol_index = HashMap::new();
        symbol_index.insert(
            FileId::new(1).unwrap(),
            vec![(
                SymbolId::new(10).unwrap(),
                "foo".into(),
                LangId::Python,
                None,
            )],
        );

        let ctx = ResolutionContext {
            symbol_index,
            import_adjacency: HashMap::new(),
            file_languages: HashMap::from([(FileId::new(1).unwrap(), LangId::Python)]),
            file_paths: HashMap::new(),
        };

        let cache = FlattenedScopeCache::build(&ctx, &mut Vec::new());
        assert!(cache.resolve(FileId::new(1).unwrap(), "bar").is_none());
    }

    #[test]
    fn scope_cache_cycle_safe() {
        let mut symbol_index = HashMap::new();
        symbol_index.insert(
            FileId::new(1).unwrap(),
            vec![(
                SymbolId::new(10).unwrap(),
                "a".into(),
                LangId::Python,
                Some(Visibility::Public),
            )],
        );
        symbol_index.insert(
            FileId::new(2).unwrap(),
            vec![(
                SymbolId::new(20).unwrap(),
                "b".into(),
                LangId::Python,
                Some(Visibility::Public),
            )],
        );

        // Cycle: 0 -> 1 -> 0
        let ctx = ResolutionContext {
            symbol_index,
            import_adjacency: HashMap::from([
                (FileId::new(1).unwrap(), vec![FileId::new(2).unwrap()]),
                (FileId::new(2).unwrap(), vec![FileId::new(1).unwrap()]),
            ]),
            file_languages: HashMap::from([
                (FileId::new(1).unwrap(), LangId::Python),
                (FileId::new(2).unwrap(), LangId::Python),
            ]),
            file_paths: HashMap::new(),
        };

        let cache = FlattenedScopeCache::build(&ctx, &mut Vec::new());
        // Should not infinite loop
        assert!(cache.resolve(FileId::new(1).unwrap(), "b").is_some());
        assert!(cache.resolve(FileId::new(2).unwrap(), "a").is_some());
    }

    #[test]
    fn scope_cache_cross_language_confidence() {
        let mut symbol_index = HashMap::new();
        symbol_index.insert(FileId::new(1).unwrap(), vec![]);
        symbol_index.insert(
            FileId::new(2).unwrap(),
            vec![(
                SymbolId::new(20).unwrap(),
                "util".into(),
                LangId::Rust,
                Some(Visibility::Public),
            )],
        );

        let ctx = ResolutionContext {
            symbol_index,
            import_adjacency: HashMap::from([(
                FileId::new(1).unwrap(),
                vec![FileId::new(2).unwrap()],
            )]),
            file_languages: HashMap::from([
                (FileId::new(1).unwrap(), LangId::Python),
                (FileId::new(2).unwrap(), LangId::Rust),
            ]),
            file_paths: HashMap::new(),
        };

        let cache = FlattenedScopeCache::build(&ctx, &mut Vec::new());
        let result = cache.resolve(FileId::new(1).unwrap(), "util");
        assert!(result.is_some());
        assert_eq!(result.unwrap()[0].1, 0.6);
    }

    #[test]
    fn resolve_references_creates_edges() {
        use crate::model::{LineColumn, SourceRange, Symbol, SymbolKind, UnresolvedReference};

        let sym_a = Symbol {
            id: SymbolId::new(1).unwrap(),
            name: "caller".into(),
            kind: SymbolKind::Function,
            language: LangId::Python,
            file_path: PathBuf::from("/proj/a.py"),
            source_range: SourceRange {
                byte_start: 0,
                byte_end: 50,
                start: LineColumn { line: 0, column: 0 },
                end: LineColumn { line: 2, column: 0 },
            },
            name_range: None,
            visibility: None,
            signature: None,
            docstring: None,
            is_async: false,
        };

        let mut file = FileExtraction::empty(PathBuf::from("/proj/a.py"), LangId::Python);
        file.symbols = vec![sym_a];
        file.references = vec![UnresolvedReference {
            name: "helper".into(),
            range: SourceRange {
                byte_start: 20,
                byte_end: 26,
                start: LineColumn { line: 1, column: 4 },
                end: LineColumn {
                    line: 1,
                    column: 10,
                },
            },
        }];

        let mut path_to_file_id = HashMap::new();
        path_to_file_id.insert(PathBuf::from("/proj/a.py"), FileId::new(1).unwrap());

        let mut scopes: HashMap<FileId, ScopeMap> = HashMap::new();
        let mut scope = HashMap::new();
        scope.insert("helper".into(), vec![(SymbolId::new(99).unwrap(), 1.0)]);
        scopes.insert(FileId::new(1).unwrap(), scope);

        let cache = FlattenedScopeCache { scopes };

        let edges = resolve_all_references(&[file], &path_to_file_id, &cache, &mut Vec::new());
        assert_eq!(edges.len(), 1);
        assert_eq!(edges[0].0, SymbolId::new(1).unwrap());
        assert_eq!(edges[0].1, SymbolId::new(99).unwrap());
        assert_eq!(edges[0].2, 1.0);
    }

    #[test]
    fn resolve_references_selects_innermost_enclosing_symbol_regardless_of_vector_order() {
        use crate::model::{LineColumn, SourceRange, Symbol, SymbolKind, UnresolvedReference};

        // Inner method (span 40: 10..50)
        let inner_method = Symbol {
            id: SymbolId::new(1).unwrap(),
            name: "inner_method".into(),
            kind: SymbolKind::Method,
            language: LangId::Python,
            file_path: PathBuf::from("/proj/a.py"),
            source_range: SourceRange {
                byte_start: 10,
                byte_end: 50,
                start: LineColumn { line: 1, column: 0 },
                end: LineColumn { line: 3, column: 0 },
            },
            name_range: None,
            visibility: None,
            signature: None,
            docstring: None,
            is_async: false,
        };

        // Outer class (span 100: 0..100) placed AFTER inner_method in vector
        let outer_class = Symbol {
            id: SymbolId::new(2).unwrap(),
            name: "OuterClass".into(),
            kind: SymbolKind::Class,
            language: LangId::Python,
            file_path: PathBuf::from("/proj/a.py"),
            source_range: SourceRange {
                byte_start: 0,
                byte_end: 100,
                start: LineColumn { line: 0, column: 0 },
                end: LineColumn { line: 5, column: 0 },
            },
            name_range: None,
            visibility: None,
            signature: None,
            docstring: None,
            is_async: false,
        };

        let mut file = FileExtraction::empty(PathBuf::from("/proj/a.py"), LangId::Python);
        file.symbols = vec![inner_method, outer_class]; // Order: inner first, outer second
        file.references = vec![UnresolvedReference {
            name: "helper".into(),
            range: SourceRange {
                byte_start: 20,
                byte_end: 26,
                start: LineColumn { line: 2, column: 4 },
                end: LineColumn {
                    line: 2,
                    column: 10,
                },
            },
        }];

        let mut path_to_file_id = HashMap::new();
        path_to_file_id.insert(PathBuf::from("/proj/a.py"), FileId::new(1).unwrap());

        let mut scopes: HashMap<FileId, ScopeMap> = HashMap::new();
        let mut scope = HashMap::new();
        scope.insert("helper".into(), vec![(SymbolId::new(99).unwrap(), 1.0)]);
        scopes.insert(FileId::new(1).unwrap(), scope);

        let cache = FlattenedScopeCache { scopes };

        let edges = resolve_all_references(&[file], &path_to_file_id, &cache, &mut Vec::new());
        assert_eq!(edges.len(), 1);
        // Must resolve from SymbolId(1) (inner_method), NOT SymbolId(2) (outer_class)
        assert_eq!(
            edges[0].0,
            SymbolId::new(1).unwrap(),
            "Reference should attach to innermost symbol SymbolId(1), but attached to SymbolId({})",
            edges[0].0.to_raw()
        );
        assert_eq!(edges[0].1, SymbolId::new(99).unwrap());
    }

    #[test]
    fn local_symbol_shadows_the_imported_symbol() {
        let mut symbol_index: SymbolIndex = HashMap::new();
        symbol_index.insert(
            FileId::new(1).unwrap(),
            vec![(
                SymbolId::new(10).unwrap(),
                "helper".into(),
                LangId::Python,
                Some(Visibility::Public),
            )],
        );
        symbol_index.insert(
            FileId::new(2).unwrap(),
            vec![(
                SymbolId::new(20).unwrap(),
                "helper".into(),
                LangId::Python,
                Some(Visibility::Public),
            )],
        );

        let ctx = ResolutionContext {
            symbol_index,
            import_adjacency: HashMap::from([(
                FileId::new(1).unwrap(),
                vec![FileId::new(2).unwrap()],
            )]),
            file_languages: HashMap::from([
                (FileId::new(1).unwrap(), LangId::Python),
                (FileId::new(2).unwrap(), LangId::Python),
            ]),
            file_paths: HashMap::from([
                (FileId::new(1).unwrap(), PathBuf::from("/proj/main.py")),
                (FileId::new(2).unwrap(), PathBuf::from("/proj/lib.py")),
            ]),
        };

        let cache = FlattenedScopeCache::build(&ctx, &mut Vec::new());
        let matches = cache.resolve(FileId::new(1).unwrap(), "helper").unwrap();
        assert_eq!(
            matches.len(),
            1,
            "the local definition must shadow the imported one"
        );
        assert_eq!(matches[0].0, SymbolId::new(10).unwrap());
        assert_eq!(matches[0].1, 1.0);
    }

    #[test]
    fn imported_candidates_are_ranked_by_path_not_by_id() {
        let mut symbol_index: SymbolIndex = HashMap::new();
        symbol_index.insert(FileId::new(1).unwrap(), vec![]);
        // File 2 sorts before file 3 by path but holds the higher symbol id.
        symbol_index.insert(
            FileId::new(2).unwrap(),
            vec![(
                SymbolId::new(30).unwrap(),
                "util".into(),
                LangId::Python,
                Some(Visibility::Public),
            )],
        );
        symbol_index.insert(
            FileId::new(3).unwrap(),
            vec![(
                SymbolId::new(20).unwrap(),
                "util".into(),
                LangId::Python,
                Some(Visibility::Public),
            )],
        );

        let ctx = ResolutionContext {
            symbol_index,
            import_adjacency: HashMap::from([(
                FileId::new(1).unwrap(),
                vec![FileId::new(2).unwrap(), FileId::new(3).unwrap()],
            )]),
            file_languages: HashMap::from([
                (FileId::new(1).unwrap(), LangId::Python),
                (FileId::new(2).unwrap(), LangId::Python),
                (FileId::new(3).unwrap(), LangId::Python),
            ]),
            file_paths: HashMap::from([
                (FileId::new(1).unwrap(), PathBuf::from("/proj/app.py")),
                (FileId::new(2).unwrap(), PathBuf::from("/proj/a_util.py")),
                (FileId::new(3).unwrap(), PathBuf::from("/proj/z_util.py")),
            ]),
        };

        let cache = FlattenedScopeCache::build(&ctx, &mut Vec::new());
        let matches = cache.resolve(FileId::new(1).unwrap(), "util").unwrap();
        assert_eq!(
            matches.len(),
            2,
            "an ambiguous import keeps both candidates"
        );
        assert_eq!(
            matches[0].0,
            SymbolId::new(30).unwrap(),
            "candidate order must follow the file path, not the raw symbol id"
        );
    }
}