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        Self::detect_optional(root).unwrap_or(Self::Ts)
78    }
79
80    /// Like `detect`, but returns `None` when there are no manifest files and no source files
81    /// of any supported language.
82    pub fn detect_optional(root: &Path) -> Option<Self> {
83        let has = |name: &str| root.join(name).exists();
84        if has("go.mod") {
85            return Some(Self::Go);
86        }
87        if has("pom.xml") || has("build.gradle") || has("build.gradle.kts") {
88            // A Gradle Kotlin DSL module can hold Kotlin, Java or both. Kotlin owns only a
89            // module with Kotlin sources and no Java sources; mixed modules stay Java in
90            // phase 1. `pom.xml` modules are Java unless `--lang kotlin` overrides.
91            if !has("pom.xml") && (has("build.gradle.kts") || has("build.gradle")) {
92                let mut kt = 0usize;
93                let mut java = 0usize;
94                let module = root.to_path_buf();
95                for entry in crate::walk::filtered(root, move |e| {
96                    if !e.file_type().is_some_and(|kind| kind.is_dir()) {
97                        return true;
98                    }
99                    let name = e.file_name().to_string_lossy();
100                    if ![
101                        "build",
102                        ".gradle",
103                        ".kotlin",
104                        "out",
105                        "node_modules",
106                        "target",
107                    ]
108                    .contains(&name.as_ref())
109                    {
110                        return true;
111                    }
112                    // `src/main/java/com/acme/build/` is a package, not build output.
113                    !e.path()
114                        .strip_prefix(&module)
115                        .unwrap_or(e.path())
116                        .components()
117                        .any(|c| c.as_os_str() == std::ffi::OsStr::new("src"))
118                })
119                .hidden(true)
120                .require_git(false)
121                .build()
122                .flatten()
123                {
124                    if !entry.file_type().is_some_and(|kind| kind.is_file()) {
125                        continue;
126                    }
127                    match entry.path().extension().and_then(|e| e.to_str()) {
128                        // `kts` is the Gradle Kotlin DSL build script, not Kotlin source.
129                        Some("kt") => kt += 1,
130                        Some("java") => java += 1,
131                        _ => {}
132                    }
133                }
134                if kt > 0 && java == 0 {
135                    return Some(Self::Kotlin);
136                }
137            }
138            return Some(Self::Java);
139        }
140        let dotnet = std::fs::read_dir(root).is_ok_and(|entries| {
141            entries.flatten().any(|e| {
142                let name = e.file_name().to_string_lossy().into_owned();
143                name.ends_with(".csproj") || name.ends_with(".sln") || name.ends_with(".slnx")
144            })
145        });
146        if dotnet || has("Directory.Build.props") {
147            return Some(Self::Csharp);
148        }
149        if has("pyproject.toml") || has("setup.py") || has("setup.cfg") {
150            return Some(Self::Python);
151        }
152        if has("Gemfile") {
153            return Some(Self::Ruby);
154        }
155        if has("composer.json") {
156            return Some(Self::Php);
157        }
158        if has("package.json") {
159            return Some(Self::Ts);
160        }
161        let mut counts = [0usize; Self::ALL.len()];
162        for entry in crate::walk::builder(root)
163            .hidden(true)
164            .require_git(false)
165            .build()
166            .flatten()
167        {
168            let ext = entry
169                .path()
170                .extension()
171                .and_then(|e| e.to_str())
172                .unwrap_or("");
173            if !entry.file_type().is_some_and(|kind| kind.is_file()) {
174                continue;
175            }
176            if let Some(i) = Self::ALL.iter().position(|l| l.extensions().contains(&ext)) {
177                counts[i] += 1;
178            }
179        }
180        if counts.iter().all(|&c| c == 0) {
181            return None;
182        }
183        let best = (0..Self::ALL.len())
184            .max_by_key(|&i| (counts[i], std::cmp::Reverse(i)))
185            .unwrap_or(0);
186        Some(Self::ALL[best])
187    }
188
189    const ALL: [Self; 10] = [
190        Self::Ts,
191        Self::Python,
192        Self::C,
193        Self::Go,
194        Self::Ruby,
195        Self::Java,
196        Self::Kotlin,
197        Self::Php,
198        Self::Csharp,
199        Self::Powershell,
200    ];
201
202    /// Starts of a line that is a comment, not code, for counting lines of code. `* ` and `*/`
203    /// rather than `*`, so a C or Go line that starts with a dereference stays code.
204    pub fn comment_prefixes(self) -> &'static [&'static str] {
205        match self {
206            Lang::Python | Lang::Ruby => &["#"],
207            Lang::Php => &["//", "#", "/*", "* ", "*/"],
208            Lang::Powershell => &["#", "<#"],
209            _ => &["//", "/*", "* ", "*/"],
210        }
211    }
212
213    /// File extensions of the language's source files.
214    pub fn extensions(self) -> &'static [&'static str] {
215        match self {
216            Self::Ts => &[
217                "ts", "mts", "cts", "js", "mjs", "cjs", "tsx", "jsx", "vue", "svelte", "astro",
218            ],
219            Self::Python => &["py"],
220            Self::C => &["c", "h"],
221            Self::Go => &["go"],
222            Self::Ruby => &["rb"],
223            Self::Java => &["java"],
224            Self::Kotlin => &["kt"],
225            Self::Php => &["php"],
226            Self::Csharp => &["cs"],
227            Self::Powershell => &["ps1", "psm1"],
228        }
229    }
230}
231
232/// Where an import points, for languages other than TS.
233pub enum Resolution {
234    File(usize),
235    External(String),
236    Stdlib,
237    Unresolved,
238}
239
240pub fn discover(lang: Lang, root: &Path) -> anyhow::Result<crate::ts::discover::Workspace> {
241    match lang {
242        Lang::Python => python::discover(root),
243        Lang::C => c::discover(root),
244        Lang::Go => go::discover(root),
245        Lang::Ruby => ruby::discover(root),
246        Lang::Java => java::discover(root),
247        Lang::Kotlin => kotlin::discover(root),
248        Lang::Php => php::discover(root),
249        Lang::Csharp => csharp::discover(root),
250        Lang::Powershell => powershell::discover(root),
251        _ => anyhow::bail!("{} is not supported yet", lang.name()),
252    }
253}
254
255pub fn scan(lang: Lang, _path: &str, text: &str) -> crate::ts::scan::FileFacts {
256    match lang {
257        Lang::Python => python::scan(text),
258        Lang::C => c::scan(text),
259        Lang::Go => go::scan(text),
260        Lang::Ruby => ruby::scan(text),
261        Lang::Java => java::scan(text),
262        Lang::Kotlin => kotlin::scan(text),
263        Lang::Php => php::scan(text),
264        Lang::Csharp => csharp::scan(text),
265        Lang::Powershell => powershell::scan(text),
266        _ => crate::ts::scan::FileFacts::default(),
267    }
268}
269
270pub fn resolve(
271    lang: Lang,
272    from: &str,
273    spec: &str,
274    index: &std::collections::HashMap<&str, usize>,
275    ws: &crate::ts::discover::Workspace,
276) -> Resolution {
277    match lang {
278        Lang::Python => match python::resolve(from, spec, index, ws) {
279            python::Resolution::File(i) => Resolution::File(i),
280            python::Resolution::External(n) => Resolution::External(n),
281            python::Resolution::Stdlib => Resolution::Stdlib,
282            python::Resolution::Unresolved => Resolution::Unresolved,
283        },
284        Lang::C => c::resolve(from, spec, index),
285        Lang::Go => go::resolve(spec, index, ws),
286        Lang::Ruby => ruby::resolve(from, spec, index, ws),
287        Lang::Java => java::resolve(spec, index, ws),
288        Lang::Kotlin => kotlin::resolve(spec, index, ws),
289        Lang::Php => php::resolve(from, spec, index, ws),
290        Lang::Csharp => csharp::resolve(spec, index, ws),
291        Lang::Powershell => powershell::resolve(from, spec, index, ws),
292        _ => Resolution::Unresolved,
293    }
294}
295
296pub fn exports(
297    lang: Lang,
298    path: &str,
299    text: &str,
300) -> (
301    Vec<crate::ts::exports::ExportedFn>,
302    Vec<crate::ts::exports::ExportedClass>,
303) {
304    match lang {
305        Lang::Python => python::exports(path, text),
306        Lang::C => (c::exports(path, text), Vec::new()),
307        Lang::Go => (go::exports(path, text), Vec::new()),
308        Lang::Ruby => (ruby::exports(path, text), Vec::new()),
309        Lang::Java => (java::exports(path, text), Vec::new()),
310        Lang::Kotlin => (kotlin::exports(path, text), Vec::new()),
311        Lang::Php => (php::exports(path, text), Vec::new()),
312        Lang::Csharp => (csharp::exports(path, text), Vec::new()),
313        Lang::Powershell => (powershell::exports(path, text), Vec::new()),
314        _ => (Vec::new(), Vec::new()),
315    }
316}
317
318/// Dependency tables of the languages without their own module entry yet.
319pub fn lookup(lang: Lang, name: &str) -> Option<crate::ts::deps::CrateMatch> {
320    match lang {
321        Lang::C => c::lookup(name),
322        Lang::Go => go::lookup(name),
323        Lang::Ruby => ruby::lookup(name),
324        Lang::Java => java::lookup(name),
325        Lang::Kotlin => kotlin::lookup(name),
326        Lang::Php => php::lookup(name),
327        Lang::Csharp => csharp::lookup(name),
328        Lang::Powershell => powershell::lookup(name),
329        _ => None,
330    }
331}
332
333#[cfg(test)]
334mod tests {
335    use super::Lang;
336    use std::path::PathBuf;
337
338    fn project(name: &str, files: &[(&str, &str)]) -> PathBuf {
339        let dir = std::env::temp_dir().join(format!(
340            "rust-anything-detect-{}-{name}",
341            std::process::id()
342        ));
343        let _ = std::fs::remove_dir_all(&dir);
344        for (path, text) in files {
345            let full = dir.join(path);
346            std::fs::create_dir_all(full.parent().unwrap()).unwrap();
347            std::fs::write(full, text).unwrap();
348        }
349        dir
350    }
351
352    #[test]
353    fn kotlin_dsl_with_only_kotlin_sources_is_kotlin() {
354        let dir = project(
355            "kotlin-only",
356            &[
357                ("build.gradle.kts", "plugins { kotlin(\"jvm\") }\n"),
358                ("src/main/kotlin/com/example/A.kt", "package com.example\n"),
359            ],
360        );
361        assert_eq!(Lang::detect(&dir), Lang::Kotlin);
362        let _ = std::fs::remove_dir_all(dir);
363    }
364
365    #[test]
366    fn a_mixed_module_stays_java() {
367        let dir = project(
368            "mixed",
369            &[
370                ("build.gradle.kts", "plugins { kotlin(\"jvm\") }\n"),
371                ("src/main/kotlin/A.kt", "package a\n"),
372                ("src/main/java/B.java", "package a;\n"),
373            ],
374        );
375        assert_eq!(Lang::detect(&dir), Lang::Java);
376        let _ = std::fs::remove_dir_all(dir);
377    }
378
379    #[test]
380    fn a_build_script_alone_does_not_make_a_kotlin_project() {
381        let dir = project("script-only", &[("build.gradle.kts", "plugins { java }\n")]);
382        assert_eq!(Lang::detect(&dir), Lang::Java);
383        let _ = std::fs::remove_dir_all(dir);
384    }
385
386    #[test]
387    fn maven_with_kotlin_sources_stays_java_until_overridden() {
388        let dir = project(
389            "maven-kotlin",
390            &[
391                ("pom.xml", "<project/>\n"),
392                ("src/main/kotlin/A.kt", "package a\n"),
393            ],
394        );
395        assert_eq!(Lang::detect(&dir), Lang::Java);
396        let _ = std::fs::remove_dir_all(dir);
397    }
398}