1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
use php_ast::{ClassMemberKind, EnumMemberKind, NamespaceBody, Stmt, StmtKind};
use tower_lsp::lsp_types::*;
use std::collections::HashMap;
use crate::ast::{ParsedDoc, str_offset};
use crate::util::word_at_position;
/// Return a moniker for the symbol at `position`.
///
/// Scheme: `"php"`.
/// Identifier: the fully-qualified name in PHP convention. For class-like
/// declarations or references that resolve via `use` / namespace this is
/// `Ns\\ClassName`. For methods, properties, class constants, or enum cases
/// it is `Ns\\ClassName::member` (`::$prop` for properties), determined by
/// inspecting the AST node under the cursor. For unqualified words that
/// don't resolve to a local declaration or import, the bare word is
/// returned — the namespace prefix is *not* applied as a guess (PHP's
/// resolver falls back to global for unqualified function calls; for
/// classes the FQCN can't be inferred without explicit qualification).
/// Uniqueness: `project`.
pub fn moniker_at(
source: &str,
doc: &ParsedDoc,
position: Position,
file_imports: &HashMap<String, String>,
) -> Option<Moniker> {
let word = word_at_position(source, position)?;
if word.is_empty() {
return None;
}
// Use the AST's own source for member detection. AST name slices
// point into `doc.source()`, so `str_offset`'s pointer arithmetic
// resolves to per-occurrence offsets only when the same allocation
// is used; mixing in the caller-provided `source` falls back to
// `source.find(name)`, which returns the first textual occurrence
// and silently misattributes cursors when names collide (comments
// mentioning the symbol, or the same method name in two classes).
let ast_source = doc.source();
// Member-name declaration sites are checked first so that property
// declarations (whose `word` starts with `$`) still produce a moniker.
let identifier = if let Some(id) = enclosing_member_identifier(ast_source, doc, position, &word)
{
id
} else if word.starts_with('$') {
// Plain variable — no project-stable identifier.
return None;
} else {
resolve_fqn_for_moniker(doc, &word, file_imports)
};
Some(Moniker {
scheme: "php".to_string(),
identifier,
unique: UniquenessLevel::Project,
kind: Some(MonikerKind::Export),
})
}
/// If the cursor sits on the *name* of a method, property, class constant, or
/// enum case declaration inside a class/interface/trait/enum, return
/// `Class::name` (or `Ns\\Class::name`, `Ns\\Class::$prop`, `Ns\\Enum::Case`).
/// Returns `None` for cursor positions outside a class-like declaration's
/// member-name span.
fn enclosing_member_identifier(
source: &str,
doc: &ParsedDoc,
position: Position,
word: &str,
) -> Option<String> {
let cursor_byte = doc.view().byte_of_position(position);
// Property declarations carry the AST name without the `$`; strip it
// from the cursor word before comparing.
let bare = word.trim_start_matches('\\').trim_start_matches('$');
walk_for_member(&doc.program().stmts, source, cursor_byte, bare, "")
}
fn walk_for_member(
stmts: &[Stmt<'_, '_>],
source: &str,
cursor_byte: u32,
word: &str,
ns_prefix: &str,
) -> Option<String> {
let mut current_ns: String = ns_prefix.to_owned();
for stmt in stmts {
match &stmt.kind {
StmtKind::Namespace(ns) => {
let ns_name = ns
.name
.as_ref()
.map(|n| n.to_string_repr().to_string())
.unwrap_or_default();
match &ns.body {
NamespaceBody::Braced(inner) => {
let prefix = if ns_name.is_empty() {
String::new()
} else {
format!("{ns_name}\\")
};
if let Some(id) = walk_for_member(inner, source, cursor_byte, word, &prefix)
{
return Some(id);
}
}
NamespaceBody::Simple => {
current_ns = if ns_name.is_empty() {
String::new()
} else {
format!("{ns_name}\\")
};
}
}
}
StmtKind::Class(c) => {
if !span_contains(stmt.span.start, stmt.span.end, cursor_byte) {
continue;
}
let Some(class_name) = c.name else { continue };
let class_name_str = class_name.to_string();
for member in c.members.iter() {
if let Some(id) = match_class_member(
&member.kind,
source,
cursor_byte,
word,
¤t_ns,
&class_name_str,
member.span,
) {
return Some(id);
}
}
}
StmtKind::Interface(i) => {
if !span_contains(stmt.span.start, stmt.span.end, cursor_byte) {
continue;
}
let interface_name = i.name.to_string();
for member in i.members.iter() {
if let Some(id) = match_class_member(
&member.kind,
source,
cursor_byte,
word,
¤t_ns,
&interface_name,
member.span,
) {
return Some(id);
}
}
}
StmtKind::Trait(t) => {
if !span_contains(stmt.span.start, stmt.span.end, cursor_byte) {
continue;
}
let trait_name = t.name.to_string();
for member in t.members.iter() {
if let Some(id) = match_class_member(
&member.kind,
source,
cursor_byte,
word,
¤t_ns,
&trait_name,
member.span,
) {
return Some(id);
}
}
}
StmtKind::Enum(e) => {
if !span_contains(stmt.span.start, stmt.span.end, cursor_byte) {
continue;
}
for member in e.members.iter() {
let id = match &member.kind {
EnumMemberKind::Method(m) if m.name == word => cursor_on_name_in_span(
source,
cursor_byte,
&m.name.to_string(),
member.span,
)
.then(|| format!("{current_ns}{}::{}", e.name, &m.name.to_string())),
EnumMemberKind::Case(c) if c.name == word => cursor_on_name_in_span(
source,
cursor_byte,
&c.name.to_string(),
member.span,
)
.then(|| format!("{current_ns}{}::{}", e.name, &c.name.to_string())),
EnumMemberKind::ClassConst(cc) if cc.name == word => {
cursor_on_name_in_span(
source,
cursor_byte,
&cc.name.to_string(),
member.span,
)
.then(|| format!("{current_ns}{}::{}", e.name, &cc.name.to_string()))
}
_ => None,
};
if id.is_some() {
return id;
}
}
}
_ => {}
}
}
None
}
fn match_class_member(
kind: &ClassMemberKind<'_, '_>,
source: &str,
cursor_byte: u32,
word: &str,
ns_prefix: &str,
class_name: &str,
member_span: php_ast::Span,
) -> Option<String> {
match kind {
ClassMemberKind::Method(m) if m.name == word => {
cursor_on_name_in_span(source, cursor_byte, &m.name.to_string(), member_span)
.then(|| format!("{ns_prefix}{class_name}::{}", &m.name.to_string()))
}
ClassMemberKind::Property(p) if p.name == word => {
cursor_on_name_in_span(source, cursor_byte, &p.name.to_string(), member_span)
.then(|| format!("{ns_prefix}{class_name}::${}", p.name))
}
ClassMemberKind::ClassConst(c) if c.name == word => {
cursor_on_name_in_span(source, cursor_byte, &c.name.to_string(), member_span)
.then(|| format!("{ns_prefix}{class_name}::{}", &c.name.to_string()))
}
_ => None,
}
}
/// Variant of [`cursor_on_name`] that searches for the name within
/// `member_span` rather than the whole file. Avoids the global-`str_offset`
/// bug where two classes with same-named members both map to the first one.
#[inline]
fn cursor_on_name_in_span(
source: &str,
cursor_byte: u32,
name: &str,
member_span: php_ast::Span,
) -> bool {
let s = member_span.start as usize;
let e = (member_span.end as usize).min(source.len());
let Some(slice) = source.get(s..e) else {
return false;
};
let Some(off) = slice.find(name) else {
return false;
};
let start = member_span.start + off as u32;
let end = start + name.len() as u32;
// Inclusive on the right boundary so that a cursor positioned right
// after the name (e.g. between `bar` and `(`) — a common "just typed
// the name" position — still resolves.
cursor_byte >= start && cursor_byte <= end
}
#[inline]
#[allow(dead_code)]
fn cursor_on_name(source: &str, cursor_byte: u32, name: &str) -> bool {
let start = str_offset(source, name).unwrap_or(0);
let end = start + name.len() as u32;
// Inclusive on the right boundary so that a cursor positioned right
// after the name (e.g. between `bar` and `(`) — a common "just typed
// the name" position — still counts as on the name.
cursor_byte >= start && cursor_byte <= end
}
#[inline]
fn span_contains(start: u32, end: u32, off: u32) -> bool {
off >= start && off < end
}
/// Moniker-flavored FQN resolution. Like `resolve_fqn` but does NOT attach
/// the file's namespace prefix to unresolved unqualified words: PHP's
/// resolver falls back to global for unqualified function calls, and for
/// classes the FQCN cannot be inferred without explicit qualification or a
/// `use` import. Returning the bare word is therefore safer than guessing.
fn resolve_fqn_for_moniker(
doc: &ParsedDoc,
name: &str,
file_imports: &HashMap<String, String>,
) -> String {
let bare = name.trim_start_matches('\\');
fn matches_top(kind: &StmtKind<'_, '_>, name: &str) -> bool {
match kind {
StmtKind::Class(c) => c.name.as_ref().map(|n| n.to_string()) == Some(name.to_string()),
StmtKind::Interface(i) => i.name == name,
StmtKind::Trait(t) => t.name == name,
StmtKind::Enum(e) => e.name == name,
StmtKind::Function(f) => f.name == name,
_ => false,
}
}
let mut current_ns: Option<String> = None;
for stmt in doc.program().stmts.iter() {
match &stmt.kind {
StmtKind::Namespace(ns) => {
let ns_name = ns.name.as_ref().map(|n| n.to_string_repr().to_string());
match &ns.body {
NamespaceBody::Braced(inner) => {
let ns_prefix = ns_name
.as_ref()
.map(|n| format!("{n}\\"))
.unwrap_or_default();
for s in inner.iter() {
if matches_top(&s.kind, bare) {
return format!("{ns_prefix}{bare}");
}
}
}
NamespaceBody::Simple => {
current_ns = ns_name;
}
}
}
k if matches_top(k, bare) => {
return match ¤t_ns {
Some(ns) => format!("{ns}\\{bare}"),
None => bare.to_string(),
};
}
_ => {}
}
}
if let Some(fqn) = file_imports.get(bare) {
return fqn.clone();
}
bare.to_string()
}
/// Walk the top-level statements of `doc` looking for a declaration of `name`
/// and return its fully-qualified name including the namespace prefix.
/// When the name is not declared in this file, checks `use` statements so that
/// imported names resolve to their FQN (e.g. `Mailer` → `App\\Services\\Mailer`).
/// Falls back to returning `name` as-is.
pub(crate) fn resolve_fqn(
doc: &ParsedDoc,
name: &str,
file_imports: &HashMap<String, String>,
) -> String {
// Strip a leading `\` from a fully-qualified reference.
let bare = name.trim_start_matches('\\');
// Track the current namespace prefix across top-level statements so that
// the declaration-form `namespace App;` (NamespaceBody::Simple) applies
// to every subsequent class/function until the next namespace statement.
let mut current_ns: Option<String> = None;
// Namespace from the braced form — used as fallback when the name is not a
// local declaration but the whole file lives inside `namespace Foo { }`.
let mut braced_ns: Option<String> = None;
fn matches_top(kind: &StmtKind<'_, '_>, name: &str) -> bool {
match kind {
StmtKind::Class(c) => c.name.as_ref().map(|n| n.to_string()) == Some(name.to_string()),
StmtKind::Interface(i) => i.name == name,
StmtKind::Trait(t) => t.name == name,
StmtKind::Enum(e) => e.name == name,
StmtKind::Function(f) => f.name == name,
_ => false,
}
}
for stmt in doc.program().stmts.iter() {
match &stmt.kind {
StmtKind::Namespace(ns) => {
let ns_name = ns.name.as_ref().map(|n| n.to_string_repr().to_string());
match &ns.body {
NamespaceBody::Braced(inner) => {
let ns_prefix = ns_name
.as_ref()
.map(|n| format!("{n}\\"))
.unwrap_or_default();
for s in inner.iter() {
if matches_top(&s.kind, bare) {
return format!("{ns_prefix}{bare}");
}
}
// No local declaration matched — record the braced namespace so
// unqualified names that resolve via imports or fallback still
// get the correct namespace prefix applied.
braced_ns = ns_name;
}
NamespaceBody::Simple => {
// Set the "active namespace" for all following top-level stmts.
current_ns = ns_name;
}
}
}
k if matches_top(k, bare) => {
return match ¤t_ns {
Some(ns) => format!("{ns}\\{bare}"),
None => bare.to_string(),
};
}
_ => {}
}
}
// Not a local declaration — resolve via `use` statements.
if let Some(fqn) = file_imports.get(bare) {
return fqn.clone();
}
// No local declaration and no `use` import. When the file declares a
// namespace (Simple or Braced form), unqualified references still resolve
// to that namespace (PHP falls back to global only for *functions*; for
// classes the namespace-prefixed FQCN is authoritative).
let effective_ns = current_ns.or(braced_ns);
if let Some(ns) = effective_ns {
return format!("{ns}\\{bare}");
}
bare.to_string()
}
#[cfg(test)]
mod tests {
use super::*;
fn doc(src: &str) -> ParsedDoc {
ParsedDoc::parse(src.to_string())
}
fn pos(line: u32, character: u32) -> Position {
Position { line, character }
}
fn empty() -> HashMap<String, String> {
HashMap::new()
}
#[test]
fn bare_class_name() {
let src = "<?php\nclass Foo {}";
let d = doc(src);
let m = moniker_at(src, &d, pos(1, 7), &empty()).unwrap();
assert_eq!(m.scheme, "php");
assert_eq!(m.identifier, "Foo");
assert_eq!(m.unique, UniquenessLevel::Project);
assert_eq!(m.kind, Some(MonikerKind::Export));
}
#[test]
fn namespaced_class() {
let src = "<?php\nnamespace App\\Services {\n class FooService {}\n}";
let d = doc(src);
let m = moniker_at(src, &d, pos(2, 10), &empty()).unwrap();
assert_eq!(m.identifier, "App\\Services\\FooService");
}
#[test]
fn unknown_word_returns_bare_name() {
let src = "<?php\n$x = doSomething();";
let d = doc(src);
let m = moniker_at(src, &d, pos(1, 6), &empty()).unwrap();
assert_eq!(m.identifier, "doSomething");
}
#[test]
fn empty_position_returns_none() {
let src = "<?php\n ";
let d = doc(src);
assert!(moniker_at(src, &d, pos(1, 1), &empty()).is_none());
}
#[test]
fn variable_returns_none() {
let src = "<?php\n$foo = 1;";
let d = doc(src);
assert!(moniker_at(src, &d, pos(1, 1), &empty()).is_none());
}
#[test]
fn imported_name_resolves_via_use_statement() {
let src = "<?php\nuse App\\Services\\Mailer;\n$m = new Mailer();";
let d = doc(src);
let imports = HashMap::from([("Mailer".to_string(), "App\\Services\\Mailer".to_string())]);
// Cursor on `Mailer` in `new Mailer()`
let m = moniker_at(src, &d, pos(2, 10), &imports).unwrap();
assert_eq!(m.identifier, "App\\Services\\Mailer");
}
#[test]
fn use_alias_resolves_to_fqn() {
let src = "<?php\nuse App\\Http\\Request as Req;\n$r = new Req();";
let d = doc(src);
let imports = HashMap::from([("Req".to_string(), "App\\Http\\Request".to_string())]);
let m = moniker_at(src, &d, pos(2, 10), &imports).unwrap();
assert_eq!(m.identifier, "App\\Http\\Request");
}
#[test]
fn uniqueness_is_workspace() {
let src = "<?php\nclass Foo {}";
let d = doc(src);
let m = moniker_at(src, &d, pos(1, 7), &empty()).unwrap();
assert_eq!(m.unique, UniquenessLevel::Project);
}
}