php-lsp 0.5.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
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
//! Text formatting: document formatting, range formatting, and on-type formatting.

use super::*;

#[tokio::test]
async fn formatting_returns_null_or_valid_edits() {
    let mut server = TestServer::new().await;
    server
        .open("fmt.php", "<?php\nfunction ugly( $x ){return $x;}\n")
        .await;

    let resp = server.formatting("fmt.php").await;

    assert!(resp["error"].is_null(), "formatting error: {:?}", resp);
    match resp["result"].as_array() {
        None => assert!(
            resp["result"].is_null(),
            "expected null (no formatter) or TextEdit array, got: {:?}",
            resp["result"]
        ),
        Some(edits) => {
            assert!(!edits.is_empty(), "formatter returned empty edit array");
            for edit in edits {
                assert!(
                    edit["range"].is_object(),
                    "TextEdit missing 'range': {:?}",
                    edit
                );
                assert!(
                    edit["newText"].is_string(),
                    "TextEdit missing 'newText': {:?}",
                    edit
                );
            }
        }
    }
}

#[tokio::test]
async fn range_formatting_returns_null_or_valid_edits() {
    let mut server = TestServer::new().await;
    server
        .open("rfmt.php", "<?php\nfunction ugly( $x ){return $x;}\n")
        .await;

    let resp = server.range_formatting("rfmt.php", 0, 0, 2, 0).await;

    assert!(resp["error"].is_null(), "rangeFormatting error: {:?}", resp);
    match resp["result"].as_array() {
        None => assert!(
            resp["result"].is_null(),
            "expected null (no formatter) or TextEdit array, got: {:?}",
            resp["result"]
        ),
        Some(edits) => {
            assert!(!edits.is_empty(), "formatter returned empty edit array");
            for edit in edits {
                assert!(
                    edit["range"].is_object(),
                    "TextEdit missing 'range': {:?}",
                    edit
                );
                assert!(
                    edit["newText"].is_string(),
                    "TextEdit missing 'newText': {:?}",
                    edit
                );
            }
        }
    }
}

/// Unknown trigger characters must return null — the handler only supports `}` and `\n`.
#[tokio::test]
async fn on_type_formatting_unknown_trigger_returns_null() {
    let mut server = TestServer::new().await;
    server.open("otfmt.php", "<?php\nif (true) {\n").await;

    let resp = server.on_type_formatting("otfmt.php", 1, 10, "{").await;

    assert!(
        resp["error"].is_null(),
        "onTypeFormatting error: {:?}",
        resp
    );
    assert!(
        resp["result"].is_null(),
        "expected null for unhandled trigger '{{', got: {:?}",
        resp["result"]
    );
}

/// The `}` trigger is handled in-process (no external tool needed) and must
/// de-indent the closing brace to match the indentation of the opening `{`.
#[tokio::test]
async fn on_type_formatting_close_brace_deindents() {
    let mut server = TestServer::new().await;
    server
        .open("otfmt2.php", "<?php\nif (true) {\n    }\n")
        .await;

    let resp = server.on_type_formatting("otfmt2.php", 2, 4, "}").await;

    assert!(
        resp["error"].is_null(),
        "onTypeFormatting error: {:?}",
        resp
    );
    let edits = resp["result"]
        .as_array()
        .expect("} trigger must produce a TextEdit array");
    assert_eq!(edits.len(), 1, "expected exactly one de-indent edit");

    let edit = &edits[0];
    assert_eq!(
        edit["range"]["start"],
        serde_json::json!({"line": 2, "character": 0}),
        "edit start must be at line 2, character 0"
    );
    assert_eq!(
        edit["range"]["end"],
        serde_json::json!({"line": 2, "character": 4}),
        "edit end must be at line 2, character 4 (replacing 4-space indent)"
    );
    assert_eq!(
        edit["newText"].as_str().unwrap(),
        "",
        "newText must be empty (de-indent to column 0)"
    );
}

/// Close brace in nested block must align to the inner `if` indent.
#[tokio::test]
async fn on_type_formatting_close_brace_nested_block() {
    let mut server = TestServer::new().await;
    server
        .open(
            "otfmt_nested.php",
            "<?php\nif (true) {\n    if (false) {\n        }\n}\n",
        )
        .await;

    let resp = server
        .on_type_formatting("otfmt_nested.php", 3, 8, "}")
        .await;

    assert!(
        resp["error"].is_null(),
        "onTypeFormatting error: {:?}",
        resp
    );
    let edits = resp["result"]
        .as_array()
        .expect("} trigger must produce a TextEdit array");
    assert_eq!(edits.len(), 1, "expected exactly one edit for nested block");

    let edit = &edits[0];
    assert_eq!(
        edit["range"]["start"],
        serde_json::json!({"line": 3, "character": 0}),
        "edit must start at column 0"
    );
    assert_eq!(
        edit["range"]["end"],
        serde_json::json!({"line": 3, "character": 8}),
        "edit must replace 8-space indent"
    );
    assert_eq!(
        edit["newText"].as_str().unwrap(),
        "    ",
        "newText must be 4-space indent (matching inner if)"
    );
}

