php-lsp 0.22.0

A PHP Language Server Protocol implementation
Documentation
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
use php_ast::{ExprKind, NamespaceBody, Stmt, StmtKind};
use tower_lsp_server::ls_types::{CompletionItem, CompletionItemKind, Position};

/// An `#[\Attribute]`-annotated class with its resolved target bitmask.
///
/// Target bitmask uses PHP's `Attribute::TARGET_*` constants:
/// - `TARGET_CLASS = 1`
/// - `TARGET_FUNCTION = 2`
/// - `TARGET_METHOD = 4`
/// - `TARGET_PROPERTY = 8`
/// - `TARGET_CLASS_CONSTANT = 16`
/// - `TARGET_PARAMETER = 32`
/// - `TARGET_ALL = 63` (default when no argument is given)
pub(super) struct AttributeClassEntry {
    pub label: String,
    pub fqn: String,
    pub target: i64,
}

/// Collect only classes annotated with `#[\Attribute]` (or `#[Attribute]`),
/// resolving the first constructor argument as the target bitmask.
pub(super) fn collect_attribute_classes(
    stmts: &[Stmt<'_, '_>],
    ns_prefix: &str,
    out: &mut Vec<AttributeClassEntry>,
) {
    let mut cur_ns = ns_prefix.to_string();

    let fqn_for = |short: &str, ns: &str| -> String {
        if ns.is_empty() {
            short.to_string()
        } else {
            format!("{}\\{}", ns, short)
        }
    };

    for stmt in stmts {
        match &stmt.kind {
            StmtKind::Class(c) => {
                let short = c.name.as_ref().map(|n| n.to_string()).unwrap_or_default();
                if short.is_empty() {
                    continue;
                }
                let target = attribute_target_from_attrs(&c.attributes);
                if let Some(target) = target {
                    out.push(AttributeClassEntry {
                        label: short.to_string(),
                        fqn: fqn_for(&short.to_string(), &cur_ns),
                        target,
                    });
                }
            }
            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) => {
                        collect_attribute_classes(&inner.stmts, &ns_name, out);
                    }
                    NamespaceBody::Simple => {
                        cur_ns = ns_name;
                    }
                }
            }
            _ => {}
        }
    }
}

/// Returns `Some(target_bitmask)` if the attribute list contains an
/// `#[Attribute]` or `#[\Attribute]` annotation, `None` otherwise.
///
/// The target is parsed from the first argument:
/// - `#[\Attribute]` → `Some(63)` (TARGET_ALL)
/// - `#[\Attribute(63)]` → `Some(63)`
/// - `#[\Attribute(\Attribute::TARGET_CLASS)]` → `Some(1)`
fn attribute_target_from_attrs(
    attrs: &php_ast::ArenaVec<'_, php_ast::Attribute<'_, '_>>,
) -> Option<i64> {
    for attr in attrs.iter() {
        let name = attr.name.to_string_repr();
        if name.rsplit('\\').next() != Some("Attribute") {
            continue;
        }
        // Found the `#[Attribute]` annotation; parse its target argument.
        let target = attr
            .args
            .first()
            .and_then(|arg| resolve_target_expr(&arg.value.kind))
            .unwrap_or(63); // TARGET_ALL when no argument given
        return Some(target);
    }
    None
}

fn resolve_target_expr(expr: &ExprKind<'_, '_>) -> Option<i64> {
    match expr {
        ExprKind::Int(v) => Some(*v),
        ExprKind::ClassConstAccess(acc) => {
            // `\Attribute::TARGET_CLASS` → member is an Identifier "TARGET_CLASS"
            acc.member.name_str().and_then(target_const_to_bitmask)
        }
        _ => None,
    }
}

fn target_const_to_bitmask(name: &str) -> Option<i64> {
    match name {
        "TARGET_CLASS" => Some(1),
        "TARGET_FUNCTION" => Some(2),
        "TARGET_METHOD" => Some(4),
        "TARGET_PROPERTY" => Some(8),
        "TARGET_CLASS_CONSTANT" => Some(16),
        "TARGET_PARAMETER" => Some(32),
        "TARGET_ALL" => Some(63),
        _ => None,
    }
}

