go.rs 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223
  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. let kind = node.kind();
  356. let mut skip_children = false;
  357. self.maybe_capture_fn_refs(node);
  358. if kind == "function_declaration" {
  359. self.extract_function(node);
  360. skip_children = true;
  361. } else if kind == "method_declaration" {
  362. self.extract_method(node);
  363. skip_children = true;
  364. } else if kind == "type_spec" {
  365. skip_children = self.extract_type_alias(node);
  366. } else if matches!(kind, "var_declaration" | "short_var_declaration" | "const_declaration")
  367. && !self.inside_class_like()
  368. {
  369. self.extract_variable(node);
  370. self.scan_fn_ref_subtree(node, 0);
  371. skip_children = true;
  372. } else if kind == "import_declaration" {
  373. self.extract_import(node);
  374. } else if kind == "call_expression" {
  375. self.extract_call(node);
  376. } else if kind == "composite_literal" {
  377. self.extract_instantiation(node);
  378. }
  379. if !skip_children {
  380. for i in 0..node.named_child_count() {
  381. if let Some(c) = node.named_child(i) {
  382. self.visit_node(c);
  383. }
  384. }
  385. }
  386. }
  387. fn visit_function_body(&mut self, body: Node<'t>) {
  388. self.visit_for_calls_and_structure(body);
  389. }
  390. fn visit_for_calls_and_structure(&mut self, node: Node<'t>) {
  391. let kind = node.kind();
  392. self.maybe_capture_fn_refs(node);
  393. if kind == "call_expression" {
  394. self.extract_call(node);
  395. } else if kind == "composite_literal" {
  396. self.extract_instantiation(node);
  397. }
  398. if kind == "function_declaration" {
  399. let name = self.extract_name(node);
  400. if name != "<anonymous>" {
  401. self.extract_function(node);
  402. return;
  403. }
  404. }
  405. for i in 0..node.named_child_count() {
  406. if let Some(c) = node.named_child(i) {
  407. self.visit_for_calls_and_structure(c);
  408. }
  409. }
  410. }
  411. // --- extractors --------------------------------------------------------------
  412. fn extract_function(&mut self, node: Node<'t>) {
  413. // (getReceiverType only matches method_declaration's receiver field —
  414. // function_declaration has none, so no reroute happens here)
  415. let name = self.extract_name(node);
  416. if name == "<anonymous>" {
  417. if let Some(body) = node.child_by_field_name("body") {
  418. self.visit_function_body(body);
  419. }
  420. return;
  421. }
  422. let extra = Extra {
  423. docstring: preceding_docstring(node, self.src),
  424. signature: self.signature_of(node),
  425. is_exported: Some(self.is_exported(node)),
  426. return_type: self.return_type_of(node),
  427. ..Extra::default()
  428. };
  429. let Some(row) = self.create_node("function", &name, node, extra) else { return };
  430. self.extract_type_annotations(node, row);
  431. self.stack.push(Scope { row, kind: "function", name });
  432. if let Some(body) = node.child_by_field_name("body") {
  433. self.visit_function_body(body);
  434. }
  435. self.stack.pop();
  436. }
  437. fn extract_method(&mut self, node: Node<'t>) {
  438. // methodsAreTopLevel: always a method. Receiver-qualified name +
  439. // a contains edge from the FIRST earlier struct/class/enum/trait
  440. // node of the receiver's name (mirrors the this.nodes.find scan).
  441. let receiver_type = self.receiver_type_of(node);
  442. let name = self.extract_name(node);
  443. let extra = Extra {
  444. docstring: preceding_docstring(node, self.src),
  445. signature: self.signature_of(node),
  446. return_type: self.return_type_of(node),
  447. qualified_name: receiver_type.as_ref().map(|r| format!("{r}::{name}")),
  448. ..Extra::default() // extractMethod passes no isExported
  449. };
  450. let Some(row) = self.create_node("method", &name, node, extra) else { return };
  451. if let Some(receiver_type) = &receiver_type {
  452. if !self.inside_class_like() {
  453. let owner_row = self
  454. .nodes_meta
  455. .iter()
  456. .position(|m| {
  457. m.name == *receiver_type
  458. && matches!(m.kind, "struct" | "class" | "enum" | "trait")
  459. })
  460. .map(|i| i as u32);
  461. if let Some(owner_row) = owner_row {
  462. self.tables.push_edge(&EdgeRow {
  463. source_idx: owner_row,
  464. target_idx: row,
  465. kind: edge_kind_index("contains").unwrap(),
  466. provenance: 0,
  467. line: NONE,
  468. column: NONE,
  469. metadata_json: NONE_STR,
  470. source_id_str: NONE_STR,
  471. target_id_str: NONE_STR,
  472. });
  473. }
  474. }
  475. }
  476. self.extract_type_annotations(node, row);
  477. self.stack.push(Scope { row, kind: "method", name });
  478. if let Some(body) = node.child_by_field_name("body") {
  479. self.visit_function_body(body);
  480. }
  481. self.stack.pop();
  482. }
  483. /// extractTypeAlias for Go: type_spec → struct / interface / plain alias.
  484. fn extract_type_alias(&mut self, node: Node<'t>) -> bool {
  485. let name = self.extract_name(node);
  486. if name == "<anonymous>" {
  487. return false;
  488. }
  489. let docstring = preceding_docstring(node, self.src);
  490. let is_exported = Some(self.is_exported(node));
  491. let type_child = node.child_by_field_name("type");
  492. let resolved = type_child.map(|t| t.kind());
  493. if resolved == Some("struct_type") {
  494. let Some(row) = self.create_node(
  495. "struct",
  496. &name,
  497. node,
  498. Extra { docstring, is_exported, ..Extra::default() },
  499. ) else {
  500. return true;
  501. };
  502. self.stack.push(Scope { row, kind: "struct", name });
  503. if let Some(type_child) = type_child {
  504. // Struct embedding → extends (field_declaration without a
  505. // field_identifier), reached via the inheritance recursion.
  506. self.extract_inheritance(type_child, row);
  507. let body = type_child.child_by_field_name("body").unwrap_or(type_child);
  508. for i in 0..body.named_child_count() {
  509. if let Some(c) = body.named_child(i) {
  510. self.visit_node(c);
  511. }
  512. }
  513. }
  514. self.stack.pop();
  515. return true;
  516. }
  517. if resolved == Some("interface_type") {
  518. let Some(row) = self.create_node(
  519. "interface",
  520. &name,
  521. node,
  522. Extra { docstring, is_exported, ..Extra::default() },
  523. ) else {
  524. return true;
  525. };
  526. if let Some(type_child) = type_child {
  527. self.extract_inheritance(type_child, row);
  528. self.extract_go_interface_methods(type_child, row, &name);
  529. }
  530. return true;
  531. }
  532. self.create_node(
  533. "type_alias",
  534. &name,
  535. node,
  536. Extra { docstring, is_exported, ..Extra::default() },
  537. );
  538. // (go type_spec has no `value` field — no type-ref walk; TS/tsx member
  539. // extraction is TS-family-only)
  540. false
  541. }
  542. /// extractGoInterfaceMethods: method_elem/method_spec → method nodes.
  543. fn extract_go_interface_methods(&mut self, interface_type: Node<'t>, iface_row: u32, iface_name: &str) {
  544. self.stack.push(Scope { row: iface_row, kind: "interface", name: iface_name.to_string() });
  545. for i in 0..interface_type.named_child_count() {
  546. let Some(m) = interface_type.named_child(i) else { continue };
  547. if !matches!(m.kind(), "method_elem" | "method_spec") {
  548. continue;
  549. }
  550. let name_node = m.child_by_field_name("name").or_else(|| m.named_child(0));
  551. let Some(name_node) = name_node else { continue };
  552. let mname = self.text(name_node).to_string();
  553. if !mname.is_empty() {
  554. let signature = self.signature_of(m);
  555. self.create_node("method", &mname, m, Extra { signature, ..Extra::default() });
  556. }
  557. }
  558. self.stack.pop();
  559. }
  560. /// extractVariable's Go branch: var/const specs + short_var_declaration.
  561. fn extract_variable(&mut self, node: Node<'t>) {
  562. let docstring = preceding_docstring(node, self.src);
  563. let is_const_decl = node.kind() == "const_declaration";
  564. for i in 0..node.named_child_count() {
  565. let Some(spec) = node.named_child(i) else { continue };
  566. if !matches!(spec.kind(), "var_spec" | "const_spec") {
  567. continue;
  568. }
  569. let mut var_row: Option<u32> = None;
  570. if let Some(name_node) = spec.named_child(0) {
  571. if name_node.kind() == "identifier" {
  572. let name = self.text(name_node).to_string();
  573. let value_node = if spec.named_child_count() > 1 {
  574. spec.named_child(spec.named_child_count() - 1)
  575. } else {
  576. None
  577. };
  578. let signature = value_node.map(|v| util::init_signature(self.text(v)));
  579. var_row = self.create_node(
  580. if is_const_decl { "constant" } else { "variable" },
  581. &name,
  582. spec,
  583. Extra { docstring: docstring.clone(), signature, ..Extra::default() },
  584. );
  585. }
  586. }
  587. // Walk the initializer ATTRIBUTED to the declared symbol (#693).
  588. if let Some(value_field) = spec.child_by_field_name("value") {
  589. if let Some(row) = var_row {
  590. let name = self.nodes_meta[row as usize].name.clone();
  591. self.stack.push(Scope { row, kind: "variable", name });
  592. self.visit_function_body(value_field);
  593. self.stack.pop();
  594. } else {
  595. self.visit_function_body(value_field);
  596. }
  597. }
  598. }
  599. if node.kind() == "short_var_declaration" {
  600. let left = node.child_by_field_name("left");
  601. let right = node.child_by_field_name("right");
  602. if let Some(left) = left {
  603. let identifiers: Vec<Node> = if left.kind() == "expression_list" {
  604. (0..left.named_child_count())
  605. .filter_map(|i| left.named_child(i))
  606. .filter(|c| c.kind() == "identifier")
  607. .collect()
  608. } else {
  609. vec![left]
  610. };
  611. for id in identifiers {
  612. let name = self.text(id).to_string();
  613. let signature = right.map(|r| util::init_signature(self.text(r)));
  614. self.create_node(
  615. "variable",
  616. &name,
  617. node,
  618. Extra { docstring: docstring.clone(), signature, ..Extra::default() },
  619. );
  620. }
  621. }
  622. }
  623. }
  624. /// extractImport's Go branch: one import node + ref per import_spec.
  625. fn extract_import(&mut self, node: Node<'t>) {
  626. let parent = self.top_row();
  627. let imports_kind = edge_kind_index("imports").unwrap();
  628. let mut handle_spec = |w: &mut Self, spec: Node<'t>| {
  629. let lit = (0..spec.named_child_count())
  630. .filter_map(|i| spec.named_child(i))
  631. .find(|c| c.kind() == "interpreted_string_literal");
  632. let Some(lit) = lit else { return };
  633. let import_path: String = w
  634. .text(lit)
  635. .chars()
  636. .filter(|c| *c != '\'' && *c != '"')
  637. .collect();
  638. if import_path.is_empty() {
  639. return;
  640. }
  641. let signature = w.text(spec).trim().to_string();
  642. w.create_node(
  643. "import",
  644. &import_path,
  645. spec,
  646. Extra { signature: Some(signature), ..Extra::default() },
  647. );
  648. w.push_ref_at(parent, &import_path, imports_kind, spec);
  649. };
  650. let spec_list = (0..node.named_child_count())
  651. .filter_map(|i| node.named_child(i))
  652. .find(|c| c.kind() == "import_spec_list");
  653. if let Some(list) = spec_list {
  654. for i in 0..list.named_child_count() {
  655. if let Some(spec) = list.named_child(i) {
  656. if spec.kind() == "import_spec" {
  657. handle_spec(self, spec);
  658. }
  659. }
  660. }
  661. } else {
  662. let spec = (0..node.named_child_count())
  663. .filter_map(|i| node.named_child(i))
  664. .find(|c| c.kind() == "import_spec");
  665. if let Some(spec) = spec {
  666. handle_spec(self, spec);
  667. }
  668. }
  669. }
  670. /// extractCall — Go's generic-tail paths (selector_expression callees).
  671. fn extract_call(&mut self, node: Node<'t>) {
  672. if self.stack.is_empty() {
  673. return;
  674. }
  675. let func = node
  676. .child_by_field_name("function")
  677. .or_else(|| node.named_child(0));
  678. let mut callee_name = String::new();
  679. if let Some(func) = func {
  680. if func.kind() == "selector_expression" {
  681. let property = func
  682. .child_by_field_name("property")
  683. .or_else(|| func.child_by_field_name("field"));
  684. if let Some(property) = property {
  685. let method_name = self.text(property);
  686. let receiver = func
  687. .child_by_field_name("object")
  688. .or_else(|| func.child_by_field_name("operand"))
  689. .or_else(|| func.child_by_field_name("argument"))
  690. .or_else(|| func.named_child(0));
  691. if let Some(r) = receiver {
  692. if is_literal_receiver(r.kind()) {
  693. return;
  694. }
  695. }
  696. if let Some(r) = receiver {
  697. match r.kind() {
  698. "identifier" | "simple_identifier" | "field_identifier" => {
  699. let receiver_name = self.text(r);
  700. if !matches!(receiver_name, "self" | "this" | "cls" | "super") {
  701. callee_name = format!("{receiver_name}.{method_name}");
  702. } else {
  703. callee_name = method_name.to_string();
  704. }
  705. }
  706. "call_expression" => {
  707. // Bare package-level factory chain `New().Method()`
  708. // re-encodes; instance chains keep the bare name.
  709. let inner_fn = r.child_by_field_name("function");
  710. let reencode =
  711. inner_fn.map(|f| f.kind() == "identifier").unwrap_or(false);
  712. if reencode {
  713. let inner: String = self
  714. .text(inner_fn.unwrap())
  715. .replace("->", ".")
  716. .chars()
  717. .filter(|c| !c.is_whitespace())
  718. .collect();
  719. callee_name = format!("{inner}().{method_name}");
  720. } else {
  721. callee_name = method_name.to_string();
  722. }
  723. }
  724. "selector_expression" => {
  725. // 2-hop field chain `t.conn.Exec` (#1276).
  726. let chain: String = self
  727. .text(r)
  728. .chars()
  729. .filter(|c| !c.is_whitespace())
  730. .collect();
  731. if go_two_hop_re().is_match(&chain) {
  732. callee_name = format!("{chain}.{method_name}");
  733. } else {
  734. callee_name = method_name.to_string();
  735. }
  736. }
  737. _ => {
  738. callee_name = method_name.to_string();
  739. }
  740. }
  741. } else {
  742. callee_name = method_name.to_string();
  743. }
  744. }
  745. } else {
  746. callee_name = self.text(func).to_string();
  747. }
  748. }
  749. if !callee_name.is_empty() {
  750. // `(*T)(x)` conversions normalize to `T`.
  751. if let Some(c) = util::paren_conversion().captures(&callee_name) {
  752. callee_name = c[1].to_string();
  753. }
  754. let from = self.top_row();
  755. self.push_ref_at(from, &callee_name.clone(), edge_kind_index("calls").unwrap(), node);
  756. }
  757. }
  758. /// extractInstantiation's composite_literal branch: named struct types
  759. /// only; the package qualifier is KEPT.
  760. fn extract_instantiation(&mut self, node: Node<'t>) {
  761. if self.stack.is_empty() {
  762. return;
  763. }
  764. let ctor = node
  765. .child_by_field_name("constructor")
  766. .or_else(|| node.child_by_field_name("type"))
  767. .or_else(|| node.child_by_field_name("name"))
  768. .or_else(|| node.named_child(0));
  769. let Some(ctor) = ctor else { return };
  770. if !matches!(ctor.kind(), "type_identifier" | "qualified_type") {
  771. return;
  772. }
  773. let mut go_type = self.text(ctor).trim().to_string();
  774. if let Some(br) = go_type.find('[') {
  775. if br > 0 {
  776. go_type.truncate(br);
  777. go_type = go_type.trim().to_string();
  778. }
  779. }
  780. if !go_type.is_empty() {
  781. let from = self.top_row();
  782. self.push_ref_at(from, &go_type, edge_kind_index("instantiates").unwrap(), node);
  783. }
  784. }
  785. /// extractInheritance — the Go branches: interface embedding
  786. /// (constraint_elem) and struct embedding (field_declaration without a
  787. /// field_identifier), plus the field_declaration_list recursion.
  788. fn extract_inheritance(&mut self, node: Node<'t>, class_row: u32) {
  789. let extends_kind = edge_kind_index("extends").unwrap();
  790. for i in 0..node.named_child_count() {
  791. let Some(child) = node.named_child(i) else { continue };
  792. match child.kind() {
  793. "constraint_elem" => {
  794. let type_id = (0..child.named_child_count())
  795. .filter_map(|j| child.named_child(j))
  796. .find(|c| c.kind() == "type_identifier");
  797. if let Some(type_id) = type_id {
  798. let name = self.text(type_id).to_string();
  799. self.push_ref_at(class_row, &name, extends_kind, type_id);
  800. }
  801. }
  802. "field_declaration" => {
  803. let has_field_identifier = (0..child.named_child_count())
  804. .filter_map(|j| child.named_child(j))
  805. .any(|c| c.kind() == "field_identifier");
  806. if !has_field_identifier {
  807. let type_id = (0..child.named_child_count())
  808. .filter_map(|j| child.named_child(j))
  809. .find(|c| c.kind() == "type_identifier");
  810. if let Some(type_id) = type_id {
  811. let name = self.text(type_id).to_string();
  812. self.push_ref_at(class_row, &name, extends_kind, type_id);
  813. }
  814. }
  815. }
  816. "field_declaration_list" | "class_heritage" => {
  817. self.extract_inheritance(child, class_row);
  818. }
  819. _ => {}
  820. }
  821. }
  822. }
  823. /// extractTypeAnnotations — Go's returnField is `result`.
  824. fn extract_type_annotations(&mut self, node: Node<'t>, from_row: u32) {
  825. if let Some(params) = node.child_by_field_name("parameters") {
  826. self.extract_type_refs_from_subtree(params, from_row);
  827. }
  828. if let Some(ret) = node.child_by_field_name("result") {
  829. self.extract_type_refs_from_subtree(ret, from_row);
  830. }
  831. let type_annotation = (0..node.named_child_count())
  832. .filter_map(|i| node.named_child(i))
  833. .find(|c| c.kind() == "type_annotation");
  834. if let Some(ta) = type_annotation {
  835. self.extract_type_refs_from_subtree(ta, from_row);
  836. }
  837. }
  838. fn extract_type_refs_from_subtree(&mut self, node: Node<'t>, from_row: u32) {
  839. if node.kind() == "type_identifier" {
  840. let type_name = self.text(node).to_string();
  841. if !type_name.is_empty() && !is_builtin_type(&type_name) {
  842. self.push_ref_at(from_row, &type_name, edge_kind_index("references").unwrap(), node);
  843. }
  844. return;
  845. }
  846. for i in 0..node.named_child_count() {
  847. if let Some(c) = node.named_child(i) {
  848. self.extract_type_refs_from_subtree(c, from_row);
  849. }
  850. }
  851. }
  852. // --- fn refs (GO_SPEC, with the literal_element/expression_list layers) --------
  853. fn maybe_capture_fn_refs(&mut self, node: Node<'t>) {
  854. let (mode, field): (&str, &str) = match node.kind() {
  855. "argument_list" => ("args", ""),
  856. "assignment_statement" => ("rhs", "right"),
  857. "short_var_declaration" => ("rhs", "right"),
  858. "var_spec" => ("varinit", "value"),
  859. "keyed_element" => ("value", ""), // value = LAST named child
  860. "literal_value" => ("list", ""),
  861. _ => return,
  862. };
  863. if self.stack.is_empty() {
  864. return;
  865. }
  866. let from = self.top_row();
  867. let mut values: Vec<Node> = Vec::new();
  868. match mode {
  869. "args" | "list" => {
  870. for i in 0..node.named_child_count() {
  871. if let Some(c) = node.named_child(i) {
  872. values.push(c);
  873. }
  874. }
  875. }
  876. "rhs" => {
  877. if let Some(rhs) = node.child_by_field_name(field) {
  878. let lhs_text = node
  879. .child_by_field_name("left")
  880. .map(|l| self.text(l))
  881. .unwrap_or("");
  882. let lhs_last = util::lhs_last_name()
  883. .captures(lhs_text)
  884. .and_then(|c| c.get(1))
  885. .map(|m| m.as_str());
  886. if !(lhs_last.is_some() && lhs_last == Some(self.text(rhs).trim())) {
  887. values.push(rhs);
  888. }
  889. }
  890. }
  891. "value" => {
  892. let v = node
  893. .child_by_field_name("value")
  894. .or_else(|| {
  895. if node.named_child_count() > 0 {
  896. node.named_child(node.named_child_count() - 1)
  897. } else {
  898. None
  899. }
  900. });
  901. if let Some(v) = v {
  902. values.push(v);
  903. }
  904. }
  905. _ => {
  906. // varinit — Go var_spec names are plain identifiers (no
  907. // destructuring patterns to skip).
  908. if let Some(v) = node.child_by_field_name(field) {
  909. values.push(v);
  910. }
  911. }
  912. }
  913. for v in values {
  914. self.normalize_fn_ref_value(v, from, 0);
  915. }
  916. }
  917. /// normalizeValue with GO_SPEC's transparent layers (literal_element,
  918. /// expression_list — both fan out to named children).
  919. fn normalize_fn_ref_value(&mut self, v: Node<'t>, from: u32, depth: u32) {
  920. if depth > 4 {
  921. return;
  922. }
  923. match v.kind() {
  924. "identifier" => {
  925. let name = self.text(v).to_string();
  926. if name.is_empty() || is_stoplisted(&name) {
  927. return;
  928. }
  929. let p = v.start_position();
  930. self.fn_ref_cands.push(Cand {
  931. from,
  932. name,
  933. line: p.row as u32 + 1,
  934. column_byte: v.start_byte(),
  935. row: p.row,
  936. });
  937. }
  938. "literal_element" | "expression_list" => {
  939. for i in 0..v.named_child_count() {
  940. if let Some(c) = v.named_child(i) {
  941. self.normalize_fn_ref_value(c, from, depth + 1);
  942. }
  943. }
  944. }
  945. _ => {}
  946. }
  947. }
  948. fn scan_fn_ref_subtree(&mut self, node: Node<'t>, depth: u32) {
  949. if depth > 12 {
  950. return;
  951. }
  952. if depth > 0
  953. && matches!(
  954. node.kind(),
  955. "function_declaration" | "arrow_function" | "function_expression"
  956. | "lambda_literal" | "lambda_expression"
  957. )
  958. {
  959. return;
  960. }
  961. self.maybe_capture_fn_refs(node);
  962. for i in 0..node.named_child_count() {
  963. if let Some(c) = node.named_child(i) {
  964. self.scan_fn_ref_subtree(c, depth + 1);
  965. }
  966. }
  967. }
  968. fn flush_fn_ref_candidates(&mut self) {
  969. let cands = std::mem::take(&mut self.fn_ref_cands);
  970. if cands.is_empty() || util::is_generated_file(self.file_path) {
  971. return;
  972. }
  973. let mut seen: HashSet<(String, String)> = HashSet::new();
  974. for c in cands {
  975. if !c.name.starts_with("this.")
  976. && !c.name.contains("::")
  977. && !self.defined_fn_names.contains(&c.name)
  978. && !self.imported_names.contains(&c.name)
  979. {
  980. continue;
  981. }
  982. if !seen.insert((self.node_ids[c.from as usize].clone(), c.name.clone())) {
  983. continue;
  984. }
  985. let column = util::col16(self.src, &self.line_starts, c.row, c.column_byte);
  986. let name_ref = self.arena.put(&c.name);
  987. self.tables.push_ref(&RefRow {
  988. from_idx: c.from,
  989. kind: FUNCTION_REF_CODE,
  990. line: c.line,
  991. column,
  992. reference_name: name_ref,
  993. candidates: NONE_STR,
  994. from_id_str: NONE_STR,
  995. });
  996. }
  997. }
  998. // --- value refs -------------------------------------------------------------------
  999. fn flush_value_refs(&mut self, root: Node<'t>) {
  1000. let scopes = std::mem::take(&mut self.value_scopes);
  1001. let mut targets = std::mem::take(&mut self.fs_values);
  1002. let counts = std::mem::take(&mut self.fs_value_counts);
  1003. if std::env::var("CODEGRAPH_VALUE_REFS").as_deref() == Ok("0") {
  1004. return;
  1005. }
  1006. if targets.is_empty() || scopes.is_empty() || util::is_generated_file(self.file_path) {
  1007. return;
  1008. }
  1009. // Shadow prune — Go declarator shapes: const_spec/var_spec (name =
  1010. // first child) and short_var_declaration (left / expression_list).
  1011. let mut decl_counts: HashMap<&str, u32> = HashMap::new();
  1012. let mut bump = |decl_counts: &mut HashMap<&'t str, u32>, name_node: Option<Node<'t>>, src: &'t str, targets: &HashMap<String, u32>| {
  1013. if let Some(n) = name_node {
  1014. if matches!(n.kind(), "identifier" | "simple_identifier") {
  1015. let nm = &src[n.byte_range()];
  1016. if targets.contains_key(nm) {
  1017. *decl_counts.entry(nm).or_insert(0) += 1;
  1018. }
  1019. }
  1020. }
  1021. };
  1022. let mut dstack: Vec<Node> = vec![root];
  1023. let mut dvisited = 0usize;
  1024. while let Some(n) = dstack.pop() {
  1025. if dvisited >= MAX_VALUE_REF_NODES {
  1026. break;
  1027. }
  1028. dvisited += 1;
  1029. match n.kind() {
  1030. "const_spec" | "var_spec" => bump(&mut decl_counts, n.named_child(0), self.src, &targets),
  1031. "short_var_declaration" => {
  1032. let left = n
  1033. .child_by_field_name("left")
  1034. .or_else(|| n.child_by_field_name("pattern"))
  1035. .or_else(|| n.named_child(0));
  1036. if let Some(left) = left {
  1037. if left.kind() == "identifier" {
  1038. bump(&mut decl_counts, Some(left), self.src, &targets);
  1039. } else {
  1040. for i in 0..left.named_child_count() {
  1041. bump(&mut decl_counts, left.named_child(i), self.src, &targets);
  1042. }
  1043. }
  1044. }
  1045. }
  1046. _ => {}
  1047. }
  1048. for i in 0..n.named_child_count() {
  1049. if let Some(c) = n.named_child(i) {
  1050. dstack.push(c);
  1051. }
  1052. }
  1053. }
  1054. let shadowed: Vec<String> = decl_counts
  1055. .iter()
  1056. .filter(|(nm, c)| **c > counts.get(**nm).copied().unwrap_or(1))
  1057. .map(|(nm, _)| nm.to_string())
  1058. .collect();
  1059. for nm in shadowed {
  1060. targets.remove(&nm);
  1061. }
  1062. if targets.is_empty() {
  1063. return;
  1064. }
  1065. let refs_kind = edge_kind_index("references").unwrap();
  1066. for scope in &scopes {
  1067. let mut seen: HashSet<&str> = HashSet::new();
  1068. let mut stack: Vec<Node> = vec![scope.node];
  1069. let mut visited = 0usize;
  1070. while let Some(n) = stack.pop() {
  1071. if visited >= MAX_VALUE_REF_NODES {
  1072. break;
  1073. }
  1074. visited += 1;
  1075. if matches!(n.kind(), "identifier" | "constant" | "name" | "simple_identifier") {
  1076. let ref_name = self.text(n);
  1077. if let Some(&target_row) = targets.get(ref_name) {
  1078. let target_id = self.node_ids[target_row as usize].as_str();
  1079. if target_id != self.node_ids[scope.row as usize]
  1080. && ref_name != scope.name
  1081. && !seen.contains(&target_id)
  1082. {
  1083. seen.insert(target_id);
  1084. let meta = self.arena.put(r#"{"valueRef":true}"#);
  1085. self.tables.push_edge(&EdgeRow {
  1086. source_idx: scope.row,
  1087. target_idx: target_row,
  1088. kind: refs_kind,
  1089. provenance: 0,
  1090. line: NONE,
  1091. column: NONE,
  1092. metadata_json: meta,
  1093. source_id_str: NONE_STR,
  1094. target_id_str: NONE_STR,
  1095. });
  1096. }
  1097. }
  1098. }
  1099. for i in 0..n.named_child_count() {
  1100. if let Some(c) = n.named_child(i) {
  1101. stack.push(c);
  1102. }
  1103. }
  1104. }
  1105. }
  1106. }
  1107. }
  1108. fn is_stoplisted(name: &str) -> bool {
  1109. matches!(
  1110. name,
  1111. "this" | "self" | "super" | "null" | "nil" | "true" | "false" | "undefined" | "new"
  1112. | "NULL" | "nullptr" | "None"
  1113. )
  1114. }
  1115. fn is_literal_receiver(kind: &str) -> bool {
  1116. matches!(
  1117. kind,
  1118. "string" | "string_literal" | "interpreted_string_literal" | "raw_string_literal"
  1119. | "template_string" | "concatenated_string" | "formatted_string" | "f_string"
  1120. | "line_string_literal" | "string_content" | "heredoc_body"
  1121. | "number" | "number_literal" | "integer" | "integer_literal" | "float"
  1122. | "float_literal" | "int_literal" | "decimal_integer_literal" | "real_literal"
  1123. | "char_literal" | "character_literal" | "rune_literal" | "regex" | "regex_literal"
  1124. | "true" | "false" | "boolean_literal" | "bool_literal" | "none" | "null" | "nil"
  1125. | "null_literal" | "undefined"
  1126. | "list" | "list_literal" | "array" | "array_literal" | "array_creation_expression"
  1127. | "dictionary" | "dict_literal" | "object" | "tuple" | "set"
  1128. )
  1129. }
  1130. /// BUILTIN_TYPES (shared table).
  1131. fn is_builtin_type(name: &str) -> bool {
  1132. matches!(
  1133. name,
  1134. "string" | "number" | "boolean" | "void" | "null" | "undefined" | "never" | "any"
  1135. | "unknown" | "object" | "symbol" | "bigint" | "true" | "false"
  1136. | "str" | "bool" | "i8" | "i16" | "i32" | "i64" | "i128" | "isize"
  1137. | "u8" | "u16" | "u32" | "u64" | "u128" | "usize" | "f32" | "f64" | "char"
  1138. | "int" | "long" | "short" | "byte" | "float" | "double"
  1139. | "int8" | "int16" | "int32" | "int64" | "uint8" | "uint16" | "uint32" | "uint64"
  1140. | "float32" | "float64" | "complex64" | "complex128" | "rune" | "error"
  1141. | "Int" | "Long" | "Short" | "Byte" | "Float" | "Double" | "Boolean" | "Char"
  1142. | "Unit" | "String" | "Any" | "AnyRef" | "AnyVal" | "Nothing" | "Null"
  1143. )
  1144. }
  1145. fn opt_str(arena: &mut Arena, s: Option<&str>) -> StrRef {
  1146. match s {
  1147. Some(s) => arena.put(s),
  1148. None => NONE_STR,
  1149. }
  1150. }