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
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
#![allow(dead_code)]

use php_lsp::backend::Backend;
use serde_json::{Value, json};
use std::collections::VecDeque;
use tokio::io::{AsyncReadExt, AsyncWriteExt, DuplexStream, ReadHalf, WriteHalf};
use tokio::time::Duration;
use tower_lsp_server::{LspService, Server};

// ---------- low-level framing ----------

pub(super) fn frame(msg: &Value) -> Vec<u8> {
    let body = serde_json::to_string(msg).unwrap();
    format!("Content-Length: {}\r\n\r\n{}", body.len(), body).into_bytes()
}

pub(super) async fn read_msg(reader: &mut (impl AsyncReadExt + Unpin)) -> Value {
    let mut header_buf = Vec::new();
    loop {
        let b = reader.read_u8().await.expect("read byte");
        header_buf.push(b);
        if header_buf.ends_with(b"\r\n\r\n") {
            break;
        }
    }
    let header_str = std::str::from_utf8(&header_buf).unwrap();
    let content_length: usize = header_str
        .lines()
        .find(|l| l.to_lowercase().starts_with("content-length:"))
        .and_then(|l| l.split(':').nth(1))
        .and_then(|v| v.trim().parse().ok())
        .expect("Content-Length header");
    let mut body = vec![0u8; content_length];
    reader.read_exact(&mut body).await.expect("read body");
    serde_json::from_slice(&body).expect("parse JSON")
}

/// Pull the next protocol message, preferring anything an earlier, unrelated
/// wait already read off the wire and rebuffered (via `pending`) because it
/// wasn't what *that* call was looking for — e.g. a `$/php-lsp/indexReady`
/// notification seen while something else was only waiting on a specific
/// `publishDiagnostics`. Without this, that notification would be read once
/// and gone, and a later `wait_for_index_ready()` would hang forever.
///
/// Server→client requests (method + id) are ACKed with `null` inline and
/// never returned — the server may be blocked on that reply regardless of
/// which wait loop happens to observe it, and no caller here needs anything
/// but `null` back.
///
/// `budget` bounds how many already-buffered entries this call will draw
/// down before falling back to a real (yielding) socket read. Without a
/// bound, a call whose target never shows up among the buffered messages
/// would requeue-and-repop the same items forever without ever performing a
/// real `.await` on I/O — starving the `tokio::time::timeout` driving it on
/// a current-thread runtime instead of eventually erroring out.
async fn recv_or_buffered(
    pending: &mut VecDeque<Value>,
    read: &mut ReadHalf<DuplexStream>,
    write: &mut WriteHalf<DuplexStream>,
    budget: &mut usize,
) -> Value {
    loop {
        let msg = if *budget > 0 {
            *budget -= 1;
            pending
                .pop_front()
                .expect("budget bounded by pending.len()")
        } else {
            read_msg(read).await
        };
        if msg.get("method").is_some()
            && let Some(id) = msg.get("id")
        {
            let response = json!({
                "jsonrpc": "2.0",
                "id": id,
                "result": null,
            });
            write.write_all(&frame(&response)).await.unwrap();
            continue;
        }
        return msg;
    }
}

// ---------- raw client ----------

/// Minimal LSP client over in-memory duplex streams. Prefer `TestServer` for
/// feature tests — drop to `TestClient` only when a scenario needs unusual
/// message sequencing.
pub struct TestClient {
    pub(crate) write: WriteHalf<DuplexStream>,
    pub(crate) read: ReadHalf<DuplexStream>,
    pub(crate) next_id: u64,
    /// Notifications/responses read off the wire by one `wait_for_*` call
    /// that didn't match what it was looking for, held here for whichever
    /// later call does want them. See `recv_or_buffered`.
    pending: VecDeque<Value>,
}

