php.rs 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524
  1. //! PHP extraction — a faithful Rust port of `TreeSitterExtractor`'s PHP paths
  2. //! (src/extraction/tree-sitter.ts) plus languages/php.ts.
  3. //!
  4. //! Same porting contract as the other walkers: behavior parity, bug-for-bug.
  5. //! The authoritative quirk list is docs/design/php-kernel-port-checklist.md —
  6. //! including what this file preserves on purpose: the visitNode hook consumes
  7. //! const_declaration (constants at ANY scope, values never walked) and
  8. //! trait-`use` (implements refs WITH filePath — the v2 ref-flag wire slot,
  9. //! shipped with ruby) before the ladder; the FIRST file-level namespace scopes
  10. //! the whole walk (braced namespaces scope nothing); anonymous classes on the
  11. //! v0.24.2 grammar mint NO anon-class node (top-level methods become file-level
  12. //! functions, in-body methods vanish) and their instantiates ref is the whole
  13. //! anon-class text run through the suffix logic; scoped calls are DOT-joined
  14. //! (`UserModel.query`); `$this->prop->m()` emits `this->prop.m` (the #1251
  15. //! machinery is resolution-side); nullsafe `?->` emits nothing; literal
  16. //! receivers are not suppressed; interface multi-extends drops all but the
  17. //! first base; property type-hints emit no refs from field nodes. Positions in
  18. //! UTF-16 code units. Files with parse errors defer to wasm (≈0–0.1%).
  19. use crate::buffers::{
  20. build_meta, edge_kind_index, node_kind_index, Arena, BoolFlags, EdgeRow, EmitOut, NodeRow,
  21. RefRow, StrRef, Tables, FLAG_IS_EXPORTED, FLAG_IS_STATIC, FUNCTION_REF_CODE, NONE, NONE_STR,
  22. REF_FLAG_FILE_PATH,
  23. };
  24. use crate::docstring::preceding_docstring;
  25. use crate::ids;
  26. use crate::textutil as util;
  27. use regex::Regex;
  28. use std::collections::{HashMap, HashSet};
  29. use std::sync::OnceLock;
  30. use tree_sitter::{Node, Parser};
  31. const MAX_VALUE_REF_NODES: usize = 20_000;
  32. /// NAME_STOPLIST (function-ref.ts).
  33. fn is_stoplisted(name: &str) -> bool {
  34. matches!(
  35. name,
  36. "this" | "self" | "super" | "null" | "nil" | "true" | "false" | "undefined" | "new"
  37. | "NULL" | "nullptr" | "None"
  38. )
  39. }
  40. /// PHP_NON_CLASS_RETURN (languages/php.ts:37).
  41. fn is_php_non_class_return(lc: &str) -> bool {
  42. matches!(
  43. lc,
  44. "array" | "string" | "int" | "integer" | "float" | "double" | "bool" | "boolean"
  45. | "void" | "mixed" | "never" | "null" | "false" | "true" | "object" | "callable"
  46. | "iterable" | "resource"
  47. )
  48. }
  49. /// PHP_PSEUDO_TYPES (tree-sitter.ts:5760).
  50. fn is_php_pseudo_type(name: &str) -> bool {
  51. matches!(
  52. name,
  53. "self" | "static" | "parent" | "mixed" | "object" | "iterable" | "callable" | "void"
  54. | "null" | "false" | "true" | "never" | "array" | "int" | "float" | "string" | "bool"
  55. )
  56. }
  57. /// PHP_TYPE_NODES (tree-sitter.ts:310).
  58. fn is_php_type_node(kind: &str) -> bool {
  59. matches!(
  60. kind,
  61. "named_type" | "optional_type" | "nullable_type" | "union_type" | "intersection_type"
  62. | "disjunctive_normal_form_type" | "primitive_type"
  63. )
  64. }
  65. /// PHP_CALLABLE_HOFS (function-ref.ts:347).
  66. fn is_php_callable_hof(name: &str) -> bool {
  67. matches!(
  68. name,
  69. "array_map" | "array_filter" | "array_walk" | "array_walk_recursive" | "array_reduce"
  70. | "usort" | "uasort" | "uksort"
  71. | "array_udiff" | "array_udiff_assoc" | "array_uintersect" | "array_uintersect_assoc"
  72. | "call_user_func" | "call_user_func_array"
  73. | "forward_static_call" | "forward_static_call_array"
  74. | "preg_replace_callback" | "preg_replace_callback_array"
  75. | "register_shutdown_function" | "register_tick_function"
  76. | "set_error_handler" | "set_exception_handler" | "spl_autoload_register"
  77. | "ob_start" | "iterator_apply" | "header_register_callback"
  78. | "is_callable"
  79. )
  80. }
  81. /// `/^[A-Za-z_]\w*$/` with JS's ASCII `\w`.
  82. fn ascii_ident_re() -> &'static Regex {
  83. static RE: OnceLock<Regex> = OnceLock::new();
  84. RE.get_or_init(|| Regex::new(r"^[A-Za-z_][0-9A-Za-z_]*$").unwrap())
  85. }
  86. /// String-callable simple-name shape (`/^[A-Za-z_][A-Za-z0-9_]*$/`).
  87. fn simple_callable_re() -> &'static Regex {
  88. static RE: OnceLock<Regex> = OnceLock::new();
  89. RE.get_or_init(|| Regex::new(r"^[A-Za-z_][A-Za-z0-9_]*$").unwrap())
  90. }
  91. /// String-callable qualified shape (`/^\w+::\w+$/`, JS ASCII `\w`).
  92. fn qualified_callable_re() -> &'static Regex {
  93. static RE: OnceLock<Regex> = OnceLock::new();
  94. RE.get_or_init(|| Regex::new(r"^[0-9A-Za-z_]+::[0-9A-Za-z_]+$").unwrap())
  95. }
  96. /// extractStaticMemberRef's capitalized-receiver test.
  97. fn capitalized_re() -> &'static Regex {
  98. static RE: OnceLock<Regex> = OnceLock::new();
  99. RE.get_or_init(|| Regex::new(r"^[A-Z][A-Za-z0-9_]*$").unwrap())
  100. }
  101. struct Scope {
  102. row: u32,
  103. kind: &'static str,
  104. name: String,
  105. }
  106. #[derive(Default)]
  107. struct Extra {
  108. docstring: Option<String>,
  109. signature: Option<String>,
  110. visibility: Option<u8>,
  111. is_static: Option<bool>,
  112. return_type: Option<String>,
  113. }
  114. struct ValueScope<'t> {
  115. row: u32,
  116. node: Node<'t>,
  117. name: String,
  118. }
  119. struct Cand {
  120. from: u32,
  121. name: String,
  122. line: u32,
  123. column_byte: usize,
  124. row: usize,
  125. skip_gate: bool,
  126. }
  127. pub struct Walker<'t> {
  128. src: &'t str,
  129. file_path: &'t str,
  130. line_starts: Vec<usize>,
  131. arena: Arena,
  132. tables: Tables,
  133. stack: Vec<Scope>,
  134. node_ids: Vec<String>,
  135. defined_fn_names: HashSet<String>,
  136. imported_names: HashSet<String>,
  137. fn_ref_cands: Vec<Cand>,
  138. fs_values: HashMap<String, u32>,
  139. fs_value_counts: HashMap<String, u32>,
  140. value_scopes: Vec<ValueScope<'t>>,
  141. }
  142. pub fn extract(file_path: &str, source: &str) -> Result<EmitOut, String> {
  143. let grammar = crate::langs::grammar_for("php").ok_or("no php grammar")?;
  144. let t0 = std::time::Instant::now();
  145. let mut parser = Parser::new();
  146. parser
  147. .set_language(&grammar)
  148. .map_err(|e| format!("set_language(php) failed: {e}"))?;
  149. let tree = parser
  150. .parse(source, None)
  151. .ok_or_else(|| "parser returned null tree".to_string())?;
  152. if tree.root_node().has_error() {
  153. return Err("defer: parse tree contains errors — wasm recovery is canonical".to_string());
  154. }
  155. let mut w = Walker {
  156. src: source,
  157. file_path,
  158. line_starts: util::line_starts(source),
  159. arena: Arena::default(),
  160. tables: Tables::default(),
  161. stack: Vec::new(),
  162. node_ids: Vec::new(),
  163. defined_fn_names: HashSet::new(),
  164. imported_names: HashSet::new(),
  165. fn_ref_cands: Vec::new(),
  166. fs_values: HashMap::new(),
  167. fs_value_counts: HashMap::new(),
  168. value_scopes: Vec::new(),
  169. };
  170. let line_count = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1;
  171. let base_name = file_path.rsplit(['/', '\\']).next().unwrap_or(file_path);
  172. let mut flags = BoolFlags::default();
  173. flags.set(FLAG_IS_EXPORTED, false);
  174. let file_id = w.arena.put(&ids::file_node_id(file_path));
  175. let name_ref = w.arena.put(base_name);
  176. let qn_ref = w.arena.put(file_path);
  177. w.tables.push_node(&NodeRow {
  178. kind: node_kind_index("file").unwrap(),
  179. visibility: 0,
  180. flags,
  181. start_line: 1,
  182. end_line: line_count,
  183. start_column: 0,
  184. end_column: 0,
  185. name: name_ref,
  186. qualified_name: qn_ref,
  187. id: file_id,
  188. docstring: NONE_STR,
  189. signature: NONE_STR,
  190. decorators: NONE_STR,
  191. type_parameters: NONE_STR,
  192. return_type: NONE_STR,
  193. extra_json: NONE_STR,
  194. });
  195. w.node_ids.push(ids::file_node_id(file_path));
  196. w.stack.push(Scope { row: 0, kind: "file", name: base_name.to_string() });
  197. // extractFilePackage: the FIRST namespace_definition among the root's
  198. // direct namedChildren; braced namespaces (a compound_statement /
  199. // declaration_list child) make NO node and scope NOTHING. The node stays
  200. // pushed for the whole walk — QNs become `App\Services::Name` and import
  201. // nodes/refs hang off it.
  202. let root = tree.root_node();
  203. let mut pkg_pushed = false;
  204. for i in 0..root.named_child_count() {
  205. let Some(child) = root.named_child(i) else { continue };
  206. if child.kind() != "namespace_definition" {
  207. continue;
  208. }
  209. let ns_name = (0..child.named_child_count())
  210. .filter_map(|j| child.named_child(j))
  211. .find(|c| c.kind() == "namespace_name");
  212. let has_body = (0..child.named_child_count())
  213. .filter_map(|j| child.named_child(j))
  214. .any(|c| matches!(c.kind(), "compound_statement" | "declaration_list"));
  215. if let Some(ns_name) = ns_name {
  216. if !has_body {
  217. let pkg = w.text(ns_name).to_string();
  218. if !pkg.is_empty() {
  219. if let Some(row) = w.create_node("namespace", &pkg, child, Extra::default()) {
  220. w.stack.push(Scope { row, kind: "namespace", name: pkg });
  221. pkg_pushed = true;
  222. }
  223. }
  224. }
  225. }
  226. break;
  227. }
  228. w.visit_node(root);
  229. w.flush_fn_ref_candidates();
  230. w.flush_value_refs();
  231. if pkg_pushed {
  232. w.stack.pop();
  233. }
  234. w.stack.pop();
  235. let duration_ms = t0.elapsed().as_secs_f64() * 1000.0;
  236. let meta = build_meta(&w.tables, w.arena.len(), NONE_STR, duration_ms);
  237. Ok(EmitOut {
  238. meta,
  239. nodes: w.tables.nodes,
  240. edges: w.tables.edges,
  241. refs: w.tables.refs,
  242. arena: w.arena.into_vec(),
  243. })
  244. }
  245. impl<'t> Walker<'t> {
  246. fn text(&self, node: Node) -> &'t str {
  247. &self.src[node.byte_range()]
  248. }
  249. fn line_of(&self, node: Node) -> u32 {
  250. node.start_position().row as u32 + 1
  251. }
  252. fn col_of(&self, node: Node) -> u32 {
  253. util::col16(self.src, &self.line_starts, node.start_position().row, node.start_byte())
  254. }
  255. fn end_col_of(&self, node: Node) -> u32 {
  256. util::col16(self.src, &self.line_starts, node.end_position().row, node.end_byte())
  257. }
  258. fn top_row(&self) -> u32 {
  259. self.stack.last().map(|s| s.row).unwrap_or(0)
  260. }
  261. fn inside_class_like(&self) -> bool {
  262. self.stack
  263. .last()
  264. .map(|s| matches!(s.kind, "class" | "struct" | "interface" | "trait" | "enum" | "module"))
  265. .unwrap_or(false)
  266. }
  267. fn push_ref(&mut self, from_row: u32, name: &str, kind_code: u8, line: u32, column: u32) {
  268. let name_ref = self.arena.put(name);
  269. self.tables.push_ref(&RefRow {
  270. from_idx: from_row,
  271. kind: kind_code,
  272. line,
  273. column,
  274. reference_name: name_ref,
  275. candidates: NONE_STR,
  276. from_id_str: NONE_STR,
  277. });
  278. if kind_code == edge_kind_index("imports").unwrap() {
  279. if util::simple_name().is_match(name) {
  280. self.imported_names.insert(name.to_string());
  281. } else if let Some(c) = util::qualified_import().captures(name) {
  282. self.imported_names.insert(c[1].to_string());
  283. }
  284. }
  285. }
  286. fn push_ref_at(&mut self, from_row: u32, name: &str, kind_code: u8, node: Node) {
  287. self.push_ref(from_row, name, kind_code, self.line_of(node), self.col_of(node));
  288. }
  289. // --- createNode ------------------------------------------------------------
  290. fn create_node(&mut self, kind: &'static str, name: &str, node: Node<'t>, extra: Extra) -> Option<u32> {
  291. if name.is_empty() {
  292. return None;
  293. }
  294. let start_line = self.line_of(node);
  295. let id = ids::node_id(self.file_path, kind, name, start_line);
  296. let end_line = node.end_position().row as u32 + 1; // no resolveBody for php
  297. let qualified = {
  298. let mut parts: Vec<&str> = Vec::new();
  299. for s in &self.stack {
  300. if s.kind != "file" {
  301. parts.push(&s.name);
  302. }
  303. }
  304. let mut qn = parts.join("::");
  305. if !qn.is_empty() {
  306. qn.push_str("::");
  307. }
  308. qn.push_str(name);
  309. qn
  310. };
  311. let mut flags = BoolFlags::default();
  312. if let Some(v) = extra.is_static {
  313. flags.set(FLAG_IS_STATIC, v);
  314. }
  315. let name_ref = self.arena.put(name);
  316. let qn_ref = self.arena.put(&qualified);
  317. let id_ref = self.arena.put(&id);
  318. let doc_ref = opt_str(&mut self.arena, extra.docstring.as_deref());
  319. let sig_ref = opt_str(&mut self.arena, extra.signature.as_deref());
  320. let ret_ref = opt_str(&mut self.arena, extra.return_type.as_deref());
  321. let row = self.tables.push_node(&NodeRow {
  322. kind: node_kind_index(kind).unwrap(),
  323. visibility: extra.visibility.unwrap_or(0),
  324. flags,
  325. start_line,
  326. end_line,
  327. start_column: self.col_of(node),
  328. end_column: self.end_col_of(node),
  329. name: name_ref,
  330. qualified_name: qn_ref,
  331. id: id_ref,
  332. docstring: doc_ref,
  333. signature: sig_ref,
  334. decorators: NONE_STR, // php attributes never emit decorates refs
  335. type_parameters: NONE_STR,
  336. return_type: ret_ref,
  337. extra_json: NONE_STR,
  338. });
  339. self.node_ids.push(id);
  340. let parent_row = self.top_row();
  341. self.tables.push_edge(&EdgeRow {
  342. source_idx: parent_row,
  343. target_idx: row,
  344. kind: edge_kind_index("contains").unwrap(),
  345. provenance: 0,
  346. line: NONE,
  347. column: NONE,
  348. metadata_json: NONE_STR,
  349. source_id_str: NONE_STR,
  350. target_id_str: NONE_STR,
  351. });
  352. if kind == "function" || kind == "method" {
  353. self.defined_fn_names.insert(name.to_string());
  354. }
  355. // captureValueRefScope — with a namespace pushed, top-level constants
  356. // have a `namespace` parent (NOT in the accepted set) and are dropped
  357. // as targets; class/enum consts qualify, interface/trait ones don't.
  358. let target_kind_ok = kind == "constant" || kind == "variable";
  359. if target_kind_ok
  360. && util::utf16_len(name) >= 3
  361. && util::has_upper_or_underscore().is_match(name)
  362. {
  363. let parent_ok = self
  364. .stack
  365. .last()
  366. .map(|s| matches!(s.kind, "file" | "class" | "module" | "struct" | "enum"))
  367. .unwrap_or(false);
  368. if parent_ok {
  369. self.fs_values.insert(name.to_string(), row);
  370. *self.fs_value_counts.entry(name.to_string()).or_insert(0) += 1;
  371. }
  372. }
  373. if matches!(kind, "function" | "method" | "constant" | "variable") {
  374. self.value_scopes.push(ValueScope { row, node, name: name.to_string() });
  375. }
  376. Some(row)
  377. }
  378. fn extract_name(&self, node: Node) -> String {
  379. if let Some(name_node) = node.child_by_field_name("name") {
  380. return self.text(name_node).to_string();
  381. }
  382. for i in 0..node.named_child_count() {
  383. if let Some(c) = node.named_child(i) {
  384. if matches!(c.kind(), "identifier" | "type_identifier" | "simple_identifier" | "constant") {
  385. return self.text(c).to_string();
  386. }
  387. }
  388. }
  389. "<anonymous>".to_string()
  390. }
  391. // --- hooks (languages/php.ts) ------------------------------------------------
  392. /// getVisibility: any `visibility_modifier` child with one of the three
  393. /// texts; none → public (the php default).
  394. fn visibility_of(&self, node: Node) -> u8 {
  395. for i in 0..node.child_count() {
  396. let Some(child) = node.child(i) else { continue };
  397. if child.kind() == "visibility_modifier" {
  398. match self.text(child) {
  399. "public" => return 1,
  400. "private" => return 2,
  401. "protected" => return 3,
  402. _ => {}
  403. }
  404. }
  405. }
  406. 1 // PHP defaults to public
  407. }
  408. fn is_static(&self, node: Node) -> bool {
  409. (0..node.child_count())
  410. .filter_map(|i| node.child(i))
  411. .any(|c| c.kind() == "static_modifier")
  412. }
  413. /// extractPhpReturnType — `self`/`static` collapse to the `'self'` marker
  414. /// (#608 chained-call fuel); primitives/unions → None.
  415. fn return_type_of(&self, node: Node) -> Option<String> {
  416. let mut rt = node.child_by_field_name("return_type")?;
  417. if rt.kind() == "optional_type" {
  418. rt = rt.named_child(0).unwrap_or(rt);
  419. }
  420. if rt.kind() == "primitive_type" {
  421. return None;
  422. }
  423. let name_node = if rt.kind() == "named_type" { rt.named_child(0).unwrap_or(rt) } else { rt };
  424. let text = self.text(name_node).trim();
  425. let text = text.strip_prefix('\\').unwrap_or(text);
  426. if text.is_empty() {
  427. return None;
  428. }
  429. let last = text.rsplit('\\').next().unwrap_or(text);
  430. let lc = last.to_lowercase();
  431. if matches!(lc.as_str(), "self" | "static" | "this" | "$this") {
  432. return Some("self".to_string());
  433. }
  434. if is_php_non_class_return(&lc) {
  435. return None;
  436. }
  437. if !ascii_ident_re().is_match(last) {
  438. return None; // unions/intersections/complex
  439. }
  440. Some(last.to_string())
  441. }
  442. // --- the visitNode hook (php.ts:108) ------------------------------------------
  443. fn try_visit_hook(&mut self, node: Node<'t>) -> bool {
  444. match node.kind() {
  445. // Class/interface/trait/enum/top-level constants: one `constant`
  446. // node per const_element, NO extras, values never walked.
  447. "const_declaration" => {
  448. let elements: Vec<Node> = (0..node.named_child_count())
  449. .filter_map(|i| node.named_child(i))
  450. .filter(|c| c.kind() == "const_element")
  451. .collect();
  452. for elem in elements {
  453. let name_node = (0..elem.named_child_count())
  454. .filter_map(|i| elem.named_child(i))
  455. .find(|c| c.kind() == "name");
  456. let Some(name_node) = name_node else { continue };
  457. let name = self.text(name_node).to_string();
  458. self.create_node("constant", &name, elem, Extra::default());
  459. }
  460. true
  461. }
  462. // Trait use inside a class-like body: one `implements` ref per
  463. // used name (full qualified text), all at the use_declaration's
  464. // position — WITH filePath (the hook sets ctx.filePath; v2 flag).
  465. "use_declaration" => {
  466. let names: Vec<Node> = (0..node.named_child_count())
  467. .filter_map(|i| node.named_child(i))
  468. .filter(|c| matches!(c.kind(), "name" | "qualified_name"))
  469. .collect();
  470. let parent = self.top_row();
  471. let implements = edge_kind_index("implements").unwrap();
  472. let line = self.line_of(node);
  473. let col = self.col_of(node);
  474. for n in names {
  475. let name_ref = self.arena.put(self.text(n));
  476. self.tables.push_ref_flagged(
  477. &RefRow {
  478. from_idx: parent,
  479. kind: implements,
  480. line,
  481. column: col,
  482. reference_name: name_ref,
  483. candidates: NONE_STR,
  484. from_id_str: NONE_STR,
  485. },
  486. REF_FLAG_FILE_PATH,
  487. );
  488. }
  489. true
  490. }
  491. _ => false,
  492. }
  493. }
  494. // --- the dispatcher (visitNode, PHP-relevant branches) ------------------------
  495. fn visit_node(&mut self, node: Node<'t>) {
  496. if self.try_visit_hook(node) {
  497. self.scan_fn_ref_subtree(node, 0);
  498. return;
  499. }
  500. let kind = node.kind();
  501. let mut skip_children = false;
  502. self.maybe_capture_fn_refs(node);
  503. if kind == "function_definition" {
  504. // functionTypes; method_declaration is not in it, so this is
  505. // always extractFunction (php functions can't be class members).
  506. self.extract_function(node);
  507. skip_children = true;
  508. } else if kind == "class_declaration" {
  509. self.extract_class(node, "class");
  510. skip_children = true;
  511. } else if kind == "trait_declaration" {
  512. // classifyClassNode → 'trait'.
  513. self.extract_class(node, "trait");
  514. skip_children = true;
  515. } else if kind == "method_declaration" {
  516. // Inside a class-like → method; outside (an anonymous class's
  517. // members at TOP level — grammar-bump delta #1) the 1747 gate
  518. // bounces to extractFunction: a file-level `function` node.
  519. if self.inside_class_like() {
  520. self.extract_method(node);
  521. } else {
  522. self.extract_function(node);
  523. }
  524. skip_children = true;
  525. } else if kind == "interface_declaration" {
  526. self.extract_interface(node);
  527. skip_children = true;
  528. } else if kind == "enum_declaration" {
  529. self.extract_enum(node);
  530. skip_children = true;
  531. } else if kind == "property_declaration" && self.inside_class_like() {
  532. self.extract_field(node);
  533. self.scan_fn_ref_subtree(node, 0);
  534. skip_children = true;
  535. } else if matches!(
  536. kind,
  537. "namespace_use_declaration" | "include_expression" | "include_once_expression"
  538. | "require_expression" | "require_once_expression"
  539. ) {
  540. self.extract_import(node);
  541. // children still visited (importTypes sets no skipChildren)
  542. } else if matches!(
  543. kind,
  544. "function_call_expression" | "member_call_expression" | "scoped_call_expression"
  545. ) {
  546. self.extract_call(node);
  547. } else if kind == "object_creation_expression" {
  548. self.extract_instantiation(node);
  549. if let Some(anon_body) = find_anonymous_class_body(node) {
  550. // v0.24.2 nests the declaration_list in `anonymous_class`, so
  551. // this never fires — mirrored for shape.
  552. self.extract_anonymous_class(node, anon_body);
  553. skip_children = true;
  554. }
  555. }
  556. // text / php_tag / text_interpolation / namespace_definition /
  557. // nullsafe_member_call_expression / expression_statement / closures /
  558. // match / attributes: no branch — children visited.
  559. if !skip_children {
  560. for i in 0..node.named_child_count() {
  561. if let Some(c) = node.named_child(i) {
  562. self.visit_node(c);
  563. }
  564. }
  565. }
  566. }
  567. // --- visitFunctionBody --------------------------------------------------------
  568. fn visit_function_body(&mut self, body: Node<'t>) {
  569. self.visit_for_calls_and_structure(body);
  570. }
  571. fn visit_for_calls_and_structure(&mut self, node: Node<'t>) {
  572. let kind = node.kind();
  573. self.maybe_capture_fn_refs(node);
  574. if matches!(
  575. kind,
  576. "function_call_expression" | "member_call_expression" | "scoped_call_expression"
  577. ) {
  578. self.extract_call(node);
  579. } else if kind == "object_creation_expression" {
  580. self.extract_instantiation(node);
  581. if let Some(anon_body) = find_anonymous_class_body(node) {
  582. self.extract_anonymous_class(node, anon_body);
  583. return;
  584. }
  585. }
  586. // Static value reads (`Cls::CONST`, `Cls::$prop`, `Cls::class`).
  587. self.extract_static_member_ref(node);
  588. // Nested NAMED functions; body-level class/trait/enum/interface
  589. // declarations (the polyfill idiom). NOTE: no method_declaration
  590. // branch — in-body anonymous-class methods vanish (delta #1), and the
  591. // visitNode hook does NOT run here (a const_declaration in a body-level
  592. // class still extracts via extractClass's own visitNode body walk).
  593. if kind == "function_definition" {
  594. let name = self.extract_name(node);
  595. if name != "<anonymous>" {
  596. self.extract_function(node);
  597. return;
  598. }
  599. }
  600. if kind == "class_declaration" {
  601. self.extract_class(node, "class");
  602. return;
  603. }
  604. if kind == "trait_declaration" {
  605. self.extract_class(node, "trait");
  606. return;
  607. }
  608. if kind == "enum_declaration" {
  609. self.extract_enum(node);
  610. return;
  611. }
  612. if kind == "interface_declaration" {
  613. self.extract_interface(node);
  614. return;
  615. }
  616. for i in 0..node.named_child_count() {
  617. if let Some(c) = node.named_child(i) {
  618. self.visit_for_calls_and_structure(c);
  619. }
  620. }
  621. }
  622. // --- extractors ----------------------------------------------------------------
  623. fn extract_function(&mut self, node: Node<'t>) {
  624. let name = self.extract_name(node);
  625. if name == "<anonymous>" {
  626. if let Some(body) = node.child_by_field_name("body") {
  627. self.visit_function_body(body);
  628. }
  629. return;
  630. }
  631. let extra = Extra {
  632. docstring: preceding_docstring(node, self.src),
  633. signature: None, // no getSignature hook
  634. visibility: Some(self.visibility_of(node)),
  635. is_static: Some(self.is_static(node)),
  636. return_type: self.return_type_of(node),
  637. };
  638. let Some(row) = self.create_node("function", &name, node, extra) else { return };
  639. self.extract_php_type_refs(node, row);
  640. // decorators: none.
  641. self.stack.push(Scope { row, kind: "function", name });
  642. if let Some(body) = node.child_by_field_name("body") {
  643. self.visit_function_body(body);
  644. }
  645. self.stack.pop();
  646. }
  647. fn extract_method(&mut self, node: Node<'t>) {
  648. let name = self.extract_name(node);
  649. let extra = Extra {
  650. docstring: preceding_docstring(node, self.src),
  651. signature: None,
  652. visibility: Some(self.visibility_of(node)),
  653. is_static: Some(self.is_static(node)),
  654. return_type: self.return_type_of(node),
  655. };
  656. let Some(row) = self.create_node("method", &name, node, extra) else { return };
  657. self.extract_php_type_refs(node, row);
  658. self.stack.push(Scope { row, kind: "method", name });
  659. // Bodiless (interface/abstract) methods still mint nodes, no walk.
  660. if let Some(body) = node.child_by_field_name("body") {
  661. self.visit_function_body(body);
  662. }
  663. self.stack.pop();
  664. }
  665. fn extract_class(&mut self, node: Node<'t>, kind: &'static str) {
  666. let name = self.extract_name(node);
  667. let extra = Extra {
  668. docstring: preceding_docstring(node, self.src),
  669. visibility: Some(self.visibility_of(node)),
  670. ..Extra::default()
  671. };
  672. let Some(row) = self.create_node(kind, &name, node, extra) else { return };
  673. self.extract_inheritance(node, row);
  674. // primary-ctor refs: csharp-only (needs a parameter_list child type);
  675. // decorators: none.
  676. self.stack.push(Scope { row, kind, name });
  677. let body = node.child_by_field_name("body").unwrap_or(node);
  678. for i in 0..body.named_child_count() {
  679. if let Some(c) = body.named_child(i) {
  680. self.visit_node(c);
  681. }
  682. }
  683. self.stack.pop();
  684. }
  685. fn extract_interface(&mut self, node: Node<'t>) {
  686. let name = self.extract_name(node);
  687. let extra = Extra {
  688. docstring: preceding_docstring(node, self.src),
  689. ..Extra::default() // NO visibility — extractInterface never asks
  690. };
  691. let Some(row) = self.create_node("interface", &name, node, extra) else { return };
  692. self.extract_inheritance(node, row);
  693. self.stack.push(Scope { row, kind: "interface", name });
  694. let body = node.child_by_field_name("body").unwrap_or(node);
  695. for i in 0..body.named_child_count() {
  696. if let Some(c) = body.named_child(i) {
  697. self.visit_node(c);
  698. }
  699. }
  700. self.stack.pop();
  701. }
  702. fn extract_enum(&mut self, node: Node<'t>) {
  703. let Some(body) = node.child_by_field_name("body") else { return };
  704. let name = self.extract_name(node);
  705. let extra = Extra {
  706. docstring: preceding_docstring(node, self.src),
  707. visibility: Some(self.visibility_of(node)),
  708. ..Extra::default()
  709. };
  710. let Some(row) = self.create_node("enum", &name, node, extra) else { return };
  711. // class_interface_clause → implements refs; the backing type is never
  712. // read (it's not in a base_clause).
  713. self.extract_inheritance(node, row);
  714. self.stack.push(Scope { row, kind: "enum", name });
  715. for i in 0..body.named_child_count() {
  716. let Some(child) = body.named_child(i) else { continue };
  717. if child.kind() == "enum_case" {
  718. self.extract_enum_members(child);
  719. } else {
  720. self.visit_node(child);
  721. }
  722. }
  723. self.stack.pop();
  724. }
  725. fn extract_enum_members(&mut self, node: Node<'t>) {
  726. // name-field path: one enum_member at the enum_case; backed values
  727. // (`= 'H'`) never walked.
  728. if let Some(name_node) = node.child_by_field_name("name") {
  729. let name = self.text(name_node).to_string();
  730. self.create_node("enum_member", &name, node, Extra::default());
  731. }
  732. }
  733. /// extractField — the php property_element branch (2077-2104): one `field`
  734. /// node per element, `$` re-added in the signature only, then RETURN — no
  735. /// decorators, no type-annotation refs from fields.
  736. fn extract_field(&mut self, node: Node<'t>) {
  737. let docstring = preceding_docstring(node, self.src);
  738. let visibility = Some(self.visibility_of(node));
  739. let is_static = Some(self.is_static(node));
  740. let prop_elements: Vec<Node> = (0..node.named_child_count())
  741. .filter_map(|i| node.named_child(i))
  742. .filter(|c| c.kind() == "property_element")
  743. .collect();
  744. if prop_elements.is_empty() {
  745. // The declarator/bare fallbacks find nothing on php shapes.
  746. return;
  747. }
  748. // The type node: first namedChild that isn't a modifier or element.
  749. // QUIRK: final_modifier/abstract_modifier are NOT excluded — a
  750. // `final public Foo $x` takes `final` as the type text. PRESERVE.
  751. let type_node = (0..node.named_child_count())
  752. .filter_map(|i| node.named_child(i))
  753. .find(|c| {
  754. !matches!(
  755. c.kind(),
  756. "visibility_modifier" | "static_modifier" | "readonly_modifier"
  757. | "property_element" | "var_modifier"
  758. )
  759. });
  760. let type_text = type_node.map(|t| self.text(t).to_string());
  761. for elem in prop_elements {
  762. let var_name = (0..elem.named_child_count())
  763. .filter_map(|i| elem.named_child(i))
  764. .find(|c| c.kind() == "variable_name");
  765. let Some(var_name) = var_name else { continue };
  766. let name_node = (0..var_name.named_child_count())
  767. .filter_map(|i| var_name.named_child(i))
  768. .find(|c| c.kind() == "name");
  769. let Some(name_node) = name_node else { continue };
  770. let name = self.text(name_node).to_string();
  771. let signature = match &type_text {
  772. Some(t) => format!("{t} ${name}"),
  773. None => format!("${name}"),
  774. };
  775. self.create_node(
  776. "field",
  777. &name,
  778. elem,
  779. Extra {
  780. docstring: docstring.clone(),
  781. signature: Some(signature),
  782. visibility,
  783. is_static,
  784. ..Extra::default()
  785. },
  786. );
  787. }
  788. }
  789. // --- imports -------------------------------------------------------------------
  790. /// pushPhpUseRef (3563): `Foo\Bar\Baz` → an `imports` ref named
  791. /// `Foo\Bar::Baz`; a global-namespace name (no `\` after stripping one
  792. /// leading `\`) emits nothing here.
  793. fn push_php_use_ref(&mut self, fqn: &str, from_row: u32, node: Node) {
  794. let clean = fqn.strip_prefix('\\').unwrap_or(fqn);
  795. let Some(last_sep) = clean.rfind('\\') else { return };
  796. let name = format!("{}::{}", &clean[..last_sep], &clean[last_sep + 1..]);
  797. self.push_ref_at(from_row, &name, edge_kind_index("imports").unwrap(), node);
  798. }
  799. fn extract_import(&mut self, node: Node<'t>) {
  800. let kind = node.kind();
  801. let import_text = self.text(node).trim().to_string();
  802. let imports_kind = edge_kind_index("imports").unwrap();
  803. if matches!(
  804. kind,
  805. "include_expression" | "include_once_expression" | "require_expression"
  806. | "require_once_expression"
  807. ) {
  808. // phpStaticIncludePath: static string literals only; dynamic
  809. // forms (`__DIR__ . '/x'`, interpolation) emit NOTHING.
  810. let mut arg = node.named_child(0);
  811. if let Some(a) = arg {
  812. if a.kind() == "parenthesized_expression" {
  813. arg = a.named_child(0);
  814. }
  815. }
  816. let Some(arg) = arg else { return };
  817. if !matches!(arg.kind(), "string" | "encapsed_string") {
  818. return;
  819. }
  820. let mut content: Option<Node> = None;
  821. for i in 0..arg.named_child_count() {
  822. let Some(c) = arg.named_child(i) else { continue };
  823. if c.kind() != "string_content" {
  824. return; // interpolation/escape → not a static path
  825. }
  826. if content.is_none() {
  827. content = Some(c);
  828. }
  829. }
  830. let Some(content) = content else { return };
  831. let module_name = self.text(content).to_string();
  832. if module_name.is_empty() {
  833. return;
  834. }
  835. self.create_node(
  836. "import",
  837. &module_name,
  838. node,
  839. Extra { signature: Some(import_text), ..Extra::default() },
  840. );
  841. let parent = self.top_row();
  842. self.push_ref_at(parent, &module_name.clone(), imports_kind, node);
  843. return;
  844. }
  845. // namespace_use_declaration.
  846. let ns_prefix = (0..node.named_child_count())
  847. .filter_map(|i| node.named_child(i))
  848. .find(|c| c.kind() == "namespace_name");
  849. let use_group = (0..node.named_child_count())
  850. .filter_map(|i| node.named_child(i))
  851. .find(|c| c.kind() == "namespace_use_group");
  852. if let (Some(ns_prefix), Some(use_group)) = (ns_prefix, use_group) {
  853. // Grouped `use A\{B, C as D, Sub\E}` — hook declines, the inline
  854. // branch emits per-member nodes named `A\B` (first `name` child =
  855. // the SOURCE name; a nested `Sub\E` clause has a qualified_name,
  856. // no direct `name` → SKIPPED, grammar-bump delta #2). All nodes
  857. // and refs sit at the whole declaration's position.
  858. let prefix = self.text(ns_prefix).to_string();
  859. let clauses: Vec<Node> = (0..use_group.named_child_count())
  860. .filter_map(|i| use_group.named_child(i))
  861. .filter(|c| {
  862. matches!(c.kind(), "namespace_use_group_clause" | "namespace_use_clause")
  863. })
  864. .collect();
  865. for clause in clauses {
  866. let ns_name = (0..clause.named_child_count())
  867. .filter_map(|i| clause.named_child(i))
  868. .find(|c| c.kind() == "namespace_name");
  869. let name = match ns_name {
  870. Some(nn) => (0..nn.named_child_count())
  871. .filter_map(|i| nn.named_child(i))
  872. .find(|c| c.kind() == "name"),
  873. None => (0..clause.named_child_count())
  874. .filter_map(|i| clause.named_child(i))
  875. .find(|c| c.kind() == "name"),
  876. };
  877. if let Some(name) = name {
  878. let full = format!("{prefix}\\{}", self.text(name));
  879. self.create_node(
  880. "import",
  881. &full,
  882. node,
  883. Extra { signature: Some(import_text.clone()), ..Extra::default() },
  884. );
  885. let parent = self.top_row();
  886. self.push_php_use_ref(&full, parent, node);
  887. }
  888. }
  889. return;
  890. }
  891. // Single use (incl. `use function`/`use const`/aliased): the hook's
  892. // qualified_name-else-name read; alias never included.
  893. let use_clause = (0..node.named_child_count())
  894. .filter_map(|i| node.named_child(i))
  895. .find(|c| c.kind() == "namespace_use_clause");
  896. let Some(use_clause) = use_clause else { return };
  897. let target = (0..use_clause.named_child_count())
  898. .filter_map(|i| use_clause.named_child(i))
  899. .find(|c| c.kind() == "qualified_name")
  900. .or_else(|| {
  901. (0..use_clause.named_child_count())
  902. .filter_map(|i| use_clause.named_child(i))
  903. .find(|c| c.kind() == "name")
  904. });
  905. let Some(target) = target else { return }; // hook null → nothing
  906. let module_name = self.text(target).to_string();
  907. if module_name.is_empty() {
  908. return;
  909. }
  910. self.create_node(
  911. "import",
  912. &module_name,
  913. node,
  914. Extra { signature: Some(import_text), ..Extra::default() },
  915. );
  916. let parent = self.top_row();
  917. self.push_ref_at(parent, &module_name.clone(), imports_kind, node);
  918. // emitPhpUseRefs → the `Foo\Bar::Baz` ref (bare single-segment `use
  919. // Countable;` has no `\` → no `::` ref).
  920. self.push_php_use_ref(&module_name, parent, node);
  921. }
  922. // --- calls ---------------------------------------------------------------------
  923. fn extract_call(&mut self, node: Node<'t>) {
  924. if self.stack.is_empty() {
  925. return;
  926. }
  927. let caller = self.top_row();
  928. let mut callee_name = String::new();
  929. let name_field = node.child_by_field_name("name");
  930. let object_field = node
  931. .child_by_field_name("object")
  932. .or_else(|| node.child_by_field_name("scope"));
  933. if let (Some(name_field), Some(object_field)) = (name_field, object_field) {
  934. // member_call_expression / scoped_call_expression.
  935. let method_name = self.text(name_field);
  936. // Fluent static-factory `Cls::factory($x)->method()` — encode
  937. // `Cls::factory().method` (inner args dropped) and return; the
  938. // inner scoped call is also visited by recursion (`Cls.factory`).
  939. if !method_name.is_empty() && object_field.kind() == "scoped_call_expression" {
  940. let inner_scope = object_field.child_by_field_name("scope");
  941. let inner_name = object_field.child_by_field_name("name");
  942. let callee = match (inner_scope, inner_name) {
  943. (Some(s), Some(n)) => {
  944. format!("{}::{}().{method_name}", self.text(s), self.text(n))
  945. }
  946. _ => method_name.to_string(),
  947. };
  948. if !callee.is_empty() {
  949. self.push_ref_at(caller, &callee, edge_kind_index("calls").unwrap(), node);
  950. }
  951. return;
  952. }
  953. // receiverName = raw receiver text with ONE leading `$` stripped:
  954. // `$this->prop->m()` → `this->prop.m` (#1251 encoding — the whole
  955. // resolution machinery is TS-side); chains keep args
  956. // (`this->factory($cfg).m`); literals are NOT suppressed
  957. // (`"chain".upper`); scoped calls are DOT-joined (`UserModel.query`).
  958. let receiver_raw = self.text(object_field);
  959. let receiver = receiver_raw.strip_prefix('$').unwrap_or(receiver_raw);
  960. if !method_name.is_empty() {
  961. if matches!(receiver, "self" | "this" | "cls" | "super" | "parent" | "static") {
  962. callee_name = method_name.to_string();
  963. } else {
  964. callee_name = format!("{receiver}.{method_name}");
  965. }
  966. }
  967. } else {
  968. // function_call_expression: raw func text — bare `helper`,
  969. // qualified `\App\Helpers\format_id` verbatim, `$fn` for
  970. // variable callees, FCC `f(...)` → `f`.
  971. let func = node
  972. .child_by_field_name("function")
  973. .or_else(|| node.named_child(0));
  974. if let Some(func) = func {
  975. callee_name = self.text(func).to_string();
  976. }
  977. }
  978. if !callee_name.is_empty() {
  979. if let Some(c) = util::paren_conversion().captures(&callee_name) {
  980. callee_name = c[1].to_string();
  981. }
  982. self.push_ref_at(caller, &callee_name.clone(), edge_kind_index("calls").unwrap(), node);
  983. }
  984. }
  985. fn extract_instantiation(&mut self, node: Node<'t>) {
  986. if self.stack.is_empty() {
  987. return;
  988. }
  989. // php has no constructor/type/name FIELDS → namedChild(0). Backslashes
  990. // are NOT split by the suffix logic → `new \App\Models\User()` keeps
  991. // the full qualified text; `new $cls()` keeps the `$`; an
  992. // anonymous_class yields its whole source text through the shared
  993. // normalization (garbage, deterministic — preserve).
  994. let ctor = node
  995. .child_by_field_name("constructor")
  996. .or_else(|| node.child_by_field_name("type"))
  997. .or_else(|| node.child_by_field_name("name"))
  998. .or_else(|| node.named_child(0));
  999. let Some(ctor) = ctor else { return };
  1000. let class_name = strip_generic_and_qualifier(self.text(ctor));
  1001. if !class_name.is_empty() {
  1002. let from = self.top_row();
  1003. self.push_ref_at(from, &class_name, edge_kind_index("instantiates").unwrap(), node);
  1004. }
  1005. }
  1006. /// extractAnonymousClass — unreachable on v0.24.2 (the declaration_list
  1007. /// nests inside `anonymous_class`, so findAnonymousClassBody finds no
  1008. /// DIRECT child) — mirrored from the shared TS path for shape.
  1009. fn extract_anonymous_class(&mut self, node: Node<'t>, body: Node<'t>) {
  1010. let type_node = node
  1011. .child_by_field_name("constructor")
  1012. .or_else(|| node.child_by_field_name("type"))
  1013. .or_else(|| node.child_by_field_name("name"))
  1014. .or_else(|| node.named_child(0));
  1015. let mut type_name =
  1016. type_node.map(|t| self.text(t).to_string()).unwrap_or_else(|| "Object".to_string());
  1017. type_name = strip_generic_and_qualifier(&type_name);
  1018. if type_name.is_empty() {
  1019. type_name = "Object".to_string();
  1020. }
  1021. let anon_name = format!("<{type_name}$anon@{}>", node.start_position().row + 1);
  1022. let Some(row) = self.create_node("class", &anon_name, node, Extra::default()) else {
  1023. return;
  1024. };
  1025. let (line, column) = match type_node {
  1026. Some(t) => (t.start_position().row as u32, self.col_of(t)),
  1027. None => (node.start_position().row as u32, self.col_of(node)),
  1028. };
  1029. self.push_ref(row, &type_name, edge_kind_index("extends").unwrap(), line, column);
  1030. self.stack.push(Scope { row, kind: "class", name: anon_name });
  1031. for i in 0..body.named_child_count() {
  1032. if let Some(c) = body.named_child(i) {
  1033. self.visit_node(c);
  1034. }
  1035. }
  1036. self.stack.pop();
  1037. }
  1038. /// extractStaticMemberRef — php's class_constant_access_expression +
  1039. /// scoped_property_access_expression (member_access_expression is
  1040. /// evaluated but its variable_name receiver never passes).
  1041. fn extract_static_member_ref(&mut self, node: Node<'t>) {
  1042. if !matches!(
  1043. node.kind(),
  1044. "class_constant_access_expression" | "scoped_property_access_expression"
  1045. | "member_access_expression"
  1046. ) {
  1047. return;
  1048. }
  1049. if self.stack.is_empty() {
  1050. return;
  1051. }
  1052. let owner = self.top_row();
  1053. if let Some(parent) = node.parent() {
  1054. if matches!(
  1055. parent.kind(),
  1056. "function_call_expression" | "member_call_expression" | "scoped_call_expression"
  1057. ) {
  1058. let callee = parent
  1059. .child_by_field_name("function")
  1060. .or_else(|| parent.child_by_field_name("method"))
  1061. .or_else(|| parent.named_child(0));
  1062. if let Some(callee) = callee {
  1063. if callee.start_byte() == node.start_byte() {
  1064. return;
  1065. }
  1066. }
  1067. }
  1068. }
  1069. let recv = node
  1070. .child_by_field_name("object")
  1071. .or_else(|| node.child_by_field_name("expression"))
  1072. .or_else(|| node.child_by_field_name("scope"))
  1073. .or_else(|| node.named_child(0));
  1074. let Some(recv) = recv else { return };
  1075. if matches!(
  1076. recv.kind(),
  1077. "identifier" | "type_identifier" | "simple_identifier" | "name" | "scoped_type_identifier"
  1078. ) {
  1079. let text = self.text(recv);
  1080. if capitalized_re().is_match(text) {
  1081. self.push_ref_at(owner, &text.to_string(), edge_kind_index("references").unwrap(), recv);
  1082. }
  1083. }
  1084. }
  1085. /// extractInheritance — base_clause takes ONLY the first base (interface
  1086. /// multi-extends drops the rest); class_interface_clause takes ALL
  1087. /// children unfiltered (full text, incl. leading `\`).
  1088. fn extract_inheritance(&mut self, node: Node<'t>, class_row: u32) {
  1089. let extends_kind = edge_kind_index("extends").unwrap();
  1090. let implements_kind = edge_kind_index("implements").unwrap();
  1091. for i in 0..node.named_child_count() {
  1092. let Some(child) = node.named_child(i) else { continue };
  1093. if child.kind() == "base_clause" {
  1094. if let Some(target) = child.named_child(0) {
  1095. let name = self.text(target).to_string();
  1096. self.push_ref_at(class_row, &name, extends_kind, target);
  1097. }
  1098. } else if child.kind() == "class_interface_clause" {
  1099. for j in 0..child.named_child_count() {
  1100. let Some(iface) = child.named_child(j) else { continue };
  1101. let name = self.text(iface).to_string();
  1102. self.push_ref_at(class_row, &name, implements_kind, iface);
  1103. }
  1104. }
  1105. }
  1106. }
  1107. // --- php type refs (extractPhpTypeRefs, 6022) ----------------------------------
  1108. fn extract_php_type_refs(&mut self, node: Node<'t>, from_row: u32) {
  1109. let params = (0..node.named_child_count())
  1110. .filter_map(|i| node.named_child(i))
  1111. .find(|c| c.kind() == "formal_parameters");
  1112. if let Some(params) = params {
  1113. for i in 0..params.named_child_count() {
  1114. let Some(p) = params.named_child(i) else { continue };
  1115. for j in 0..p.named_child_count() {
  1116. let Some(c) = p.named_child(j) else { continue };
  1117. if is_php_type_node(c.kind()) {
  1118. self.walk_php_type_position(c, from_row);
  1119. }
  1120. }
  1121. }
  1122. }
  1123. for i in 0..node.named_child_count() {
  1124. let Some(c) = node.named_child(i) else { continue };
  1125. if is_php_type_node(c.kind()) {
  1126. self.walk_php_type_position(c, from_row);
  1127. }
  1128. }
  1129. }
  1130. fn walk_php_type_position(&mut self, node: Node<'t>, from_row: u32) {
  1131. match node.kind() {
  1132. "primitive_type" => {}
  1133. "name" => {
  1134. let name = self.text(node);
  1135. if !name.is_empty() && !is_php_pseudo_type(name) {
  1136. self.push_ref_at(from_row, &name.to_string(), edge_kind_index("references").unwrap(), node);
  1137. }
  1138. }
  1139. "qualified_name" => {
  1140. let text = self.text(node);
  1141. let last = text.rsplit('\\').next().unwrap_or("");
  1142. if !last.is_empty() && !is_php_pseudo_type(last) {
  1143. self.push_ref_at(from_row, &last.to_string(), edge_kind_index("references").unwrap(), node);
  1144. }
  1145. }
  1146. _ => {
  1147. for i in 0..node.named_child_count() {
  1148. if let Some(c) = node.named_child(i) {
  1149. self.walk_php_type_position(c, from_row);
  1150. }
  1151. }
  1152. }
  1153. }
  1154. }
  1155. // --- function-as-value refs (PHP_SPEC, function-ref.ts:360) --------------------
  1156. fn maybe_capture_fn_refs(&mut self, node: Node<'t>) {
  1157. if node.kind() != "arguments" {
  1158. return;
  1159. }
  1160. if self.stack.is_empty() {
  1161. return;
  1162. }
  1163. let from = self.top_row();
  1164. for i in 0..node.named_child_count() {
  1165. if let Some(c) = node.named_child(i) {
  1166. self.normalize_fn_ref_value(c, from, 0);
  1167. }
  1168. }
  1169. }
  1170. fn normalize_fn_ref_value(&mut self, v: Node<'t>, from: u32, depth: u32) {
  1171. if depth > 4 {
  1172. return;
  1173. }
  1174. match v.kind() {
  1175. "argument" => {
  1176. for i in 0..v.named_child_count() {
  1177. if let Some(c) = v.named_child(i) {
  1178. self.normalize_fn_ref_value(c, from, depth + 1);
  1179. }
  1180. }
  1181. }
  1182. // String callable — trustworthy ONLY as an argument to a known
  1183. // callable-taking core function; skipGate (resolution's
  1184. // unique-or-drop rule takes over). Namespaced strings drop.
  1185. "string" | "encapsed_string" => {
  1186. let Some(callee) = php_enclosing_call_name(v).map(|f| self.text(f)) else {
  1187. return;
  1188. };
  1189. if !is_php_callable_hof(callee) {
  1190. return;
  1191. }
  1192. let Some(content) = self.php_string_content(v) else { return };
  1193. if simple_callable_re().is_match(&content) || qualified_callable_re().is_match(&content)
  1194. {
  1195. self.push_fn_ref_cand(from, &content, v, true);
  1196. }
  1197. }
  1198. // Array callables in ANY call's arguments: `[$this, 'm']` →
  1199. // this.m; `[Foo::class, 'm']` → Foo::m; `['Cls', 'm']` → nothing.
  1200. "array_creation_expression" => {
  1201. if v.named_child_count() != 2 {
  1202. return;
  1203. }
  1204. let recv = v.named_child(0).and_then(|e| e.named_child(0));
  1205. let str_el = v.named_child(1).and_then(|e| e.named_child(0));
  1206. let (Some(recv), Some(str_el)) = (recv, str_el) else { return };
  1207. if !matches!(str_el.kind(), "encapsed_string" | "string") {
  1208. return;
  1209. }
  1210. let Some(member) = self.php_string_content(str_el) else { return };
  1211. if !simple_callable_re().is_match(&member) {
  1212. return;
  1213. }
  1214. if recv.kind() == "variable_name" && self.text(recv) == "$this" {
  1215. let name = format!("this.{member}");
  1216. self.push_fn_ref_cand(from, &name, str_el, false);
  1217. } else if recv.kind() == "class_constant_access_expression" {
  1218. let cls = recv.named_child(0);
  1219. let kw = recv.named_child(1);
  1220. if let (Some(cls), Some(kw)) = (cls, kw) {
  1221. if self.text(kw) == "class" {
  1222. let name = format!("{}::{member}", self.text(cls));
  1223. self.push_fn_ref_cand(from, &name, str_el, false);
  1224. }
  1225. }
  1226. }
  1227. }
  1228. _ => {}
  1229. }
  1230. }
  1231. /// phpStringContent: the string's first string_content child, trimmed.
  1232. fn php_string_content(&self, node: Node) -> Option<String> {
  1233. for i in 0..node.named_child_count() {
  1234. let Some(c) = node.named_child(i) else { continue };
  1235. if c.kind() == "string_content" {
  1236. return Some(self.text(c).trim().to_string());
  1237. }
  1238. }
  1239. None
  1240. }
  1241. fn push_fn_ref_cand(&mut self, from: u32, name: &str, node: Node, skip_gate: bool) {
  1242. if name.is_empty() || is_stoplisted(name) {
  1243. return;
  1244. }
  1245. let p = node.start_position();
  1246. self.fn_ref_cands.push(Cand {
  1247. from,
  1248. name: name.to_string(),
  1249. line: p.row as u32 + 1,
  1250. column_byte: node.start_byte(),
  1251. row: p.row,
  1252. skip_gate,
  1253. });
  1254. }
  1255. fn scan_fn_ref_subtree(&mut self, node: Node<'t>, depth: u32) {
  1256. if depth > 12 {
  1257. return;
  1258. }
  1259. // Halts at functionTypes (function_definition) + arrow_function (in
  1260. // the fixed list); anonymous_function is NOT halted — scans descend
  1261. // into closures.
  1262. if depth > 0
  1263. && matches!(
  1264. node.kind(),
  1265. "function_definition" | "arrow_function" | "function_expression" | "lambda_literal"
  1266. | "lambda_expression"
  1267. )
  1268. {
  1269. return;
  1270. }
  1271. self.maybe_capture_fn_refs(node);
  1272. for i in 0..node.named_child_count() {
  1273. if let Some(c) = node.named_child(i) {
  1274. self.scan_fn_ref_subtree(c, depth + 1);
  1275. }
  1276. }
  1277. }
  1278. fn flush_fn_ref_candidates(&mut self) {
  1279. let cands = std::mem::take(&mut self.fn_ref_cands);
  1280. if cands.is_empty() || util::is_generated_file(self.file_path) {
  1281. return;
  1282. }
  1283. let mut seen: HashSet<(String, String)> = HashSet::new();
  1284. for c in cands {
  1285. // `this.<m>` and `Cls::m` shapes always flush; HOF-position string
  1286. // callables skip the gate (unique-or-drop at resolution); the rest
  1287. // gate on defined-in-file ∪ bare single-segment `use` imports
  1288. // (path-shaped and `::`-shaped import refs match neither regex).
  1289. if !c.name.starts_with("this.") && !c.name.contains("::") {
  1290. let skip = c.skip_gate;
  1291. if !skip
  1292. && !self.defined_fn_names.contains(&c.name)
  1293. && !self.imported_names.contains(&c.name)
  1294. {
  1295. continue;
  1296. }
  1297. }
  1298. if !seen.insert((self.node_ids[c.from as usize].clone(), c.name.clone())) {
  1299. continue;
  1300. }
  1301. let column = util::col16(self.src, &self.line_starts, c.row, c.column_byte);
  1302. let name_ref = self.arena.put(&c.name);
  1303. self.tables.push_ref(&RefRow {
  1304. from_idx: c.from,
  1305. kind: FUNCTION_REF_CODE,
  1306. line: c.line,
  1307. column,
  1308. reference_name: name_ref,
  1309. candidates: NONE_STR,
  1310. from_id_str: NONE_STR,
  1311. });
  1312. }
  1313. }
  1314. // --- value references ------------------------------------------------------------
  1315. fn flush_value_refs(&mut self) {
  1316. let scopes = std::mem::take(&mut self.value_scopes);
  1317. let targets = std::mem::take(&mut self.fs_values);
  1318. let _counts = std::mem::take(&mut self.fs_value_counts);
  1319. if std::env::var("CODEGRAPH_VALUE_REFS").as_deref() == Ok("0") {
  1320. return;
  1321. }
  1322. if targets.is_empty() || scopes.is_empty() || util::is_generated_file(self.file_path) {
  1323. return;
  1324. }
  1325. // Shadow prune: the per-grammar declarator switch has NO resolving php
  1326. // cases (`assignment` is python's node; property_declaration's
  1327. // Kotlin/Swift path yields null) → declCounts stays empty → no php
  1328. // target is ever pruned. Skipping the scan is byte-identical.
  1329. let refs_kind = edge_kind_index("references").unwrap();
  1330. for scope in &scopes {
  1331. let mut seen: HashSet<&str> = HashSet::new();
  1332. let mut stack: Vec<Node> = vec![scope.node];
  1333. let mut visited = 0usize;
  1334. while let Some(n) = stack.pop() {
  1335. if visited >= MAX_VALUE_REF_NODES {
  1336. break;
  1337. }
  1338. visited += 1;
  1339. // `name` is the php-live reader kind — ANY textual occurrence
  1340. // of a target name in a reader's subtree emits (const reads,
  1341. // `self::MAX`, `$MAX` variable names, interpolated `$MAX`).
  1342. if matches!(n.kind(), "identifier" | "constant" | "name" | "simple_identifier") {
  1343. let ref_name = self.text(n);
  1344. if let Some(&target_row) = targets.get(ref_name) {
  1345. let target_id = self.node_ids[target_row as usize].as_str();
  1346. if target_id != self.node_ids[scope.row as usize]
  1347. && ref_name != scope.name
  1348. && !seen.contains(&target_id)
  1349. {
  1350. seen.insert(target_id);
  1351. let meta = self.arena.put(r#"{"valueRef":true}"#);
  1352. self.tables.push_edge(&EdgeRow {
  1353. source_idx: scope.row,
  1354. target_idx: target_row,
  1355. kind: refs_kind,
  1356. provenance: 0,
  1357. line: NONE,
  1358. column: NONE,
  1359. metadata_json: meta,
  1360. source_id_str: NONE_STR,
  1361. target_id_str: NONE_STR,
  1362. });
  1363. }
  1364. }
  1365. }
  1366. for i in 0..n.named_child_count() {
  1367. if let Some(c) = n.named_child(i) {
  1368. stack.push(c);
  1369. }
  1370. }
  1371. }
  1372. }
  1373. }
  1374. }
  1375. /// The function name node of the php call whose arguments contain `node` —
  1376. /// ≤4 parent hops to a function_call_expression; member/scoped calls abort
  1377. /// (method-call HOFs never qualify). (function-ref.ts:822)
  1378. fn php_enclosing_call_name(node: Node) -> Option<Node> {
  1379. let mut cur = node.parent();
  1380. for _ in 0..4 {
  1381. let c = cur?;
  1382. if c.kind() == "function_call_expression" {
  1383. return c.child_by_field_name("function");
  1384. }
  1385. if matches!(c.kind(), "member_call_expression" | "scoped_call_expression") {
  1386. return None;
  1387. }
  1388. cur = c.parent();
  1389. }
  1390. None
  1391. }
  1392. fn find_anonymous_class_body(node: Node) -> Option<Node> {
  1393. for i in 0..node.named_child_count() {
  1394. if let Some(child) = node.named_child(i) {
  1395. if matches!(child.kind(), "class_body" | "declaration_list") {
  1396. return Some(child);
  1397. }
  1398. }
  1399. }
  1400. None
  1401. }
  1402. /// The shared `new ns.Foo<T>()` normalization: strip `<...` from the first
  1403. /// `<` (index > 0), keep the segment after the last `.`/`::`, strip ONE
  1404. /// leading `:` or `.`, trim. Backslashes are NOT handled — php qualified
  1405. /// names pass through whole.
  1406. fn strip_generic_and_qualifier(raw: &str) -> String {
  1407. let mut name = raw.to_string();
  1408. if let Some(lt) = name.find('<') {
  1409. if lt > 0 {
  1410. name.truncate(lt);
  1411. }
  1412. }
  1413. let last_dot = name
  1414. .rfind('.')
  1415. .map(|i| i as isize)
  1416. .unwrap_or(-1)
  1417. .max(name.rfind("::").map(|i| i as isize).unwrap_or(-1));
  1418. if last_dot >= 0 {
  1419. name = name[(last_dot as usize + 1)..].to_string();
  1420. if name.starts_with(':') || name.starts_with('.') {
  1421. name.remove(0);
  1422. }
  1423. }
  1424. name.trim().to_string()
  1425. }
  1426. fn opt_str(arena: &mut Arena, s: Option<&str>) -> StrRef {
  1427. match s {
  1428. Some(s) => arena.put(s),
  1429. None => NONE_STR,
  1430. }
  1431. }