hjkl-lsp 0.40.0

LSP client for the hjkl modal editor.
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
//! Async dispatch loop: owns server actors and buffer attachment state.

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;

use crossbeam_channel::Sender;
use serde_json::json;
use tokio::sync::mpsc::UnboundedReceiver;
use url::Url;

use crate::BufferId;
use crate::config::LspConfig;
use crate::event::{LspCommand, LspEvent, ServerKey, TextChange};
use crate::server::Server;
use crate::{params, workspace};

/// Per-buffer attachment record.
struct AttachedBuffer {
    uri: Url,
    server_key: ServerKey,
    version: i32,
}

/// Main async dispatch loop. Runs inside `runtime.block_on(...)` on the
/// dedicated "hjkl-lsp" std::thread.
pub async fn dispatch(
    mut cmd_rx: UnboundedReceiver<LspCommand>,
    evt_tx: Sender<LspEvent>,
    config: LspConfig,
) {
    let mut servers: HashMap<ServerKey, Server> = HashMap::new();
    let mut buffers: HashMap<BufferId, AttachedBuffer> = HashMap::new();

    while let Some(cmd) = cmd_rx.recv().await {
        match cmd {
            LspCommand::AttachBuffer {
                id,
                path,
                language_id,
                text,
            } => {
                handle_attach(
                    id,
                    path,
                    language_id,
                    text,
                    &config,
                    &mut servers,
                    &mut buffers,
                    &evt_tx,
                )
                .await;
            }
            LspCommand::DetachBuffer { id } => {
                handle_detach(id, &mut servers, &mut buffers).await;
            }
            LspCommand::NotifyChange { id, full_text } => {
                handle_notify_change(id, full_text, &mut servers, &mut buffers);
            }
            LspCommand::NotifyChangeIncremental { id, changes } => {
                handle_notify_change_incremental(id, changes, &mut servers, &mut buffers);
            }
            LspCommand::NotifySave { id } => {
                handle_notify_save(id, &mut servers, &mut buffers);
            }
            LspCommand::Cancel { request_id } => {
                // Phase 4 will cancel in-flight requests. For now just log.
                tracing::debug!(
                    request_id,
                    "LspCommand::Cancel received (Phase 4 placeholder)"
                );
            }
            LspCommand::Request {
                request_id,
                buffer_id,
                method,
                params,
            } => {
                handle_request(
                    request_id,
                    buffer_id,
                    &method,
                    params,
                    &mut servers,
                    &buffers,
                );
            }
            LspCommand::ServerExited { key } => {
                servers.remove(&key);
                buffers.retain(|_, buffer| buffer.server_key != key);
                tracing::info!(?key, "removed exited LSP server and its buffer attachments");
            }
            LspCommand::ShutdownAll => {
                tracing::info!("shutting down all LSP servers");
                for (_key, server) in servers.drain() {
                    server.shutdown().await;
                }
                break;
            }
        }
    }
}

#[allow(clippy::too_many_arguments)]
async fn handle_attach(
    id: BufferId,
    path: PathBuf,
    language_id: String,
    text: String,
    config: &LspConfig,
    servers: &mut HashMap<ServerKey, Server>,
    buffers: &mut HashMap<BufferId, AttachedBuffer>,
    evt_tx: &Sender<LspEvent>,
) {
    if buffers.contains_key(&id) {
        tracing::debug!(id, "AttachBuffer: already attached, ignoring");
        return;
    }

    // Look up server config for this language.
    let Some(server_cfg) = config.servers.get(&language_id) else {
        tracing::debug!(
            language_id,
            "AttachBuffer: no server configured for language"
        );
        return;
    };

    // Resolve workspace root.
    let markers: Vec<&str> = server_cfg.root_markers.iter().map(String::as_str).collect();
    let root = workspace::find_root(&path, &markers)
        .unwrap_or_else(|| path.parent().unwrap_or(&path).to_path_buf());

    let key = ServerKey {
        language: language_id.clone(),
        root,
    };

    // Build file URI.
    let Ok(uri) = crate::uri::from_path(&path) else {
        tracing::warn!(path = ?path, "AttachBuffer: cannot convert path to URI");
        return;
    };

    // Ensure server is running.
    if !servers.contains_key(&key) {
        match Server::spawn(key.clone(), server_cfg, evt_tx.clone()).await {
            Ok(server) => {
                servers.insert(key.clone(), server);
            }
            Err(e) => {
                tracing::warn!(key = ?key, "failed to spawn LSP server: {e:#}");
                return;
            }
        }
    }

    let server = servers.get_mut(&key).expect("just inserted");

    // Send textDocument/didOpen. `text` is *moved* into the params object
    // (see `crate::params`) — building it with `json!` would have deep-copied
    // the whole document.
    server.send_notification(
        "textDocument/didOpen",
        params::did_open(uri.as_str(), language_id, 1, text),
    );

    buffers.insert(
        id,
        AttachedBuffer {
            uri,
            server_key: key,
            version: 1,
        },
    );
}