impl TestClient {
    pub async fn request(&mut self, method: &str, params: Value) -> Value {
        let id = self.next_id;
        self.next_id += 1;
        let msg = json!({
            "jsonrpc": "2.0",
            "id": id,
            "method": method,
            "params": params,
        });
        self.write.write_all(&frame(&msg)).await.unwrap();
        let method_owned = method.to_owned();
        // Safe to search history: `id` is unique per request, so a buffered
        // match can only ever be the one response for this exact call.
        let mut budget = self.pending.len();
        let TestClient {
            pending,
            read,
            write,
            ..
        } = self;
        tokio::time::timeout(Duration::from_secs(10), async {
            loop {
                let msg = recv_or_buffered(pending, read, write, &mut budget).await;
                if msg.get("id") == Some(&json!(id)) {
                    return msg;
                }
                pending.push_back(msg);
            }
        })
        .await
        .unwrap_or_else(|_| panic!("timed out waiting for response to {method_owned}"))
    }

    pub async fn request_no_params(&mut self, method: &str) -> Value {
        let id = self.next_id;
        self.next_id += 1;
        let msg = json!({
            "jsonrpc": "2.0",
            "id": id,
            "method": method,
        });
        self.write.write_all(&frame(&msg)).await.unwrap();
        let method_owned = method.to_owned();
        let mut budget = self.pending.len();
        let TestClient {
            pending,
            read,
            write,
            ..
        } = self;
        tokio::time::timeout(Duration::from_secs(10), async {
            loop {
                let msg = recv_or_buffered(pending, read, write, &mut budget).await;
                if msg.get("id") == Some(&json!(id)) {
                    return msg;
                }
                pending.push_back(msg);
            }
        })
        .await
        .unwrap_or_else(|_| panic!("timed out waiting for response to {method_owned}"))
    }

    /// Send a request and immediately follow it with `$/cancelRequest` for
    /// the same id — without waiting in between — then return the response
    /// for that id. Pins tower-lsp's cancellation semantics: a request whose
    /// handler is still pending when the cancel is processed resolves to a
    /// `RequestCancelled` (-32800) error.
    pub async fn request_then_cancel(&mut self, method: &str, params: Value) -> Value {
        let id = self.next_id;
        self.next_id += 1;
        let msg = json!({
            "jsonrpc": "2.0",
            "id": id,
            "method": method,
            "params": params,
        });
        self.write.write_all(&frame(&msg)).await.unwrap();
        let cancel = json!({
            "jsonrpc": "2.0",
            "method": "$/cancelRequest",
            "params": { "id": id },
        });
        self.write.write_all(&frame(&cancel)).await.unwrap();
        let method_owned = method.to_owned();
        let mut budget = self.pending.len();
        let TestClient {
            pending,
            read,
            write,
            ..
        } = self;
        tokio::time::timeout(Duration::from_secs(5), async {
            loop {
                let msg = recv_or_buffered(pending, read, write, &mut budget).await;
                if msg.get("id") == Some(&json!(id)) {
                    return msg;
                }
                pending.push_back(msg);
            }
        })
        .await
        .unwrap_or_else(|_| panic!("timed out waiting for response to {method_owned}"))
    }

    pub async fn notify(&mut self, method: &str, params: Value) {
        let msg = json!({
            "jsonrpc": "2.0",
            "method": method,
            "params": params,
        });
        self.write.write_all(&frame(&msg)).await.unwrap();
    }