/// Infer the attribute target context by looking ahead from `position` in
/// `source` for the first declaration keyword (class / function / etc.).
///
/// Returns the appropriate `Attribute::TARGET_*` bitmask, or `63` (ALL) if
/// no specific context can be determined.
pub(super) fn infer_attribute_target(source: &str, position: Position) -> i64 {
    let lines: Vec<&str> = source.lines().collect();
    let start = (position.line as usize).saturating_add(1);
    for line in lines.iter().skip(start).take(10) {
        let t = line.trim();
        if t.is_empty()
            || t.starts_with("//")
            || t.starts_with("/*")
            || t.starts_with("*")
            || t.starts_with("#[")
        {
            continue;
        }
        // Strip common visibility/modifier keywords before checking
        let stripped = t
            .trim_start_matches("abstract ")
            .trim_start_matches("final ")
            .trim_start_matches("readonly ")
            .trim_start_matches("public ")
            .trim_start_matches("protected ")
            .trim_start_matches("private ")
            .trim_start_matches("static ");
        if stripped.starts_with("class ")
            || stripped.starts_with("interface ")
            || stripped.starts_with("enum ")
            || stripped.starts_with("trait ")
        {
            return 1; // TARGET_CLASS
        }
        if stripped.starts_with("function ") {
            return 2 | 4; // TARGET_FUNCTION | TARGET_METHOD
        }
        // Property: starts with a type hint or $ before any `=`
        if stripped.starts_with('$') || is_property_declaration(stripped) {
            return 8; // TARGET_PROPERTY
        }
        if stripped.starts_with("const ") {
            return 16; // TARGET_CLASS_CONSTANT
        }
        break;
    }
    63 // TARGET_ALL — context unknown
}

fn is_property_declaration(s: &str) -> bool {
    // Heuristic: PHP type followed by `$varname`
    // e.g. `string $name`, `int $count`, `?Foo $bar`
    let s = s.trim_start_matches('?');
    if let Some(rest) = s.split_once(' ') {
        rest.1.trim().starts_with('$')
    } else {
        false
    }
}

pub(super) fn collect_classes_with_ns(
    stmts: &[Stmt<'_, '_>],
    ns_prefix: &str,
    items: &mut Vec<(String, CompletionItemKind, String)>,
) {
    // `cur_ns` tracks the namespace context for unbraced `namespace Foo;` declarations,
    // which apply to all subsequent statements at the same level.
    let mut cur_ns = ns_prefix.to_string();

    let fqn_for = |short: &str, ns: &str| -> String {
        if ns.is_empty() {
            short.to_string()
        } else {
            format!("{}\\{}", ns, short)
        }
    };

    for stmt in stmts {
        match &stmt.kind {
            StmtKind::Class(c) => {
                let short = c.name.as_ref().map(|n| n.to_string()).unwrap_or_default();
                if !short.is_empty() {
                    items.push((
                        short.to_string(),
                        CompletionItemKind::CLASS,
                        fqn_for(&short.to_string(), &cur_ns),
                    ));
                }
            }
            StmtKind::Interface(i) => {
                items.push((
                    i.name.to_string(),
                    CompletionItemKind::INTERFACE,
                    fqn_for(&i.name.to_string(), &cur_ns),
                ));
            }
            StmtKind::Trait(t) => {
                items.push((
                    t.name.to_string(),
                    CompletionItemKind::CLASS,
                    fqn_for(&t.name.to_string(), &cur_ns),
                ));
            }
            StmtKind::Enum(e) => {
                items.push((
                    e.name.to_string(),
                    CompletionItemKind::ENUM,
                    fqn_for(&e.name.to_string(), &cur_ns),
                ));
            }
            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) => {
                        collect_classes_with_ns(&inner.stmts, &ns_name, items);
                    }
                    NamespaceBody::Simple => {
                        // Unbraced namespace: applies to all subsequent statements.
                        cur_ns = ns_name;
                    }
                }
            }
            _ => {}
        }
    }
}

/// The line+col where a new `use` statement should be inserted in the current file.
pub(super) fn use_insert_position(source: &str) -> Position {
    let mut last_use_line: Option<u32> = None;
    let mut anchor_line: u32 = 0;
    for (i, line) in source.lines().enumerate() {
        let trimmed = line.trim();
        if trimmed.starts_with("<?") || trimmed.starts_with("namespace ") {
            anchor_line = i as u32;
        }
        if trimmed.starts_with("use ") && !trimmed.starts_with("use function ") {
            last_use_line = Some(i as u32);
        }
    }
    Position {
        line: last_use_line.unwrap_or(anchor_line) + 1,
        character: 0,
    }
}

/// The namespace declared at the top of the given statements, if any.
pub(super) fn current_file_namespace(stmts: &[Stmt<'_, '_>]) -> String {
    for stmt in stmts {
        if let StmtKind::Namespace(ns) = &stmt.kind {
            return ns
                .name
                .as_ref()
                .map(|n| n.to_string_repr().to_string())
                .unwrap_or_default();
        }
    }
    String::new()
}

/// Which symbol table a `use` completion should search — determined by
/// whether the statement is `use`, `use function`, or `use const`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum UseCompletionKind {
    ClassLike,
    Function,
    Const,
}

