java.rs 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621
  1. //! Java extraction — a faithful Rust port of `TreeSitterExtractor`'s Java
  2. //! paths (src/extraction/tree-sitter.ts) plus languages/java.ts, including
  3. //! the Lombok member synthesizer (#912).
  4. //!
  5. //! Same porting contract as tsjs/: behavior parity with the wasm path,
  6. //! bug-for-bug, verified by scripts/kernel-parity.mjs and the full-index
  7. //! dump-diff gate. Positions in UTF-16 code units. Files whose parse tree
  8. //! contains ERRORS defer to the wasm extractor (encoding-dependent recovery —
  9. //! see tsjs/mod.rs).
  10. use crate::buffers::{
  11. build_meta, edge_kind_index, node_kind_index, Arena, BoolFlags, EdgeRow, EmitOut, NodeRow,
  12. RefRow, StrRef, Tables, FLAG_IS_STATIC, FUNCTION_REF_CODE, NONE, NONE_STR,
  13. };
  14. use crate::docstring::preceding_docstring;
  15. use crate::ids;
  16. use crate::textutil as util;
  17. use regex::Regex;
  18. use std::collections::{HashMap, HashSet};
  19. use std::sync::OnceLock;
  20. use tree_sitter::{Node, Parser};
  21. const MAX_VALUE_REF_NODES: usize = 20_000;
  22. fn is_method_type(kind: &str) -> bool {
  23. matches!(kind, "method_declaration" | "constructor_declaration")
  24. }
  25. fn is_interface_type(kind: &str) -> bool {
  26. matches!(kind, "interface_declaration" | "annotation_type_declaration")
  27. }
  28. /// JAVA_NON_CLASS_RETURN_NODES (languages/java.ts).
  29. fn is_non_class_return(kind: &str) -> bool {
  30. matches!(kind, "void_type" | "integral_type" | "floating_point_type" | "boolean_type")
  31. }
  32. /// BUILTIN_TYPES (tree-sitter.ts) — shared table; only the Java-relevant names
  33. /// fire here but membership is what the TS code tests.
  34. fn is_builtin_type(name: &str) -> bool {
  35. matches!(
  36. name,
  37. "string" | "number" | "boolean" | "void" | "null" | "undefined" | "never" | "any"
  38. | "unknown" | "object" | "symbol" | "bigint" | "true" | "false"
  39. | "str" | "bool" | "i8" | "i16" | "i32" | "i64" | "i128" | "isize"
  40. | "u8" | "u16" | "u32" | "u64" | "u128" | "usize" | "f32" | "f64" | "char"
  41. | "int" | "long" | "short" | "byte" | "float" | "double"
  42. | "int8" | "int16" | "int32" | "int64" | "uint8" | "uint16" | "uint32" | "uint64"
  43. | "float32" | "float64" | "complex64" | "complex128" | "rune" | "error"
  44. | "Int" | "Long" | "Short" | "Byte" | "Float" | "Double" | "Boolean" | "Char"
  45. | "Unit" | "String" | "Any" | "AnyRef" | "AnyVal" | "Nothing" | "Null"
  46. )
  47. }
  48. /// LOMBOK_LOG_ANNOTATIONS (languages/java.ts).
  49. fn is_lombok_log_annotation(name: &str) -> bool {
  50. matches!(
  51. name,
  52. "Slf4j" | "Log4j" | "Log4j2" | "Log" | "CommonsLog" | "JBossLog" | "Flogger" | "XSlf4j"
  53. | "CustomLog"
  54. )
  55. }
  56. fn generic_args_re() -> &'static Regex {
  57. static RE: OnceLock<Regex> = OnceLock::new();
  58. RE.get_or_init(|| Regex::new(r"<[^>]*>").unwrap())
  59. }
  60. fn simple_ident_re() -> &'static Regex {
  61. static RE: OnceLock<Regex> = OnceLock::new();
  62. RE.get_or_init(|| Regex::new(r"^[A-Za-z_]\w*$").unwrap())
  63. }
  64. fn capitalized_re() -> &'static Regex {
  65. static RE: OnceLock<Regex> = OnceLock::new();
  66. RE.get_or_init(|| Regex::new(r"^[A-Z][A-Za-z0-9_]*$").unwrap())
  67. }
  68. fn method_ref_type_re() -> &'static Regex {
  69. static RE: OnceLock<Regex> = OnceLock::new();
  70. RE.get_or_init(|| Regex::new(r"^([A-Z][A-Za-z0-9_]*)\s*::").unwrap())
  71. }
  72. fn is_prefix_re(word: &str) -> bool {
  73. // /^is[A-Z]/ for Lombok boolean getters.
  74. word.len() > 2 && word.starts_with("is") && word.as_bytes()[2].is_ascii_uppercase()
  75. }
  76. struct Scope {
  77. row: u32,
  78. kind: &'static str,
  79. name: String,
  80. }
  81. /// Per-node metadata kept for the Lombok synthesizer's taken-member scan
  82. /// (mirrors its walk over ctx.nodes by qualifiedName).
  83. struct NodeMeta {
  84. kind: &'static str,
  85. name: String,
  86. qualified_name: String,
  87. }
  88. #[derive(Default)]
  89. struct Extra {
  90. docstring: Option<String>,
  91. signature: Option<String>,
  92. visibility: Option<u8>,
  93. is_static: Option<bool>,
  94. return_type: Option<String>,
  95. decorators: Option<Vec<String>>,
  96. }
  97. struct ValueScope<'t> {
  98. row: u32,
  99. node: Node<'t>,
  100. name: String,
  101. }
  102. struct Cand {
  103. from: u32,
  104. name: String,
  105. line: u32,
  106. column_byte: usize,
  107. row: usize,
  108. }
  109. pub struct Walker<'t> {
  110. src: &'t str,
  111. file_path: &'t str,
  112. line_starts: Vec<usize>,
  113. arena: Arena,
  114. tables: Tables,
  115. stack: Vec<Scope>,
  116. nodes_meta: Vec<NodeMeta>,
  117. /// Node id string per row — ids COLLIDE for same-(kind, name, line) nodes
  118. /// and the TS side's fn-ref dedupe / value-ref self-checks key on the id.
  119. node_ids: Vec<String>,
  120. defined_fn_names: HashSet<String>,
  121. imported_names: HashSet<String>,
  122. fn_ref_cands: Vec<Cand>,
  123. fs_values: HashMap<String, u32>,
  124. fs_value_counts: HashMap<String, u32>,
  125. value_scopes: Vec<ValueScope<'t>>,
  126. }
  127. pub fn extract(file_path: &str, source: &str) -> Result<EmitOut, String> {
  128. let grammar = crate::langs::grammar_for("java").ok_or("no java grammar")?;
  129. let t0 = std::time::Instant::now();
  130. let mut parser = Parser::new();
  131. parser
  132. .set_language(&grammar)
  133. .map_err(|e| format!("set_language(java) failed: {e}"))?;
  134. let tree = parser
  135. .parse(source, None)
  136. .ok_or_else(|| "parser returned null tree".to_string())?;
  137. if tree.root_node().has_error() {
  138. return Err("defer: parse tree contains errors — wasm recovery is canonical".to_string());
  139. }
  140. let mut w = Walker {
  141. src: source,
  142. file_path,
  143. line_starts: util::line_starts(source),
  144. arena: Arena::default(),
  145. tables: Tables::default(),
  146. stack: Vec::new(),
  147. nodes_meta: Vec::new(),
  148. node_ids: Vec::new(),
  149. defined_fn_names: HashSet::new(),
  150. imported_names: HashSet::new(),
  151. fn_ref_cands: Vec::new(),
  152. fs_values: HashMap::new(),
  153. fs_value_counts: HashMap::new(),
  154. value_scopes: Vec::new(),
  155. };
  156. // File node (TreeSitterExtractor.extract).
  157. let line_count = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1;
  158. let base_name = file_path.rsplit(['/', '\\']).next().unwrap_or(file_path);
  159. let mut flags = BoolFlags::default();
  160. flags.set(crate::buffers::FLAG_IS_EXPORTED, false);
  161. let file_id = w.arena.put(&ids::file_node_id(file_path));
  162. let name_ref = w.arena.put(base_name);
  163. let qn_ref = w.arena.put(file_path);
  164. w.tables.push_node(&NodeRow {
  165. kind: node_kind_index("file").unwrap(),
  166. visibility: 0,
  167. flags,
  168. start_line: 1,
  169. end_line: line_count,
  170. start_column: 0,
  171. end_column: 0,
  172. name: name_ref,
  173. qualified_name: qn_ref,
  174. id: file_id,
  175. docstring: NONE_STR,
  176. signature: NONE_STR,
  177. decorators: NONE_STR,
  178. type_parameters: NONE_STR,
  179. return_type: NONE_STR,
  180. extra_json: NONE_STR,
  181. });
  182. w.nodes_meta.push(NodeMeta {
  183. kind: "file",
  184. name: base_name.to_string(),
  185. qualified_name: file_path.to_string(),
  186. });
  187. w.node_ids.push(ids::file_node_id(file_path));
  188. w.stack.push(Scope { row: 0, kind: "file", name: base_name.to_string() });
  189. // extractFilePackage: wrap top-level declarations in a `namespace` node
  190. // carrying the package FQN.
  191. let root = tree.root_node();
  192. let mut pkg_pushed = false;
  193. for i in 0..root.named_child_count() {
  194. let Some(child) = root.named_child(i) else { continue };
  195. if child.kind() != "package_declaration" {
  196. continue;
  197. }
  198. let id_node = (0..child.named_child_count())
  199. .filter_map(|j| child.named_child(j))
  200. .find(|c| matches!(c.kind(), "scoped_identifier" | "identifier"));
  201. if let Some(id_node) = id_node {
  202. let pkg = w.text(id_node).trim().to_string();
  203. if !pkg.is_empty() {
  204. if let Some(row) = w.create_node("namespace", &pkg, child, Extra::default()) {
  205. w.stack.push(Scope { row, kind: "namespace", name: pkg });
  206. pkg_pushed = true;
  207. }
  208. }
  209. }
  210. break;
  211. }
  212. w.visit_node(root);
  213. w.flush_fn_ref_candidates();
  214. w.flush_value_refs(root);
  215. if pkg_pushed {
  216. w.stack.pop();
  217. }
  218. w.stack.pop();
  219. let duration_ms = t0.elapsed().as_secs_f64() * 1000.0;
  220. let meta = build_meta(&w.tables, w.arena.len(), NONE_STR, duration_ms);
  221. Ok(EmitOut {
  222. meta,
  223. nodes: w.tables.nodes,
  224. edges: w.tables.edges,
  225. refs: w.tables.refs,
  226. arena: w.arena.into_vec(),
  227. })
  228. }
  229. impl<'t> Walker<'t> {
  230. fn text(&self, node: Node) -> &'t str {
  231. &self.src[node.byte_range()]
  232. }
  233. fn line_of(&self, node: Node) -> u32 {
  234. node.start_position().row as u32 + 1
  235. }
  236. fn col_of(&self, node: Node) -> u32 {
  237. util::col16(self.src, &self.line_starts, node.start_position().row, node.start_byte())
  238. }
  239. fn end_col_of(&self, node: Node) -> u32 {
  240. util::col16(self.src, &self.line_starts, node.end_position().row, node.end_byte())
  241. }
  242. fn top_row(&self) -> u32 {
  243. self.stack.last().map(|s| s.row).unwrap_or(0)
  244. }
  245. fn inside_class_like(&self) -> bool {
  246. self.stack
  247. .last()
  248. .map(|s| matches!(s.kind, "class" | "struct" | "interface" | "trait" | "enum" | "module"))
  249. .unwrap_or(false)
  250. }
  251. fn push_ref(&mut self, from_row: u32, name: &str, kind_code: u8, line: u32, column: u32) {
  252. let name_ref = self.arena.put(name);
  253. self.tables.push_ref(&RefRow {
  254. from_idx: from_row,
  255. kind: kind_code,
  256. line,
  257. column,
  258. reference_name: name_ref,
  259. candidates: NONE_STR,
  260. from_id_str: NONE_STR,
  261. });
  262. if kind_code == edge_kind_index("imports").unwrap() {
  263. if util::simple_name().is_match(name) {
  264. self.imported_names.insert(name.to_string());
  265. } else if let Some(c) = util::qualified_import().captures(name) {
  266. self.imported_names.insert(c[1].to_string());
  267. }
  268. }
  269. }
  270. fn push_ref_at(&mut self, from_row: u32, name: &str, kind_code: u8, node: Node) {
  271. self.push_ref(from_row, name, kind_code, self.line_of(node), self.col_of(node));
  272. }
  273. // --- createNode ------------------------------------------------------------
  274. fn create_node(&mut self, kind: &'static str, name: &str, node: Node<'t>, extra: Extra) -> Option<u32> {
  275. if name.is_empty() {
  276. return None;
  277. }
  278. let start_line = self.line_of(node);
  279. let id = ids::node_id(self.file_path, kind, name, start_line);
  280. let end_line = node.end_position().row as u32 + 1; // no resolveBody for java
  281. let qualified = {
  282. let mut parts: Vec<&str> = Vec::new();
  283. for s in &self.stack {
  284. if s.kind != "file" {
  285. parts.push(&s.name);
  286. }
  287. }
  288. let mut qn = parts.join("::");
  289. if !qn.is_empty() {
  290. qn.push_str("::");
  291. }
  292. qn.push_str(name);
  293. qn
  294. };
  295. let mut flags = BoolFlags::default();
  296. if let Some(v) = extra.is_static {
  297. flags.set(FLAG_IS_STATIC, v);
  298. }
  299. let name_ref = self.arena.put(name);
  300. let qn_ref = self.arena.put(&qualified);
  301. let id_ref = self.arena.put(&id);
  302. let doc_ref = opt_str(&mut self.arena, extra.docstring.as_deref());
  303. let sig_ref = opt_str(&mut self.arena, extra.signature.as_deref());
  304. let ret_ref = opt_str(&mut self.arena, extra.return_type.as_deref());
  305. let dec_ref: StrRef = match &extra.decorators {
  306. Some(list) if !list.is_empty() => self.arena.put_list(list),
  307. _ => NONE_STR,
  308. };
  309. let row = self.tables.push_node(&NodeRow {
  310. kind: node_kind_index(kind).unwrap(),
  311. visibility: extra.visibility.unwrap_or(0),
  312. flags,
  313. start_line,
  314. end_line,
  315. start_column: self.col_of(node),
  316. end_column: self.end_col_of(node),
  317. name: name_ref,
  318. qualified_name: qn_ref,
  319. id: id_ref,
  320. docstring: doc_ref,
  321. signature: sig_ref,
  322. decorators: dec_ref,
  323. type_parameters: NONE_STR,
  324. return_type: ret_ref,
  325. extra_json: NONE_STR,
  326. });
  327. self.nodes_meta.push(NodeMeta { kind, name: name.to_string(), qualified_name: qualified });
  328. self.node_ids.push(id);
  329. let parent_row = self.top_row();
  330. self.tables.push_edge(&EdgeRow {
  331. source_idx: parent_row,
  332. target_idx: row,
  333. kind: edge_kind_index("contains").unwrap(),
  334. provenance: 0,
  335. line: NONE,
  336. column: NONE,
  337. metadata_json: NONE_STR,
  338. source_id_str: NONE_STR,
  339. target_id_str: NONE_STR,
  340. });
  341. if kind == "function" || kind == "method" {
  342. self.defined_fn_names.insert(name.to_string());
  343. }
  344. self.capture_value_ref_scope(kind, name, row, node);
  345. Some(row)
  346. }
  347. fn capture_value_ref_scope(&mut self, kind: &'static str, name: &str, row: u32, node: Node<'t>) {
  348. let target_kind_ok = kind == "constant" || kind == "variable";
  349. if target_kind_ok
  350. && util::utf16_len(name) >= 3
  351. && util::has_upper_or_underscore().is_match(name)
  352. {
  353. let parent_ok = self
  354. .stack
  355. .last()
  356. .map(|s| matches!(s.kind, "file" | "class" | "module" | "struct" | "enum"))
  357. .unwrap_or(false);
  358. if parent_ok {
  359. self.fs_values.insert(name.to_string(), row);
  360. *self.fs_value_counts.entry(name.to_string()).or_insert(0) += 1;
  361. }
  362. }
  363. if matches!(kind, "function" | "method" | "constant" | "variable") {
  364. self.value_scopes.push(ValueScope { row, node, name: name.to_string() });
  365. }
  366. }
  367. // --- modifiers / hooks (languages/java.ts) -----------------------------------
  368. fn modifiers_child(&self, node: Node<'t>) -> Option<Node<'t>> {
  369. (0..node.named_child_count())
  370. .filter_map(|i| node.named_child(i))
  371. .find(|c| c.kind() == "modifiers")
  372. }
  373. fn visibility_of(&self, node: Node) -> Option<u8> {
  374. for i in 0..node.child_count() {
  375. let child = node.child(i)?;
  376. if child.kind() == "modifiers" {
  377. let text = self.text(child);
  378. if text.contains("public") {
  379. return Some(1);
  380. }
  381. if text.contains("private") {
  382. return Some(2);
  383. }
  384. if text.contains("protected") {
  385. return Some(3);
  386. }
  387. }
  388. }
  389. None
  390. }
  391. fn is_static(&self, node: Node) -> bool {
  392. for i in 0..node.child_count() {
  393. if let Some(child) = node.child(i) {
  394. if child.kind() == "modifiers" && self.text(child).contains("static") {
  395. return true;
  396. }
  397. }
  398. }
  399. false
  400. }
  401. /// javaExtractor.isConst: `static final` field → constant.
  402. fn is_const(&self, node: Node) -> bool {
  403. for i in 0..node.child_count() {
  404. if let Some(child) = node.child(i) {
  405. if child.kind() == "modifiers" {
  406. let text = self.text(child);
  407. return word_re("static").is_match(text) && word_re("final").is_match(text);
  408. }
  409. }
  410. }
  411. false
  412. }
  413. fn signature_of(&self, node: Node) -> Option<String> {
  414. let params = node.child_by_field_name("parameters")?;
  415. let params_text = self.text(params);
  416. match node.child_by_field_name("type") {
  417. Some(ret) => Some(format!("{} {}", self.text(ret), params_text)),
  418. None => Some(params_text.to_string()),
  419. }
  420. }
  421. /// normalizeJavaType (languages/java.ts).
  422. fn normalize_java_type(&self, type_node: Option<Node>) -> Option<String> {
  423. let t = type_node?;
  424. if is_non_class_return(t.kind()) || t.kind() == "array_type" {
  425. return None;
  426. }
  427. let raw = generic_args_re().replace_all(self.text(t).trim(), "").into_owned();
  428. let last = raw.rsplit('.').next().unwrap_or("").trim().to_string();
  429. if last.is_empty() || !simple_ident_re().is_match(&last) {
  430. return None;
  431. }
  432. Some(last)
  433. }
  434. fn extract_name(&self, node: Node) -> String {
  435. if let Some(name_node) = node.child_by_field_name("name") {
  436. return self.text(name_node).to_string();
  437. }
  438. for i in 0..node.named_child_count() {
  439. if let Some(c) = node.named_child(i) {
  440. if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") {
  441. return self.text(c).to_string();
  442. }
  443. }
  444. }
  445. "<anonymous>".to_string()
  446. }
  447. // --- the dispatcher (visitNode, Java-relevant branches) -----------------------
  448. fn visit_node(&mut self, node: Node<'t>) {
  449. stack_guard!();
  450. let kind = node.kind();
  451. let mut skip_children = false;
  452. self.maybe_capture_fn_refs(node);
  453. if kind == "class_declaration" {
  454. self.extract_class(node);
  455. skip_children = true;
  456. } else if is_method_type(kind) {
  457. self.extract_method(node);
  458. skip_children = true;
  459. } else if is_interface_type(kind) {
  460. self.extract_interface(node);
  461. skip_children = true;
  462. } else if kind == "enum_declaration" {
  463. self.extract_enum(node);
  464. skip_children = true;
  465. } else if kind == "field_declaration" && self.inside_class_like() {
  466. self.extract_field(node);
  467. self.scan_fn_ref_subtree(node, 0);
  468. skip_children = true;
  469. } else if kind == "local_variable_declaration" && !self.inside_class_like() {
  470. self.extract_variable(node);
  471. self.scan_fn_ref_subtree(node, 0);
  472. skip_children = true;
  473. } else if kind == "import_declaration" {
  474. self.extract_import(node);
  475. } else if kind == "method_invocation" {
  476. self.extract_call(node);
  477. } else if kind == "object_creation_expression" {
  478. self.extract_instantiation(node);
  479. if let Some(anon_body) = find_anonymous_class_body(node) {
  480. self.extract_anonymous_class(node, anon_body);
  481. skip_children = true;
  482. }
  483. }
  484. if !skip_children {
  485. for i in 0..node.named_child_count() {
  486. if let Some(c) = node.named_child(i) {
  487. self.visit_node(c);
  488. }
  489. }
  490. }
  491. }
  492. // --- visitFunctionBody ----------------------------------------------------------
  493. fn visit_function_body(&mut self, body: Node<'t>) {
  494. stack_guard!();
  495. self.visit_for_calls_and_structure(body);
  496. }
  497. fn visit_for_calls_and_structure(&mut self, node: Node<'t>) {
  498. stack_guard!();
  499. let kind = node.kind();
  500. self.maybe_capture_fn_refs(node);
  501. if kind == "method_invocation" {
  502. self.extract_call(node);
  503. } else if kind == "object_creation_expression" {
  504. self.extract_instantiation(node);
  505. if let Some(anon_body) = find_anonymous_class_body(node) {
  506. self.extract_anonymous_class(node, anon_body);
  507. return;
  508. }
  509. }
  510. // Static-member / value-read (`Type.CONST`) — self-gates on field_access.
  511. self.extract_static_member_ref(node);
  512. if kind == "class_declaration" {
  513. self.extract_class(node);
  514. return;
  515. }
  516. if kind == "enum_declaration" {
  517. self.extract_enum(node);
  518. return;
  519. }
  520. if is_interface_type(kind) {
  521. self.extract_interface(node);
  522. return;
  523. }
  524. for i in 0..node.named_child_count() {
  525. if let Some(c) = node.named_child(i) {
  526. self.visit_for_calls_and_structure(c);
  527. }
  528. }
  529. }
  530. // --- extractors --------------------------------------------------------------
  531. fn extract_class(&mut self, node: Node<'t>) {
  532. stack_guard!();
  533. let name = self.extract_name(node);
  534. let extra = Extra {
  535. docstring: preceding_docstring(node, self.src),
  536. visibility: self.visibility_of(node),
  537. ..Extra::default() // java has no isExported hook
  538. };
  539. let Some(row) = self.create_node("class", &name, node, extra) else { return };
  540. self.extract_inheritance(node, row);
  541. self.extract_decorators_for(node, row);
  542. self.stack.push(Scope { row, kind: "class", name });
  543. let body = node.child_by_field_name("body").unwrap_or(node);
  544. for i in 0..body.named_child_count() {
  545. if let Some(c) = body.named_child(i) {
  546. self.visit_node(c);
  547. }
  548. }
  549. // Lombok member synthesis (#912) — class still on the stack.
  550. self.synthesize_lombok_members(node, row);
  551. self.stack.pop();
  552. }
  553. fn extract_method(&mut self, node: Node<'t>) {
  554. stack_guard!();
  555. if !self.inside_class_like() {
  556. // (object-literal parents don't exist in Java; a stray top-level
  557. // method extracts as a function, mirroring extractMethod's tail)
  558. self.extract_function(node);
  559. return;
  560. }
  561. let name = self.extract_name(node);
  562. let extra = Extra {
  563. docstring: preceding_docstring(node, self.src),
  564. signature: self.signature_of(node),
  565. visibility: self.visibility_of(node),
  566. is_static: Some(self.is_static(node)),
  567. return_type: self.normalize_java_type(node.child_by_field_name("type")),
  568. ..Extra::default()
  569. };
  570. let Some(row) = self.create_node("method", &name, node, extra) else { return };
  571. self.extract_type_annotations(node, row);
  572. self.extract_decorators_for(node, row);
  573. self.stack.push(Scope { row, kind: "method", name });
  574. if let Some(body) = node.child_by_field_name("body") {
  575. self.visit_function_body(body);
  576. }
  577. self.stack.pop();
  578. }
  579. /// extractFunction — only reachable for a method outside any class.
  580. fn extract_function(&mut self, node: Node<'t>) {
  581. stack_guard!();
  582. let name = self.extract_name(node);
  583. if name == "<anonymous>" {
  584. if let Some(body) = node.child_by_field_name("body") {
  585. self.visit_function_body(body);
  586. }
  587. return;
  588. }
  589. let extra = Extra {
  590. docstring: preceding_docstring(node, self.src),
  591. signature: self.signature_of(node),
  592. visibility: self.visibility_of(node),
  593. is_static: Some(self.is_static(node)),
  594. return_type: self.normalize_java_type(node.child_by_field_name("type")),
  595. ..Extra::default()
  596. };
  597. let Some(row) = self.create_node("function", &name, node, extra) else { return };
  598. self.extract_type_annotations(node, row);
  599. self.extract_decorators_for(node, row);
  600. self.stack.push(Scope { row, kind: "function", name });
  601. if let Some(body) = node.child_by_field_name("body") {
  602. self.visit_function_body(body);
  603. }
  604. self.stack.pop();
  605. }
  606. fn extract_interface(&mut self, node: Node<'t>) {
  607. stack_guard!();
  608. let name = self.extract_name(node);
  609. let extra = Extra {
  610. docstring: preceding_docstring(node, self.src),
  611. ..Extra::default()
  612. };
  613. let Some(row) = self.create_node("interface", &name, node, extra) else { return };
  614. self.extract_inheritance(node, row);
  615. self.stack.push(Scope { row, kind: "interface", name });
  616. let body = node.child_by_field_name("body").unwrap_or(node);
  617. for i in 0..body.named_child_count() {
  618. if let Some(c) = body.named_child(i) {
  619. self.visit_node(c);
  620. }
  621. }
  622. self.stack.pop();
  623. }
  624. fn extract_enum(&mut self, node: Node<'t>) {
  625. stack_guard!();
  626. let Some(body) = node.child_by_field_name("body") else { return };
  627. let name = self.extract_name(node);
  628. let extra = Extra {
  629. docstring: preceding_docstring(node, self.src),
  630. visibility: self.visibility_of(node),
  631. ..Extra::default()
  632. };
  633. let Some(row) = self.create_node("enum", &name, node, extra) else { return };
  634. self.extract_inheritance(node, row);
  635. self.stack.push(Scope { row, kind: "enum", name });
  636. for i in 0..body.named_child_count() {
  637. let Some(child) = body.named_child(i) else { continue };
  638. if child.kind() == "enum_constant" {
  639. self.extract_enum_members(child);
  640. } else {
  641. self.visit_node(child);
  642. }
  643. }
  644. self.stack.pop();
  645. }
  646. fn extract_enum_members(&mut self, node: Node<'t>) {
  647. if let Some(name_node) = node.child_by_field_name("name") {
  648. let name = self.text(name_node).to_string();
  649. self.create_node("enum_member", &name, node, Extra::default());
  650. }
  651. // (identifier-children / leaf fallbacks are other grammars' shapes)
  652. }
  653. /// extractField — each declarator becomes a field/constant node.
  654. fn extract_field(&mut self, node: Node<'t>) {
  655. let docstring = preceding_docstring(node, self.src);
  656. let visibility = self.visibility_of(node);
  657. let is_static = Some(self.is_static(node));
  658. let field_kind: &'static str = if self.is_const(node) { "constant" } else { "field" };
  659. let declarators: Vec<Node> = (0..node.named_child_count())
  660. .filter_map(|i| node.named_child(i))
  661. .filter(|c| c.kind() == "variable_declarator")
  662. .collect();
  663. if !declarators.is_empty() {
  664. let type_node = (0..node.named_child_count())
  665. .filter_map(|i| node.named_child(i))
  666. .find(|c| {
  667. !matches!(
  668. c.kind(),
  669. "modifiers" | "modifier" | "variable_declarator" | "variable_declaration"
  670. | "marker_annotation" | "annotation"
  671. )
  672. });
  673. let type_text = type_node.map(|t| self.text(t).to_string());
  674. for decl in declarators {
  675. let name_node = decl.child_by_field_name("name").or_else(|| {
  676. (0..decl.named_child_count())
  677. .filter_map(|i| decl.named_child(i))
  678. .find(|c| c.kind() == "identifier")
  679. });
  680. let Some(name_node) = name_node else { continue };
  681. let name = self.text(name_node).to_string();
  682. let signature = match &type_text {
  683. Some(t) => format!("{t} {name}"),
  684. None => name.clone(),
  685. };
  686. let row = self.create_node(
  687. field_kind,
  688. &name,
  689. decl,
  690. Extra {
  691. docstring: docstring.clone(),
  692. signature: Some(signature),
  693. visibility,
  694. is_static,
  695. ..Extra::default()
  696. },
  697. );
  698. if let Some(row) = row {
  699. self.extract_decorators_for(node, row);
  700. self.extract_type_annotations(node, row);
  701. }
  702. }
  703. } else {
  704. let name_node = node.child_by_field_name("name").or_else(|| {
  705. (0..node.named_child_count())
  706. .filter_map(|i| node.named_child(i))
  707. .find(|c| c.kind() == "identifier")
  708. });
  709. if let Some(name_node) = name_node {
  710. let name = self.text(name_node).to_string();
  711. self.create_node(
  712. field_kind,
  713. &name,
  714. node,
  715. Extra { docstring, visibility, is_static, ..Extra::default() },
  716. );
  717. }
  718. }
  719. }
  720. /// extractVariable's generic fallback (top-level locals — rare in Java).
  721. fn extract_variable(&mut self, node: Node<'t>) {
  722. let kind: &'static str = if self.is_const(node) { "constant" } else { "variable" };
  723. let docstring = preceding_docstring(node, self.src);
  724. for i in 0..node.named_child_count() {
  725. let Some(child) = node.named_child(i) else { continue };
  726. let name = match child.kind() {
  727. "identifier" => self.text(child).to_string(),
  728. "variable_declarator" => self.extract_name(child),
  729. _ => continue,
  730. };
  731. if name.is_empty() || name == "<anonymous>" {
  732. continue;
  733. }
  734. self.create_node(
  735. kind,
  736. &name,
  737. child,
  738. Extra { docstring: docstring.clone(), ..Extra::default() },
  739. );
  740. }
  741. }
  742. fn extract_import(&mut self, node: Node<'t>) {
  743. let import_text = self.text(node).trim().to_string();
  744. let scoped = (0..node.named_child_count())
  745. .filter_map(|i| node.named_child(i))
  746. .find(|c| c.kind() == "scoped_identifier");
  747. let Some(scoped) = scoped else { return }; // hook declined
  748. let module_name = self.text(scoped).to_string();
  749. if module_name.is_empty() {
  750. return;
  751. }
  752. self.create_node(
  753. "import",
  754. &module_name,
  755. node,
  756. Extra { signature: Some(import_text), ..Extra::default() },
  757. );
  758. let parent = self.top_row();
  759. self.push_ref_at(parent, &module_name.clone(), edge_kind_index("imports").unwrap(), node);
  760. }
  761. /// extractCall — the Java method_invocation paths.
  762. fn extract_call(&mut self, node: Node<'t>) {
  763. if self.stack.is_empty() {
  764. return;
  765. }
  766. let caller = self.top_row();
  767. let name_field = node.child_by_field_name("name");
  768. let object_field = node
  769. .child_by_field_name("object")
  770. .or_else(|| node.child_by_field_name("scope"));
  771. let mut callee_name = String::new();
  772. if let (Some(name_field), Some(object_field)) = (name_field, object_field) {
  773. let method_name = self.text(name_field);
  774. // Static-factory / fluent chain: `Foo.getInstance().bar()` →
  775. // `<inner-receiver>.<inner-method>().<method>` (#645/#608).
  776. if !method_name.is_empty() && object_field.kind() == "method_invocation" {
  777. let inner_obj = object_field.child_by_field_name("object");
  778. let inner_name = object_field.child_by_field_name("name");
  779. if let (Some(io), Some(inm)) = (inner_obj, inner_name) {
  780. let callee = format!("{}.{}().{}", self.text(io), self.text(inm), method_name);
  781. self.push_ref_at(caller, &callee, edge_kind_index("calls").unwrap(), node);
  782. return;
  783. }
  784. }
  785. // `this.userbo.toLogin2()` — unwrap the field after `this.`.
  786. let receiver_name = if object_field.kind() == "field_access" {
  787. let inner = object_field.child_by_field_name("object");
  788. let fld = object_field.child_by_field_name("field");
  789. match (inner, fld) {
  790. (Some(inner), Some(fld))
  791. if matches!(inner.kind(), "this" | "this_expression") =>
  792. {
  793. self.text(fld).to_string()
  794. }
  795. _ => self.text(object_field).to_string(),
  796. }
  797. } else {
  798. self.text(object_field).to_string()
  799. };
  800. let receiver_name = receiver_name.strip_prefix('$').unwrap_or(&receiver_name);
  801. if !method_name.is_empty() {
  802. if matches!(receiver_name, "self" | "this" | "cls" | "super" | "parent" | "static") {
  803. callee_name = method_name.to_string();
  804. } else {
  805. callee_name = format!("{receiver_name}.{method_name}");
  806. }
  807. }
  808. } else {
  809. // Bare call `foo()` — the generic tail: function field ?? first child.
  810. let func = node
  811. .child_by_field_name("function")
  812. .or_else(|| node.named_child(0));
  813. if let Some(func) = func {
  814. callee_name = self.text(func).to_string();
  815. }
  816. }
  817. if !callee_name.is_empty() {
  818. if let Some(c) = util::paren_conversion().captures(&callee_name) {
  819. callee_name = c[1].to_string();
  820. }
  821. self.push_ref_at(caller, &callee_name.clone(), edge_kind_index("calls").unwrap(), node);
  822. }
  823. }
  824. fn extract_instantiation(&mut self, node: Node<'t>) {
  825. if self.stack.is_empty() {
  826. return;
  827. }
  828. let ctor = node
  829. .child_by_field_name("constructor")
  830. .or_else(|| node.child_by_field_name("type"))
  831. .or_else(|| node.child_by_field_name("name"))
  832. .or_else(|| node.named_child(0));
  833. let Some(ctor) = ctor else { return };
  834. let class_name = strip_generic_and_qualifier(self.text(ctor));
  835. if !class_name.is_empty() {
  836. let from = self.top_row();
  837. self.push_ref_at(from, &class_name, edge_kind_index("instantiates").unwrap(), node);
  838. }
  839. }
  840. /// extractAnonymousClass — `new T() { ... }`.
  841. fn extract_anonymous_class(&mut self, node: Node<'t>, body: Node<'t>) {
  842. stack_guard!();
  843. let type_node = node
  844. .child_by_field_name("constructor")
  845. .or_else(|| node.child_by_field_name("type"))
  846. .or_else(|| node.child_by_field_name("name"))
  847. .or_else(|| node.named_child(0));
  848. let mut type_name = type_node.map(|t| self.text(t).to_string()).unwrap_or_else(|| "Object".to_string());
  849. type_name = strip_generic_and_qualifier(&type_name);
  850. if type_name.is_empty() {
  851. type_name = "Object".to_string();
  852. }
  853. let anon_name = format!("<{type_name}$anon@{}>", node.start_position().row + 1);
  854. let Some(row) = self.create_node("class", &anon_name, node, Extra::default()) else {
  855. return;
  856. };
  857. // Bug-for-bug: the TS code uses `startPosition.row` (0-based) as the
  858. // LINE here — the one place it forgets the +1.
  859. let (line, column) = match type_node {
  860. Some(t) => (t.start_position().row as u32, self.col_of(t)),
  861. None => (node.start_position().row as u32, self.col_of(node)),
  862. };
  863. self.push_ref(row, &type_name, edge_kind_index("extends").unwrap(), line, column);
  864. self.stack.push(Scope { row, kind: "class", name: anon_name });
  865. for i in 0..body.named_child_count() {
  866. if let Some(c) = body.named_child(i) {
  867. self.visit_node(c);
  868. }
  869. }
  870. self.stack.pop();
  871. }
  872. /// extractStaticMemberRef — `Type.CONST` value reads (java: field_access).
  873. fn extract_static_member_ref(&mut self, node: Node<'t>) {
  874. if node.kind() != "field_access" {
  875. return;
  876. }
  877. if self.stack.is_empty() {
  878. return;
  879. }
  880. let owner = self.top_row();
  881. // Skip `Type.method()` — the access is a call's callee, already linked.
  882. if let Some(parent) = node.parent() {
  883. if parent.kind() == "method_invocation" {
  884. let callee = parent
  885. .child_by_field_name("function")
  886. .or_else(|| parent.child_by_field_name("method"))
  887. .or_else(|| parent.named_child(0));
  888. if let Some(callee) = callee {
  889. if callee.start_byte() == node.start_byte() {
  890. return;
  891. }
  892. }
  893. }
  894. }
  895. let recv = node
  896. .child_by_field_name("object")
  897. .or_else(|| node.child_by_field_name("expression"))
  898. .or_else(|| node.child_by_field_name("scope"))
  899. .or_else(|| node.named_child(0));
  900. let Some(recv) = recv else { return };
  901. if matches!(
  902. recv.kind(),
  903. "identifier" | "type_identifier" | "simple_identifier" | "name" | "scoped_type_identifier"
  904. ) {
  905. let text = self.text(recv);
  906. if capitalized_re().is_match(text) {
  907. self.push_ref_at(owner, &text.to_string(), edge_kind_index("references").unwrap(), recv);
  908. }
  909. }
  910. }
  911. /// extractInheritance — the Java clauses (type_list-aware).
  912. fn extract_inheritance(&mut self, node: Node<'t>, class_row: u32) {
  913. let extends_kind = edge_kind_index("extends").unwrap();
  914. let implements_kind = edge_kind_index("implements").unwrap();
  915. for i in 0..node.named_child_count() {
  916. let Some(child) = node.named_child(i) else { continue };
  917. match child.kind() {
  918. "superclass" | "extends_interfaces" => {
  919. let type_list = (0..child.named_child_count())
  920. .filter_map(|j| child.named_child(j))
  921. .find(|c| c.kind() == "type_list");
  922. let targets: Vec<Node> = match type_list {
  923. Some(tl) => (0..tl.named_child_count()).filter_map(|j| tl.named_child(j)).collect(),
  924. None => child.named_child(0).into_iter().collect(),
  925. };
  926. for target in targets {
  927. let name = self.text(target).to_string();
  928. self.push_ref_at(class_row, &name, extends_kind, target);
  929. }
  930. }
  931. "super_interfaces" => {
  932. let type_list = (0..child.named_child_count())
  933. .filter_map(|j| child.named_child(j))
  934. .find(|c| c.kind() == "type_list");
  935. let targets: Vec<Node> = match type_list {
  936. Some(tl) => (0..tl.named_child_count()).filter_map(|j| tl.named_child(j)).collect(),
  937. None => (0..child.named_child_count()).filter_map(|j| child.named_child(j)).collect(),
  938. };
  939. for iface in targets {
  940. let name = self.text(iface).to_string();
  941. self.push_ref_at(class_row, &name, implements_kind, iface);
  942. }
  943. }
  944. _ => {}
  945. }
  946. }
  947. }
  948. /// extractDecoratorsFor — Java annotations live inside `modifiers`.
  949. fn extract_decorators_for(&mut self, decl: Node<'t>, decorated_row: u32) {
  950. for i in 0..decl.named_child_count() {
  951. let Some(child) = decl.named_child(i) else { continue };
  952. self.consider_decorator(child, decorated_row);
  953. if child.kind() == "modifiers" {
  954. for j in 0..child.named_child_count() {
  955. if let Some(m) = child.named_child(j) {
  956. self.consider_decorator(m, decorated_row);
  957. }
  958. }
  959. }
  960. }
  961. // Preceding-sibling scan (TS-style class decorators) — Java annotations
  962. // are inside modifiers, so this is inert here; kept for parity of shape.
  963. let Some(parent) = decl.parent() else { return };
  964. let decl_start = decl.start_byte();
  965. let mut decl_idx: isize = -1;
  966. for i in 0..parent.named_child_count() {
  967. if let Some(sib) = parent.named_child(i) {
  968. if sib.start_byte() == decl_start {
  969. decl_idx = i as isize;
  970. break;
  971. }
  972. }
  973. }
  974. if decl_idx > 0 {
  975. let mut j = decl_idx - 1;
  976. while j >= 0 {
  977. let Some(sib) = parent.named_child(j as usize) else {
  978. j -= 1;
  979. continue;
  980. };
  981. if !matches!(sib.kind(), "decorator" | "annotation" | "marker_annotation") {
  982. break;
  983. }
  984. self.consider_decorator(sib, decorated_row);
  985. j -= 1;
  986. }
  987. }
  988. }
  989. fn consider_decorator(&mut self, n: Node<'t>, decorated_row: u32) {
  990. if !matches!(n.kind(), "decorator" | "annotation" | "marker_annotation" | "attribute") {
  991. return;
  992. }
  993. let mut target: Option<Node> = None;
  994. for i in 0..n.named_child_count() {
  995. let Some(child) = n.named_child(i) else { continue };
  996. if child.kind() == "call_expression" {
  997. target = child.child_by_field_name("function").or_else(|| child.named_child(0));
  998. if target.is_some() {
  999. break;
  1000. }
  1001. }
  1002. if matches!(
  1003. child.kind(),
  1004. "identifier" | "member_expression" | "scoped_identifier" | "navigation_expression"
  1005. | "user_type" | "type_identifier"
  1006. ) {
  1007. target = Some(child);
  1008. break;
  1009. }
  1010. }
  1011. let Some(target) = target else { return };
  1012. let name = strip_generic_and_qualifier(self.text(target));
  1013. if name.is_empty() {
  1014. return;
  1015. }
  1016. self.push_ref_at(decorated_row, &name, edge_kind_index("decorates").unwrap(), n);
  1017. }
  1018. /// extractTypeAnnotations — Java's returnField is `type`.
  1019. fn extract_type_annotations(&mut self, node: Node<'t>, from_row: u32) {
  1020. if let Some(params) = node.child_by_field_name("parameters") {
  1021. self.extract_type_refs_from_subtree(params, from_row);
  1022. }
  1023. if let Some(ret) = node.child_by_field_name("type") {
  1024. self.extract_type_refs_from_subtree(ret, from_row);
  1025. }
  1026. let type_annotation = (0..node.named_child_count())
  1027. .filter_map(|i| node.named_child(i))
  1028. .find(|c| c.kind() == "type_annotation");
  1029. if let Some(ta) = type_annotation {
  1030. self.extract_type_refs_from_subtree(ta, from_row);
  1031. }
  1032. }
  1033. fn extract_type_refs_from_subtree(&mut self, node: Node<'t>, from_row: u32) {
  1034. stack_guard!();
  1035. if node.kind() == "type_identifier" {
  1036. let type_name = self.text(node).to_string();
  1037. if !type_name.is_empty() && !is_builtin_type(&type_name) {
  1038. self.push_ref_at(from_row, &type_name, edge_kind_index("references").unwrap(), node);
  1039. }
  1040. return;
  1041. }
  1042. for i in 0..node.named_child_count() {
  1043. if let Some(c) = node.named_child(i) {
  1044. self.extract_type_refs_from_subtree(c, from_row);
  1045. }
  1046. }
  1047. }
  1048. // --- function-as-value refs (JAVA_SPEC: method references only) ----------------
  1049. fn maybe_capture_fn_refs(&mut self, node: Node<'t>) {
  1050. let mode_field: Option<&str> = match node.kind() {
  1051. "argument_list" => Some(""), // args: every named child
  1052. "assignment_expression" => Some("right"),
  1053. "variable_declarator" => Some("value"),
  1054. _ => None,
  1055. };
  1056. let Some(field) = mode_field else { return };
  1057. if self.stack.is_empty() {
  1058. return;
  1059. }
  1060. let from = self.top_row();
  1061. let mut values: Vec<Node> = Vec::new();
  1062. if field.is_empty() {
  1063. for i in 0..node.named_child_count() {
  1064. if let Some(c) = node.named_child(i) {
  1065. values.push(c);
  1066. }
  1067. }
  1068. } else if field == "right" {
  1069. if let Some(rhs) = node.child_by_field_name("right") {
  1070. let lhs_text = node
  1071. .child_by_field_name("left")
  1072. .map(|l| self.text(l))
  1073. .unwrap_or("");
  1074. let lhs_last = util::lhs_last_name()
  1075. .captures(lhs_text)
  1076. .and_then(|c| c.get(1))
  1077. .map(|m| m.as_str());
  1078. if !(lhs_last.is_some() && lhs_last == Some(self.text(rhs).trim())) {
  1079. values.push(rhs);
  1080. }
  1081. }
  1082. } else if let Some(v) = node.child_by_field_name("value") {
  1083. // varinit — destructuring patterns don't exist in Java.
  1084. values.push(v);
  1085. }
  1086. for v in values {
  1087. if v.kind() != "method_reference" {
  1088. continue; // idTypes is EMPTY for Java — only method references
  1089. }
  1090. let mut last_ident: Option<Node> = None;
  1091. for i in 0..v.named_child_count() {
  1092. if let Some(c) = v.named_child(i) {
  1093. if c.kind() == "identifier" {
  1094. last_ident = Some(c);
  1095. }
  1096. }
  1097. }
  1098. let Some(last) = last_ident else { continue };
  1099. let m = self.text(last);
  1100. let text = self.text(v);
  1101. let name = if text.starts_with("this::") || text.starts_with("super::") {
  1102. format!("this.{m}")
  1103. } else if let Some(c) = method_ref_type_re().captures(text) {
  1104. if m == "new" {
  1105. continue;
  1106. }
  1107. format!("{}::{m}", &c[1])
  1108. } else {
  1109. continue;
  1110. };
  1111. let p = last.start_position();
  1112. self.fn_ref_cands.push(Cand {
  1113. from,
  1114. name,
  1115. line: p.row as u32 + 1,
  1116. column_byte: last.start_byte(),
  1117. row: p.row,
  1118. });
  1119. }
  1120. }
  1121. fn scan_fn_ref_subtree(&mut self, node: Node<'t>, depth: u32) {
  1122. stack_guard!();
  1123. if depth > 12 {
  1124. return;
  1125. }
  1126. // (functionTypes is empty for Java; lambda_expression halts the scan)
  1127. if depth > 0 && matches!(node.kind(), "lambda_literal" | "lambda_expression") {
  1128. return;
  1129. }
  1130. self.maybe_capture_fn_refs(node);
  1131. for i in 0..node.named_child_count() {
  1132. if let Some(c) = node.named_child(i) {
  1133. self.scan_fn_ref_subtree(c, depth + 1);
  1134. }
  1135. }
  1136. }
  1137. fn flush_fn_ref_candidates(&mut self) {
  1138. let cands = std::mem::take(&mut self.fn_ref_cands);
  1139. if cands.is_empty() || util::is_generated_file(self.file_path) {
  1140. return;
  1141. }
  1142. let mut seen: HashSet<(String, String)> = HashSet::new();
  1143. for c in cands {
  1144. if !c.name.starts_with("this.")
  1145. && !c.name.contains("::")
  1146. && !self.defined_fn_names.contains(&c.name)
  1147. && !self.imported_names.contains(&c.name)
  1148. {
  1149. continue;
  1150. }
  1151. // Dedupe on the node ID string (ids collide; the TS side keys on
  1152. // `${fromNodeId}|${name}`).
  1153. if !seen.insert((self.node_ids[c.from as usize].clone(), c.name.clone())) {
  1154. continue;
  1155. }
  1156. let column = util::col16(self.src, &self.line_starts, c.row, c.column_byte);
  1157. let name_ref = self.arena.put(&c.name);
  1158. self.tables.push_ref(&RefRow {
  1159. from_idx: c.from,
  1160. kind: FUNCTION_REF_CODE,
  1161. line: c.line,
  1162. column,
  1163. reference_name: name_ref,
  1164. candidates: NONE_STR,
  1165. from_id_str: NONE_STR,
  1166. });
  1167. }
  1168. }
  1169. // --- value references ------------------------------------------------------------
  1170. fn flush_value_refs(&mut self, root: Node<'t>) {
  1171. let scopes = std::mem::take(&mut self.value_scopes);
  1172. let mut targets = std::mem::take(&mut self.fs_values);
  1173. let counts = std::mem::take(&mut self.fs_value_counts);
  1174. if std::env::var("CODEGRAPH_VALUE_REFS").as_deref() == Ok("0") {
  1175. return;
  1176. }
  1177. if targets.is_empty() || scopes.is_empty() || util::is_generated_file(self.file_path) {
  1178. return;
  1179. }
  1180. let mut decl_counts: HashMap<&str, u32> = HashMap::new();
  1181. let mut dstack: Vec<Node> = vec![root];
  1182. let mut dvisited = 0usize;
  1183. while let Some(n) = dstack.pop() {
  1184. if dvisited >= MAX_VALUE_REF_NODES {
  1185. break;
  1186. }
  1187. dvisited += 1;
  1188. if n.kind() == "variable_declarator" {
  1189. if let Some(first) = n.named_child(0) {
  1190. if first.kind() == "identifier" {
  1191. let nm = self.text(first);
  1192. if targets.contains_key(nm) {
  1193. *decl_counts.entry(nm).or_insert(0) += 1;
  1194. }
  1195. }
  1196. }
  1197. }
  1198. for i in 0..n.named_child_count() {
  1199. if let Some(c) = n.named_child(i) {
  1200. dstack.push(c);
  1201. }
  1202. }
  1203. }
  1204. let shadowed: Vec<String> = decl_counts
  1205. .iter()
  1206. .filter(|(nm, c)| **c > counts.get(**nm).copied().unwrap_or(1))
  1207. .map(|(nm, _)| nm.to_string())
  1208. .collect();
  1209. for nm in shadowed {
  1210. targets.remove(&nm);
  1211. }
  1212. if targets.is_empty() {
  1213. return;
  1214. }
  1215. let refs_kind = edge_kind_index("references").unwrap();
  1216. for scope in &scopes {
  1217. // ID-string comparisons, matching the TS side (ids collide).
  1218. let mut seen: HashSet<&str> = HashSet::new();
  1219. let mut stack: Vec<Node> = vec![scope.node];
  1220. let mut visited = 0usize;
  1221. while let Some(n) = stack.pop() {
  1222. if visited >= MAX_VALUE_REF_NODES {
  1223. break;
  1224. }
  1225. visited += 1;
  1226. if matches!(n.kind(), "identifier" | "constant" | "name" | "simple_identifier") {
  1227. let ref_name = self.text(n);
  1228. if let Some(&target_row) = targets.get(ref_name) {
  1229. let target_id = self.node_ids[target_row as usize].as_str();
  1230. if target_id != self.node_ids[scope.row as usize]
  1231. && ref_name != scope.name
  1232. && !seen.contains(&target_id)
  1233. {
  1234. seen.insert(target_id);
  1235. let meta = self.arena.put(r#"{"valueRef":true}"#);
  1236. self.tables.push_edge(&EdgeRow {
  1237. source_idx: scope.row,
  1238. target_idx: target_row,
  1239. kind: refs_kind,
  1240. provenance: 0,
  1241. line: NONE,
  1242. column: NONE,
  1243. metadata_json: meta,
  1244. source_id_str: NONE_STR,
  1245. target_id_str: NONE_STR,
  1246. });
  1247. }
  1248. }
  1249. }
  1250. for i in 0..n.named_child_count() {
  1251. if let Some(c) = n.named_child(i) {
  1252. stack.push(c);
  1253. }
  1254. }
  1255. }
  1256. }
  1257. }
  1258. // --- Lombok synthesis (#912, languages/java.ts synthesizeLombokMembers) ------------
  1259. fn lombok_annotation_names(&self, node: Node<'t>) -> HashSet<String> {
  1260. let mut names = HashSet::new();
  1261. let Some(modifiers) = self.modifiers_child(node) else { return names };
  1262. for i in 0..modifiers.named_child_count() {
  1263. let Some(child) = modifiers.named_child(i) else { continue };
  1264. if matches!(child.kind(), "marker_annotation" | "annotation") {
  1265. if let Some(name_node) = child.child_by_field_name("name") {
  1266. if let Some(simple) = self.text(name_node).trim().rsplit('.').next() {
  1267. if !simple.is_empty() {
  1268. names.insert(simple.to_string());
  1269. }
  1270. }
  1271. }
  1272. }
  1273. }
  1274. names
  1275. }
  1276. fn synthesize_lombok_members(&mut self, class_node: Node<'t>, class_row: u32) {
  1277. let class_anns = self.lombok_annotation_names(class_node);
  1278. let class_getter = class_anns.contains("Getter");
  1279. let class_setter = class_anns.contains("Setter");
  1280. let is_data = class_anns.contains("Data");
  1281. let is_value = class_anns.contains("Value");
  1282. let has_builder = class_anns.contains("Builder") || class_anns.contains("SuperBuilder");
  1283. let has_to_string = is_data || is_value || class_anns.contains("ToString");
  1284. let has_equals = is_data || is_value || class_anns.contains("EqualsAndHashCode");
  1285. let log_ann = class_anns.iter().find(|a| is_lombok_log_annotation(a)).cloned();
  1286. let Some(body) = class_node.child_by_field_name("body") else { return };
  1287. let fields: Vec<Node> = (0..body.named_child_count())
  1288. .filter_map(|i| body.named_child(i))
  1289. .filter(|c| c.kind() == "field_declaration")
  1290. .collect();
  1291. let class_has_lombok = class_getter
  1292. || class_setter
  1293. || is_data
  1294. || is_value
  1295. || has_builder
  1296. || has_to_string
  1297. || has_equals
  1298. || log_ann.is_some();
  1299. if !class_has_lombok && !fields.iter().any(|f| !self.lombok_annotation_names(*f).is_empty()) {
  1300. return;
  1301. }
  1302. // Members the source already declares (exact `classQN::name` matches).
  1303. let class_qn = self.nodes_meta[class_row as usize].qualified_name.clone();
  1304. let class_name = self.nodes_meta[class_row as usize].name.clone();
  1305. let mut taken_methods: HashSet<String> = HashSet::new();
  1306. let mut taken_fields: HashSet<String> = HashSet::new();
  1307. for m in &self.nodes_meta {
  1308. if m.qualified_name == format!("{class_qn}::{}", m.name) {
  1309. match m.kind {
  1310. "method" | "function" => {
  1311. taken_methods.insert(m.name.clone());
  1312. }
  1313. "field" | "variable" | "constant" | "property" => {
  1314. taken_fields.insert(m.name.clone());
  1315. }
  1316. _ => {}
  1317. }
  1318. }
  1319. }
  1320. let class_name_node = class_node.child_by_field_name("name").unwrap_or(class_node);
  1321. macro_rules! emit_method {
  1322. ($name:expr, $anchor:expr, $sig:expr, $from:expr, $is_static:expr, $ret:expr) => {{
  1323. let name: String = $name;
  1324. if !name.is_empty() && !taken_methods.contains(&name) {
  1325. taken_methods.insert(name.clone());
  1326. self.create_node(
  1327. "method",
  1328. &name,
  1329. $anchor,
  1330. Extra {
  1331. visibility: Some(1),
  1332. signature: Some($sig),
  1333. docstring: Some(format!("Lombok-generated ({})", $from)),
  1334. decorators: Some(vec!["lombok".to_string()]),
  1335. is_static: $is_static,
  1336. return_type: $ret,
  1337. },
  1338. );
  1339. }
  1340. }};
  1341. }
  1342. // Per-field getters/setters.
  1343. for fd in &fields {
  1344. let mods = self
  1345. .modifiers_child(*fd)
  1346. .map(|m| self.text(m))
  1347. .unwrap_or("");
  1348. if word_re("static").is_match(mods) {
  1349. continue;
  1350. }
  1351. let is_final = word_re("final").is_match(mods);
  1352. let field_anns = self.lombok_annotation_names(*fd);
  1353. let field_getter = field_anns.contains("Getter");
  1354. let field_setter = field_anns.contains("Setter");
  1355. let want_getter = class_getter || is_data || is_value || field_getter;
  1356. let want_setter = (class_setter || is_data || field_setter) && !is_final;
  1357. if !want_getter && !want_setter {
  1358. continue;
  1359. }
  1360. let type_node = fd.child_by_field_name("type");
  1361. let type_text = type_node
  1362. .map(|t| self.text(t).trim().to_string())
  1363. .unwrap_or_else(|| "Object".to_string());
  1364. let is_boolean_primitive = type_node.map(|t| t.kind() == "boolean_type").unwrap_or(false);
  1365. let return_type = self.normalize_java_type(type_node);
  1366. for i in 0..fd.named_child_count() {
  1367. let Some(vd) = fd.named_child(i) else { continue };
  1368. if vd.kind() != "variable_declarator" {
  1369. continue;
  1370. }
  1371. let Some(name_node) = vd.child_by_field_name("name") else { continue };
  1372. let field_name = self.text(name_node).trim().to_string();
  1373. if field_name.is_empty() {
  1374. continue;
  1375. }
  1376. if want_getter {
  1377. let g = if is_boolean_primitive {
  1378. if is_prefix_re(&field_name) {
  1379. field_name.clone()
  1380. } else {
  1381. format!("is{}", capitalize(&field_name))
  1382. }
  1383. } else {
  1384. format!("get{}", capitalize(&field_name))
  1385. };
  1386. let from = if field_getter {
  1387. "@Getter"
  1388. } else if is_data {
  1389. "@Data"
  1390. } else if is_value {
  1391. "@Value"
  1392. } else {
  1393. "@Getter"
  1394. };
  1395. emit_method!(g.clone(), name_node, format!("{type_text} {g}()"), from, None, return_type.clone());
  1396. }
  1397. if want_setter {
  1398. let base = if is_boolean_primitive && is_prefix_re(&field_name) {
  1399. field_name[2..].to_string()
  1400. } else {
  1401. field_name.clone()
  1402. };
  1403. let s = format!("set{}", capitalize(&base));
  1404. let from = if field_setter {
  1405. "@Setter"
  1406. } else if is_data {
  1407. "@Data"
  1408. } else {
  1409. "@Setter"
  1410. };
  1411. emit_method!(s.clone(), name_node, format!("void {s}({type_text} {field_name})"), from, None, None);
  1412. }
  1413. }
  1414. }
  1415. // Class-level synthesized methods.
  1416. if has_builder {
  1417. let from = if class_anns.contains("SuperBuilder") { "@SuperBuilder" } else { "@Builder" };
  1418. emit_method!(
  1419. "builder".to_string(),
  1420. class_name_node,
  1421. format!("static {class_name}.{class_name}Builder builder()"),
  1422. from,
  1423. Some(true),
  1424. Some(format!("{class_name}Builder"))
  1425. );
  1426. }
  1427. if has_to_string {
  1428. let from = if is_data { "@Data" } else if is_value { "@Value" } else { "@ToString" };
  1429. emit_method!("toString".to_string(), class_name_node, "String toString()".to_string(), from, None, None);
  1430. }
  1431. if has_equals {
  1432. let from = if is_data { "@Data" } else if is_value { "@Value" } else { "@EqualsAndHashCode" };
  1433. emit_method!("equals".to_string(), class_name_node, "boolean equals(Object o)".to_string(), from, None, None);
  1434. emit_method!("hashCode".to_string(), class_name_node, "int hashCode()".to_string(), from, None, None);
  1435. }
  1436. // Logger field (@Slf4j and friends).
  1437. if let Some(log_ann) = log_ann {
  1438. if !taken_fields.contains("log") {
  1439. self.create_node(
  1440. "field",
  1441. "log",
  1442. class_name_node,
  1443. Extra {
  1444. visibility: Some(2),
  1445. is_static: Some(true),
  1446. signature: Some("Logger log".to_string()),
  1447. docstring: Some(format!("Lombok-generated (@{log_ann})")),
  1448. decorators: Some(vec!["lombok".to_string()]),
  1449. ..Extra::default()
  1450. },
  1451. );
  1452. }
  1453. }
  1454. }
  1455. }
  1456. fn find_anonymous_class_body(node: Node) -> Option<Node> {
  1457. for i in 0..node.named_child_count() {
  1458. if let Some(child) = node.named_child(i) {
  1459. if matches!(child.kind(), "class_body" | "declaration_list") {
  1460. return Some(child);
  1461. }
  1462. }
  1463. }
  1464. None
  1465. }
  1466. /// The `new ns.Foo<T>()` name normalization shared by instantiation /
  1467. /// anonymous-class / decorator extraction: strip `<...` from the first `<`
  1468. /// (index > 0), keep the segment after the last `.`/`::`, strip ONE leading
  1469. /// `:` or `.`, trim.
  1470. fn strip_generic_and_qualifier(raw: &str) -> String {
  1471. let mut name = raw.to_string();
  1472. if let Some(lt) = name.find('<') {
  1473. if lt > 0 {
  1474. name.truncate(lt);
  1475. }
  1476. }
  1477. let last_dot = name
  1478. .rfind('.')
  1479. .map(|i| i as isize)
  1480. .unwrap_or(-1)
  1481. .max(name.rfind("::").map(|i| i as isize).unwrap_or(-1));
  1482. if last_dot >= 0 {
  1483. name = name[(last_dot as usize + 1)..].to_string();
  1484. if name.starts_with(':') || name.starts_with('.') {
  1485. name.remove(0);
  1486. }
  1487. }
  1488. name.trim().to_string()
  1489. }
  1490. fn capitalize(name: &str) -> String {
  1491. let mut chars = name.chars();
  1492. match chars.next() {
  1493. Some(c) => c.to_uppercase().collect::<String>() + chars.as_str(),
  1494. None => String::new(),
  1495. }
  1496. }
  1497. /// `\bword\b` matcher (modifier keyword tests in languages/java.ts).
  1498. fn word_re(word: &'static str) -> &'static Regex {
  1499. static STATIC_RE: OnceLock<Regex> = OnceLock::new();
  1500. static FINAL_RE: OnceLock<Regex> = OnceLock::new();
  1501. match word {
  1502. "static" => STATIC_RE.get_or_init(|| Regex::new(r"\bstatic\b").unwrap()),
  1503. "final" => FINAL_RE.get_or_init(|| Regex::new(r"\bfinal\b").unwrap()),
  1504. _ => unreachable!("word_re only supports static/final"),
  1505. }
  1506. }
  1507. fn opt_str(arena: &mut Arena, s: Option<&str>) -> StrRef {
  1508. match s {
  1509. Some(s) => arena.put(s),
  1510. None => NONE_STR,
  1511. }
  1512. }