    /// Like `request`, but also collects every notification matching
    /// `capture_method` seen while waiting for the response (instead of
    /// silently discarding it, as `request` does). Returns
    /// `(response, captured_notifications)` in arrival order. Use for
    /// protocol tests asserting on server-sent notifications tied to a
    /// specific in-flight request (e.g. `$/progress` partial results).
    pub async fn request_capturing_notifications(
        &mut self,
        method: &str,
        params: Value,
        capture_method: &str,
    ) -> (Value, Vec<Value>) {
        let id = self.next_id;
        self.next_id += 1;
        let msg = json!({
            "jsonrpc": "2.0",
            "id": id,
            "method": method,
            "params": params,
        });
        self.write.write_all(&frame(&msg)).await.unwrap();
        let method_owned = method.to_owned();
        let mut captured = Vec::new();
        let mut budget = self.pending.len();
        let TestClient {
            pending,
            read,
            write,
            ..
        } = self;
        let resp = tokio::time::timeout(Duration::from_secs(10), async {
            loop {
                let msg = recv_or_buffered(pending, read, write, &mut budget).await;
                if msg.get("method") == Some(&json!(capture_method)) {
                    captured.push(msg);
                    continue;
                }
                if msg.get("id") == Some(&json!(id)) {
                    return msg;
                }
                pending.push_back(msg);
            }
        })
        .await
        .unwrap_or_else(|_| panic!("timed out waiting for response to {method_owned}"));
        (resp, captured)
    }

    /// Block until a notification with `method` arrives. 5 s timeout.
    ///
    /// Forward-only (ignores anything already buffered): a bare method name
    /// can recur (e.g. multiple `window/logMessage`s in one session), so a
    /// historical match here could silently return a stale message instead
    /// of the fresh one this call actually wants — unlike the one-shot
    /// `$/php-lsp/indexReady`, there's no way to tell "the right one" apart
    /// from "an earlier one" by method name alone.
    pub async fn read_notification(&mut self, method: &str) -> Value {
        let mut budget = 0;
        let TestClient {
            pending,
            read,
            write,
            ..
        } = self;
        tokio::time::timeout(Duration::from_secs(5), async {
            loop {
                let msg = recv_or_buffered(pending, read, write, &mut budget).await;
                if msg.get("method") == Some(&json!(method)) {
                    return msg;
                }
                pending.push_back(msg);
            }
        })
        .await
        .unwrap_or_else(|_| panic!("timed out waiting for {method} notification"))
    }

    /// Block until `textDocument/publishDiagnostics` arrives for `uri`.
    /// Since `did_open` publishes diagnostics synchronously after parse +
    /// semantic analysis finish, this is a deterministic replacement for
    /// `sleep(150ms)` debounce waits.
    ///
    pub async fn wait_for_diagnostics(&mut self, uri: &str) -> Value {
        let uri_val = json!(uri);
        // Forward-only: a uri's diagnostics can republish (e.g. after
        // `indexReady` or a later edit), so honoring a buffered match could
        // return a stale publish instead of the one this call is for.
        let mut budget = 0;
        let TestClient {
            pending,
            read,
            write,
            ..
        } = self;
        tokio::time::timeout(Duration::from_secs(10), async {
            loop {
                let msg = recv_or_buffered(pending, read, write, &mut budget).await;
                if msg.get("method") == Some(&json!("textDocument/publishDiagnostics"))
                    && msg["params"]["uri"] == uri_val
                {
                    return msg;
                }
                pending.push_back(msg);
            }
        })
        .await
        .unwrap_or_else(|_| panic!("timed out waiting for publishDiagnostics for {uri}"))
    }

    /// Wait for `textDocument/publishDiagnostics` for each of `uris`, in any
    /// order. Discards messages for other URIs encountered along the way.
    /// Returns a map keyed by URI. Replies to any server→client requests
    /// with `null` so the server isn't blocked while we're draining.
    ///
    /// Use when a single LSP event triggers publishes for multiple files
    /// (e.g., cross-file republish after a dependency change) and the test
    /// needs to assert against each independently.
    pub async fn wait_for_diagnostics_multi(
        &mut self,
        uris: &[&str],
    ) -> std::collections::HashMap<String, Value> {
        let mut remaining: std::collections::HashSet<String> =
            uris.iter().map(|s| s.to_string()).collect();
        let mut collected: std::collections::HashMap<String, Value> =
            std::collections::HashMap::new();
        let expected = remaining.clone();
        // Forward-only — see `wait_for_diagnostics` on why a repeatable
        // per-uri signal can't safely be satisfied from history.
        let mut budget = 0;
        let TestClient {
            pending,
            read,
            write,
            ..
        } = self;
        tokio::time::timeout(Duration::from_secs(10), async {
            while !remaining.is_empty() {
                let msg = recv_or_buffered(pending, read, write, &mut budget).await;
                let wanted_uri = (msg.get("method")
                    == Some(&json!("textDocument/publishDiagnostics")))
                .then(|| msg["params"]["uri"].as_str())
                .flatten()
                .filter(|uri| remaining.contains(*uri))
                .map(|uri| uri.to_string());
                match wanted_uri {
                    Some(uri) => {
                        remaining.remove(&uri);
                        collected.insert(uri, msg);
                    }
                    None => pending.push_back(msg),
                }
            }
        })
        .await
        .unwrap_or_else(|_| {
            panic!("timed out; expected publishDiagnostics for {expected:?}, got {collected:?}")
        });
        collected
    }

