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
use crate::common::{create_psr4_workspace, create_test_backend};
use tower_lsp::LanguageServer;
use tower_lsp::lsp_types::*;

// ─── Template parameter bounds completion tests ─────────────────────────────
//
// These tests verify that when a property or variable has a type that is a
// template parameter (e.g. `TNode`), the resolver falls back to the upper
// bound declared in `@template TNode of SomeClass` so that completion and
// go-to-definition still work.

/// Helper: open a document, send a completion request, return item labels.
async fn complete_at(
    backend: &phpantom_lsp::Backend,
    uri: &Url,
    text: &str,
    line: u32,
    character: u32,
) -> Vec<String> {
    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "php".to_string(),
                version: 1,
                text: text.to_string(),
            },
        })
        .await;

    let result = backend
        .completion(CompletionParams {
            text_document_position: TextDocumentPositionParams {
                text_document: TextDocumentIdentifier { uri: uri.clone() },
                position: Position { line, character },
            },
            work_done_progress_params: WorkDoneProgressParams::default(),
            partial_result_params: PartialResultParams::default(),
            context: None,
        })
        .await
        .unwrap();

    match result {
        Some(CompletionResponse::Array(items)) => items.iter().map(|i| i.label.clone()).collect(),
        _ => vec![],
    }
}

// ─── Basic template bound on promoted constructor property ──────────────────

/// When a class declares `@template TNode of SomeBase` and a property is
/// typed as `TNode` via `@param`, completion should resolve to `SomeBase`.
#[tokio::test]
async fn test_template_bound_on_constructor_param() {
    let backend = create_test_backend();
    let uri = Url::parse("file:///tpl_bound_basic.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class PDependNode {\n",
        "    public function getParent(): ?PDependNode { return null; }\n",
        "    public function getChildren(): array { return []; }\n",
        "}\n",
        "/**\n",
        " * @template-covariant TNode of PDependNode\n",
        " */\n",
        "abstract class AbstractNode {\n",
        "    /**\n",
        "     * @param TNode $node\n",
        "     */\n",
        "    public function __construct(\n",
        "        private readonly PDependNode $node,\n",
        "    ) {}\n",
        "    public function doStuff(): void {\n",
        "        $this->node->\n",
        "    }\n",
        "}\n",
    );

    // Cursor after `$this->node->` on line 16
    let names = complete_at(&backend, &uri, text, 16, 22).await;
    assert!(
        names.iter().any(|n| n.starts_with("getParent(")),
        "Should offer PDependNode::getParent() via template bound, got: {names:?}"
    );
    assert!(
        names.iter().any(|n| n.starts_with("getChildren(")),
        "Should offer PDependNode::getChildren() via template bound, got: {names:?}"
    );
}

// ─── Template bound on a regular (non-promoted) property ────────────────────

/// A `@var TNode` annotation on a class property should fall back to the
/// template bound when `TNode` itself is not a real class.
#[tokio::test]
async fn test_template_bound_on_var_property() {
    let backend = create_test_backend();
    let uri = Url::parse("file:///tpl_bound_var.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Animal {\n",
        "    public function speak(): string { return ''; }\n",
        "}\n",
        "/**\n",
        " * @template T of Animal\n",
        " */\n",
        "class Cage {\n",
        "    /** @var T */\n",
        "    public $occupant;\n",
        "    public function test(): void {\n",
        "        $this->occupant->\n",
        "    }\n",
        "}\n",
    );

    // Cursor after `$this->occupant->` on line 11
    let names = complete_at(&backend, &uri, text, 11, 26).await;
    assert!(
        names.iter().any(|n| n.starts_with("speak(")),
        "Should offer Animal::speak() via template bound on @var, got: {names:?}"
    );
}

// ─── Template bound via @phpstan-template ───────────────────────────────────

/// The `@phpstan-template` variant should also have its bounds recognised.
#[tokio::test]
async fn test_phpstan_template_bound() {
    let backend = create_test_backend();
    let uri = Url::parse("file:///tpl_bound_phpstan.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Renderer {\n",
        "    public function render(): string { return ''; }\n",
        "}\n",
        "/**\n",
        " * @phpstan-template TRenderer of Renderer\n",
        " */\n",
        "class View {\n",
        "    /** @var TRenderer */\n",
        "    public $renderer;\n",
        "    public function show(): void {\n",
        "        $this->renderer->\n",
        "    }\n",
        "}\n",
    );

    let names = complete_at(&backend, &uri, text, 11, 26).await;
    assert!(
        names.iter().any(|n| n.starts_with("render(")),
        "Should offer Renderer::render() via @phpstan-template bound, got: {names:?}"
    );
}

