phpantom_lsp 0.7.0

Fast PHP language server with deep type intelligence. Generics, Laravel, PHPStan annotations. Ready in an instant.
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
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
//! Named argument completion for PHP 8.0+ syntax.
//!
//! When the cursor is inside the parentheses of a function or method call,
//! this module detects the call context and offers parameter names as
//! completion items with a trailing `:` so the user can quickly write
//! named arguments like `foo(paramName: $value)`.
//!
//! ## Supported call forms
//!
//! - Standalone functions: `foo(|)`
//! - Instance methods: `$this->method(|)`, `$var->method(|)`
//! - Static methods: `ClassName::method(|)`, `self::method(|)`
//! - Constructors: `new ClassName(|)`
//!
//! ## Smart features
//!
//! - Already-used named arguments are excluded from suggestions
//! - Positional arguments are counted to skip leading parameters
//! - The user's partial prefix is used for filtering

use tower_lsp::lsp_types::*;

// ─── Context ────────────────────────────────────────────────────────────────

/// Information about a named-argument completion context.
#[derive(Debug, Clone)]
pub struct NamedArgContext {
    /// The call expression in a format suitable for resolution:
    /// - `"functionName"` for standalone functions
    /// - `"$this->method"` or `"$var->method"` for instance methods
    /// - `"ClassName::method"` or `"self::method"` for static methods
    /// - `"new ClassName"` for constructor calls
    pub call_expression: String,
    /// Parameter names already specified as named arguments in this call.
    pub existing_named_args: Vec<String>,
    /// Number of positional (non-named) arguments before the cursor.
    pub positional_count: usize,
    /// The partial identifier prefix the user has typed (e.g. `"na"` from `foo(na|)`).
    pub prefix: String,
}

// ─── Detection ──────────────────────────────────────────────────────────────

/// Detect whether the cursor is inside a function/method call and extract
/// the context needed for named-argument completion.
///
/// Returns `None` if the cursor is not at an eligible position (e.g. after
/// `$`, `->`, `::`, or inside a string/comment).
pub fn detect_named_arg_context(content: &str, position: Position) -> Option<NamedArgContext> {
    let chars: Vec<char> = content.chars().collect();
    let cursor = position_to_char_offset(&chars, position)?;

    // ── Check eligibility at cursor ─────────────────────────────────
    // Walk backward from cursor through identifier chars to find the
    // start of the current "word".
    let mut word_start = cursor;
    while word_start > 0
        && (chars[word_start - 1].is_alphanumeric() || chars[word_start - 1] == '_')
    {
        word_start -= 1;
    }

    // If preceded by `$`, this is a variable — not a named arg.
    if word_start > 0 && chars[word_start - 1] == '$' {
        return None;
    }

    // If preceded by `->` or `::`, member completion handles this.
    if word_start >= 2 && chars[word_start - 2] == '-' && chars[word_start - 1] == '>' {
        return None;
    }
    if word_start >= 2 && chars[word_start - 2] == ':' && chars[word_start - 1] == ':' {
        return None;
    }

    let prefix: String = chars[word_start..cursor].iter().collect();

    // ── Find enclosing open paren ───────────────────────────────────
    let open_paren = find_enclosing_open_paren(&chars, word_start)?;

    // ── Extract call expression before `(` ──────────────────────────
    let call_expr = extract_call_expression(&chars, open_paren)?;
    if call_expr.is_empty() {
        return None;
    }

    // ── Parse arguments between `(` and cursor ──────────────────────
    let args_text: String = chars[open_paren + 1..word_start].iter().collect();
    let (existing_named, positional_count) = parse_existing_args(&args_text);

    Some(NamedArgContext {
        call_expression: call_expr,
        existing_named_args: existing_named,
        positional_count,
        prefix,
    })
}

// Re-exported from `crate::util` for backward compatibility with
// existing import paths.
pub use crate::util::position_to_char_offset;

