1
0

php.rs 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536
  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. stack_guard!();
  497. if self.try_visit_hook(node) {
  498. self.scan_fn_ref_subtree(node, 0);
  499. return;
  500. }
  501. let kind = node.kind();
  502. let mut skip_children = false;
  503. self.maybe_capture_fn_refs(node);
  504. if kind == "function_definition" {
  505. // functionTypes; method_declaration is not in it, so this is
  506. // always extractFunction (php functions can't be class members).
  507. self.extract_function(node);
  508. skip_children = true;
  509. } else if kind == "class_declaration" {
  510. self.extract_class(node, "class");
  511. skip_children = true;
  512. } else if kind == "trait_declaration" {
  513. // classifyClassNode → 'trait'.
  514. self.extract_class(node, "trait");
  515. skip_children = true;
  516. } else if kind == "method_declaration" {
  517. // Inside a class-like → method; outside (an anonymous class's
  518. // members at TOP level — grammar-bump delta #1) the 1747 gate
  519. // bounces to extractFunction: a file-level `function` node.
  520. if self.inside_class_like() {
  521. self.extract_method(node);
  522. } else {
  523. self.extract_function(node);
  524. }
  525. skip_children = true;
  526. } else if kind == "interface_declaration" {
  527. self.extract_interface(node);
  528. skip_children = true;
  529. } else if kind == "enum_declaration" {
  530. self.extract_enum(node);
  531. skip_children = true;
  532. } else if kind == "property_declaration" && self.inside_class_like() {
  533. self.extract_field(node);
  534. self.scan_fn_ref_subtree(node, 0);
  535. skip_children = true;
  536. } else if matches!(
  537. kind,
  538. "namespace_use_declaration" | "include_expression" | "include_once_expression"
  539. | "require_expression" | "require_once_expression"
  540. ) {
  541. self.extract_import(node);
  542. // children still visited (importTypes sets no skipChildren)
  543. } else if matches!(
  544. kind,
  545. "function_call_expression" | "member_call_expression" | "scoped_call_expression"
  546. ) {
  547. self.extract_call(node);
  548. } else if kind == "object_creation_expression" {
  549. self.extract_instantiation(node);
  550. if let Some(anon_body) = find_anonymous_class_body(node) {
  551. // v0.24.2 nests the declaration_list in `anonymous_class`, so
  552. // this never fires — mirrored for shape.
  553. self.extract_anonymous_class(node, anon_body);
  554. skip_children = true;
  555. }
  556. }
  557. // text / php_tag / text_interpolation / namespace_definition /
  558. // nullsafe_member_call_expression / expression_statement / closures /
  559. // match / attributes: no branch — children visited.
  560. if !skip_children {
  561. for i in 0..node.named_child_count() {
  562. if let Some(c) = node.named_child(i) {
  563. self.visit_node(c);
  564. }
  565. }
  566. }
  567. }
  568. // --- visitFunctionBody --------------------------------------------------------
  569. fn visit_function_body(&mut self, body: Node<'t>) {
  570. stack_guard!();
  571. self.visit_for_calls_and_structure(body);
  572. }
  573. fn visit_for_calls_and_structure(&mut self, node: Node<'t>) {
  574. stack_guard!();
  575. let kind = node.kind();
  576. self.maybe_capture_fn_refs(node);
  577. if matches!(
  578. kind,
  579. "function_call_expression" | "member_call_expression" | "scoped_call_expression"
  580. ) {
  581. self.extract_call(node);
  582. } else if kind == "object_creation_expression" {
  583. self.extract_instantiation(node);
  584. if let Some(anon_body) = find_anonymous_class_body(node) {
  585. self.extract_anonymous_class(node, anon_body);
  586. return;
  587. }
  588. }
  589. // Static value reads (`Cls::CONST`, `Cls::$prop`, `Cls::class`).
  590. self.extract_static_member_ref(node);
  591. // Nested NAMED functions; body-level class/trait/enum/interface
  592. // declarations (the polyfill idiom). NOTE: no method_declaration
  593. // branch — in-body anonymous-class methods vanish (delta #1), and the
  594. // visitNode hook does NOT run here (a const_declaration in a body-level
  595. // class still extracts via extractClass's own visitNode body walk).
  596. if kind == "function_definition" {
  597. let name = self.extract_name(node);
  598. if name != "<anonymous>" {
  599. self.extract_function(node);
  600. return;
  601. }
  602. }
  603. if kind == "class_declaration" {
  604. self.extract_class(node, "class");
  605. return;
  606. }
  607. if kind == "trait_declaration" {
  608. self.extract_class(node, "trait");
  609. return;
  610. }
  611. if kind == "enum_declaration" {
  612. self.extract_enum(node);
  613. return;
  614. }
  615. if kind == "interface_declaration" {
  616. self.extract_interface(node);
  617. return;
  618. }
  619. for i in 0..node.named_child_count() {
  620. if let Some(c) = node.named_child(i) {
  621. self.visit_for_calls_and_structure(c);
  622. }
  623. }
  624. }
  625. // --- extractors ----------------------------------------------------------------
  626. fn extract_function(&mut self, node: Node<'t>) {
  627. stack_guard!();
  628. let name = self.extract_name(node);
  629. if name == "<anonymous>" {
  630. if let Some(body) = node.child_by_field_name("body") {
  631. self.visit_function_body(body);
  632. }
  633. return;
  634. }
  635. let extra = Extra {
  636. docstring: preceding_docstring(node, self.src),
  637. signature: None, // no getSignature hook
  638. visibility: Some(self.visibility_of(node)),
  639. is_static: Some(self.is_static(node)),
  640. return_type: self.return_type_of(node),
  641. };
  642. let Some(row) = self.create_node("function", &name, node, extra) else { return };
  643. self.extract_php_type_refs(node, row);
  644. // decorators: none.
  645. self.stack.push(Scope { row, kind: "function", name });
  646. if let Some(body) = node.child_by_field_name("body") {
  647. self.visit_function_body(body);
  648. }
  649. self.stack.pop();
  650. }
  651. fn extract_method(&mut self, node: Node<'t>) {
  652. stack_guard!();
  653. let name = self.extract_name(node);
  654. let extra = Extra {
  655. docstring: preceding_docstring(node, self.src),
  656. signature: None,
  657. visibility: Some(self.visibility_of(node)),
  658. is_static: Some(self.is_static(node)),
  659. return_type: self.return_type_of(node),
  660. };
  661. let Some(row) = self.create_node("method", &name, node, extra) else { return };
  662. self.extract_php_type_refs(node, row);
  663. self.stack.push(Scope { row, kind: "method", name });
  664. // Bodiless (interface/abstract) methods still mint nodes, no walk.
  665. if let Some(body) = node.child_by_field_name("body") {
  666. self.visit_function_body(body);
  667. }
  668. self.stack.pop();
  669. }
  670. fn extract_class(&mut self, node: Node<'t>, kind: &'static str) {
  671. stack_guard!();
  672. let name = self.extract_name(node);
  673. let extra = Extra {
  674. docstring: preceding_docstring(node, self.src),
  675. visibility: Some(self.visibility_of(node)),
  676. ..Extra::default()
  677. };
  678. let Some(row) = self.create_node(kind, &name, node, extra) else { return };
  679. self.extract_inheritance(node, row);
  680. // primary-ctor refs: csharp-only (needs a parameter_list child type);
  681. // decorators: none.
  682. self.stack.push(Scope { row, kind, name });
  683. let body = node.child_by_field_name("body").unwrap_or(node);
  684. for i in 0..body.named_child_count() {
  685. if let Some(c) = body.named_child(i) {
  686. self.visit_node(c);
  687. }
  688. }
  689. self.stack.pop();
  690. }
  691. fn extract_interface(&mut self, node: Node<'t>) {
  692. stack_guard!();
  693. let name = self.extract_name(node);
  694. let extra = Extra {
  695. docstring: preceding_docstring(node, self.src),
  696. ..Extra::default() // NO visibility — extractInterface never asks
  697. };
  698. let Some(row) = self.create_node("interface", &name, node, extra) else { return };
  699. self.extract_inheritance(node, row);
  700. self.stack.push(Scope { row, kind: "interface", name });
  701. let body = node.child_by_field_name("body").unwrap_or(node);
  702. for i in 0..body.named_child_count() {
  703. if let Some(c) = body.named_child(i) {
  704. self.visit_node(c);
  705. }
  706. }
  707. self.stack.pop();
  708. }
  709. fn extract_enum(&mut self, node: Node<'t>) {
  710. stack_guard!();
  711. let Some(body) = node.child_by_field_name("body") else { return };
  712. let name = self.extract_name(node);
  713. let extra = Extra {
  714. docstring: preceding_docstring(node, self.src),
  715. visibility: Some(self.visibility_of(node)),
  716. ..Extra::default()
  717. };
  718. let Some(row) = self.create_node("enum", &name, node, extra) else { return };
  719. // class_interface_clause → implements refs; the backing type is never
  720. // read (it's not in a base_clause).
  721. self.extract_inheritance(node, row);
  722. self.stack.push(Scope { row, kind: "enum", name });
  723. for i in 0..body.named_child_count() {
  724. let Some(child) = body.named_child(i) else { continue };
  725. if child.kind() == "enum_case" {
  726. self.extract_enum_members(child);
  727. } else {
  728. self.visit_node(child);
  729. }
  730. }
  731. self.stack.pop();
  732. }
  733. fn extract_enum_members(&mut self, node: Node<'t>) {
  734. // name-field path: one enum_member at the enum_case; backed values
  735. // (`= 'H'`) never walked.
  736. if let Some(name_node) = node.child_by_field_name("name") {
  737. let name = self.text(name_node).to_string();
  738. self.create_node("enum_member", &name, node, Extra::default());
  739. }
  740. }
  741. /// extractField — the php property_element branch (2077-2104): one `field`
  742. /// node per element, `$` re-added in the signature only, then RETURN — no
  743. /// decorators, no type-annotation refs from fields.
  744. fn extract_field(&mut self, node: Node<'t>) {
  745. let docstring = preceding_docstring(node, self.src);
  746. let visibility = Some(self.visibility_of(node));
  747. let is_static = Some(self.is_static(node));
  748. let prop_elements: Vec<Node> = (0..node.named_child_count())
  749. .filter_map(|i| node.named_child(i))
  750. .filter(|c| c.kind() == "property_element")
  751. .collect();
  752. if prop_elements.is_empty() {
  753. // The declarator/bare fallbacks find nothing on php shapes.
  754. return;
  755. }
  756. // The type node: first namedChild that isn't a modifier or element.
  757. // QUIRK: final_modifier/abstract_modifier are NOT excluded — a
  758. // `final public Foo $x` takes `final` as the type text. PRESERVE.
  759. let type_node = (0..node.named_child_count())
  760. .filter_map(|i| node.named_child(i))
  761. .find(|c| {
  762. !matches!(
  763. c.kind(),
  764. "visibility_modifier" | "static_modifier" | "readonly_modifier"
  765. | "property_element" | "var_modifier"
  766. )
  767. });
  768. let type_text = type_node.map(|t| self.text(t).to_string());
  769. for elem in prop_elements {
  770. let var_name = (0..elem.named_child_count())
  771. .filter_map(|i| elem.named_child(i))
  772. .find(|c| c.kind() == "variable_name");
  773. let Some(var_name) = var_name else { continue };
  774. let name_node = (0..var_name.named_child_count())
  775. .filter_map(|i| var_name.named_child(i))
  776. .find(|c| c.kind() == "name");
  777. let Some(name_node) = name_node else { continue };
  778. let name = self.text(name_node).to_string();
  779. let signature = match &type_text {
  780. Some(t) => format!("{t} ${name}"),
  781. None => format!("${name}"),
  782. };
  783. self.create_node(
  784. "field",
  785. &name,
  786. elem,
  787. Extra {
  788. docstring: docstring.clone(),
  789. signature: Some(signature),
  790. visibility,
  791. is_static,
  792. ..Extra::default()
  793. },
  794. );
  795. }
  796. }
  797. // --- imports -------------------------------------------------------------------
  798. /// pushPhpUseRef (3563): `Foo\Bar\Baz` → an `imports` ref named
  799. /// `Foo\Bar::Baz`; a global-namespace name (no `\` after stripping one
  800. /// leading `\`) emits nothing here.
  801. fn push_php_use_ref(&mut self, fqn: &str, from_row: u32, node: Node) {
  802. let clean = fqn.strip_prefix('\\').unwrap_or(fqn);
  803. let Some(last_sep) = clean.rfind('\\') else { return };
  804. let name = format!("{}::{}", &clean[..last_sep], &clean[last_sep + 1..]);
  805. self.push_ref_at(from_row, &name, edge_kind_index("imports").unwrap(), node);
  806. }
  807. fn extract_import(&mut self, node: Node<'t>) {
  808. let kind = node.kind();
  809. let import_text = self.text(node).trim().to_string();
  810. let imports_kind = edge_kind_index("imports").unwrap();
  811. if matches!(
  812. kind,
  813. "include_expression" | "include_once_expression" | "require_expression"
  814. | "require_once_expression"
  815. ) {
  816. // phpStaticIncludePath: static string literals only; dynamic
  817. // forms (`__DIR__ . '/x'`, interpolation) emit NOTHING.
  818. let mut arg = node.named_child(0);
  819. if let Some(a) = arg {
  820. if a.kind() == "parenthesized_expression" {
  821. arg = a.named_child(0);
  822. }
  823. }
  824. let Some(arg) = arg else { return };
  825. if !matches!(arg.kind(), "string" | "encapsed_string") {
  826. return;
  827. }
  828. let mut content: Option<Node> = None;
  829. for i in 0..arg.named_child_count() {
  830. let Some(c) = arg.named_child(i) else { continue };
  831. if c.kind() != "string_content" {
  832. return; // interpolation/escape → not a static path
  833. }
  834. if content.is_none() {
  835. content = Some(c);
  836. }
  837. }
  838. let Some(content) = content else { return };
  839. let module_name = self.text(content).to_string();
  840. if module_name.is_empty() {
  841. return;
  842. }
  843. self.create_node(
  844. "import",
  845. &module_name,
  846. node,
  847. Extra { signature: Some(import_text), ..Extra::default() },
  848. );
  849. let parent = self.top_row();
  850. self.push_ref_at(parent, &module_name.clone(), imports_kind, node);
  851. return;
  852. }
  853. // namespace_use_declaration.
  854. let ns_prefix = (0..node.named_child_count())
  855. .filter_map(|i| node.named_child(i))
  856. .find(|c| c.kind() == "namespace_name");
  857. let use_group = (0..node.named_child_count())
  858. .filter_map(|i| node.named_child(i))
  859. .find(|c| c.kind() == "namespace_use_group");
  860. if let (Some(ns_prefix), Some(use_group)) = (ns_prefix, use_group) {
  861. // Grouped `use A\{B, C as D, Sub\E}` — hook declines, the inline
  862. // branch emits per-member nodes named `A\B` (first `name` child =
  863. // the SOURCE name; a nested `Sub\E` clause has a qualified_name,
  864. // no direct `name` → SKIPPED, grammar-bump delta #2). All nodes
  865. // and refs sit at the whole declaration's position.
  866. let prefix = self.text(ns_prefix).to_string();
  867. let clauses: Vec<Node> = (0..use_group.named_child_count())
  868. .filter_map(|i| use_group.named_child(i))
  869. .filter(|c| {
  870. matches!(c.kind(), "namespace_use_group_clause" | "namespace_use_clause")
  871. })
  872. .collect();
  873. for clause in clauses {
  874. let ns_name = (0..clause.named_child_count())
  875. .filter_map(|i| clause.named_child(i))
  876. .find(|c| c.kind() == "namespace_name");
  877. let name = match ns_name {
  878. Some(nn) => (0..nn.named_child_count())
  879. .filter_map(|i| nn.named_child(i))
  880. .find(|c| c.kind() == "name"),
  881. None => (0..clause.named_child_count())
  882. .filter_map(|i| clause.named_child(i))
  883. .find(|c| c.kind() == "name"),
  884. };
  885. if let Some(name) = name {
  886. let full = format!("{prefix}\\{}", self.text(name));
  887. self.create_node(
  888. "import",
  889. &full,
  890. node,
  891. Extra { signature: Some(import_text.clone()), ..Extra::default() },
  892. );
  893. let parent = self.top_row();
  894. self.push_php_use_ref(&full, parent, node);
  895. }
  896. }
  897. return;
  898. }
  899. // Single use (incl. `use function`/`use const`/aliased): the hook's
  900. // qualified_name-else-name read; alias never included.
  901. let use_clause = (0..node.named_child_count())
  902. .filter_map(|i| node.named_child(i))
  903. .find(|c| c.kind() == "namespace_use_clause");
  904. let Some(use_clause) = use_clause else { return };
  905. let target = (0..use_clause.named_child_count())
  906. .filter_map(|i| use_clause.named_child(i))
  907. .find(|c| c.kind() == "qualified_name")
  908. .or_else(|| {
  909. (0..use_clause.named_child_count())
  910. .filter_map(|i| use_clause.named_child(i))
  911. .find(|c| c.kind() == "name")
  912. });
  913. let Some(target) = target else { return }; // hook null → nothing
  914. let module_name = self.text(target).to_string();
  915. if module_name.is_empty() {
  916. return;
  917. }
  918. self.create_node(
  919. "import",
  920. &module_name,
  921. node,
  922. Extra { signature: Some(import_text), ..Extra::default() },
  923. );
  924. let parent = self.top_row();
  925. self.push_ref_at(parent, &module_name.clone(), imports_kind, node);
  926. // emitPhpUseRefs → the `Foo\Bar::Baz` ref (bare single-segment `use
  927. // Countable;` has no `\` → no `::` ref).
  928. self.push_php_use_ref(&module_name, parent, node);
  929. }
  930. // --- calls ---------------------------------------------------------------------
  931. fn extract_call(&mut self, node: Node<'t>) {
  932. if self.stack.is_empty() {
  933. return;
  934. }
  935. let caller = self.top_row();
  936. let mut callee_name = String::new();
  937. let name_field = node.child_by_field_name("name");
  938. let object_field = node
  939. .child_by_field_name("object")
  940. .or_else(|| node.child_by_field_name("scope"));
  941. if let (Some(name_field), Some(object_field)) = (name_field, object_field) {
  942. // member_call_expression / scoped_call_expression.
  943. let method_name = self.text(name_field);
  944. // Fluent static-factory `Cls::factory($x)->method()` — encode
  945. // `Cls::factory().method` (inner args dropped) and return; the
  946. // inner scoped call is also visited by recursion (`Cls.factory`).
  947. if !method_name.is_empty() && object_field.kind() == "scoped_call_expression" {
  948. let inner_scope = object_field.child_by_field_name("scope");
  949. let inner_name = object_field.child_by_field_name("name");
  950. let callee = match (inner_scope, inner_name) {
  951. (Some(s), Some(n)) => {
  952. format!("{}::{}().{method_name}", self.text(s), self.text(n))
  953. }
  954. _ => method_name.to_string(),
  955. };
  956. if !callee.is_empty() {
  957. self.push_ref_at(caller, &callee, edge_kind_index("calls").unwrap(), node);
  958. }
  959. return;
  960. }
  961. // receiverName = raw receiver text with ONE leading `$` stripped:
  962. // `$this->prop->m()` → `this->prop.m` (#1251 encoding — the whole
  963. // resolution machinery is TS-side); chains keep args
  964. // (`this->factory($cfg).m`); literals are NOT suppressed
  965. // (`"chain".upper`); scoped calls are DOT-joined (`UserModel.query`).
  966. let receiver_raw = self.text(object_field);
  967. let receiver = receiver_raw.strip_prefix('$').unwrap_or(receiver_raw);
  968. if !method_name.is_empty() {
  969. if matches!(receiver, "self" | "this" | "cls" | "super" | "parent" | "static") {
  970. callee_name = method_name.to_string();
  971. } else {
  972. callee_name = format!("{receiver}.{method_name}");
  973. }
  974. }
  975. } else {
  976. // function_call_expression: raw func text — bare `helper`,
  977. // qualified `\App\Helpers\format_id` verbatim, `$fn` for
  978. // variable callees, FCC `f(...)` → `f`.
  979. let func = node
  980. .child_by_field_name("function")
  981. .or_else(|| node.named_child(0));
  982. if let Some(func) = func {
  983. callee_name = self.text(func).to_string();
  984. }
  985. }
  986. if !callee_name.is_empty() {
  987. if let Some(c) = util::paren_conversion().captures(&callee_name) {
  988. callee_name = c[1].to_string();
  989. }
  990. self.push_ref_at(caller, &callee_name.clone(), edge_kind_index("calls").unwrap(), node);
  991. }
  992. }
  993. fn extract_instantiation(&mut self, node: Node<'t>) {
  994. if self.stack.is_empty() {
  995. return;
  996. }
  997. // php has no constructor/type/name FIELDS → namedChild(0). Backslashes
  998. // are NOT split by the suffix logic → `new \App\Models\User()` keeps
  999. // the full qualified text; `new $cls()` keeps the `$`; an
  1000. // anonymous_class yields its whole source text through the shared
  1001. // normalization (garbage, deterministic — preserve).
  1002. let ctor = node
  1003. .child_by_field_name("constructor")
  1004. .or_else(|| node.child_by_field_name("type"))
  1005. .or_else(|| node.child_by_field_name("name"))
  1006. .or_else(|| node.named_child(0));
  1007. let Some(ctor) = ctor else { return };
  1008. let class_name = strip_generic_and_qualifier(self.text(ctor));
  1009. if !class_name.is_empty() {
  1010. let from = self.top_row();
  1011. self.push_ref_at(from, &class_name, edge_kind_index("instantiates").unwrap(), node);
  1012. }
  1013. }
  1014. /// extractAnonymousClass — unreachable on v0.24.2 (the declaration_list
  1015. /// nests inside `anonymous_class`, so findAnonymousClassBody finds no
  1016. /// DIRECT child) — mirrored from the shared TS path for shape.
  1017. fn extract_anonymous_class(&mut self, node: Node<'t>, body: Node<'t>) {
  1018. stack_guard!();
  1019. let type_node = node
  1020. .child_by_field_name("constructor")
  1021. .or_else(|| node.child_by_field_name("type"))
  1022. .or_else(|| node.child_by_field_name("name"))
  1023. .or_else(|| node.named_child(0));
  1024. let mut type_name =
  1025. type_node.map(|t| self.text(t).to_string()).unwrap_or_else(|| "Object".to_string());
  1026. type_name = strip_generic_and_qualifier(&type_name);
  1027. if type_name.is_empty() {
  1028. type_name = "Object".to_string();
  1029. }
  1030. let anon_name = format!("<{type_name}$anon@{}>", node.start_position().row + 1);
  1031. let Some(row) = self.create_node("class", &anon_name, node, Extra::default()) else {
  1032. return;
  1033. };
  1034. let (line, column) = match type_node {
  1035. Some(t) => (t.start_position().row as u32, self.col_of(t)),
  1036. None => (node.start_position().row as u32, self.col_of(node)),
  1037. };
  1038. self.push_ref(row, &type_name, edge_kind_index("extends").unwrap(), line, column);
  1039. self.stack.push(Scope { row, kind: "class", name: anon_name });
  1040. for i in 0..body.named_child_count() {
  1041. if let Some(c) = body.named_child(i) {
  1042. self.visit_node(c);
  1043. }
  1044. }
  1045. self.stack.pop();
  1046. }
  1047. /// extractStaticMemberRef — php's class_constant_access_expression +
  1048. /// scoped_property_access_expression (member_access_expression is
  1049. /// evaluated but its variable_name receiver never passes).
  1050. fn extract_static_member_ref(&mut self, node: Node<'t>) {
  1051. if !matches!(
  1052. node.kind(),
  1053. "class_constant_access_expression" | "scoped_property_access_expression"
  1054. | "member_access_expression"
  1055. ) {
  1056. return;
  1057. }
  1058. if self.stack.is_empty() {
  1059. return;
  1060. }
  1061. let owner = self.top_row();
  1062. if let Some(parent) = node.parent() {
  1063. if matches!(
  1064. parent.kind(),
  1065. "function_call_expression" | "member_call_expression" | "scoped_call_expression"
  1066. ) {
  1067. let callee = parent
  1068. .child_by_field_name("function")
  1069. .or_else(|| parent.child_by_field_name("method"))
  1070. .or_else(|| parent.named_child(0));
  1071. if let Some(callee) = callee {
  1072. if callee.start_byte() == node.start_byte() {
  1073. return;
  1074. }
  1075. }
  1076. }
  1077. }
  1078. let recv = node
  1079. .child_by_field_name("object")
  1080. .or_else(|| node.child_by_field_name("expression"))
  1081. .or_else(|| node.child_by_field_name("scope"))
  1082. .or_else(|| node.named_child(0));
  1083. let Some(recv) = recv else { return };
  1084. if matches!(
  1085. recv.kind(),
  1086. "identifier" | "type_identifier" | "simple_identifier" | "name" | "scoped_type_identifier"
  1087. ) {
  1088. let text = self.text(recv);
  1089. if capitalized_re().is_match(text) {
  1090. self.push_ref_at(owner, &text.to_string(), edge_kind_index("references").unwrap(), recv);
  1091. }
  1092. }
  1093. }
  1094. /// extractInheritance — base_clause takes ONLY the first base (interface
  1095. /// multi-extends drops the rest); class_interface_clause takes ALL
  1096. /// children unfiltered (full text, incl. leading `\`).
  1097. fn extract_inheritance(&mut self, node: Node<'t>, class_row: u32) {
  1098. let extends_kind = edge_kind_index("extends").unwrap();
  1099. let implements_kind = edge_kind_index("implements").unwrap();
  1100. for i in 0..node.named_child_count() {
  1101. let Some(child) = node.named_child(i) else { continue };
  1102. if child.kind() == "base_clause" {
  1103. if let Some(target) = child.named_child(0) {
  1104. let name = self.text(target).to_string();
  1105. self.push_ref_at(class_row, &name, extends_kind, target);
  1106. }
  1107. } else if child.kind() == "class_interface_clause" {
  1108. for j in 0..child.named_child_count() {
  1109. let Some(iface) = child.named_child(j) else { continue };
  1110. let name = self.text(iface).to_string();
  1111. self.push_ref_at(class_row, &name, implements_kind, iface);
  1112. }
  1113. }
  1114. }
  1115. }
  1116. // --- php type refs (extractPhpTypeRefs, 6022) ----------------------------------
  1117. fn extract_php_type_refs(&mut self, node: Node<'t>, from_row: u32) {
  1118. let params = (0..node.named_child_count())
  1119. .filter_map(|i| node.named_child(i))
  1120. .find(|c| c.kind() == "formal_parameters");
  1121. if let Some(params) = params {
  1122. for i in 0..params.named_child_count() {
  1123. let Some(p) = params.named_child(i) else { continue };
  1124. for j in 0..p.named_child_count() {
  1125. let Some(c) = p.named_child(j) else { continue };
  1126. if is_php_type_node(c.kind()) {
  1127. self.walk_php_type_position(c, from_row);
  1128. }
  1129. }
  1130. }
  1131. }
  1132. for i in 0..node.named_child_count() {
  1133. let Some(c) = node.named_child(i) else { continue };
  1134. if is_php_type_node(c.kind()) {
  1135. self.walk_php_type_position(c, from_row);
  1136. }
  1137. }
  1138. }
  1139. fn walk_php_type_position(&mut self, node: Node<'t>, from_row: u32) {
  1140. stack_guard!();
  1141. match node.kind() {
  1142. "primitive_type" => {}
  1143. "name" => {
  1144. let name = self.text(node);
  1145. if !name.is_empty() && !is_php_pseudo_type(name) {
  1146. self.push_ref_at(from_row, &name.to_string(), edge_kind_index("references").unwrap(), node);
  1147. }
  1148. }
  1149. "qualified_name" => {
  1150. let text = self.text(node);
  1151. let last = text.rsplit('\\').next().unwrap_or("");
  1152. if !last.is_empty() && !is_php_pseudo_type(last) {
  1153. self.push_ref_at(from_row, &last.to_string(), edge_kind_index("references").unwrap(), node);
  1154. }
  1155. }
  1156. _ => {
  1157. for i in 0..node.named_child_count() {
  1158. if let Some(c) = node.named_child(i) {
  1159. self.walk_php_type_position(c, from_row);
  1160. }
  1161. }
  1162. }
  1163. }
  1164. }
  1165. // --- function-as-value refs (PHP_SPEC, function-ref.ts:360) --------------------
  1166. fn maybe_capture_fn_refs(&mut self, node: Node<'t>) {
  1167. if node.kind() != "arguments" {
  1168. return;
  1169. }
  1170. if self.stack.is_empty() {
  1171. return;
  1172. }
  1173. let from = self.top_row();
  1174. for i in 0..node.named_child_count() {
  1175. if let Some(c) = node.named_child(i) {
  1176. self.normalize_fn_ref_value(c, from, 0);
  1177. }
  1178. }
  1179. }
  1180. fn normalize_fn_ref_value(&mut self, v: Node<'t>, from: u32, depth: u32) {
  1181. stack_guard!();
  1182. if depth > 4 {
  1183. return;
  1184. }
  1185. match v.kind() {
  1186. "argument" => {
  1187. for i in 0..v.named_child_count() {
  1188. if let Some(c) = v.named_child(i) {
  1189. self.normalize_fn_ref_value(c, from, depth + 1);
  1190. }
  1191. }
  1192. }
  1193. // String callable — trustworthy ONLY as an argument to a known
  1194. // callable-taking core function; skipGate (resolution's
  1195. // unique-or-drop rule takes over). Namespaced strings drop.
  1196. "string" | "encapsed_string" => {
  1197. let Some(callee) = php_enclosing_call_name(v).map(|f| self.text(f)) else {
  1198. return;
  1199. };
  1200. if !is_php_callable_hof(callee) {
  1201. return;
  1202. }
  1203. let Some(content) = self.php_string_content(v) else { return };
  1204. if simple_callable_re().is_match(&content) || qualified_callable_re().is_match(&content)
  1205. {
  1206. self.push_fn_ref_cand(from, &content, v, true);
  1207. }
  1208. }
  1209. // Array callables in ANY call's arguments: `[$this, 'm']` →
  1210. // this.m; `[Foo::class, 'm']` → Foo::m; `['Cls', 'm']` → nothing.
  1211. "array_creation_expression" => {
  1212. if v.named_child_count() != 2 {
  1213. return;
  1214. }
  1215. let recv = v.named_child(0).and_then(|e| e.named_child(0));
  1216. let str_el = v.named_child(1).and_then(|e| e.named_child(0));
  1217. let (Some(recv), Some(str_el)) = (recv, str_el) else { return };
  1218. if !matches!(str_el.kind(), "encapsed_string" | "string") {
  1219. return;
  1220. }
  1221. let Some(member) = self.php_string_content(str_el) else { return };
  1222. if !simple_callable_re().is_match(&member) {
  1223. return;
  1224. }
  1225. if recv.kind() == "variable_name" && self.text(recv) == "$this" {
  1226. let name = format!("this.{member}");
  1227. self.push_fn_ref_cand(from, &name, str_el, false);
  1228. } else if recv.kind() == "class_constant_access_expression" {
  1229. let cls = recv.named_child(0);
  1230. let kw = recv.named_child(1);
  1231. if let (Some(cls), Some(kw)) = (cls, kw) {
  1232. if self.text(kw) == "class" {
  1233. let name = format!("{}::{member}", self.text(cls));
  1234. self.push_fn_ref_cand(from, &name, str_el, false);
  1235. }
  1236. }
  1237. }
  1238. }
  1239. _ => {}
  1240. }
  1241. }
  1242. /// phpStringContent: the string's first string_content child, trimmed.
  1243. fn php_string_content(&self, node: Node) -> Option<String> {
  1244. for i in 0..node.named_child_count() {
  1245. let Some(c) = node.named_child(i) else { continue };
  1246. if c.kind() == "string_content" {
  1247. return Some(self.text(c).trim().to_string());
  1248. }
  1249. }
  1250. None
  1251. }
  1252. fn push_fn_ref_cand(&mut self, from: u32, name: &str, node: Node, skip_gate: bool) {
  1253. if name.is_empty() || is_stoplisted(name) {
  1254. return;
  1255. }
  1256. let p = node.start_position();
  1257. self.fn_ref_cands.push(Cand {
  1258. from,
  1259. name: name.to_string(),
  1260. line: p.row as u32 + 1,
  1261. column_byte: node.start_byte(),
  1262. row: p.row,
  1263. skip_gate,
  1264. });
  1265. }
  1266. fn scan_fn_ref_subtree(&mut self, node: Node<'t>, depth: u32) {
  1267. stack_guard!();
  1268. if depth > 12 {
  1269. return;
  1270. }
  1271. // Halts at functionTypes (function_definition) + arrow_function (in
  1272. // the fixed list); anonymous_function is NOT halted — scans descend
  1273. // into closures.
  1274. if depth > 0
  1275. && matches!(
  1276. node.kind(),
  1277. "function_definition" | "arrow_function" | "function_expression" | "lambda_literal"
  1278. | "lambda_expression"
  1279. )
  1280. {
  1281. return;
  1282. }
  1283. self.maybe_capture_fn_refs(node);
  1284. for i in 0..node.named_child_count() {
  1285. if let Some(c) = node.named_child(i) {
  1286. self.scan_fn_ref_subtree(c, depth + 1);
  1287. }
  1288. }
  1289. }
  1290. fn flush_fn_ref_candidates(&mut self) {
  1291. let cands = std::mem::take(&mut self.fn_ref_cands);
  1292. if cands.is_empty() || util::is_generated_file(self.file_path) {
  1293. return;
  1294. }
  1295. let mut seen: HashSet<(String, String)> = HashSet::new();
  1296. for c in cands {
  1297. // `this.<m>` and `Cls::m` shapes always flush; HOF-position string
  1298. // callables skip the gate (unique-or-drop at resolution); the rest
  1299. // gate on defined-in-file ∪ bare single-segment `use` imports
  1300. // (path-shaped and `::`-shaped import refs match neither regex).
  1301. if !c.name.starts_with("this.") && !c.name.contains("::") {
  1302. let skip = c.skip_gate;
  1303. if !skip
  1304. && !self.defined_fn_names.contains(&c.name)
  1305. && !self.imported_names.contains(&c.name)
  1306. {
  1307. continue;
  1308. }
  1309. }
  1310. if !seen.insert((self.node_ids[c.from as usize].clone(), c.name.clone())) {
  1311. continue;
  1312. }
  1313. let column = util::col16(self.src, &self.line_starts, c.row, c.column_byte);
  1314. let name_ref = self.arena.put(&c.name);
  1315. self.tables.push_ref(&RefRow {
  1316. from_idx: c.from,
  1317. kind: FUNCTION_REF_CODE,
  1318. line: c.line,
  1319. column,
  1320. reference_name: name_ref,
  1321. candidates: NONE_STR,
  1322. from_id_str: NONE_STR,
  1323. });
  1324. }
  1325. }
  1326. // --- value references ------------------------------------------------------------
  1327. fn flush_value_refs(&mut self) {
  1328. let scopes = std::mem::take(&mut self.value_scopes);
  1329. let targets = std::mem::take(&mut self.fs_values);
  1330. let _counts = std::mem::take(&mut self.fs_value_counts);
  1331. if std::env::var("CODEGRAPH_VALUE_REFS").as_deref() == Ok("0") {
  1332. return;
  1333. }
  1334. if targets.is_empty() || scopes.is_empty() || util::is_generated_file(self.file_path) {
  1335. return;
  1336. }
  1337. // Shadow prune: the per-grammar declarator switch has NO resolving php
  1338. // cases (`assignment` is python's node; property_declaration's
  1339. // Kotlin/Swift path yields null) → declCounts stays empty → no php
  1340. // target is ever pruned. Skipping the scan is byte-identical.
  1341. let refs_kind = edge_kind_index("references").unwrap();
  1342. for scope in &scopes {
  1343. let mut seen: HashSet<&str> = HashSet::new();
  1344. let mut stack: Vec<Node> = vec![scope.node];
  1345. let mut visited = 0usize;
  1346. while let Some(n) = stack.pop() {
  1347. if visited >= MAX_VALUE_REF_NODES {
  1348. break;
  1349. }
  1350. visited += 1;
  1351. // `name` is the php-live reader kind — ANY textual occurrence
  1352. // of a target name in a reader's subtree emits (const reads,
  1353. // `self::MAX`, `$MAX` variable names, interpolated `$MAX`).
  1354. if matches!(n.kind(), "identifier" | "constant" | "name" | "simple_identifier") {
  1355. let ref_name = self.text(n);
  1356. if let Some(&target_row) = targets.get(ref_name) {
  1357. let target_id = self.node_ids[target_row as usize].as_str();
  1358. if target_id != self.node_ids[scope.row as usize]
  1359. && ref_name != scope.name
  1360. && !seen.contains(&target_id)
  1361. {
  1362. seen.insert(target_id);
  1363. let meta = self.arena.put(r#"{"valueRef":true}"#);
  1364. self.tables.push_edge(&EdgeRow {
  1365. source_idx: scope.row,
  1366. target_idx: target_row,
  1367. kind: refs_kind,
  1368. provenance: 0,
  1369. line: NONE,
  1370. column: NONE,
  1371. metadata_json: meta,
  1372. source_id_str: NONE_STR,
  1373. target_id_str: NONE_STR,
  1374. });
  1375. }
  1376. }
  1377. }
  1378. for i in 0..n.named_child_count() {
  1379. if let Some(c) = n.named_child(i) {
  1380. stack.push(c);
  1381. }
  1382. }
  1383. }
  1384. }
  1385. }
  1386. }
  1387. /// The function name node of the php call whose arguments contain `node` —
  1388. /// ≤4 parent hops to a function_call_expression; member/scoped calls abort
  1389. /// (method-call HOFs never qualify). (function-ref.ts:822)
  1390. fn php_enclosing_call_name(node: Node) -> Option<Node> {
  1391. let mut cur = node.parent();
  1392. for _ in 0..4 {
  1393. let c = cur?;
  1394. if c.kind() == "function_call_expression" {
  1395. return c.child_by_field_name("function");
  1396. }
  1397. if matches!(c.kind(), "member_call_expression" | "scoped_call_expression") {
  1398. return None;
  1399. }
  1400. cur = c.parent();
  1401. }
  1402. None
  1403. }
  1404. fn find_anonymous_class_body(node: Node) -> Option<Node> {
  1405. for i in 0..node.named_child_count() {
  1406. if let Some(child) = node.named_child(i) {
  1407. if matches!(child.kind(), "class_body" | "declaration_list") {
  1408. return Some(child);
  1409. }
  1410. }
  1411. }
  1412. None
  1413. }
  1414. /// The shared `new ns.Foo<T>()` normalization: strip `<...` from the first
  1415. /// `<` (index > 0), keep the segment after the last `.`/`::`, strip ONE
  1416. /// leading `:` or `.`, trim. Backslashes are NOT handled — php qualified
  1417. /// names pass through whole.
  1418. fn strip_generic_and_qualifier(raw: &str) -> String {
  1419. let mut name = raw.to_string();
  1420. if let Some(lt) = name.find('<') {
  1421. if lt > 0 {
  1422. name.truncate(lt);
  1423. }
  1424. }
  1425. let last_dot = name
  1426. .rfind('.')
  1427. .map(|i| i as isize)
  1428. .unwrap_or(-1)
  1429. .max(name.rfind("::").map(|i| i as isize).unwrap_or(-1));
  1430. if last_dot >= 0 {
  1431. name = name[(last_dot as usize + 1)..].to_string();
  1432. if name.starts_with(':') || name.starts_with('.') {
  1433. name.remove(0);
  1434. }
  1435. }
  1436. name.trim().to_string()
  1437. }
  1438. fn opt_str(arena: &mut Arena, s: Option<&str>) -> StrRef {
  1439. match s {
  1440. Some(s) => arena.put(s),
  1441. None => NONE_STR,
  1442. }
  1443. }