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, crate::lang::Lang::Java),
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
345fn strip_kw<'a>(s: &'a str, kw: &str) -> Option<&'a str> {
346    let rest = s.strip_prefix(kw)?;
347    if rest.starts_with(char::is_whitespace) {
348        Some(rest.trim_start())
349    } else {
350        None
351    }
352}
353
354/// A Java type in the TS-like dialect (return position), or why the bridge cannot carry it.
355pub fn java_to_ts(t: &str) -> Result<String, String> {
356    java_to_ts_inner(t, false)
357}
358
359/// A Java parameter type in the TS-like dialect: covariant `? extends T` wildcards read as `T`.
360pub fn java_to_ts_param(t: &str) -> Result<String, String> {
361    java_to_ts_inner(t, true)
362}
363
364fn java_to_ts_inner(t: &str, in_param: bool) -> Result<String, String> {
365    let t = t.trim();
366    if let Some(rest) = t.strip_prefix('?') {
367        let rest = rest.trim();
368        if rest.is_empty() {
369            return Err("takes or returns `Object`: values of any type".into());
370        }
371        if in_param
372            && let Some(bound) = strip_kw(rest, "extends")
373            && !bound.is_empty()
374            && !bound.contains('&')
375        {
376            return java_to_ts_inner(bound, true);
377        }
378        return Err(format!("uses a wildcard `{t}`"));
379    }
380    if let Some(inner) = t.strip_suffix("[]") {
381        return java_to_ts_inner(inner, in_param).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 qualified = head.trim();
388    let head = qualified.rsplit('.').next().unwrap_or(qualified);
389    let arg = |i: usize| -> Result<String, String> {
390        args.get(i).map_or_else(
391            || Err(format!("raw `{head}`")),
392            |a| java_to_ts_inner(a, in_param),
393        )
394    };
395    Ok(match head {
396        "String" | "CharSequence" => "string".into(),
397        "int" | "long" | "short" | "byte" | "Integer" | "Long" | "Short" | "Byte" => "int".into(),
398        "double" | "float" | "Double" | "Float" => "number".into(),
399        "boolean" | "Boolean" => "boolean".into(),
400        "void" | "Void" => "void".into(),
401        "List" | "ArrayList" | "Collection" | "Iterable" | "LinkedList" => {
402            let inner = arg(0)?;
403            if inner.contains(' ') {
404                format!("({inner})[]")
405            } else {
406                format!("{inner}[]")
407            }
408        }
409        "SortedSet" | "NavigableSet" | "TreeSet" | "LinkedHashSet" if jdk_set(qualified) => {
410            let inner = arg(0)?;
411            if inner.contains(' ') {
412                format!("({inner})[]")
413            } else {
414                format!("{inner}[]")
415            }
416        }
417        "Map" | "LinkedHashMap" | "TreeMap" | "HashMap" => {
418            if arg(0)? != "string" {
419                return Err(format!("`{t}`: JSON object keys are strings"));
420            }
421            format!("Record<string, {}>", arg(1)?)
422        }
423        "Optional" => format!("{} | undefined", arg(0)?),
424        "OptionalInt" | "OptionalLong" => "int | undefined".into(),
425        "OptionalDouble" => "number | undefined".into(),
426        "char" | "Character" => return Err("uses `char`, a UTF-16 code unit".into()),
427        "Object" => return Err("takes or returns `Object`: values of any type".into()),
428        "Set" | "HashSet" if jdk_set(qualified) => {
429            return Err(format!("uses `{head}`, an unordered collection"));
430        }
431        "Function" | "BiFunction" | "Supplier" | "Consumer" | "Predicate" | "Runnable"
432        | "Callable" | "Comparator" => {
433            return Err("takes or returns a function".into());
434        }
435        "Stream" | "Iterator" | "IntStream" => {
436            return Err(format!("uses `{head}`, a lazy sequence"));
437        }
438        other => return Err(format!("uses the class `{other}`")),
439    })
440}
441
442/// Whether a set type is the JDK's: unqualified, or under `java.util`. `com.acme.Set` is the
443/// project's own class.
444fn jdk_set(qualified: &str) -> bool {
445    match qualified.rsplit_once('.') {
446        Some((package, _)) => package == "java.util",
447        None => true,
448    }
449}
450
451fn split_top(text: &str) -> Vec<String> {
452    let mut out = Vec::new();
453    let mut depth = 0i32;
454    let mut current = String::new();
455    for c in text.chars() {
456        match c {
457            '<' => depth += 1,
458            '>' => depth -= 1,
459            ',' if depth == 0 => {
460                out.push(current.trim().to_string());
461                current.clear();
462                continue;
463            }
464            _ => {}
465        }
466        current.push(c);
467    }
468    if !current.trim().is_empty() {
469        out.push(current.trim().to_string());
470    }
471    out
472}
473
474/// The `package` of a Java file.
475pub fn package_name(source: &str) -> Option<String> {
476    let tree = syntax::parse(&language(), source)?;
477    package_name_in(tree.root_node(), source)
478}
479
480fn package_name_in(root: Node<'_>, source: &str) -> Option<String> {
481    let declaration = named_children(root)
482        .into_iter()
483        .find(|node| node.kind() == "package_declaration")?;
484    let name = named_children(declaration)
485        .into_iter()
486        .find(|node| matches!(node.kind(), "identifier" | "scoped_identifier"))?;
487    let mut components = Vec::new();
488    syntax::walk(name, |node| {
489        if node.kind() == "identifier" {
490            components.push(text(node, source));
491        }
492    });
493    Some(components.join("."))
494}
495
496/// `public static` methods of the file's public top-level classes. `prototype` holds the
497/// declaring class's fully qualified name and the signature: `com.x.Strings.slugify(String text)`.
498pub fn exports(path: &str, source: &str) -> Vec<ExportedFn> {
499    if !path.ends_with(".java") {
500        return Vec::new();
501    }
502    let Some(tree) = syntax::parse(&language(), source) else {
503        return Vec::new();
504    };
505    let package = package_name_in(tree.root_node(), source);
506    let mut out = Vec::new();
507    for class in named_children(tree.root_node()) {
508        if class.kind() != "class_declaration" {
509            continue;
510        }
511        let modifiers = |n: Node| {
512            named_children(n)
513                .into_iter()
514                .find(|c| c.kind() == "modifiers")
515                .map_or(String::new(), |m| text(m, source).to_string())
516        };
517        if !modifiers(class).split_whitespace().any(|w| w == "public") {
518            continue;
519        }
520        let Some(class_name) = class
521            .child_by_field_name("name")
522            .map(|n| text(n, source).to_string())
523        else {
524            continue;
525        };
526        let qualified = match &package {
527            Some(p) => format!("{p}.{class_name}"),
528            None => class_name.clone(),
529        };
530        let Some(body) = class.child_by_field_name("body") else {
531            continue;
532        };
533        for method in named_children(body) {
534            if method.kind() != "method_declaration" {
535                continue;
536            }
537            let mods = modifiers(method);
538            let words: Vec<&str> = mods.split_whitespace().collect();
539            if !(words.contains(&"public") && words.contains(&"static")) {
540                continue;
541            }
542            let Some(name) = method
543                .child_by_field_name("name")
544                .map(|n| text(n, source).to_string())
545            else {
546                continue;
547            };
548            let mut blocker = None;
549            if method.child_by_field_name("type_parameters").is_some() {
550                blocker = Some("generic: erased types cannot be recovered".to_string());
551            }
552            let mut params = Vec::new();
553            let mut signature = Vec::new();
554            if let Some(list) = method.child_by_field_name("parameters") {
555                for p in named_children(list) {
556                    let (ty, pname) = match p.kind() {
557                        "formal_parameter" => {
558                            let base = p
559                                .child_by_field_name("type")
560                                .map_or("", |t| text(t, source))
561                                .to_string();
562                            // `int values[]` is the same type as `int[] values`: tree-sitter keeps
563                            // the brackets in a separate `dimensions` child of the parameter.
564                            let dims = named_children(p)
565                                .iter()
566                                .find(|c| c.kind() == "dimensions")
567                                .map_or(String::new(), |d| {
568                                    text(*d, source).split_whitespace().collect::<String>()
569                                });
570                            (
571                                format!("{base}{dims}"),
572                                p.child_by_field_name("name")
573                                    .map_or("", |n| text(n, source))
574                                    .to_string(),
575                            )
576                        }
577                        "spread_parameter" => {
578                            blocker.get_or_insert_with(|| "is variadic".into());
579                            continue;
580                        }
581                        _ => continue,
582                    };
583                    let ts_type = java_to_ts_param(&ty).unwrap_or_else(|reason| {
584                        blocker.get_or_insert(reason);
585                        "unknown".into()
586                    });
587                    signature.push(format!("{ty} {pname}"));
588                    params.push(Param {
589                        name: pname,
590                        ts_type,
591                        native_type: Some(ty),
592                        ..Default::default()
593                    });
594                }
595            }
596            let ret = method
597                .child_by_field_name("type")
598                .map_or("void", |t| text(t, source))
599                .to_string();
600            let returns = java_to_ts(&ret).unwrap_or_else(|reason| {
601                blocker.get_or_insert(reason);
602                "unknown".into()
603            });
604            if out.iter().any(|f: &ExportedFn| f.name == name) {
605                blocker = Some(super::OVERLOADED.into());
606            }
607            out.push(ExportedFn {
608                name,
609                file: path.to_string(),
610                line: syntax::line(method),
611                params,
612                returns,
613                native_return: Some(ret),
614                prototype: Some(format!(
615                    "{qualified}.{}({})",
616                    text(method.child_by_field_name("name").unwrap_or(method), source),
617                    signature.join(", ")
618                )),
619                blocker,
620                ..Default::default()
621            });
622        }
623    }
624    // The reflection driver keys methods by name alone: an overload would pick an arbitrary
625    // signature. Block every export sharing a name, not just the later declaration.
626    let mut counts: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
627    for f in &out {
628        *counts.entry(f.name.clone()).or_default() += 1;
629    }
630    for f in &mut out {
631        if counts.get(&f.name).copied().unwrap_or(0) > 1 {
632            f.blocker = Some(super::OVERLOADED.into());
633        }
634    }
635    out
636}
637
638/// The declaring class and the method name of an export: `("com.x.Strings", "slugify")`.
639pub fn receiver(f: &ExportedFn) -> (String, String) {
640    let proto = f.prototype.as_deref().unwrap_or(&f.name);
641    let head = proto.split('(').next().unwrap_or(proto);
642    match head.rsplit_once('.') {
643        Some((class, name)) => (class.to_string(), name.to_string()),
644        None => (String::new(), f.name.clone()),
645    }
646}
647
648#[cfg(test)]
649mod tests {
650    use super::*;
651
652    #[test]
653    fn a_c_style_array_parameter_keeps_its_dimensions() {
654        // `int values[]` is `int[] values`: tree-sitter keeps the brackets in a `dimensions` child,
655        // which used to be dropped, so the parameter came out as a plain `int`.
656        // The brackets can hold a tab: `int values[\t]` is the same type as `int values[]`.
657        let src = "package acme;\npublic class Stats {\n    public static int sum(int values[]) { return 0; }\n    public static int plain(int[] values) { return 0; }\n    public static int grid(int rows[][]) { return 0; }\n    public static int tabbed(int xs[\t]) { return 0; }\n}\n";
658        let fns = exports("acme/Stats.java", src);
659        let types: Vec<(&str, &str)> = fns
660            .iter()
661            .map(|f| (f.name.as_str(), f.params[0].ts_type.as_str()))
662            .collect();
663        assert_eq!(
664            types,
665            [
666                ("sum", "int[]"),
667                ("plain", "int[]"),
668                ("grid", "int[][]"),
669                ("tabbed", "int[]"),
670            ]
671        );
672    }
673
674    #[test]
675    fn bounded_extends_wildcards_map_in_params_and_stay_refused_in_returns() {
676        // Return position keeps refusing every wildcard, naming it as one.
677        for t in ["List<? extends CharSequence>", "List<? extends Number>"] {
678            let reason = java_to_ts(t).unwrap_err();
679            assert!(reason.contains("wildcard"), "{t}: {reason}");
680            assert!(!reason.contains("uses the class"), "{t}: {reason}");
681        }
682        assert_eq!(java_to_ts("List<String>").unwrap(), "string[]");
683        // `? super` writes, and an unbounded `?` is `Object`: both stay refusals in every position.
684        for f in [java_to_ts, java_to_ts_param] {
685            assert!(
686                f("List<? super String>")
687                    .unwrap_err()
688                    .contains("? super String")
689            );
690            assert!(f("List<?>").unwrap_err().contains("values of any type"));
691        }
692        // Parameter position unwraps `? extends T` to `T`, including nested containers.
693        assert_eq!(
694            java_to_ts_param("List<? extends CharSequence>").unwrap(),
695            "string[]"
696        );
697        assert_eq!(
698            java_to_ts_param("Map<String, ? extends Integer>").unwrap(),
699            "Record<string, int>"
700        );
701        assert_eq!(
702            java_to_ts_param("Map<? extends CharSequence, ? extends Double>").unwrap(),
703            "Record<string, number>"
704        );
705        assert_eq!(
706            java_to_ts_param("Optional<? extends String>").unwrap(),
707            "string | undefined"
708        );
709        assert_eq!(
710            java_to_ts_param("List<? extends List<? extends CharSequence>>").unwrap(),
711            "string[][]"
712        );
713        // Unbridged upper bounds report the bound's own reason, not "wildcard".
714        assert_eq!(
715            java_to_ts_param("List<? extends Number>").unwrap_err(),
716            "uses the class `Number`"
717        );
718        assert!(
719            java_to_ts_param("List<? extends Object>")
720                .unwrap_err()
721                .contains("values of any type")
722        );
723    }
724
725    #[test]
726    fn exports_accept_extends_wildcards_in_parameters_only() {
727        let src = r#"package acme;
728import java.util.List;
729import java.util.Map;
730import java.util.Optional;
731public class Totals {
732    public static int count(List<? extends CharSequence> xs) { return xs.size(); }
733    public static int lookup(Map<String, ? extends Integer> m, Optional<? extends CharSequence> k) { return m.size(); }
734    public static double total(List<? extends Number> xs) { return 0.0; }
735    public static List<? extends CharSequence> echo(List<? extends CharSequence> xs) { return xs; }
736    public static void add(List<? super String> xs) {}
737    public static int anyLen(List<?> xs) { return xs.size(); }
738}
739"#;
740        let fns = exports("acme/Totals.java", src);
741        let by = |name: &str| fns.iter().find(|f| f.name == name).unwrap();
742
743        let count = by("count");
744        assert!(count.blocker.is_none(), "{count:?}");
745        assert_eq!(count.params[0].ts_type, "string[]");
746        assert_eq!(
747            count.params[0].native_type.as_deref(),
748            Some("List<? extends CharSequence>")
749        );
750
751        let lookup = by("lookup");
752        assert!(lookup.blocker.is_none(), "{lookup:?}");
753        assert_eq!(lookup.params[0].ts_type, "Record<string, int>");
754        assert_eq!(lookup.params[1].ts_type, "string | undefined");
755
756        let total = by("total");
757        assert_eq!(total.blocker.as_deref(), Some("uses the class `Number`"));
758
759        let echo = by("echo");
760        assert_eq!(
761            echo.blocker.as_deref(),
762            Some("uses a wildcard `? extends CharSequence`")
763        );
764
765        let add = by("add");
766        assert_eq!(
767            add.blocker.as_deref(),
768            Some("uses a wildcard `? super String`")
769        );
770
771        let any_len = by("anyLen");
772        assert!(
773            any_len
774                .blocker
775                .as_deref()
776                .unwrap_or("")
777                .contains("values of any type")
778        );
779    }
780
781    #[test]
782    fn maps_types() {
783        assert_eq!(java_to_ts("List<String>").unwrap(), "string[]");
784        assert_eq!(
785            java_to_ts("Map<String, List<Integer>>").unwrap(),
786            "Record<string, int[]>"
787        );
788        assert_eq!(java_to_ts("double[]").unwrap(), "number[]");
789        assert!(java_to_ts("Point").is_err());
790    }
791
792    #[test]
793    fn finds_public_static_methods() {
794        let src = "package com.example.text;\nimport java.util.List;\npublic final class Strings {\n\
795                   private Strings() {}\n\
796                   public static String slugify(String text, int max) { return text; }\n\
797                   public static List<String> words(final String text) { return null; }\n\
798                   public static <T> T id(T x) { return x; }\n\
799                   static int hidden() { return 1; }\n\
800                   public int instance() { return 1; }\n}\n";
801        let fns = exports("src/main/java/com/example/text/Strings.java", src);
802        let names: Vec<&str> = fns.iter().map(|f| f.name.as_str()).collect();
803        assert_eq!(names, ["slugify", "words", "id"]);
804        assert_eq!(fns[0].params[1].ts_type, "int");
805        assert_eq!(
806            receiver(&fns[0]),
807            ("com.example.text.Strings".into(), "slugify".into())
808        );
809        assert_eq!(fns[1].returns, "string[]");
810        assert!(fns[2].blocker.is_some());
811    }
812
813    #[test]
814    fn every_overload_of_a_name_is_blocked() {
815        let src = "package com.example;\npublic final class Nums {\n\
816                   public static int add(int a, int b) { return a + b; }\n\
817                   public static double add(double a, double b) { return a + b; }\n\
818                   public static int one() { return 1; }\n}\n";
819        let fns = exports("src/main/java/com/example/Nums.java", src);
820        let blocked: Vec<(&str, bool)> = fns
821            .iter()
822            .map(|f| (f.name.as_str(), f.blocker.is_some()))
823            .collect();
824        assert_eq!(blocked, [("add", true), ("add", true), ("one", false)]);
825    }
826
827    #[test]
828    fn ordered_sets_bridge_and_unordered_sets_explain_why() {
829        for t in [
830            "SortedSet<String>",
831            "NavigableSet<String>",
832            "TreeSet<String>",
833            "LinkedHashSet<String>",
834            "java.util.TreeSet<String>",
835            "SortedSet<? extends CharSequence>",
836        ] {
837            assert_eq!(java_to_ts_param(t).unwrap(), "string[]", "{t}");
838        }
839        assert_eq!(java_to_ts("TreeSet<Integer>").unwrap(), "int[]");
840        assert_eq!(java_to_ts("LinkedHashSet<Double>").unwrap(), "number[]");
841        assert_eq!(java_to_ts("TreeSet").unwrap_err(), "raw `TreeSet`");
842
843        for (t, expected) in [
844            ("Set<String>", "uses `Set`, an unordered collection"),
845            ("HashSet<String>", "uses `HashSet`, an unordered collection"),
846            (
847                "java.util.Set<Integer>",
848                "uses `Set`, an unordered collection",
849            ),
850        ] {
851            assert_eq!(java_to_ts(t).unwrap_err(), expected, "{t}");
852            assert_eq!(java_to_ts_param(t).unwrap_err(), expected, "{t}");
853        }
854        for t in ["com.acme.Set", "acme.util.TreeSet<String>"] {
855            let reason = java_to_ts(t).unwrap_err();
856            assert!(reason.starts_with("uses the class"), "{t}: {reason}");
857        }
858        assert!(
859            java_to_ts_param("List<Set<String>>")
860                .unwrap_err()
861                .contains("unordered collection")
862        );
863    }
864}