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
//! Stateful import path resolution seam.
//!
//! Provides the `ImportResolver` trait and a `StatelessResolver` adapter
//! that wraps existing stateless function pointers, allowing gradual
//! migration to stateful per-language resolvers.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::RwLock;

/// Stateful import path resolution seam.
///
/// Implementors resolve a raw import string to an on-disk path within a project.
/// The interface is stateful (takes `&self`) to allow implementors to cache
/// config file reads (tsconfig.json, go.mod, sys.path) on first use.
pub trait ImportResolver: Send + Sync {
    fn resolve(&self, raw: &str, source_dir: &Path, project_root: &Path) -> Option<PathBuf>;

    /// Invalidate any memoized filesystem state or configuration caches.
    fn clear_cache(&self) {}
}

/// Strip quote chars that wrap an import specifier.
pub(crate) fn strip_import_quotes(raw: &str) -> &str {
    raw.trim_matches(|c| c == '"' || c == '\'')
}

/// Strip quote chars plus C/C++ bracket delimiters.
pub(crate) fn strip_c_family_quotes(raw: &str) -> &str {
    raw.trim_matches(|c| c == '<' || c == '>' || c == '"' || c == '\'')
}

/// Probe `base.join(raw)` with each extension in order.
pub(crate) fn probe_relative(
    raw: &str,
    source_dir: &Path,
    extensions: &[&str],
    is_file: &dyn Fn(&Path) -> bool,
    fallback: bool,
) -> Option<PathBuf> {
    let base = if raw.starts_with('/') {
        PathBuf::from("/")
    } else {
        source_dir.to_path_buf()
    };
    let path = base.join(raw);
    for ext in extensions {
        let candidate = if ext.is_empty() {
            path.clone()
        } else {
            path.with_extension(ext.trim_start_matches('.'))
        };
        if is_file(&candidate) {
            return Some(candidate);
        }
    }
    fallback.then(|| path.clone())
}

/// Shared stateless core for JS-family imports.
///
/// Bare specifiers return as external paths. Relative paths probe
/// `base.join(raw)` with each extension in order.
pub(crate) fn resolve_js_family_import(
    raw: &str,
    source_dir: &Path,
    extensions: &[&str],
    is_file: &dyn Fn(&Path) -> bool,
) -> Option<PathBuf> {
    let raw = strip_import_quotes(raw);
    if raw.is_empty() {
        return None;
    }
    if !raw.starts_with('.') && !raw.starts_with('/') {
        return Some(PathBuf::from(raw));
    }
    probe_relative(raw, source_dir, extensions, is_file, true)
}

/// Resolve a C or C++ include specifier to a project file.
///
/// A system include (`<...>`) never resolves. There is no include path
/// model, so a quoted include resolves only when the file sits next to the
/// source file. Everything else stays external (ADR 0003).
pub(crate) fn resolve_c_family_import(raw: &str, source_dir: &Path) -> Option<PathBuf> {
    let trimmed = raw.trim();
    if trimmed.is_empty() || trimmed.starts_with('<') {
        return None;
    }
    let relative = strip_c_family_quotes(trimmed);
    if relative.is_empty() {
        return None;
    }
    let candidate = source_dir.join(relative);
    let candidate = if candidate.extension().is_none() {
        candidate.with_extension("h")
    } else {
        candidate
    };
    candidate.is_file().then_some(candidate)
}