/// Walk backward from `start` (exclusive) to find the unmatched `(` that
/// encloses the cursor.
///
/// Skips balanced `(…)` pairs and string literals.  Returns `None` if no
/// enclosing `(` is found (cursor is not inside call parens).
pub fn find_enclosing_open_paren(chars: &[char], start: usize) -> Option<usize> {
    let mut i = start;
    let mut depth: i32 = 0;

    while i > 0 {
        i -= 1;
        match chars[i] {
            ')' => depth += 1,
            '(' => {
                if depth > 0 {
                    depth -= 1;
                } else {
                    // Found unmatched `(` — this is the call's open paren.
                    return Some(i);
                }
            }
            // Skip single-quoted strings backwards
            '\'' => {
                i = skip_string_backward(chars, i, '\'');
            }
            // Skip double-quoted strings backwards
            '"' => {
                i = skip_string_backward(chars, i, '"');
            }
            // If we hit `{` or `[` without a matching `}` or `]`, we've
            // left the expression context — stop searching.
            '{' | '[' => return None,
            // If we hit `;` we've gone past a statement boundary.
            ';' => return None,
            _ => {}
        }
    }

    None
}

/// Skip backward past a string literal ending at position `end` (which
/// points to the closing quote character `q`).
///
/// Returns the position of the opening quote, or 0 if not found.
pub fn skip_string_backward(chars: &[char], end: usize, q: char) -> usize {
    if end == 0 {
        return 0;
    }
    let mut j = end - 1;
    while j > 0 {
        if chars[j] == q {
            // Check it's not escaped
            let mut backslashes = 0u32;
            let mut k = j;
            while k > 0 && chars[k - 1] == '\\' {
                backslashes += 1;
                k -= 1;
            }
            if backslashes.is_multiple_of(2) {
                // Not escaped — this is the opening quote
                return j;
            }
        }
        j -= 1;
    }
    0
}

/// Extract the call expression that precedes the opening paren at `open`.
///
/// Handles:
/// - `foo(` → `"foo"`
/// - `$this->method(` → `"$this->method"`
/// - `$var->method(` → `"$var->method"`
/// - `ClassName::method(` → `"ClassName::method"`
/// - `self::method(` / `static::method(` / `parent::method(` → as-is
/// - `new ClassName(` → `"new ClassName"`
/// - `(new Foo())->method(` → `"$this->method"` etc. — simplified
pub fn extract_call_expression(chars: &[char], open: usize) -> Option<String> {
    if open == 0 {
        return None;
    }

    let mut i = open;

    // Skip whitespace before `(`
    while i > 0 && chars[i - 1] == ' ' {
        i -= 1;
    }

    if i == 0 {
        return None;
    }

    // ── If preceded by `)`, this is a chained call like `foo()->bar(`.
    // We won't try to resolve through call chains for named args — the
    // complexity is high and the user can rely on member completion.
    // But we DO need to handle `(new Foo)(` — skip for now.
    if chars[i - 1] == ')' {
        return None;
    }

    // ── Read the identifier (function/method name) ──────────────────
    let ident_end = i;
    while i > 0 && (chars[i - 1].is_alphanumeric() || chars[i - 1] == '_' || chars[i - 1] == '\\') {
        i -= 1;
    }
    if i == ident_end {
        return None;
    }
    let ident: String = chars[i..ident_end].iter().collect();

    // ── Check what precedes the identifier ──────────────────────────

    // Instance method: `->method(`
    if i >= 2 && chars[i - 2] == '-' && chars[i - 1] == '>' {
        let subject = extract_subject_before_arrow(chars, i - 2);
        if !subject.is_empty() {
            return Some(format!("{}->{}", subject, ident));
        }
        return None;
    }

    // Null-safe method: `?->method(`
    if i >= 3 && chars[i - 3] == '?' && chars[i - 2] == '-' && chars[i - 1] == '>' {
        let subject = extract_subject_before_arrow(chars, i - 3);
        if !subject.is_empty() {
            return Some(format!("{}->{}", subject, ident));
        }
        return None;
    }

    // Static method: `::method(`
    if i >= 2 && chars[i - 2] == ':' && chars[i - 1] == ':' {
        let class_name = extract_class_name_backward(chars, i - 2);
        if !class_name.is_empty() {
            return Some(format!("{}::{}", class_name, ident));
        }
        return None;
    }

    // Constructor: `new ClassName(`
    // Skip whitespace and check for `new` keyword.
    let mut j = i;
    while j > 0 && chars[j - 1] == ' ' {
        j -= 1;
    }
    if j >= 3 && chars[j - 3] == 'n' && chars[j - 2] == 'e' && chars[j - 1] == 'w' {
        // Verify word boundary before `new`
        let before_ok = j == 3 || { !chars[j - 4].is_alphanumeric() && chars[j - 4] != '_' };
        if before_ok {
            return Some(format!("new {}", ident));
        }
    }

    // Standalone function call: `foo(`
    Some(ident)
}

