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