Skip to main content

lean_ctx/core/import_resolver/
languages.rs

1//! Per-language import resolvers.
2//!
3//! Each `resolve_*` maps a language's import specifier to a project file path and
4//! is dispatched from the parent module's `resolve_one`. Language-private helpers (path
5//! probing, stdlib checks) stay private to this module.
6
7#[allow(clippy::wildcard_imports)]
8use super::*;
9
10// ---------------------------------------------------------------------------
11// TypeScript / JavaScript
12// ---------------------------------------------------------------------------
13
14pub fn resolve_ts(
15    imp: &ImportInfo,
16    file_path: &str,
17    ctx: &ResolverContext,
18) -> (Option<String>, bool) {
19    let source = &imp.source;
20
21    if source.starts_with('.') {
22        let dir = Path::new(file_path).parent().unwrap_or(Path::new(""));
23        let resolved = dir.join(source);
24        let normalized = normalize_path(&resolved);
25
26        if let Some(found) = try_ts_with_js_remap(&normalized, ctx) {
27            return (Some(found), false);
28        }
29        return (None, false);
30    }
31
32    if let Some(mapped) = resolve_tsconfig_path(source, ctx) {
33        return (Some(mapped), false);
34    }
35
36    (None, true)
37}
38
39/// Resolve a TS/JS import path, handling the TypeScript convention where
40/// `.js` specifiers in `.ts` files resolve to `.ts` sources.
41/// See: <https://www.typescriptlang.org/docs/handbook/modules/reference.html#relative-file-path-resolution>
42fn try_ts_with_js_remap(base: &str, ctx: &ResolverContext) -> Option<String> {
43    const JS_TO_TS: &[(&str, &[&str])] = &[
44        (".js", &[".ts", ".tsx"]),
45        (".jsx", &[".tsx", ".ts"]),
46        (".mjs", &[".mts"]),
47        (".cjs", &[".cts"]),
48    ];
49
50    for &(js_ext, ts_exts) in JS_TO_TS {
51        if let Some(stem) = base.strip_suffix(js_ext) {
52            for ts_ext in ts_exts {
53                let candidate = format!("{stem}{ts_ext}");
54                if ctx.file_exists(&candidate) {
55                    return Some(candidate);
56                }
57            }
58        }
59    }
60
61    try_ts_extensions(base, ctx)
62}
63
64fn try_ts_extensions(base: &str, ctx: &ResolverContext) -> Option<String> {
65    let extensions = [".ts", ".tsx", ".js", ".jsx", ".d.ts"];
66
67    if ctx.file_exists(base) {
68        return Some(base.to_string());
69    }
70
71    for ext in &extensions {
72        let with_ext = format!("{base}{ext}");
73        if ctx.file_exists(&with_ext) {
74            return Some(with_ext);
75        }
76    }
77
78    let index_extensions = ["index.ts", "index.tsx", "index.js", "index.jsx"];
79    for idx in &index_extensions {
80        let index_path = format!("{base}/{idx}");
81        if ctx.file_exists(&index_path) {
82            return Some(index_path);
83        }
84    }
85
86    None
87}
88
89fn resolve_tsconfig_path(source: &str, ctx: &ResolverContext) -> Option<String> {
90    for (pattern, target) in &ctx.tsconfig_paths {
91        let prefix = pattern.trim_end_matches('*');
92        if let Some(remainder) = source.strip_prefix(prefix) {
93            let target_base = target.trim_end_matches('*');
94            let candidate = format!("{target_base}{remainder}");
95            if let Some(found) = try_ts_with_js_remap(&candidate, ctx) {
96                return Some(found);
97            }
98        }
99    }
100    None
101}
102
103// ---------------------------------------------------------------------------
104// Rust
105// ---------------------------------------------------------------------------
106
107pub fn resolve_rust(
108    imp: &ImportInfo,
109    file_path: &str,
110    ctx: &ResolverContext,
111) -> (Option<String>, bool) {
112    let source = &imp.source;
113
114    if source.starts_with("crate::")
115        || source.starts_with("super::")
116        || source.starts_with("self::")
117    {
118        let cleaned = source.replace("crate::", "").replace("self::", "");
119
120        let resolved = if source.starts_with("super::") {
121            let dir = Path::new(file_path).parent().and_then(|p| p.parent());
122            match dir {
123                Some(d) => {
124                    let rest = source.trim_start_matches("super::");
125                    d.join(rest.replace("::", "/"))
126                        .to_string_lossy()
127                        .to_string()
128                }
129                None => cleaned.replace("::", "/"),
130            }
131        } else {
132            cleaned.replace("::", "/")
133        };
134
135        if let Some(found) = try_rust_paths(&resolved, ctx) {
136            return (Some(found), false);
137        }
138        return (None, false);
139    }
140
141    let parts: Vec<&str> = source.split("::").collect();
142    if parts.is_empty() {
143        return (None, true);
144    }
145
146    let is_external = !source.starts_with("crate")
147        && !source.starts_with("super")
148        && !source.starts_with("self")
149        && !ctx.file_paths.iter().any(|f| {
150            let stem = Path::new(f)
151                .file_stem()
152                .and_then(|s| s.to_str())
153                .unwrap_or("");
154            stem == parts[0] || f.contains(&format!("/{}/", parts[0]))
155        });
156
157    if is_external {
158        return (None, true);
159    }
160
161    let as_path = source.replace("::", "/");
162    if let Some(found) = try_rust_paths(&as_path, ctx) {
163        return (Some(found), false);
164    }
165
166    (None, is_external)
167}
168
169fn try_rust_paths(base: &str, ctx: &ResolverContext) -> Option<String> {
170    let prefixes = ["", "src/", "rust/src/"];
171    for prefix in &prefixes {
172        let candidate = format!("{prefix}{base}.rs");
173        if ctx.file_exists(&candidate) {
174            return Some(candidate);
175        }
176        let mod_candidate = format!("{prefix}{base}/mod.rs");
177        if ctx.file_exists(&mod_candidate) {
178            return Some(mod_candidate);
179        }
180    }
181
182    let parts: Vec<&str> = base.rsplitn(2, '/').collect();
183    if parts.len() == 2 {
184        let parent = parts[1];
185        for prefix in &prefixes {
186            let candidate = format!("{prefix}{parent}.rs");
187            if ctx.file_exists(&candidate) {
188                return Some(candidate);
189            }
190        }
191    }
192
193    None
194}
195
196// ---------------------------------------------------------------------------
197// Python
198// ---------------------------------------------------------------------------
199
200pub fn resolve_python(
201    imp: &ImportInfo,
202    file_path: &str,
203    ctx: &ResolverContext,
204) -> (Option<String>, bool) {
205    let source = &imp.source;
206
207    if source.starts_with('.') {
208        let dot_count = source.chars().take_while(|c| *c == '.').count();
209        let module_part = &source[dot_count..];
210
211        let mut dir = Path::new(file_path).parent().unwrap_or(Path::new(""));
212        for _ in 1..dot_count {
213            dir = dir.parent().unwrap_or(Path::new(""));
214        }
215
216        let as_path = module_part.replace('.', "/");
217        let base = if as_path.is_empty() {
218            dir.to_string_lossy().to_string()
219        } else {
220            format!("{}/{as_path}", dir.display())
221        };
222
223        if let Some(found) = try_python_paths(&base, ctx) {
224            return (Some(found), false);
225        }
226        return (None, false);
227    }
228
229    let as_path = source.replace('.', "/");
230
231    if let Some(found) = try_python_paths(&as_path, ctx) {
232        return (Some(found), false);
233    }
234
235    let is_stdlib = is_python_stdlib(source);
236    (
237        None,
238        is_stdlib || !ctx.file_paths.iter().any(|f| f.contains(&as_path)),
239    )
240}
241
242fn try_python_paths(base: &str, ctx: &ResolverContext) -> Option<String> {
243    let py_file = format!("{base}.py");
244    if ctx.file_exists(&py_file) {
245        return Some(py_file);
246    }
247
248    let init_file = format!("{base}/__init__.py");
249    if ctx.file_exists(&init_file) {
250        return Some(init_file);
251    }
252
253    let prefixes = ["src/", "lib/"];
254    for prefix in &prefixes {
255        let candidate = format!("{prefix}{base}.py");
256        if ctx.file_exists(&candidate) {
257            return Some(candidate);
258        }
259        let init = format!("{prefix}{base}/__init__.py");
260        if ctx.file_exists(&init) {
261            return Some(init);
262        }
263    }
264
265    None
266}
267
268fn is_python_stdlib(module: &str) -> bool {
269    let first = module.split('.').next().unwrap_or(module);
270    matches!(
271        first,
272        "os" | "sys"
273            | "json"
274            | "re"
275            | "math"
276            | "datetime"
277            | "typing"
278            | "collections"
279            | "itertools"
280            | "functools"
281            | "pathlib"
282            | "io"
283            | "abc"
284            | "enum"
285            | "dataclasses"
286            | "logging"
287            | "unittest"
288            | "argparse"
289            | "subprocess"
290            | "threading"
291            | "multiprocessing"
292            | "socket"
293            | "http"
294            | "urllib"
295            | "hashlib"
296            | "hmac"
297            | "secrets"
298            | "time"
299            | "copy"
300            | "pprint"
301            | "textwrap"
302            | "shutil"
303            | "tempfile"
304            | "glob"
305            | "fnmatch"
306            | "contextlib"
307            | "inspect"
308            | "importlib"
309            | "pickle"
310            | "shelve"
311            | "csv"
312            | "configparser"
313            | "struct"
314            | "codecs"
315            | "string"
316            | "difflib"
317            | "ast"
318            | "dis"
319            | "traceback"
320            | "warnings"
321            | "concurrent"
322            | "asyncio"
323            | "signal"
324            | "select"
325    )
326}
327
328// ---------------------------------------------------------------------------
329// Go
330// ---------------------------------------------------------------------------
331
332pub fn resolve_go(imp: &ImportInfo, ctx: &ResolverContext) -> (Option<String>, bool) {
333    let source = &imp.source;
334
335    if let Some(ref go_mod) = ctx.go_module
336        && source.starts_with(go_mod.as_str())
337    {
338        let relative = source.strip_prefix(go_mod.as_str()).unwrap_or(source);
339        let relative = relative.trim_start_matches('/');
340
341        if let Some(found) = try_go_package(relative, ctx) {
342            return (Some(found), false);
343        }
344        return (None, false);
345    }
346
347    if let Some(found) = try_go_package(source, ctx) {
348        return (Some(found), false);
349    }
350
351    (None, true)
352}
353
354fn try_go_package(pkg_path: &str, ctx: &ResolverContext) -> Option<String> {
355    for file in &ctx.file_paths {
356        let p = Path::new(file.as_str());
357        if p.extension().and_then(|e| e.to_str()) != Some("go") {
358            continue;
359        }
360        if file.ends_with("_test.go") {
361            continue;
362        }
363        let dir = p.parent()?.to_string_lossy();
364        if dir == pkg_path || dir.ends_with(pkg_path) {
365            return Some(file.clone());
366        }
367    }
368    None
369}
370
371// ---------------------------------------------------------------------------
372// Java
373// ---------------------------------------------------------------------------
374
375pub fn resolve_java(imp: &ImportInfo, ctx: &ResolverContext) -> (Option<String>, bool) {
376    let source = &imp.source;
377
378    if source.starts_with("java.") || source.starts_with("javax.") || source.starts_with("sun.") {
379        return (None, true);
380    }
381
382    let parts: Vec<&str> = source.rsplitn(2, '.').collect();
383    if parts.len() < 2 {
384        return (None, true);
385    }
386
387    let class_name = parts[0];
388    let package_path = parts[1].replace('.', "/");
389    let file_path = format!("{package_path}/{class_name}.java");
390
391    let search_roots = ["", "src/main/java/", "src/", "app/src/main/java/"];
392    for root in &search_roots {
393        let candidate = format!("{root}{file_path}");
394        if ctx.file_exists(&candidate) {
395            return (Some(candidate), false);
396        }
397    }
398
399    (
400        None,
401        !ctx.file_paths.iter().any(|f| f.contains(&package_path)),
402    )
403}
404
405// ---------------------------------------------------------------------------
406// Kotlin
407// ---------------------------------------------------------------------------
408
409pub fn resolve_kotlin(imp: &ImportInfo, ctx: &ResolverContext) -> (Option<String>, bool) {
410    let source = &imp.source;
411
412    if source.starts_with("java.")
413        || source.starts_with("javax.")
414        || source.starts_with("kotlin.")
415        || source.starts_with("kotlinx.")
416        || source.starts_with("android.")
417        || source.starts_with("androidx.")
418        || source.starts_with("org.junit.")
419        || source.starts_with("org.jetbrains.")
420    {
421        return (None, true);
422    }
423
424    let parts: Vec<&str> = source.rsplitn(2, '.').collect();
425    if parts.len() < 2 {
426        return (None, true);
427    }
428
429    let class_name = parts[0];
430    let package_path = parts[1].replace('.', "/");
431
432    let search_roots = [
433        "",
434        "src/main/kotlin/",
435        "src/main/java/",
436        "src/",
437        "app/src/main/kotlin/",
438        "app/src/main/java/",
439        "src/commonMain/kotlin/",
440    ];
441
442    for root in &search_roots {
443        for ext in &["kt", "kts", "java"] {
444            let candidate = format!("{root}{package_path}/{class_name}.{ext}");
445            if ctx.file_exists(&candidate) {
446                return (Some(candidate), false);
447            }
448        }
449    }
450
451    (
452        None,
453        !ctx.file_paths.iter().any(|f| f.contains(&package_path)),
454    )
455}
456
457// ---------------------------------------------------------------------------
458// C / C++
459// ---------------------------------------------------------------------------
460
461pub fn resolve_c_like(
462    imp: &ImportInfo,
463    file_path: &str,
464    ctx: &ResolverContext,
465) -> (Option<String>, bool) {
466    let source = imp.source.trim();
467    if source.is_empty() {
468        return (None, true);
469    }
470
471    let try_prefixes = |prefixes: &[&str], rel: &str| -> Option<String> {
472        let rel = rel.trim_start_matches("./").trim_start_matches('/');
473        let mut candidates: Vec<String> = vec![rel.to_string()];
474        for ext in [".h", ".hpp", ".c", ".cpp"] {
475            if !rel.ends_with(ext) {
476                candidates.push(format!("{rel}{ext}"));
477            }
478        }
479        for prefix in prefixes {
480            for c in &candidates {
481                let p = format!("{prefix}{c}");
482                if ctx.file_exists(&p) {
483                    return Some(p);
484                }
485            }
486        }
487        None
488    };
489
490    if source.starts_with('.') {
491        let dir = Path::new(file_path).parent().unwrap_or(Path::new(""));
492        let dir_prefix = if dir.as_os_str().is_empty() {
493            String::new()
494        } else {
495            format!("{}/", dir.to_string_lossy())
496        };
497        if let Some(found) = try_prefixes(&[dir_prefix.as_str()], source) {
498            return (Some(found), false);
499        }
500        return (None, false);
501    }
502
503    if ctx.file_exists(source) {
504        return (Some(source.to_string()), false);
505    }
506
507    if let Some(found) = try_prefixes(&["", "include/", "src/"], source) {
508        return (Some(found), false);
509    }
510
511    (None, true)
512}
513
514// ---------------------------------------------------------------------------
515// Ruby
516// ---------------------------------------------------------------------------
517
518pub fn resolve_ruby(
519    imp: &ImportInfo,
520    file_path: &str,
521    ctx: &ResolverContext,
522) -> (Option<String>, bool) {
523    let source = imp.source.trim();
524    if source.is_empty() {
525        return (None, true);
526    }
527    let source_rel = source.trim_start_matches("./").trim_start_matches('/');
528
529    let try_prefixes = |prefixes: &[&str]| -> Option<String> {
530        let mut candidates: Vec<String> = vec![source_rel.to_string()];
531        if !Path::new(source_rel)
532            .extension()
533            .is_some_and(|e| e.eq_ignore_ascii_case("rb"))
534        {
535            candidates.push(format!("{source_rel}.rb"));
536        }
537        for prefix in prefixes {
538            for c in &candidates {
539                let p = format!("{prefix}{c}");
540                if ctx.file_exists(&p) {
541                    return Some(p);
542                }
543            }
544        }
545        None
546    };
547
548    if source.starts_with('.') || source_rel.contains('/') {
549        let dir = Path::new(file_path).parent().unwrap_or(Path::new(""));
550        let dir_prefix = if dir.as_os_str().is_empty() {
551            String::new()
552        } else {
553            format!("{}/", dir.to_string_lossy())
554        };
555        if let Some(found) = try_prefixes(&[dir_prefix.as_str()]) {
556            return (Some(found), false);
557        }
558        if let Some(found) = try_prefixes(&["", "lib/", "src/"]) {
559            return (Some(found), false);
560        }
561        return (None, false);
562    }
563
564    (None, true)
565}
566
567// ---------------------------------------------------------------------------
568// PHP
569// ---------------------------------------------------------------------------
570
571pub fn resolve_php(
572    imp: &ImportInfo,
573    file_path: &str,
574    ctx: &ResolverContext,
575) -> (Option<String>, bool) {
576    let source = imp.source.trim();
577    if source.is_empty() {
578        return (None, true);
579    }
580    if source.starts_with("http://") || source.starts_with("https://") {
581        return (None, true);
582    }
583    let source_rel = source.trim_start_matches("./").trim_start_matches('/');
584
585    let try_prefixes = |prefixes: &[&str]| -> Option<String> {
586        let mut candidates: Vec<String> = vec![source_rel.to_string()];
587        if !Path::new(source_rel)
588            .extension()
589            .is_some_and(|e| e.eq_ignore_ascii_case("php"))
590        {
591            candidates.push(format!("{source_rel}.php"));
592        }
593        for prefix in prefixes {
594            for c in &candidates {
595                let p = format!("{prefix}{c}");
596                if ctx.file_exists(&p) {
597                    return Some(p);
598                }
599            }
600        }
601        None
602    };
603
604    if source.starts_with('.') || source.starts_with('/') || source_rel.contains('/') {
605        let dir = Path::new(file_path).parent().unwrap_or(Path::new(""));
606        let dir_prefix = if dir.as_os_str().is_empty() {
607            String::new()
608        } else {
609            format!("{}/", dir.to_string_lossy())
610        };
611        if let Some(found) = try_prefixes(&[dir_prefix.as_str()]) {
612            return (Some(found), false);
613        }
614        if let Some(found) = try_prefixes(&["", "src/", "lib/"]) {
615            return (Some(found), false);
616        }
617        return (None, false);
618    }
619
620    (None, true)
621}
622
623// ---------------------------------------------------------------------------
624// Bash
625// ---------------------------------------------------------------------------
626
627pub fn resolve_bash(
628    imp: &ImportInfo,
629    file_path: &str,
630    ctx: &ResolverContext,
631) -> (Option<String>, bool) {
632    let source = imp.source.trim();
633    if source.is_empty() {
634        return (None, true);
635    }
636    let source_rel = source.trim_start_matches("./").trim_start_matches('/');
637
638    let try_prefixes = |prefixes: &[&str]| -> Option<String> {
639        let mut candidates: Vec<String> = vec![source_rel.to_string()];
640        if !Path::new(source_rel)
641            .extension()
642            .is_some_and(|e| e.eq_ignore_ascii_case("sh"))
643        {
644            candidates.push(format!("{source_rel}.sh"));
645        }
646        for prefix in prefixes {
647            for c in &candidates {
648                let p = format!("{prefix}{c}");
649                if ctx.file_exists(&p) {
650                    return Some(p);
651                }
652            }
653        }
654        None
655    };
656
657    if source.starts_with('.') || source.starts_with('/') || source_rel.contains('/') {
658        let dir = Path::new(file_path).parent().unwrap_or(Path::new(""));
659        let dir_prefix = if dir.as_os_str().is_empty() {
660            String::new()
661        } else {
662            format!("{}/", dir.to_string_lossy())
663        };
664        if let Some(found) = try_prefixes(&[dir_prefix.as_str()]) {
665            return (Some(found), false);
666        }
667        if let Some(found) = try_prefixes(&["", "scripts/", "bin/"]) {
668            return (Some(found), false);
669        }
670        return (None, false);
671    }
672
673    (None, true)
674}
675
676// ---------------------------------------------------------------------------
677// Dart
678// ---------------------------------------------------------------------------
679
680pub fn resolve_dart(
681    imp: &ImportInfo,
682    file_path: &str,
683    ctx: &ResolverContext,
684) -> (Option<String>, bool) {
685    let source = imp.source.trim();
686    if source.is_empty() {
687        return (None, true);
688    }
689    if source.starts_with("dart:") {
690        return (None, true);
691    }
692
693    let try_prefixes = |prefixes: &[&str], rel: &str| -> Option<String> {
694        let rel = rel.trim_start_matches("./").trim_start_matches('/').trim();
695        let mut candidates: Vec<String> = vec![rel.to_string()];
696        if !Path::new(rel)
697            .extension()
698            .is_some_and(|e| e.eq_ignore_ascii_case("dart"))
699        {
700            candidates.push(format!("{rel}.dart"));
701        }
702        for prefix in prefixes {
703            for c in &candidates {
704                let p = format!("{prefix}{c}");
705                if ctx.file_exists(&p) {
706                    return Some(p);
707                }
708            }
709        }
710        None
711    };
712
713    if source.starts_with("package:") {
714        if let Some(pkg) = ctx.dart_package.as_deref() {
715            let prefix = format!("package:{pkg}/");
716            if let Some(rest) = source.strip_prefix(&prefix) {
717                if let Some(found) = try_prefixes(&["lib/", ""], rest) {
718                    return (Some(found), false);
719                }
720                return (None, false);
721            }
722        }
723        return (None, true);
724    }
725
726    if source.starts_with('.') || source.starts_with('/') {
727        let dir = Path::new(file_path).parent().unwrap_or(Path::new(""));
728        let dir_prefix = if dir.as_os_str().is_empty() {
729            String::new()
730        } else {
731            format!("{}/", dir.to_string_lossy())
732        };
733        if let Some(found) = try_prefixes(&[dir_prefix.as_str()], source) {
734            return (Some(found), false);
735        }
736        if let Some(found) = try_prefixes(&["", "lib/"], source) {
737            return (Some(found), false);
738        }
739        return (None, false);
740    }
741
742    (None, true)
743}
744
745// ---------------------------------------------------------------------------
746// GDScript (Godot)
747// ---------------------------------------------------------------------------
748
749/// Resolves GDScript `extends "res://…"` and `preload`/`load` resource paths.
750/// `res://` is anchored at the project root; `user://` is a runtime data path
751/// (never a source file); other paths are resolved relative to the importer.
752pub fn resolve_gd(
753    imp: &ImportInfo,
754    file_path: &str,
755    ctx: &ResolverContext,
756) -> (Option<String>, bool) {
757    let source = imp.source.trim();
758    if source.is_empty() {
759        return (None, true);
760    }
761
762    // Probe the verbatim path first (the common `preload("…/Foo.tscn")` form
763    // already carries its extension), then Godot resource suffixes for imports
764    // that omit one (`extends "res://actors/Player"`). #315
765    let try_paths = |rel: &str| -> Option<String> {
766        let rel = rel.trim();
767        if ctx.file_exists(rel) {
768            return Some(rel.to_string());
769        }
770        if Path::new(rel).extension().is_none() {
771            for ext in ["gd", "tscn", "tres"] {
772                let candidate = format!("{rel}.{ext}");
773                if ctx.file_exists(&candidate) {
774                    return Some(candidate);
775                }
776            }
777        }
778        None
779    };
780
781    if let Some(rest) = source.strip_prefix("res://") {
782        let rel = rest.trim_start_matches('/');
783        if let Some(found) = try_paths(rel) {
784            return (Some(found), false);
785        }
786        // `res://` always names an intra-project resource. When the target is a
787        // concrete file (carries a resource extension) that simply isn't indexed
788        // yet — e.g. a `.tscn` scene before scene indexing exists (#316) — still
789        // emit the edge to the declared path so scene references survive. #315
790        if !rel.is_empty() && Path::new(rel).extension().is_some() {
791            return (Some(rel.to_string()), false);
792        }
793        return (None, false);
794    }
795
796    // Runtime user data path — not a project source file.
797    if source.starts_with("user://") {
798        return (None, true);
799    }
800
801    if source.starts_with('.') || source.contains('/') {
802        let stripped = source.trim_start_matches("./");
803        let dir = Path::new(file_path).parent().unwrap_or(Path::new(""));
804        let joined = if dir.as_os_str().is_empty() {
805            stripped.to_string()
806        } else {
807            format!("{}/{stripped}", dir.to_string_lossy())
808        };
809        if let Some(found) = try_paths(&joined) {
810            return (Some(found), false);
811        }
812        return (try_paths(stripped), false);
813    }
814
815    (None, true)
816}
817
818// ---------------------------------------------------------------------------
819// Lua / Luau
820// ---------------------------------------------------------------------------
821
822/// Resolves Lua `require("a.b.c")` (dotted module path, package.path style) and
823/// Luau `require("a/b")` / `require("./a")` (slash/relative paths) to a project
824/// file. Dotted specifiers map `.` -> `/`; pathy specifiers are used verbatim.
825/// Candidates: `<rel>.lua`, `<rel>/init.lua` (and `.luau`), probed relative to
826/// the importer first, then the project root and common source roots.
827pub fn resolve_lua(
828    imp: &ImportInfo,
829    file_path: &str,
830    ctx: &ResolverContext,
831) -> (Option<String>, bool) {
832    let source = imp.source.trim();
833    if source.is_empty() {
834        return (None, true);
835    }
836
837    // Pathy specifiers (Luau relative/slash form) are used as-is; pure dotted
838    // module names (`a.b.c`) map dots to directory separators (package.path).
839    let is_pathy = source.contains('/') || source.starts_with('.');
840    let rel = if is_pathy {
841        source
842            .trim_start_matches("./")
843            .trim_start_matches('/')
844            .to_string()
845    } else {
846        source.replace('.', "/")
847    };
848    if rel.is_empty() {
849        return (None, true);
850    }
851
852    let try_paths = |base: &str| -> Option<String> {
853        let base = base.trim_start_matches('/');
854        if ctx.file_exists(base) {
855            return Some(base.to_string());
856        }
857        for ext in ["lua", "luau"] {
858            let file = format!("{base}.{ext}");
859            if ctx.file_exists(&file) {
860                return Some(file);
861            }
862            let init = format!("{base}/init.{ext}");
863            if ctx.file_exists(&init) {
864                return Some(init);
865            }
866        }
867        None
868    };
869
870    let dir = Path::new(file_path).parent().unwrap_or(Path::new(""));
871    let relative_to_importer = || -> Option<String> {
872        if dir.as_os_str().is_empty() {
873            return None;
874        }
875        try_paths(&format!("{}/{rel}", dir.to_string_lossy()))
876    };
877    // Project root + common Lua source roots (package.path style).
878    let from_roots = || -> Option<String> {
879        try_paths(&rel).or_else(|| {
880            ["src/", "lua/", "lib/"]
881                .iter()
882                .find_map(|prefix| try_paths(&format!("{prefix}{rel}")))
883        })
884    };
885
886    // Luau slash/relative requires are importer-relative first; standard Lua
887    // dotted module names resolve from the project/source roots first.
888    let found = if is_pathy {
889        relative_to_importer().or_else(from_roots)
890    } else {
891        from_roots().or_else(relative_to_importer)
892    };
893
894    match found {
895        Some(path) => (Some(path), false),
896        None => (None, true),
897    }
898}
899
900// ---------------------------------------------------------------------------
901// Zig
902// ---------------------------------------------------------------------------
903
904pub fn resolve_zig(
905    imp: &ImportInfo,
906    file_path: &str,
907    ctx: &ResolverContext,
908) -> (Option<String>, bool) {
909    let source = imp.source.trim();
910    if source.is_empty() {
911        return (None, true);
912    }
913    let source_rel = source.trim_start_matches("./").trim_start_matches('/');
914    if source_rel == "std" {
915        return (None, true);
916    }
917
918    let try_prefixes = |prefixes: &[&str]| -> Option<String> {
919        let mut candidates: Vec<String> = vec![source_rel.to_string()];
920        if !Path::new(source_rel)
921            .extension()
922            .is_some_and(|e| e.eq_ignore_ascii_case("zig"))
923        {
924            candidates.push(format!("{source_rel}.zig"));
925        }
926        for prefix in prefixes {
927            for c in &candidates {
928                let p = format!("{prefix}{c}");
929                if ctx.file_exists(&p) {
930                    return Some(p);
931                }
932            }
933        }
934        None
935    };
936
937    if source.starts_with('.')
938        || source_rel.contains('/')
939        || Path::new(source_rel)
940            .extension()
941            .is_some_and(|e| e.eq_ignore_ascii_case("zig"))
942    {
943        let dir = Path::new(file_path).parent().unwrap_or(Path::new(""));
944        let dir_prefix = if dir.as_os_str().is_empty() {
945            String::new()
946        } else {
947            format!("{}/", dir.to_string_lossy())
948        };
949        if let Some(found) = try_prefixes(&[dir_prefix.as_str()]) {
950            return (Some(found), false);
951        }
952        if let Some(found) = try_prefixes(&["", "src/"]) {
953            return (Some(found), false);
954        }
955        return (None, false);
956    }
957
958    (None, true)
959}
960
961// ---------------------------------------------------------------------------
962// C#
963// ---------------------------------------------------------------------------
964
965pub fn resolve_csharp(imp: &ImportInfo, ctx: &ResolverContext) -> (Option<String>, bool) {
966    let ns = imp.source.trim();
967    if ns.is_empty() {
968        return (None, true);
969    }
970
971    // 1) .NET BCL / common NuGet roots are external — resolved first so a `using`
972    //    such as `System.Text` or `System.IO` can never fall through to a local
973    //    folder that happens to share the trailing segment (`Text/`, `IO/`).
974    if is_csharp_external_namespace(ns) {
975        return (None, true);
976    }
977
978    let segs: Vec<&str> = ns.split('.').filter(|s| !s.is_empty()).collect();
979    if segs.is_empty() {
980        return (None, true);
981    }
982
983    // 2) `using A.B.C` names a *namespace*. The C# root namespace (the assembly's
984    //    default namespace, possibly multi-segment) is usually NOT a folder, so we
985    //    probe every trailing folder-suffix, longest (most specific) match first.
986    if let Some(file) = probe_csharp_namespace(&segs, ctx) {
987        return (Some(file), false);
988    }
989
990    // 3) `using A.B.C` may instead import the *type* `C` from namespace `A.B`:
991    //    drop the final segment and probe the parent namespace's folder.
992    if segs.len() >= 2
993        && let Some(file) = probe_csharp_namespace(&segs[..segs.len() - 1], ctx)
994    {
995        return (Some(file), false);
996    }
997
998    // 4) Unresolved: treat as external so it neither creates a phantom edge nor
999    //    is miscounted as a missing local dependency.
1000    (None, true)
1001}
1002
1003/// Probe trailing folder-suffixes of a namespace path against the C# namespace
1004/// index, returning the representative file of the longest (most specific) match.
1005/// `["MyApp", "Models"]` probes `MyApp/Models` then `Models`, so a root namespace
1006/// that isn't mirrored as a folder (the common case) still resolves.
1007fn probe_csharp_namespace(segs: &[&str], ctx: &ResolverContext) -> Option<String> {
1008    (0..segs.len())
1009        .map(|start| segs[start..].join("/"))
1010        .find_map(|key| ctx.csharp_namespace_file(&key).map(str::to_string))
1011}
1012
1013/// Roots of the .NET BCL and common NuGet packages. A `using` whose first
1014/// segment matches one of these is an external dependency (no local edge).
1015fn is_csharp_external_namespace(ns: &str) -> bool {
1016    const EXTERNAL_ROOTS: &[&str] = &[
1017        "System",
1018        "Microsoft",
1019        "Windows",
1020        "Mono",
1021        "Newtonsoft",
1022        "NUnit",
1023        "Xunit",
1024        "Moq",
1025        "Serilog",
1026        "AutoMapper",
1027        "MediatR",
1028        "FluentValidation",
1029        "Polly",
1030        "Castle",
1031        "Dapper",
1032        "RestSharp",
1033        "Google",
1034        "Amazon",
1035        "Azure",
1036        "Grpc",
1037        "Nito",
1038        "StackExchange",
1039    ];
1040    let root = ns.split('.').next().unwrap_or(ns);
1041    EXTERNAL_ROOTS.contains(&root)
1042}
1043
1044// ---------------------------------------------------------------------------
1045// Swift
1046// ---------------------------------------------------------------------------
1047
1048pub fn resolve_swift(
1049    imp: &ImportInfo,
1050    file_path: &str,
1051    ctx: &ResolverContext,
1052) -> (Option<String>, bool) {
1053    let source = &imp.source;
1054
1055    if matches!(
1056        source.as_str(),
1057        "Foundation" | "UIKit" | "SwiftUI" | "Combine" | "CoreData" | "Darwin"
1058    ) {
1059        return (None, true);
1060    }
1061
1062    let dir = Path::new(file_path)
1063        .parent()
1064        .map(|p| p.to_string_lossy().to_string())
1065        .unwrap_or_default();
1066
1067    let candidate = if dir.is_empty() {
1068        format!("{source}.swift")
1069    } else {
1070        format!("{dir}/{source}.swift")
1071    };
1072    if ctx.file_exists(&candidate) {
1073        return (Some(candidate), false);
1074    }
1075    (None, false)
1076}
1077
1078// ---------------------------------------------------------------------------
1079// Scala
1080// ---------------------------------------------------------------------------
1081
1082pub fn resolve_scala(imp: &ImportInfo, ctx: &ResolverContext) -> (Option<String>, bool) {
1083    let source = &imp.source;
1084
1085    if source.starts_with("scala.") || source.starts_with("java.") {
1086        return (None, true);
1087    }
1088
1089    let parts: Vec<&str> = source.rsplitn(2, '.').collect();
1090    if parts.len() < 2 {
1091        return (None, true);
1092    }
1093
1094    let name = parts[0];
1095    let package_path = parts[1].replace('.', "/");
1096
1097    for ext in ["scala", "sc"] {
1098        let candidate = format!("{package_path}/{name}.{ext}");
1099        if ctx.file_exists(&candidate) {
1100            return (Some(candidate), false);
1101        }
1102    }
1103    (None, false)
1104}
1105
1106// ---------------------------------------------------------------------------
1107// Elixir
1108// ---------------------------------------------------------------------------
1109
1110pub fn resolve_elixir(
1111    imp: &ImportInfo,
1112    file_path: &str,
1113    ctx: &ResolverContext,
1114) -> (Option<String>, bool) {
1115    let source = &imp.source;
1116
1117    if source.starts_with("Kernel") || source.starts_with("Enum") || source.starts_with("IO") {
1118        return (None, true);
1119    }
1120
1121    let snake =
1122        source
1123            .replace('.', "/")
1124            .chars()
1125            .enumerate()
1126            .fold(String::new(), |mut acc, (i, c)| {
1127                if c.is_uppercase() && i > 0 && !acc.ends_with('/') {
1128                    acc.push('_');
1129                }
1130                acc.push(c.to_ascii_lowercase());
1131                acc
1132            });
1133
1134    let dir = Path::new(file_path)
1135        .parent()
1136        .map(|p| p.to_string_lossy().to_string())
1137        .unwrap_or_default();
1138
1139    for ext in ["ex", "exs"] {
1140        let candidate = format!("lib/{snake}.{ext}");
1141        if ctx.file_exists(&candidate) {
1142            return (Some(candidate), false);
1143        }
1144        if !dir.is_empty() {
1145            let local = format!("{dir}/{snake}.{ext}");
1146            if ctx.file_exists(&local) {
1147                return (Some(local), false);
1148            }
1149        }
1150    }
1151    (None, false)
1152}