Skip to main content

rust_anything/lang/
java.rs

1//! Java: Maven and Gradle modules, imports, risks, the artifact-to-crate table, and `public
2//! static` methods of public classes with Java types mapped into the TS-like type dialect.
3//! A unit is a package (a folder).
4
5use std::collections::HashMap;
6use std::path::Path;
7
8use anyhow::Result;
9use tree_sitter::Node;
10
11use super::syntax::{self, named_children, text};
12use crate::risks::{Risk, regex_needs_fancy};
13use crate::ts::deps::{CrateMatch, Fit};
14use crate::ts::discover::{FileKind, Package, SourceFile, Workspace};
15use crate::ts::exports::{ExportedFn, Param};
16use crate::ts::scan::{FileFacts, Import};
17
18fn language() -> tree_sitter::Language {
19    tree_sitter_java::LANGUAGE.into()
20}
21
22const SKIP_DIRS: &[&str] = &[
23    "target",
24    "build",
25    "out",
26    ".gradle",
27    ".idea",
28    "node_modules",
29    "bin",
30];
31
32// ---- discovery -------------------------------------------------------------------------------
33
34/// `groupId:artifactId` of each `<dependency>` in a pom, or `group:name` of Gradle coordinates.
35fn dependencies(text: &str) -> (Vec<String>, Vec<String>) {
36    let (mut deps, mut dev) = (Vec::new(), Vec::new());
37    for block in text.split("<dependency>").skip(1) {
38        let block = block.split("</dependency>").next().unwrap_or("");
39        let tag = |t: &str| {
40            block
41                .split(&format!("<{t}>"))
42                .nth(1)
43                .and_then(|r| r.split(&format!("</{t}>")).next())
44                .map(str::trim)
45                .unwrap_or("")
46                .to_string()
47        };
48        let name = format!("{}:{}", tag("groupId"), tag("artifactId"));
49        if tag("scope") == "test" {
50            dev.push(name);
51        } else {
52            deps.push(name);
53        }
54    }
55    for line in text.lines() {
56        let line = line.trim();
57        let Some((config, rest)) = line.split_once(['(', ' ']) else {
58            continue;
59        };
60        let coords = rest
61            .split(['"', '\''])
62            .nth(1)
63            .filter(|c| c.matches(':').count() >= 1);
64        let Some(coords) = coords else { continue };
65        let name = coords.split(':').take(2).collect::<Vec<_>>().join(":");
66        match config {
67            "implementation" | "api" | "compile" | "compileOnly" | "runtimeOnly" => deps.push(name),
68            "testImplementation" | "testCompile" | "testRuntimeOnly" => dev.push(name),
69            _ => {}
70        }
71    }
72    (deps, dev)
73}
74
75pub fn discover(root: &Path) -> Result<Workspace> {
76    let mut packages: Vec<Package> = Vec::new();
77    let mut files = Vec::new();
78    let walker = crate::walk::filtered(root, |e| {
79        !(e.file_type().is_some_and(|t| t.is_dir())
80            && SKIP_DIRS.contains(&e.file_name().to_string_lossy().as_ref()))
81    })
82    .hidden(true)
83    .require_git(false)
84    .build();
85    for entry in walker.flatten() {
86        if !entry.file_type().is_some_and(|t| t.is_file()) {
87            continue;
88        }
89        let Ok(rel) = entry.path().strip_prefix(root) else {
90            continue;
91        };
92        let rel = rel.to_string_lossy().replace('\\', "/");
93        let name = rel.rsplit('/').next().unwrap_or(&rel);
94        let dir = rel
95            .rsplit_once('/')
96            .map_or(String::new(), |(d, _)| d.to_string());
97        if matches!(name, "pom.xml" | "build.gradle" | "build.gradle.kts") {
98            let text = std::fs::read_to_string(entry.path()).unwrap_or_default();
99            let (deps, dev) = dependencies(&text);
100            let artifact = text
101                .split("<artifactId>")
102                .nth(1)
103                .and_then(|r| r.split("</artifactId>").next())
104                .map(str::to_string);
105            packages.push(Package {
106                name: artifact.unwrap_or_else(|| {
107                    if dir.is_empty() {
108                        root.file_name()
109                            .map_or_else(|| "root".into(), |n| n.to_string_lossy().into_owned())
110                    } else {
111                        dir.clone()
112                    }
113                }),
114                src_root: if root.join(&dir).join("src/main/java").is_dir() {
115                    join(&dir, "src/main/java")
116                } else {
117                    dir.clone()
118                },
119                dir,
120                deps,
121                dev_deps: dev,
122            });
123        } else if name.ends_with(".java") {
124            let is_test = rel.contains("src/test/")
125                || name.ends_with("Test.java")
126                || name.ends_with("Tests.java")
127                || name.ends_with("IT.java");
128            files.push((
129                rel,
130                if is_test {
131                    FileKind::Test
132                } else {
133                    FileKind::Source
134                },
135            ));
136        }
137    }
138    if packages.is_empty() {
139        packages.push(Package {
140            name: root
141                .file_name()
142                .map_or_else(|| "root".into(), |n| n.to_string_lossy().into_owned()),
143            dir: String::new(),
144            src_root: if root.join("src/main/java").is_dir() {
145                "src/main/java".into()
146            } else if root.join("src").is_dir() {
147                "src".into()
148            } else {
149                String::new()
150            },
151            deps: Vec::new(),
152            dev_deps: Vec::new(),
153        });
154    }
155    packages.sort_by(|a, b| a.dir.cmp(&b.dir));
156    packages.dedup_by(|a, b| a.dir == b.dir);
157    files.sort_by(|a, b| a.0.cmp(&b.0));
158    let files = files
159        .into_iter()
160        .map(|(path, kind)| {
161            let package = packages
162                .iter()
163                .enumerate()
164                .filter(|(_, p)| p.dir.is_empty() || path.starts_with(&format!("{}/", p.dir)))
165                .max_by_key(|(_, p)| p.dir.len())
166                .map_or(0, |(i, _)| i);
167            SourceFile {
168                path,
169                package,
170                kind,
171            }
172        })
173        .collect();
174    Ok(Workspace { packages, files })
175}
176
177fn join(dir: &str, rest: &str) -> String {
178    if dir.is_empty() {
179        rest.to_string()
180    } else {
181        format!("{dir}/{rest}")
182    }
183}
184
185// ---- risks and imports -----------------------------------------------------------------------
186
187pub fn scan(source: &str) -> FileFacts {
188    let mut facts = FileFacts {
189        loc: syntax::loc(source),
190        ..FileFacts::default()
191    };
192    let Some(tree) = syntax::parse(&language(), source) else {
193        return facts;
194    };
195    let root = tree.root_node();
196    facts.parse_errors = usize::from(root.has_error());
197    let add = |facts: &mut FileFacts, risk: Risk, node: Node| {
198        facts
199            .risks
200            .entry(risk)
201            .or_default()
202            .push(syntax::line(node))
203    };
204    syntax::walk(root, |node| match node.kind() {
205        "import_declaration" => {
206            let spec = text(node, source)
207                .trim_start_matches("import")
208                .trim()
209                .trim_start_matches("static ")
210                .trim_end_matches(';')
211                .trim()
212                .to_string();
213            match spec.as_str() {
214                s if s.starts_with("java.lang.reflect") => add(&mut facts, Risk::Reflection, node),
215                s if s.starts_with("java.util.concurrent") => {
216                    add(&mut facts, Risk::Concurrency, node)
217                }
218                s if s.starts_with("java.util.regex") => add(&mut facts, Risk::RegexSyntax, node),
219                "java.util.HashMap" | "java.util.HashSet" => {
220                    add(&mut facts, Risk::UnorderedIteration, node)
221                }
222                _ => {}
223            }
224            facts.imports.push(Import {
225                specifier: spec,
226                type_only: false,
227                dynamic: false,
228            });
229        }
230        "synchronized_statement" => add(&mut facts, Risk::Concurrency, node),
231        "modifiers"
232            if text(node, source).contains("synchronized")
233                || text(node, source).contains("volatile") =>
234        {
235            add(&mut facts, Risk::Concurrency, node)
236        }
237        "null_literal" => add(&mut facts, Risk::NullReferences, node),
238        "instanceof_expression" | "cast_expression" => add(&mut facts, Risk::DynamicTyping, node),
239        "lambda_expression" | "method_reference" => add(&mut facts, Risk::Callbacks, node),
240        "throw_statement" | "try_statement" | "catch_clause" => {
241            add(&mut facts, Risk::Exceptions, node)
242        }
243        "superclass" | "super_interfaces" => add(&mut facts, Risk::ClassInheritance, node),
244        "binary_expression" => {
245            let op = node
246                .child_by_field_name("operator")
247                .map_or("", |o| text(o, source));
248            match op {
249                "/" | "%" => add(&mut facts, Risk::DivisionSemantics, node),
250                "<<" | ">>" | ">>>" | "*" => add(&mut facts, Risk::IntegerSemantics, node),
251                _ => {}
252            }
253        }
254        "method_invocation" => {
255            let name = node
256                .child_by_field_name("name")
257                .map_or("", |n| text(n, source));
258            match name {
259                "substring" | "charAt" | "indexOf" | "lastIndexOf" | "codePointAt" | "length" => {
260                    add(&mut facts, Risk::StringOffsets, node)
261                }
262                "getClass" | "forName" | "getDeclaredMethod" | "invoke" | "newInstance" => {
263                    add(&mut facts, Risk::Reflection, node)
264                }
265                "matches" | "replaceAll" | "replaceFirst" | "split" | "compile" => {
266                    // Java regex is close to the `regex` crate; lookaround and backreferences are not.
267                    let pattern = node
268                        .child_by_field_name("arguments")
269                        .and_then(|a| named_children(a).into_iter().next())
270                        .map(|a| text(a, source).to_string());
271                    match pattern {
272                        Some(p) if p.starts_with('"') => {
273                            let unescaped = p.trim_matches('"').replace("\\\\", "\\");
274                            if regex_needs_fancy(&unescaped, "") {
275                                add(&mut facts, Risk::RegexSyntax, node);
276                            }
277                        }
278                        _ => add(&mut facts, Risk::DynamicRegex, node),
279                    }
280                }
281                "hashCode" => add(&mut facts, Risk::IntegerSemantics, node),
282                _ => {}
283            }
284        }
285        "for_statement" | "enhanced_for_statement" | "while_statement" | "do_statement" => {
286            facts.loops += 1
287        }
288        _ => {}
289    });
290    facts
291}
292
293pub fn resolve(spec: &str, index: &HashMap<&str, usize>, ws: &Workspace) -> super::Resolution {
294    let first = spec.split('.').next().unwrap_or("");
295    if matches!(first, "java" | "javax" | "jdk" | "sun") || spec.starts_with("com.sun.") {
296        return super::Resolution::Stdlib;
297    }
298    let path = spec.trim_end_matches(".*").replace('.', "/");
299    for p in &ws.packages {
300        // `import a.b.C` names a file; `import a.b.*` a folder.
301        let file = join(&p.src_root, &format!("{path}.java"));
302        if let Some(i) = index.get(file.as_str()) {
303            return super::Resolution::File(*i);
304        }
305        let dir = join(&p.src_root, &path);
306        if let Some((_, i)) = index
307            .iter()
308            .filter(|(f, _)| f.rsplit_once('/').is_some_and(|(d, _)| d == dir))
309            .min_by_key(|(f, _)| **f)
310        {
311            return super::Resolution::File(*i);
312        }
313    }
314    super::Resolution::External(spec.split('.').take(2).collect::<Vec<_>>().join("."))
315}
316
317const fn m(crates: &'static str, fit: Fit, note: &'static str) -> CrateMatch {
318    CrateMatch { crates, fit, note }
319}
320
321/// Rust counterparts of common Java libraries, by import prefix or Maven coordinates.
322pub fn lookup(name: &str) -> Option<CrateMatch> {
323    let key = name.split(':').next().unwrap_or(name);
324    Some(match key {
325        k if k.starts_with("com.google.guava") || k.starts_with("com.google.common") => m(
326            "std, itertools, indexmap",
327            Fit::Partial,
328            "Guava spans many crates",
329        ),
330        k if k.starts_with("org.apache.commons") => m("std, itertools", Fit::Partial, ""),
331        k if k.starts_with("com.fasterxml.jackson")
332            || k.starts_with("com.google.gson")
333            || k.starts_with("com.google.code.gson") =>
334        {
335            m("serde_json", Fit::Good, "")
336        }
337        k if k.starts_with("org.slf4j")
338            || k.starts_with("ch.qos.logback")
339            || k.starts_with("org.apache.logging") =>
340        {
341            m("tracing", Fit::Good, "")
342        }
343        k if k.starts_with("org.junit")
344            || k.starts_with("junit")
345            || k.starts_with("org.assertj") =>
346        {
347            m("std test", Fit::Good, "")
348        }
349        k if k.starts_with("org.springframework") => m(
350            "axum",
351            Fit::None,
352            "a framework is an application rewrite, not a port",
353        ),
354        k if k.starts_with("org.projectlombok") || k.starts_with("lombok") => m(
355            "derive macros",
356            Fit::Good,
357            "Lombok's generated code becomes derives",
358        ),
359        k if k.starts_with("com.squareup.okhttp3")
360            || k.starts_with("org.apache.httpcomponents") =>
361        {
362            m("reqwest", Fit::Good, "")
363        }
364        k if k.starts_with("org.yaml") => m("serde_yaml_ng", Fit::Good, ""),
365        k if k.starts_with("info.picocli") || k.starts_with("com.beust") => {
366            m("clap", Fit::Good, "")
367        }
368        k if k.starts_with("org.postgresql") => m("tokio-postgres, sqlx", Fit::Good, ""),
369        k if k.starts_with("org.xerial") => m("rusqlite", Fit::Good, ""),
370        k if k.starts_with("com.ibm.icu") => m("icu", Fit::Partial, ""),
371        _ => return None,
372    })
373}
374
375// ---- exports ---------------------------------------------------------------------------------
376
377/// A Java type in the TS-like dialect, or why the bridge cannot carry it.
378pub fn java_to_ts(t: &str) -> Result<String, String> {
379    let t = t.trim();
380    if let Some(inner) = t.strip_suffix("[]") {
381        return java_to_ts(inner).map(|i| format!("{i}[]"));
382    }
383    let (head, args) = match t.find('<') {
384        Some(i) if t.ends_with('>') => (&t[..i], split_top(&t[i + 1..t.len() - 1])),
385        _ => (t, Vec::new()),
386    };
387    let head = head.trim().rsplit('.').next().unwrap_or(head);
388    let arg = |i: usize| -> Result<String, String> {
389        args.get(i)
390            .map_or_else(|| Err(format!("raw `{head}`")), |a| java_to_ts(a))
391    };
392    Ok(match head {
393        "String" | "CharSequence" => "string".into(),
394        "int" | "long" | "short" | "byte" | "Integer" | "Long" | "Short" | "Byte" => "int".into(),
395        "double" | "float" | "Double" | "Float" => "number".into(),
396        "boolean" | "Boolean" => "boolean".into(),
397        "void" | "Void" => "void".into(),
398        "List" | "ArrayList" | "Collection" | "Iterable" | "LinkedList" => {
399            let inner = arg(0)?;
400            if inner.contains(' ') {
401                format!("({inner})[]")
402            } else {
403                format!("{inner}[]")
404            }
405        }
406        "Map" | "LinkedHashMap" | "TreeMap" | "HashMap" => {
407            if arg(0)? != "string" {
408                return Err(format!("`{t}`: JSON object keys are strings"));
409            }
410            format!("Record<string, {}>", arg(1)?)
411        }
412        "Optional" => format!("{} | undefined", arg(0)?),
413        "OptionalInt" | "OptionalLong" => "int | undefined".into(),
414        "OptionalDouble" => "number | undefined".into(),
415        "char" | "Character" => return Err("uses `char`, a UTF-16 code unit".into()),
416        "Object" => return Err("takes or returns `Object`: values of any type".into()),
417        "Function" | "BiFunction" | "Supplier" | "Consumer" | "Predicate" | "Runnable"
418        | "Callable" | "Comparator" => {
419            return Err("takes or returns a function".into());
420        }
421        "Stream" | "Iterator" | "IntStream" => {
422            return Err(format!("uses `{head}`, a lazy sequence"));
423        }
424        other => return Err(format!("uses the class `{other}`")),
425    })
426}
427
428fn split_top(text: &str) -> Vec<String> {
429    let mut out = Vec::new();
430    let mut depth = 0i32;
431    let mut current = String::new();
432    for c in text.chars() {
433        match c {
434            '<' => depth += 1,
435            '>' => depth -= 1,
436            ',' if depth == 0 => {
437                out.push(current.trim().to_string());
438                current.clear();
439                continue;
440            }
441            _ => {}
442        }
443        current.push(c);
444    }
445    if !current.trim().is_empty() {
446        out.push(current.trim().to_string());
447    }
448    out
449}
450
451/// The `package` of a Java file.
452pub fn package_name(source: &str) -> Option<String> {
453    source.lines().find_map(|l| {
454        l.trim()
455            .strip_prefix("package ")
456            .map(|p| p.trim_end_matches(';').trim().to_string())
457    })
458}
459
460/// `public static` methods of the file's public top-level classes. `prototype` holds the
461/// declaring class's fully qualified name and the signature: `com.x.Strings.slugify(String text)`.
462pub fn exports(path: &str, source: &str) -> Vec<ExportedFn> {
463    if !path.ends_with(".java") {
464        return Vec::new();
465    }
466    let Some(tree) = syntax::parse(&language(), source) else {
467        return Vec::new();
468    };
469    let package = package_name(source);
470    let mut out = Vec::new();
471    for class in named_children(tree.root_node()) {
472        if class.kind() != "class_declaration" {
473            continue;
474        }
475        let modifiers = |n: Node| {
476            named_children(n)
477                .into_iter()
478                .find(|c| c.kind() == "modifiers")
479                .map_or(String::new(), |m| text(m, source).to_string())
480        };
481        if !modifiers(class).split_whitespace().any(|w| w == "public") {
482            continue;
483        }
484        let Some(class_name) = class
485            .child_by_field_name("name")
486            .map(|n| text(n, source).to_string())
487        else {
488            continue;
489        };
490        let qualified = match &package {
491            Some(p) => format!("{p}.{class_name}"),
492            None => class_name.clone(),
493        };
494        let Some(body) = class.child_by_field_name("body") else {
495            continue;
496        };
497        for method in named_children(body) {
498            if method.kind() != "method_declaration" {
499                continue;
500            }
501            let mods = modifiers(method);
502            let words: Vec<&str> = mods.split_whitespace().collect();
503            if !(words.contains(&"public") && words.contains(&"static")) {
504                continue;
505            }
506            let Some(name) = method
507                .child_by_field_name("name")
508                .map(|n| text(n, source).to_string())
509            else {
510                continue;
511            };
512            let mut blocker = None;
513            if method.child_by_field_name("type_parameters").is_some() {
514                blocker = Some("generic: erased types cannot be recovered".to_string());
515            }
516            let mut params = Vec::new();
517            let mut signature = Vec::new();
518            if let Some(list) = method.child_by_field_name("parameters") {
519                for p in named_children(list) {
520                    let (ty, pname) = match p.kind() {
521                        "formal_parameter" => (
522                            p.child_by_field_name("type")
523                                .map_or("", |t| text(t, source))
524                                .to_string(),
525                            p.child_by_field_name("name")
526                                .map_or("", |n| text(n, source))
527                                .to_string(),
528                        ),
529                        "spread_parameter" => {
530                            blocker.get_or_insert_with(|| "is variadic".into());
531                            continue;
532                        }
533                        _ => continue,
534                    };
535                    let ts_type = java_to_ts(&ty).unwrap_or_else(|reason| {
536                        blocker.get_or_insert(reason);
537                        "unknown".into()
538                    });
539                    signature.push(format!("{ty} {pname}"));
540                    params.push(Param {
541                        name: pname,
542                        ts_type,
543                        native_type: Some(ty),
544                        ..Default::default()
545                    });
546                }
547            }
548            let ret = method
549                .child_by_field_name("type")
550                .map_or("void", |t| text(t, source))
551                .to_string();
552            let returns = java_to_ts(&ret).unwrap_or_else(|reason| {
553                blocker.get_or_insert(reason);
554                "unknown".into()
555            });
556            if out.iter().any(|f: &ExportedFn| f.name == name) {
557                blocker = Some("overloaded: one name, several signatures".into());
558            }
559            out.push(ExportedFn {
560                name,
561                file: path.to_string(),
562                line: syntax::line(method),
563                params,
564                returns,
565                native_return: Some(ret),
566                prototype: Some(format!(
567                    "{qualified}.{}({})",
568                    text(method.child_by_field_name("name").unwrap_or(method), source),
569                    signature.join(", ")
570                )),
571                blocker,
572                ..Default::default()
573            });
574        }
575    }
576    out
577}
578
579/// The declaring class and the method name of an export: `("com.x.Strings", "slugify")`.
580pub fn receiver(f: &ExportedFn) -> (String, String) {
581    let proto = f.prototype.as_deref().unwrap_or(&f.name);
582    let head = proto.split('(').next().unwrap_or(proto);
583    match head.rsplit_once('.') {
584        Some((class, name)) => (class.to_string(), name.to_string()),
585        None => (String::new(), f.name.clone()),
586    }
587}
588
589#[cfg(test)]
590mod tests {
591    use super::*;
592
593    #[test]
594    fn maps_types() {
595        assert_eq!(java_to_ts("List<String>").unwrap(), "string[]");
596        assert_eq!(
597            java_to_ts("Map<String, List<Integer>>").unwrap(),
598            "Record<string, int[]>"
599        );
600        assert_eq!(java_to_ts("double[]").unwrap(), "number[]");
601        assert!(java_to_ts("Point").is_err());
602    }
603
604    #[test]
605    fn finds_public_static_methods() {
606        let src = "package com.example.text;\nimport java.util.List;\npublic final class Strings {\n\
607                   private Strings() {}\n\
608                   public static String slugify(String text, int max) { return text; }\n\
609                   public static List<String> words(final String text) { return null; }\n\
610                   public static <T> T id(T x) { return x; }\n\
611                   static int hidden() { return 1; }\n\
612                   public int instance() { return 1; }\n}\n";
613        let fns = exports("src/main/java/com/example/text/Strings.java", src);
614        let names: Vec<&str> = fns.iter().map(|f| f.name.as_str()).collect();
615        assert_eq!(names, ["slugify", "words", "id"]);
616        assert_eq!(fns[0].params[1].ts_type, "int");
617        assert_eq!(
618            receiver(&fns[0]),
619            ("com.example.text.Strings".into(), "slugify".into())
620        );
621        assert_eq!(fns[1].returns, "string[]");
622        assert!(fns[2].blocker.is_some());
623    }
624}