// ─── Template-covariant with `of` bound ─────────────────────────────────────

/// `@template-covariant T of SomeClass` should work the same as
/// `@template T of SomeClass`.
#[tokio::test]
async fn test_template_covariant_bound() {
    let backend = create_test_backend();
    let uri = Url::parse("file:///tpl_bound_covariant.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Shape {\n",
        "    public function area(): float { return 0.0; }\n",
        "}\n",
        "/**\n",
        " * @template-covariant TShape of Shape\n",
        " */\n",
        "class Canvas {\n",
        "    /** @var TShape */\n",
        "    public $shape;\n",
        "    public function draw(): void {\n",
        "        $this->shape->\n",
        "    }\n",
        "}\n",
    );

    let names = complete_at(&backend, &uri, text, 11, 22).await;
    assert!(
        names.iter().any(|n| n.starts_with("area(")),
        "Should offer Shape::area() via @template-covariant bound, got: {names:?}"
    );
}

// ─── Template without bound (bare @template T) ─────────────────────────────

/// When `@template T` has no `of` clause, the type cannot be resolved
/// to anything meaningful. Completion should gracefully return nothing
/// rather than crash or produce incorrect results.
#[tokio::test]
async fn test_template_without_bound_no_crash() {
    let backend = create_test_backend();
    let uri = Url::parse("file:///tpl_no_bound.php").unwrap();
    let text = concat!(
        "<?php\n",
        "/**\n",
        " * @template T\n",
        " */\n",
        "class Box {\n",
        "    /** @var T */\n",
        "    public $value;\n",
        "    public function test(): void {\n",
        "        $this->value->\n",
        "    }\n",
        "}\n",
    );

    // Should not crash; may return empty or limited results.
    let names = complete_at(&backend, &uri, text, 8, 23).await;
    // We just verify it doesn't panic. The result set may be empty.
    let _ = names;
}

// ─── Multiple template parameters, only one with bound ──────────────────────

/// When a class has multiple template parameters, only the one with a
/// bound should resolve through the bound type.
#[tokio::test]
async fn test_multiple_templates_one_with_bound() {
    let backend = create_test_backend();
    let uri = Url::parse("file:///tpl_bound_multi.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Entity {\n",
        "    public function getId(): int { return 0; }\n",
        "}\n",
        "/**\n",
        " * @template TKey\n",
        " * @template TEntity of Entity\n",
        " */\n",
        "class Repository {\n",
        "    /** @var TEntity */\n",
        "    public $entity;\n",
        "    public function test(): void {\n",
        "        $this->entity->\n",
        "    }\n",
        "}\n",
    );

    let names = complete_at(&backend, &uri, text, 12, 23).await;
    assert!(
        names.iter().any(|n| n.starts_with("getId(")),
        "Should offer Entity::getId() for TEntity with bound, got: {names:?}"
    );
}

// ─── Cross-file template bound resolution ───────────────────────────────────

/// Template bounds should resolve even when the bound type is defined in
/// a different file loaded via PSR-4.
#[tokio::test]
async fn test_template_bound_cross_file() {
    let (backend, _dir) = create_psr4_workspace(
        r#"{
            "autoload": {
                "psr-4": {
                    "App\\": "src/"
                }
            }
        }"#,
        &[(
            "src/BaseModel.php",
            concat!(
                "<?php\n",
                "namespace App;\n",
                "class BaseModel {\n",
                "    public function save(): bool { return true; }\n",
                "    public function delete(): bool { return true; }\n",
                "}\n",
            ),
        )],
    );

    let uri = Url::parse("file:///test_tpl_cross.php").unwrap();
    let text = concat!(
        "<?php\n",
        "use App\\BaseModel;\n",
        "/**\n",
        " * @template TModel of BaseModel\n",
        " */\n",
        "abstract class AbstractRepository {\n",
        "    /** @var TModel */\n",
        "    protected $model;\n",
        "    public function persist(): void {\n",
        "        $this->model->\n",
        "    }\n",
        "}\n",
    );

    let names = complete_at(&backend, &uri, text, 9, 22).await;
    assert!(
        names.iter().any(|n| n.starts_with("save(")),
        "Should offer BaseModel::save() via cross-file template bound, got: {names:?}"
    );
    assert!(
        names.iter().any(|n| n.starts_with("delete(")),
        "Should offer BaseModel::delete() via cross-file template bound, got: {names:?}"
    );
}

