csharp.rs 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610
  1. //! C# extraction — a faithful Rust port of `TreeSitterExtractor`'s C# paths
  2. //! (src/extraction/tree-sitter.ts) plus languages/csharp.ts.
  3. //!
  4. //! Same porting contract as the other walkers: behavior parity with the wasm
  5. //! path, bug-for-bug, verified by scripts/kernel-parity.mjs and the full-index
  6. //! dump-diff gate. The authoritative quirk list is
  7. //! docs/design/csharp-kernel-port-checklist.md — including every deliberate
  8. //! emission hole (property/accessor bodies, constructor initializers,
  9. //! delegates/events/operators/indexers, top-level locals) and garbage ref
  10. //! (`(repo)` primary-ctor extends, `: byte` enum extends, `nameof` calls)
  11. //! this file preserves on purpose. Positions in UTF-16 code units. Files whose
  12. //! parse tree contains ERRORS defer to the wasm extractor.
  13. //!
  14. //! preParse (#237 `#if` blanking) stays TS-side: the route point hoists it, so
  15. //! the kernel receives pre-blanked bytes — port NOTHING of it here (its regex
  16. //! carries JS `(?m)`/CRLF semantics that must not be re-implemented).
  17. use crate::buffers::{
  18. build_meta, edge_kind_index, node_kind_index, Arena, BoolFlags, EdgeRow, EmitOut, NodeRow,
  19. RefRow, StrRef, Tables, FLAG_IS_ASYNC, FLAG_IS_EXPORTED, FLAG_IS_STATIC, FUNCTION_REF_CODE,
  20. NONE, NONE_STR,
  21. };
  22. use crate::docstring::preceding_docstring;
  23. use crate::ids;
  24. use crate::textutil as util;
  25. use regex::Regex;
  26. use std::collections::{HashMap, HashSet};
  27. use std::sync::OnceLock;
  28. use tree_sitter::{Node, Parser};
  29. const MAX_VALUE_REF_NODES: usize = 20_000;
  30. /// BUILTIN_TYPES (tree-sitter.ts) — the full shared table; membership is what
  31. /// the TS code tests, so every row is ported even where only the Java/C# row
  32. /// can fire (a C# type named `String`/`error` IS suppressed via other rows).
  33. fn is_builtin_type(name: &str) -> bool {
  34. matches!(
  35. name,
  36. "string" | "number" | "boolean" | "void" | "null" | "undefined" | "never" | "any"
  37. | "unknown" | "object" | "symbol" | "bigint" | "true" | "false"
  38. | "str" | "bool" | "i8" | "i16" | "i32" | "i64" | "i128" | "isize"
  39. | "u8" | "u16" | "u32" | "u64" | "u128" | "usize" | "f32" | "f64" | "char"
  40. | "int" | "long" | "short" | "byte" | "float" | "double"
  41. | "int8" | "int16" | "int32" | "int64" | "uint8" | "uint16" | "uint32" | "uint64"
  42. | "float32" | "float64" | "complex64" | "complex128" | "rune" | "error"
  43. | "Int" | "Long" | "Short" | "Byte" | "Float" | "Double" | "Boolean" | "Char"
  44. | "Unit" | "String" | "Any" | "AnyRef" | "AnyVal" | "Nothing" | "Null"
  45. )
  46. }
  47. /// NAME_STOPLIST (function-ref.ts).
  48. fn is_stoplisted(name: &str) -> bool {
  49. matches!(
  50. name,
  51. "this" | "self" | "super" | "null" | "nil" | "true" | "false" | "undefined" | "new"
  52. | "NULL" | "nullptr" | "None"
  53. )
  54. }
  55. /// extractCsharpReturnType's trailing-nullable strip (`/\?+$/`).
  56. fn trailing_nullable_re() -> &'static Regex {
  57. static RE: OnceLock<Regex> = OnceLock::new();
  58. RE.get_or_init(|| Regex::new(r"\?+$").unwrap())
  59. }
  60. /// extractCsharpReturnType's generics strip (`/<[^>]*>/g`) — deliberately
  61. /// non-nesting: `Task<List<Foo>>` → `Task>` → the ident test fails →
  62. /// returnType undefined (same class of quirk as rust; PRESERVE).
  63. fn generic_args_re() -> &'static Regex {
  64. static RE: OnceLock<Regex> = OnceLock::new();
  65. RE.get_or_init(|| Regex::new(r"<[^>]*>").unwrap())
  66. }
  67. /// `/^[A-Za-z_]\w*$/` with JS's ASCII `\w` (Rust's default `\w` is Unicode).
  68. fn ascii_ident_re() -> &'static Regex {
  69. static RE: OnceLock<Regex> = OnceLock::new();
  70. RE.get_or_init(|| Regex::new(r"^[A-Za-z_][0-9A-Za-z_]*$").unwrap())
  71. }
  72. /// extractStaticMemberRef's capitalized-receiver test.
  73. fn capitalized_re() -> &'static Regex {
  74. static RE: OnceLock<Regex> = OnceLock::new();
  75. RE.get_or_init(|| Regex::new(r"^[A-Z][A-Za-z0-9_]*$").unwrap())
  76. }
  77. /// JS `\s` (WhiteSpace ∪ LineTerminator) — differs from Rust's `\p{White_Space}`
  78. /// on U+FEFF (JS: yes) and U+0085 (JS: no). The chained-call inner-callee strip
  79. /// (`.replace(/\s+/g, '')`) runs on arbitrary source slices, so match JS exactly.
  80. fn is_js_space(c: char) -> bool {
  81. matches!(
  82. c,
  83. '\t' | '\n' | '\x0B' | '\x0C' | '\r' | ' ' | '\u{00A0}' | '\u{1680}'
  84. | '\u{2000}'..='\u{200A}' | '\u{2028}' | '\u{2029}' | '\u{202F}' | '\u{205F}'
  85. | '\u{3000}' | '\u{FEFF}'
  86. )
  87. }
  88. fn strip_js_ws(s: &str) -> String {
  89. s.chars().filter(|c| !is_js_space(*c)).collect()
  90. }
  91. struct Scope {
  92. row: u32,
  93. kind: &'static str,
  94. name: String,
  95. }
  96. #[derive(Default)]
  97. struct Extra {
  98. docstring: Option<String>,
  99. signature: Option<String>,
  100. visibility: Option<u8>,
  101. is_static: Option<bool>,
  102. is_async: Option<bool>,
  103. return_type: 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 id string per row — ids COLLIDE for same-(kind, name, line) nodes
  125. /// and the TS side's fn-ref dedupe / value-ref self-checks key on the id.
  126. node_ids: Vec<String>,
  127. defined_fn_names: HashSet<String>,
  128. imported_names: HashSet<String>,
  129. fn_ref_cands: Vec<Cand>,
  130. fs_values: HashMap<String, u32>,
  131. fs_value_counts: HashMap<String, u32>,
  132. value_scopes: Vec<ValueScope<'t>>,
  133. }
  134. pub fn extract(file_path: &str, source: &str) -> Result<EmitOut, String> {
  135. let grammar = crate::langs::grammar_for("csharp").ok_or("no csharp grammar")?;
  136. let t0 = std::time::Instant::now();
  137. let mut parser = Parser::new();
  138. parser
  139. .set_language(&grammar)
  140. .map_err(|e| format!("set_language(csharp) failed: {e}"))?;
  141. let tree = parser
  142. .parse(source, None)
  143. .ok_or_else(|| "parser returned null tree".to_string())?;
  144. if tree.root_node().has_error() {
  145. return Err("defer: parse tree contains errors — wasm recovery is canonical".to_string());
  146. }
  147. let mut w = Walker {
  148. src: source,
  149. file_path,
  150. line_starts: util::line_starts(source),
  151. arena: Arena::default(),
  152. tables: Tables::default(),
  153. stack: Vec::new(),
  154. node_ids: Vec::new(),
  155. defined_fn_names: HashSet::new(),
  156. imported_names: HashSet::new(),
  157. fn_ref_cands: Vec::new(),
  158. fs_values: HashMap::new(),
  159. fs_value_counts: HashMap::new(),
  160. value_scopes: Vec::new(),
  161. };
  162. // File node (TreeSitterExtractor.extract). Source here is the pre-blanked
  163. // text (the route point hoists preParse), identical bytes on both arms.
  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.stack.push(Scope { row: 0, kind: "file", name: base_name.to_string() });
  191. // extractFilePackage: the FIRST top-level namespace declaration mints ONE
  192. // `namespace` node that stays pushed for the ENTIRE file — a second
  193. // top-level namespace's types nest under the first's node/QN, nested
  194. // namespaces leave no trace, and every import ref in a namespaced file
  195. // hangs off this node (checklist §namespace).
  196. let root = tree.root_node();
  197. let mut pkg_pushed = false;
  198. for i in 0..root.named_child_count() {
  199. let Some(child) = root.named_child(i) else { continue };
  200. if child.kind() != "namespace_declaration"
  201. && child.kind() != "file_scoped_namespace_declaration"
  202. {
  203. continue;
  204. }
  205. // csharpExtractor.extractPackage: `name` field ?? first
  206. // qualified_name/identifier named child. No trim.
  207. let name_node = child.child_by_field_name("name").or_else(|| {
  208. (0..child.named_child_count())
  209. .filter_map(|j| child.named_child(j))
  210. .find(|c| matches!(c.kind(), "qualified_name" | "identifier"))
  211. });
  212. if let Some(name_node) = name_node {
  213. let pkg = w.text(name_node).to_string();
  214. if !pkg.is_empty() {
  215. if let Some(row) = w.create_node("namespace", &pkg, child, Extra::default()) {
  216. w.stack.push(Scope { row, kind: "namespace", name: pkg });
  217. pkg_pushed = true;
  218. }
  219. }
  220. }
  221. break;
  222. }
  223. w.visit_node(root);
  224. w.flush_fn_ref_candidates();
  225. w.flush_value_refs(root);
  226. if pkg_pushed {
  227. w.stack.pop();
  228. }
  229. w.stack.pop();
  230. let duration_ms = t0.elapsed().as_secs_f64() * 1000.0;
  231. let meta = build_meta(&w.tables, w.arena.len(), NONE_STR, duration_ms);
  232. Ok(EmitOut {
  233. meta,
  234. nodes: w.tables.nodes,
  235. edges: w.tables.edges,
  236. refs: w.tables.refs,
  237. arena: w.arena.into_vec(),
  238. })
  239. }
  240. /// classifyClassNode (languages/csharp.ts): a record_declaration with an
  241. /// anonymous `struct` keyword child is a record struct.
  242. fn record_is_struct(node: Node) -> bool {
  243. (0..node.child_count())
  244. .filter_map(|i| node.child(i))
  245. .any(|c| c.kind() == "struct")
  246. }
  247. impl<'t> Walker<'t> {
  248. fn text(&self, node: Node) -> &'t str {
  249. &self.src[node.byte_range()]
  250. }
  251. fn line_of(&self, node: Node) -> u32 {
  252. node.start_position().row as u32 + 1
  253. }
  254. fn col_of(&self, node: Node) -> u32 {
  255. util::col16(self.src, &self.line_starts, node.start_position().row, node.start_byte())
  256. }
  257. fn end_col_of(&self, node: Node) -> u32 {
  258. util::col16(self.src, &self.line_starts, node.end_position().row, node.end_byte())
  259. }
  260. fn top_row(&self) -> u32 {
  261. self.stack.last().map(|s| s.row).unwrap_or(0)
  262. }
  263. fn inside_class_like(&self) -> bool {
  264. self.stack
  265. .last()
  266. .map(|s| matches!(s.kind, "class" | "struct" | "interface" | "trait" | "enum" | "module"))
  267. .unwrap_or(false)
  268. }
  269. fn push_ref(&mut self, from_row: u32, name: &str, kind_code: u8, line: u32, column: u32) {
  270. let name_ref = self.arena.put(name);
  271. self.tables.push_ref(&RefRow {
  272. from_idx: from_row,
  273. kind: kind_code,
  274. line,
  275. column,
  276. reference_name: name_ref,
  277. candidates: NONE_STR,
  278. from_id_str: NONE_STR,
  279. });
  280. if kind_code == edge_kind_index("imports").unwrap() {
  281. if util::simple_name().is_match(name) {
  282. self.imported_names.insert(name.to_string());
  283. } else if let Some(c) = util::qualified_import().captures(name) {
  284. self.imported_names.insert(c[1].to_string());
  285. }
  286. }
  287. }
  288. fn push_ref_at(&mut self, from_row: u32, name: &str, kind_code: u8, node: Node) {
  289. self.push_ref(from_row, name, kind_code, self.line_of(node), self.col_of(node));
  290. }
  291. // --- createNode ------------------------------------------------------------
  292. fn create_node(&mut self, kind: &'static str, name: &str, node: Node<'t>, extra: Extra) -> Option<u32> {
  293. if name.is_empty() {
  294. return None;
  295. }
  296. let start_line = self.line_of(node);
  297. let id = ids::node_id(self.file_path, kind, name, start_line);
  298. let end_line = node.end_position().row as u32 + 1; // no resolveBody for csharp
  299. let qualified = {
  300. let mut parts: Vec<&str> = Vec::new();
  301. for s in &self.stack {
  302. if s.kind != "file" {
  303. parts.push(&s.name);
  304. }
  305. }
  306. let mut qn = parts.join("::");
  307. if !qn.is_empty() {
  308. qn.push_str("::");
  309. }
  310. qn.push_str(name);
  311. qn
  312. };
  313. let mut flags = BoolFlags::default();
  314. if let Some(v) = extra.is_static {
  315. flags.set(FLAG_IS_STATIC, v);
  316. }
  317. if let Some(v) = extra.is_async {
  318. flags.set(FLAG_IS_ASYNC, v);
  319. }
  320. let name_ref = self.arena.put(name);
  321. let qn_ref = self.arena.put(&qualified);
  322. let id_ref = self.arena.put(&id);
  323. let doc_ref = opt_str(&mut self.arena, extra.docstring.as_deref());
  324. let sig_ref = opt_str(&mut self.arena, extra.signature.as_deref());
  325. let ret_ref = opt_str(&mut self.arena, extra.return_type.as_deref());
  326. let row = self.tables.push_node(&NodeRow {
  327. kind: node_kind_index(kind).unwrap(),
  328. visibility: extra.visibility.unwrap_or(0),
  329. flags,
  330. start_line,
  331. end_line,
  332. start_column: self.col_of(node),
  333. end_column: self.end_col_of(node),
  334. name: name_ref,
  335. qualified_name: qn_ref,
  336. id: id_ref,
  337. docstring: doc_ref,
  338. signature: sig_ref,
  339. decorators: NONE_STR, // C# extraction emits no decorators (checklist §decorators)
  340. type_parameters: NONE_STR,
  341. return_type: ret_ref,
  342. extra_json: NONE_STR,
  343. });
  344. self.node_ids.push(id);
  345. let parent_row = self.top_row();
  346. self.tables.push_edge(&EdgeRow {
  347. source_idx: parent_row,
  348. target_idx: row,
  349. kind: edge_kind_index("contains").unwrap(),
  350. provenance: 0,
  351. line: NONE,
  352. column: NONE,
  353. metadata_json: NONE_STR,
  354. source_id_str: NONE_STR,
  355. target_id_str: NONE_STR,
  356. });
  357. if kind == "function" || kind == "method" {
  358. self.defined_fn_names.insert(name.to_string());
  359. }
  360. self.capture_value_ref_scope(kind, name, row, node);
  361. Some(row)
  362. }
  363. fn capture_value_ref_scope(&mut self, kind: &'static str, name: &str, row: u32, node: Node<'t>) {
  364. let target_kind_ok = kind == "constant" || kind == "variable";
  365. if target_kind_ok
  366. && util::utf16_len(name) >= 3
  367. && util::has_upper_or_underscore().is_match(name)
  368. {
  369. let parent_ok = self
  370. .stack
  371. .last()
  372. .map(|s| matches!(s.kind, "file" | "class" | "module" | "struct" | "enum"))
  373. .unwrap_or(false);
  374. if parent_ok {
  375. self.fs_values.insert(name.to_string(), row);
  376. *self.fs_value_counts.entry(name.to_string()).or_insert(0) += 1;
  377. }
  378. }
  379. if matches!(kind, "function" | "method" | "constant" | "variable") {
  380. self.value_scopes.push(ValueScope { row, node, name: name.to_string() });
  381. }
  382. }
  383. // --- hooks (languages/csharp.ts) --------------------------------------------
  384. //
  385. // C# modifiers are individual named `modifier` children — there is NO
  386. // Java-style `modifiers` wrapper (probed).
  387. /// getVisibility: FIRST `modifier` child whose text is one of the four
  388. /// levels wins; none → private (the C# default).
  389. fn visibility_of(&self, node: Node) -> u8 {
  390. for i in 0..node.child_count() {
  391. let Some(child) = node.child(i) else { continue };
  392. if child.kind() == "modifier" {
  393. match self.text(child) {
  394. "public" => return 1,
  395. "private" => return 2,
  396. "protected" => return 3,
  397. "internal" => return 4,
  398. _ => {}
  399. }
  400. }
  401. }
  402. 2 // C# defaults to private
  403. }
  404. fn is_static(&self, node: Node) -> bool {
  405. (0..node.child_count())
  406. .filter_map(|i| node.child(i))
  407. .any(|c| c.kind() == "modifier" && self.text(c) == "static")
  408. }
  409. fn is_async(&self, node: Node) -> bool {
  410. (0..node.child_count())
  411. .filter_map(|i| node.child(i))
  412. .any(|c| c.kind() == "modifier" && self.text(c) == "async")
  413. }
  414. /// isConst: `const` → true; else `static` AND `readonly` both present.
  415. fn is_const(&self, node: Node) -> bool {
  416. let mut has_static = false;
  417. let mut has_readonly = false;
  418. for i in 0..node.child_count() {
  419. let Some(child) = node.child(i) else { continue };
  420. if child.kind() != "modifier" {
  421. continue;
  422. }
  423. match self.text(child) {
  424. "const" => return true,
  425. "static" => has_static = true,
  426. "readonly" => has_readonly = true,
  427. _ => {}
  428. }
  429. }
  430. has_static && has_readonly
  431. }
  432. /// extractCsharpReturnType — reads the `returns` field; feeds the
  433. /// #645/#608 chained-call resolution. Constructors have no `returns`.
  434. fn return_type_of(&self, node: Node) -> Option<String> {
  435. let t = node.child_by_field_name("returns")?;
  436. if matches!(t.kind(), "predefined_type" | "array_type") {
  437. return None;
  438. }
  439. let mut s = self.text(t).trim().to_string();
  440. s = trailing_nullable_re().replace(&s, "").into_owned();
  441. s = generic_args_re().replace_all(&s, "").into_owned();
  442. let last = s.rsplit('.').next().unwrap_or("").trim().to_string();
  443. if last.is_empty() || !ascii_ident_re().is_match(&last) {
  444. return None;
  445. }
  446. Some(last)
  447. }
  448. /// extractName (tree-sitter.ts:90) — the C#-reachable paths: the `name`
  449. /// field (always present on named declarations), else the shared
  450. /// identifier scan, else `<anonymous>`.
  451. fn extract_name(&self, node: Node) -> String {
  452. if let Some(name_node) = node.child_by_field_name("name") {
  453. return self.text(name_node).to_string();
  454. }
  455. for i in 0..node.named_child_count() {
  456. if let Some(c) = node.named_child(i) {
  457. if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") {
  458. return self.text(c).to_string();
  459. }
  460. }
  461. }
  462. "<anonymous>".to_string()
  463. }
  464. // --- the dispatcher (visitNode, C#-relevant branches) -----------------------
  465. fn visit_node(&mut self, node: Node<'t>) {
  466. let kind = node.kind();
  467. let mut skip_children = false;
  468. self.maybe_capture_fn_refs(node);
  469. if kind == "class_declaration" || kind == "record_declaration" {
  470. // classifyClassNode: `record struct` → extractStruct, else class.
  471. if kind == "record_declaration" && record_is_struct(node) {
  472. self.extract_struct(node);
  473. } else {
  474. self.extract_class(node);
  475. }
  476. skip_children = true;
  477. } else if kind == "method_declaration" || kind == "constructor_declaration" {
  478. self.extract_method(node);
  479. skip_children = true;
  480. } else if kind == "interface_declaration" {
  481. self.extract_interface(node);
  482. skip_children = true;
  483. } else if kind == "struct_declaration" || kind == "record_struct_declaration" {
  484. self.extract_struct(node);
  485. skip_children = true;
  486. } else if kind == "enum_declaration" {
  487. self.extract_enum(node);
  488. skip_children = true;
  489. } else if kind == "property_declaration" && self.inside_class_like() {
  490. // Property accessor/expression bodies are NEVER walked (calls
  491. // inside are lost by design) — candidates-only scan.
  492. self.extract_property(node);
  493. self.scan_fn_ref_subtree(node, 0);
  494. skip_children = true;
  495. } else if kind == "field_declaration" && self.inside_class_like() {
  496. self.extract_field(node);
  497. self.scan_fn_ref_subtree(node, 0);
  498. skip_children = true;
  499. } else if kind == "local_declaration_statement" && !self.inside_class_like() {
  500. // Top-level statements: extractVariable's generic fallback finds no
  501. // direct identifier/variable_declarator children (C# nests them in
  502. // variable_declaration) → ZERO nodes, zero refs. Candidates only.
  503. self.extract_variable(node);
  504. self.scan_fn_ref_subtree(node, 0);
  505. skip_children = true;
  506. } else if kind == "using_directive" {
  507. self.extract_import(node);
  508. // no skipChildren (TS importTypes branch) — children visited below
  509. } else if kind == "invocation_expression" {
  510. self.extract_call(node);
  511. } else if kind == "object_creation_expression" {
  512. self.extract_instantiation(node);
  513. if let Some(anon_body) = find_anonymous_class_body(node) {
  514. self.extract_anonymous_class(node, anon_body);
  515. skip_children = true;
  516. }
  517. }
  518. // Everything else (namespace_declaration, global_statement, delegates,
  519. // events, operators, indexers, destructors, local functions, preproc_*)
  520. // falls through: no node minted, children visited — their bodies' calls
  521. // attribute to the enclosing scope (checklist §dispatch).
  522. if !skip_children {
  523. for i in 0..node.named_child_count() {
  524. if let Some(c) = node.named_child(i) {
  525. self.visit_node(c);
  526. }
  527. }
  528. }
  529. }
  530. // --- visitFunctionBody ------------------------------------------------------
  531. fn visit_function_body(&mut self, body: Node<'t>) {
  532. self.visit_for_calls_and_structure(body);
  533. }
  534. fn visit_for_calls_and_structure(&mut self, node: Node<'t>) {
  535. let kind = node.kind();
  536. self.maybe_capture_fn_refs(node);
  537. if kind == "invocation_expression" {
  538. self.extract_call(node);
  539. } else if kind == "object_creation_expression" {
  540. self.extract_instantiation(node);
  541. if let Some(anon_body) = find_anonymous_class_body(node) {
  542. self.extract_anonymous_class(node, anon_body);
  543. return;
  544. }
  545. }
  546. // Static value reads (`ReadType.ReadAsDouble`) — body walker only.
  547. self.extract_static_member_ref(node);
  548. // (variable_declarator type-annotation branch: C# has no
  549. // `type_annotation` child node — structurally inert, not ported.
  550. // functionTypes is empty — no nested-function branch.)
  551. if kind == "class_declaration" || kind == "record_declaration" {
  552. if kind == "record_declaration" && record_is_struct(node) {
  553. self.extract_struct(node);
  554. } else {
  555. self.extract_class(node);
  556. }
  557. return;
  558. }
  559. if kind == "struct_declaration" || kind == "record_struct_declaration" {
  560. self.extract_struct(node);
  561. return;
  562. }
  563. if kind == "enum_declaration" {
  564. self.extract_enum(node);
  565. return;
  566. }
  567. if kind == "interface_declaration" {
  568. self.extract_interface(node);
  569. return;
  570. }
  571. for i in 0..node.named_child_count() {
  572. if let Some(c) = node.named_child(i) {
  573. self.visit_for_calls_and_structure(c);
  574. }
  575. }
  576. }
  577. // --- extractors --------------------------------------------------------------
  578. fn extract_class(&mut self, node: Node<'t>) {
  579. // skipBodilessClass unset: a bodiless `record Empty;` still mints a node.
  580. let name = self.extract_name(node);
  581. let extra = Extra {
  582. docstring: preceding_docstring(node, self.src),
  583. visibility: Some(self.visibility_of(node)),
  584. ..Extra::default() // isExported hook absent → flag not present
  585. };
  586. let Some(row) = self.create_node("class", &name, node, extra) else { return };
  587. self.extract_inheritance(node, row);
  588. self.extract_primary_ctor_param_refs(node, row);
  589. // extractDecoratorsFor: C# attributes never match its accepted node
  590. // types (attribute_list is skipped, its children never reached) —
  591. // zero `decorates` refs; the call slot emits nothing.
  592. self.stack.push(Scope { row, kind: "class", name });
  593. // body ?? node: a bodiless record's own children are iterated
  594. // "harmlessly" — visit_node on identifier/parameter_list/base_list
  595. // children falls through (base-arg identifiers still feed fn-ref
  596. // capture, mirroring the TS walk).
  597. let body = node.child_by_field_name("body").unwrap_or(node);
  598. for i in 0..body.named_child_count() {
  599. if let Some(c) = body.named_child(i) {
  600. self.visit_node(c);
  601. }
  602. }
  603. // no synthesizeMembers for C#
  604. self.stack.pop();
  605. }
  606. fn extract_struct(&mut self, node: Node<'t>) {
  607. // Body gate — EXCEPT C# positional records (`record struct M(…);`,
  608. // node type record_declaration), complete definitions with no body.
  609. // A bodiless `struct Fwd;` mints NO node. (#831)
  610. let body = node.child_by_field_name("body");
  611. if body.is_none() && node.kind() != "record_declaration" {
  612. return;
  613. }
  614. let name = self.extract_name(node);
  615. let extra = Extra {
  616. docstring: preceding_docstring(node, self.src),
  617. visibility: Some(self.visibility_of(node)),
  618. ..Extra::default()
  619. };
  620. let Some(row) = self.create_node("struct", &name, node, extra) else { return };
  621. self.extract_inheritance(node, row);
  622. self.extract_primary_ctor_param_refs(node, row);
  623. // NOTE: extractStruct does NOT call extractDecoratorsFor (TS parity).
  624. if let Some(body) = body {
  625. self.stack.push(Scope { row, kind: "struct", name });
  626. for i in 0..body.named_child_count() {
  627. if let Some(c) = body.named_child(i) {
  628. self.visit_node(c);
  629. }
  630. }
  631. self.stack.pop();
  632. }
  633. }
  634. fn extract_interface(&mut self, node: Node<'t>) {
  635. let name = self.extract_name(node);
  636. let extra = Extra {
  637. docstring: preceding_docstring(node, self.src),
  638. ..Extra::default() // NO visibility — extractInterface never asks
  639. };
  640. let Some(row) = self.create_node("interface", &name, node, extra) else { return };
  641. self.extract_inheritance(node, row);
  642. self.stack.push(Scope { row, kind: "interface", name });
  643. let body = node.child_by_field_name("body").unwrap_or(node);
  644. for i in 0..body.named_child_count() {
  645. if let Some(c) = body.named_child(i) {
  646. self.visit_node(c);
  647. }
  648. }
  649. self.stack.pop();
  650. }
  651. fn extract_enum(&mut self, node: Node<'t>) {
  652. let Some(body) = node.child_by_field_name("body") else { return };
  653. let name = self.extract_name(node);
  654. let extra = Extra {
  655. docstring: preceding_docstring(node, self.src),
  656. visibility: Some(self.visibility_of(node)),
  657. ..Extra::default()
  658. };
  659. let Some(row) = self.create_node("enum", &name, node, extra) else { return };
  660. // The underlying type (`enum ReadType : byte`) sits in base_list →
  661. // an `extends` ref named `byte` (garbage, PRESERVE).
  662. self.extract_inheritance(node, row);
  663. self.stack.push(Scope { row, kind: "enum", name });
  664. for i in 0..body.named_child_count() {
  665. let Some(child) = body.named_child(i) else { continue };
  666. if child.kind() == "enum_member_declaration" {
  667. self.extract_enum_members(child);
  668. } else {
  669. self.visit_node(child);
  670. }
  671. }
  672. self.stack.pop();
  673. }
  674. fn extract_enum_members(&mut self, node: Node<'t>) {
  675. // name-field path: one enum_member node positioned at the MEMBER node
  676. // (attributes included in its span); values/attributes ignored.
  677. if let Some(name_node) = node.child_by_field_name("name") {
  678. let name = self.text(name_node).to_string();
  679. self.create_node("enum_member", &name, node, Extra::default());
  680. }
  681. // (identifier-children / leaf fallbacks are other grammars' shapes)
  682. }
  683. /// extractProperty (1986) — property_declaration only (dispatch-gated to
  684. /// class-like scopes). Accessor bodies and `=>` value clauses are never
  685. /// walked; type refs DO come from the `type` field.
  686. fn extract_property(&mut self, node: Node<'t>) {
  687. let docstring = preceding_docstring(node, self.src);
  688. let visibility = Some(self.visibility_of(node));
  689. let is_static = Some(self.is_static(node)); // ?? false — always concrete
  690. let name_node = node
  691. .child_by_field_name("name")
  692. .or_else(|| node.child_by_field_name("property"))
  693. .or_else(|| {
  694. (0..node.named_child_count())
  695. .filter_map(|i| node.named_child(i))
  696. .find(|c| c.kind() == "identifier")
  697. });
  698. let Some(name_node) = name_node else { return };
  699. let name = self.text(name_node).to_string();
  700. if name.is_empty() {
  701. return;
  702. }
  703. // Generic scan (isTsJsField=false): FIRST namedChild that isn't a
  704. // modifier/name/accessor/initializer. A BARE-identifier declared type
  705. // (`public Widget Parent {get;}`) is excluded by the `identifier`
  706. // filter → the signature loses its type (QUIRK, preserve); the type
  707. // ref below still fires via the `type` FIELD.
  708. let type_node = (0..node.named_child_count())
  709. .filter_map(|i| node.named_child(i))
  710. .find(|c| {
  711. !matches!(
  712. c.kind(),
  713. "modifier" | "modifiers" | "identifier" | "accessor_list" | "accessors"
  714. | "equals_value_clause"
  715. )
  716. });
  717. let type_text = type_node.map(|t| {
  718. let raw = self.text(t);
  719. // TS `.replace(/^:\s*/, '')` — inert for C# type text; mirrored.
  720. match raw.strip_prefix(':') {
  721. Some(rest) => rest.trim_start_matches(is_js_space).to_string(),
  722. None => raw.to_string(),
  723. }
  724. });
  725. let signature = match &type_text {
  726. Some(t) => format!("{t} {name}"),
  727. None => name.clone(),
  728. };
  729. let row = self.create_node(
  730. "property",
  731. &name,
  732. node,
  733. Extra { docstring, signature: Some(signature), visibility, is_static, ..Extra::default() },
  734. );
  735. if let Some(row) = row {
  736. // decorators: none for C#; then the csharp type-ref path.
  737. self.extract_csharp_type_refs(node, row);
  738. }
  739. }
  740. /// extractField (2046) — field_declaration; each declarator becomes a
  741. /// field/constant node anchored at the DECLARATOR.
  742. fn extract_field(&mut self, node: Node<'t>) {
  743. let docstring = preceding_docstring(node, self.src);
  744. let visibility = Some(self.visibility_of(node));
  745. let is_static = Some(self.is_static(node));
  746. // `const` / `static readonly` → constant (value-ref targets).
  747. let field_kind: &'static str = if self.is_const(node) { "constant" } else { "field" };
  748. // Direct declarators (Java shape) — none for C#; the wrapper path:
  749. let mut declarators: Vec<Node> = (0..node.named_child_count())
  750. .filter_map(|i| node.named_child(i))
  751. .filter(|c| c.kind() == "variable_declarator")
  752. .collect();
  753. let var_decl = (0..node.named_child_count())
  754. .filter_map(|i| node.named_child(i))
  755. .find(|c| c.kind() == "variable_declaration");
  756. if declarators.is_empty() {
  757. if let Some(vd) = var_decl {
  758. declarators = (0..vd.named_child_count())
  759. .filter_map(|i| vd.named_child(i))
  760. .filter(|c| c.kind() == "variable_declarator")
  761. .collect();
  762. }
  763. }
  764. // (PHP property_element branch: unreachable for C#.)
  765. if !declarators.is_empty() {
  766. let type_search = var_decl.unwrap_or(node);
  767. let type_node = (0..type_search.named_child_count())
  768. .filter_map(|i| type_search.named_child(i))
  769. .find(|c| {
  770. !matches!(
  771. c.kind(),
  772. "modifiers" | "modifier" | "variable_declarator" | "variable_declaration"
  773. | "marker_annotation" | "annotation"
  774. )
  775. });
  776. let type_text = type_node.map(|t| self.text(t).to_string());
  777. for decl in declarators {
  778. let name_node = decl.child_by_field_name("name").or_else(|| {
  779. (0..decl.named_child_count())
  780. .filter_map(|i| decl.named_child(i))
  781. .find(|c| c.kind() == "identifier")
  782. });
  783. let Some(name_node) = name_node else { continue };
  784. let name = self.text(name_node).to_string();
  785. let signature = match &type_text {
  786. Some(t) => format!("{t} {name}"),
  787. None => name.clone(),
  788. };
  789. let row = self.create_node(
  790. field_kind,
  791. &name,
  792. decl,
  793. Extra {
  794. docstring: docstring.clone(),
  795. signature: Some(signature),
  796. visibility,
  797. is_static,
  798. ..Extra::default()
  799. },
  800. );
  801. if let Some(row) = row {
  802. // decorators: none; type refs from the OUTER declaration —
  803. // multi-declarator fields emit the type refs once PER
  804. // declarator, each from its own field node.
  805. self.extract_csharp_type_refs(node, row);
  806. }
  807. }
  808. } else {
  809. // Bare fallback (unreachable on non-erroring C#; ported for shape).
  810. let name_node = node.child_by_field_name("name").or_else(|| {
  811. (0..node.named_child_count())
  812. .filter_map(|i| node.named_child(i))
  813. .find(|c| c.kind() == "identifier")
  814. });
  815. if let Some(name_node) = name_node {
  816. let name = self.text(name_node).to_string();
  817. self.create_node(
  818. field_kind,
  819. &name,
  820. node,
  821. Extra { docstring, visibility, is_static, ..Extra::default() },
  822. );
  823. }
  824. }
  825. }
  826. /// extractMethod (1737) — method_declaration + constructor_declaration.
  827. /// Signature is ALWAYS undefined (no getSignature hook); isAsync is real.
  828. fn extract_method(&mut self, node: Node<'t>) {
  829. if !self.inside_class_like() {
  830. // Unreachable on non-erroring C# (top-level `void M(){}` parses as
  831. // local_function_statement; erroring files defer) — mirror the TS
  832. // treat-as-function tail for shape.
  833. self.extract_function(node);
  834. return;
  835. }
  836. let name = self.extract_name(node);
  837. let extra = Extra {
  838. docstring: preceding_docstring(node, self.src),
  839. signature: None,
  840. visibility: Some(self.visibility_of(node)),
  841. is_async: Some(self.is_async(node)),
  842. is_static: Some(self.is_static(node)),
  843. return_type: self.return_type_of(node),
  844. };
  845. let Some(row) = self.create_node("method", &name, node, extra) else { return };
  846. // extractTypeAnnotations short-circuits into the csharp path:
  847. // `returns`-field refs FIRST, then per-parameter type refs.
  848. self.extract_csharp_type_refs(node, row);
  849. // decorators: none.
  850. self.stack.push(Scope { row, kind: "method", name });
  851. // The `body` FIELD only (block or arrow_expression_clause). A
  852. // constructor_initializer (`: base(args)`) is NOT the body → its
  853. // argument calls are LOST (quirk, preserve).
  854. if let Some(body) = node.child_by_field_name("body") {
  855. self.visit_function_body(body);
  856. }
  857. self.stack.pop();
  858. }
  859. /// extractFunction — only reachable for a method outside any class
  860. /// (unreachable on non-erroring C#; kept faithful to the generic tail).
  861. fn extract_function(&mut self, node: Node<'t>) {
  862. let name = self.extract_name(node);
  863. if name == "<anonymous>" {
  864. if let Some(body) = node.child_by_field_name("body") {
  865. self.visit_function_body(body);
  866. }
  867. return;
  868. }
  869. let extra = Extra {
  870. docstring: preceding_docstring(node, self.src),
  871. signature: None,
  872. visibility: Some(self.visibility_of(node)),
  873. is_async: Some(self.is_async(node)),
  874. is_static: Some(self.is_static(node)),
  875. return_type: self.return_type_of(node),
  876. };
  877. let Some(row) = self.create_node("function", &name, node, extra) else { return };
  878. self.extract_csharp_type_refs(node, row);
  879. self.stack.push(Scope { row, kind: "function", name });
  880. if let Some(body) = node.child_by_field_name("body") {
  881. self.visit_function_body(body);
  882. }
  883. self.stack.pop();
  884. }
  885. fn extract_variable(&mut self, node: Node<'t>) {
  886. // extractVariable's generic fallback: direct identifier /
  887. // variable_declarator children only — C# nests declarators inside
  888. // variable_declaration, so this NEVER fires (`var x = F();` at top
  889. // level produces no node, no calls ref, no instantiates — preserve).
  890. let kind: &'static str = if self.is_const(node) { "constant" } else { "variable" };
  891. let docstring = preceding_docstring(node, self.src);
  892. for i in 0..node.named_child_count() {
  893. let Some(child) = node.named_child(i) else { continue };
  894. let name = match child.kind() {
  895. "identifier" => self.text(child).to_string(),
  896. "variable_declarator" => self.extract_name(child),
  897. _ => continue,
  898. };
  899. if name.is_empty() || name == "<anonymous>" {
  900. continue;
  901. }
  902. self.create_node(
  903. kind,
  904. &name,
  905. child,
  906. Extra { docstring: docstring.clone(), ..Extra::default() },
  907. );
  908. }
  909. }
  910. /// extractImport via csharpExtractor.extractImport: moduleName = first
  911. /// qualified_name child's text, else first identifier's — with the alias
  912. /// quirks (alias-to-qualified keeps generic args on the TARGET text;
  913. /// alias-to-identifier captures the ALIAS name) preserved verbatim.
  914. fn extract_import(&mut self, node: Node<'t>) {
  915. let import_text = self.text(node).trim().to_string();
  916. let target = (0..node.named_child_count())
  917. .filter_map(|i| node.named_child(i))
  918. .find(|c| c.kind() == "qualified_name")
  919. .or_else(|| {
  920. (0..node.named_child_count())
  921. .filter_map(|i| node.named_child(i))
  922. .find(|c| c.kind() == "identifier")
  923. });
  924. let Some(target) = target else { return }; // hook declined → no node, no ref
  925. let module_name = self.text(target).to_string();
  926. if module_name.is_empty() {
  927. return;
  928. }
  929. self.create_node(
  930. "import",
  931. &module_name,
  932. node,
  933. Extra { signature: Some(import_text), ..Extra::default() },
  934. );
  935. // One generic `imports` ref from the stack top (the namespace node in
  936. // a namespaced file, else the file node). No per-binding emitter.
  937. let parent = self.top_row();
  938. self.push_ref_at(parent, &module_name.clone(), edge_kind_index("imports").unwrap(), node);
  939. }
  940. /// extractCall — the C# branch (tree-sitter.ts:4502) + shared tail.
  941. fn extract_call(&mut self, node: Node<'t>) {
  942. if self.stack.is_empty() {
  943. return;
  944. }
  945. let caller = self.top_row();
  946. let func = node
  947. .child_by_field_name("function")
  948. .or_else(|| node.named_child(0));
  949. let Some(func) = func else { return };
  950. let mut callee_name: String;
  951. if func.kind() == "member_access_expression" {
  952. let recv = func.child_by_field_name("expression");
  953. let name_node = func.child_by_field_name("name");
  954. let method_name = name_node.map(|n| self.text(n)).unwrap_or("");
  955. let chained = recv
  956. .map(|r| r.kind() == "invocation_expression" && !method_name.is_empty())
  957. .unwrap_or(false);
  958. if chained {
  959. // Chained factory `Foo.Create(args).Bar()` → `Foo.Create().Bar`
  960. // (inner whitespace stripped, EVERY call-receiver re-encodes —
  961. // no capitalization gate, unlike kotlin/scala).
  962. let inner_func = recv.unwrap().child_by_field_name("function");
  963. let inner_callee = inner_func.map(|f| strip_js_ws(self.text(f))).unwrap_or_default();
  964. callee_name = if inner_callee.is_empty() {
  965. method_name.to_string()
  966. } else {
  967. format!("{inner_callee}().{method_name}")
  968. };
  969. } else {
  970. // RAW full member-access text: `this.Run`, `base.Method`,
  971. // `"lit".ToUpper`, multi-line fluent chains with their
  972. // newlines — no SKIP_RECEIVERS, no literal filter (preserve).
  973. callee_name = self.text(func).to_string();
  974. }
  975. } else {
  976. // Bare `Helper()`, generic `Generic<int>` kept verbatim,
  977. // `nameof(...)` → a calls ref named `nameof`, `?.` chains raw,
  978. // `(myDel)(x)` → parenthesized text (normalized below).
  979. callee_name = self.text(func).to_string();
  980. }
  981. // Shared parenthesized-conversion normalization — the one shared
  982. // normalization C# actually hits: `(myDel)(x)` → `myDel`.
  983. if !callee_name.is_empty() {
  984. if let Some(c) = util::paren_conversion().captures(&callee_name) {
  985. callee_name = c[1].to_string();
  986. }
  987. }
  988. // (template strip + fn-ptr fan-out are c/cpp-gated — not C#.)
  989. if !callee_name.is_empty() {
  990. self.push_ref_at(caller, &callee_name.clone(), edge_kind_index("calls").unwrap(), node);
  991. }
  992. }
  993. fn extract_instantiation(&mut self, node: Node<'t>) {
  994. if self.stack.is_empty() {
  995. return;
  996. }
  997. let ctor = node
  998. .child_by_field_name("constructor")
  999. .or_else(|| node.child_by_field_name("type"))
  1000. .or_else(|| node.child_by_field_name("name"))
  1001. .or_else(|| node.named_child(0));
  1002. let Some(ctor) = ctor else { return };
  1003. // `new List<Foo>()` → `List`; `new Ns.Foo()` → `Foo`. Target-typed
  1004. // `new()` / anonymous `new { }` / arrays `new T[n]` never reach here
  1005. // (not in INSTANTIATION_KINDS) — invisible by design.
  1006. let class_name = strip_generic_and_qualifier(self.text(ctor));
  1007. if !class_name.is_empty() {
  1008. let from = self.top_row();
  1009. self.push_ref_at(from, &class_name, edge_kind_index("instantiates").unwrap(), node);
  1010. }
  1011. }
  1012. /// extractAnonymousClass — `new T() { ... }`. The C# grammar never
  1013. /// produces a class_body/declaration_list child on object_creation
  1014. /// (object initializers are initializer_expression), so this is
  1015. /// unreachable — mirrored from the shared TS path like java.rs.
  1016. fn extract_anonymous_class(&mut self, node: Node<'t>, body: Node<'t>) {
  1017. let type_node = node
  1018. .child_by_field_name("constructor")
  1019. .or_else(|| node.child_by_field_name("type"))
  1020. .or_else(|| node.child_by_field_name("name"))
  1021. .or_else(|| node.named_child(0));
  1022. let mut type_name =
  1023. type_node.map(|t| self.text(t).to_string()).unwrap_or_else(|| "Object".to_string());
  1024. type_name = strip_generic_and_qualifier(&type_name);
  1025. if type_name.is_empty() {
  1026. type_name = "Object".to_string();
  1027. }
  1028. let anon_name = format!("<{type_name}$anon@{}>", node.start_position().row + 1);
  1029. let Some(row) = self.create_node("class", &anon_name, node, Extra::default()) else {
  1030. return;
  1031. };
  1032. // Bug-for-bug: the TS code uses `startPosition.row` (0-based) as the
  1033. // LINE here — the one place it forgets the +1.
  1034. let (line, column) = match type_node {
  1035. Some(t) => (t.start_position().row as u32, self.col_of(t)),
  1036. None => (node.start_position().row as u32, self.col_of(node)),
  1037. };
  1038. self.push_ref(row, &type_name, edge_kind_index("extends").unwrap(), line, column);
  1039. self.stack.push(Scope { row, kind: "class", name: anon_name });
  1040. for i in 0..body.named_child_count() {
  1041. if let Some(c) = body.named_child(i) {
  1042. self.visit_node(c);
  1043. }
  1044. }
  1045. self.stack.pop();
  1046. }
  1047. /// extractStaticMemberRef — csharp ∈ STATIC_MEMBER_LANGS; C#'s
  1048. /// member-access node with the `expression` receiver field.
  1049. fn extract_static_member_ref(&mut self, node: Node<'t>) {
  1050. if node.kind() != "member_access_expression" {
  1051. return;
  1052. }
  1053. if self.stack.is_empty() {
  1054. return;
  1055. }
  1056. let owner = self.top_row();
  1057. // Skip `Type.Method()` — the access is a call's callee, already linked.
  1058. if let Some(parent) = node.parent() {
  1059. if parent.kind() == "invocation_expression" {
  1060. let callee = parent
  1061. .child_by_field_name("function")
  1062. .or_else(|| parent.child_by_field_name("method"))
  1063. .or_else(|| parent.named_child(0));
  1064. if let Some(callee) = callee {
  1065. if callee.start_byte() == node.start_byte() {
  1066. return;
  1067. }
  1068. }
  1069. }
  1070. }
  1071. let recv = node
  1072. .child_by_field_name("object")
  1073. .or_else(|| node.child_by_field_name("expression"))
  1074. .or_else(|| node.child_by_field_name("scope"))
  1075. .or_else(|| node.named_child(0));
  1076. let Some(recv) = recv else { return };
  1077. if matches!(
  1078. recv.kind(),
  1079. "identifier" | "type_identifier" | "simple_identifier" | "name" | "scoped_type_identifier"
  1080. ) {
  1081. let text = self.text(recv);
  1082. if capitalized_re().is_match(text) {
  1083. self.push_ref_at(owner, &text.to_string(), edge_kind_index("references").unwrap(), recv);
  1084. }
  1085. }
  1086. }
  1087. /// extractInheritance — the C# base_list branch (5577): EVERY namedChild
  1088. /// emits one `extends` ref (interfaces conflated by design; the garbage
  1089. /// `(repo)` argument-list / `BaseDto(Name)` / `: byte` shapes preserved).
  1090. fn extract_inheritance(&mut self, node: Node<'t>, class_row: u32) {
  1091. let extends_kind = edge_kind_index("extends").unwrap();
  1092. for i in 0..node.named_child_count() {
  1093. let Some(child) = node.named_child(i) else { continue };
  1094. if child.kind() != "base_list" {
  1095. continue;
  1096. }
  1097. for j in 0..child.named_child_count() {
  1098. let Some(base) = child.named_child(j) else { continue };
  1099. let name = if base.kind() == "generic_name" {
  1100. // `ClientBase<T>` → head identifier; position = generic_name.
  1101. let ident = (0..base.named_child_count())
  1102. .filter_map(|k| base.named_child(k))
  1103. .find(|c| c.kind() == "identifier");
  1104. match ident {
  1105. Some(idn) => self.text(idn).to_string(),
  1106. None => self.text(base).to_string(),
  1107. }
  1108. } else {
  1109. self.text(base).to_string()
  1110. };
  1111. self.push_ref_at(class_row, &name, extends_kind, base);
  1112. }
  1113. }
  1114. }
  1115. // --- C# type-reference engine (extractCsharpTypeRefs, 5893) -----------------
  1116. fn extract_csharp_type_refs(&mut self, node: Node<'t>, from_row: u32) {
  1117. // Property `type` / method `returns` (a node carries only one).
  1118. let direct = node
  1119. .child_by_field_name("type")
  1120. .or_else(|| node.child_by_field_name("returns"));
  1121. if let Some(t) = direct {
  1122. self.walk_type_position(t, from_row);
  1123. }
  1124. // Field declarations: the variable_declaration wrapper's `type` field.
  1125. let var_decl = (0..node.named_child_count())
  1126. .filter_map(|i| node.named_child(i))
  1127. .find(|c| c.kind() == "variable_declaration");
  1128. if let Some(vd) = var_decl {
  1129. if let Some(t) = vd.child_by_field_name("type") {
  1130. self.walk_type_position(t, from_row);
  1131. }
  1132. }
  1133. // Method/constructor parameters: ONLY each `parameter`'s `type` field.
  1134. if let Some(params) = node.child_by_field_name("parameters") {
  1135. for i in 0..params.named_child_count() {
  1136. let Some(p) = params.named_child(i) else { continue };
  1137. if p.kind() != "parameter" {
  1138. continue;
  1139. }
  1140. if let Some(t) = p.child_by_field_name("type") {
  1141. self.walk_type_position(t, from_row);
  1142. }
  1143. }
  1144. }
  1145. }
  1146. /// extractCsharpPrimaryCtorParamRefs (5938) — the class/struct/record
  1147. /// primary constructor's parameter_list (an unnamed-field child).
  1148. fn extract_primary_ctor_param_refs(&mut self, node: Node<'t>, owner_row: u32) {
  1149. let param_list = (0..node.named_child_count())
  1150. .filter_map(|i| node.named_child(i))
  1151. .find(|c| c.kind() == "parameter_list");
  1152. let Some(param_list) = param_list else { return };
  1153. for i in 0..param_list.named_child_count() {
  1154. let Some(p) = param_list.named_child(i) else { continue };
  1155. if p.kind() != "parameter" {
  1156. continue;
  1157. }
  1158. if let Some(t) = p.child_by_field_name("type") {
  1159. self.walk_type_position(t, owner_row);
  1160. }
  1161. }
  1162. }
  1163. /// walkCsharpTypePosition (5955).
  1164. fn walk_type_position(&mut self, node: Node<'t>, from_row: u32) {
  1165. match node.kind() {
  1166. "predefined_type" => {}
  1167. "identifier" => {
  1168. let name = self.text(node);
  1169. if !name.is_empty() && !is_builtin_type(name) {
  1170. self.push_ref_at(from_row, &name.to_string(), edge_kind_index("references").unwrap(), node);
  1171. }
  1172. }
  1173. "qualified_name" => {
  1174. // Rightmost segment is the type; position = the whole node.
  1175. let text = self.text(node);
  1176. let last = text.rsplit('.').next().unwrap_or(text);
  1177. if !last.is_empty() && !is_builtin_type(last) {
  1178. self.push_ref_at(from_row, &last.to_string(), edge_kind_index("references").unwrap(), node);
  1179. }
  1180. }
  1181. "tuple_element" => {
  1182. // Walk the type field only — never the element NAME.
  1183. if let Some(t) = node.child_by_field_name("type") {
  1184. self.walk_type_position(t, from_row);
  1185. }
  1186. }
  1187. _ => {
  1188. for i in 0..node.named_child_count() {
  1189. if let Some(c) = node.named_child(i) {
  1190. self.walk_type_position(c, from_row);
  1191. }
  1192. }
  1193. }
  1194. }
  1195. }
  1196. // --- function-as-value refs (CSHARP_SPEC, function-ref.ts:250) --------------
  1197. fn maybe_capture_fn_refs(&mut self, node: Node<'t>) {
  1198. #[derive(PartialEq)]
  1199. enum Mode {
  1200. Args,
  1201. Rhs,
  1202. List,
  1203. Varinit,
  1204. }
  1205. let mode = match node.kind() {
  1206. "argument_list" => Mode::Args,
  1207. "assignment_expression" => Mode::Rhs, // covers `+=` event subscription
  1208. "initializer_expression" => Mode::List,
  1209. "variable_declarator" => Mode::Varinit,
  1210. _ => return,
  1211. };
  1212. if self.stack.is_empty() {
  1213. return;
  1214. }
  1215. let from = self.top_row();
  1216. let mut values: Vec<Node> = Vec::new();
  1217. match mode {
  1218. Mode::Args | Mode::List => {
  1219. for i in 0..node.named_child_count() {
  1220. if let Some(c) = node.named_child(i) {
  1221. values.push(c);
  1222. }
  1223. }
  1224. }
  1225. Mode::Rhs => {
  1226. if let Some(rhs) = node.child_by_field_name("right") {
  1227. // Param-storage skip: `this.status = status`.
  1228. let lhs = node
  1229. .child_by_field_name("left")
  1230. .or_else(|| node.child_by_field_name("lhs"))
  1231. .or_else(|| node.child_by_field_name("target"))
  1232. .or_else(|| {
  1233. if node.named_child_count() >= 2 { node.named_child(0) } else { None }
  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. let rhs_text = self.text(rhs).trim();
  1241. if !(lhs_last.is_some() && lhs_last == Some(rhs_text)) {
  1242. values.push(rhs);
  1243. }
  1244. }
  1245. }
  1246. Mode::Varinit => {
  1247. // No `value` field on C# variable_declarator: the initializer
  1248. // is the LAST named child — but an initializer-less declarator
  1249. // has its NAME there. Require ≥2 named children and never pick
  1250. // the name child. (Destructuring pattern gate never matches C#.)
  1251. let name_child = node
  1252. .child_by_field_name("name")
  1253. .or_else(|| node.child_by_field_name("pattern"));
  1254. let is_destructuring = name_child
  1255. .map(|nc| {
  1256. matches!(
  1257. nc.kind(),
  1258. "object_pattern" | "array_pattern" | "tuple_pattern" | "struct_pattern"
  1259. )
  1260. })
  1261. .unwrap_or(false);
  1262. if !is_destructuring && node.named_child_count() >= 2 {
  1263. if let Some(value) = node.named_child(node.named_child_count() - 1) {
  1264. let is_name = name_child.map(|nc| nc.id() == value.id()).unwrap_or(false);
  1265. if !is_name {
  1266. values.push(value);
  1267. }
  1268. }
  1269. }
  1270. }
  1271. }
  1272. for v in values {
  1273. self.normalize_fn_ref_value(v, from, 0);
  1274. }
  1275. }
  1276. /// normalizeValue (function-ref.ts:525) for CSHARP_SPEC: bare identifiers,
  1277. /// the transparent `argument` layer, and the `this.Member` special.
  1278. fn normalize_fn_ref_value(&mut self, v: Node<'t>, from: u32, depth: u32) {
  1279. if depth > 4 {
  1280. return;
  1281. }
  1282. match v.kind() {
  1283. "identifier" => {
  1284. let name = self.text(v);
  1285. self.push_fn_ref_cand(from, name, v);
  1286. }
  1287. "argument" => {
  1288. // Transparent layer (field=null) → recurse all named children.
  1289. for i in 0..v.named_child_count() {
  1290. if let Some(c) = v.named_child(i) {
  1291. self.normalize_fn_ref_value(c, from, depth + 1);
  1292. }
  1293. }
  1294. }
  1295. "member_access_expression" => {
  1296. // `this.Run0` — receiver must be EXACTLY `this` (the vendored
  1297. // grammar yields the anonymous `this` token via the field;
  1298. // text-prefix fallback for field-less shapes). Candidate is
  1299. // the BARE member name at the name node's position.
  1300. let Some(name_node) = v.child_by_field_name("name") else { return };
  1301. let is_this = match v.child_by_field_name("expression") {
  1302. Some(e) => e.kind() == "this_expression" || e.kind() == "this",
  1303. None => self.text(v).starts_with("this."),
  1304. };
  1305. if is_this {
  1306. let name = self.text(name_node);
  1307. self.push_fn_ref_cand(from, name, name_node);
  1308. }
  1309. }
  1310. _ => {}
  1311. }
  1312. }
  1313. fn push_fn_ref_cand(&mut self, from: u32, name: &str, node: Node) {
  1314. if name.is_empty() || is_stoplisted(name) {
  1315. return;
  1316. }
  1317. let p = node.start_position();
  1318. self.fn_ref_cands.push(Cand {
  1319. from,
  1320. name: name.to_string(),
  1321. line: p.row as u32 + 1,
  1322. column_byte: node.start_byte(),
  1323. row: p.row,
  1324. });
  1325. }
  1326. fn scan_fn_ref_subtree(&mut self, node: Node<'t>, depth: u32) {
  1327. if depth > 12 {
  1328. return;
  1329. }
  1330. // functionTypes is EMPTY for C#; the literal halt list applies —
  1331. // lambda_expression IS C#'s lambda, so initializer lambdas stop the
  1332. // scan; anonymous_method_expression is NOT listed and scans through.
  1333. if depth > 0
  1334. && matches!(
  1335. node.kind(),
  1336. "arrow_function" | "function_expression" | "lambda_literal" | "lambda_expression"
  1337. )
  1338. {
  1339. return;
  1340. }
  1341. self.maybe_capture_fn_refs(node);
  1342. for i in 0..node.named_child_count() {
  1343. if let Some(c) = node.named_child(i) {
  1344. self.scan_fn_ref_subtree(c, depth + 1);
  1345. }
  1346. }
  1347. }
  1348. fn flush_fn_ref_candidates(&mut self) {
  1349. let cands = std::mem::take(&mut self.fn_ref_cands);
  1350. if cands.is_empty() || util::is_generated_file(self.file_path) {
  1351. return;
  1352. }
  1353. let mut seen: HashSet<(String, String)> = HashSet::new();
  1354. for c in cands {
  1355. // C# candidates are always bare names (its this-forms normalize to
  1356. // the bare member), so the `this.`/`::` bypasses are inert — kept
  1357. // for shared-shape parity. Gate: definedHere ∪ importedNames.
  1358. if !c.name.starts_with("this.")
  1359. && !c.name.contains("::")
  1360. && !self.defined_fn_names.contains(&c.name)
  1361. && !self.imported_names.contains(&c.name)
  1362. {
  1363. continue;
  1364. }
  1365. if !seen.insert((self.node_ids[c.from as usize].clone(), c.name.clone())) {
  1366. continue;
  1367. }
  1368. let column = util::col16(self.src, &self.line_starts, c.row, c.column_byte);
  1369. let name_ref = self.arena.put(&c.name);
  1370. self.tables.push_ref(&RefRow {
  1371. from_idx: c.from,
  1372. kind: FUNCTION_REF_CODE,
  1373. line: c.line,
  1374. column,
  1375. reference_name: name_ref,
  1376. candidates: NONE_STR,
  1377. from_id_str: NONE_STR,
  1378. });
  1379. }
  1380. }
  1381. // --- value references --------------------------------------------------------
  1382. fn flush_value_refs(&mut self, root: Node<'t>) {
  1383. let scopes = std::mem::take(&mut self.value_scopes);
  1384. let mut targets = std::mem::take(&mut self.fs_values);
  1385. let counts = std::mem::take(&mut self.fs_value_counts);
  1386. if std::env::var("CODEGRAPH_VALUE_REFS").as_deref() == Ok("0") {
  1387. return;
  1388. }
  1389. if targets.is_empty() || scopes.is_empty() || util::is_generated_file(self.file_path) {
  1390. return;
  1391. }
  1392. // Shadow prune: count every variable_declarator declaring a target
  1393. // name (field declarators AND method-body/top-level locals); more
  1394. // declarations than file-scope captures → shadowed → dropped.
  1395. let mut decl_counts: HashMap<&str, u32> = HashMap::new();
  1396. let mut dstack: Vec<Node> = vec![root];
  1397. let mut dvisited = 0usize;
  1398. while let Some(n) = dstack.pop() {
  1399. if dvisited >= MAX_VALUE_REF_NODES {
  1400. break;
  1401. }
  1402. dvisited += 1;
  1403. if n.kind() == "variable_declarator" {
  1404. if let Some(first) = n.named_child(0) {
  1405. if first.kind() == "identifier" {
  1406. let nm = self.text(first);
  1407. if targets.contains_key(nm) {
  1408. *decl_counts.entry(nm).or_insert(0) += 1;
  1409. }
  1410. }
  1411. }
  1412. }
  1413. // (property_declaration's bump is structurally null for C# — not ported.)
  1414. for i in 0..n.named_child_count() {
  1415. if let Some(c) = n.named_child(i) {
  1416. dstack.push(c);
  1417. }
  1418. }
  1419. }
  1420. let shadowed: Vec<String> = decl_counts
  1421. .iter()
  1422. .filter(|(nm, c)| **c > counts.get(**nm).copied().unwrap_or(1))
  1423. .map(|(nm, _)| nm.to_string())
  1424. .collect();
  1425. for nm in shadowed {
  1426. targets.remove(&nm);
  1427. }
  1428. if targets.is_empty() {
  1429. return;
  1430. }
  1431. let refs_kind = edge_kind_index("references").unwrap();
  1432. for scope in &scopes {
  1433. // ID-string comparisons, matching the TS side (ids collide).
  1434. let mut seen: HashSet<&str> = HashSet::new();
  1435. let mut stack: Vec<Node> = vec![scope.node];
  1436. let mut visited = 0usize;
  1437. while let Some(n) = stack.pop() {
  1438. if visited >= MAX_VALUE_REF_NODES {
  1439. break;
  1440. }
  1441. visited += 1;
  1442. if matches!(n.kind(), "identifier" | "constant" | "name" | "simple_identifier") {
  1443. let ref_name = self.text(n);
  1444. if let Some(&target_row) = targets.get(ref_name) {
  1445. let target_id = self.node_ids[target_row as usize].as_str();
  1446. if target_id != self.node_ids[scope.row as usize]
  1447. && ref_name != scope.name
  1448. && !seen.contains(&target_id)
  1449. {
  1450. seen.insert(target_id);
  1451. let meta = self.arena.put(r#"{"valueRef":true}"#);
  1452. self.tables.push_edge(&EdgeRow {
  1453. source_idx: scope.row,
  1454. target_idx: target_row,
  1455. kind: refs_kind,
  1456. provenance: 0,
  1457. line: NONE,
  1458. column: NONE,
  1459. metadata_json: meta,
  1460. source_id_str: NONE_STR,
  1461. target_id_str: NONE_STR,
  1462. });
  1463. }
  1464. }
  1465. }
  1466. for i in 0..n.named_child_count() {
  1467. if let Some(c) = n.named_child(i) {
  1468. stack.push(c);
  1469. }
  1470. }
  1471. }
  1472. }
  1473. }
  1474. }
  1475. fn find_anonymous_class_body(node: Node) -> Option<Node> {
  1476. for i in 0..node.named_child_count() {
  1477. if let Some(child) = node.named_child(i) {
  1478. if matches!(child.kind(), "class_body" | "declaration_list") {
  1479. return Some(child);
  1480. }
  1481. }
  1482. }
  1483. None
  1484. }
  1485. /// The `new ns.Foo<T>()` name normalization shared by instantiation /
  1486. /// anonymous-class extraction: strip `<...` from the first `<` (index > 0),
  1487. /// keep the segment after the last `.`/`::`, strip ONE leading `:` or `.`,
  1488. /// trim. (The vbnet paren strip in the TS path is vbnet-gated — inert here.)
  1489. fn strip_generic_and_qualifier(raw: &str) -> String {
  1490. let mut name = raw.to_string();
  1491. if let Some(lt) = name.find('<') {
  1492. if lt > 0 {
  1493. name.truncate(lt);
  1494. }
  1495. }
  1496. let last_dot = name
  1497. .rfind('.')
  1498. .map(|i| i as isize)
  1499. .unwrap_or(-1)
  1500. .max(name.rfind("::").map(|i| i as isize).unwrap_or(-1));
  1501. if last_dot >= 0 {
  1502. name = name[(last_dot as usize + 1)..].to_string();
  1503. if name.starts_with(':') || name.starts_with('.') {
  1504. name.remove(0);
  1505. }
  1506. }
  1507. name.trim().to_string()
  1508. }
  1509. fn opt_str(arena: &mut Arena, s: Option<&str>) -> StrRef {
  1510. match s {
  1511. Some(s) => arena.put(s),
  1512. None => NONE_STR,
  1513. }
  1514. }