async fn handle_detach(
    id: BufferId,
    servers: &mut HashMap<ServerKey, Server>,
    buffers: &mut HashMap<BufferId, AttachedBuffer>,
) {
    let Some(buf) = buffers.remove(&id) else {
        tracing::debug!(id, "DetachBuffer: buffer not attached");
        return;
    };

    if let Some(server) = servers.get_mut(&buf.server_key) {
        server.send_notification(
            "textDocument/didClose",
            json!({
                "textDocument": { "uri": buf.uri.as_str() }
            }),
        );
    }

    // Reference-count attached buffers per server, derived from the existing
    // `buffers` map rather than a parallel counter: if no remaining buffer
    // references this server's key, nothing needs it anymore. Shut it down
    // (reusing the same graceful-shutdown path `ShutdownAll` uses per server)
    // and drop it from `servers` so a later attach for this key re-spawns a
    // fresh server instead of finding a stale entry.
    let still_in_use = buffers.values().any(|b| b.server_key == buf.server_key);
    if !still_in_use && let Some(server) = servers.remove(&buf.server_key) {
        tracing::info!(
            key = ?buf.server_key,
            "last buffer detached; shutting down LSP server"
        );
        server.shutdown().await;
    }
}

fn handle_request(
    request_id: i64,
    buffer_id: BufferId,
    method: &str,
    params: serde_json::Value,
    servers: &mut HashMap<ServerKey, Server>,
    buffers: &HashMap<BufferId, AttachedBuffer>,
) {
    let Some(buf) = buffers.get(&buffer_id) else {
        tracing::debug!(buffer_id, method, "Request: buffer not attached");
        return;
    };
    if let Some(server) = servers.get_mut(&buf.server_key) {
        server.send_request(request_id, method, params);
    } else {
        tracing::debug!(key = ?buf.server_key, method, "Request: server not found");
    }
}

/// Full-document sync. Takes the text `Arc` by value so the params object
/// can *move* the `String` in when this side holds the only reference —
/// `Arc::unwrap_or_clone` copies only when the sender still shares it.
///
/// Note the app's current caller does still share it: `content_joined()`
/// keeps the `Arc` in the buffer's `dirty_gen` cache, so on that path
/// `unwrap_or_clone` pays for one copy — exactly the one `json!` used to
/// make, no more. Fully eliminating it for a shared `Arc` would require
/// serializing the notification directly instead of materializing a
/// `serde_json::Value` (which has no borrowed/shared string variant).
/// The unconditional win is on the owned-text paths: `didOpen` and
/// incremental `didChange`, where the text really does move.
fn handle_notify_change(
    id: BufferId,
    full_text: Arc<String>,
    servers: &mut HashMap<ServerKey, Server>,
    buffers: &mut HashMap<BufferId, AttachedBuffer>,
) {
    let Some(buf) = buffers.get_mut(&id) else {
        tracing::debug!(id, "NotifyChange: buffer not attached");
        return;
    };
    buf.version += 1;
    let version = buf.version;

    if let Some(server) = servers.get_mut(&buf.server_key) {
        server.send_notification(
            "textDocument/didChange",
            params::did_change_full(buf.uri.as_str(), version, Arc::unwrap_or_clone(full_text)),
        );
    }
}

fn handle_notify_save(
    id: BufferId,
    servers: &mut HashMap<ServerKey, Server>,
    buffers: &mut HashMap<BufferId, AttachedBuffer>,
) {
    let Some(buf) = buffers.get(&id) else {
        tracing::debug!(id, "NotifySave: buffer not attached");
        return;
    };
    let uri = buf.uri.as_str().to_string();
    if let Some(server) = servers.get_mut(&buf.server_key) {
        server.send_notification(
            "textDocument/didSave",
            json!({ "textDocument": { "uri": uri } }),
        );
    }
}

fn handle_notify_change_incremental(
    id: BufferId,
    changes: Vec<TextChange>,
    servers: &mut HashMap<ServerKey, Server>,
    buffers: &mut HashMap<BufferId, AttachedBuffer>,
) {
    if changes.is_empty() {
        return;
    }
    let Some(buf) = buffers.get_mut(&id) else {
        tracing::debug!(id, "NotifyChangeIncremental: buffer not attached");
        return;
    };
    buf.version += 1;
    let version = buf.version;

    if let Some(server) = servers.get_mut(&buf.server_key) {
        server.send_notification(
            "textDocument/didChange",
            params::did_change_incremental(buf.uri.as_str(), version, changes),
        );
    }
}