    /// Drain incoming messages for `duration`, returning every
    /// `publishDiagnostics` URI seen. Used to assert the *absence* of a
    /// publish (e.g., closed file must not receive cross-file republishes).
    pub async fn drain_publish_diagnostics_uris(&mut self, duration: Duration) -> Vec<String> {
        let mut uris = Vec::new();
        // Forward-only — this asserts on what arrives *during this call's
        // window*; a stale buffered publish from before it started isn't
        // part of that window and would just be noise.
        let mut budget = 0;
        let TestClient {
            pending,
            read,
            write,
            ..
        } = self;
        let _ = tokio::time::timeout(duration, async {
            loop {
                let msg = recv_or_buffered(pending, read, write, &mut budget).await;
                if msg.get("method") == Some(&json!("textDocument/publishDiagnostics")) {
                    if let Some(uri) = msg["params"]["uri"].as_str() {
                        uris.push(uri.to_string());
                    }
                } else {
                    pending.push_back(msg);
                }
            }
        })
        .await;
        uris
    }

    /// Read messages until a server→client request with the given `method`
    /// arrives. Returns `(id, params)`. Panics after 10 seconds.
    ///
    /// Deliberately does *not* touch `pending` and does *not* ACK any
    /// other message it passes over (matching this call's original,
    /// pre-buffering behavior exactly): some callers rely on an unrelated
    /// request (e.g. `client/registerCapability`, sent but never replied to
    /// until something acks it) staying un-acked for the rest of the
    /// session — acking it here would let whatever's awaiting that reply
    /// proceed and emit messages the test never anticipated, upsetting the
    /// ordering the strict `read_notification` callers depend on.
    pub async fn expect_server_request(&mut self, method: &str) -> (Value, Value) {
        tokio::time::timeout(Duration::from_secs(10), async {
            loop {
                let msg = read_msg(&mut self.read).await;
                if msg.get("method") == Some(&json!(method)) && msg.get("id").is_some() {
                    let id = msg["id"].clone();
                    let params = msg.get("params").cloned().unwrap_or(json!(null));
                    return (id, params);
                }
            }
        })
        .await
        .unwrap_or_else(|_| panic!("timed out waiting for server request {method}"))
    }

    /// Send a successful response to a server→client request.
    pub async fn reply_to_server_request(&mut self, id: Value, result: Value) {
        let response = json!({
            "jsonrpc": "2.0",
            "id": id,
            "result": result,
        });
        self.write.write_all(&frame(&response)).await.unwrap();
    }

    /// Drain messages until `$/php-lsp/indexReady` arrives, returning every
    /// notification seen along the way (server→client requests are acknowledged
    /// with `null` as usual). Useful for asserting protocol behavior during the
    /// workspace scan without racing against the ready signal.
    pub async fn collect_until_index_ready(&mut self) -> Vec<Value> {
        let mut notifications: Vec<Value> = Vec::new();
        let mut budget = self.pending.len();
        let TestClient {
            pending,
            read,
            write,
            ..
        } = self;
        tokio::time::timeout(Duration::from_secs(10), async {
            loop {
                let msg = recv_or_buffered(pending, read, write, &mut budget).await;
                if msg.get("method") == Some(&json!("$/php-lsp/indexReady")) {
                    return;
                }
                notifications.push(msg.clone());
                pending.push_back(msg);
            }
        })
        .await
        .unwrap_or_else(|_| panic!("timed out waiting for $/php-lsp/indexReady"));
        notifications
    }