/// Candidate `__init__.py` and module file for a Python import.
///
/// One leading dot is the current package, two dots the parent package, and
/// so on (PEP 328).
pub(crate) fn python_candidate_paths(
    raw: &str,
    source_dir: &Path,
    project_root: &Path,
) -> Option<(PathBuf, PathBuf)> {
    let raw = strip_import_quotes(raw);
    if raw.is_empty() {
        return None;
    }
    if !raw.starts_with('.') {
        let path = project_root.join(raw.replace('.', std::path::MAIN_SEPARATOR_STR));
        let init = path.join("__init__.py");
        let module = path.with_extension("py");
        return Some((init, module));
    }

    let dots = raw.chars().take_while(|c| *c == '.').count();
    let base = source_dir.ancestors().nth(dots - 1)?;
    let rest = &raw[dots..];
    if rest.is_empty() {
        let init = base.join("__init__.py");
        return Some((init.clone(), init));
    }
    let path = base.join(rest.replace('.', std::path::MAIN_SEPARATOR_STR));
    let init = path.join("__init__.py");
    let module = path.with_extension("py");
    Some((init, module))
}

/// Walk `project_root` parents for `go.mod` and parse the module name.
pub(crate) fn find_go_module(project_root: &Path) -> Option<(PathBuf, String)> {
    let mut current = Some(project_root);
    while let Some(dir) = current {
        let go_mod = dir.join("go.mod");
        if go_mod.is_file() {
            if let Ok(content) = std::fs::read_to_string(&go_mod) {
                for line in content.lines() {
                    let line = line.trim();
                    if let Some(module) = line.strip_prefix("module ") {
                        return Some((dir.to_path_buf(), module.trim().to_string()));
                    }
                }
            }
            return None;
        }
        current = dir.parent();
    }
    None
}

/// Zero-cost adapter wrapping a stateless function pointer.
///
/// Bridges the existing `LanguageSpec.import_path_resolver` fn pointers
/// to the `ImportResolver` trait without changing the `LanguageSpec` struct.
pub struct StatelessResolver {
    f: fn(&str, &Path, &Path) -> Option<PathBuf>,
}

impl StatelessResolver {
    pub fn new(f: fn(&str, &Path, &Path) -> Option<PathBuf>) -> Self {
        Self { f }
    }
}

impl ImportResolver for StatelessResolver {
    fn resolve(&self, raw: &str, source_dir: &Path, project_root: &Path) -> Option<PathBuf> {
        (self.f)(raw, source_dir, project_root)
    }
}

/// Stateful resolver for Python import paths.
///
/// Only positive answers are memoized, so a module created after a miss is
/// found on the next resolve instead of being answered from a stale entry.
pub struct PythonResolver {
    f: fn(&str, &Path, &Path) -> Option<PathBuf>,
    exists_cache: RwLock<HashMap<PathBuf, bool>>,
}

impl PythonResolver {
    pub fn new(f: fn(&str, &Path, &Path) -> Option<PathBuf>) -> Self {
        Self {
            f,
            exists_cache: RwLock::new(HashMap::new()),
        }
    }

    pub fn clear_cache(&self) {
        let mut cache = self
            .exists_cache
            .write()
            .unwrap_or_else(|poison| poison.into_inner());
        cache.clear();
    }
}

impl ImportResolver for PythonResolver {
    fn resolve(&self, raw: &str, source_dir: &Path, project_root: &Path) -> Option<PathBuf> {
        let check_exists = |path: &Path| -> bool {
            let cache_val = self
                .exists_cache
                .read()
                .ok()
                .and_then(|cache| cache.get(path).copied());
            if let Some(res) = cache_val {
                return res;
            }
            let res = path.exists();
            if res && let Ok(mut cache) = self.exists_cache.write() {
                cache.insert(path.to_path_buf(), res);
            }
            res
        };

        if let Some((init_path, _)) = python_candidate_paths(raw, source_dir, project_root) {
            let stripped = strip_import_quotes(raw);
            if stripped.trim_start_matches('.').is_empty() && stripped.starts_with('.') {
                return Some(init_path);
            }
            if check_exists(&init_path) {
                return Some(init_path);
            }
        } else {
            return None;
        }

        (self.f)(raw, source_dir, project_root)
    }

    fn clear_cache(&self) {
        PythonResolver::clear_cache(self);
    }
}