#[cfg(test)]
mod tests {
    //! `handle_detach` reference-counting tests. These drive `Server`
    //! instances backed by an in-memory `duplex` pair (no real child
    //! process — see `crate::server::spawn_from_io`), so they exercise the
    //! exact production code path (including the graceful `Server::shutdown`
    //! sequence `ShutdownAll` also uses) without spawning anything.

    use std::path::PathBuf;
    use std::time::Duration;

    use tokio::io::{AsyncWrite, BufReader, DuplexStream, ReadHalf, WriteHalf, duplex};

    use super::*;
    use crate::server;

    async fn read_json<R: tokio::io::AsyncRead + Unpin>(r: &mut BufReader<R>) -> serde_json::Value {
        let bytes = crate::codec::read_message(r)
            .await
            .expect("read_json: io error")
            .expect("read_json: clean EOF before message");
        serde_json::from_slice(&bytes).expect("read_json: invalid JSON")
    }

    async fn write_json<W: AsyncWrite + Unpin>(w: &mut W, val: &serde_json::Value) {
        let bytes = serde_json::to_vec(val).unwrap();
        crate::codec::write_message(w, &bytes).await.unwrap();
    }

    /// Absolute path under a tmp-style prefix accepted by
    /// `url::Url::from_file_path` on every platform (mirrors the helper in
    /// `tests/mock_server.rs`).
    fn workspace_root(leaf: &str) -> PathBuf {
        #[cfg(unix)]
        {
            PathBuf::from(format!("/tmp/{leaf}"))
        }
        #[cfg(windows)]
        {
            PathBuf::from(format!(r"C:\{leaf}"))
        }
    }

    /// Spawn a mock `Server` over an in-memory duplex pair, driving the
    /// `initialize` handshake to completion. Returns the ready `Server`
    /// plus the driver's read/write halves so the test can observe further
    /// protocol traffic (didClose / shutdown / exit).
    async fn mock_server(
        key: ServerKey,
    ) -> (
        Server,
        BufReader<ReadHalf<DuplexStream>>,
        WriteHalf<DuplexStream>,
    ) {
        let (client_io, driver_io) = duplex(64 * 1024);
        let (evt_tx, _evt_rx) = crossbeam_channel::unbounded::<LspEvent>();

        let (driver_read, mut driver_write) = tokio::io::split(driver_io);
        let mut driver_reader = BufReader::with_capacity(256 * 1024, driver_read);
        let (client_read, client_write) = tokio::io::split(client_io);

        let server_task = tokio::spawn({
            let key = key.clone();
            async move { server::spawn_from_io(key, client_write, client_read, evt_tx).await }
        });

        let req = read_json(&mut driver_reader).await;
        let req_id = req["id"].as_i64().unwrap();
        write_json(
            &mut driver_write,
            &json!({
                "jsonrpc": "2.0",
                "id": req_id,
                "result": { "capabilities": {} }
            }),
        )
        .await;
        let _initialized = read_json(&mut driver_reader).await; // "initialized" notification

        let server = server_task
            .await
            .expect("mock_server task panicked")
            .expect("spawn_from_io failed");
        (server, driver_reader, driver_write)
    }

    /// Build an `AttachedBuffer` pointing at `key` for a fake file under
    /// `root`. The exact path only needs to convert cleanly to a `file://`
    /// URI — its contents don't matter to `handle_detach`.
    fn attached_buffer(root: &std::path::Path, leaf: &str, key: ServerKey) -> AttachedBuffer {
        AttachedBuffer {
            uri: crate::uri::from_path(&root.join(leaf)).unwrap(),
            server_key: key,
            version: 1,
        }
    }

    /// Detaching one of *two* buffers attached to the same server must leave
    /// the server running: the other buffer still needs it. Only a
    /// `textDocument/didClose` should go out — no shutdown/exit.
    #[tokio::test(flavor = "current_thread")]
    async fn detach_keeps_server_alive_with_remaining_buffers() {
        tokio::time::timeout(Duration::from_millis(500), async {
            let root = workspace_root("refcount-keep-alive");
            let key = ServerKey {
                language: "rust".to_string(),
                root: root.clone(),
            };
            let (server, mut driver_reader, driver_write) = mock_server(key.clone()).await;

            let mut servers = HashMap::new();
            servers.insert(key.clone(), server);

            let mut buffers = HashMap::new();
            buffers.insert(1, attached_buffer(&root, "a.rs", key.clone()));
            buffers.insert(2, attached_buffer(&root, "b.rs", key.clone()));

            handle_detach(1, &mut servers, &mut buffers).await;

            assert!(
                servers.contains_key(&key),
                "server shut down while buffer 2 still references it"
            );
            assert!(!buffers.contains_key(&1));
            assert!(buffers.contains_key(&2));

            let did_close = read_json(&mut driver_reader).await;
            assert_eq!(did_close["method"], "textDocument/didClose");

            // Nothing else should be queued — specifically no "shutdown".
            let probe =
                tokio::time::timeout(Duration::from_millis(50), read_json(&mut driver_reader))
                    .await;
            assert!(
                probe.is_err(),
                "unexpected extra message after didClose: server must not have been shut down"
            );

            drop(driver_write);
        })
        .await
        .expect("detach_keeps_server_alive_with_remaining_buffers timed out");
    }

