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