/// Stateful resolver for Go module import paths.
pub struct GoModResolver {
    f: fn(&str, &Path, &Path) -> Option<PathBuf>,
    cached_module: RwLock<Option<Option<(PathBuf, String)>>>,
}

impl GoModResolver {
    pub fn new(f: fn(&str, &Path, &Path) -> Option<PathBuf>) -> Self {
        Self {
            f,
            cached_module: RwLock::new(None),
        }
    }

    pub fn clear_cache(&self) {
        let mut guard = self
            .cached_module
            .write()
            .unwrap_or_else(|poison| poison.into_inner());
        *guard = None;
    }
}

impl ImportResolver for GoModResolver {
    fn resolve(&self, raw: &str, source_dir: &Path, project_root: &Path) -> Option<PathBuf> {
        let raw = strip_import_quotes(raw);
        if raw.is_empty() || raw.starts_with('.') {
            // Go modules reject relative imports, so there is no path to build.
            return None;
        }

        let cached = self
            .cached_module
            .read()
            .ok()
            .and_then(|guard| guard.clone());
        let module_info = match cached {
            Some(info) => info,
            None => {
                // A missing go.mod is re-checked on the next resolve, so a
                // module file written after the first miss is not cached away.
                let computed = find_go_module(project_root);
                if let Some(found) = computed.as_ref()
                    && let Ok(mut guard) = self.cached_module.write()
                {
                    *guard = Some(Some(found.clone()));
                }
                computed
            }
        };

        let matched_module = module_info.as_ref().and_then(|(dir, name)| {
            raw.strip_prefix(name.as_str())
                .filter(|rest| rest.is_empty() || rest.starts_with('/'))
                .map(|_| (dir, name))
        });
        if let Some((dir, module_name)) = matched_module {
            let relative = raw[module_name.len()..].trim_start_matches('/');
            if relative.is_empty() {
                // A package is a directory. One file cannot represent it.
                return None;
            }
            return Some(dir.join(relative).with_extension("go"));
        }

        (self.f)(raw, source_dir, project_root)
    }

    fn clear_cache(&self) {
        GoModResolver::clear_cache(self);
    }
}

/// Stateful resolver for JavaScript-family import paths.
///
/// Parameterized by extension list so JS and TS/TSX share one core.
/// JS probes Node-style extensions, TS probes TS-family extensions.
pub struct NodeResolver {
    f: fn(&str, &Path, &Path) -> Option<PathBuf>,
    extensions: &'static [&'static str],
    is_file_cache: RwLock<HashMap<PathBuf, bool>>,
}

/// Node-style extensions probed by the JS resolver.
pub(crate) const JS_EXTS: &[&str] = &["", ".js", ".json", ".node", ".mjs", ".cjs"];
/// TS-family extensions probed by the TS/TSX resolver.
pub(crate) const TS_EXTS: &[&str] = &["", ".js", ".ts", ".jsx", ".tsx", ".mjs", ".cjs"];

impl NodeResolver {
    pub fn new(
        f: fn(&str, &Path, &Path) -> Option<PathBuf>,
        extensions: &'static [&'static str],
    ) -> Self {
        Self {
            f,
            extensions,
            is_file_cache: RwLock::new(HashMap::new()),
        }
    }

    pub fn clear_cache(&self) {
        let mut cache = self
            .is_file_cache
            .write()
            .unwrap_or_else(|poison| poison.into_inner());
        cache.clear();
    }
}

