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