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 php;
14pub mod python;
15pub mod ruby;
16pub mod syntax;
17
18#[derive(
19    Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, clap::ValueEnum,
20)]
21#[serde(rename_all = "lowercase")]
22pub enum Lang {
23    #[default]
24    Ts,
25    Python,
26    C,
27    Go,
28    Ruby,
29    Java,
30    Php,
31    Csharp,
32}
33
34impl Lang {
35    pub fn name(self) -> &'static str {
36        match self {
37            Self::Ts => "TypeScript/JavaScript",
38            Self::Python => "Python",
39            Self::C => "C",
40            Self::Go => "Go",
41            Self::Ruby => "Ruby",
42            Self::Java => "Java",
43            Self::Php => "PHP",
44            Self::Csharp => "C#",
45        }
46    }
47
48    /// Where third-party dependencies come from in this language: used when a dependency
49    /// is not in the crate table, so a Python stdlib omission is not reported as `npm`.
50    pub fn registry(self) -> &'static str {
51        match self {
52            Self::Ts => "npm",
53            Self::Python => "PyPI",
54            Self::C => "system libraries",
55            Self::Go => "Go modules",
56            Self::Ruby => "gems",
57            Self::Java => "Maven",
58            Self::Php => "Composer",
59            Self::Csharp => "NuGet",
60        }
61    }
62
63    /// The language of a repository: from its manifest files, else its most common source files.
64    pub fn detect(root: &Path) -> Self {
65        let has = |name: &str| root.join(name).exists();
66        if has("go.mod") {
67            return Self::Go;
68        }
69        if has("pom.xml") || has("build.gradle") || has("build.gradle.kts") {
70            return Self::Java;
71        }
72        let dotnet = std::fs::read_dir(root).is_ok_and(|entries| {
73            entries.flatten().any(|e| {
74                let name = e.file_name().to_string_lossy().into_owned();
75                name.ends_with(".csproj") || name.ends_with(".sln") || name.ends_with(".slnx")
76            })
77        });
78        if dotnet || has("Directory.Build.props") {
79            return Self::Csharp;
80        }
81        if has("pyproject.toml") || has("setup.py") || has("setup.cfg") {
82            return Self::Python;
83        }
84        if has("Gemfile") {
85            return Self::Ruby;
86        }
87        if has("composer.json") {
88            return Self::Php;
89        }
90        if has("package.json") {
91            return Self::Ts;
92        }
93        let mut counts = [0usize; 8];
94        for entry in crate::walk::builder(root)
95            .hidden(true)
96            .require_git(false)
97            .build()
98            .flatten()
99        {
100            let ext = entry
101                .path()
102                .extension()
103                .and_then(|e| e.to_str())
104                .unwrap_or("");
105            if !entry.file_type().is_some_and(|kind| kind.is_file()) {
106                continue;
107            }
108            if let Some(i) = Self::ALL.iter().position(|l| l.extensions().contains(&ext)) {
109                counts[i] += 1;
110            }
111        }
112        let best = (0..8)
113            .max_by_key(|&i| (counts[i], std::cmp::Reverse(i)))
114            .unwrap_or(0);
115        Self::ALL[best]
116    }
117
118    const ALL: [Self; 8] = [
119        Self::Ts,
120        Self::Python,
121        Self::C,
122        Self::Go,
123        Self::Ruby,
124        Self::Java,
125        Self::Php,
126        Self::Csharp,
127    ];
128
129    /// File extensions of the language's source files.
130    pub fn extensions(self) -> &'static [&'static str] {
131        match self {
132            Self::Ts => &[
133                "ts", "mts", "cts", "js", "mjs", "cjs", "tsx", "jsx", "vue", "svelte", "astro",
134            ],
135            Self::Python => &["py"],
136            Self::C => &["c", "h"],
137            Self::Go => &["go"],
138            Self::Ruby => &["rb"],
139            Self::Java => &["java"],
140            Self::Php => &["php"],
141            Self::Csharp => &["cs"],
142        }
143    }
144}
145
146/// Where an import points, for languages other than TS.
147pub enum Resolution {
148    File(usize),
149    External(String),
150    Stdlib,
151    Unresolved,
152}
153
154pub fn discover(lang: Lang, root: &Path) -> anyhow::Result<crate::ts::discover::Workspace> {
155    match lang {
156        Lang::Python => python::discover(root),
157        Lang::C => c::discover(root),
158        Lang::Go => go::discover(root),
159        Lang::Ruby => ruby::discover(root),
160        Lang::Java => java::discover(root),
161        Lang::Php => php::discover(root),
162        Lang::Csharp => csharp::discover(root),
163        _ => anyhow::bail!("{} is not supported yet", lang.name()),
164    }
165}
166
167pub fn scan(lang: Lang, _path: &str, text: &str) -> crate::ts::scan::FileFacts {
168    match lang {
169        Lang::Python => python::scan(text),
170        Lang::C => c::scan(text),
171        Lang::Go => go::scan(text),
172        Lang::Ruby => ruby::scan(text),
173        Lang::Java => java::scan(text),
174        Lang::Php => php::scan(text),
175        Lang::Csharp => csharp::scan(text),
176        _ => crate::ts::scan::FileFacts::default(),
177    }
178}
179
180pub fn resolve(
181    lang: Lang,
182    from: &str,
183    spec: &str,
184    index: &std::collections::HashMap<&str, usize>,
185    ws: &crate::ts::discover::Workspace,
186) -> Resolution {
187    match lang {
188        Lang::Python => match python::resolve(from, spec, index, ws) {
189            python::Resolution::File(i) => Resolution::File(i),
190            python::Resolution::External(n) => Resolution::External(n),
191            python::Resolution::Stdlib => Resolution::Stdlib,
192            python::Resolution::Unresolved => Resolution::Unresolved,
193        },
194        Lang::C => c::resolve(from, spec, index),
195        Lang::Go => go::resolve(spec, index, ws),
196        Lang::Ruby => ruby::resolve(from, spec, index, ws),
197        Lang::Java => java::resolve(spec, index, ws),
198        Lang::Php => php::resolve(from, spec, index, ws),
199        Lang::Csharp => csharp::resolve(spec, index, ws),
200        _ => Resolution::Unresolved,
201    }
202}
203
204pub fn exports(
205    lang: Lang,
206    path: &str,
207    text: &str,
208) -> (
209    Vec<crate::ts::exports::ExportedFn>,
210    Vec<crate::ts::exports::ExportedClass>,
211) {
212    match lang {
213        Lang::Python => python::exports(path, text),
214        Lang::C => (c::exports(path, text), Vec::new()),
215        Lang::Go => (go::exports(path, text), Vec::new()),
216        Lang::Ruby => (ruby::exports(path, text), Vec::new()),
217        Lang::Java => (java::exports(path, text), Vec::new()),
218        Lang::Php => (php::exports(path, text), Vec::new()),
219        Lang::Csharp => (csharp::exports(path, text), Vec::new()),
220        _ => (Vec::new(), Vec::new()),
221    }
222}
223
224/// Dependency tables of the languages without their own module entry yet.
225pub fn lookup(lang: Lang, name: &str) -> Option<crate::ts::deps::CrateMatch> {
226    match lang {
227        Lang::C => c::lookup(name),
228        Lang::Go => go::lookup(name),
229        Lang::Ruby => ruby::lookup(name),
230        Lang::Java => java::lookup(name),
231        Lang::Php => php::lookup(name),
232        Lang::Csharp => csharp::lookup(name),
233        _ => None,
234    }
235}