// ─── Bound with namespace prefix ────────────────────────────────────────────

/// When the bound type uses a fully-qualified name (e.g. `\App\SomeClass`),
/// it should still resolve.
#[tokio::test]
async fn test_template_bound_fqn() {
    let backend = create_test_backend();
    let uri = Url::parse("file:///tpl_bound_fqn.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Logger {\n",
        "    public function log(string $msg): void {}\n",
        "}\n",
        "/**\n",
        " * @template TLogger of Logger\n",
        " */\n",
        "class LogAware {\n",
        "    /** @var TLogger */\n",
        "    public $logger;\n",
        "    public function test(): void {\n",
        "        $this->logger->\n",
        "    }\n",
        "}\n",
    );

    let names = complete_at(&backend, &uri, text, 11, 23).await;
    assert!(
        names.iter().any(|n| n.starts_with("log(")),
        "Should offer Logger::log() via template bound, got: {names:?}"
    );
}

// ─── extract_template_params_with_bounds unit tests ─────────────────────────

#[test]
fn test_extract_bounds_basic() {
    use phpantom_lsp::docblock::extract_template_params_with_bounds;
    use phpantom_lsp::php_type::PhpType;

    let docblock = "/**\n * @template T of SomeClass\n */";
    let result = extract_template_params_with_bounds(docblock);
    assert_eq!(
        result,
        vec![("T".to_string(), Some(PhpType::parse("SomeClass")))]
    );
}

#[test]
fn test_extract_bounds_no_bound() {
    use phpantom_lsp::docblock::extract_template_params_with_bounds;

    let docblock = "/**\n * @template T\n */";
    let result = extract_template_params_with_bounds(docblock);
    assert_eq!(result, vec![("T".to_string(), None)]);
}

#[test]
fn test_extract_bounds_mixed() {
    use phpantom_lsp::docblock::extract_template_params_with_bounds;
    use phpantom_lsp::php_type::PhpType;

    let docblock = "/**\n * @template TKey\n * @template TValue of SomeInterface\n */";
    let result = extract_template_params_with_bounds(docblock);
    assert_eq!(
        result,
        vec![
            ("TKey".to_string(), None),
            ("TValue".to_string(), Some(PhpType::parse("SomeInterface"))),
        ]
    );
}

#[test]
fn test_extract_bounds_covariant() {
    use phpantom_lsp::docblock::extract_template_params_with_bounds;
    use phpantom_lsp::php_type::PhpType;

    let docblock = "/**\n * @template-covariant TNode of PDependNode\n */";
    let result = extract_template_params_with_bounds(docblock);
    assert_eq!(
        result,
        vec![("TNode".to_string(), Some(PhpType::parse("PDependNode")))]
    );
}

#[test]
fn test_extract_bounds_phpstan_prefix() {
    use phpantom_lsp::docblock::extract_template_params_with_bounds;
    use phpantom_lsp::php_type::PhpType;

    let docblock = "/**\n * @phpstan-template T of Stringable\n */";
    let result = extract_template_params_with_bounds(docblock);
    assert_eq!(
        result,
        vec![("T".to_string(), Some(PhpType::parse("Stringable")))]
    );
}

#[test]
fn test_extract_bounds_contravariant_with_bound() {
    use phpantom_lsp::docblock::extract_template_params_with_bounds;
    use phpantom_lsp::php_type::PhpType;

    let docblock = "/**\n * @template-contravariant TInput of Comparable\n */";
    let result = extract_template_params_with_bounds(docblock);
    assert_eq!(
        result,
        vec![("TInput".to_string(), Some(PhpType::parse("Comparable")))]
    );
}