    /// Wait for `$/php-lsp/indexReady` with a custom timeout.
    /// Useful for large real-world codebases where 10 s is not enough.
    pub async fn wait_for_index_ready_secs(&mut self, secs: u64) {
        let mut budget = self.pending.len();
        let TestClient {
            pending,
            read,
            write,
            ..
        } = self;
        tokio::time::timeout(Duration::from_secs(secs), async {
            loop {
                let msg = recv_or_buffered(pending, read, write, &mut budget).await;
                if msg.get("method") == Some(&json!("$/php-lsp/indexReady")) {
                    return;
                }
                pending.push_back(msg);
            }
        })
        .await
        .unwrap_or_else(|_| panic!("timed out waiting for $/php-lsp/indexReady after {secs}s"))
    }

    /// Wait for `$/php-lsp/indexReady` (10 s timeout). Auto-replies to any
    /// server-to-client requests sent during the workspace scan.
    pub async fn wait_for_index_ready(&mut self) {
        let mut budget = self.pending.len();
        let TestClient {
            pending,
            read,
            write,
            ..
        } = self;
        tokio::time::timeout(Duration::from_secs(10), async {
            loop {
                let msg = recv_or_buffered(pending, read, write, &mut budget).await;
                if msg.get("method") == Some(&json!("$/php-lsp/indexReady")) {
                    return;
                }
                pending.push_back(msg);
            }
        })
        .await
        .unwrap_or_else(|_| panic!("timed out waiting for $/php-lsp/indexReady"))
    }

    /// Wait for a `window/logMessage` whose text starts with `prefix`.
    /// Used by flows (e.g. `workspace/didChangeConfiguration`) whose
    /// completion is only observable as a specific log line.
    ///
    /// Unlike `wait_for_index_ready` (a fires-once signal, safe to satisfy
    /// from history), this log line recurs — once at startup for
    /// auto-detection and again after every `didChangeConfiguration` — so
    /// matching against a buffered *past* occurrence would silently return
    /// a stale message instead of the one this specific call caused. Budget
    /// starts at 0 to force every message to come from a fresh (post-call)
    /// read; anything already buffered is left untouched for its rightful
    /// waiter.
    pub async fn wait_for_log_message_starting_with(&mut self, prefix: &str) -> Value {
        let mut budget = 0;
        let TestClient {
            pending,
            read,
            write,
            ..
        } = self;
        tokio::time::timeout(Duration::from_secs(5), async {
            loop {
                let msg = recv_or_buffered(pending, read, write, &mut budget).await;
                if msg.get("method") == Some(&json!("window/logMessage"))
                    && msg["params"]["message"]
                        .as_str()
                        .unwrap_or("")
                        .starts_with(prefix)
                {
                    return msg;
                }
                pending.push_back(msg);
            }
        })
        .await
        .unwrap_or_else(|_| panic!("timed out waiting for log message starting with {prefix:?}"))
    }
}

pub(crate) fn spawn_server() -> TestClient {
    let (client_stream, server_stream) = tokio::io::duplex(1 << 20);
    let (server_read, server_write) = tokio::io::split(server_stream);
    let (client_read, client_write) = tokio::io::split(client_stream);
    let (service, socket) = LspService::build(Backend::new)
        .custom_method("$/php-lsp/debugStats", Backend::debug_stats)
        .finish();
    tokio::spawn(Server::new(server_read, server_write, socket).serve(service));
    TestClient {
        write: client_write,
        read: client_read,
        next_id: 1,
        pending: VecDeque::new(),
    }
}