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