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    /// Starts of a line that is a comment, not code, for counting lines of code. `* ` and `*/`
194    /// rather than `*`, so a C or Go line that starts with a dereference stays code.
195    pub fn comment_prefixes(self) -> &'static [&'static str] {
196        match self {
197            Lang::Python | Lang::Ruby => &["#"],
198            Lang::Php => &["//", "#", "/*", "* ", "*/"],
199            Lang::Powershell => &["#", "<#"],
200            _ => &["//", "/*", "* ", "*/"],
201        }
202    }
203
204    /// File extensions of the language's source files.
205    pub fn extensions(self) -> &'static [&'static str] {
206        match self {
207            Self::Ts => &[
208                "ts", "mts", "cts", "js", "mjs", "cjs", "tsx", "jsx", "vue", "svelte", "astro",
209            ],
210            Self::Python => &["py"],
211            Self::C => &["c", "h"],
212            Self::Go => &["go"],
213            Self::Ruby => &["rb"],
214            Self::Java => &["java"],
215            Self::Kotlin => &["kt"],
216            Self::Php => &["php"],
217            Self::Csharp => &["cs"],
218            Self::Powershell => &["ps1", "psm1"],
219        }
220    }
221}
222
223/// Where an import points, for languages other than TS.
224pub enum Resolution {
225    File(usize),
226    External(String),
227    Stdlib,
228    Unresolved,
229}
230
231pub fn discover(lang: Lang, root: &Path) -> anyhow::Result<crate::ts::discover::Workspace> {
232    match lang {
233        Lang::Python => python::discover(root),
234        Lang::C => c::discover(root),
235        Lang::Go => go::discover(root),
236        Lang::Ruby => ruby::discover(root),
237        Lang::Java => java::discover(root),
238        Lang::Kotlin => kotlin::discover(root),
239        Lang::Php => php::discover(root),
240        Lang::Csharp => csharp::discover(root),
241        Lang::Powershell => powershell::discover(root),
242        _ => anyhow::bail!("{} is not supported yet", lang.name()),
243    }
244}
245
246pub fn scan(lang: Lang, _path: &str, text: &str) -> crate::ts::scan::FileFacts {
247    match lang {
248        Lang::Python => python::scan(text),
249        Lang::C => c::scan(text),
250        Lang::Go => go::scan(text),
251        Lang::Ruby => ruby::scan(text),
252        Lang::Java => java::scan(text),
253        Lang::Kotlin => kotlin::scan(text),
254        Lang::Php => php::scan(text),
255        Lang::Csharp => csharp::scan(text),
256        Lang::Powershell => powershell::scan(text),
257        _ => crate::ts::scan::FileFacts::default(),
258    }
259}
260
261pub fn resolve(
262    lang: Lang,
263    from: &str,
264    spec: &str,
265    index: &std::collections::HashMap<&str, usize>,
266    ws: &crate::ts::discover::Workspace,
267) -> Resolution {
268    match lang {
269        Lang::Python => match python::resolve(from, spec, index, ws) {
270            python::Resolution::File(i) => Resolution::File(i),
271            python::Resolution::External(n) => Resolution::External(n),
272            python::Resolution::Stdlib => Resolution::Stdlib,
273            python::Resolution::Unresolved => Resolution::Unresolved,
274        },
275        Lang::C => c::resolve(from, spec, index),
276        Lang::Go => go::resolve(spec, index, ws),
277        Lang::Ruby => ruby::resolve(from, spec, index, ws),
278        Lang::Java => java::resolve(spec, index, ws),
279        Lang::Kotlin => kotlin::resolve(spec, index, ws),
280        Lang::Php => php::resolve(from, spec, index, ws),
281        Lang::Csharp => csharp::resolve(spec, index, ws),
282        Lang::Powershell => powershell::resolve(from, spec, index, ws),
283        _ => Resolution::Unresolved,
284    }
285}
286
287pub fn exports(
288    lang: Lang,
289    path: &str,
290    text: &str,
291) -> (
292    Vec<crate::ts::exports::ExportedFn>,
293    Vec<crate::ts::exports::ExportedClass>,
294) {
295    match lang {
296        Lang::Python => python::exports(path, text),
297        Lang::C => (c::exports(path, text), Vec::new()),
298        Lang::Go => (go::exports(path, text), Vec::new()),
299        Lang::Ruby => (ruby::exports(path, text), Vec::new()),
300        Lang::Java => (java::exports(path, text), Vec::new()),
301        Lang::Kotlin => (kotlin::exports(path, text), Vec::new()),
302        Lang::Php => (php::exports(path, text), Vec::new()),
303        Lang::Csharp => (csharp::exports(path, text), Vec::new()),
304        Lang::Powershell => (powershell::exports(path, text), Vec::new()),
305        _ => (Vec::new(), Vec::new()),
306    }
307}
308
309/// Dependency tables of the languages without their own module entry yet.
310pub fn lookup(lang: Lang, name: &str) -> Option<crate::ts::deps::CrateMatch> {
311    match lang {
312        Lang::C => c::lookup(name),
313        Lang::Go => go::lookup(name),
314        Lang::Ruby => ruby::lookup(name),
315        Lang::Java => java::lookup(name),
316        Lang::Kotlin => kotlin::lookup(name),
317        Lang::Php => php::lookup(name),
318        Lang::Csharp => csharp::lookup(name),
319        Lang::Powershell => powershell::lookup(name),
320        _ => None,
321    }
322}
323
324#[cfg(test)]
325mod tests {
326    use super::Lang;
327    use std::path::PathBuf;
328
329    fn project(name: &str, files: &[(&str, &str)]) -> PathBuf {
330        let dir = std::env::temp_dir().join(format!(
331            "rust-anything-detect-{}-{name}",
332            std::process::id()
333        ));
334        let _ = std::fs::remove_dir_all(&dir);
335        for (path, text) in files {
336            let full = dir.join(path);
337            std::fs::create_dir_all(full.parent().unwrap()).unwrap();
338            std::fs::write(full, text).unwrap();
339        }
340        dir
341    }
342
343    #[test]
344    fn kotlin_dsl_with_only_kotlin_sources_is_kotlin() {
345        let dir = project(
346            "kotlin-only",
347            &[
348                ("build.gradle.kts", "plugins { kotlin(\"jvm\") }\n"),
349                ("src/main/kotlin/com/example/A.kt", "package com.example\n"),
350            ],
351        );
352        assert_eq!(Lang::detect(&dir), Lang::Kotlin);
353        let _ = std::fs::remove_dir_all(dir);
354    }
355
356    #[test]
357    fn a_mixed_module_stays_java() {
358        let dir = project(
359            "mixed",
360            &[
361                ("build.gradle.kts", "plugins { kotlin(\"jvm\") }\n"),
362                ("src/main/kotlin/A.kt", "package a\n"),
363                ("src/main/java/B.java", "package a;\n"),
364            ],
365        );
366        assert_eq!(Lang::detect(&dir), Lang::Java);
367        let _ = std::fs::remove_dir_all(dir);
368    }
369
370    #[test]
371    fn a_build_script_alone_does_not_make_a_kotlin_project() {
372        let dir = project("script-only", &[("build.gradle.kts", "plugins { java }\n")]);
373        assert_eq!(Lang::detect(&dir), Lang::Java);
374        let _ = std::fs::remove_dir_all(dir);
375    }
376
377    #[test]
378    fn maven_with_kotlin_sources_stays_java_until_overridden() {
379        let dir = project(
380            "maven-kotlin",
381            &[
382                ("pom.xml", "<project/>\n"),
383                ("src/main/kotlin/A.kt", "package a\n"),
384            ],
385        );
386        assert_eq!(Lang::detect(&dir), Lang::Java);
387        let _ = std::fs::remove_dir_all(dir);
388    }
389}