go.rs 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232
  1. //! Go extraction — a faithful Rust port of `TreeSitterExtractor`'s Go paths
  2. //! (src/extraction/tree-sitter.ts) plus languages/go.ts.
  3. //!
  4. //! Go's shape quirks, mirrored exactly: methods are top-level with a receiver
  5. //! (qualifiedName override `Recv::name` + a contains edge to the FIRST
  6. //! earlier-in-file struct of that name), structs/interfaces arrive as
  7. //! `type_spec` and classify via the inner type node (struct embedding →
  8. //! extends; interface method_elems become method nodes), composite literals
  9. //! (`pkga.Widget{}`) keep their package qualifier as `instantiates` refs,
  10. //! top-level var/const specs walk their initializers ATTRIBUTED to the
  11. //! declared symbol (#693), 2-hop field chains (`t.conn.Exec`) keep the chain
  12. //! (#1276), and `New().Method()` re-encodes as `New().Method` (#645/#608)
  13. //! only for bare-identifier factories. Files with parse errors defer to wasm.
  14. use crate::buffers::{
  15. build_meta, edge_kind_index, node_kind_index, Arena, BoolFlags, EdgeRow, EmitOut, NodeRow,
  16. RefRow, StrRef, Tables, FLAG_IS_EXPORTED, FUNCTION_REF_CODE, NONE, NONE_STR,
  17. };
  18. use crate::docstring::preceding_docstring;
  19. use crate::ids;
  20. use crate::textutil as util;
  21. use regex::Regex;
  22. use std::collections::{HashMap, HashSet};
  23. use std::sync::OnceLock;
  24. use tree_sitter::{Node, Parser};
  25. const MAX_VALUE_REF_NODES: usize = 20_000;
  26. fn receiver_re() -> &'static Regex {
  27. static RE: OnceLock<Regex> = OnceLock::new();
  28. RE.get_or_init(|| Regex::new(r"\(\s*(?:[A-Za-z_]\w*\s+)?\*?\s*([A-Za-z_]\w*)").unwrap())
  29. }
  30. fn simple_ident_re() -> &'static Regex {
  31. static RE: OnceLock<Regex> = OnceLock::new();
  32. RE.get_or_init(|| Regex::new(r"^[A-Za-z_]\w*$").unwrap())
  33. }
  34. fn go_two_hop_re() -> &'static Regex {
  35. static RE: OnceLock<Regex> = OnceLock::new();
  36. RE.get_or_init(|| Regex::new(r"^[A-Za-z_]\w*\.[A-Za-z_]\w*$").unwrap())
  37. }
  38. fn generic_angle_re() -> &'static Regex {
  39. static RE: OnceLock<Regex> = OnceLock::new();
  40. RE.get_or_init(|| Regex::new(r"<[^>]*>").unwrap())
  41. }
  42. fn bracket_args_re() -> &'static Regex {
  43. static RE: OnceLock<Regex> = OnceLock::new();
  44. RE.get_or_init(|| Regex::new(r"\[[^\]]*\]").unwrap())
  45. }
  46. struct Scope {
  47. row: u32,
  48. kind: &'static str,
  49. name: String,
  50. }
  51. #[derive(Default)]
  52. struct Extra {
  53. docstring: Option<String>,
  54. signature: Option<String>,
  55. is_exported: Option<bool>,
  56. return_type: Option<String>,
  57. qualified_name: Option<String>,
  58. }
  59. struct ValueScope<'t> {
  60. row: u32,
  61. node: Node<'t>,
  62. name: String,
  63. }
  64. struct Cand {
  65. from: u32,
  66. name: String,
  67. line: u32,
  68. column_byte: usize,
  69. row: usize,
  70. }
  71. /// Per-node metadata for the receiver-method owner lookup (mirrors the TS
  72. /// side's scan over `this.nodes` — FIRST match wins, earlier-in-file only).
  73. struct NodeMeta {
  74. kind: &'static str,
  75. name: String,
  76. }
  77. pub struct Walker<'t> {
  78. src: &'t str,
  79. file_path: &'t str,
  80. line_starts: Vec<usize>,
  81. arena: Arena,
  82. tables: Tables,
  83. stack: Vec<Scope>,
  84. nodes_meta: Vec<NodeMeta>,
  85. node_ids: Vec<String>,
  86. defined_fn_names: HashSet<String>,
  87. imported_names: HashSet<String>,
  88. fn_ref_cands: Vec<Cand>,
  89. fs_values: HashMap<String, u32>,
  90. fs_value_counts: HashMap<String, u32>,
  91. value_scopes: Vec<ValueScope<'t>>,
  92. }
  93. pub fn extract(file_path: &str, source: &str) -> Result<EmitOut, String> {
  94. let grammar = crate::langs::grammar_for("go").ok_or("no go grammar")?;
  95. let t0 = std::time::Instant::now();
  96. let mut parser = Parser::new();
  97. parser
  98. .set_language(&grammar)
  99. .map_err(|e| format!("set_language(go) failed: {e}"))?;
  100. let tree = parser
  101. .parse(source, None)
  102. .ok_or_else(|| "parser returned null tree".to_string())?;
  103. if tree.root_node().has_error() {
  104. return Err("defer: parse tree contains errors — wasm recovery is canonical".to_string());
  105. }
  106. let mut w = Walker {
  107. src: source,
  108. file_path,
  109. line_starts: util::line_starts(source),
  110. arena: Arena::default(),
  111. tables: Tables::default(),
  112. stack: Vec::new(),
  113. nodes_meta: Vec::new(),
  114. node_ids: Vec::new(),
  115. defined_fn_names: HashSet::new(),
  116. imported_names: HashSet::new(),
  117. fn_ref_cands: Vec::new(),
  118. fs_values: HashMap::new(),
  119. fs_value_counts: HashMap::new(),
  120. value_scopes: Vec::new(),
  121. };
  122. let line_count = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1;
  123. let base_name = file_path.rsplit(['/', '\\']).next().unwrap_or(file_path);
  124. let mut flags = BoolFlags::default();
  125. flags.set(FLAG_IS_EXPORTED, false);
  126. let file_id = w.arena.put(&ids::file_node_id(file_path));
  127. let name_ref = w.arena.put(base_name);
  128. let qn_ref = w.arena.put(file_path);
  129. w.tables.push_node(&NodeRow {
  130. kind: node_kind_index("file").unwrap(),
  131. visibility: 0,
  132. flags,
  133. start_line: 1,
  134. end_line: line_count,
  135. start_column: 0,
  136. end_column: 0,
  137. name: name_ref,
  138. qualified_name: qn_ref,
  139. id: file_id,
  140. docstring: NONE_STR,
  141. signature: NONE_STR,
  142. decorators: NONE_STR,
  143. type_parameters: NONE_STR,
  144. return_type: NONE_STR,
  145. extra_json: NONE_STR,
  146. });
  147. w.nodes_meta.push(NodeMeta { kind: "file", name: base_name.to_string() });
  148. w.node_ids.push(ids::file_node_id(file_path));
  149. w.stack.push(Scope { row: 0, kind: "file", name: base_name.to_string() });
  150. w.visit_node(tree.root_node());
  151. w.flush_fn_ref_candidates();
  152. w.flush_value_refs(tree.root_node());
  153. w.stack.pop();
  154. let duration_ms = t0.elapsed().as_secs_f64() * 1000.0;
  155. let meta = build_meta(&w.tables, w.arena.len(), NONE_STR, duration_ms);
  156. Ok(EmitOut {
  157. meta,
  158. nodes: w.tables.nodes,
  159. edges: w.tables.edges,
  160. refs: w.tables.refs,
  161. arena: w.arena.into_vec(),
  162. })
  163. }
  164. impl<'t> Walker<'t> {
  165. fn text(&self, node: Node) -> &'t str {
  166. &self.src[node.byte_range()]
  167. }
  168. fn line_of(&self, node: Node) -> u32 {
  169. node.start_position().row as u32 + 1
  170. }
  171. fn col_of(&self, node: Node) -> u32 {
  172. util::col16(self.src, &self.line_starts, node.start_position().row, node.start_byte())
  173. }
  174. fn end_col_of(&self, node: Node) -> u32 {
  175. util::col16(self.src, &self.line_starts, node.end_position().row, node.end_byte())
  176. }
  177. fn top_row(&self) -> u32 {
  178. self.stack.last().map(|s| s.row).unwrap_or(0)
  179. }
  180. fn inside_class_like(&self) -> bool {
  181. self.stack
  182. .last()
  183. .map(|s| matches!(s.kind, "class" | "struct" | "interface" | "trait" | "enum" | "module"))
  184. .unwrap_or(false)
  185. }
  186. fn push_ref_at(&mut self, from_row: u32, name: &str, kind_code: u8, node: Node) {
  187. let name_ref = self.arena.put(name);
  188. self.tables.push_ref(&RefRow {
  189. from_idx: from_row,
  190. kind: kind_code,
  191. line: self.line_of(node),
  192. column: self.col_of(node),
  193. reference_name: name_ref,
  194. candidates: NONE_STR,
  195. from_id_str: NONE_STR,
  196. });
  197. if kind_code == edge_kind_index("imports").unwrap() {
  198. if util::simple_name().is_match(name) {
  199. self.imported_names.insert(name.to_string());
  200. } else if let Some(c) = util::qualified_import().captures(name) {
  201. self.imported_names.insert(c[1].to_string());
  202. }
  203. }
  204. }
  205. fn create_node(&mut self, kind: &'static str, name: &str, node: Node<'t>, extra: Extra) -> Option<u32> {
  206. if name.is_empty() {
  207. return None;
  208. }
  209. let start_line = self.line_of(node);
  210. let id = ids::node_id(self.file_path, kind, name, start_line);
  211. let end_line = node.end_position().row as u32 + 1;
  212. let qualified = extra.qualified_name.unwrap_or_else(|| {
  213. let mut parts: Vec<&str> = Vec::new();
  214. for s in &self.stack {
  215. if s.kind != "file" {
  216. parts.push(&s.name);
  217. }
  218. }
  219. let mut qn = parts.join("::");
  220. if !qn.is_empty() {
  221. qn.push_str("::");
  222. }
  223. qn.push_str(name);
  224. qn
  225. });
  226. let mut flags = BoolFlags::default();
  227. if let Some(v) = extra.is_exported {
  228. flags.set(FLAG_IS_EXPORTED, v);
  229. }
  230. let name_ref = self.arena.put(name);
  231. let qn_ref = self.arena.put(&qualified);
  232. let id_ref = self.arena.put(&id);
  233. let doc_ref = opt_str(&mut self.arena, extra.docstring.as_deref());
  234. let sig_ref = opt_str(&mut self.arena, extra.signature.as_deref());
  235. let ret_ref = opt_str(&mut self.arena, extra.return_type.as_deref());
  236. let row = self.tables.push_node(&NodeRow {
  237. kind: node_kind_index(kind).unwrap(),
  238. visibility: 0,
  239. flags,
  240. start_line,
  241. end_line,
  242. start_column: self.col_of(node),
  243. end_column: self.end_col_of(node),
  244. name: name_ref,
  245. qualified_name: qn_ref,
  246. id: id_ref,
  247. docstring: doc_ref,
  248. signature: sig_ref,
  249. decorators: NONE_STR,
  250. type_parameters: NONE_STR,
  251. return_type: ret_ref,
  252. extra_json: NONE_STR,
  253. });
  254. self.nodes_meta.push(NodeMeta { kind, name: name.to_string() });
  255. self.node_ids.push(id);
  256. let parent_row = self.top_row();
  257. self.tables.push_edge(&EdgeRow {
  258. source_idx: parent_row,
  259. target_idx: row,
  260. kind: edge_kind_index("contains").unwrap(),
  261. provenance: 0,
  262. line: NONE,
  263. column: NONE,
  264. metadata_json: NONE_STR,
  265. source_id_str: NONE_STR,
  266. target_id_str: NONE_STR,
  267. });
  268. if kind == "function" || kind == "method" {
  269. self.defined_fn_names.insert(name.to_string());
  270. }
  271. let target_kind_ok = kind == "constant" || kind == "variable";
  272. if target_kind_ok
  273. && util::utf16_len(name) >= 3
  274. && util::has_upper_or_underscore().is_match(name)
  275. {
  276. let parent_ok = self
  277. .stack
  278. .last()
  279. .map(|s| matches!(s.kind, "file" | "class" | "module" | "struct" | "enum"))
  280. .unwrap_or(false);
  281. if parent_ok {
  282. self.fs_values.insert(name.to_string(), row);
  283. *self.fs_value_counts.entry(name.to_string()).or_insert(0) += 1;
  284. }
  285. }
  286. if matches!(kind, "function" | "method" | "constant" | "variable") {
  287. self.value_scopes.push(ValueScope { row, node, name: name.to_string() });
  288. }
  289. Some(row)
  290. }
  291. fn extract_name(&self, node: Node) -> String {
  292. if let Some(name_node) = node.child_by_field_name("name") {
  293. return self.text(name_node).to_string();
  294. }
  295. for i in 0..node.named_child_count() {
  296. if let Some(c) = node.named_child(i) {
  297. if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") {
  298. return self.text(c).to_string();
  299. }
  300. }
  301. }
  302. "<anonymous>".to_string()
  303. }
  304. /// goExtractor.getSignature: params + ' ' + result.
  305. fn signature_of(&self, node: Node) -> Option<String> {
  306. let params = node.child_by_field_name("parameters")?;
  307. let mut sig = self.text(params).to_string();
  308. if let Some(result) = node.child_by_field_name("result") {
  309. sig.push(' ');
  310. sig.push_str(self.text(result));
  311. }
  312. Some(sig)
  313. }
  314. /// goExtractor.isExported: uppercase first letter of the name field.
  315. fn is_exported(&self, node: Node) -> bool {
  316. if let Some(name_node) = node.child_by_field_name("name") {
  317. let text = self.text(name_node);
  318. return text.as_bytes().first().map(|b| b.is_ascii_uppercase()).unwrap_or(false);
  319. }
  320. false
  321. }
  322. /// extractGoReturnType (languages/go.ts).
  323. fn return_type_of(&self, node: Node) -> Option<String> {
  324. let mut result = node.child_by_field_name("result")?;
  325. if result.kind() == "parameter_list" {
  326. let first = (0..result.named_child_count())
  327. .filter_map(|i| result.named_child(i))
  328. .find(|c| c.kind() == "parameter_declaration")?;
  329. result = first.child_by_field_name("type").unwrap_or(first);
  330. }
  331. if result.kind() == "pointer_type" {
  332. result = (0..result.named_child_count())
  333. .filter_map(|i| result.named_child(i))
  334. .find(|c| matches!(c.kind(), "type_identifier" | "qualified_type" | "generic_type"))
  335. .unwrap_or(result);
  336. }
  337. let text = self.text(result).trim();
  338. let text = text.strip_prefix('*').unwrap_or(text);
  339. let text = generic_angle_re().replace_all(text, "");
  340. let text = bracket_args_re().replace_all(&text, "");
  341. let last = text.rsplit('.').next().unwrap_or("").trim().to_string();
  342. if last.is_empty() || !simple_ident_re().is_match(&last) {
  343. return None;
  344. }
  345. Some(last)
  346. }
  347. /// goExtractor.getReceiverType: the regex over the receiver's text.
  348. fn receiver_type_of(&self, node: Node) -> Option<String> {
  349. let receiver = node.child_by_field_name("receiver")?;
  350. let text = self.text(receiver);
  351. receiver_re().captures(text).map(|c| c[1].to_string())
  352. }
  353. // --- visitNode ------------------------------------------------------------
  354. fn visit_node(&mut self, node: Node<'t>) {
  355. stack_guard!();
  356. let kind = node.kind();
  357. let mut skip_children = false;
  358. self.maybe_capture_fn_refs(node);
  359. if kind == "function_declaration" {
  360. self.extract_function(node);
  361. skip_children = true;
  362. } else if kind == "method_declaration" {
  363. self.extract_method(node);
  364. skip_children = true;
  365. } else if kind == "type_spec" {
  366. skip_children = self.extract_type_alias(node);
  367. } else if matches!(kind, "var_declaration" | "short_var_declaration" | "const_declaration")
  368. && !self.inside_class_like()
  369. {
  370. self.extract_variable(node);
  371. self.scan_fn_ref_subtree(node, 0);
  372. skip_children = true;
  373. } else if kind == "import_declaration" {
  374. self.extract_import(node);
  375. } else if kind == "call_expression" {
  376. self.extract_call(node);
  377. } else if kind == "composite_literal" {
  378. self.extract_instantiation(node);
  379. }
  380. if !skip_children {
  381. for i in 0..node.named_child_count() {
  382. if let Some(c) = node.named_child(i) {
  383. self.visit_node(c);
  384. }
  385. }
  386. }
  387. }
  388. fn visit_function_body(&mut self, body: Node<'t>) {
  389. stack_guard!();
  390. self.visit_for_calls_and_structure(body);
  391. }
  392. fn visit_for_calls_and_structure(&mut self, node: Node<'t>) {
  393. stack_guard!();
  394. let kind = node.kind();
  395. self.maybe_capture_fn_refs(node);
  396. if kind == "call_expression" {
  397. self.extract_call(node);
  398. } else if kind == "composite_literal" {
  399. self.extract_instantiation(node);
  400. }
  401. if kind == "function_declaration" {
  402. let name = self.extract_name(node);
  403. if name != "<anonymous>" {
  404. self.extract_function(node);
  405. return;
  406. }
  407. }
  408. for i in 0..node.named_child_count() {
  409. if let Some(c) = node.named_child(i) {
  410. self.visit_for_calls_and_structure(c);
  411. }
  412. }
  413. }
  414. // --- extractors --------------------------------------------------------------
  415. fn extract_function(&mut self, node: Node<'t>) {
  416. stack_guard!();
  417. // (getReceiverType only matches method_declaration's receiver field —
  418. // function_declaration has none, so no reroute happens here)
  419. let name = self.extract_name(node);
  420. if name == "<anonymous>" {
  421. if let Some(body) = node.child_by_field_name("body") {
  422. self.visit_function_body(body);
  423. }
  424. return;
  425. }
  426. let extra = Extra {
  427. docstring: preceding_docstring(node, self.src),
  428. signature: self.signature_of(node),
  429. is_exported: Some(self.is_exported(node)),
  430. return_type: self.return_type_of(node),
  431. ..Extra::default()
  432. };
  433. let Some(row) = self.create_node("function", &name, node, extra) else { return };
  434. self.extract_type_annotations(node, row);
  435. self.stack.push(Scope { row, kind: "function", name });
  436. if let Some(body) = node.child_by_field_name("body") {
  437. self.visit_function_body(body);
  438. }
  439. self.stack.pop();
  440. }
  441. fn extract_method(&mut self, node: Node<'t>) {
  442. // methodsAreTopLevel: always a method. Receiver-qualified name +
  443. // a contains edge from the FIRST earlier struct/class/enum/trait
  444. // node of the receiver's name (mirrors the this.nodes.find scan).
  445. let receiver_type = self.receiver_type_of(node);
  446. let name = self.extract_name(node);
  447. let extra = Extra {
  448. docstring: preceding_docstring(node, self.src),
  449. signature: self.signature_of(node),
  450. return_type: self.return_type_of(node),
  451. qualified_name: receiver_type.as_ref().map(|r| format!("{r}::{name}")),
  452. ..Extra::default() // extractMethod passes no isExported
  453. };
  454. let Some(row) = self.create_node("method", &name, node, extra) else { return };
  455. if let Some(receiver_type) = &receiver_type {
  456. if !self.inside_class_like() {
  457. let owner_row = self
  458. .nodes_meta
  459. .iter()
  460. .position(|m| {
  461. m.name == *receiver_type
  462. && matches!(m.kind, "struct" | "class" | "enum" | "trait")
  463. })
  464. .map(|i| i as u32);
  465. if let Some(owner_row) = owner_row {
  466. self.tables.push_edge(&EdgeRow {
  467. source_idx: owner_row,
  468. target_idx: row,
  469. kind: edge_kind_index("contains").unwrap(),
  470. provenance: 0,
  471. line: NONE,
  472. column: NONE,
  473. metadata_json: NONE_STR,
  474. source_id_str: NONE_STR,
  475. target_id_str: NONE_STR,
  476. });
  477. }
  478. }
  479. }
  480. self.extract_type_annotations(node, row);
  481. self.stack.push(Scope { row, kind: "method", name });
  482. if let Some(body) = node.child_by_field_name("body") {
  483. self.visit_function_body(body);
  484. }
  485. self.stack.pop();
  486. }
  487. /// extractTypeAlias for Go: type_spec → struct / interface / plain alias.
  488. fn extract_type_alias(&mut self, node: Node<'t>) -> bool {
  489. stack_guard!();
  490. let name = self.extract_name(node);
  491. if name == "<anonymous>" {
  492. return false;
  493. }
  494. let docstring = preceding_docstring(node, self.src);
  495. let is_exported = Some(self.is_exported(node));
  496. let type_child = node.child_by_field_name("type");
  497. let resolved = type_child.map(|t| t.kind());
  498. if resolved == Some("struct_type") {
  499. let Some(row) = self.create_node(
  500. "struct",
  501. &name,
  502. node,
  503. Extra { docstring, is_exported, ..Extra::default() },
  504. ) else {
  505. return true;
  506. };
  507. self.stack.push(Scope { row, kind: "struct", name });
  508. if let Some(type_child) = type_child {
  509. // Struct embedding → extends (field_declaration without a
  510. // field_identifier), reached via the inheritance recursion.
  511. self.extract_inheritance(type_child, row);
  512. let body = type_child.child_by_field_name("body").unwrap_or(type_child);
  513. for i in 0..body.named_child_count() {
  514. if let Some(c) = body.named_child(i) {
  515. self.visit_node(c);
  516. }
  517. }
  518. }
  519. self.stack.pop();
  520. return true;
  521. }
  522. if resolved == Some("interface_type") {
  523. let Some(row) = self.create_node(
  524. "interface",
  525. &name,
  526. node,
  527. Extra { docstring, is_exported, ..Extra::default() },
  528. ) else {
  529. return true;
  530. };
  531. if let Some(type_child) = type_child {
  532. self.extract_inheritance(type_child, row);
  533. self.extract_go_interface_methods(type_child, row, &name);
  534. }
  535. return true;
  536. }
  537. self.create_node(
  538. "type_alias",
  539. &name,
  540. node,
  541. Extra { docstring, is_exported, ..Extra::default() },
  542. );
  543. // (go type_spec has no `value` field — no type-ref walk; TS/tsx member
  544. // extraction is TS-family-only)
  545. false
  546. }
  547. /// extractGoInterfaceMethods: method_elem/method_spec → method nodes.
  548. fn extract_go_interface_methods(&mut self, interface_type: Node<'t>, iface_row: u32, iface_name: &str) {
  549. self.stack.push(Scope { row: iface_row, kind: "interface", name: iface_name.to_string() });
  550. for i in 0..interface_type.named_child_count() {
  551. let Some(m) = interface_type.named_child(i) else { continue };
  552. if !matches!(m.kind(), "method_elem" | "method_spec") {
  553. continue;
  554. }
  555. let name_node = m.child_by_field_name("name").or_else(|| m.named_child(0));
  556. let Some(name_node) = name_node else { continue };
  557. let mname = self.text(name_node).to_string();
  558. if !mname.is_empty() {
  559. let signature = self.signature_of(m);
  560. self.create_node("method", &mname, m, Extra { signature, ..Extra::default() });
  561. }
  562. }
  563. self.stack.pop();
  564. }
  565. /// extractVariable's Go branch: var/const specs + short_var_declaration.
  566. fn extract_variable(&mut self, node: Node<'t>) {
  567. let docstring = preceding_docstring(node, self.src);
  568. let is_const_decl = node.kind() == "const_declaration";
  569. for i in 0..node.named_child_count() {
  570. let Some(spec) = node.named_child(i) else { continue };
  571. if !matches!(spec.kind(), "var_spec" | "const_spec") {
  572. continue;
  573. }
  574. let mut var_row: Option<u32> = None;
  575. if let Some(name_node) = spec.named_child(0) {
  576. if name_node.kind() == "identifier" {
  577. let name = self.text(name_node).to_string();
  578. let value_node = if spec.named_child_count() > 1 {
  579. spec.named_child(spec.named_child_count() - 1)
  580. } else {
  581. None
  582. };
  583. let signature = value_node.map(|v| util::init_signature(self.text(v)));
  584. var_row = self.create_node(
  585. if is_const_decl { "constant" } else { "variable" },
  586. &name,
  587. spec,
  588. Extra { docstring: docstring.clone(), signature, ..Extra::default() },
  589. );
  590. }
  591. }
  592. // Walk the initializer ATTRIBUTED to the declared symbol (#693).
  593. if let Some(value_field) = spec.child_by_field_name("value") {
  594. if let Some(row) = var_row {
  595. let name = self.nodes_meta[row as usize].name.clone();
  596. self.stack.push(Scope { row, kind: "variable", name });
  597. self.visit_function_body(value_field);
  598. self.stack.pop();
  599. } else {
  600. self.visit_function_body(value_field);
  601. }
  602. }
  603. }
  604. if node.kind() == "short_var_declaration" {
  605. let left = node.child_by_field_name("left");
  606. let right = node.child_by_field_name("right");
  607. if let Some(left) = left {
  608. let identifiers: Vec<Node> = if left.kind() == "expression_list" {
  609. (0..left.named_child_count())
  610. .filter_map(|i| left.named_child(i))
  611. .filter(|c| c.kind() == "identifier")
  612. .collect()
  613. } else {
  614. vec![left]
  615. };
  616. for id in identifiers {
  617. let name = self.text(id).to_string();
  618. let signature = right.map(|r| util::init_signature(self.text(r)));
  619. self.create_node(
  620. "variable",
  621. &name,
  622. node,
  623. Extra { docstring: docstring.clone(), signature, ..Extra::default() },
  624. );
  625. }
  626. }
  627. }
  628. }
  629. /// extractImport's Go branch: one import node + ref per import_spec.
  630. fn extract_import(&mut self, node: Node<'t>) {
  631. let parent = self.top_row();
  632. let imports_kind = edge_kind_index("imports").unwrap();
  633. let mut handle_spec = |w: &mut Self, spec: Node<'t>| {
  634. let lit = (0..spec.named_child_count())
  635. .filter_map(|i| spec.named_child(i))
  636. .find(|c| c.kind() == "interpreted_string_literal");
  637. let Some(lit) = lit else { return };
  638. let import_path: String = w
  639. .text(lit)
  640. .chars()
  641. .filter(|c| *c != '\'' && *c != '"')
  642. .collect();
  643. if import_path.is_empty() {
  644. return;
  645. }
  646. let signature = w.text(spec).trim().to_string();
  647. w.create_node(
  648. "import",
  649. &import_path,
  650. spec,
  651. Extra { signature: Some(signature), ..Extra::default() },
  652. );
  653. w.push_ref_at(parent, &import_path, imports_kind, spec);
  654. };
  655. let spec_list = (0..node.named_child_count())
  656. .filter_map(|i| node.named_child(i))
  657. .find(|c| c.kind() == "import_spec_list");
  658. if let Some(list) = spec_list {
  659. for i in 0..list.named_child_count() {
  660. if let Some(spec) = list.named_child(i) {
  661. if spec.kind() == "import_spec" {
  662. handle_spec(self, spec);
  663. }
  664. }
  665. }
  666. } else {
  667. let spec = (0..node.named_child_count())
  668. .filter_map(|i| node.named_child(i))
  669. .find(|c| c.kind() == "import_spec");
  670. if let Some(spec) = spec {
  671. handle_spec(self, spec);
  672. }
  673. }
  674. }
  675. /// extractCall — Go's generic-tail paths (selector_expression callees).
  676. fn extract_call(&mut self, node: Node<'t>) {
  677. if self.stack.is_empty() {
  678. return;
  679. }
  680. let func = node
  681. .child_by_field_name("function")
  682. .or_else(|| node.named_child(0));
  683. let mut callee_name = String::new();
  684. if let Some(func) = func {
  685. if func.kind() == "selector_expression" {
  686. let property = func
  687. .child_by_field_name("property")
  688. .or_else(|| func.child_by_field_name("field"));
  689. if let Some(property) = property {
  690. let method_name = self.text(property);
  691. let receiver = func
  692. .child_by_field_name("object")
  693. .or_else(|| func.child_by_field_name("operand"))
  694. .or_else(|| func.child_by_field_name("argument"))
  695. .or_else(|| func.named_child(0));
  696. if let Some(r) = receiver {
  697. if is_literal_receiver(r.kind()) {
  698. return;
  699. }
  700. }
  701. if let Some(r) = receiver {
  702. match r.kind() {
  703. "identifier" | "simple_identifier" | "field_identifier" => {
  704. let receiver_name = self.text(r);
  705. if !matches!(receiver_name, "self" | "this" | "cls" | "super") {
  706. callee_name = format!("{receiver_name}.{method_name}");
  707. } else {
  708. callee_name = method_name.to_string();
  709. }
  710. }
  711. "call_expression" => {
  712. // Bare package-level factory chain `New().Method()`
  713. // re-encodes; instance chains keep the bare name.
  714. let inner_fn = r.child_by_field_name("function");
  715. let reencode =
  716. inner_fn.map(|f| f.kind() == "identifier").unwrap_or(false);
  717. if reencode {
  718. let inner: String = self
  719. .text(inner_fn.unwrap())
  720. .replace("->", ".")
  721. .chars()
  722. .filter(|c| !c.is_whitespace())
  723. .collect();
  724. callee_name = format!("{inner}().{method_name}");
  725. } else {
  726. callee_name = method_name.to_string();
  727. }
  728. }
  729. "selector_expression" => {
  730. // 2-hop field chain `t.conn.Exec` (#1276).
  731. let chain: String = self
  732. .text(r)
  733. .chars()
  734. .filter(|c| !c.is_whitespace())
  735. .collect();
  736. if go_two_hop_re().is_match(&chain) {
  737. callee_name = format!("{chain}.{method_name}");
  738. } else {
  739. callee_name = method_name.to_string();
  740. }
  741. }
  742. _ => {
  743. callee_name = method_name.to_string();
  744. }
  745. }
  746. } else {
  747. callee_name = method_name.to_string();
  748. }
  749. }
  750. } else {
  751. callee_name = self.text(func).to_string();
  752. }
  753. }
  754. if !callee_name.is_empty() {
  755. // `(*T)(x)` conversions normalize to `T`.
  756. if let Some(c) = util::paren_conversion().captures(&callee_name) {
  757. callee_name = c[1].to_string();
  758. }
  759. let from = self.top_row();
  760. self.push_ref_at(from, &callee_name.clone(), edge_kind_index("calls").unwrap(), node);
  761. }
  762. }
  763. /// extractInstantiation's composite_literal branch: named struct types
  764. /// only; the package qualifier is KEPT.
  765. fn extract_instantiation(&mut self, node: Node<'t>) {
  766. if self.stack.is_empty() {
  767. return;
  768. }
  769. let ctor = node
  770. .child_by_field_name("constructor")
  771. .or_else(|| node.child_by_field_name("type"))
  772. .or_else(|| node.child_by_field_name("name"))
  773. .or_else(|| node.named_child(0));
  774. let Some(ctor) = ctor else { return };
  775. if !matches!(ctor.kind(), "type_identifier" | "qualified_type") {
  776. return;
  777. }
  778. let mut go_type = self.text(ctor).trim().to_string();
  779. if let Some(br) = go_type.find('[') {
  780. if br > 0 {
  781. go_type.truncate(br);
  782. go_type = go_type.trim().to_string();
  783. }
  784. }
  785. if !go_type.is_empty() {
  786. let from = self.top_row();
  787. self.push_ref_at(from, &go_type, edge_kind_index("instantiates").unwrap(), node);
  788. }
  789. }
  790. /// extractInheritance — the Go branches: interface embedding
  791. /// (constraint_elem) and struct embedding (field_declaration without a
  792. /// field_identifier), plus the field_declaration_list recursion.
  793. fn extract_inheritance(&mut self, node: Node<'t>, class_row: u32) {
  794. stack_guard!();
  795. let extends_kind = edge_kind_index("extends").unwrap();
  796. for i in 0..node.named_child_count() {
  797. let Some(child) = node.named_child(i) else { continue };
  798. match child.kind() {
  799. "constraint_elem" => {
  800. let type_id = (0..child.named_child_count())
  801. .filter_map(|j| child.named_child(j))
  802. .find(|c| c.kind() == "type_identifier");
  803. if let Some(type_id) = type_id {
  804. let name = self.text(type_id).to_string();
  805. self.push_ref_at(class_row, &name, extends_kind, type_id);
  806. }
  807. }
  808. "field_declaration" => {
  809. let has_field_identifier = (0..child.named_child_count())
  810. .filter_map(|j| child.named_child(j))
  811. .any(|c| c.kind() == "field_identifier");
  812. if !has_field_identifier {
  813. let type_id = (0..child.named_child_count())
  814. .filter_map(|j| child.named_child(j))
  815. .find(|c| c.kind() == "type_identifier");
  816. if let Some(type_id) = type_id {
  817. let name = self.text(type_id).to_string();
  818. self.push_ref_at(class_row, &name, extends_kind, type_id);
  819. }
  820. }
  821. }
  822. "field_declaration_list" | "class_heritage" => {
  823. self.extract_inheritance(child, class_row);
  824. }
  825. _ => {}
  826. }
  827. }
  828. }
  829. /// extractTypeAnnotations — Go's returnField is `result`.
  830. fn extract_type_annotations(&mut self, node: Node<'t>, from_row: u32) {
  831. if let Some(params) = node.child_by_field_name("parameters") {
  832. self.extract_type_refs_from_subtree(params, from_row);
  833. }
  834. if let Some(ret) = node.child_by_field_name("result") {
  835. self.extract_type_refs_from_subtree(ret, from_row);
  836. }
  837. let type_annotation = (0..node.named_child_count())
  838. .filter_map(|i| node.named_child(i))
  839. .find(|c| c.kind() == "type_annotation");
  840. if let Some(ta) = type_annotation {
  841. self.extract_type_refs_from_subtree(ta, from_row);
  842. }
  843. }
  844. fn extract_type_refs_from_subtree(&mut self, node: Node<'t>, from_row: u32) {
  845. stack_guard!();
  846. if node.kind() == "type_identifier" {
  847. let type_name = self.text(node).to_string();
  848. if !type_name.is_empty() && !is_builtin_type(&type_name) {
  849. self.push_ref_at(from_row, &type_name, edge_kind_index("references").unwrap(), node);
  850. }
  851. return;
  852. }
  853. for i in 0..node.named_child_count() {
  854. if let Some(c) = node.named_child(i) {
  855. self.extract_type_refs_from_subtree(c, from_row);
  856. }
  857. }
  858. }
  859. // --- fn refs (GO_SPEC, with the literal_element/expression_list layers) --------
  860. fn maybe_capture_fn_refs(&mut self, node: Node<'t>) {
  861. let (mode, field): (&str, &str) = match node.kind() {
  862. "argument_list" => ("args", ""),
  863. "assignment_statement" => ("rhs", "right"),
  864. "short_var_declaration" => ("rhs", "right"),
  865. "var_spec" => ("varinit", "value"),
  866. "keyed_element" => ("value", ""), // value = LAST named child
  867. "literal_value" => ("list", ""),
  868. _ => return,
  869. };
  870. if self.stack.is_empty() {
  871. return;
  872. }
  873. let from = self.top_row();
  874. let mut values: Vec<Node> = Vec::new();
  875. match mode {
  876. "args" | "list" => {
  877. for i in 0..node.named_child_count() {
  878. if let Some(c) = node.named_child(i) {
  879. values.push(c);
  880. }
  881. }
  882. }
  883. "rhs" => {
  884. if let Some(rhs) = node.child_by_field_name(field) {
  885. let lhs_text = node
  886. .child_by_field_name("left")
  887. .map(|l| self.text(l))
  888. .unwrap_or("");
  889. let lhs_last = util::lhs_last_name()
  890. .captures(lhs_text)
  891. .and_then(|c| c.get(1))
  892. .map(|m| m.as_str());
  893. if !(lhs_last.is_some() && lhs_last == Some(self.text(rhs).trim())) {
  894. values.push(rhs);
  895. }
  896. }
  897. }
  898. "value" => {
  899. let v = node
  900. .child_by_field_name("value")
  901. .or_else(|| {
  902. if node.named_child_count() > 0 {
  903. node.named_child(node.named_child_count() - 1)
  904. } else {
  905. None
  906. }
  907. });
  908. if let Some(v) = v {
  909. values.push(v);
  910. }
  911. }
  912. _ => {
  913. // varinit — Go var_spec names are plain identifiers (no
  914. // destructuring patterns to skip).
  915. if let Some(v) = node.child_by_field_name(field) {
  916. values.push(v);
  917. }
  918. }
  919. }
  920. for v in values {
  921. self.normalize_fn_ref_value(v, from, 0);
  922. }
  923. }
  924. /// normalizeValue with GO_SPEC's transparent layers (literal_element,
  925. /// expression_list — both fan out to named children).
  926. fn normalize_fn_ref_value(&mut self, v: Node<'t>, from: u32, depth: u32) {
  927. stack_guard!();
  928. if depth > 4 {
  929. return;
  930. }
  931. match v.kind() {
  932. "identifier" => {
  933. let name = self.text(v).to_string();
  934. if name.is_empty() || is_stoplisted(&name) {
  935. return;
  936. }
  937. let p = v.start_position();
  938. self.fn_ref_cands.push(Cand {
  939. from,
  940. name,
  941. line: p.row as u32 + 1,
  942. column_byte: v.start_byte(),
  943. row: p.row,
  944. });
  945. }
  946. "literal_element" | "expression_list" => {
  947. for i in 0..v.named_child_count() {
  948. if let Some(c) = v.named_child(i) {
  949. self.normalize_fn_ref_value(c, from, depth + 1);
  950. }
  951. }
  952. }
  953. _ => {}
  954. }
  955. }
  956. fn scan_fn_ref_subtree(&mut self, node: Node<'t>, depth: u32) {
  957. stack_guard!();
  958. if depth > 12 {
  959. return;
  960. }
  961. if depth > 0
  962. && matches!(
  963. node.kind(),
  964. "function_declaration" | "arrow_function" | "function_expression"
  965. | "lambda_literal" | "lambda_expression"
  966. )
  967. {
  968. return;
  969. }
  970. self.maybe_capture_fn_refs(node);
  971. for i in 0..node.named_child_count() {
  972. if let Some(c) = node.named_child(i) {
  973. self.scan_fn_ref_subtree(c, depth + 1);
  974. }
  975. }
  976. }
  977. fn flush_fn_ref_candidates(&mut self) {
  978. let cands = std::mem::take(&mut self.fn_ref_cands);
  979. if cands.is_empty() || util::is_generated_file(self.file_path) {
  980. return;
  981. }
  982. let mut seen: HashSet<(String, String)> = HashSet::new();
  983. for c in cands {
  984. if !c.name.starts_with("this.")
  985. && !c.name.contains("::")
  986. && !self.defined_fn_names.contains(&c.name)
  987. && !self.imported_names.contains(&c.name)
  988. {
  989. continue;
  990. }
  991. if !seen.insert((self.node_ids[c.from as usize].clone(), c.name.clone())) {
  992. continue;
  993. }
  994. let column = util::col16(self.src, &self.line_starts, c.row, c.column_byte);
  995. let name_ref = self.arena.put(&c.name);
  996. self.tables.push_ref(&RefRow {
  997. from_idx: c.from,
  998. kind: FUNCTION_REF_CODE,
  999. line: c.line,
  1000. column,
  1001. reference_name: name_ref,
  1002. candidates: NONE_STR,
  1003. from_id_str: NONE_STR,
  1004. });
  1005. }
  1006. }
  1007. // --- value refs -------------------------------------------------------------------
  1008. fn flush_value_refs(&mut self, root: Node<'t>) {
  1009. let scopes = std::mem::take(&mut self.value_scopes);
  1010. let mut targets = std::mem::take(&mut self.fs_values);
  1011. let counts = std::mem::take(&mut self.fs_value_counts);
  1012. if std::env::var("CODEGRAPH_VALUE_REFS").as_deref() == Ok("0") {
  1013. return;
  1014. }
  1015. if targets.is_empty() || scopes.is_empty() || util::is_generated_file(self.file_path) {
  1016. return;
  1017. }
  1018. // Shadow prune — Go declarator shapes: const_spec/var_spec (name =
  1019. // first child) and short_var_declaration (left / expression_list).
  1020. let mut decl_counts: HashMap<&str, u32> = HashMap::new();
  1021. let mut bump = |decl_counts: &mut HashMap<&'t str, u32>, name_node: Option<Node<'t>>, src: &'t str, targets: &HashMap<String, u32>| {
  1022. if let Some(n) = name_node {
  1023. if matches!(n.kind(), "identifier" | "simple_identifier") {
  1024. let nm = &src[n.byte_range()];
  1025. if targets.contains_key(nm) {
  1026. *decl_counts.entry(nm).or_insert(0) += 1;
  1027. }
  1028. }
  1029. }
  1030. };
  1031. let mut dstack: Vec<Node> = vec![root];
  1032. let mut dvisited = 0usize;
  1033. while let Some(n) = dstack.pop() {
  1034. if dvisited >= MAX_VALUE_REF_NODES {
  1035. break;
  1036. }
  1037. dvisited += 1;
  1038. match n.kind() {
  1039. "const_spec" | "var_spec" => bump(&mut decl_counts, n.named_child(0), self.src, &targets),
  1040. "short_var_declaration" => {
  1041. let left = n
  1042. .child_by_field_name("left")
  1043. .or_else(|| n.child_by_field_name("pattern"))
  1044. .or_else(|| n.named_child(0));
  1045. if let Some(left) = left {
  1046. if left.kind() == "identifier" {
  1047. bump(&mut decl_counts, Some(left), self.src, &targets);
  1048. } else {
  1049. for i in 0..left.named_child_count() {
  1050. bump(&mut decl_counts, left.named_child(i), self.src, &targets);
  1051. }
  1052. }
  1053. }
  1054. }
  1055. _ => {}
  1056. }
  1057. for i in 0..n.named_child_count() {
  1058. if let Some(c) = n.named_child(i) {
  1059. dstack.push(c);
  1060. }
  1061. }
  1062. }
  1063. let shadowed: Vec<String> = decl_counts
  1064. .iter()
  1065. .filter(|(nm, c)| **c > counts.get(**nm).copied().unwrap_or(1))
  1066. .map(|(nm, _)| nm.to_string())
  1067. .collect();
  1068. for nm in shadowed {
  1069. targets.remove(&nm);
  1070. }
  1071. if targets.is_empty() {
  1072. return;
  1073. }
  1074. let refs_kind = edge_kind_index("references").unwrap();
  1075. for scope in &scopes {
  1076. let mut seen: HashSet<&str> = HashSet::new();
  1077. let mut stack: Vec<Node> = vec![scope.node];
  1078. let mut visited = 0usize;
  1079. while let Some(n) = stack.pop() {
  1080. if visited >= MAX_VALUE_REF_NODES {
  1081. break;
  1082. }
  1083. visited += 1;
  1084. if matches!(n.kind(), "identifier" | "constant" | "name" | "simple_identifier") {
  1085. let ref_name = self.text(n);
  1086. if let Some(&target_row) = targets.get(ref_name) {
  1087. let target_id = self.node_ids[target_row as usize].as_str();
  1088. if target_id != self.node_ids[scope.row as usize]
  1089. && ref_name != scope.name
  1090. && !seen.contains(&target_id)
  1091. {
  1092. seen.insert(target_id);
  1093. let meta = self.arena.put(r#"{"valueRef":true}"#);
  1094. self.tables.push_edge(&EdgeRow {
  1095. source_idx: scope.row,
  1096. target_idx: target_row,
  1097. kind: refs_kind,
  1098. provenance: 0,
  1099. line: NONE,
  1100. column: NONE,
  1101. metadata_json: meta,
  1102. source_id_str: NONE_STR,
  1103. target_id_str: NONE_STR,
  1104. });
  1105. }
  1106. }
  1107. }
  1108. for i in 0..n.named_child_count() {
  1109. if let Some(c) = n.named_child(i) {
  1110. stack.push(c);
  1111. }
  1112. }
  1113. }
  1114. }
  1115. }
  1116. }
  1117. fn is_stoplisted(name: &str) -> bool {
  1118. matches!(
  1119. name,
  1120. "this" | "self" | "super" | "null" | "nil" | "true" | "false" | "undefined" | "new"
  1121. | "NULL" | "nullptr" | "None"
  1122. )
  1123. }
  1124. fn is_literal_receiver(kind: &str) -> bool {
  1125. matches!(
  1126. kind,
  1127. "string" | "string_literal" | "interpreted_string_literal" | "raw_string_literal"
  1128. | "template_string" | "concatenated_string" | "formatted_string" | "f_string"
  1129. | "line_string_literal" | "string_content" | "heredoc_body"
  1130. | "number" | "number_literal" | "integer" | "integer_literal" | "float"
  1131. | "float_literal" | "int_literal" | "decimal_integer_literal" | "real_literal"
  1132. | "char_literal" | "character_literal" | "rune_literal" | "regex" | "regex_literal"
  1133. | "true" | "false" | "boolean_literal" | "bool_literal" | "none" | "null" | "nil"
  1134. | "null_literal" | "undefined"
  1135. | "list" | "list_literal" | "array" | "array_literal" | "array_creation_expression"
  1136. | "dictionary" | "dict_literal" | "object" | "tuple" | "set"
  1137. )
  1138. }
  1139. /// BUILTIN_TYPES (shared table).
  1140. fn is_builtin_type(name: &str) -> bool {
  1141. matches!(
  1142. name,
  1143. "string" | "number" | "boolean" | "void" | "null" | "undefined" | "never" | "any"
  1144. | "unknown" | "object" | "symbol" | "bigint" | "true" | "false"
  1145. | "str" | "bool" | "i8" | "i16" | "i32" | "i64" | "i128" | "isize"
  1146. | "u8" | "u16" | "u32" | "u64" | "u128" | "usize" | "f32" | "f64" | "char"
  1147. | "int" | "long" | "short" | "byte" | "float" | "double"
  1148. | "int8" | "int16" | "int32" | "int64" | "uint8" | "uint16" | "uint32" | "uint64"
  1149. | "float32" | "float64" | "complex64" | "complex128" | "rune" | "error"
  1150. | "Int" | "Long" | "Short" | "Byte" | "Float" | "Double" | "Boolean" | "Char"
  1151. | "Unit" | "String" | "Any" | "AnyRef" | "AnyVal" | "Nothing" | "Null"
  1152. )
  1153. }
  1154. fn opt_str(arena: &mut Arena, s: Option<&str>) -> StrRef {
  1155. match s {
  1156. Some(s) => arena.put(s),
  1157. None => NONE_STR,
  1158. }
  1159. }