/// Extract the subject before `->` for method calls.
///
/// `arrow_pos` points to the `-` of `->`.
/// Handles `$this`, `$var`, and simple variable names.
pub fn extract_subject_before_arrow(chars: &[char], arrow_pos: usize) -> String {
    let mut i = arrow_pos;
    // Skip whitespace
    while i > 0 && chars[i - 1] == ' ' {
        i -= 1;
    }

    // Check for `)` — chained call, skip for now
    if i > 0 && chars[i - 1] == ')' {
        return String::new();
    }

    // Read identifier (property or variable name without `$`)
    let end = i;
    while i > 0 && (chars[i - 1].is_alphanumeric() || chars[i - 1] == '_') {
        i -= 1;
    }

    // Check for `$` prefix (variable)
    if i > 0 && chars[i - 1] == '$' {
        i -= 1;
        return chars[i..end].iter().collect();
    }

    // Could be a chained property: `$this->prop->method(` — just return
    // the identifier; resolution in server.rs will handle it.
    chars[i..end].iter().collect()
}

/// Extract a class name (possibly namespace-qualified) before `::`.
///
/// `colon_pos` points to the first `:` of `::`.
pub fn extract_class_name_backward(chars: &[char], colon_pos: usize) -> String {
    let mut i = colon_pos;
    // Skip whitespace
    while i > 0 && chars[i - 1] == ' ' {
        i -= 1;
    }
    let end = i;
    while i > 0 && (chars[i - 1].is_alphanumeric() || chars[i - 1] == '_' || chars[i - 1] == '\\') {
        i -= 1;
    }
    chars[i..end].iter().collect()
}

/// Parse the arguments text between `(` and the cursor to determine:
/// - Which parameter names have already been used as named arguments
/// - How many positional (non-named) arguments precede the cursor
///
/// Returns `(existing_named_args, positional_count)`.
pub fn parse_existing_args(args_text: &str) -> (Vec<String>, usize) {
    let mut named = Vec::new();
    let mut positional = 0usize;

    // Split by commas at the top level (respecting nested parens/strings)
    let args = split_args_top_level(args_text);

    for arg in &args {
        let trimmed = arg.trim();
        if trimmed.is_empty() {
            continue;
        }

        // Check if this argument is a named argument: `name: value`
        // Named args look like `identifier:` (but NOT `::`)
        if let Some(name) = extract_named_arg_name(trimmed) {
            named.push(name);
        } else {
            positional += 1;
        }
    }

    (named, positional)
}

