Skip to main content

rust_anything/lang/
mod.rs

1//! Source languages. TypeScript/JavaScript lives in `crate::ts`; the others are plugins that
2//! produce the same workspace, facts and exports, with types mapped into the TS-like type
3//! dialect the planner, generators and port stubs use (`string`, `number`, `int`, `T[]`, ...).
4
5use std::path::Path;
6
7use serde::{Deserialize, Serialize};
8
9pub mod c;
10pub mod csharp;
11pub mod go;
12pub mod java;
13pub mod kotlin;
14pub mod php;
15pub mod powershell;
16pub mod python;
17pub mod ruby;
18pub mod syntax;
19
20/// Why an export of an overloaded name stays in the original: the bindings name each export by
21/// its name alone, so one name cannot carry several signatures.
22pub const OVERLOADED: &str = "overloaded: one name, several signatures";
23
24#[derive(
25    Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, clap::ValueEnum,
26)]
27#[serde(rename_all = "lowercase")]
28pub enum Lang {
29    #[default]
30    Ts,
31    Python,
32    C,
33    Go,
34    Ruby,
35    Java,
36    Kotlin,
37    Php,
38    Csharp,
39    Powershell,
40}
41
42impl Lang {
43    pub fn name(self) -> &'static str {
44        match self {
45            Self::Ts => "TypeScript/JavaScript",
46            Self::Python => "Python",
47            Self::C => "C",
48            Self::Go => "Go",
49            Self::Ruby => "Ruby",
50            Self::Java => "Java",
51            Self::Kotlin => "Kotlin",
52            Self::Php => "PHP",
53            Self::Csharp => "C#",
54            Self::Powershell => "PowerShell",
55        }
56    }
57
58    /// Where third-party dependencies come from in this language: used when a dependency
59    /// is not in the crate table, so a Python stdlib omission is not reported as `npm`.
60    pub fn registry(self) -> &'static str {
61        match self {
62            Self::Ts => "npm",
63            Self::Python => "PyPI",
64            Self::C => "system libraries",
65            Self::Go => "Go modules",
66            Self::Ruby => "gems",
67            Self::Java => "Maven",
68            Self::Kotlin => "Maven",
69            Self::Php => "Composer",
70            Self::Csharp => "NuGet",
71            Self::Powershell => "the PowerShell Gallery",
72        }
73    }
74
75    /// The language of a repository: from its manifest files, else its most common source files.
76    pub fn detect(root: &Path) -> Self {
77        let has = |name: &str| root.join(name).exists();
78        if has("go.mod") {
79            return Self::Go;
80        }
81        if has("pom.xml") || has("build.gradle") || has("build.gradle.kts") {
82            // A Gradle Kotlin DSL module can hold Kotlin, Java or both. Kotlin owns only a
83            // module with Kotlin sources and no Java sources; mixed modules stay Java in
84            // phase 1. `pom.xml` modules are Java unless `--lang kotlin` overrides.
85            if !has("pom.xml") && (has("build.gradle.kts") || has("build.gradle")) {
86                let mut kt = 0usize;
87                let mut java = 0usize;
88                let module = root.to_path_buf();
89                for entry in crate::walk::filtered(root, move |e| {
90                    if !e.file_type().is_some_and(|kind| kind.is_dir()) {
91                        return true;
92                    }
93                    let name = e.file_name().to_string_lossy();
94                    if ![
95                        "build",
96                        ".gradle",
97                        ".kotlin",
98                        "out",
99                        "node_modules",
100                        "target",
101                    ]
102                    .contains(&name.as_ref())
103                    {
104                        return true;
105                    }
106                    // `src/main/java/com/acme/build/` is a package, not build output.
107                    !e.path()
108                        .strip_prefix(&module)
109                        .unwrap_or(e.path())
110                        .components()
111                        .any(|c| c.as_os_str() == std::ffi::OsStr::new("src"))
112                })
113                .hidden(true)
114                .require_git(false)
115                .build()
116                .flatten()
117                {
118                    if !entry.file_type().is_some_and(|kind| kind.is_file()) {
119                        continue;
120                    }
121                    match entry.path().extension().and_then(|e| e.to_str()) {
122                        // `kts` is the Gradle Kotlin DSL build script, not Kotlin source.
123                        Some("kt") => kt += 1,
124                        Some("java") => java += 1,
125                        _ => {}
126                    }
127                }
128                if kt > 0 && java == 0 {
129                    return Self::Kotlin;
130                }
131            }
132            return Self::Java;
133        }
134        let dotnet = std::fs::read_dir(root).is_ok_and(|entries| {
135            entries.flatten().any(|e| {
136                let name = e.file_name().to_string_lossy().into_owned();
137                name.ends_with(".csproj") || name.ends_with(".sln") || name.ends_with(".slnx")
138            })
139        });
140        if dotnet || has("Directory.Build.props") {
141            return Self::Csharp;
142        }
143        if has("pyproject.toml") || has("setup.py") || has("setup.cfg") {
144            return Self::Python;
145        }
146        if has("Gemfile") {
147            return Self::Ruby;
148        }
149        if has("composer.json") {
150            return Self::Php;
151        }
152        if has("package.json") {
153            return Self::Ts;
154        }
155        let mut counts = [0usize; Self::ALL.len()];
156        for entry in crate::walk::builder(root)
157            .hidden(true)
158            .require_git(false)
159            .build()
160            .flatten()
161        {
162            let ext = entry
163                .path()
164                .extension()
165                .and_then(|e| e.to_str())
166                .unwrap_or("");
167            if !entry.file_type().is_some_and(|kind| kind.is_file()) {
168                continue;
169            }
170            if let Some(i) = Self::ALL.iter().position(|l| l.extensions().contains(&ext)) {
171                counts[i] += 1;
172            }
173        }
174        let best = (0..Self::ALL.len())
175            .max_by_key(|&i| (counts[i], std::cmp::Reverse(i)))
176            .unwrap_or(0);
177        Self::ALL[best]
178    }
179
180    const ALL: [Self; 10] = [
181        Self::Ts,
182        Self::Python,
183        Self::C,
184        Self::Go,
185        Self::Ruby,
186        Self::Java,
187        Self::Kotlin,
188        Self::Php,
189        Self::Csharp,
190        Self::Powershell,
191    ];
192
193    /// File extensions of the language's source files.
194    pub fn extensions(self) -> &'static [&'static str] {
195        match self {
196            Self::Ts => &[
197                "ts", "mts", "cts", "js", "mjs", "cjs", "tsx", "jsx", "vue", "svelte", "astro",
198            ],
199            Self::Python => &["py"],
200            Self::C => &["c", "h"],
201            Self::Go => &["go"],
202            Self::Ruby => &["rb"],
203            Self::Java => &["java"],
204            Self::Kotlin => &["kt"],
205            Self::Php => &["php"],
206            Self::Csharp => &["cs"],
207            Self::Powershell => &["ps1", "psm1"],
208        }
209    }
210}
211
212/// Where an import points, for languages other than TS.
213pub enum Resolution {
214    File(usize),
215    External(String),
216    Stdlib,
217    Unresolved,
218}
219
220pub fn discover(lang: Lang, root: &Path) -> anyhow::Result<crate::ts::discover::Workspace> {
221    match lang {
222        Lang::Python => python::discover(root),
223        Lang::C => c::discover(root),
224        Lang::Go => go::discover(root),
225        Lang::Ruby => ruby::discover(root),
226        Lang::Java => java::discover(root),
227        Lang::Kotlin => kotlin::discover(root),
228        Lang::Php => php::discover(root),
229        Lang::Csharp => csharp::discover(root),
230        Lang::Powershell => powershell::discover(root),
231        _ => anyhow::bail!("{} is not supported yet", lang.name()),
232    }
233}
234
235pub fn scan(lang: Lang, _path: &str, text: &str) -> crate::ts::scan::FileFacts {
236    match lang {
237        Lang::Python => python::scan(text),
238        Lang::C => c::scan(text),
239        Lang::Go => go::scan(text),
240        Lang::Ruby => ruby::scan(text),
241        Lang::Java => java::scan(text),
242        Lang::Kotlin => kotlin::scan(text),
243        Lang::Php => php::scan(text),
244        Lang::Csharp => csharp::scan(text),
245        Lang::Powershell => powershell::scan(text),
246        _ => crate::ts::scan::FileFacts::default(),
247    }
248}
249
250pub fn resolve(
251    lang: Lang,
252    from: &str,
253    spec: &str,
254    index: &std::collections::HashMap<&str, usize>,
255    ws: &crate::ts::discover::Workspace,
256) -> Resolution {
257    match lang {
258        Lang::Python => match python::resolve(from, spec, index, ws) {
259            python::Resolution::File(i) => Resolution::File(i),
260            python::Resolution::External(n) => Resolution::External(n),
261            python::Resolution::Stdlib => Resolution::Stdlib,
262            python::Resolution::Unresolved => Resolution::Unresolved,
263        },
264        Lang::C => c::resolve(from, spec, index),
265        Lang::Go => go::resolve(spec, index, ws),
266        Lang::Ruby => ruby::resolve(from, spec, index, ws),
267        Lang::Java => java::resolve(spec, index, ws),
268        Lang::Kotlin => kotlin::resolve(spec, index, ws),
269        Lang::Php => php::resolve(from, spec, index, ws),
270        Lang::Csharp => csharp::resolve(spec, index, ws),
271        Lang::Powershell => powershell::resolve(from, spec, index, ws),
272        _ => Resolution::Unresolved,
273    }
274}
275
276pub fn exports(
277    lang: Lang,
278    path: &str,
279    text: &str,
280) -> (
281    Vec<crate::ts::exports::ExportedFn>,
282    Vec<crate::ts::exports::ExportedClass>,
283) {
284    match lang {
285        Lang::Python => python::exports(path, text),
286        Lang::C => (c::exports(path, text), Vec::new()),
287        Lang::Go => (go::exports(path, text), Vec::new()),
288        Lang::Ruby => (ruby::exports(path, text), Vec::new()),
289        Lang::Java => (java::exports(path, text), Vec::new()),
290        Lang::Kotlin => (kotlin::exports(path, text), Vec::new()),
291        Lang::Php => (php::exports(path, text), Vec::new()),
292        Lang::Csharp => (csharp::exports(path, text), Vec::new()),
293        Lang::Powershell => (powershell::exports(path, text), Vec::new()),
294        _ => (Vec::new(), Vec::new()),
295    }
296}
297
298/// Dependency tables of the languages without their own module entry yet.
299pub fn lookup(lang: Lang, name: &str) -> Option<crate::ts::deps::CrateMatch> {
300    match lang {
301        Lang::C => c::lookup(name),
302        Lang::Go => go::lookup(name),
303        Lang::Ruby => ruby::lookup(name),
304        Lang::Java => java::lookup(name),
305        Lang::Kotlin => kotlin::lookup(name),
306        Lang::Php => php::lookup(name),
307        Lang::Csharp => csharp::lookup(name),
308        Lang::Powershell => powershell::lookup(name),
309        _ => None,
310    }
311}
312
313#[cfg(test)]
314mod tests {
315    use super::Lang;
316    use std::path::PathBuf;
317
318    fn project(name: &str, files: &[(&str, &str)]) -> PathBuf {
319        let dir = std::env::temp_dir().join(format!(
320            "rust-anything-detect-{}-{name}",
321            std::process::id()
322        ));
323        let _ = std::fs::remove_dir_all(&dir);
324        for (path, text) in files {
325            let full = dir.join(path);
326            std::fs::create_dir_all(full.parent().unwrap()).unwrap();
327            std::fs::write(full, text).unwrap();
328        }
329        dir
330    }
331
332    #[test]
333    fn kotlin_dsl_with_only_kotlin_sources_is_kotlin() {
334        let dir = project(
335            "kotlin-only",
336            &[
337                ("build.gradle.kts", "plugins { kotlin(\"jvm\") }\n"),
338                ("src/main/kotlin/com/example/A.kt", "package com.example\n"),
339            ],
340        );
341        assert_eq!(Lang::detect(&dir), Lang::Kotlin);
342        let _ = std::fs::remove_dir_all(dir);
343    }
344
345    #[test]
346    fn a_mixed_module_stays_java() {
347        let dir = project(
348            "mixed",
349            &[
350                ("build.gradle.kts", "plugins { kotlin(\"jvm\") }\n"),
351                ("src/main/kotlin/A.kt", "package a\n"),
352                ("src/main/java/B.java", "package a;\n"),
353            ],
354        );
355        assert_eq!(Lang::detect(&dir), Lang::Java);
356        let _ = std::fs::remove_dir_all(dir);
357    }
358
359    #[test]
360    fn a_build_script_alone_does_not_make_a_kotlin_project() {
361        let dir = project("script-only", &[("build.gradle.kts", "plugins { java }\n")]);
362        assert_eq!(Lang::detect(&dir), Lang::Java);
363        let _ = std::fs::remove_dir_all(dir);
364    }
365
366    #[test]
367    fn maven_with_kotlin_sources_stays_java_until_overridden() {
368        let dir = project(
369            "maven-kotlin",
370            &[
371                ("pom.xml", "<project/>\n"),
372                ("src/main/kotlin/A.kt", "package a\n"),
373            ],
374        );
375        assert_eq!(Lang::detect(&dir), Lang::Java);
376        let _ = std::fs::remove_dir_all(dir);
377    }
378}