/// Close brace already at correct indent produces no edits.
#[tokio::test]
async fn on_type_formatting_close_brace_already_aligned() {
    let mut server = TestServer::new().await;
    server
        .open("otfmt_aligned.php", "<?php\nif (true) {\n}\n")
        .await;

    let resp = server
        .on_type_formatting("otfmt_aligned.php", 2, 0, "}")
        .await;

    assert!(
        resp["error"].is_null(),
        "onTypeFormatting error: {:?}",
        resp
    );
    let result = &resp["result"];
    assert!(
        result.is_null(),
        "no edit needed when already aligned; expected null, got: {:?}",
        result
    );
}

/// Range formatting with a single-line range.
#[tokio::test]
async fn range_formatting_single_line_range() {
    let mut server = TestServer::new().await;
    server
        .open(
            "rfmt_single.php",
            "<?php\nfunction ugly( $x ){return $x;}\n",
        )
        .await;

    let resp = server
        .range_formatting("rfmt_single.php", 1, 0, 1, 38)
        .await;

    assert!(resp["error"].is_null(), "rangeFormatting error: {:?}", resp);
    match resp["result"].as_array() {
        None => assert!(
            resp["result"].is_null(),
            "expected null (no formatter) or TextEdit array, got: {:?}",
            resp["result"]
        ),
        Some(edits) => {
            for edit in edits {
                let start_line = edit["range"]["start"]["line"].as_u64().unwrap_or(0);
                let end_line = edit["range"]["end"]["line"].as_u64().unwrap_or(0);
                assert!(
                    start_line >= 1 && end_line <= 1,
                    "all edits should be within the specified range (line 1)"
                );
            }
        }
    }
}

/// Range formatting covering the entire file.
#[tokio::test]
async fn range_formatting_entire_file_range() {
    let mut server = TestServer::new().await;
    server
        .open("rfmt_all.php", "<?php\nfunction ugly( $x ){return $x;}\n\n")
        .await;

    let resp = server.range_formatting("rfmt_all.php", 0, 0, 3, 0).await;

    assert!(resp["error"].is_null(), "rangeFormatting error: {:?}", resp);
    match resp["result"].as_array() {
        None => assert!(
            resp["result"].is_null(),
            "expected null (no formatter) or TextEdit array, got: {:?}",
            resp["result"]
        ),
        Some(edits) => {
            assert!(
                !edits.is_empty(),
                "when formatter is available, whole-file range should produce edits"
            );
            for edit in edits {
                assert!(
                    edit["range"].is_object(),
                    "TextEdit missing 'range': {:?}",
                    edit
                );
                assert!(
                    edit["newText"].is_string(),
                    "TextEdit missing 'newText': {:?}",
                    edit
                );
            }
        }
    }
}

/// Newline trigger after opening brace must indent the new line.
#[tokio::test]
async fn on_type_formatting_newline_indents_after_open_brace() {
    let mut server = TestServer::new().await;
    server
        .open("otfmt_nl1.php", "<?php\nif (true) {\n\n}")
        .await;

    let resp = server.on_type_formatting("otfmt_nl1.php", 2, 0, "\n").await;

    assert!(
        resp["error"].is_null(),
        "onTypeFormatting error: {:?}",
        resp
    );
    let edits = resp["result"]
        .as_array()
        .expect("newline trigger must produce edits");
    assert_eq!(
        edits.len(),
        1,
        "expected exactly one indent edit for newline after brace"
    );
    assert_eq!(
        edits[0]["newText"].as_str().unwrap(),
        "    ",
        "newline should produce 4-space indent"
    );
}

/// Newline trigger on an indented line copies the base indent.
#[tokio::test]
async fn on_type_formatting_newline_copies_base_indent() {
    let mut server = TestServer::new().await;
    server.open("otfmt_nl2.php", "<?php\n    $x = 1;\n").await;

    let resp = server.on_type_formatting("otfmt_nl2.php", 2, 0, "\n").await;

    assert!(
        resp["error"].is_null(),
        "onTypeFormatting error: {:?}",
        resp
    );
    let edits = resp["result"]
        .as_array()
        .expect("newline trigger must produce edits");
    assert_eq!(
        edits.len(),
        1,
        "expected exactly one indent edit for newline"
    );
    assert_eq!(
        edits[0]["newText"].as_str().unwrap(),
        "    ",
        "newline should copy the 4-space base indent"
    );
}