impl ImportResolver for NodeResolver {
    fn resolve(&self, raw: &str, source_dir: &Path, project_root: &Path) -> Option<PathBuf> {
        let raw = strip_import_quotes(raw);
        if raw.is_empty() {
            return None;
        }

        let check_is_file = |path: &Path| -> bool {
            let cache_val = self
                .is_file_cache
                .read()
                .ok()
                .and_then(|cache| cache.get(path).copied());
            if let Some(res) = cache_val {
                return res;
            }
            let res = path.is_file();
            if res && let Ok(mut cache) = self.is_file_cache.write() {
                cache.insert(path.to_path_buf(), res);
            }
            res
        };

        if !raw.starts_with('.') && !raw.starts_with('/') {
            return (self.f)(raw, source_dir, project_root);
        }

        let path = if raw.starts_with('/') {
            PathBuf::from("/").join(raw)
        } else {
            source_dir.join(raw)
        };

        for ext in self.extensions {
            let candidate = if ext.is_empty() {
                path.clone()
            } else {
                path.with_extension(ext.trim_start_matches('.'))
            };
            if check_is_file(&candidate) {
                return Some(candidate);
            }
        }

        (self.f)(raw, source_dir, project_root)
    }

    fn clear_cache(&self) {
        NodeResolver::clear_cache(self);
    }
}