    /// Detaching the LAST buffer on a server must gracefully shut it down
    /// (the same shutdown/exit sequence `ShutdownAll` uses per server) and
    /// remove it from the `servers` map — no leaked process, no tombstone
    /// entry left behind that could block a later re-attach.
    #[tokio::test(flavor = "current_thread")]
    async fn detach_last_buffer_shuts_down_and_removes_server() {
        tokio::time::timeout(Duration::from_millis(500), async {
            let root = workspace_root("refcount-last-detach");
            let key = ServerKey {
                language: "rust".to_string(),
                root: root.clone(),
            };
            let (server, mut driver_reader, driver_write) = mock_server(key.clone()).await;

            let mut servers = HashMap::new();
            servers.insert(key.clone(), server);

            let mut buffers = HashMap::new();
            buffers.insert(1, attached_buffer(&root, "a.rs", key.clone()));

            handle_detach(1, &mut servers, &mut buffers).await;

            // The core assertion: no tombstone. `handle_attach`'s only spawn
            // gate is `!servers.contains_key(&key)`, so this is exactly the
            // condition that lets a later attach for this key re-spawn a
            // fresh server instead of silently no-op'ing.
            assert!(
                !servers.contains_key(&key),
                "server must be removed from the map after its last buffer detaches"
            );
            assert!(!buffers.contains_key(&1));

            let did_close = read_json(&mut driver_reader).await;
            assert_eq!(did_close["method"], "textDocument/didClose");
            let shutdown_req = read_json(&mut driver_reader).await;
            assert_eq!(shutdown_req["method"], "shutdown");
            let exit_notif = read_json(&mut driver_reader).await;
            assert_eq!(exit_notif["method"], "exit");

            drop(driver_write);
        })
        .await
        .expect("detach_last_buffer_shuts_down_and_removes_server timed out");
    }

    /// Detaching a buffer from server A must not touch server B: different
    /// `ServerKey`s are independent reference-counting domains.
    #[tokio::test(flavor = "current_thread")]
    async fn detach_does_not_affect_other_server() {
        tokio::time::timeout(Duration::from_millis(500), async {
            let root_a = workspace_root("refcount-isolation-a");
            let root_b = workspace_root("refcount-isolation-b");
            let key_a = ServerKey {
                language: "rust".to_string(),
                root: root_a.clone(),
            };
            let key_b = ServerKey {
                language: "go".to_string(),
                root: root_b.clone(),
            };

            let (server_a, mut driver_reader_a, driver_write_a) = mock_server(key_a.clone()).await;
            let (server_b, mut driver_reader_b, driver_write_b) = mock_server(key_b.clone()).await;

            let mut servers = HashMap::new();
            servers.insert(key_a.clone(), server_a);
            servers.insert(key_b.clone(), server_b);

            let mut buffers = HashMap::new();
            buffers.insert(1, attached_buffer(&root_a, "a.rs", key_a.clone()));
            buffers.insert(2, attached_buffer(&root_b, "b.go", key_b.clone()));

            handle_detach(1, &mut servers, &mut buffers).await;

            assert!(!servers.contains_key(&key_a), "server A must be reaped");
            assert!(servers.contains_key(&key_b), "server B must be untouched");
            assert!(
                buffers.contains_key(&2),
                "server B's buffer must remain attached"
            );

            // Server A: didClose, shutdown, exit.
            let did_close = read_json(&mut driver_reader_a).await;
            assert_eq!(did_close["method"], "textDocument/didClose");
            let shutdown_req = read_json(&mut driver_reader_a).await;
            assert_eq!(shutdown_req["method"], "shutdown");
            let exit_notif = read_json(&mut driver_reader_a).await;
            assert_eq!(exit_notif["method"], "exit");

            // Server B: nothing at all.
            let probe =
                tokio::time::timeout(Duration::from_millis(50), read_json(&mut driver_reader_b))
                    .await;
            assert!(
                probe.is_err(),
                "server B must not receive any protocol traffic"
            );

            drop(driver_write_a);
            drop(driver_write_b);
        })
        .await
        .expect("detach_does_not_affect_other_server timed out");
    }
}