dart.rs 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555
  1. //! Dart extraction — a faithful Rust port of the dart paths of
  2. //! `TreeSitterExtractor` (src/extraction/tree-sitter.ts) plus
  3. //! languages/dart.ts.
  4. //!
  5. //! Same porting contract as the other walkers: behavior parity, bug-for-bug.
  6. //! The authoritative quirk list is docs/design/dart-kernel-port-checklist.md.
  7. //! The center of gravity is THE SIBLING-BODY DOUBLE-WALK: dart attaches every
  8. //! function/method body as a NEXT SIBLING of its signature node, and the TS
  9. //! walkers consume the body TWICE — once via resolveBody (attributed to the
  10. //! function/method) and once via the enclosing generic walk (attributed to
  11. //! the file/class). The deterministic result — duplicate local-function
  12. //! nodes with the SAME id under different parents, duplicated
  13. //! calls/instantiates refs, file/class-attributed fn-ref twins — must be
  14. //! reproduced byte-for-byte in the observed interleave; a "helpful" dedupe
  15. //! breaks parity. Other load-bearing oddities preserved on purpose:
  16. //! callTypes is EMPTY (all call refs ride extractBareCall's selector
  17. //! walking in the body walker — cascades are invisible, `?.` encodes like
  18. //! `.`); `ConfigT.load()` double-emits (calls + a static-member references
  19. //! ref — no callee-of-call skip in the dart branch); operator methods mint
  20. //! `method "<anonymous>"`; the unnamed constructor is skipped
  21. //! (isMisparsedFunction) while named ctors/factories are named by the CTOR
  22. //! name with the class as returnType; instance fields mint NO nodes (only
  23. //! static_final_declaration → constant, via the hook); prefixed return
  24. //! types keep the PREFIX (`other.OtherClass f()` → returnType `other` —
  25. //! bug, preserved); enum `with` mixins emit nothing while enum `implements`
  26. //! works; deferred imports are invisible; named-argument callbacks are NOT
  27. //! fn-ref-captured; `async*`/`sync*` are NOT async. Positions in UTF-16
  28. //! code units. Files with parse errors defer to wasm (3.4–20.7% both-arm
  29. //! incidence — empty object patterns and unnamed `library;` dominate).
  30. use crate::buffers::{
  31. build_meta, edge_kind_index, node_kind_index, Arena, BoolFlags, EdgeRow, EmitOut, NodeRow,
  32. RefRow, StrRef, Tables, FLAG_IS_ASYNC, FLAG_IS_EXPORTED, FLAG_IS_STATIC, FUNCTION_REF_CODE,
  33. NONE, NONE_STR,
  34. };
  35. use crate::docstring::preceding_docstring;
  36. use crate::ids;
  37. use crate::textutil as util;
  38. use regex::Regex;
  39. use std::collections::{HashMap, HashSet};
  40. use std::sync::OnceLock;
  41. use tree_sitter::{Node, Parser};
  42. const MAX_VALUE_REF_NODES: usize = 20_000;
  43. /// NAME_STOPLIST (function-ref.ts).
  44. fn is_stoplisted(name: &str) -> bool {
  45. matches!(
  46. name,
  47. "this" | "self" | "super" | "null" | "nil" | "true" | "false" | "undefined" | "new"
  48. | "NULL" | "nullptr" | "None"
  49. )
  50. }
  51. /// BUILTIN_TYPES (tree-sitter.ts:5768-5782).
  52. fn is_builtin_type(name: &str) -> bool {
  53. matches!(
  54. name,
  55. "string" | "number" | "boolean" | "void" | "null" | "undefined" | "never" | "any"
  56. | "unknown" | "object" | "symbol" | "bigint" | "true" | "false"
  57. | "str" | "bool" | "i8" | "i16" | "i32" | "i64" | "i128" | "isize"
  58. | "u8" | "u16" | "u32" | "u64" | "u128" | "usize" | "f32" | "f64" | "char"
  59. | "int" | "long" | "short" | "byte" | "float" | "double"
  60. | "int8" | "int16" | "int32" | "int64" | "uint8" | "uint16" | "uint32" | "uint64"
  61. | "float32" | "float64" | "complex64" | "complex128" | "rune" | "error"
  62. | "Int" | "Long" | "Short" | "Byte" | "Float" | "Double" | "Boolean" | "Char"
  63. | "Unit" | "String" | "Any" | "AnyRef" | "AnyVal" | "Nothing" | "Null"
  64. )
  65. }
  66. /// extractDartReturnType's simple-name gate + the static-member receiver gate.
  67. fn simple_type_name_re() -> &'static Regex {
  68. static RE: OnceLock<Regex> = OnceLock::new();
  69. RE.get_or_init(|| Regex::new(r"^[A-Za-z_]\w*$").unwrap())
  70. }
  71. fn cap_ident_re() -> &'static Regex {
  72. static RE: OnceLock<Regex> = OnceLock::new();
  73. RE.get_or_init(|| Regex::new(r"^[A-Z][A-Za-z0-9_]*$").unwrap())
  74. }
  75. /// The chained-call re-encode gate (`/^[A-Z]/`).
  76. fn starts_upper_re() -> &'static Regex {
  77. static RE: OnceLock<Regex> = OnceLock::new();
  78. RE.get_or_init(|| Regex::new(r"^[A-Z]").unwrap())
  79. }
  80. /// extractDartReturnType's `<...>` strip (`/<[^>]*>/g`).
  81. fn angle_args_re() -> &'static Regex {
  82. static RE: OnceLock<Regex> = OnceLock::new();
  83. RE.get_or_init(|| Regex::new(r"<[^>]*>").unwrap())
  84. }
  85. struct Scope {
  86. row: u32,
  87. kind: &'static str,
  88. name: String,
  89. }
  90. struct Cand {
  91. from: u32,
  92. name: String,
  93. line: u32,
  94. column_byte: usize,
  95. row: usize,
  96. }
  97. struct ValueScope<'t> {
  98. row: u32,
  99. node: Node<'t>,
  100. name: String,
  101. }
  102. #[derive(Default)]
  103. struct Extra {
  104. docstring: Option<String>,
  105. signature: Option<String>,
  106. /// 0 = absent; 1 public, 2 private.
  107. visibility: u8,
  108. is_async: Option<bool>,
  109. is_static: Option<bool>,
  110. return_type: Option<String>,
  111. /// resolveBody-driven endLine extension (LIVE for dart sibling bodies).
  112. end_line_override: Option<u32>,
  113. }
  114. pub struct Walker<'t> {
  115. src: &'t str,
  116. file_path: &'t str,
  117. line_starts: Vec<usize>,
  118. arena: Arena,
  119. tables: Tables,
  120. stack: Vec<Scope>,
  121. node_ids: Vec<String>,
  122. defined_fn_names: HashSet<String>,
  123. imported_names: HashSet<String>,
  124. fn_ref_cands: Vec<Cand>,
  125. fs_values: HashMap<String, u32>,
  126. fs_value_counts: HashMap<String, u32>,
  127. value_scopes: Vec<ValueScope<'t>>,
  128. }
  129. pub fn extract(file_path: &str, source: &str) -> Result<EmitOut, String> {
  130. let grammar = crate::langs::grammar_for("dart").ok_or("no dart grammar")?;
  131. let t0 = std::time::Instant::now();
  132. let mut parser = Parser::new();
  133. parser
  134. .set_language(&grammar)
  135. .map_err(|e| format!("set_language(dart) failed: {e}"))?;
  136. let tree = parser
  137. .parse(source, None)
  138. .ok_or_else(|| "parser returned null tree".to_string())?;
  139. if tree.root_node().has_error() {
  140. return Err("defer: parse tree contains errors — wasm recovery is canonical".to_string());
  141. }
  142. let mut w = Walker {
  143. src: source,
  144. file_path,
  145. line_starts: util::line_starts(source),
  146. arena: Arena::default(),
  147. tables: Tables::default(),
  148. stack: Vec::new(),
  149. node_ids: Vec::new(),
  150. defined_fn_names: HashSet::new(),
  151. imported_names: HashSet::new(),
  152. fn_ref_cands: Vec::new(),
  153. fs_values: HashMap::new(),
  154. fs_value_counts: HashMap::new(),
  155. value_scopes: Vec::new(),
  156. };
  157. // File node (tree-sitter.ts:508-521).
  158. let line_count = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1;
  159. let base_name = file_path.rsplit(['/', '\\']).next().unwrap_or(file_path);
  160. let mut flags = BoolFlags::default();
  161. flags.set(FLAG_IS_EXPORTED, false);
  162. let file_id = w.arena.put(&ids::file_node_id(file_path));
  163. let name_ref = w.arena.put(base_name);
  164. let qn_ref = w.arena.put(file_path);
  165. w.tables.push_node(&NodeRow {
  166. kind: node_kind_index("file").unwrap(),
  167. visibility: 0,
  168. flags,
  169. start_line: 1,
  170. end_line: line_count,
  171. start_column: 0,
  172. end_column: 0,
  173. name: name_ref,
  174. qualified_name: qn_ref,
  175. id: file_id,
  176. docstring: NONE_STR,
  177. signature: NONE_STR,
  178. decorators: NONE_STR,
  179. type_parameters: NONE_STR,
  180. return_type: NONE_STR,
  181. extra_json: NONE_STR,
  182. });
  183. w.node_ids.push(ids::file_node_id(file_path));
  184. w.stack.push(Scope { row: 0, kind: "file", name: base_name.to_string() });
  185. w.visit(tree.root_node());
  186. w.flush_fn_ref_candidates();
  187. w.flush_value_refs(tree.root_node());
  188. w.stack.pop();
  189. let duration_ms = t0.elapsed().as_secs_f64() * 1000.0;
  190. let meta = build_meta(&w.tables, w.arena.len(), NONE_STR, duration_ms);
  191. Ok(EmitOut {
  192. meta,
  193. nodes: w.tables.nodes,
  194. edges: w.tables.edges,
  195. refs: w.tables.refs,
  196. arena: w.arena.into_vec(),
  197. })
  198. }
  199. impl<'t> Walker<'t> {
  200. fn text(&self, node: Node) -> &'t str {
  201. &self.src[node.byte_range()]
  202. }
  203. fn line_of(&self, node: Node) -> u32 {
  204. node.start_position().row as u32 + 1
  205. }
  206. fn col_of(&self, node: Node) -> u32 {
  207. util::col16(self.src, &self.line_starts, node.start_position().row, node.start_byte())
  208. }
  209. fn end_col_of(&self, node: Node) -> u32 {
  210. util::col16(self.src, &self.line_starts, node.end_position().row, node.end_byte())
  211. }
  212. fn top_row(&self) -> u32 {
  213. self.stack.last().map(|s| s.row).unwrap_or(0)
  214. }
  215. fn inside_class_like(&self) -> bool {
  216. self.stack
  217. .last()
  218. .map(|s| matches!(s.kind, "class" | "struct" | "interface" | "trait" | "enum" | "module"))
  219. .unwrap_or(false)
  220. }
  221. fn push_ref_at(&mut self, from_row: u32, name: &str, kind: &str, node: Node) {
  222. let name_ref = self.arena.put(name);
  223. self.tables.push_ref(&RefRow {
  224. from_idx: from_row,
  225. kind: edge_kind_index(kind).unwrap(),
  226. line: self.line_of(node),
  227. column: self.col_of(node),
  228. reference_name: name_ref,
  229. candidates: NONE_STR,
  230. from_id_str: NONE_STR,
  231. });
  232. // Dart import names are URIs (`package:x/y.dart`) — they match neither
  233. // SIMPLE_NAME nor QUALIFIED_IMPORT, so importedNames stays empty in
  234. // practice; ported for fidelity.
  235. if kind == "imports" {
  236. if util::simple_name().is_match(name) {
  237. self.imported_names.insert(name.to_string());
  238. } else if let Some(c) = util::qualified_import().captures(name) {
  239. self.imported_names.insert(c[1].to_string());
  240. }
  241. }
  242. }
  243. // --- createNode (tree-sitter.ts:1308) ---------------------------------
  244. fn create_node(&mut self, kind: &'static str, name: &str, node: Node<'t>, extra: Extra) -> Option<u32> {
  245. if name.is_empty() {
  246. return None;
  247. }
  248. let start_line = self.line_of(node);
  249. let id = ids::node_id(self.file_path, kind, name, start_line);
  250. let qualified = {
  251. let mut parts: Vec<&str> = Vec::new();
  252. for s in &self.stack {
  253. if s.kind != "file" {
  254. parts.push(&s.name);
  255. }
  256. }
  257. let mut qn = parts.join("::");
  258. if !qn.is_empty() {
  259. qn.push_str("::");
  260. }
  261. qn.push_str(name);
  262. qn
  263. };
  264. // endLine extension (:1322-1334) — LIVE for dart: a function/method
  265. // node's endLine extends to its sibling function_body's end.
  266. let mut end_line = node.end_position().row as u32 + 1;
  267. if let Some(ext) = extra.end_line_override {
  268. if ext > end_line {
  269. end_line = ext;
  270. }
  271. }
  272. let name_ref = self.arena.put(name);
  273. let qn_ref = self.arena.put(&qualified);
  274. let id_ref = self.arena.put(&id);
  275. let doc_ref = opt_str(&mut self.arena, extra.docstring.as_deref());
  276. let sig_ref = opt_str(&mut self.arena, extra.signature.as_deref());
  277. let ret_ref = opt_str(&mut self.arena, extra.return_type.as_deref());
  278. let mut flags = BoolFlags::default();
  279. if let Some(v) = extra.is_async {
  280. flags.set(FLAG_IS_ASYNC, v);
  281. }
  282. if let Some(v) = extra.is_static {
  283. flags.set(FLAG_IS_STATIC, v);
  284. }
  285. let row = self.tables.push_node(&NodeRow {
  286. kind: node_kind_index(kind).unwrap(),
  287. visibility: extra.visibility,
  288. flags,
  289. start_line,
  290. end_line,
  291. start_column: self.col_of(node),
  292. end_column: self.end_col_of(node),
  293. name: name_ref,
  294. qualified_name: qn_ref,
  295. id: id_ref,
  296. docstring: doc_ref,
  297. signature: sig_ref,
  298. decorators: NONE_STR,
  299. type_parameters: NONE_STR,
  300. return_type: ret_ref,
  301. extra_json: NONE_STR,
  302. });
  303. self.node_ids.push(id.clone());
  304. if kind == "function" || kind == "method" {
  305. self.defined_fn_names.insert(name.to_string());
  306. }
  307. let parent_row = self.top_row();
  308. self.tables.push_edge(&EdgeRow {
  309. source_idx: parent_row,
  310. target_idx: row,
  311. kind: edge_kind_index("contains").unwrap(),
  312. provenance: 0,
  313. line: NONE,
  314. column: NONE,
  315. metadata_json: NONE_STR,
  316. source_id_str: NONE_STR,
  317. target_id_str: NONE_STR,
  318. });
  319. // captureValueRefScope (:735-767). Dart mints only `constant` targets.
  320. if (kind == "constant" || kind == "variable")
  321. && util::utf16_len(name) >= 3
  322. && util::has_upper_or_underscore().is_match(name)
  323. {
  324. let parent_ok = self
  325. .stack
  326. .last()
  327. .map(|s| matches!(s.kind, "file" | "class" | "module" | "struct" | "enum"))
  328. .unwrap_or(false);
  329. if parent_ok {
  330. self.fs_values.insert(name.to_string(), row);
  331. *self.fs_value_counts.entry(name.to_string()).or_insert(0) += 1;
  332. }
  333. }
  334. if matches!(kind, "function" | "method" | "constant" | "variable") {
  335. self.value_scopes.push(ValueScope { row, node, name: name.to_string() });
  336. }
  337. Some(row)
  338. }
  339. // --- languages/dart.ts helper transcriptions --------------------------
  340. /// dartInnerSignature (dart.ts:9-17).
  341. fn inner_signature(&self, node: Node<'t>) -> Node<'t> {
  342. if node.kind() == "method_signature" {
  343. let mut cursor = node.walk();
  344. let inner = node.named_children(&mut cursor).find(|c| {
  345. matches!(c.kind(), "function_signature" | "getter_signature" | "setter_signature")
  346. });
  347. if let Some(inner) = inner {
  348. return inner;
  349. }
  350. }
  351. node
  352. }
  353. /// dartConstructorSignature (dart.ts:25-35).
  354. fn constructor_signature(&self, node: Node<'t>) -> Option<Node<'t>> {
  355. if matches!(node.kind(), "factory_constructor_signature" | "constructor_signature") {
  356. return Some(node);
  357. }
  358. if node.kind() == "method_signature" {
  359. let mut cursor = node.walk();
  360. return node.named_children(&mut cursor).find(|c| {
  361. matches!(c.kind(), "factory_constructor_signature" | "constructor_signature")
  362. });
  363. }
  364. None
  365. }
  366. /// dartEnclosingTypeName (dart.ts:38-50).
  367. fn enclosing_type_name(&self, node: Node<'t>) -> Option<&'t str> {
  368. let mut p = node.parent();
  369. while let Some(parent) = p {
  370. if matches!(
  371. parent.kind(),
  372. "class_definition" | "mixin_declaration" | "extension_declaration" | "enum_declaration"
  373. ) {
  374. return parent.child_by_field_name("name").map(|n| self.text(n));
  375. }
  376. p = parent.parent();
  377. }
  378. None
  379. }
  380. /// dartCtorInfo (dart.ts:61-70).
  381. fn ctor_info(&self, node: Node<'t>) -> Option<(String, String)> {
  382. let ctor = self.constructor_signature(node)?;
  383. let mut cursor = ctor.walk();
  384. let ids: Vec<Node<'t>> = ctor
  385. .named_children(&mut cursor)
  386. .filter(|c| c.kind() == "identifier")
  387. .collect();
  388. let class_name = self.enclosing_type_name(node)?;
  389. let first = ids.first()?;
  390. if self.text(*first) != class_name {
  391. return None; // misparsed method, not a ctor
  392. }
  393. let ctor_name = ids.get(1).map(|n| self.text(*n)).unwrap_or(class_name);
  394. Some((class_name.to_string(), ctor_name.to_string()))
  395. }
  396. /// extractDartReturnType (dart.ts:80-92).
  397. fn return_type_of(&self, node: Node<'t>) -> Option<String> {
  398. if let Some((class_name, _)) = self.ctor_info(node) {
  399. return Some(class_name);
  400. }
  401. let sig = self.inner_signature(node);
  402. let mut cursor = sig.walk();
  403. let ret = sig
  404. .named_children(&mut cursor)
  405. .find(|c| c.kind() == "type_identifier")?;
  406. let text = angle_args_re().replace_all(self.text(ret), "");
  407. let text = text.trim();
  408. let last = text.split('.').next_back()?;
  409. if last.is_empty() || !simple_type_name_re().is_match(last) {
  410. return None;
  411. }
  412. Some(last.to_string())
  413. }
  414. /// isMisparsedFunction (dart.ts:177-188) — skip the UNNAMED constructor.
  415. fn is_unnamed_ctor(&self, node: Node<'t>) -> bool {
  416. match self.ctor_info(node) {
  417. Some((class_name, ctor_name)) => ctor_name == class_name,
  418. None => false,
  419. }
  420. }
  421. /// getSignature (dart.ts:189-208).
  422. fn signature_of(&self, node: Node<'t>) -> Option<String> {
  423. let sig = self.inner_signature(node);
  424. let mut c1 = sig.walk();
  425. let params = sig
  426. .named_children(&mut c1)
  427. .find(|c| c.kind() == "formal_parameter_list");
  428. let mut c2 = sig.walk();
  429. let ret = sig
  430. .named_children(&mut c2)
  431. .find(|c| matches!(c.kind(), "type_identifier" | "void_type"));
  432. if params.is_none() && ret.is_none() {
  433. return None;
  434. }
  435. let mut result = String::new();
  436. if let Some(r) = ret {
  437. result.push_str(self.text(r));
  438. result.push(' ');
  439. }
  440. if let Some(p) = params {
  441. result.push_str(self.text(p));
  442. }
  443. let trimmed = result.trim();
  444. if trimmed.is_empty() {
  445. None
  446. } else {
  447. Some(trimmed.to_string())
  448. }
  449. }
  450. /// getVisibility (dart.ts:209-222) — `_` prefix = private; every
  451. /// constructor is public (the unwrap misses ctor signatures / the name
  452. /// FIELD is the class identifier).
  453. fn visibility_of(&self, node: Node<'t>) -> u8 {
  454. let name_node = if node.kind() == "method_signature" {
  455. let mut cursor = node.walk();
  456. let inner = node.named_children(&mut cursor).find(|c| {
  457. matches!(c.kind(), "function_signature" | "getter_signature" | "setter_signature")
  458. });
  459. inner.and_then(|i| {
  460. let mut ic = i.walk();
  461. let found = i.named_children(&mut ic).find(|c| c.kind() == "identifier");
  462. found
  463. })
  464. } else {
  465. node.child_by_field_name("name")
  466. };
  467. match name_node {
  468. Some(n) if self.text(n).starts_with('_') => 2,
  469. _ => 1,
  470. }
  471. }
  472. /// isAsync (dart.ts:223-233) — the `async` anon child of the SIBLING
  473. /// function_body; `async*`/`sync*` are different token types → false.
  474. fn is_async_of(&self, node: Node<'t>) -> bool {
  475. if let Some(next) = node.next_named_sibling() {
  476. if next.kind() == "function_body" {
  477. for i in 0..next.child_count() {
  478. if let Some(c) = next.child(i) {
  479. if c.kind() == "async" {
  480. return true;
  481. }
  482. }
  483. }
  484. }
  485. }
  486. false
  487. }
  488. /// isStatic (dart.ts:234-243).
  489. fn is_static_of(&self, node: Node<'t>) -> bool {
  490. if node.kind() == "method_signature" {
  491. for i in 0..node.child_count() {
  492. if let Some(c) = node.child(i) {
  493. if c.kind() == "static" {
  494. return true;
  495. }
  496. }
  497. }
  498. }
  499. false
  500. }
  501. /// resolveBody (dart.ts:158-171).
  502. fn resolve_body(&self, node: Node<'t>) -> Option<Node<'t>> {
  503. if matches!(node.kind(), "function_signature" | "method_signature") {
  504. let next = node.next_named_sibling()?;
  505. if next.kind() == "function_body" {
  506. return Some(next);
  507. }
  508. return None;
  509. }
  510. if let Some(standard) = node.child_by_field_name("body") {
  511. return Some(standard);
  512. }
  513. let mut cursor = node.walk();
  514. let found = node
  515. .named_children(&mut cursor)
  516. .find(|c| matches!(c.kind(), "class_body" | "extension_body"));
  517. found
  518. }
  519. /// extractName (tree-sitter.ts:90-192) — resolveName (ctor names) →
  520. /// name field → the method_signature inner unwrap → identifier-ish
  521. /// child → `<anonymous>` (operators land here).
  522. fn extract_name(&self, node: Node<'t>) -> String {
  523. // resolveName hook (dart.ts:244-260): named ctor/factory → ctor name.
  524. if let Some((class_name, ctor_name)) = self.ctor_info(node) {
  525. if ctor_name != class_name {
  526. return ctor_name;
  527. }
  528. }
  529. if let Some(name_node) = node.child_by_field_name("name") {
  530. return self.text(name_node).to_string();
  531. }
  532. if node.kind() == "method_signature" {
  533. let mut cursor = node.walk();
  534. let inner = node.named_children(&mut cursor).find(|c| {
  535. matches!(
  536. c.kind(),
  537. "function_signature" | "getter_signature" | "setter_signature"
  538. | "constructor_signature" | "factory_constructor_signature"
  539. )
  540. });
  541. if let Some(inner) = inner {
  542. let mut ic = inner.walk();
  543. let id = inner.named_children(&mut ic).find(|c| c.kind() == "identifier");
  544. if let Some(id) = id {
  545. return self.text(id).to_string();
  546. }
  547. }
  548. }
  549. let mut cursor = node.walk();
  550. for c in node.named_children(&mut cursor) {
  551. if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") {
  552. return self.text(c).to_string();
  553. }
  554. }
  555. "<anonymous>".to_string()
  556. }
  557. // --- the main walk (visitNode, tree-sitter.ts:936-1303) ---------------
  558. fn visit(&mut self, node: Node<'t>) {
  559. stack_guard!();
  560. // The visitNode hook (dart.ts:144-157) — the constants branch.
  561. if node.kind() == "static_final_declaration" {
  562. let mut cursor = node.walk();
  563. let name_node = node.named_children(&mut cursor).find(|c| c.kind() == "identifier");
  564. if let Some(name_node) = name_node {
  565. // signature = first value sibling's text, sliced to 100
  566. // UTF-16 units (a flattened chain captures just its head).
  567. let signature = name_node.next_named_sibling().map(|v| {
  568. let (sliced, _) = util::slice_utf16(self.text(v), 100);
  569. if util::utf16_len(&sliced) >= 100 {
  570. format!("= {sliced}...")
  571. } else {
  572. format!("= {sliced}")
  573. }
  574. });
  575. let name = self.text(name_node).to_string();
  576. self.create_node("constant", &name, node, Extra { signature, ..Default::default() });
  577. }
  578. self.scan_fn_ref_subtree(node, 0);
  579. return;
  580. }
  581. // maybeCaptureFnRefs (:990) — the double-walk fn-ref twin source.
  582. self.maybe_capture_fn_refs(node);
  583. match node.kind() {
  584. "function_signature" => {
  585. // functionTypes row — method_signature does NOT include it →
  586. // always extractFunction, even inside a class (abstract
  587. // members become kind `function` contained by the class).
  588. self.extract_function(node);
  589. return;
  590. }
  591. "class_definition" | "mixin_declaration" | "extension_declaration" => {
  592. self.extract_class(node);
  593. return;
  594. }
  595. "method_signature" | "constructor_signature" => {
  596. self.extract_method(node);
  597. return;
  598. }
  599. "enum_declaration" => {
  600. self.extract_enum(node);
  601. return;
  602. }
  603. "type_alias" => {
  604. let skip = self.extract_type_alias(node);
  605. if skip {
  606. return;
  607. }
  608. }
  609. "import_or_export" => {
  610. self.extract_import(node);
  611. return;
  612. }
  613. "new_expression" => {
  614. // INSTANTIATION_KINDS row — from the FILE/CLASS on the
  615. // sibling revisit (the double-walk's pass 2a).
  616. self.extract_instantiation(node);
  617. }
  618. _ => {}
  619. }
  620. let mut cursor = node.walk();
  621. let children: Vec<Node<'t>> = node.named_children(&mut cursor).collect();
  622. for child in children {
  623. self.visit(child);
  624. }
  625. }
  626. // --- extractFunction / extractMethod (:1517 / :1737) ------------------
  627. fn extract_function(&mut self, node: Node<'t>) {
  628. stack_guard!();
  629. // No receiver hook. Name first (resolveName inside extract_name).
  630. let name = self.extract_name(node);
  631. if name == "<anonymous>" {
  632. // :1549 — body-only walk (nothing pushed). Dart signatures always
  633. // name; preserved for fidelity.
  634. if let Some(body) = self.resolve_body(node) {
  635. self.visit_body(body);
  636. }
  637. return;
  638. }
  639. // isMisparsedFunction: the unnamed constructor is skipped — node
  640. // suppressed, body still walked (attributed to the current stack top).
  641. if self.is_unnamed_ctor(node) {
  642. if let Some(body) = self.resolve_body(node) {
  643. self.visit_body(body);
  644. }
  645. return;
  646. }
  647. let docstring = preceding_docstring(node, self.src);
  648. let signature = self.signature_of(node);
  649. let visibility = self.visibility_of(node);
  650. let is_async = self.is_async_of(node);
  651. let is_static = self.is_static_of(node);
  652. let return_type = self.return_type_of(node);
  653. let body = self.resolve_body(node);
  654. let end_line_override = body.map(|b| b.end_position().row as u32 + 1);
  655. let row = self.create_node(
  656. "function",
  657. &name,
  658. node,
  659. Extra {
  660. docstring,
  661. signature,
  662. visibility,
  663. is_async: Some(is_async),
  664. is_static: Some(is_static),
  665. return_type,
  666. end_line_override,
  667. },
  668. );
  669. let Some(row) = row else { return };
  670. self.extract_type_annotations(node, row);
  671. self.extract_decorators_for(node, row);
  672. self.stack.push(Scope { row, kind: "function", name });
  673. if let Some(body) = body {
  674. self.visit_body(body);
  675. }
  676. self.stack.pop();
  677. }
  678. fn extract_method(&mut self, node: Node<'t>) {
  679. // Gate (:1747): not inside class-like (no methodsAreTopLevel, no
  680. // receiver, parent never object/object_expression) → extractFunction.
  681. if !self.inside_class_like() {
  682. self.extract_function(node);
  683. return;
  684. }
  685. let name = self.extract_name(node);
  686. // isMisparsedFunction — the unnamed ctor: body-only walk.
  687. if self.is_unnamed_ctor(node) {
  688. if let Some(body) = self.resolve_body(node) {
  689. self.visit_body(body);
  690. }
  691. return;
  692. }
  693. let docstring = preceding_docstring(node, self.src);
  694. let signature = self.signature_of(node);
  695. let visibility = self.visibility_of(node);
  696. let is_async = self.is_async_of(node);
  697. let is_static = self.is_static_of(node);
  698. let return_type = self.return_type_of(node);
  699. let body = self.resolve_body(node);
  700. let end_line_override = body.map(|b| b.end_position().row as u32 + 1);
  701. // Operators mint method "<anonymous>" — extractMethod has NO skip.
  702. let row = self.create_node(
  703. "method",
  704. &name,
  705. node,
  706. Extra {
  707. docstring,
  708. signature,
  709. visibility,
  710. is_async: Some(is_async),
  711. is_static: Some(is_static),
  712. return_type,
  713. end_line_override,
  714. },
  715. );
  716. let Some(row) = row else { return };
  717. self.extract_type_annotations(node, row);
  718. self.extract_decorators_for(node, row);
  719. self.stack.push(Scope { row, kind: "method", name });
  720. if let Some(body) = body {
  721. self.visit_body(body);
  722. }
  723. self.stack.pop();
  724. }
  725. // --- extractClass (:1679) — classes, mixins, extensions ---------------
  726. fn extract_class(&mut self, node: Node<'t>) {
  727. stack_guard!();
  728. let resolved_body = self.resolve_body(node);
  729. // No skipBodilessClass. Anonymous `extension on String` → the name
  730. // fallback finds the ON type's type_identifier — a class named after
  731. // the extended type (preserved).
  732. let name = self.extract_name(node);
  733. let docstring = preceding_docstring(node, self.src);
  734. let visibility = self.visibility_of(node);
  735. let row = self.create_node(
  736. "class",
  737. &name,
  738. node,
  739. Extra { docstring, visibility, ..Default::default() },
  740. );
  741. let Some(row) = row else { return };
  742. self.extract_inheritance(node, row);
  743. // extractCsharpPrimaryCtorParamRefs — csharp-gated no-op.
  744. self.extract_decorators_for(node, row);
  745. self.stack.push(Scope { row, kind: "class", name });
  746. let body = resolved_body.unwrap_or(node);
  747. let mut cursor = body.walk();
  748. let children: Vec<Node<'t>> = body.named_children(&mut cursor).collect();
  749. for child in children {
  750. self.visit(child);
  751. }
  752. self.stack.pop();
  753. }
  754. // --- extractEnum (:1914) ----------------------------------------------
  755. fn extract_enum(&mut self, node: Node<'t>) {
  756. stack_guard!();
  757. let body = match self.resolve_body(node) {
  758. Some(b) => b,
  759. None => return,
  760. };
  761. let name = self.extract_name(node);
  762. let docstring = preceding_docstring(node, self.src);
  763. let visibility = self.visibility_of(node);
  764. let row = self.create_node(
  765. "enum",
  766. &name,
  767. node,
  768. Extra { docstring, visibility, ..Default::default() },
  769. );
  770. let Some(row) = row else { return };
  771. // Enum `with` mixins are a DIRECT child (no superclass wrapper) →
  772. // no clause matches; `interfaces` DOES → implements only.
  773. self.extract_inheritance(node, row);
  774. // No extractDecoratorsFor on the enum path.
  775. self.stack.push(Scope { row, kind: "enum", name });
  776. let mut cursor = body.walk();
  777. let children: Vec<Node<'t>> = body.named_children(&mut cursor).collect();
  778. for child in children {
  779. if child.kind() == "enum_constant" {
  780. self.extract_enum_members(child);
  781. } else {
  782. self.visit(child);
  783. }
  784. }
  785. self.stack.pop();
  786. }
  787. /// extractEnumMembers (:1958) — one enum_member per constant, positioned
  788. /// at the enum_constant node; ctor arguments never walked.
  789. fn extract_enum_members(&mut self, node: Node<'t>) {
  790. if let Some(name_node) = node.child_by_field_name("name") {
  791. let name = self.text(name_node).to_string();
  792. self.create_node("enum_member", &name, node, Extra::default());
  793. }
  794. }
  795. // --- extractTypeAlias (:2890, plain path) -----------------------------
  796. fn extract_type_alias(&mut self, node: Node<'t>) -> bool {
  797. let name = self.extract_name(node);
  798. if name == "<anonymous>" {
  799. return false;
  800. }
  801. let docstring = preceding_docstring(node, self.src);
  802. // `value` field is null (type_alias has no fields) → no refs from
  803. // the aliased type; returns false → children re-visited.
  804. self.create_node("type_alias", &name, node, Extra { docstring, ..Default::default() });
  805. false
  806. }
  807. // --- extractImport (:3170; hook dart.ts:261-304) ----------------------
  808. fn extract_import(&mut self, node: Node<'t>) {
  809. let find_child = |parent: Node<'t>, kind: &str| -> Option<Node<'t>> {
  810. let mut cursor = parent.walk();
  811. let found = parent.named_children(&mut cursor).find(|c| c.kind() == kind);
  812. found
  813. };
  814. let uri_of = |spec: Node<'t>| -> Option<Node<'t>> {
  815. let configurable = find_child(spec, "configurable_uri")?;
  816. let uri = find_child(configurable, "uri")?;
  817. find_child(uri, "string_literal")
  818. };
  819. let mut module: Option<String> = None;
  820. if let Some(li) = find_child(node, "library_import") {
  821. if let Some(spec) = find_child(li, "import_specification") {
  822. if let Some(sl) = uri_of(spec) {
  823. module = Some(self.text(sl).replace(['\'', '"'], ""));
  824. }
  825. }
  826. }
  827. if module.is_none() {
  828. if let Some(le) = find_child(node, "library_export") {
  829. if let Some(sl) = uri_of(le) {
  830. module = Some(self.text(sl).replace(['\'', '"'], ""));
  831. }
  832. }
  833. }
  834. // Deferred imports (bare `uri`, no configurable_uri) → hook null →
  835. // nothing at all (invisible).
  836. let Some(module) = module.filter(|m| !m.is_empty()) else { return };
  837. let signature = self.text(node).trim().to_string();
  838. let created = self.create_node(
  839. "import",
  840. &module,
  841. node,
  842. Extra { signature: Some(signature), ..Default::default() },
  843. );
  844. if created.is_some() && !self.stack.is_empty() {
  845. let parent_row = self.top_row();
  846. self.push_ref_at(parent_row, &module, "imports", node);
  847. }
  848. }
  849. // --- extractInstantiation (:4610, generic tail) -----------------------
  850. fn extract_instantiation(&mut self, node: Node<'t>) {
  851. if self.stack.is_empty() {
  852. return;
  853. }
  854. let from_row = self.top_row();
  855. let ctor = node
  856. .child_by_field_name("constructor")
  857. .or_else(|| node.child_by_field_name("type"))
  858. .or_else(|| node.child_by_field_name("name"))
  859. .or_else(|| node.named_child(0));
  860. let Some(ctor) = ctor else { return };
  861. let mut class_name = self.text(ctor).to_string();
  862. if let Some(lt) = class_name.find('<') {
  863. if lt > 0 {
  864. class_name.truncate(lt);
  865. }
  866. }
  867. let last_dot = class_name.rfind('.').map(|i| i as i64).unwrap_or(-1);
  868. let last_colons = class_name.rfind("::").map(|i| (i + 1) as i64).unwrap_or(-1);
  869. let last = last_dot.max(last_colons);
  870. if last >= 0 {
  871. class_name = class_name[(last as usize + 1)..].to_string();
  872. class_name = class_name.trim_start_matches([':', '.']).to_string();
  873. }
  874. let class_name = class_name.trim().to_string();
  875. if class_name.is_empty() {
  876. return;
  877. }
  878. self.push_ref_at(from_row, &class_name, "instantiates", node);
  879. }
  880. // --- extractBareCall (dart.ts:305-379) --------------------------------
  881. fn bare_call_name(&self, node: Node<'t>) -> Option<String> {
  882. if node.kind() == "selector" {
  883. let mut cursor = node.walk();
  884. let has_arg_part = node.named_children(&mut cursor).any(|c| c.kind() == "argument_part");
  885. if !has_arg_part {
  886. return None;
  887. }
  888. let prev = node.prev_named_sibling()?;
  889. if prev.kind() == "identifier" {
  890. return Some(self.text(prev).to_string());
  891. }
  892. if prev.kind() == "selector" {
  893. let mut pc = prev.walk();
  894. let accessor = prev.named_children(&mut pc).find(|c| {
  895. matches!(
  896. c.kind(),
  897. "unconditional_assignable_selector" | "conditional_assignable_selector"
  898. )
  899. });
  900. if let Some(accessor) = accessor {
  901. let mut ac = accessor.walk();
  902. let method_id = accessor.named_children(&mut ac).find(|c| c.kind() == "identifier");
  903. if let Some(method_id) = method_id {
  904. let accessor_prev = prev.prev_named_sibling();
  905. if let Some(ap) = accessor_prev {
  906. if ap.kind() == "identifier" {
  907. return Some(format!("{}.{}", self.text(ap), self.text(method_id)));
  908. }
  909. // Chained static-factory: the receiver is itself
  910. // a call — re-encode `<inner>().<method>` when
  911. // the chain starts capitalized (#750).
  912. if ap.kind() == "selector" {
  913. let mut apc = ap.walk();
  914. if ap.named_children(&mut apc).any(|c| c.kind() == "argument_part") {
  915. if let Some(inner) = self.callee_of_arg_part(ap) {
  916. if starts_upper_re().is_match(&inner) {
  917. return Some(format!("{}().{}", inner, self.text(method_id)));
  918. }
  919. }
  920. }
  921. }
  922. }
  923. return Some(self.text(method_id).to_string());
  924. }
  925. }
  926. }
  927. // super.method() / this.method(): prev is a bare accessor.
  928. if matches!(
  929. prev.kind(),
  930. "unconditional_assignable_selector" | "conditional_assignable_selector"
  931. ) {
  932. let mut pc = prev.walk();
  933. let id = prev.named_children(&mut pc).find(|c| c.kind() == "identifier");
  934. if let Some(id) = id {
  935. return Some(self.text(id).to_string());
  936. }
  937. }
  938. return None;
  939. }
  940. // new_expression arm — DEAD in practice (the INSTANTIATION branch
  941. // fires first in the body walker); ported for fidelity.
  942. if node.kind() == "new_expression" {
  943. let mut cursor = node.walk();
  944. let found = node
  945. .named_children(&mut cursor)
  946. .find(|c| c.kind() == "type_identifier")
  947. .map(|t| self.text(t).to_string());
  948. return found;
  949. }
  950. // const EdgeInsets.all(8.0) — const constructor call.
  951. if node.kind() == "const_object_expression" {
  952. let mut c1 = node.walk();
  953. let type_id = node.named_children(&mut c1).find(|c| c.kind() == "type_identifier");
  954. let mut c2 = node.walk();
  955. let name_id = node.named_children(&mut c2).find(|c| c.kind() == "identifier");
  956. return match (type_id, name_id) {
  957. (Some(t), Some(n)) => Some(format!("{}.{}", self.text(t), self.text(n))),
  958. (Some(t), None) => Some(self.text(t).to_string()),
  959. _ => None,
  960. };
  961. }
  962. None
  963. }
  964. /// dartCalleeOfArgPart (dart.ts:100-116).
  965. fn callee_of_arg_part(&self, arg_part: Node<'t>) -> Option<String> {
  966. let prev = arg_part.prev_named_sibling()?;
  967. if prev.kind() == "identifier" {
  968. return Some(self.text(prev).to_string());
  969. }
  970. if prev.kind() == "selector" {
  971. let mut pc = prev.walk();
  972. let accessor = prev.named_children(&mut pc).find(|c| {
  973. matches!(
  974. c.kind(),
  975. "unconditional_assignable_selector" | "conditional_assignable_selector"
  976. )
  977. });
  978. let method_id = accessor.and_then(|a| {
  979. let mut ac = a.walk();
  980. let found = a.named_children(&mut ac).find(|c| c.kind() == "identifier");
  981. found
  982. });
  983. if let Some(method_id) = method_id {
  984. let accessor_prev = prev.prev_named_sibling();
  985. if let Some(ap) = accessor_prev {
  986. if ap.kind() == "identifier" {
  987. return Some(format!("{}.{}", self.text(ap), self.text(method_id)));
  988. }
  989. }
  990. return Some(self.text(method_id).to_string());
  991. }
  992. }
  993. None
  994. }
  995. // --- extractStaticMemberRef — the dart branch (:4759-4767) ------------
  996. fn extract_static_member_ref(&mut self, node: Node<'t>) {
  997. if self.stack.is_empty() {
  998. return;
  999. }
  1000. let owner_row = self.top_row();
  1001. if node.kind() != "selector" {
  1002. return;
  1003. }
  1004. let mut cursor = node.walk();
  1005. if node.named_children(&mut cursor).any(|c| c.kind() == "argument_part") {
  1006. return;
  1007. }
  1008. let Some(prev) = node.prev_named_sibling() else { return };
  1009. if prev.kind() == "identifier" && cap_ident_re().is_match(self.text(prev)) {
  1010. let name = self.text(prev).to_string();
  1011. // NO callee-of-call skip — `ConfigT.load()` double-emits
  1012. // (references + calls). Position = the IDENTIFIER (receiver).
  1013. self.push_ref_at(owner_row, &name, "references", prev);
  1014. }
  1015. }
  1016. // --- extractDecoratorsFor (:4897-5024) — the sibling scan -------------
  1017. fn extract_decorators_for(&mut self, decl: Node<'t>, decorated_row: u32) {
  1018. // Scan 1: direct children (+ modifiers descent) — inert for dart
  1019. // (annotations are preceding siblings), ported for fidelity.
  1020. let mut cursor = decl.walk();
  1021. let kids: Vec<Node<'t>> = decl.named_children(&mut cursor).collect();
  1022. for child in kids {
  1023. self.consider_decorator(child, decorated_row);
  1024. if child.kind() == "modifiers" {
  1025. let mut mc = child.walk();
  1026. let inner: Vec<Node<'t>> = child.named_children(&mut mc).collect();
  1027. for m in inner {
  1028. self.consider_decorator(m, decorated_row);
  1029. }
  1030. }
  1031. }
  1032. // Scan 2: preceding siblings, backward, stop at the first
  1033. // non-annotation — stacked annotations emit in REVERSE source order.
  1034. if let Some(parent) = decl.parent() {
  1035. let decl_start = decl.start_byte();
  1036. let mut decl_idx: Option<usize> = None;
  1037. for i in 0..parent.named_child_count() {
  1038. if let Some(sib) = parent.named_child(i) {
  1039. if sib.start_byte() == decl_start {
  1040. decl_idx = Some(i);
  1041. break;
  1042. }
  1043. }
  1044. }
  1045. if let Some(di) = decl_idx {
  1046. for j in (0..di).rev() {
  1047. let Some(sib) = parent.named_child(j) else { continue };
  1048. if !matches!(sib.kind(), "decorator" | "annotation" | "marker_annotation") {
  1049. break;
  1050. }
  1051. self.consider_decorator(sib, decorated_row);
  1052. }
  1053. }
  1054. }
  1055. }
  1056. fn consider_decorator(&mut self, n: Node<'t>, decorated_row: u32) {
  1057. if !matches!(n.kind(), "decorator" | "annotation" | "marker_annotation" | "attribute") {
  1058. return;
  1059. }
  1060. let mut target: Option<Node<'t>> = None;
  1061. let mut cursor = n.walk();
  1062. let kids: Vec<Node<'t>> = n.named_children(&mut cursor).collect();
  1063. for child in kids {
  1064. if child.kind() == "call_expression" {
  1065. let fnn = child.child_by_field_name("function").or_else(|| child.named_child(0));
  1066. if let Some(f) = fnn {
  1067. target = Some(f);
  1068. }
  1069. if target.is_some() {
  1070. break;
  1071. }
  1072. }
  1073. if matches!(
  1074. child.kind(),
  1075. "identifier" | "member_expression" | "scoped_identifier" | "navigation_expression"
  1076. | "user_type" | "type_identifier"
  1077. ) {
  1078. target = Some(child);
  1079. break;
  1080. }
  1081. }
  1082. let Some(target) = target else { return };
  1083. let mut name = self.text(target).to_string();
  1084. if let Some(lt) = name.find('<') {
  1085. if lt > 0 {
  1086. name.truncate(lt);
  1087. }
  1088. }
  1089. let last_dot = name.rfind('.').map(|i| i as i64).unwrap_or(-1);
  1090. let last_colons = name.rfind("::").map(|i| (i + 1) as i64).unwrap_or(-1);
  1091. let last = last_dot.max(last_colons);
  1092. if last >= 0 {
  1093. name = name[(last as usize + 1)..].to_string();
  1094. name = name.trim_start_matches([':', '.']).to_string();
  1095. }
  1096. let name = name.trim().to_string();
  1097. if name.is_empty() {
  1098. return;
  1099. }
  1100. self.push_ref_at(decorated_row, &name, "decorates", n);
  1101. }
  1102. // --- extractInheritance — the dart rows (:5368-5393, :5437-5459) ------
  1103. fn extract_inheritance(&mut self, node: Node<'t>, class_row: u32) {
  1104. let mut cursor = node.walk();
  1105. let kids: Vec<Node<'t>> = node.named_children(&mut cursor).collect();
  1106. for child in kids {
  1107. if child.kind() == "superclass" {
  1108. // extends type + `with` mixins (implements) — dart branch.
  1109. let mut cc = child.walk();
  1110. let targets: Vec<Node<'t>> = child.named_children(&mut cc).collect();
  1111. for t in targets {
  1112. if t.kind() == "mixins" {
  1113. let mut mc = t.walk();
  1114. let mixins: Vec<Node<'t>> = t.named_children(&mut mc).collect();
  1115. for m in mixins {
  1116. if m.kind() == "type_identifier" {
  1117. let name = self.text(m).to_string();
  1118. self.push_ref_at(class_row, &name, "implements", m);
  1119. }
  1120. }
  1121. } else if t.kind() == "type_identifier" {
  1122. let name = self.text(t).to_string();
  1123. self.push_ref_at(class_row, &name, "extends", t);
  1124. }
  1125. }
  1126. } else if child.kind() == "interfaces" {
  1127. // implements — one per named child, FULL child text.
  1128. let mut cc = child.walk();
  1129. let targets: Vec<Node<'t>> = child.named_children(&mut cc).collect();
  1130. for iface in targets {
  1131. let name = self.text(iface).to_string();
  1132. self.push_ref_at(class_row, &name, "implements", iface);
  1133. }
  1134. }
  1135. }
  1136. }
  1137. // --- extractTypeAnnotations — the dart path (:5819-5833) --------------
  1138. fn extract_type_annotations(&mut self, node: Node<'t>, row: u32) {
  1139. let sig = if node.kind() == "method_signature" {
  1140. let mut cursor = node.walk();
  1141. let found = node.named_children(&mut cursor).find(|c| {
  1142. matches!(
  1143. c.kind(),
  1144. "function_signature" | "getter_signature" | "setter_signature"
  1145. | "constructor_signature" | "factory_constructor_signature"
  1146. )
  1147. });
  1148. found.unwrap_or(node) // operators fall back to the wrapper itself
  1149. } else {
  1150. node
  1151. };
  1152. self.type_refs_from_subtree(sig, row);
  1153. }
  1154. fn type_refs_from_subtree(&mut self, node: Node<'t>, from_row: u32) {
  1155. stack_guard!();
  1156. if node.kind() == "type_identifier" {
  1157. let name = self.text(node);
  1158. if !name.is_empty() && !is_builtin_type(name) {
  1159. let name = name.to_string();
  1160. self.push_ref_at(from_row, &name, "references", node);
  1161. }
  1162. return;
  1163. }
  1164. let mut cursor = node.walk();
  1165. let kids: Vec<Node<'t>> = node.named_children(&mut cursor).collect();
  1166. for c in kids {
  1167. self.type_refs_from_subtree(c, from_row);
  1168. }
  1169. }
  1170. // --- visitFunctionBody (:5129-5286) — dart rows -----------------------
  1171. fn visit_body(&mut self, node: Node<'t>) {
  1172. stack_guard!();
  1173. self.maybe_capture_fn_refs(node);
  1174. let kind = node.kind();
  1175. if kind == "new_expression" {
  1176. // INSTANTIATION branch fires first — extractBareCall's
  1177. // new_expression arm is dead. Children still recursed.
  1178. self.extract_instantiation(node);
  1179. } else if let Some(callee) = self.bare_call_name(node) {
  1180. // extractBareCall (:5159-5173) — ref at the MATCHED node.
  1181. if !self.stack.is_empty() {
  1182. let caller_row = self.top_row();
  1183. self.push_ref_at(caller_row, &callee, "calls", node);
  1184. }
  1185. }
  1186. self.extract_static_member_ref(node);
  1187. if kind == "function_signature" {
  1188. // Nested named functions (:5245) — extractFunction walks the
  1189. // nested body itself; the enclosing walker ALSO revisits the
  1190. // sibling function_body (double-walk pass 2b) via recursion.
  1191. self.extract_function(node);
  1192. return;
  1193. }
  1194. let mut cursor = node.walk();
  1195. let children: Vec<Node<'t>> = node.named_children(&mut cursor).collect();
  1196. for child in children {
  1197. self.visit_body(child);
  1198. }
  1199. }
  1200. // --- function-as-value capture (#756) — DART_SPEC ---------------------
  1201. fn maybe_capture_fn_refs(&mut self, node: Node<'t>) {
  1202. let (mode, field): (&str, &str) = match node.kind() {
  1203. "arguments" => ("args", ""),
  1204. "assignment_expression" => ("rhs", "right"),
  1205. "pair" => ("value", "value"),
  1206. "list_literal" => ("list", ""),
  1207. "static_final_declaration" => ("varinit", ""),
  1208. _ => return,
  1209. };
  1210. if self.stack.is_empty() {
  1211. return;
  1212. }
  1213. let from = self.top_row();
  1214. let mut values: Vec<Node<'t>> = Vec::new();
  1215. match mode {
  1216. "args" | "list" => {
  1217. let mut cursor = node.walk();
  1218. for c in node.named_children(&mut cursor) {
  1219. values.push(c);
  1220. }
  1221. }
  1222. "rhs" => {
  1223. if let Some(rhs) = node.child_by_field_name(field) {
  1224. let lhs = node
  1225. .child_by_field_name("left")
  1226. .or_else(|| node.child_by_field_name("lhs"))
  1227. .or_else(|| node.child_by_field_name("target"))
  1228. .or_else(|| {
  1229. if node.named_child_count() >= 2 {
  1230. node.named_child(0)
  1231. } else {
  1232. None
  1233. }
  1234. });
  1235. let lhs_text = lhs.map(|l| self.text(l)).unwrap_or("");
  1236. let lhs_last = util::lhs_last_name()
  1237. .captures(lhs_text)
  1238. .and_then(|c| c.get(1))
  1239. .map(|m| m.as_str());
  1240. if !(lhs_last.is_some() && lhs_last == Some(self.text(rhs).trim())) {
  1241. values.push(rhs);
  1242. }
  1243. }
  1244. }
  1245. "value" => {
  1246. let v = node.child_by_field_name(field).or_else(|| {
  1247. let count = node.named_child_count();
  1248. if count > 0 { node.named_child(count - 1) } else { None }
  1249. });
  1250. if let Some(v) = v {
  1251. values.push(v);
  1252. }
  1253. }
  1254. _ => {
  1255. // varinit, NO field (function-ref.ts:471-487): the last named
  1256. // child, requiring ≥2 named children; the name-field guard is
  1257. // inert (static_final_declaration has no name/pattern field).
  1258. let count = node.named_child_count();
  1259. if count >= 2 {
  1260. if let Some(v) = node.named_child(count - 1) {
  1261. values.push(v);
  1262. }
  1263. }
  1264. }
  1265. }
  1266. for v in values {
  1267. self.normalize_fn_ref_value(v, from, 0);
  1268. }
  1269. }
  1270. /// normalizeValue with DART_SPEC's one layer (`argument` → fan out).
  1271. /// Named arguments are NOT captured (named_argument is not a layer).
  1272. fn normalize_fn_ref_value(&mut self, v: Node<'t>, from: u32, depth: u32) {
  1273. stack_guard!();
  1274. if depth > 4 {
  1275. return;
  1276. }
  1277. match v.kind() {
  1278. "identifier" => {
  1279. let name = self.text(v).to_string();
  1280. if name.is_empty() || is_stoplisted(&name) {
  1281. return;
  1282. }
  1283. let p = v.start_position();
  1284. self.fn_ref_cands.push(Cand {
  1285. from,
  1286. name,
  1287. line: p.row as u32 + 1,
  1288. column_byte: v.start_byte(),
  1289. row: p.row,
  1290. });
  1291. }
  1292. "argument" => {
  1293. let mut cursor = v.walk();
  1294. let kids: Vec<Node<'t>> = v.named_children(&mut cursor).collect();
  1295. for c in kids {
  1296. self.normalize_fn_ref_value(c, from, depth + 1);
  1297. }
  1298. }
  1299. _ => {}
  1300. }
  1301. }
  1302. fn scan_fn_ref_subtree(&mut self, node: Node<'t>, depth: u32) {
  1303. stack_guard!();
  1304. if depth > 12 {
  1305. return;
  1306. }
  1307. // Halt list: functionTypes (function_signature) + the lambda kinds —
  1308. // function_expression IS dart's lambda, so constant-initializer
  1309. // lambdas don't leak candidates.
  1310. if depth > 0
  1311. && matches!(
  1312. node.kind(),
  1313. "function_signature" | "arrow_function" | "function_expression"
  1314. | "lambda_literal" | "lambda_expression"
  1315. )
  1316. {
  1317. return;
  1318. }
  1319. self.maybe_capture_fn_refs(node);
  1320. let mut cursor = node.walk();
  1321. let children: Vec<Node<'t>> = node.named_children(&mut cursor).collect();
  1322. for c in children {
  1323. self.scan_fn_ref_subtree(c, depth + 1);
  1324. }
  1325. }
  1326. fn flush_fn_ref_candidates(&mut self) {
  1327. let cands = std::mem::take(&mut self.fn_ref_cands);
  1328. if cands.is_empty() || util::is_generated_file(self.file_path) {
  1329. return;
  1330. }
  1331. let mut seen: HashSet<(String, String)> = HashSet::new();
  1332. for c in cands {
  1333. if !c.name.starts_with("this.")
  1334. && !c.name.contains("::")
  1335. && !self.defined_fn_names.contains(&c.name)
  1336. && !self.imported_names.contains(&c.name)
  1337. {
  1338. continue;
  1339. }
  1340. if !seen.insert((self.node_ids[c.from as usize].clone(), c.name.clone())) {
  1341. continue;
  1342. }
  1343. let column = util::col16(self.src, &self.line_starts, c.row, c.column_byte);
  1344. let name_ref = self.arena.put(&c.name);
  1345. self.tables.push_ref(&RefRow {
  1346. from_idx: c.from,
  1347. kind: FUNCTION_REF_CODE,
  1348. line: c.line,
  1349. column,
  1350. reference_name: name_ref,
  1351. candidates: NONE_STR,
  1352. from_id_str: NONE_STR,
  1353. });
  1354. }
  1355. }
  1356. // --- value-reference edges (:398-931) ---------------------------------
  1357. fn flush_value_refs(&mut self, root: Node<'t>) {
  1358. let scopes = std::mem::take(&mut self.value_scopes);
  1359. let mut targets = std::mem::take(&mut self.fs_values);
  1360. let counts = std::mem::take(&mut self.fs_value_counts);
  1361. if std::env::var("CODEGRAPH_VALUE_REFS").as_deref() == Ok("0") {
  1362. return;
  1363. }
  1364. if targets.is_empty() || scopes.is_empty() || util::is_generated_file(self.file_path) {
  1365. return;
  1366. }
  1367. // Shadow prune — the dart declarator shapes (:844-850): each bumps
  1368. // its first identifier-typed named child. Uninitialized locals bump;
  1369. // assignment_expression is NOT a prune case.
  1370. let mut decl_counts: HashMap<&str, u32> = HashMap::new();
  1371. let mut dstack: Vec<Node> = vec![root];
  1372. let mut dvisited = 0usize;
  1373. while let Some(n) = dstack.pop() {
  1374. if dvisited >= MAX_VALUE_REF_NODES {
  1375. break;
  1376. }
  1377. dvisited += 1;
  1378. if matches!(
  1379. n.kind(),
  1380. "static_final_declaration" | "initialized_identifier" | "initialized_variable_definition"
  1381. ) {
  1382. let mut cursor = n.walk();
  1383. let id = n.named_children(&mut cursor).find(|c| c.kind() == "identifier");
  1384. if let Some(id) = id {
  1385. let nm = self.text(id);
  1386. if targets.contains_key(nm) {
  1387. *decl_counts.entry(nm).or_insert(0) += 1;
  1388. }
  1389. }
  1390. }
  1391. for i in 0..n.named_child_count() {
  1392. if let Some(c) = n.named_child(i) {
  1393. dstack.push(c);
  1394. }
  1395. }
  1396. }
  1397. let shadowed: Vec<String> = decl_counts
  1398. .iter()
  1399. .filter(|(nm, c)| **c > counts.get(**nm).copied().unwrap_or(1))
  1400. .map(|(nm, _)| nm.to_string())
  1401. .collect();
  1402. for nm in shadowed {
  1403. targets.remove(&nm);
  1404. }
  1405. if targets.is_empty() {
  1406. return;
  1407. }
  1408. let refs_kind = edge_kind_index("references").unwrap();
  1409. for scope in &scopes {
  1410. let mut seen: HashSet<&str> = HashSet::new();
  1411. let mut stack: Vec<Node> = vec![scope.node];
  1412. // The Dart sibling-body pull (:883-892) is LIVE and load-bearing:
  1413. // reader scopes are SIGNATURE nodes; their reads live in the
  1414. // sibling function_body.
  1415. if let Some(sib) = scope.node.next_named_sibling() {
  1416. if matches!(sib.kind(), "function_body" | "block") {
  1417. stack.push(sib);
  1418. }
  1419. }
  1420. let mut visited = 0usize;
  1421. while let Some(n) = stack.pop() {
  1422. if visited >= MAX_VALUE_REF_NODES {
  1423. break;
  1424. }
  1425. visited += 1;
  1426. if matches!(n.kind(), "identifier" | "constant" | "name" | "simple_identifier") {
  1427. let ref_name = self.text(n);
  1428. if let Some(&target_row) = targets.get(ref_name) {
  1429. let target_id = self.node_ids[target_row as usize].as_str();
  1430. if target_id != self.node_ids[scope.row as usize]
  1431. && ref_name != scope.name
  1432. && !seen.contains(&target_id)
  1433. {
  1434. seen.insert(target_id);
  1435. let meta = self.arena.put(r#"{"valueRef":true}"#);
  1436. self.tables.push_edge(&EdgeRow {
  1437. source_idx: scope.row,
  1438. target_idx: target_row,
  1439. kind: refs_kind,
  1440. provenance: 0,
  1441. line: NONE,
  1442. column: NONE,
  1443. metadata_json: meta,
  1444. source_id_str: NONE_STR,
  1445. target_id_str: NONE_STR,
  1446. });
  1447. }
  1448. }
  1449. }
  1450. for i in 0..n.named_child_count() {
  1451. if let Some(c) = n.named_child(i) {
  1452. stack.push(c);
  1453. }
  1454. }
  1455. }
  1456. }
  1457. }
  1458. }
  1459. fn opt_str(arena: &mut Arena, s: Option<&str>) -> StrRef {
  1460. match s {
  1461. Some(s) => arena.put(s),
  1462. None => NONE_STR,
  1463. }
  1464. }