kotlin.rs 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588
  1. //! Kotlin extraction — a faithful Rust port of `TreeSitterExtractor`'s Kotlin
  2. //! paths (src/extraction/tree-sitter.ts) plus languages/kotlin.ts.
  3. //!
  4. //! Same porting contract as the other walkers: behavior parity, bug-for-bug.
  5. //! The authoritative quirk list is docs/design/kotlin-kernel-port-checklist.md.
  6. //! Two surfaces are FIRSTS for the kernel: extension-function receivers
  7. //! (getReceiverType → `Type::method` qualified-name OVERRIDE with no package
  8. //! prefix + the owner-contains fallback that excludes `interface` kinds and
  9. //! is source-order dependent) and extractModifiers (expect/actual platform
  10. //! modifiers → the node DECORATORS wire field, on every created node — the
  11. //! KMP synthesizer's input). Preserved on purpose: the FIELD_COUNT-0 dead
  12. //! cluster (no signatures, ZERO type-annotation refs), hook-consumed property
  13. //! initializers emitting nothing, the bodiless-class header re-walk asymmetry,
  14. //! enum-entry bodies being invisible, KDoc (`multiline_comment`) never being
  15. //! a docstring AND chain-breaking, comment-gluing into import/package extents,
  16. //! `@Anno(args)` emitting nothing while `@Anno` emits decorates, zero
  17. //! instantiates refs (constructors are capitalized `calls`), the qualified-
  18. //! receiver `com::qext` bug, the paren-then-lambda `trailing()` garbage
  19. //! callee, and the packaged-file value-ref target drop (namespace parents are
  20. //! not accepted). The fun-interface misparse-recovery hook branches are
  21. //! DEFER-SHIELDED (every such file has_error → wasm) and are not ported.
  22. //! Positions in UTF-16 code units. Expected deferral 4.7–8.5% (both-arm,
  23. //! grammar-inherent — incl. phantom errors: trust the has_error FLAG).
  24. use crate::buffers::{
  25. build_meta, edge_kind_index, node_kind_index, Arena, BoolFlags, EdgeRow, EmitOut, NodeRow,
  26. RefRow, StrRef, Tables, FLAG_IS_ASYNC, FLAG_IS_EXPORTED, FLAG_IS_STATIC, FUNCTION_REF_CODE,
  27. NONE, NONE_STR,
  28. };
  29. use crate::docstring::preceding_docstring;
  30. use crate::ids;
  31. use crate::textutil as util;
  32. use regex::Regex;
  33. use std::collections::{HashMap, HashSet};
  34. use std::sync::OnceLock;
  35. use tree_sitter::{Node, Parser};
  36. const MAX_VALUE_REF_NODES: usize = 20_000;
  37. /// NAME_STOPLIST (function-ref.ts).
  38. fn is_stoplisted(name: &str) -> bool {
  39. matches!(
  40. name,
  41. "this" | "self" | "super" | "null" | "nil" | "true" | "false" | "undefined" | "new"
  42. | "NULL" | "nullptr" | "None"
  43. )
  44. }
  45. /// LITERAL_RECEIVER_TYPES (tree-sitter.ts:373) — full shared set.
  46. fn is_literal_receiver(kind: &str) -> bool {
  47. matches!(
  48. kind,
  49. "string" | "string_literal" | "interpreted_string_literal" | "raw_string_literal"
  50. | "template_string" | "concatenated_string" | "formatted_string" | "f_string"
  51. | "line_string_literal" | "string_content" | "heredoc_body"
  52. | "number" | "number_literal" | "integer" | "integer_literal" | "float"
  53. | "float_literal" | "int_literal" | "decimal_integer_literal" | "real_literal"
  54. | "char_literal" | "character_literal" | "rune_literal" | "regex" | "regex_literal"
  55. | "true" | "false" | "boolean_literal" | "bool_literal" | "none" | "null" | "nil"
  56. | "null_literal" | "undefined"
  57. | "list" | "list_literal" | "array" | "array_literal" | "array_creation_expression"
  58. | "dictionary" | "dict_literal" | "object" | "tuple" | "set"
  59. )
  60. }
  61. /// `/^[A-Za-z_]\w*$/` with JS's ASCII `\w` (getReturnType's ident test).
  62. fn ascii_ident_re() -> &'static Regex {
  63. static RE: OnceLock<Regex> = OnceLock::new();
  64. RE.get_or_init(|| Regex::new(r"^[A-Za-z_][0-9A-Za-z_]*$").unwrap())
  65. }
  66. /// extractStaticMemberRef's capitalized-receiver test.
  67. fn capitalized_re() -> &'static Regex {
  68. static RE: OnceLock<Regex> = OnceLock::new();
  69. RE.get_or_init(|| Regex::new(r"^[A-Z][A-Za-z0-9_]*$").unwrap())
  70. }
  71. /// JS `\s` for the #750 inner-callee strip.
  72. fn is_js_space(c: char) -> bool {
  73. matches!(
  74. c,
  75. '\t' | '\n' | '\x0B' | '\x0C' | '\r' | ' ' | '\u{00A0}' | '\u{1680}'
  76. | '\u{2000}'..='\u{200A}' | '\u{2028}' | '\u{2029}' | '\u{202F}' | '\u{205F}'
  77. | '\u{3000}' | '\u{FEFF}'
  78. )
  79. }
  80. fn strip_js_ws(s: &str) -> String {
  81. s.chars().filter(|c| !is_js_space(*c)).collect()
  82. }
  83. struct Scope {
  84. row: u32,
  85. kind: &'static str,
  86. name: String,
  87. }
  88. /// Per-node metadata for the extension-fn owner-contains lookup.
  89. struct NodeMeta {
  90. kind: &'static str,
  91. name: String,
  92. }
  93. #[derive(Default)]
  94. struct Extra {
  95. docstring: Option<String>,
  96. signature: Option<String>,
  97. visibility: Option<u8>,
  98. is_static: Option<bool>,
  99. is_async: Option<bool>,
  100. return_type: Option<String>,
  101. /// composeReceiverQualifiedName override (extension methods) — the id
  102. /// still hashes the bare NAME; only the qualifiedName column changes.
  103. qualified_override: Option<String>,
  104. }
  105. struct ValueScope<'t> {
  106. row: u32,
  107. node: Node<'t>,
  108. name: String,
  109. }
  110. struct Cand {
  111. from: u32,
  112. name: String,
  113. line: u32,
  114. column_byte: usize,
  115. row: usize,
  116. }
  117. pub struct Walker<'t> {
  118. src: &'t str,
  119. file_path: &'t str,
  120. line_starts: Vec<usize>,
  121. arena: Arena,
  122. tables: Tables,
  123. stack: Vec<Scope>,
  124. node_ids: Vec<String>,
  125. nodes_meta: Vec<NodeMeta>,
  126. defined_fn_names: HashSet<String>,
  127. imported_names: HashSet<String>,
  128. fn_ref_cands: Vec<Cand>,
  129. fs_values: HashMap<String, u32>,
  130. fs_value_counts: HashMap<String, u32>,
  131. value_scopes: Vec<ValueScope<'t>>,
  132. }
  133. pub fn extract(file_path: &str, source: &str) -> Result<EmitOut, String> {
  134. let grammar = crate::langs::grammar_for("kotlin").ok_or("no kotlin grammar")?;
  135. let t0 = std::time::Instant::now();
  136. let mut parser = Parser::new();
  137. parser
  138. .set_language(&grammar)
  139. .map_err(|e| format!("set_language(kotlin) failed: {e}"))?;
  140. let tree = parser
  141. .parse(source, None)
  142. .ok_or_else(|| "parser returned null tree".to_string())?;
  143. if tree.root_node().has_error() {
  144. // Includes the PHANTOM errors (complete CSTs with hasError set) and
  145. // every fun-interface misparse — trust the flag, wasm is canonical.
  146. return Err("defer: parse tree contains errors — wasm recovery is canonical".to_string());
  147. }
  148. let mut w = Walker {
  149. src: source,
  150. file_path,
  151. line_starts: util::line_starts(source),
  152. arena: Arena::default(),
  153. tables: Tables::default(),
  154. stack: Vec::new(),
  155. node_ids: Vec::new(),
  156. nodes_meta: Vec::new(),
  157. defined_fn_names: HashSet::new(),
  158. imported_names: HashSet::new(),
  159. fn_ref_cands: Vec::new(),
  160. fs_values: HashMap::new(),
  161. fs_value_counts: HashMap::new(),
  162. value_scopes: Vec::new(),
  163. };
  164. let line_count = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1;
  165. let base_name = file_path.rsplit(['/', '\\']).next().unwrap_or(file_path);
  166. let mut flags = BoolFlags::default();
  167. flags.set(FLAG_IS_EXPORTED, false);
  168. let file_id = w.arena.put(&ids::file_node_id(file_path));
  169. let name_ref = w.arena.put(base_name);
  170. let qn_ref = w.arena.put(file_path);
  171. w.tables.push_node(&NodeRow {
  172. kind: node_kind_index("file").unwrap(),
  173. visibility: 0,
  174. flags,
  175. start_line: 1,
  176. end_line: line_count,
  177. start_column: 0,
  178. end_column: 0,
  179. name: name_ref,
  180. qualified_name: qn_ref,
  181. id: file_id,
  182. docstring: NONE_STR,
  183. signature: NONE_STR,
  184. decorators: NONE_STR,
  185. type_parameters: NONE_STR,
  186. return_type: NONE_STR,
  187. extra_json: NONE_STR,
  188. });
  189. w.node_ids.push(ids::file_node_id(file_path));
  190. w.nodes_meta.push(NodeMeta { kind: "file", name: base_name.to_string() });
  191. w.stack.push(Scope { row: 0, kind: "file", name: base_name.to_string() });
  192. // extractFilePackage: the FIRST package_header among root's direct named
  193. // children → namespace node (comment-glued extents included), pushed for
  194. // the whole walk.
  195. let root = tree.root_node();
  196. let mut pkg_pushed = false;
  197. for i in 0..root.named_child_count() {
  198. let Some(child) = root.named_child(i) else { continue };
  199. if child.kind() != "package_header" {
  200. continue;
  201. }
  202. let id_node = (0..child.named_child_count())
  203. .filter_map(|j| child.named_child(j))
  204. .find(|c| c.kind() == "identifier");
  205. if let Some(id_node) = id_node {
  206. let pkg = w.text(id_node).trim().to_string();
  207. if !pkg.is_empty() {
  208. if let Some(row) = w.create_node("namespace", &pkg, child, Extra::default()) {
  209. w.stack.push(Scope { row, kind: "namespace", name: pkg });
  210. pkg_pushed = true;
  211. }
  212. }
  213. }
  214. break;
  215. }
  216. w.visit_node(root);
  217. w.flush_fn_ref_candidates();
  218. w.flush_value_refs(root);
  219. if pkg_pushed {
  220. w.stack.pop();
  221. }
  222. w.stack.pop();
  223. let duration_ms = t0.elapsed().as_secs_f64() * 1000.0;
  224. let meta = build_meta(&w.tables, w.arena.len(), NONE_STR, duration_ms);
  225. Ok(EmitOut {
  226. meta,
  227. nodes: w.tables.nodes,
  228. edges: w.tables.edges,
  229. refs: w.tables.refs,
  230. arena: w.arena.into_vec(),
  231. })
  232. }
  233. impl<'t> Walker<'t> {
  234. fn text(&self, node: Node) -> &'t str {
  235. &self.src[node.byte_range()]
  236. }
  237. fn line_of(&self, node: Node) -> u32 {
  238. node.start_position().row as u32 + 1
  239. }
  240. fn col_of(&self, node: Node) -> u32 {
  241. util::col16(self.src, &self.line_starts, node.start_position().row, node.start_byte())
  242. }
  243. fn end_col_of(&self, node: Node) -> u32 {
  244. util::col16(self.src, &self.line_starts, node.end_position().row, node.end_byte())
  245. }
  246. fn top_row(&self) -> u32 {
  247. self.stack.last().map(|s| s.row).unwrap_or(0)
  248. }
  249. fn inside_class_like(&self) -> bool {
  250. self.stack
  251. .last()
  252. .map(|s| matches!(s.kind, "class" | "struct" | "interface" | "trait" | "enum" | "module"))
  253. .unwrap_or(false)
  254. }
  255. fn push_ref(&mut self, from_row: u32, name: &str, kind_code: u8, line: u32, column: u32) {
  256. let name_ref = self.arena.put(name);
  257. self.tables.push_ref(&RefRow {
  258. from_idx: from_row,
  259. kind: kind_code,
  260. line,
  261. column,
  262. reference_name: name_ref,
  263. candidates: NONE_STR,
  264. from_id_str: NONE_STR,
  265. });
  266. if kind_code == edge_kind_index("imports").unwrap() {
  267. if util::simple_name().is_match(name) {
  268. self.imported_names.insert(name.to_string());
  269. } else if let Some(c) = util::qualified_import().captures(name) {
  270. self.imported_names.insert(c[1].to_string());
  271. }
  272. }
  273. }
  274. fn push_ref_at(&mut self, from_row: u32, name: &str, kind_code: u8, node: Node) {
  275. self.push_ref(from_row, name, kind_code, self.line_of(node), self.col_of(node));
  276. }
  277. /// resolveBody (kotlin.ts:219): first ERROR child whose child(0) is `{`
  278. /// (fun-interface parent body — unreachable post-defer, kept for
  279. /// contract), else first function_body | class_body | enum_class_body.
  280. fn resolve_body(&self, node: Node<'t>) -> Option<Node<'t>> {
  281. for i in 0..node.named_child_count() {
  282. let Some(child) = node.named_child(i) else { continue };
  283. if child.kind() == "ERROR" {
  284. if let Some(first) = child.child(0) {
  285. if first.kind() == "{" {
  286. return Some(child);
  287. }
  288. }
  289. }
  290. if matches!(child.kind(), "function_body" | "class_body" | "enum_class_body") {
  291. return Some(child);
  292. }
  293. }
  294. None
  295. }
  296. // --- createNode ------------------------------------------------------------
  297. fn create_node(&mut self, kind: &'static str, name: &str, node: Node<'t>, extra: Extra) -> Option<u32> {
  298. if name.is_empty() {
  299. return None;
  300. }
  301. let start_line = self.line_of(node);
  302. let id = ids::node_id(self.file_path, kind, name, start_line);
  303. // endLine extension via resolveBody — LIVE for kotlin function/method
  304. // kinds (in-range for this grammar, so practically a no-op — but the
  305. // hook is part of the contract).
  306. let mut end_line = node.end_position().row as u32 + 1;
  307. if kind == "function" || kind == "method" {
  308. if let Some(body) = self.resolve_body(node) {
  309. let be = body.end_position().row as u32 + 1;
  310. if be > end_line {
  311. end_line = be;
  312. }
  313. }
  314. }
  315. let qualified = match &extra.qualified_override {
  316. Some(qn) => qn.clone(),
  317. None => {
  318. let mut parts: Vec<&str> = Vec::new();
  319. for s in &self.stack {
  320. if s.kind != "file" {
  321. parts.push(&s.name);
  322. }
  323. }
  324. let mut qn = parts.join("::");
  325. if !qn.is_empty() {
  326. qn.push_str("::");
  327. }
  328. qn.push_str(name);
  329. qn
  330. }
  331. };
  332. let mut flags = BoolFlags::default();
  333. if let Some(v) = extra.is_async {
  334. flags.set(FLAG_IS_ASYNC, v);
  335. }
  336. if let Some(v) = extra.is_static {
  337. flags.set(FLAG_IS_STATIC, v);
  338. }
  339. // extractModifiers merge (tree-sitter.ts:1355) — runs for EVERY
  340. // created node: expect/actual platform modifiers → decorators.
  341. let mods = self.extract_modifiers(node);
  342. let dec_ref: StrRef = match &mods {
  343. Some(list) if !list.is_empty() => self.arena.put_list(list),
  344. _ => NONE_STR,
  345. };
  346. let name_ref = self.arena.put(name);
  347. let qn_ref = self.arena.put(&qualified);
  348. let id_ref = self.arena.put(&id);
  349. let doc_ref = opt_str(&mut self.arena, extra.docstring.as_deref());
  350. let sig_ref = opt_str(&mut self.arena, extra.signature.as_deref());
  351. let ret_ref = opt_str(&mut self.arena, extra.return_type.as_deref());
  352. let row = self.tables.push_node(&NodeRow {
  353. kind: node_kind_index(kind).unwrap(),
  354. visibility: extra.visibility.unwrap_or(0),
  355. flags,
  356. start_line,
  357. end_line,
  358. start_column: self.col_of(node),
  359. end_column: self.end_col_of(node),
  360. name: name_ref,
  361. qualified_name: qn_ref,
  362. id: id_ref,
  363. docstring: doc_ref,
  364. signature: sig_ref,
  365. decorators: dec_ref,
  366. type_parameters: NONE_STR,
  367. return_type: ret_ref,
  368. extra_json: NONE_STR,
  369. });
  370. self.node_ids.push(id);
  371. self.nodes_meta.push(NodeMeta { kind, name: name.to_string() });
  372. let parent_row = self.top_row();
  373. self.tables.push_edge(&EdgeRow {
  374. source_idx: parent_row,
  375. target_idx: row,
  376. kind: edge_kind_index("contains").unwrap(),
  377. provenance: 0,
  378. line: NONE,
  379. column: NONE,
  380. metadata_json: NONE_STR,
  381. source_id_str: NONE_STR,
  382. target_id_str: NONE_STR,
  383. });
  384. if kind == "function" || kind == "method" {
  385. self.defined_fn_names.insert(name.to_string());
  386. }
  387. // captureValueRefScope — namespace parents are NOT accepted, so
  388. // packaged files' top-level constants are never targets (quirk).
  389. let target_kind_ok = kind == "constant" || kind == "variable";
  390. if target_kind_ok
  391. && util::utf16_len(name) >= 3
  392. && util::has_upper_or_underscore().is_match(name)
  393. {
  394. let parent_ok = self
  395. .stack
  396. .last()
  397. .map(|s| matches!(s.kind, "file" | "class" | "module" | "struct" | "enum"))
  398. .unwrap_or(false);
  399. if parent_ok {
  400. self.fs_values.insert(name.to_string(), row);
  401. *self.fs_value_counts.entry(name.to_string()).or_insert(0) += 1;
  402. }
  403. }
  404. if matches!(kind, "function" | "method" | "constant" | "variable") {
  405. self.value_scopes.push(ValueScope { row, node, name: name.to_string() });
  406. }
  407. Some(row)
  408. }
  409. // --- hooks (languages/kotlin.ts) ----------------------------------------------
  410. /// extractName — the zero-field grammar means the nameField lookup always
  411. /// misses; names come from the shared fallback scan (first direct
  412. /// identifier-family child; backtick names keep their backticks).
  413. fn extract_name(&self, node: Node) -> String {
  414. if let Some(name_node) = node.child_by_field_name("simple_identifier") {
  415. // nameField is a TYPE name used as a FIELD name — never resolves
  416. // (mirrored for shape; the grammar has zero fields).
  417. return self.text(name_node).to_string();
  418. }
  419. for i in 0..node.named_child_count() {
  420. if let Some(c) = node.named_child(i) {
  421. if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") {
  422. return self.text(c).to_string();
  423. }
  424. }
  425. }
  426. "<anonymous>".to_string()
  427. }
  428. /// getVisibility: modifiers text includes public/private/protected/
  429. /// internal in that order; default PUBLIC. Text-includes semantics —
  430. /// annotation text inside modifiers can flip it (bug-for-bug).
  431. fn visibility_of(&self, node: Node) -> u8 {
  432. for i in 0..node.child_count() {
  433. let Some(child) = node.child(i) else { continue };
  434. if child.kind() == "modifiers" {
  435. let text = self.text(child);
  436. if text.contains("public") {
  437. return 1;
  438. }
  439. if text.contains("private") {
  440. return 2;
  441. }
  442. if text.contains("protected") {
  443. return 3;
  444. }
  445. if text.contains("internal") {
  446. return 4;
  447. }
  448. }
  449. }
  450. 1 // Kotlin defaults to public
  451. }
  452. /// isAsync: modifiers text includes 'suspend' (text-includes false
  453. /// positive on `@suspendMarker` annotations — preserve).
  454. fn is_async(&self, node: Node) -> bool {
  455. (0..node.child_count())
  456. .filter_map(|i| node.child(i))
  457. .any(|c| c.kind() == "modifiers" && self.text(c).contains("suspend"))
  458. }
  459. /// extractKotlinReturnType — positional: the first user_type/nullable_type
  460. /// AFTER function_value_parameters; function_body/type_constraints first →
  461. /// None; Unit/Nothing → None; `: T` generic params leak (preserve).
  462. fn return_type_of(&self, node: Node) -> Option<String> {
  463. let mut seen_params = false;
  464. for i in 0..node.named_child_count() {
  465. let Some(child) = node.named_child(i) else { continue };
  466. if child.kind() == "function_value_parameters" {
  467. seen_params = true;
  468. continue;
  469. }
  470. if !seen_params {
  471. continue;
  472. }
  473. if matches!(child.kind(), "function_body" | "type_constraints") {
  474. return None;
  475. }
  476. if matches!(child.kind(), "user_type" | "nullable_type") {
  477. let ut = if child.kind() == "nullable_type" {
  478. (0..child.named_child_count())
  479. .filter_map(|j| child.named_child(j))
  480. .find(|c| c.kind() == "user_type")
  481. .unwrap_or(child)
  482. } else {
  483. child
  484. };
  485. let type_id = (0..ut.named_child_count())
  486. .filter_map(|j| ut.named_child(j))
  487. .find(|c| c.kind() == "type_identifier");
  488. let name = self.text(type_id.unwrap_or(ut)).trim();
  489. if name.is_empty() || !ascii_ident_re().is_match(name) {
  490. return None;
  491. }
  492. if matches!(name, "Unit" | "Nothing") {
  493. return None;
  494. }
  495. return Some(name.to_string());
  496. }
  497. }
  498. None
  499. }
  500. /// getReceiverType — extension functions: the last user_type BEFORE a `.`
  501. /// child; its FIRST type_identifier's text (qualified receivers take the
  502. /// FIRST segment — the `com::qext` bug, preserve).
  503. fn receiver_type_of(&self, node: Node<'t>) -> Option<String> {
  504. let mut found_user_type: Option<Node> = None;
  505. for i in 0..node.child_count() {
  506. let Some(child) = node.child(i) else { continue };
  507. match child.kind() {
  508. "user_type" => found_user_type = Some(child),
  509. "." => {
  510. if let Some(ut) = found_user_type {
  511. let type_id = (0..ut.named_child_count())
  512. .filter_map(|j| ut.named_child(j))
  513. .find(|c| c.kind() == "type_identifier");
  514. return Some(self.text(type_id.unwrap_or(ut)).to_string());
  515. }
  516. }
  517. "simple_identifier" | "function_value_parameters" => break,
  518. _ => {}
  519. }
  520. }
  521. None
  522. }
  523. /// extractModifiers — expect/actual platform modifiers, matched by NODE
  524. /// TYPE (never text), in order. Runs inside create_node for every node.
  525. fn extract_modifiers(&self, node: Node) -> Option<Vec<String>> {
  526. let mut mods: Vec<String> = Vec::new();
  527. for i in 0..node.child_count() {
  528. let Some(child) = node.child(i) else { continue };
  529. if child.kind() != "modifiers" {
  530. continue;
  531. }
  532. for j in 0..child.child_count() {
  533. let Some(pm) = child.child(j) else { continue };
  534. if pm.kind() != "platform_modifier" {
  535. continue;
  536. }
  537. for k in 0..pm.child_count() {
  538. let Some(kw) = pm.child(k) else { continue };
  539. if matches!(kw.kind(), "expect" | "actual") {
  540. mods.push(kw.kind().to_string());
  541. }
  542. }
  543. }
  544. }
  545. if mods.is_empty() { None } else { Some(mods) }
  546. }
  547. // --- the visitNode hook (property branch ONLY — fun-interface recovery is
  548. // defer-shielded and not ported) ------------------------------------------------
  549. fn try_visit_hook(&mut self, node: Node<'t>) -> bool {
  550. if node.kind() != "property_declaration" {
  551. return false;
  552. }
  553. let var_decl = (0..node.named_child_count())
  554. .filter_map(|i| node.named_child(i))
  555. .find(|c| c.kind() == "variable_declaration");
  556. let name_node = var_decl.and_then(|vd| {
  557. (0..vd.named_child_count())
  558. .filter_map(|i| vd.named_child(i))
  559. .find(|c| c.kind() == "simple_identifier")
  560. });
  561. let Some(name_node) = name_node else { return false }; // destructuring → decline
  562. let name = self.text(name_node).to_string();
  563. if name.is_empty() {
  564. return false;
  565. }
  566. // Scope walk up the parent chain — first match wins.
  567. let mut scope: &str = "const";
  568. let mut p = node.parent();
  569. while let Some(pn) = p {
  570. match pn.kind() {
  571. "function_body" | "function_declaration" | "lambda_literal"
  572. | "anonymous_initializer" | "control_structure_body" | "getter" | "setter" => {
  573. scope = "local";
  574. break;
  575. }
  576. "companion_object" | "object_declaration" => {
  577. scope = "const";
  578. break;
  579. }
  580. "class_declaration" => {
  581. scope = "instance";
  582. break;
  583. }
  584. _ => {}
  585. }
  586. p = pn.parent();
  587. }
  588. if scope == "local" {
  589. return true; // a local — extract nothing, subtree still scanned
  590. }
  591. let binding = (0..node.named_child_count())
  592. .filter_map(|i| node.named_child(i))
  593. .find(|c| c.kind() == "binding_pattern_kind");
  594. let is_val = binding.map(|b| self.text(b) == "val").unwrap_or(false);
  595. let kind: &'static str = if scope == "instance" {
  596. "field"
  597. } else if is_val {
  598. "constant"
  599. } else {
  600. "variable"
  601. };
  602. // The `type`-field signature read is dead (zero fields) → signature
  603. // undefined; NO docstring/visibility/isStatic — the modifiers merge in
  604. // create_node still decorates expect/actual properties.
  605. self.create_node(kind, &name, node, Extra::default());
  606. true
  607. }
  608. // --- the dispatcher (visitNode, Kotlin-relevant branches) -----------------------
  609. fn visit_node(&mut self, node: Node<'t>) {
  610. stack_guard!();
  611. if self.try_visit_hook(node) {
  612. self.scan_fn_ref_subtree(node, 0);
  613. return;
  614. }
  615. let kind = node.kind();
  616. let mut skip_children = false;
  617. self.maybe_capture_fn_refs(node);
  618. if kind == "function_declaration" {
  619. if self.inside_class_like() {
  620. self.extract_method(node);
  621. } else {
  622. self.extract_function(node);
  623. }
  624. skip_children = true;
  625. } else if kind == "class_declaration" {
  626. // classifyClassNode: `interface`/`enum` keyword children.
  627. let mut classified = "class";
  628. for i in 0..node.child_count() {
  629. if let Some(c) = node.child(i) {
  630. if c.kind() == "interface" {
  631. classified = "interface";
  632. break;
  633. }
  634. if c.kind() == "enum" {
  635. classified = "enum";
  636. break;
  637. }
  638. }
  639. }
  640. match classified {
  641. "interface" => self.extract_interface(node),
  642. "enum" => self.extract_enum(node),
  643. _ => self.extract_class(node),
  644. }
  645. skip_children = true;
  646. } else if kind == "object_declaration" {
  647. // extraClassNodeTypes → extractClass → kind `class`.
  648. self.extract_class(node);
  649. skip_children = true;
  650. } else if kind == "type_alias" {
  651. skip_children = self.extract_type_alias(node);
  652. } else if kind == "property_declaration" {
  653. // Hook-declined destructuring: extractField/extractVariable both
  654. // find no matching children for kotlin — NOTHING minted, RHS
  655. // invisible; candidates-only scan.
  656. self.scan_fn_ref_subtree(node, 0);
  657. skip_children = true;
  658. } else if kind == "import_header" {
  659. self.extract_import(node);
  660. } else if kind == "call_expression" {
  661. self.extract_call(node);
  662. }
  663. // companion_object, anonymous_initializer, secondary_constructor,
  664. // getter/setter siblings, file_annotation, object_literal, if/when at
  665. // top level: no branch — recursed (calls attribute to the stack top).
  666. if !skip_children {
  667. for i in 0..node.named_child_count() {
  668. if let Some(c) = node.named_child(i) {
  669. self.visit_node(c);
  670. }
  671. }
  672. }
  673. }
  674. // --- visitFunctionBody ----------------------------------------------------------
  675. fn visit_function_body(&mut self, body: Node<'t>) {
  676. stack_guard!();
  677. self.visit_for_calls_and_structure(body);
  678. }
  679. fn visit_for_calls_and_structure(&mut self, node: Node<'t>) {
  680. stack_guard!();
  681. let kind = node.kind();
  682. self.maybe_capture_fn_refs(node);
  683. if kind == "call_expression" {
  684. self.extract_call(node);
  685. }
  686. // (INSTANTIATION_KINDS has no kotlin members; extractBareCall absent.)
  687. self.extract_static_member_ref(node);
  688. if kind == "function_declaration" {
  689. let name = self.extract_name(node);
  690. if name != "<anonymous>" {
  691. // extractFunction diverts receiver-bearing nested fns to
  692. // extractMethod itself.
  693. self.extract_function(node);
  694. return;
  695. }
  696. }
  697. if kind == "class_declaration" {
  698. let mut classified = "class";
  699. for i in 0..node.child_count() {
  700. if let Some(c) = node.child(i) {
  701. if c.kind() == "interface" {
  702. classified = "interface";
  703. break;
  704. }
  705. if c.kind() == "enum" {
  706. classified = "enum";
  707. break;
  708. }
  709. }
  710. }
  711. match classified {
  712. "interface" => self.extract_interface(node),
  713. "enum" => self.extract_enum(node),
  714. _ => self.extract_class(node),
  715. }
  716. return;
  717. }
  718. // object_declaration is NOT dispatched here — a body-local object's
  719. // `fun`s hit the function branch above and leak out as FUNCTIONS
  720. // under the enclosing fn; its properties mint nothing (quirk).
  721. for i in 0..node.named_child_count() {
  722. if let Some(c) = node.named_child(i) {
  723. self.visit_for_calls_and_structure(c);
  724. }
  725. }
  726. }
  727. // --- extractors ------------------------------------------------------------------
  728. fn extract_function(&mut self, node: Node<'t>) {
  729. stack_guard!();
  730. // getReceiverType short-circuit (1522) — extension fns at any scope.
  731. if self.receiver_type_of(node).is_some() {
  732. self.extract_method(node);
  733. return;
  734. }
  735. let name = self.extract_name(node);
  736. if name == "<anonymous>" {
  737. if let Some(body) = self.resolve_body(node) {
  738. self.visit_function_body(body);
  739. }
  740. return;
  741. }
  742. let extra = Extra {
  743. docstring: preceding_docstring(node, self.src),
  744. signature: None, // dead hook (zero fields)
  745. visibility: Some(self.visibility_of(node)),
  746. is_async: Some(self.is_async(node)),
  747. is_static: Some(false), // kotlin isStatic is always false
  748. return_type: self.return_type_of(node),
  749. ..Extra::default()
  750. };
  751. let Some(row) = self.create_node("function", &name, node, extra) else { return };
  752. // extractTypeAnnotations: the generic path's field lookups all miss
  753. // (zero fields) — kotlin emits ZERO type-annotation refs.
  754. self.extract_decorators_for(node, row);
  755. self.stack.push(Scope { row, kind: "function", name });
  756. if let Some(body) = self.resolve_body(node) {
  757. self.visit_function_body(body);
  758. }
  759. self.stack.pop();
  760. }
  761. fn extract_method(&mut self, node: Node<'t>) {
  762. stack_guard!();
  763. let receiver = self.receiver_type_of(node);
  764. let name = self.extract_name(node);
  765. let qualified_override = receiver.as_ref().map(|r| format!("{r}::{name}"));
  766. let extra = Extra {
  767. docstring: preceding_docstring(node, self.src),
  768. signature: None,
  769. visibility: Some(self.visibility_of(node)),
  770. is_async: Some(self.is_async(node)),
  771. is_static: Some(false),
  772. return_type: self.return_type_of(node),
  773. qualified_override,
  774. };
  775. let Some(row) = self.create_node("method", &name, node, extra) else { return };
  776. // Owner-contains fallback (1799): receiver present, not class-like →
  777. // the FIRST same-file node named like the receiver with kind ∈
  778. // {struct, class, enum, trait} (interface EXCLUDED; source-order
  779. // dependent — both quirks preserved). Additive to the normal edge.
  780. if let Some(recv) = &receiver {
  781. if !self.inside_class_like() {
  782. let owner = self
  783. .nodes_meta
  784. .iter()
  785. .position(|m| {
  786. m.name == *recv && matches!(m.kind, "struct" | "class" | "enum" | "trait")
  787. })
  788. .map(|i| i as u32);
  789. if let Some(owner_row) = owner {
  790. self.tables.push_edge(&EdgeRow {
  791. source_idx: owner_row,
  792. target_idx: row,
  793. kind: edge_kind_index("contains").unwrap(),
  794. provenance: 0,
  795. line: NONE,
  796. column: NONE,
  797. metadata_json: NONE_STR,
  798. source_id_str: NONE_STR,
  799. target_id_str: NONE_STR,
  800. });
  801. }
  802. }
  803. }
  804. // Type annotations: dead. Decorators: live.
  805. self.extract_decorators_for(node, row);
  806. self.stack.push(Scope { row, kind: "method", name });
  807. if let Some(body) = self.resolve_body(node) {
  808. self.visit_function_body(body);
  809. }
  810. self.stack.pop();
  811. }
  812. fn extract_class(&mut self, node: Node<'t>) {
  813. stack_guard!();
  814. let resolved_body = self.resolve_body(node);
  815. let name = self.extract_name(node);
  816. let extra = Extra {
  817. docstring: preceding_docstring(node, self.src),
  818. visibility: Some(self.visibility_of(node)),
  819. ..Extra::default()
  820. };
  821. let Some(row) = self.create_node("class", &name, node, extra) else { return };
  822. self.extract_inheritance(node, row);
  823. // primaryCtor refs: csharp-gated no-op.
  824. self.extract_decorators_for(node, row);
  825. self.stack.push(Scope { row, kind: "class", name });
  826. // Bodied: ONLY class_body children (primary-ctor properties/defaults
  827. // invisible). Bodiless: the class node itself → header children
  828. // visited → ctor default-value + super-arg calls attribute to the
  829. // CLASS (the asymmetry, pinned).
  830. let body = resolved_body.unwrap_or(node);
  831. for i in 0..body.named_child_count() {
  832. if let Some(c) = body.named_child(i) {
  833. self.visit_node(c);
  834. }
  835. }
  836. self.stack.pop();
  837. }
  838. fn extract_interface(&mut self, node: Node<'t>) {
  839. stack_guard!();
  840. let name = self.extract_name(node);
  841. let extra = Extra {
  842. docstring: preceding_docstring(node, self.src),
  843. ..Extra::default() // NO visibility
  844. };
  845. let Some(row) = self.create_node("interface", &name, node, extra) else { return };
  846. self.extract_inheritance(node, row);
  847. self.stack.push(Scope { row, kind: "interface", name });
  848. let body = self.resolve_body(node).unwrap_or(node);
  849. for i in 0..body.named_child_count() {
  850. if let Some(c) = body.named_child(i) {
  851. self.visit_node(c);
  852. }
  853. }
  854. self.stack.pop();
  855. }
  856. fn extract_enum(&mut self, node: Node<'t>) {
  857. stack_guard!();
  858. let Some(body) = self.resolve_body(node) else { return };
  859. let name = self.extract_name(node);
  860. let extra = Extra {
  861. docstring: preceding_docstring(node, self.src),
  862. visibility: Some(self.visibility_of(node)),
  863. ..Extra::default()
  864. };
  865. let Some(row) = self.create_node("enum", &name, node, extra) else { return };
  866. self.extract_inheritance(node, row);
  867. self.stack.push(Scope { row, kind: "enum", name });
  868. for i in 0..body.named_child_count() {
  869. let Some(child) = body.named_child(i) else { continue };
  870. if child.kind() == "enum_entry" {
  871. self.extract_enum_members(child);
  872. } else {
  873. self.visit_node(child);
  874. }
  875. }
  876. self.stack.pop();
  877. }
  878. fn extract_enum_members(&mut self, node: Node<'t>) {
  879. // name field → null (zero fields) → the identifier-children scan: one
  880. // enum_member per direct simple_identifier, positioned AT the
  881. // identifier. Entry value_arguments and entry class_bodies (override
  882. // methods!) are never visited — invisible (quirk).
  883. for i in 0..node.named_child_count() {
  884. let Some(child) = node.named_child(i) else { continue };
  885. if matches!(child.kind(), "simple_identifier" | "identifier" | "property_identifier") {
  886. let name = self.text(child).to_string();
  887. self.create_node("enum_member", &name, child, Extra::default());
  888. }
  889. }
  890. }
  891. /// extractTypeAlias — plain node; the alias-value ref walk reads the
  892. /// `value` FIELD → null (zero fields) → NO refs. Returns false →
  893. /// children re-visited (harmless).
  894. fn extract_type_alias(&mut self, node: Node<'t>) -> bool {
  895. let name = self.extract_name(node);
  896. if name == "<anonymous>" {
  897. return false;
  898. }
  899. let extra = Extra {
  900. docstring: preceding_docstring(node, self.src),
  901. ..Extra::default()
  902. };
  903. self.create_node("type_alias", &name, node, extra);
  904. false
  905. }
  906. fn extract_import(&mut self, node: Node<'t>) {
  907. // Comment-gluing: the header's extent (and thus the signature) can
  908. // include trailing comment lines — the trimmed FULL text is the
  909. // signature; the ref stays at the header start.
  910. let import_text = self.text(node).trim().to_string();
  911. let identifier = (0..node.named_child_count())
  912. .filter_map(|i| node.named_child(i))
  913. .find(|c| c.kind() == "identifier");
  914. let Some(identifier) = identifier else { return };
  915. let module_name = self.text(identifier).to_string();
  916. if module_name.is_empty() {
  917. return;
  918. }
  919. self.create_node(
  920. "import",
  921. &module_name,
  922. node,
  923. Extra { signature: Some(import_text), ..Extra::default() },
  924. );
  925. let parent = self.top_row();
  926. self.push_ref_at(parent, &module_name.clone(), edge_kind_index("imports").unwrap(), node);
  927. }
  928. /// extractCall — the kotlin paths: navigation member branch (+ the #750
  929. /// re-encode) and the raw-text else (paren-then-lambda / glued-invoke
  930. /// garbage preserved).
  931. fn extract_call(&mut self, node: Node<'t>) {
  932. if self.stack.is_empty() {
  933. return;
  934. }
  935. let caller = self.top_row();
  936. let func = node
  937. .child_by_field_name("function")
  938. .or_else(|| node.named_child(0));
  939. let Some(func) = func else { return };
  940. let mut callee_name = String::new();
  941. if func.kind() == "navigation_expression" {
  942. let property = func
  943. .child_by_field_name("property")
  944. .or_else(|| func.child_by_field_name("field"))
  945. .or_else(|| {
  946. let c1 = func.named_child(1);
  947. match c1 {
  948. Some(c) if c.kind() == "navigation_suffix" => (0..c.named_child_count())
  949. .filter_map(|i| c.named_child(i))
  950. .find(|g| g.kind() == "simple_identifier")
  951. .or(Some(c)),
  952. other => other,
  953. }
  954. });
  955. if let Some(property) = property {
  956. let method_name = self.text(property);
  957. let receiver = func
  958. .child_by_field_name("object")
  959. .or_else(|| func.child_by_field_name("operand"))
  960. .or_else(|| func.child_by_field_name("argument"))
  961. .or_else(|| func.named_child(0));
  962. if let Some(r) = receiver {
  963. if is_literal_receiver(r.kind()) {
  964. return; // `"literal".uppercase()` / `5.toString()`
  965. }
  966. }
  967. let recv_ident = receiver.filter(|r| {
  968. matches!(r.kind(), "identifier" | "simple_identifier" | "field_identifier")
  969. });
  970. if let Some(r) = recv_ident {
  971. let receiver_name = self.text(r);
  972. if matches!(receiver_name, "self" | "this" | "cls" | "super") {
  973. callee_name = method_name.to_string();
  974. } else {
  975. callee_name = format!("{receiver_name}.{method_name}");
  976. }
  977. } else if receiver.map(|r| r.kind() == "call_expression").unwrap_or(false) {
  978. // #750 kotlin re-encode: innerNav = receiver.namedChild(0)
  979. // (NOT a function field), ws-stripped, /^[A-Z]/ gate.
  980. let inner = receiver.unwrap().named_child(0);
  981. let inner_callee =
  982. inner.map(|n| strip_js_ws(self.text(n))).unwrap_or_default();
  983. let reencode = inner_callee
  984. .as_bytes()
  985. .first()
  986. .map(|b| b.is_ascii_uppercase())
  987. .unwrap_or(false);
  988. callee_name = if reencode {
  989. format!("{inner_callee}().{method_name}")
  990. } else {
  991. method_name.to_string()
  992. };
  993. } else {
  994. // this_expression / super_expression / 2-hop nav /
  995. // postfix `!!` / parenthesized → bare method name.
  996. callee_name = method_name.to_string();
  997. }
  998. }
  999. } else {
  1000. // Raw func text: bare `helper`, constructor `WidgetK` (NO
  1001. // instantiates ever), backticked names verbatim, the
  1002. // paren-then-lambda `trailing()` and glued-invoke chains
  1003. // byte-for-byte.
  1004. callee_name = self.text(func).to_string();
  1005. }
  1006. if !callee_name.is_empty() {
  1007. if let Some(c) = util::paren_conversion().captures(&callee_name) {
  1008. callee_name = c[1].to_string();
  1009. }
  1010. self.push_ref_at(caller, &callee_name.clone(), edge_kind_index("calls").unwrap(), node);
  1011. }
  1012. }
  1013. /// extractStaticMemberRef — navigation_expression value reads, body
  1014. /// walker only (assignment WRITES parse as directly_assignable_expression
  1015. /// — not a member-access kind — and emit nothing).
  1016. fn extract_static_member_ref(&mut self, node: Node<'t>) {
  1017. if node.kind() != "navigation_expression" {
  1018. return;
  1019. }
  1020. if self.stack.is_empty() {
  1021. return;
  1022. }
  1023. let owner = self.top_row();
  1024. if let Some(parent) = node.parent() {
  1025. if parent.kind() == "call_expression" {
  1026. let callee = parent
  1027. .child_by_field_name("function")
  1028. .or_else(|| parent.child_by_field_name("method"))
  1029. .or_else(|| parent.named_child(0));
  1030. if let Some(callee) = callee {
  1031. if callee.start_byte() == node.start_byte() {
  1032. return;
  1033. }
  1034. }
  1035. }
  1036. }
  1037. let recv = node
  1038. .child_by_field_name("object")
  1039. .or_else(|| node.child_by_field_name("expression"))
  1040. .or_else(|| node.child_by_field_name("scope"))
  1041. .or_else(|| node.named_child(0));
  1042. let Some(recv) = recv else { return };
  1043. if matches!(
  1044. recv.kind(),
  1045. "identifier" | "type_identifier" | "simple_identifier" | "name" | "scoped_type_identifier"
  1046. ) {
  1047. let text = self.text(recv);
  1048. if capitalized_re().is_match(text) {
  1049. self.push_ref_at(owner, &text.to_string(), edge_kind_index("references").unwrap(), recv);
  1050. }
  1051. }
  1052. }
  1053. /// extractInheritance — delegation_specifier: user_type ?? its
  1054. /// constructor_invocation's user_type → FIRST type_identifier → ONE
  1055. /// `extends` ref at the typeId (interfaces ride extends too; qualified
  1056. /// supertypes take the FIRST segment — `com`; `by`-delegation emits
  1057. /// NOTHING).
  1058. fn extract_inheritance(&mut self, node: Node<'t>, class_row: u32) {
  1059. let extends_kind = edge_kind_index("extends").unwrap();
  1060. for i in 0..node.named_child_count() {
  1061. let Some(child) = node.named_child(i) else { continue };
  1062. if child.kind() != "delegation_specifier" {
  1063. continue;
  1064. }
  1065. let user_type = (0..child.named_child_count())
  1066. .filter_map(|j| child.named_child(j))
  1067. .find(|c| c.kind() == "user_type");
  1068. let ctor_inv = (0..child.named_child_count())
  1069. .filter_map(|j| child.named_child(j))
  1070. .find(|c| c.kind() == "constructor_invocation");
  1071. let target = user_type.or(ctor_inv);
  1072. let Some(target) = target else { continue };
  1073. let type_id: Node = if target.kind() == "user_type" {
  1074. (0..target.named_child_count())
  1075. .filter_map(|j| target.named_child(j))
  1076. .find(|c| c.kind() == "type_identifier")
  1077. .unwrap_or(target)
  1078. } else {
  1079. // constructor_invocation → its user_type → first type_identifier
  1080. let ut = (0..target.named_child_count())
  1081. .filter_map(|j| target.named_child(j))
  1082. .find(|c| c.kind() == "user_type");
  1083. match ut {
  1084. Some(ut) => (0..ut.named_child_count())
  1085. .filter_map(|j| ut.named_child(j))
  1086. .find(|c| c.kind() == "type_identifier")
  1087. .unwrap_or(ut),
  1088. None => target,
  1089. }
  1090. };
  1091. let name = self.text(type_id).to_string();
  1092. self.push_ref_at(class_row, &name, extends_kind, type_id);
  1093. }
  1094. }
  1095. /// extractDecoratorsFor — kotlin annotations inside `modifiers`:
  1096. /// `@Marker` (user_type child) → decorates ref; `@Anno(args)`
  1097. /// (constructor_invocation) → NOTHING. Runs for functions/methods/classes
  1098. /// only (hook properties never call it).
  1099. fn extract_decorators_for(&mut self, decl: Node<'t>, decorated_row: u32) {
  1100. for i in 0..decl.named_child_count() {
  1101. let Some(child) = decl.named_child(i) else { continue };
  1102. self.consider_decorator(child, decorated_row);
  1103. if child.kind() == "modifiers" {
  1104. for j in 0..child.named_child_count() {
  1105. if let Some(m) = child.named_child(j) {
  1106. self.consider_decorator(m, decorated_row);
  1107. }
  1108. }
  1109. }
  1110. }
  1111. let Some(parent) = decl.parent() else { return };
  1112. let decl_start = decl.start_byte();
  1113. let mut decl_idx: isize = -1;
  1114. for i in 0..parent.named_child_count() {
  1115. if let Some(sib) = parent.named_child(i) {
  1116. if sib.start_byte() == decl_start {
  1117. decl_idx = i as isize;
  1118. break;
  1119. }
  1120. }
  1121. }
  1122. if decl_idx > 0 {
  1123. let mut j = decl_idx - 1;
  1124. while j >= 0 {
  1125. let Some(sib) = parent.named_child(j as usize) else {
  1126. j -= 1;
  1127. continue;
  1128. };
  1129. if !matches!(sib.kind(), "decorator" | "annotation" | "marker_annotation") {
  1130. break;
  1131. }
  1132. self.consider_decorator(sib, decorated_row);
  1133. j -= 1;
  1134. }
  1135. }
  1136. }
  1137. fn consider_decorator(&mut self, n: Node<'t>, decorated_row: u32) {
  1138. if !matches!(n.kind(), "decorator" | "annotation" | "marker_annotation" | "attribute") {
  1139. return;
  1140. }
  1141. let mut target: Option<Node> = None;
  1142. for i in 0..n.named_child_count() {
  1143. let Some(child) = n.named_child(i) else { continue };
  1144. if child.kind() == "call_expression" {
  1145. target = child.child_by_field_name("function").or_else(|| child.named_child(0));
  1146. if target.is_some() {
  1147. break;
  1148. }
  1149. }
  1150. if matches!(
  1151. child.kind(),
  1152. "identifier" | "member_expression" | "scoped_identifier" | "navigation_expression"
  1153. | "user_type" | "type_identifier"
  1154. ) {
  1155. target = Some(child);
  1156. break;
  1157. }
  1158. }
  1159. let Some(target) = target else { return };
  1160. let name = strip_generic_and_qualifier(self.text(target));
  1161. if name.is_empty() {
  1162. return;
  1163. }
  1164. self.push_ref_at(decorated_row, &name, edge_kind_index("decorates").unwrap(), n);
  1165. }
  1166. // --- function-as-value refs (KOTLIN_SPEC, function-ref.ts:240) ------------------
  1167. fn maybe_capture_fn_refs(&mut self, node: Node<'t>) {
  1168. enum Mode {
  1169. Args,
  1170. Rhs,
  1171. }
  1172. let mode = match node.kind() {
  1173. "value_arguments" => Mode::Args,
  1174. "assignment" => Mode::Rhs, // NO field — RHS = LAST named child
  1175. _ => return,
  1176. };
  1177. if self.stack.is_empty() {
  1178. return;
  1179. }
  1180. let from = self.top_row();
  1181. let mut values: Vec<Node> = Vec::new();
  1182. match mode {
  1183. Mode::Args => {
  1184. for i in 0..node.named_child_count() {
  1185. if let Some(c) = node.named_child(i) {
  1186. values.push(c);
  1187. }
  1188. }
  1189. }
  1190. Mode::Rhs => {
  1191. let rhs = if node.named_child_count() > 0 {
  1192. node.named_child(node.named_child_count() - 1)
  1193. } else {
  1194. None
  1195. };
  1196. if let Some(rhs) = rhs {
  1197. let lhs = node
  1198. .child_by_field_name("left")
  1199. .or_else(|| node.child_by_field_name("lhs"))
  1200. .or_else(|| node.child_by_field_name("target"))
  1201. .or_else(|| {
  1202. if node.named_child_count() >= 2 { node.named_child(0) } else { None }
  1203. });
  1204. let lhs_text = lhs.map(|l| self.text(l)).unwrap_or("");
  1205. let lhs_last = util::lhs_last_name()
  1206. .captures(lhs_text)
  1207. .and_then(|c| c.get(1))
  1208. .map(|m| m.as_str());
  1209. let rhs_text = self.text(rhs).trim();
  1210. if !(lhs_last.is_some() && lhs_last == Some(rhs_text)) {
  1211. values.push(rhs);
  1212. }
  1213. }
  1214. }
  1215. }
  1216. for v in values {
  1217. self.normalize_fn_ref_value(v, from, 0);
  1218. }
  1219. }
  1220. fn normalize_fn_ref_value(&mut self, v: Node<'t>, from: u32, depth: u32) {
  1221. stack_guard!();
  1222. if depth > 4 {
  1223. return;
  1224. }
  1225. match v.kind() {
  1226. // value_argument layer with NO field resolution (zero fields) —
  1227. // the label-forward skip is DEAD for kotlin; fan out namedChildren.
  1228. "value_argument" => {
  1229. for i in 0..v.named_child_count() {
  1230. if let Some(c) = v.named_child(i) {
  1231. self.normalize_fn_ref_value(c, from, depth + 1);
  1232. }
  1233. }
  1234. }
  1235. // `::topLevel` / `OtherClass::handle` — receiver = LAST
  1236. // type_identifier child, member = LAST simple_identifier child;
  1237. // `String::class` has no member (anon keyword) → nothing;
  1238. // lowercase receivers dropped by the CASE regex, not node type.
  1239. "callable_reference" => {
  1240. let mut receiver: Option<Node> = None;
  1241. let mut member: Option<Node> = None;
  1242. for i in 0..v.named_child_count() {
  1243. let Some(child) = v.named_child(i) else { continue };
  1244. if child.kind() == "type_identifier" {
  1245. receiver = Some(child);
  1246. }
  1247. if child.kind() == "simple_identifier" {
  1248. member = Some(child);
  1249. }
  1250. }
  1251. let Some(member) = member else { return };
  1252. let m = self.text(member);
  1253. match receiver {
  1254. None => self.push_fn_ref_cand(from, m, member),
  1255. Some(recv) => {
  1256. let recv_text = self.text(recv);
  1257. if recv_text.as_bytes().first().map(|b| b.is_ascii_uppercase()).unwrap_or(false) {
  1258. let name = format!("{recv_text}::{m}");
  1259. self.push_fn_ref_cand(from, &name, member);
  1260. }
  1261. }
  1262. }
  1263. }
  1264. // `this::caller` → this.<member> (class-scoped, always flushes).
  1265. "navigation_expression" => {
  1266. if !self.text(v).starts_with("this::") {
  1267. return;
  1268. }
  1269. for i in 0..v.named_child_count() {
  1270. let Some(child) = v.named_child(i) else { continue };
  1271. if child.kind() == "navigation_suffix" && self.text(child).starts_with("::") {
  1272. if child.named_child_count() > 0 {
  1273. if let Some(id) = child.named_child(child.named_child_count() - 1) {
  1274. let name = format!("this.{}", self.text(id));
  1275. self.push_fn_ref_cand(from, &name, id);
  1276. }
  1277. }
  1278. return;
  1279. }
  1280. }
  1281. }
  1282. _ => {}
  1283. }
  1284. }
  1285. fn push_fn_ref_cand(&mut self, from: u32, name: &str, node: Node) {
  1286. if name.is_empty() || is_stoplisted(name) {
  1287. return;
  1288. }
  1289. let p = node.start_position();
  1290. self.fn_ref_cands.push(Cand {
  1291. from,
  1292. name: name.to_string(),
  1293. line: p.row as u32 + 1,
  1294. column_byte: node.start_byte(),
  1295. row: p.row,
  1296. });
  1297. }
  1298. fn scan_fn_ref_subtree(&mut self, node: Node<'t>, depth: u32) {
  1299. stack_guard!();
  1300. if depth > 12 {
  1301. return;
  1302. }
  1303. // Halts at functionTypes (function_declaration) + the fixed list —
  1304. // lambda_literal halts (no captures inside `by lazy { }` under a
  1305. // hook-consumed property).
  1306. if depth > 0
  1307. && matches!(
  1308. node.kind(),
  1309. "function_declaration" | "arrow_function" | "function_expression" | "lambda_literal"
  1310. | "lambda_expression"
  1311. )
  1312. {
  1313. return;
  1314. }
  1315. self.maybe_capture_fn_refs(node);
  1316. for i in 0..node.named_child_count() {
  1317. if let Some(c) = node.named_child(i) {
  1318. self.scan_fn_ref_subtree(c, depth + 1);
  1319. }
  1320. }
  1321. }
  1322. fn flush_fn_ref_candidates(&mut self) {
  1323. let cands = std::mem::take(&mut self.fn_ref_cands);
  1324. if cands.is_empty() || util::is_generated_file(self.file_path) {
  1325. return;
  1326. }
  1327. let mut seen: HashSet<(String, String)> = HashSet::new();
  1328. for c in cands {
  1329. if !c.name.starts_with("this.")
  1330. && !c.name.contains("::")
  1331. && !self.defined_fn_names.contains(&c.name)
  1332. && !self.imported_names.contains(&c.name)
  1333. {
  1334. continue;
  1335. }
  1336. if !seen.insert((self.node_ids[c.from as usize].clone(), c.name.clone())) {
  1337. continue;
  1338. }
  1339. let column = util::col16(self.src, &self.line_starts, c.row, c.column_byte);
  1340. let name_ref = self.arena.put(&c.name);
  1341. self.tables.push_ref(&RefRow {
  1342. from_idx: c.from,
  1343. kind: FUNCTION_REF_CODE,
  1344. line: c.line,
  1345. column,
  1346. reference_name: name_ref,
  1347. candidates: NONE_STR,
  1348. from_id_str: NONE_STR,
  1349. });
  1350. }
  1351. }
  1352. // --- value references --------------------------------------------------------------
  1353. fn flush_value_refs(&mut self, root: Node<'t>) {
  1354. let scopes = std::mem::take(&mut self.value_scopes);
  1355. let mut targets = std::mem::take(&mut self.fs_values);
  1356. let counts = std::mem::take(&mut self.fs_value_counts);
  1357. if std::env::var("CODEGRAPH_VALUE_REFS").as_deref() == Ok("0") {
  1358. return;
  1359. }
  1360. if targets.is_empty() || scopes.is_empty() || util::is_generated_file(self.file_path) {
  1361. return;
  1362. }
  1363. // Shadow prune — kotlin cases: property_declaration (its
  1364. // variable_declaration's first simple_identifier; destructuring bumps
  1365. // nothing) AND the shared `assignment` case (the swift-sweep lesson —
  1366. // directly_assignable_expression children bump).
  1367. let mut decl_counts: HashMap<&str, u32> = HashMap::new();
  1368. let mut dstack: Vec<Node> = vec![root];
  1369. let mut dvisited = 0usize;
  1370. while let Some(n) = dstack.pop() {
  1371. if dvisited >= MAX_VALUE_REF_NODES {
  1372. break;
  1373. }
  1374. dvisited += 1;
  1375. if n.kind() == "assignment" {
  1376. let left = n
  1377. .child_by_field_name("left")
  1378. .or_else(|| n.child_by_field_name("pattern"))
  1379. .or_else(|| n.named_child(0));
  1380. if let Some(left) = left {
  1381. if left.kind() == "identifier" {
  1382. let nm = self.text(left);
  1383. if targets.contains_key(nm) {
  1384. *decl_counts.entry(nm).or_insert(0) += 1;
  1385. }
  1386. } else {
  1387. for i in 0..left.named_child_count() {
  1388. let Some(c) = left.named_child(i) else { continue };
  1389. if matches!(c.kind(), "identifier" | "simple_identifier") {
  1390. let nm = self.text(c);
  1391. if targets.contains_key(nm) {
  1392. *decl_counts.entry(nm).or_insert(0) += 1;
  1393. }
  1394. }
  1395. }
  1396. }
  1397. }
  1398. }
  1399. if n.kind() == "property_declaration" {
  1400. let vd = (0..n.named_child_count())
  1401. .filter_map(|i| n.named_child(i))
  1402. .find(|c| c.kind() == "variable_declaration");
  1403. if let Some(vd) = vd {
  1404. let id = (0..vd.named_child_count())
  1405. .filter_map(|i| vd.named_child(i))
  1406. .find(|c| c.kind() == "simple_identifier");
  1407. if let Some(id) = id {
  1408. let nm = self.text(id);
  1409. if targets.contains_key(nm) {
  1410. *decl_counts.entry(nm).or_insert(0) += 1;
  1411. }
  1412. }
  1413. }
  1414. // (the Swift name-field half of the shared case is a null
  1415. // path for kotlin — variable_declaration always present)
  1416. }
  1417. for i in 0..n.named_child_count() {
  1418. if let Some(c) = n.named_child(i) {
  1419. dstack.push(c);
  1420. }
  1421. }
  1422. }
  1423. let shadowed: Vec<String> = decl_counts
  1424. .iter()
  1425. .filter(|(nm, c)| **c > counts.get(**nm).copied().unwrap_or(1))
  1426. .map(|(nm, _)| nm.to_string())
  1427. .collect();
  1428. for nm in shadowed {
  1429. targets.remove(&nm);
  1430. }
  1431. if targets.is_empty() {
  1432. return;
  1433. }
  1434. let refs_kind = edge_kind_index("references").unwrap();
  1435. for scope in &scopes {
  1436. let mut seen: HashSet<&str> = HashSet::new();
  1437. let mut stack: Vec<Node> = vec![scope.node];
  1438. let mut visited = 0usize;
  1439. while let Some(n) = stack.pop() {
  1440. if visited >= MAX_VALUE_REF_NODES {
  1441. break;
  1442. }
  1443. visited += 1;
  1444. // simple_identifier is kotlin's live reader kind —
  1445. // `${TARGET}` interpolations read, `$TARGET`
  1446. // (interpolated_identifier) doesn't.
  1447. if matches!(n.kind(), "identifier" | "constant" | "name" | "simple_identifier") {
  1448. let ref_name = self.text(n);
  1449. if let Some(&target_row) = targets.get(ref_name) {
  1450. let target_id = self.node_ids[target_row as usize].as_str();
  1451. if target_id != self.node_ids[scope.row as usize]
  1452. && ref_name != scope.name
  1453. && !seen.contains(&target_id)
  1454. {
  1455. seen.insert(target_id);
  1456. let meta = self.arena.put(r#"{"valueRef":true}"#);
  1457. self.tables.push_edge(&EdgeRow {
  1458. source_idx: scope.row,
  1459. target_idx: target_row,
  1460. kind: refs_kind,
  1461. provenance: 0,
  1462. line: NONE,
  1463. column: NONE,
  1464. metadata_json: meta,
  1465. source_id_str: NONE_STR,
  1466. target_id_str: NONE_STR,
  1467. });
  1468. }
  1469. }
  1470. }
  1471. for i in 0..n.named_child_count() {
  1472. if let Some(c) = n.named_child(i) {
  1473. stack.push(c);
  1474. }
  1475. }
  1476. }
  1477. }
  1478. }
  1479. }
  1480. /// The shared decorator-name normalization.
  1481. fn strip_generic_and_qualifier(raw: &str) -> String {
  1482. let mut name = raw.to_string();
  1483. if let Some(lt) = name.find('<') {
  1484. if lt > 0 {
  1485. name.truncate(lt);
  1486. }
  1487. }
  1488. let last_dot = name
  1489. .rfind('.')
  1490. .map(|i| i as isize)
  1491. .unwrap_or(-1)
  1492. .max(name.rfind("::").map(|i| i as isize).unwrap_or(-1));
  1493. if last_dot >= 0 {
  1494. name = name[(last_dot as usize + 1)..].to_string();
  1495. if name.starts_with(':') || name.starts_with('.') {
  1496. name.remove(0);
  1497. }
  1498. }
  1499. name.trim().to_string()
  1500. }
  1501. fn opt_str(arena: &mut Arena, s: Option<&str>) -> StrRef {
  1502. match s {
  1503. Some(s) => arena.put(s),
  1504. None => NONE_STR,
  1505. }
  1506. }