1use 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
32pub(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
199pub 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 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 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 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
337pub fn lookup(name: &str) -> Option<CrateMatch> {
339 let key = name.split(':').next().unwrap_or(name);
340 crate::crates::find("java", key)
341}
342
343fn 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
354pub fn java_to_ts(t: &str) -> Result<String, String> {
356 java_to_ts_inner(t, false)
357}
358
359pub 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 head = head.trim().rsplit('.').next().unwrap_or(head);
388 let arg = |i: usize| -> Result<String, String> {
389 args.get(i).map_or_else(
390 || Err(format!("raw `{head}`")),
391 |a| java_to_ts_inner(a, in_param),
392 )
393 };
394 Ok(match head {
395 "String" | "CharSequence" => "string".into(),
396 "int" | "long" | "short" | "byte" | "Integer" | "Long" | "Short" | "Byte" => "int".into(),
397 "double" | "float" | "Double" | "Float" => "number".into(),
398 "boolean" | "Boolean" => "boolean".into(),
399 "void" | "Void" => "void".into(),
400 "List" | "ArrayList" | "Collection" | "Iterable" | "LinkedList" => {
401 let inner = arg(0)?;
402 if inner.contains(' ') {
403 format!("({inner})[]")
404 } else {
405 format!("{inner}[]")
406 }
407 }
408 "Map" | "LinkedHashMap" | "TreeMap" | "HashMap" => {
409 if arg(0)? != "string" {
410 return Err(format!("`{t}`: JSON object keys are strings"));
411 }
412 format!("Record<string, {}>", arg(1)?)
413 }
414 "Optional" => format!("{} | undefined", arg(0)?),
415 "OptionalInt" | "OptionalLong" => "int | undefined".into(),
416 "OptionalDouble" => "number | undefined".into(),
417 "char" | "Character" => return Err("uses `char`, a UTF-16 code unit".into()),
418 "Object" => return Err("takes or returns `Object`: values of any type".into()),
419 "Function" | "BiFunction" | "Supplier" | "Consumer" | "Predicate" | "Runnable"
420 | "Callable" | "Comparator" => {
421 return Err("takes or returns a function".into());
422 }
423 "Stream" | "Iterator" | "IntStream" => {
424 return Err(format!("uses `{head}`, a lazy sequence"));
425 }
426 other => return Err(format!("uses the class `{other}`")),
427 })
428}
429
430fn split_top(text: &str) -> Vec<String> {
431 let mut out = Vec::new();
432 let mut depth = 0i32;
433 let mut current = String::new();
434 for c in text.chars() {
435 match c {
436 '<' => depth += 1,
437 '>' => depth -= 1,
438 ',' if depth == 0 => {
439 out.push(current.trim().to_string());
440 current.clear();
441 continue;
442 }
443 _ => {}
444 }
445 current.push(c);
446 }
447 if !current.trim().is_empty() {
448 out.push(current.trim().to_string());
449 }
450 out
451}
452
453pub fn package_name(source: &str) -> Option<String> {
455 let tree = syntax::parse(&language(), source)?;
456 package_name_in(tree.root_node(), source)
457}
458
459fn package_name_in(root: Node<'_>, source: &str) -> Option<String> {
460 let declaration = named_children(root)
461 .into_iter()
462 .find(|node| node.kind() == "package_declaration")?;
463 let name = named_children(declaration)
464 .into_iter()
465 .find(|node| matches!(node.kind(), "identifier" | "scoped_identifier"))?;
466 let mut components = Vec::new();
467 syntax::walk(name, |node| {
468 if node.kind() == "identifier" {
469 components.push(text(node, source));
470 }
471 });
472 Some(components.join("."))
473}
474
475pub fn exports(path: &str, source: &str) -> Vec<ExportedFn> {
478 if !path.ends_with(".java") {
479 return Vec::new();
480 }
481 let Some(tree) = syntax::parse(&language(), source) else {
482 return Vec::new();
483 };
484 let package = package_name_in(tree.root_node(), source);
485 let mut out = Vec::new();
486 for class in named_children(tree.root_node()) {
487 if class.kind() != "class_declaration" {
488 continue;
489 }
490 let modifiers = |n: Node| {
491 named_children(n)
492 .into_iter()
493 .find(|c| c.kind() == "modifiers")
494 .map_or(String::new(), |m| text(m, source).to_string())
495 };
496 if !modifiers(class).split_whitespace().any(|w| w == "public") {
497 continue;
498 }
499 let Some(class_name) = class
500 .child_by_field_name("name")
501 .map(|n| text(n, source).to_string())
502 else {
503 continue;
504 };
505 let qualified = match &package {
506 Some(p) => format!("{p}.{class_name}"),
507 None => class_name.clone(),
508 };
509 let Some(body) = class.child_by_field_name("body") else {
510 continue;
511 };
512 for method in named_children(body) {
513 if method.kind() != "method_declaration" {
514 continue;
515 }
516 let mods = modifiers(method);
517 let words: Vec<&str> = mods.split_whitespace().collect();
518 if !(words.contains(&"public") && words.contains(&"static")) {
519 continue;
520 }
521 let Some(name) = method
522 .child_by_field_name("name")
523 .map(|n| text(n, source).to_string())
524 else {
525 continue;
526 };
527 let mut blocker = None;
528 if method.child_by_field_name("type_parameters").is_some() {
529 blocker = Some("generic: erased types cannot be recovered".to_string());
530 }
531 let mut params = Vec::new();
532 let mut signature = Vec::new();
533 if let Some(list) = method.child_by_field_name("parameters") {
534 for p in named_children(list) {
535 let (ty, pname) = match p.kind() {
536 "formal_parameter" => {
537 let base = p
538 .child_by_field_name("type")
539 .map_or("", |t| text(t, source))
540 .to_string();
541 let dims = named_children(p)
544 .iter()
545 .find(|c| c.kind() == "dimensions")
546 .map_or(String::new(), |d| {
547 text(*d, source).split_whitespace().collect::<String>()
548 });
549 (
550 format!("{base}{dims}"),
551 p.child_by_field_name("name")
552 .map_or("", |n| text(n, source))
553 .to_string(),
554 )
555 }
556 "spread_parameter" => {
557 blocker.get_or_insert_with(|| "is variadic".into());
558 continue;
559 }
560 _ => continue,
561 };
562 let ts_type = java_to_ts_param(&ty).unwrap_or_else(|reason| {
563 blocker.get_or_insert(reason);
564 "unknown".into()
565 });
566 signature.push(format!("{ty} {pname}"));
567 params.push(Param {
568 name: pname,
569 ts_type,
570 native_type: Some(ty),
571 ..Default::default()
572 });
573 }
574 }
575 let ret = method
576 .child_by_field_name("type")
577 .map_or("void", |t| text(t, source))
578 .to_string();
579 let returns = java_to_ts(&ret).unwrap_or_else(|reason| {
580 blocker.get_or_insert(reason);
581 "unknown".into()
582 });
583 if out.iter().any(|f: &ExportedFn| f.name == name) {
584 blocker = Some(super::OVERLOADED.into());
585 }
586 out.push(ExportedFn {
587 name,
588 file: path.to_string(),
589 line: syntax::line(method),
590 params,
591 returns,
592 native_return: Some(ret),
593 prototype: Some(format!(
594 "{qualified}.{}({})",
595 text(method.child_by_field_name("name").unwrap_or(method), source),
596 signature.join(", ")
597 )),
598 blocker,
599 ..Default::default()
600 });
601 }
602 }
603 let mut counts: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
606 for f in &out {
607 *counts.entry(f.name.clone()).or_default() += 1;
608 }
609 for f in &mut out {
610 if counts.get(&f.name).copied().unwrap_or(0) > 1 {
611 f.blocker = Some(super::OVERLOADED.into());
612 }
613 }
614 out
615}
616
617pub fn receiver(f: &ExportedFn) -> (String, String) {
619 let proto = f.prototype.as_deref().unwrap_or(&f.name);
620 let head = proto.split('(').next().unwrap_or(proto);
621 match head.rsplit_once('.') {
622 Some((class, name)) => (class.to_string(), name.to_string()),
623 None => (String::new(), f.name.clone()),
624 }
625}
626
627#[cfg(test)]
628mod tests {
629 use super::*;
630
631 #[test]
632 fn a_c_style_array_parameter_keeps_its_dimensions() {
633 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";
637 let fns = exports("acme/Stats.java", src);
638 let types: Vec<(&str, &str)> = fns
639 .iter()
640 .map(|f| (f.name.as_str(), f.params[0].ts_type.as_str()))
641 .collect();
642 assert_eq!(
643 types,
644 [
645 ("sum", "int[]"),
646 ("plain", "int[]"),
647 ("grid", "int[][]"),
648 ("tabbed", "int[]"),
649 ]
650 );
651 }
652
653 #[test]
654 fn bounded_extends_wildcards_map_in_params_and_stay_refused_in_returns() {
655 for t in ["List<? extends CharSequence>", "List<? extends Number>"] {
657 let reason = java_to_ts(t).unwrap_err();
658 assert!(reason.contains("wildcard"), "{t}: {reason}");
659 assert!(!reason.contains("uses the class"), "{t}: {reason}");
660 }
661 assert_eq!(java_to_ts("List<String>").unwrap(), "string[]");
662 for f in [java_to_ts, java_to_ts_param] {
664 assert!(
665 f("List<? super String>")
666 .unwrap_err()
667 .contains("? super String")
668 );
669 assert!(f("List<?>").unwrap_err().contains("values of any type"));
670 }
671 assert_eq!(
673 java_to_ts_param("List<? extends CharSequence>").unwrap(),
674 "string[]"
675 );
676 assert_eq!(
677 java_to_ts_param("Map<String, ? extends Integer>").unwrap(),
678 "Record<string, int>"
679 );
680 assert_eq!(
681 java_to_ts_param("Map<? extends CharSequence, ? extends Double>").unwrap(),
682 "Record<string, number>"
683 );
684 assert_eq!(
685 java_to_ts_param("Optional<? extends String>").unwrap(),
686 "string | undefined"
687 );
688 assert_eq!(
689 java_to_ts_param("List<? extends List<? extends CharSequence>>").unwrap(),
690 "string[][]"
691 );
692 assert_eq!(
694 java_to_ts_param("List<? extends Number>").unwrap_err(),
695 "uses the class `Number`"
696 );
697 assert!(
698 java_to_ts_param("List<? extends Object>")
699 .unwrap_err()
700 .contains("values of any type")
701 );
702 }
703
704 #[test]
705 fn exports_accept_extends_wildcards_in_parameters_only() {
706 let src = r#"package acme;
707import java.util.List;
708import java.util.Map;
709import java.util.Optional;
710public class Totals {
711 public static int count(List<? extends CharSequence> xs) { return xs.size(); }
712 public static int lookup(Map<String, ? extends Integer> m, Optional<? extends CharSequence> k) { return m.size(); }
713 public static double total(List<? extends Number> xs) { return 0.0; }
714 public static List<? extends CharSequence> echo(List<? extends CharSequence> xs) { return xs; }
715 public static void add(List<? super String> xs) {}
716 public static int anyLen(List<?> xs) { return xs.size(); }
717}
718"#;
719 let fns = exports("acme/Totals.java", src);
720 let by = |name: &str| fns.iter().find(|f| f.name == name).unwrap();
721
722 let count = by("count");
723 assert!(count.blocker.is_none(), "{count:?}");
724 assert_eq!(count.params[0].ts_type, "string[]");
725 assert_eq!(
726 count.params[0].native_type.as_deref(),
727 Some("List<? extends CharSequence>")
728 );
729
730 let lookup = by("lookup");
731 assert!(lookup.blocker.is_none(), "{lookup:?}");
732 assert_eq!(lookup.params[0].ts_type, "Record<string, int>");
733 assert_eq!(lookup.params[1].ts_type, "string | undefined");
734
735 let total = by("total");
736 assert_eq!(total.blocker.as_deref(), Some("uses the class `Number`"));
737
738 let echo = by("echo");
739 assert_eq!(
740 echo.blocker.as_deref(),
741 Some("uses a wildcard `? extends CharSequence`")
742 );
743
744 let add = by("add");
745 assert_eq!(
746 add.blocker.as_deref(),
747 Some("uses a wildcard `? super String`")
748 );
749
750 let any_len = by("anyLen");
751 assert!(
752 any_len
753 .blocker
754 .as_deref()
755 .unwrap_or("")
756 .contains("values of any type")
757 );
758 }
759
760 #[test]
761 fn maps_types() {
762 assert_eq!(java_to_ts("List<String>").unwrap(), "string[]");
763 assert_eq!(
764 java_to_ts("Map<String, List<Integer>>").unwrap(),
765 "Record<string, int[]>"
766 );
767 assert_eq!(java_to_ts("double[]").unwrap(), "number[]");
768 assert!(java_to_ts("Point").is_err());
769 }
770
771 #[test]
772 fn finds_public_static_methods() {
773 let src = "package com.example.text;\nimport java.util.List;\npublic final class Strings {\n\
774 private Strings() {}\n\
775 public static String slugify(String text, int max) { return text; }\n\
776 public static List<String> words(final String text) { return null; }\n\
777 public static <T> T id(T x) { return x; }\n\
778 static int hidden() { return 1; }\n\
779 public int instance() { return 1; }\n}\n";
780 let fns = exports("src/main/java/com/example/text/Strings.java", src);
781 let names: Vec<&str> = fns.iter().map(|f| f.name.as_str()).collect();
782 assert_eq!(names, ["slugify", "words", "id"]);
783 assert_eq!(fns[0].params[1].ts_type, "int");
784 assert_eq!(
785 receiver(&fns[0]),
786 ("com.example.text.Strings".into(), "slugify".into())
787 );
788 assert_eq!(fns[1].returns, "string[]");
789 assert!(fns[2].blocker.is_some());
790 }
791
792 #[test]
793 fn every_overload_of_a_name_is_blocked() {
794 let src = "package com.example;\npublic final class Nums {\n\
795 public static int add(int a, int b) { return a + b; }\n\
796 public static double add(double a, double b) { return a + b; }\n\
797 public static int one() { return 1; }\n}\n";
798 let fns = exports("src/main/java/com/example/Nums.java", src);
799 let blocked: Vec<(&str, bool)> = fns
800 .iter()
801 .map(|f| (f.name.as_str(), f.blocker.is_some()))
802 .collect();
803 assert_eq!(blocked, [("add", true), ("add", true), ("one", false)]);
804 }
805}