/// Construct a boxed `ImportResolver` for the given language.
///
/// Wraps the existing stateless fn pointer from `LanguageSpec` into
/// a language-specific resolver (PythonResolver, TsConfigResolver, etc.)
/// allowing gradual, modular migration to stateful resolution.
pub fn make_resolver(lang: crate::language::LangId) -> Box<dyn ImportResolver> {
    let f = lang.spec().import_path_resolver;
    match lang {
        crate::language::LangId::Python => Box::new(PythonResolver::new(f)),
        crate::language::LangId::Go => Box::new(GoModResolver::new(f)),
        crate::language::LangId::JavaScript => Box::new(NodeResolver::new(f, JS_EXTS)),
        crate::language::LangId::TypeScript | crate::language::LangId::Tsx => {
            Box::new(NodeResolver::new(f, TS_EXTS))
        }
        _ => Box::new(StatelessResolver::new(f)),
    }
}

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

    #[test]
    fn stateless_resolver_delegates_to_fn() {
        // A fn pointer that resolves "foo" to /proj/foo.py
        fn my_resolver(raw: &str, _source: &Path, root: &Path) -> Option<PathBuf> {
            Some(root.join(format!("{raw}.py")))
        }
        let resolver = StatelessResolver::new(my_resolver);
        let result = resolver.resolve("foo", Path::new("/src"), Path::new("/proj"));
        assert_eq!(result, Some(PathBuf::from("/proj/foo.py")));
    }

    #[test]
    fn stateless_resolver_returns_none_for_unresolvable() {
        fn null_resolver(_raw: &str, _src: &Path, _root: &Path) -> Option<PathBuf> {
            None
        }
        let resolver = StatelessResolver::new(null_resolver);
        let result = resolver.resolve("anything", Path::new("/src"), Path::new("/proj"));
        assert!(result.is_none());
    }

    #[test]
    fn make_resolver_returns_working_resolver_for_python() {
        use crate::language::LangId;
        let resolver = make_resolver(LangId::Python);
        // Python should resolve "b" from /proj/a/ to /proj/a/b.py
        let result = resolver.resolve("b", Path::new("/proj/a"), Path::new("/proj"));
        // We just verify it doesn't panic and returns an Option
        let _ = result; // may be None if /proj/a/b.py doesn't exist on disk - that's fine
    }

    #[test]
    fn import_resolver_trait_is_object_safe() {
        // This test verifies the trait can be used as a trait object
        fn accepts_boxed(_resolver: &dyn ImportResolver) {}

        fn null_resolver(_raw: &str, _src: &Path, _root: &Path) -> Option<PathBuf> {
            None
        }
        let resolver = StatelessResolver::new(null_resolver);
        accepts_boxed(&resolver);
    }

    #[test]
    fn python_resolver_resolves_import() {
        fn dummy_python_resolver(raw: &str, _source: &Path, root: &Path) -> Option<PathBuf> {
            Some(root.join(format!("{raw}.py")))
        }
        let resolver = PythonResolver::new(dummy_python_resolver);
        let result = resolver.resolve("test", Path::new("/src"), Path::new("/proj"));
        assert_eq!(result, Some(PathBuf::from("/proj/test.py")));
    }

    #[test]
    fn tsconfig_resolver_resolves_import() {
        fn dummy_ts_resolver(raw: &str, _source: &Path, root: &Path) -> Option<PathBuf> {
            Some(root.join(format!("{raw}.ts")))
        }
        let resolver = NodeResolver::new(dummy_ts_resolver, TS_EXTS);
        let result = resolver.resolve("test", Path::new("/src"), Path::new("/proj"));
        assert_eq!(result, Some(PathBuf::from("/proj/test.ts")));
    }

    #[test]
    fn node_resolver_uses_configured_extensions() {
        fn fallback(raw: &str, _source: &Path, _root: &Path) -> Option<PathBuf> {
            Some(PathBuf::from(raw))
        }
        let temp = std::env::temp_dir().join("node_resolver_uses_configured_extensions");
        if temp.exists() {
            let _ = std::fs::remove_dir_all(&temp);
        }
        std::fs::create_dir_all(&temp).unwrap();
        let target = temp.join("mod.json");
        std::fs::write(&target, "{}").unwrap();

        let js = NodeResolver::new(fallback, JS_EXTS);
        assert_eq!(js.resolve("./mod", &temp, &temp), Some(target.clone()));

        let ts = NodeResolver::new(fallback, TS_EXTS);
        assert_eq!(
            ts.resolve("./mod", &temp, &temp),
            Some(PathBuf::from("./mod"))
        );

        let _ = std::fs::remove_dir_all(&temp);
    }

    #[test]
    fn shared_quote_strip_helpers() {
        assert_eq!(strip_import_quotes("\"react\""), "react");
        assert_eq!(strip_c_family_quotes("<stdio.h>"), "stdio.h");
    }

    fn scratch(name: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("meta_ast_resolver_{name}"));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    fn touch(path: &Path) {
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(path, "").unwrap();
    }

    fn resolved(
        lang: crate::language::LangId,
        raw: &str,
        source_dir: &Path,
        root: &Path,
    ) -> Option<PathBuf> {
        make_resolver(lang).resolve(raw, source_dir, root)
    }

    #[test]
    fn python_level_two_relative_import_uses_the_parent_package() {
        let root = scratch("py_level_two");
        let pkg = root.join("pkg");
        touch(&root.join("util.py"));
        touch(&pkg.join("util.py"));

        let out = resolved(crate::language::LangId::Python, "..util", &pkg, &root);
        assert_eq!(out, Some(root.join("util.py")));
    }

    #[test]
    fn python_third_party_import_is_not_a_project_path() {
        let root = scratch("py_third_party");
        let pkg = root.join("pkg");
        touch(&pkg.join("__init__.py"));

        let out = resolved(crate::language::LangId::Python, "requests", &pkg, &root);
        assert_eq!(out, None);
    }

    #[test]
    fn python_first_party_relative_import_still_resolves() {
        let root = scratch("py_first_party");
        let pkg = root.join("pkg");
        touch(&pkg.join("util.py"));

        let out = resolved(crate::language::LangId::Python, ".util", &pkg, &root);
        assert_eq!(out, Some(pkg.join("util.py")));
    }

    #[test]
    fn python_dotted_import_resolves_when_the_file_exists() {
        let root = scratch("py_dotted");
        touch(&root.join("svc/api.py"));

        let out = resolved(crate::language::LangId::Python, "svc.api", &root, &root);
        assert_eq!(out, Some(root.join("svc/api.py")));
    }

    #[test]
    fn go_relative_import_is_rejected() {
        let root = scratch("go_relative");
        let out = resolved(crate::language::LangId::Go, "\"./util\"", &root, &root);
        assert_eq!(out, None);
    }

    #[test]
    fn go_module_prefix_requires_a_boundary() {
        let root = scratch("go_prefix");
        std::fs::write(root.join("go.mod"), "module myproject\n").unwrap();

        let out = resolved(
            crate::language::LangId::Go,
            "\"myproject2/pkg\"",
            &root,
            &root,
        );
        assert_eq!(out, None);
    }

    #[test]
    fn go_module_import_of_a_subpackage_resolves() {
        let root = scratch("go_subpackage");
        std::fs::write(root.join("go.mod"), "module myproject\n").unwrap();

        let out = resolved(
            crate::language::LangId::Go,
            "\"myproject/internal/util\"",
            &root,
            &root,
        );
        assert_eq!(out, Some(root.join("internal/util.go")));
    }

    #[test]
    fn c_system_include_is_not_a_project_path() {
        let root = scratch("c_system_include");
        let src = root.join("src");
        std::fs::create_dir_all(&src).unwrap();

        let out = resolved(crate::language::LangId::C, "<stdio.h>", &src, &root);
        assert_eq!(out, None);
    }

    #[test]
    fn c_missing_quoted_include_is_not_a_project_path() {
        let root = scratch("c_missing_include");
        let src = root.join("src");
        std::fs::create_dir_all(&src).unwrap();

        let out = resolved(crate::language::LangId::C, "\"missing.h\"", &src, &root);
        assert_eq!(out, None);
    }

    #[test]
    fn c_existing_quoted_include_resolves() {
        let root = scratch("c_existing_include");
        let src = root.join("src");
        touch(&src.join("local.h"));

        let out = resolved(crate::language::LangId::C, "\"local.h\"", &src, &root);
        assert_eq!(out, Some(src.join("local.h")));
    }

    #[test]
    fn rust_crate_path_walks_all_segments() {
        let root = scratch("rust_crate_path");
        let src = root.join("src");
        touch(&src.join("a/b.rs"));

        let out = resolved(
            crate::language::LangId::Rust,
            "\"crate::a::b\"",
            &src,
            &root,
        );
        assert_eq!(out, Some(src.join("a/b.rs")));
    }

    #[test]
    fn rust_self_path_resolves_within_the_module() {
        let root = scratch("rust_self_path");
        let src = root.join("src");
        touch(&src.join("here.rs"));

        let out = resolved(crate::language::LangId::Rust, "\"self::here\"", &src, &root);
        assert_eq!(out, Some(src.join("here.rs")));
    }

    #[test]
    fn go_mod_resolver_resolves_import() {
        fn dummy_go_resolver(raw: &str, _source: &Path, root: &Path) -> Option<PathBuf> {
            Some(root.join(format!("{raw}.go")))
        }
        let resolver = GoModResolver::new(dummy_go_resolver);
        let result = resolver.resolve("test", Path::new("/src"), Path::new("/proj"));
        assert_eq!(result, Some(PathBuf::from("/proj/test.go")));
    }

    #[test]
    fn go_mod_resolver_memoizes_go_mod_file() {
        let temp_dir = std::env::temp_dir().join("go_mod_resolver_memoizes_go_mod_file");
        if temp_dir.exists() {
            let _ = std::fs::remove_dir_all(&temp_dir);
        }
        std::fs::create_dir_all(&temp_dir).unwrap();
        let go_mod_path = temp_dir.join("go.mod");
        std::fs::write(&go_mod_path, "module myproject\n").unwrap();

        let resolver = make_resolver(crate::language::LangId::Go);

        // First resolve: should succeed and read from disk
        let res1 = resolver.resolve("myproject/sub", &temp_dir, &temp_dir);
        assert_eq!(res1, Some(temp_dir.join("sub.go")));

        // Delete go.mod from disk!
        std::fs::remove_file(&go_mod_path).unwrap();

        // Second resolve: should STILL succeed because the resolver memoized the module name!
        let res2 = resolver.resolve("myproject/other", &temp_dir, &temp_dir);
        assert_eq!(res2, Some(temp_dir.join("other.go")));

        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[test]
    fn python_resolver_memoizes_exists_checks() {
        let temp_dir = std::env::temp_dir().join("python_resolver_memoizes_exists_checks");
        if temp_dir.exists() {
            let _ = std::fs::remove_dir_all(&temp_dir);
        }
        std::fs::create_dir_all(&temp_dir).unwrap();
        let pkg_dir = temp_dir.join("my_package");
        std::fs::create_dir_all(&pkg_dir).unwrap();
        let init_py = pkg_dir.join("__init__.py");
        std::fs::write(&init_py, "").unwrap();

        let resolver = make_resolver(crate::language::LangId::Python);

        // First resolve: resolves to my_package/__init__.py
        let res1 = resolver.resolve("my_package", &temp_dir, &temp_dir);
        assert_eq!(res1, Some(init_py.clone()));

        // Delete __init__.py from disk
        std::fs::remove_file(&init_py).unwrap();

        // Second resolve: should STILL return my_package/__init__.py because the resolver memoized the exists() result!
        let res2 = resolver.resolve("my_package", &temp_dir, &temp_dir);
        assert_eq!(res2, Some(init_py));

        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[test]
    fn tsconfig_resolver_memoizes_is_file_checks() {
        let temp_dir = std::env::temp_dir().join("tsconfig_resolver_memoizes_is_file_checks");
        if temp_dir.exists() {
            let _ = std::fs::remove_dir_all(&temp_dir);
        }
        std::fs::create_dir_all(&temp_dir).unwrap();
        let ts_file = temp_dir.join("my_file.ts");
        std::fs::write(&ts_file, "").unwrap();

        let resolver = make_resolver(crate::language::LangId::TypeScript);

        // First resolve: resolves to my_file.ts
        let res1 = resolver.resolve("./my_file", &temp_dir, &temp_dir);
        assert_eq!(res1, Some(ts_file.clone()));

        // Delete my_file.ts
        std::fs::remove_file(&ts_file).unwrap();

        // Second resolve: should STILL return my_file.ts because it memoized the is_file() result!
        let res2 = resolver.resolve("./my_file", &temp_dir, &temp_dir);
        assert_eq!(res2, Some(ts_file));

        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[test]
    fn resolver_clear_cache_invalidates_memoized_state() {
        let temp_dir = std::env::temp_dir().join("resolver_clear_cache_invalidates_memoized_state");
        if temp_dir.exists() {
            let _ = std::fs::remove_dir_all(&temp_dir);
        }
        std::fs::create_dir_all(&temp_dir).unwrap();

        // 1. Python resolver cache invalidation
        let pkg_dir = temp_dir.join("py_pkg");
        std::fs::create_dir_all(&pkg_dir).unwrap();
        let init_py = pkg_dir.join("__init__.py");
        std::fs::write(&init_py, "").unwrap();
        let py_resolver = make_resolver(crate::language::LangId::Python);
        assert_eq!(
            py_resolver.resolve("py_pkg", &temp_dir, &temp_dir),
            Some(init_py.clone())
        );
        std::fs::remove_file(&init_py).unwrap();
        // Still cached:
        assert_eq!(
            py_resolver.resolve("py_pkg", &temp_dir, &temp_dir),
            Some(init_py.clone())
        );
        // Invalidate:
        py_resolver.clear_cache();
        assert_eq!(py_resolver.resolve("py_pkg", &temp_dir, &temp_dir), None);

        // 2. Go resolver cache invalidation
        let go_mod_path = temp_dir.join("go.mod");
        std::fs::write(&go_mod_path, "module oldmod\n").unwrap();
        let go_resolver = make_resolver(crate::language::LangId::Go);
        assert_eq!(
            go_resolver.resolve("oldmod/sub", &temp_dir, &temp_dir),
            Some(temp_dir.join("sub.go"))
        );
        std::fs::write(&go_mod_path, "module newmod\n").unwrap();
        // Still cached to oldmod:
        assert_eq!(
            go_resolver.resolve("oldmod/sub", &temp_dir, &temp_dir),
            Some(temp_dir.join("sub.go"))
        );
        // Invalidate:
        go_resolver.clear_cache();
        assert_eq!(
            go_resolver.resolve("oldmod/sub", &temp_dir, &temp_dir),
            None
        );
        assert_eq!(
            go_resolver.resolve("newmod/sub", &temp_dir, &temp_dir),
            Some(temp_dir.join("sub.go"))
        );

        // 3. TypeScript resolver cache invalidation
        let ts_file = temp_dir.join("ts_file.ts");
        std::fs::write(&ts_file, "").unwrap();
        let ts_resolver = make_resolver(crate::language::LangId::TypeScript);
        assert_eq!(
            ts_resolver.resolve("./ts_file", &temp_dir, &temp_dir),
            Some(ts_file.clone())
        );
        std::fs::remove_file(&ts_file).unwrap();
        // Still cached:
        assert_eq!(
            ts_resolver.resolve("./ts_file", &temp_dir, &temp_dir),
            Some(ts_file)
        );
        // Invalidate:
        ts_resolver.clear_cache();
        assert_eq!(
            ts_resolver.resolve("./ts_file", &temp_dir, &temp_dir),
            Some(temp_dir.join("./ts_file"))
        );

        let _ = std::fs::remove_dir_all(&temp_dir);
    }
    #[test]
    fn python_resolver_finds_a_module_created_after_a_miss() {
        fn no_fallback(_raw: &str, _source: &Path, _root: &Path) -> Option<PathBuf> {
            None
        }

        let root = std::env::temp_dir().join("resolver_python_created_after_miss");
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(&root).unwrap();

        let resolver = PythonResolver::new(no_fallback);
        assert!(
            resolver.resolve("pkg", &root, &root).is_none(),
            "the module does not exist yet"
        );

        let (init, _module) = python_candidate_paths("pkg", &root, &root).unwrap();
        std::fs::create_dir_all(init.parent().unwrap()).unwrap();
        std::fs::write(&init, "").unwrap();

        assert_eq!(
            resolver.resolve("pkg", &root, &root),
            Some(init),
            "a module created after the first miss must resolve"
        );

        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn go_resolver_sees_a_module_file_created_after_a_miss() {
        fn no_fallback(_raw: &str, _source: &Path, _root: &Path) -> Option<PathBuf> {
            None
        }

        let root = std::env::temp_dir().join("resolver_go_created_after_miss");
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(&root).unwrap();

        let resolver = GoModResolver::new(no_fallback);
        assert!(
            resolver
                .resolve("example.com/mod/util", &root, &root)
                .is_none(),
            "there is no go.mod yet"
        );

        std::fs::write(root.join("go.mod"), "module example.com/mod\n\ngo 1.22\n").unwrap();

        assert_eq!(
            resolver.resolve("example.com/mod/util", &root, &root),
            Some(root.join("util").with_extension("go")),
            "a go.mod written after the first miss must change the answer"
        );

        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn node_resolver_finds_a_file_created_after_a_miss() {
        fn no_fallback(_raw: &str, _source: &Path, _root: &Path) -> Option<PathBuf> {
            None
        }

        let root = std::env::temp_dir().join("resolver_node_created_after_miss");
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(&root).unwrap();

        let resolver = NodeResolver::new(no_fallback, JS_EXTS);
        assert!(
            resolver.resolve("./util", &root, &root).is_none(),
            "the file does not exist yet"
        );

        let created = root.join("util.js");
        std::fs::write(&created, "module.exports = {};\n").unwrap();

        assert_eq!(
            resolver.resolve("./util", &root, &root),
            Some(created),
            "a file created after the first miss must resolve"
        );

        let _ = std::fs::remove_dir_all(&root);
    }
}