/// Collect fully-qualified names from stmts that contain `prefix`, scoped to
/// `kind` — `use function`/`use const` must only ever suggest functions/consts,
/// never classes (and vice versa), since PHP resolves each `use` variant
/// against a completely separate namespace.
pub(super) fn collect_fqns_with_prefix(
    stmts: &[Stmt<'_, '_>],
    ns: &str,
    prefix: &str,
    kind: UseCompletionKind,
    out: &mut Vec<CompletionItem>,
) {
    // Tracks the namespace context for unbraced `namespace Foo;` declarations,
    // which apply to all subsequent statements at the same level — mirrors
    // `collect_classes_with_ns`'s `cur_ns`.
    let mut cur_ns = ns.to_string();
    let prefix_lc = prefix.to_lowercase();
    for stmt in stmts {
        match &stmt.kind {
            StmtKind::Class(c) if kind == UseCompletionKind::ClassLike => {
                if let Some(name) = c.name {
                    let fqn = if cur_ns.is_empty() {
                        name.to_string()
                    } else {
                        format!("{cur_ns}\\{name}")
                    };
                    if prefix.is_empty() || fqn.to_lowercase().contains(&prefix_lc) {
                        out.push(CompletionItem {
                            label: fqn.clone(),
                            kind: Some(CompletionItemKind::CLASS),
                            insert_text: Some(fqn),
                            ..Default::default()
                        });
                    }
                }
            }
            StmtKind::Interface(i) if kind == UseCompletionKind::ClassLike => {
                let fqn = if cur_ns.is_empty() {
                    i.name.to_string()
                } else {
                    format!("{cur_ns}\\{}", i.name)
                };
                if prefix.is_empty() || fqn.to_lowercase().contains(&prefix_lc) {
                    out.push(CompletionItem {
                        label: fqn.clone(),
                        kind: Some(CompletionItemKind::INTERFACE),
                        insert_text: Some(fqn),
                        ..Default::default()
                    });
                }
            }
            StmtKind::Function(f) if kind == UseCompletionKind::Function => {
                let fqn = if cur_ns.is_empty() {
                    f.name.to_string()
                } else {
                    format!("{cur_ns}\\{}", f.name)
                };
                if prefix.is_empty() || fqn.to_lowercase().contains(&prefix_lc) {
                    out.push(CompletionItem {
                        label: fqn.clone(),
                        kind: Some(CompletionItemKind::FUNCTION),
                        insert_text: Some(fqn),
                        ..Default::default()
                    });
                }
            }
            StmtKind::Const(items) if kind == UseCompletionKind::Const => {
                for item in items.iter() {
                    let fqn = if cur_ns.is_empty() {
                        item.name.to_string()
                    } else {
                        format!("{cur_ns}\\{}", item.name)
                    };
                    if prefix.is_empty() || fqn.to_lowercase().contains(&prefix_lc) {
                        out.push(CompletionItem {
                            label: fqn.clone(),
                            kind: Some(CompletionItemKind::CONSTANT),
                            insert_text: Some(fqn),
                            ..Default::default()
                        });
                    }
                }
            }
            StmtKind::Namespace(ns_stmt) => {
                let ns_name = ns_stmt
                    .name
                    .as_ref()
                    .map(|n| {
                        if cur_ns.is_empty() {
                            n.to_string_repr().to_string()
                        } else {
                            format!("{cur_ns}\\{}", n.to_string_repr())
                        }
                    })
                    .unwrap_or_else(|| cur_ns.clone());
                match &ns_stmt.body {
                    NamespaceBody::Braced(inner) => {
                        collect_fqns_with_prefix(&inner.stmts, &ns_name, prefix, kind, out);
                    }
                    NamespaceBody::Simple => {
                        cur_ns = ns_name;
                    }
                }
            }
            _ => {}
        }
    }
}

/// Returns the `(kind, prefix)` typed after `use `/`use function `/`use const `
/// on the current line, or `None` if not in a use statement.
pub(super) fn use_completion_prefix(
    source: &str,
    position: Position,
) -> Option<(UseCompletionKind, String)> {
    let line = source.lines().nth(position.line as usize)?;
    let col = crate::text::utf16_offset_to_byte(line, position.character as usize);
    let before = line[..col].trim_start();
    let rest = before.strip_prefix("use ")?;
    let (kind, rest) = if let Some(r) = rest.strip_prefix("function ") {
        (UseCompletionKind::Function, r)
    } else if let Some(r) = rest.strip_prefix("const ") {
        (UseCompletionKind::Const, r)
    } else {
        (UseCompletionKind::ClassLike, rest)
    };
    Some((kind, rest.trim_start_matches('\\').to_string()))
}

/// Extract the identifier characters typed immediately before the cursor.
/// Includes `\` to support namespace-qualified prefixes like `App\Serv`.
pub(super) fn typed_prefix(source: Option<&str>, position: Option<Position>) -> Option<String> {
    let src = source?;
    let pos = position?;
    let line = src.lines().nth(pos.line as usize)?;
    let col = crate::text::utf16_offset_to_byte(line, pos.character as usize);
    let before = &line[..col];
    let prefix: String = before
        .chars()
        .rev()
        .take_while(|&c| c.is_alphanumeric() || c == '_' || c == '\\' || c == '$')
        .collect::<String>()
        .chars()
        .rev()
        .collect();
    if prefix.is_empty() {
        None
    } else {
        Some(prefix)
    }
}