/// Split argument text by commas at the top level (depth 0), respecting
/// nested parentheses and string literals.
pub fn split_args_top_level(text: &str) -> Vec<String> {
    let mut args = Vec::new();
    let mut current = String::new();
    let mut depth = 0i32;
    let chars: Vec<char> = text.chars().collect();
    let mut i = 0;

    while i < chars.len() {
        match chars[i] {
            '(' | '[' => {
                depth += 1;
                current.push(chars[i]);
            }
            ')' | ']' => {
                depth -= 1;
                current.push(chars[i]);
            }
            ',' if depth == 0 => {
                args.push(std::mem::take(&mut current));
            }
            '\'' | '"' => {
                let q = chars[i];
                current.push(q);
                i += 1;
                while i < chars.len() {
                    current.push(chars[i]);
                    if chars[i] == q {
                        // Check for escaping
                        let mut backslashes = 0u32;
                        let mut k = current.len() - 1;
                        while k > 0 && current.as_bytes()[k - 1] == b'\\' {
                            backslashes += 1;
                            k -= 1;
                        }
                        if backslashes.is_multiple_of(2) {
                            break;
                        }
                    }
                    i += 1;
                }
            }
            _ => current.push(chars[i]),
        }
        i += 1;
    }

    // Don't push the last segment — it's the argument currently being typed
    // and is handled separately as the prefix.
    // Actually, we DO want to push it if it has content, because parse_existing_args
    // needs to count it. But the caller already stripped the prefix from args_text,
    // so the last segment here (if any) is a complete previous argument.
    if !current.trim().is_empty() {
        args.push(current);
    }

    args
}

/// If `arg` looks like a named argument (`name: ...`), return the name.
/// Returns `None` for positional arguments.
pub fn extract_named_arg_name(arg: &str) -> Option<String> {
    // Look for `identifier:` at the start (but not `::`)
    let chars: Vec<char> = arg.chars().collect();
    let mut i = 0;

    // Skip whitespace
    while i < chars.len() && chars[i].is_whitespace() {
        i += 1;
    }

    // Read identifier
    let start = i;
    while i < chars.len() && (chars[i].is_alphanumeric() || chars[i] == '_') {
        i += 1;
    }

    if i == start {
        return None;
    }

    // Must be followed by `:` (but not `::`)
    if i < chars.len() && chars[i] == ':' {
        // Check it's not `::`
        if i + 1 < chars.len() && chars[i + 1] == ':' {
            return None;
        }
        let name: String = chars[start..i].iter().collect();
        return Some(name);
    }

    None
}

// ─── Completion Builder ─────────────────────────────────────────────────────

/// Build named-argument completion items from a list of parameters.
///
/// Parameters that have already been used as named arguments or that are
/// covered by positional arguments are excluded.
pub fn build_named_arg_completions(
    ctx: &NamedArgContext,
    parameters: &[crate::types::ParameterInfo],
) -> Vec<CompletionItem> {
    let mut items = Vec::new();
    let prefix_lower = ctx.prefix.to_lowercase();

    for (idx, param) in parameters.iter().enumerate() {
        // The parameter name in PHP includes `$`, but named args use the
        // bare name: `$name` → `name:`
        let bare_name = param.name.strip_prefix('$').unwrap_or(&param.name);

        // Skip parameters covered by positional arguments
        if idx < ctx.positional_count {
            continue;
        }

        // Skip parameters already specified as named arguments
        if ctx.existing_named_args.iter().any(|n| n == bare_name) {
            continue;
        }

        // Apply prefix filter
        if !bare_name.to_lowercase().starts_with(&prefix_lower) {
            continue;
        }

        // Build the label showing type info
        let label = if let Some(ref th) = param.type_hint {
            format!("{}: {}", bare_name, th)
        } else {
            format!("{}:", bare_name)
        };

        // Insert text: `name: ` (bare name + colon + space)
        let insert = format!("{}: ", bare_name);

        let detail = if param.is_variadic {
            Some("Named argument (variadic)".to_string())
        } else if !param.is_required {
            Some("Named argument (optional)".to_string())
        } else {
            Some("Named argument".to_string())
        };

        items.push(CompletionItem {
            label,
            kind: Some(CompletionItemKind::VARIABLE),
            detail,
            insert_text: Some(insert),
            filter_text: Some(bare_name.to_string()),
            sort_text: Some(format!("0_{:03}", idx)),
            ..CompletionItem::default()
        });
    }

    items
}