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),
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
343pub fn java_to_ts(t: &str) -> Result<String, String> {
347 let t = t.trim();
348 if let Some(rest) = t.strip_prefix('?') {
351 let rest = rest.trim();
352 return Err(
353 if rest.starts_with("super") || rest.starts_with("extends") {
354 format!("uses a wildcard `{t}`")
355 } else {
356 "takes or returns `Object`: values of any type".into()
357 },
358 );
359 }
360 if let Some(inner) = t.strip_suffix("[]") {
361 return java_to_ts(inner).map(|i| format!("{i}[]"));
362 }
363 let (head, args) = match t.find('<') {
364 Some(i) if t.ends_with('>') => (&t[..i], split_top(&t[i + 1..t.len() - 1])),
365 _ => (t, Vec::new()),
366 };
367 let head = head.trim().rsplit('.').next().unwrap_or(head);
368 let arg = |i: usize| -> Result<String, String> {
369 args.get(i)
370 .map_or_else(|| Err(format!("raw `{head}`")), |a| java_to_ts(a))
371 };
372 Ok(match head {
373 "String" | "CharSequence" => "string".into(),
374 "int" | "long" | "short" | "byte" | "Integer" | "Long" | "Short" | "Byte" => "int".into(),
375 "double" | "float" | "Double" | "Float" => "number".into(),
376 "boolean" | "Boolean" => "boolean".into(),
377 "void" | "Void" => "void".into(),
378 "List" | "ArrayList" | "Collection" | "Iterable" | "LinkedList" => {
379 let inner = arg(0)?;
380 if inner.contains(' ') {
381 format!("({inner})[]")
382 } else {
383 format!("{inner}[]")
384 }
385 }
386 "Map" | "LinkedHashMap" | "TreeMap" | "HashMap" => {
387 if arg(0)? != "string" {
388 return Err(format!("`{t}`: JSON object keys are strings"));
389 }
390 format!("Record<string, {}>", arg(1)?)
391 }
392 "Optional" => format!("{} | undefined", arg(0)?),
393 "OptionalInt" | "OptionalLong" => "int | undefined".into(),
394 "OptionalDouble" => "number | undefined".into(),
395 "char" | "Character" => return Err("uses `char`, a UTF-16 code unit".into()),
396 "Object" => return Err("takes or returns `Object`: values of any type".into()),
397 "Function" | "BiFunction" | "Supplier" | "Consumer" | "Predicate" | "Runnable"
398 | "Callable" | "Comparator" => {
399 return Err("takes or returns a function".into());
400 }
401 "Stream" | "Iterator" | "IntStream" => {
402 return Err(format!("uses `{head}`, a lazy sequence"));
403 }
404 other => return Err(format!("uses the class `{other}`")),
405 })
406}
407
408fn split_top(text: &str) -> Vec<String> {
409 let mut out = Vec::new();
410 let mut depth = 0i32;
411 let mut current = String::new();
412 for c in text.chars() {
413 match c {
414 '<' => depth += 1,
415 '>' => depth -= 1,
416 ',' if depth == 0 => {
417 out.push(current.trim().to_string());
418 current.clear();
419 continue;
420 }
421 _ => {}
422 }
423 current.push(c);
424 }
425 if !current.trim().is_empty() {
426 out.push(current.trim().to_string());
427 }
428 out
429}
430
431pub fn package_name(source: &str) -> Option<String> {
433 let tree = syntax::parse(&language(), source)?;
434 package_name_in(tree.root_node(), source)
435}
436
437fn package_name_in(root: Node<'_>, source: &str) -> Option<String> {
438 let declaration = named_children(root)
439 .into_iter()
440 .find(|node| node.kind() == "package_declaration")?;
441 let name = named_children(declaration)
442 .into_iter()
443 .find(|node| matches!(node.kind(), "identifier" | "scoped_identifier"))?;
444 let mut components = Vec::new();
445 syntax::walk(name, |node| {
446 if node.kind() == "identifier" {
447 components.push(text(node, source));
448 }
449 });
450 Some(components.join("."))
451}
452
453pub fn exports(path: &str, source: &str) -> Vec<ExportedFn> {
456 if !path.ends_with(".java") {
457 return Vec::new();
458 }
459 let Some(tree) = syntax::parse(&language(), source) else {
460 return Vec::new();
461 };
462 let package = package_name_in(tree.root_node(), source);
463 let mut out = Vec::new();
464 for class in named_children(tree.root_node()) {
465 if class.kind() != "class_declaration" {
466 continue;
467 }
468 let modifiers = |n: Node| {
469 named_children(n)
470 .into_iter()
471 .find(|c| c.kind() == "modifiers")
472 .map_or(String::new(), |m| text(m, source).to_string())
473 };
474 if !modifiers(class).split_whitespace().any(|w| w == "public") {
475 continue;
476 }
477 let Some(class_name) = class
478 .child_by_field_name("name")
479 .map(|n| text(n, source).to_string())
480 else {
481 continue;
482 };
483 let qualified = match &package {
484 Some(p) => format!("{p}.{class_name}"),
485 None => class_name.clone(),
486 };
487 let Some(body) = class.child_by_field_name("body") else {
488 continue;
489 };
490 for method in named_children(body) {
491 if method.kind() != "method_declaration" {
492 continue;
493 }
494 let mods = modifiers(method);
495 let words: Vec<&str> = mods.split_whitespace().collect();
496 if !(words.contains(&"public") && words.contains(&"static")) {
497 continue;
498 }
499 let Some(name) = method
500 .child_by_field_name("name")
501 .map(|n| text(n, source).to_string())
502 else {
503 continue;
504 };
505 let mut blocker = None;
506 if method.child_by_field_name("type_parameters").is_some() {
507 blocker = Some("generic: erased types cannot be recovered".to_string());
508 }
509 let mut params = Vec::new();
510 let mut signature = Vec::new();
511 if let Some(list) = method.child_by_field_name("parameters") {
512 for p in named_children(list) {
513 let (ty, pname) = match p.kind() {
514 "formal_parameter" => {
515 let base = p
516 .child_by_field_name("type")
517 .map_or("", |t| text(t, source))
518 .to_string();
519 let dims = named_children(p)
522 .iter()
523 .find(|c| c.kind() == "dimensions")
524 .map_or(String::new(), |d| {
525 text(*d, source).split_whitespace().collect::<String>()
526 });
527 (
528 format!("{base}{dims}"),
529 p.child_by_field_name("name")
530 .map_or("", |n| text(n, source))
531 .to_string(),
532 )
533 }
534 "spread_parameter" => {
535 blocker.get_or_insert_with(|| "is variadic".into());
536 continue;
537 }
538 _ => continue,
539 };
540 let ts_type = java_to_ts(&ty).unwrap_or_else(|reason| {
541 blocker.get_or_insert(reason);
542 "unknown".into()
543 });
544 signature.push(format!("{ty} {pname}"));
545 params.push(Param {
546 name: pname,
547 ts_type,
548 native_type: Some(ty),
549 ..Default::default()
550 });
551 }
552 }
553 let ret = method
554 .child_by_field_name("type")
555 .map_or("void", |t| text(t, source))
556 .to_string();
557 let returns = java_to_ts(&ret).unwrap_or_else(|reason| {
558 blocker.get_or_insert(reason);
559 "unknown".into()
560 });
561 if out.iter().any(|f: &ExportedFn| f.name == name) {
562 blocker = Some(super::OVERLOADED.into());
563 }
564 out.push(ExportedFn {
565 name,
566 file: path.to_string(),
567 line: syntax::line(method),
568 params,
569 returns,
570 native_return: Some(ret),
571 prototype: Some(format!(
572 "{qualified}.{}({})",
573 text(method.child_by_field_name("name").unwrap_or(method), source),
574 signature.join(", ")
575 )),
576 blocker,
577 ..Default::default()
578 });
579 }
580 }
581 let mut counts: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
584 for f in &out {
585 *counts.entry(f.name.clone()).or_default() += 1;
586 }
587 for f in &mut out {
588 if counts.get(&f.name).copied().unwrap_or(0) > 1 {
589 f.blocker = Some(super::OVERLOADED.into());
590 }
591 }
592 out
593}
594
595pub fn receiver(f: &ExportedFn) -> (String, String) {
597 let proto = f.prototype.as_deref().unwrap_or(&f.name);
598 let head = proto.split('(').next().unwrap_or(proto);
599 match head.rsplit_once('.') {
600 Some((class, name)) => (class.to_string(), name.to_string()),
601 None => (String::new(), f.name.clone()),
602 }
603}
604
605#[cfg(test)]
606mod tests {
607 use super::*;
608
609 #[test]
610 fn a_c_style_array_parameter_keeps_its_dimensions() {
611 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";
615 let fns = exports("acme/Stats.java", src);
616 let types: Vec<(&str, &str)> = fns
617 .iter()
618 .map(|f| (f.name.as_str(), f.params[0].ts_type.as_str()))
619 .collect();
620 assert_eq!(
621 types,
622 [
623 ("sum", "int[]"),
624 ("plain", "int[]"),
625 ("grid", "int[][]"),
626 ("tabbed", "int[]"),
627 ]
628 );
629 }
630
631 #[test]
632 fn a_wildcard_is_named_as_one_and_stays_refused() {
633 for t in ["List<? extends CharSequence>", "List<? extends Number>"] {
636 let reason = java_to_ts(t).unwrap_err();
637 assert!(reason.contains("wildcard"), "{t}: {reason}");
638 assert!(!reason.contains("uses the class"), "{t}: {reason}");
639 }
640 assert_eq!(java_to_ts("List<String>").unwrap(), "string[]");
641 assert!(
643 java_to_ts("List<? super String>")
644 .unwrap_err()
645 .contains("? super String")
646 );
647 assert!(
648 java_to_ts("List<?>")
649 .unwrap_err()
650 .contains("values of any type")
651 );
652 }
653
654 #[test]
655 fn maps_types() {
656 assert_eq!(java_to_ts("List<String>").unwrap(), "string[]");
657 assert_eq!(
658 java_to_ts("Map<String, List<Integer>>").unwrap(),
659 "Record<string, int[]>"
660 );
661 assert_eq!(java_to_ts("double[]").unwrap(), "number[]");
662 assert!(java_to_ts("Point").is_err());
663 }
664
665 #[test]
666 fn finds_public_static_methods() {
667 let src = "package com.example.text;\nimport java.util.List;\npublic final class Strings {\n\
668 private Strings() {}\n\
669 public static String slugify(String text, int max) { return text; }\n\
670 public static List<String> words(final String text) { return null; }\n\
671 public static <T> T id(T x) { return x; }\n\
672 static int hidden() { return 1; }\n\
673 public int instance() { return 1; }\n}\n";
674 let fns = exports("src/main/java/com/example/text/Strings.java", src);
675 let names: Vec<&str> = fns.iter().map(|f| f.name.as_str()).collect();
676 assert_eq!(names, ["slugify", "words", "id"]);
677 assert_eq!(fns[0].params[1].ts_type, "int");
678 assert_eq!(
679 receiver(&fns[0]),
680 ("com.example.text.Strings".into(), "slugify".into())
681 );
682 assert_eq!(fns[1].returns, "string[]");
683 assert!(fns[2].blocker.is_some());
684 }
685
686 #[test]
687 fn every_overload_of_a_name_is_blocked() {
688 let src = "package com.example;\npublic final class Nums {\n\
689 public static int add(int a, int b) { return a + b; }\n\
690 public static double add(double a, double b) { return a + b; }\n\
691 public static int one() { return 1; }\n}\n";
692 let fns = exports("src/main/java/com/example/Nums.java", src);
693 let blocked: Vec<(&str, bool)> = fns
694 .iter()
695 .map(|f| (f.name.as_str(), f.blocker.is_some()))
696 .collect();
697 assert_eq!(blocked, [("add", true), ("add", true), ("one", false)]);
698 }
699}