/// Newline trigger with tab indentation (insertSpaces: false).
#[tokio::test]
async fn on_type_formatting_newline_uses_tabs() {
    let mut server = TestServer::new().await;
    server
        .open("otfmt_nl_tabs.php", "<?php\nif (true) {\n\n}")
        .await;

    let resp = server
        .on_type_formatting_with_options("otfmt_nl_tabs.php", 2, 0, "\n", 4, false)
        .await;

    assert!(
        resp["error"].is_null(),
        "onTypeFormatting error: {:?}",
        resp
    );
    let edits = resp["result"]
        .as_array()
        .expect("newline trigger with tabs must produce edits");
    assert_eq!(edits.len(), 1, "expected exactly one edit");
    assert_eq!(
        edits[0]["newText"].as_str().unwrap(),
        "\t",
        "newline with insertSpaces=false should produce tab indent"
    );
}

/// Newline at top level (line 0) produces no edits.
#[tokio::test]
async fn on_type_formatting_newline_at_top_level_no_edit() {
    let mut server = TestServer::new().await;
    server.open("otfmt_nl_toplevel.php", "<?php\n").await;

    let resp = server
        .on_type_formatting("otfmt_nl_toplevel.php", 1, 0, "\n")
        .await;

    assert!(
        resp["error"].is_null(),
        "onTypeFormatting error: {:?}",
        resp
    );
    let result = &resp["result"];
    assert!(
        result.is_null(),
        "newline at top level should produce no edit; got: {:?}",
        result
    );
}

/// Newline when the line already has correct indent produces no edits.
#[tokio::test]
async fn on_type_formatting_newline_no_edit_when_already_correct() {
    let mut server = TestServer::new().await;
    server
        .open("otfmt_nl_correct.php", "<?php\nif (true) {\n    ")
        .await;

    let resp = server
        .on_type_formatting("otfmt_nl_correct.php", 2, 4, "\n")
        .await;

    assert!(
        resp["error"].is_null(),
        "onTypeFormatting error: {:?}",
        resp
    );
    let result = &resp["result"];
    assert!(
        result.is_null(),
        "no edit needed when indent is already correct; got: {:?}",
        result
    );
}

/// Range formatting on a code snippet that doesn't start with <?php
/// exercises the header injection and stripping path.
#[tokio::test]
async fn range_formatting_non_php_tagged_snippet() {
    let mut server = TestServer::new().await;
    server
        .open(
            "rfmt_no_opener.php",
            "<?php\nif (true)\n{\n    echo 'hello';\n}\n",
        )
        .await;

    // Format lines 2-4 (the if body, without <?php header)
    let resp = server
        .range_formatting("rfmt_no_opener.php", 2, 0, 4, 0)
        .await;

    assert!(resp["error"].is_null(), "rangeFormatting error: {:?}", resp);
    // Result is either null (no formatter) or edits within the range
    match resp["result"].as_array() {
        None => assert!(
            resp["result"].is_null(),
            "expected null (no formatter) or TextEdit array, got: {:?}",
            resp["result"]
        ),
        Some(_edits) => {
            // Formatter was available and produced edits
            // We can't assert exact content since it depends on the tool, but we can verify no panic
        }
    }
}

/// Range formatting must not produce edits outside the requested range.
#[tokio::test]
async fn range_formatting_returns_no_edits_outside_requested_range() {
    let mut server = TestServer::new().await;
    server
        .open(
            "rfmt_bounded.php",
            "<?php\nfunction ugly( $x ){return $x;}\nfunction pretty() { return 1; }\n",
        )
        .await;

    // Format only line 1 (the first function)
    let resp = server
        .range_formatting("rfmt_bounded.php", 1, 0, 1, 37)
        .await;

    assert!(resp["error"].is_null(), "rangeFormatting error: {:?}", resp);
    match resp["result"].as_array() {
        None => {
            // No formatter available
        }
        Some(edits) => {
            for edit in edits {
                let start_line = edit["range"]["start"]["line"].as_u64().unwrap_or(0);
                let end_line = edit["range"]["end"]["line"].as_u64().unwrap_or(0);
                assert!(
                    start_line == 1 && end_line == 1,
                    "all edits should be on line 1; got edit on lines {start_line}-{end_line}"
                );
            }
        }
    }
}

/// `}` trigger on a line index beyond the end of the file must return null/no-edits.
#[tokio::test]
async fn on_type_formatting_cursor_beyond_file_end_returns_empty() {
    let mut server = TestServer::new().await;
    server.open("otfmt_oob.php", "<?php\n$x = 1;\n").await;

    // Line 99 does not exist; close_brace should return vec![] which maps to null.
    let resp = server.on_type_formatting("otfmt_oob.php", 99, 0, "}").await;

    assert!(
        resp["error"].is_null(),
        "onTypeFormatting error: {:?}",
        resp
    );
    assert!(
        resp["result"].is_null(),
        "expected null result for cursor beyond file end, got: {:?}",
        resp["result"]
    );
}