meta-ast 0.5.1

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
//! 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, SymbolId, Visibility};

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

/// 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).
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 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();

        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 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
                    };

                    if let Some(entries) = scope.get_mut(name) {
                        entries.push((*sym_id, confidence));
                    } else {
                        scope.insert(name.clone(), vec![(*sym_id, confidence)]);
                    }
                }
            }

            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,
                        });
                    }
                }
            }
        }

        // Sort each entry: higher confidence first, then by symbol_id (stable)
        for entries in scope.values_mut() {
            entries.sort_by(|a, b| {
                b.1.partial_cmp(&a.1)
                    .unwrap_or(std::cmp::Ordering::Equal)
                    .then(a.0.to_raw().cmp(&b.0.to_raw()))
            });
        }

        (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()))
    }

    /// 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()
    }
}

/// 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,
{
    #[allow(clippy::type_complexity)]
    let results: Vec<(Vec<(SymbolId, SymbolId, f32)>, Vec<Diagnostic>)> = extractions
        .par_iter()
        .map(|file_ext| {
            let file_ext = file_ext.borrow();
            let mut local_edges = 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_edges, 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 {
                            // Don't add self-references (symbol to itself)
                            if source.id != target_id {
                                local_edges.push((source.id, 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_edges, local_diags)
        })
        .collect();

    let mut edges = Vec::new();
    for (local_edges, local_diags) in results {
        edges.extend(local_edges);
        diagnostics.extend(local_diags);
    }

    // Deduplicate: max-merge confidence for same (src, dst) pairs
    let mut seen: HashMap<(SymbolId, SymbolId), f32> = HashMap::with_capacity(edges.len());
    for (src, dst, conf) in edges {
        seen.entry((src, dst))
            .and_modify(|e| *e = e.max(conf))
            .or_insert(conf);
    }
    let mut deduped: Vec<_> = seen
        .into_iter()
        .map(|((src, dst), conf)| (src, dst, conf))
        .collect();
    deduped.sort_by_key(|(a, b, _)| (a.to_raw(), b.to_raw()));
    deduped
}

/// 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 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 },
            },
            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 },
            },
            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 },
            },
            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());
    }
}