strop-engine 0.30.0

strop editor engine: documents, grammar dispatch, services, sessions — no terminal
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
//! Live document bindings and original request ownership. Lifecycle
//! calls run through the replay tape (R11): model owners update
//! identically live and replayed; only the native wire work is gated.
use std::collections::HashMap;
use std::path::{Path, PathBuf};

use strop_core::id::{BufferRevision, ByteColumn, DocumentId, LineIndex};
use strop_lsp::{
    Client, ReplyContext, RequestInput, RequestKind, RequestRefusal, RequestStamp, ServerId,
};

use super::super::Editor;
use super::attach::AttachState;

pub(crate) struct Binding {
    pub server: ServerId,
    pub path: PathBuf,
    pub root: PathBuf,
    /// The registry language this binding serves — extensionless and
    /// ambiguous headers inherit it from the navigation that brought
    /// them here (0049 §4.4).
    pub language: String,
    /// Which filesystem `path` names — remote bindings never alias
    /// same-bytes local paths (0036 RW8).
    pub target: strop_workspace::Filesystem,
    pub revision: BufferRevision,
}

/// Tape arguments for open/change — identity only; document content
/// never enters the trace (metadata exports drop content-bearing
/// fields, and R6 forbids per-change full-text materialization).
#[derive(Debug, serde::Serialize)]
pub(crate) struct SyncArgs {
    pub server: ServerId,
    pub document: DocumentId,
    pub revision: BufferRevision,
    #[serde(with = "strop_core::path_serde")]
    pub path: PathBuf,
    pub bytes: usize,
}

#[derive(Debug, serde::Serialize)]
pub(crate) struct CloseArgs {
    pub server: ServerId,
    pub document: DocumentId,
    #[serde(with = "strop_core::path_serde")]
    pub path: PathBuf,
}

/// A server-originated jump's carried language-service context (0049
/// §4): a routing hint, NOT open state — didOpen still has to happen
/// before the document is served (the binding records that).
pub(crate) struct JumpContext {
    pub server: ServerId,
    pub root: PathBuf,
    pub language: String,
    pub target: strop_workspace::Filesystem,
}

/// What follows a format reply (config auto_format): the save that
/// triggered it (0049-adjacent; helix's auto-format).
pub(crate) enum AfterFormat {
    Save {
        document: DocumentId,
        close: bool,
        force: bool,
        request: RequestStamp,
    },
}

pub(crate) struct LspState {
    pub bindings: HashMap<DocumentId, Binding>,
    pub after_format: Option<AfterFormat>,
    /// Carried contexts for jumped-to documents not yet opened on the
    /// originating server. Consumed into a binding by didOpen.
    pub jump_contexts: HashMap<DocumentId, JumpContext>,
    pub hover: Option<RequestStamp>,
    pub navigation: Option<RequestStamp>,
    pub attach: AttachState,
}

impl Default for LspState {
    fn default() -> Self {
        Self {
            bindings: HashMap::new(),
            after_format: None,
            jump_contexts: HashMap::new(),
            hover: None,
            navigation: None,
            attach: AttachState::new(),
        }
    }
}

impl Editor {
    pub(super) fn lsp_live_client(&self, server: ServerId) -> Option<Client> {
        self.lsp_servers
            .iter()
            .find(|s| s.id == server)
            .and_then(|s| s.client.clone())
    }

    /// The document's language: a navigation-bound context's first
    /// (0049 §4.2 — an extensionless or ambiguous `.h` header keeps the
    /// language of the jump that brought it here), the extension's own
    /// for unbound ordinary opens.
    pub(super) fn lsp_doc_language(&self, document: DocumentId, path: &Path) -> Option<String> {
        if let Some(binding) = self.lsp_state.bindings.get(&document) {
            return Some(binding.language.clone());
        }
        if let Some(context) = self.lsp_state.jump_contexts.get(&document) {
            return Some(context.language.clone());
        }
        super::lsp_language(path).map(str::to_string)
    }

    pub(super) fn lsp_did_open_current(&mut self) {
        let document = self.current();
        let Some(doc) = self.lsp_current_doc_path() else {
            return;
        };
        let Some(language) = self.lsp_doc_language(document, &doc.path) else {
            return;
        };
        let Some((server, root)) =
            self.lsp_server_for(document, &doc.path, &language, &doc.filesystem)
        else {
            return;
        };
        if let Some(binding) = self.lsp_state.bindings.get(&document) {
            if binding.server == server
                && binding.path == doc.path
                && binding.target == doc.filesystem
            {
                return;
            }
            self.lsp_close_document(document);
        }
        let revision = self.buf().revision();
        let text = self.buf().snapshot();
        let args = SyncArgs {
            server,
            document,
            revision,
            path: doc.path.clone(),
            bytes: text.len_bytes(),
        };
        // Replay reproduces the recorded admission result; the binding
        // updates identically so injected replies pass freshness.
        // Headers whose extension disagrees with (or lacks) the bound
        // language speak the bound language's id (0049 §4.4).
        let lang_id = match super::lsp_language(&doc.path) {
            Some(own) if own == language => super::lang_id(&doc.path).to_string(),
            _ => language.clone(),
        };
        let opened = self.tape.call("lsp.open", &args, || {
            self.lsp_live_client(server)
                .map(|client| client.did_open(document, revision, &doc.path, &lang_id, text))
        });
        match opened {
            Ok(Some(true)) => {
                self.lsp_state.jump_contexts.remove(&document);
                self.lsp_state.bindings.insert(
                    document,
                    Binding {
                        server,
                        path: doc.path,
                        root,
                        language,
                        target: doc.filesystem,
                        revision,
                    },
                );
            }
            // A replayed refusal or a vanished connection: no binding.
            Ok(_) => {}
            Err(error) => self.message = format!("lsp open diverged from trace: {error}"),
        }
    }

    pub fn lsp_sync_changed(&mut self) {
        // Journal consumers can edit a non-current document; sync every
        // live binding in a deterministic order.
        let mut changed: Vec<_> = self
            .lsp_state
            .bindings
            .iter()
            .filter_map(|(&id, binding)| {
                let doc = self.docs.get(id)?;
                let revision = doc.buf.revision();
                (revision != binding.revision).then(|| {
                    (
                        id,
                        binding.server,
                        binding.path.clone(),
                        revision,
                        doc.buf.snapshot(),
                    )
                })
            })
            .collect();
        changed.sort_by_key(|(id, _, _, _, _)| *id);
        for (document, server, path, revision, text) in changed {
            let args = SyncArgs {
                server,
                document,
                revision,
                path: path.clone(),
                bytes: text.len_bytes(),
            };
            match self.tape.call("lsp.change", &args, || {
                self.lsp_live_client(server)
                    .map(|client| client.did_change(document, revision, &path, text))
            }) {
                Ok(Some(true)) => {
                    if let Some(binding) = self.lsp_state.bindings.get_mut(&document) {
                        binding.revision = revision;
                    }
                }
                Ok(_) => self.message = "lsp: document change refused".into(),
                Err(error) => self.message = error.to_string(),
            }
        }
    }

    pub(crate) fn lsp_close_document(&mut self, document: DocumentId) {
        self.diags.remove(&document);
        if !self.docs.is_empty() && document == self.current() {
            self.hover_card = None;
        }
        // Model owner removal happens in both modes; only the native
        // didClose notification is gated.
        if let Some(binding) = self.lsp_state.bindings.remove(&document) {
            let args = CloseArgs {
                server: binding.server,
                document,
                path: binding.path.clone(),
            };
            match self.tape.request("lsp.close", &args) {
                Ok(true) => {
                    if let Some(client) = self.lsp_live_client(binding.server) {
                        client.did_close(document, &binding.path);
                    }
                }
                Ok(false) => {}
                Err(error) => self.message = format!("lsp close diverged from trace: {error}"),
            }
        }
        if self.lsp_state.hover.is_some_and(|r| r.document == document) {
            self.lsp_state.hover = None;
            self.hover_card = None;
        }
        if self
            .lsp_state
            .navigation
            .is_some_and(|r| r.document == document)
        {
            self.lsp_state.navigation = None;
        }
        if self
            .picker
            .as_ref()
            .and_then(|p| p.lsp_context)
            .is_some_and(|c| c.stamp.document == document)
        {
            self.close_picker();
        }
        // Closing the last owning remote workspace retires its server.
        self.lsp_retire_remote_servers();
    }

    pub(crate) fn lsp_reply_fresh(&self, context: &ReplyContext) -> bool {
        let stamp = context.stamp;
        let expected = if context.kind == RequestKind::Hover {
            self.lsp_state.hover
        } else {
            self.lsp_state.navigation
        };
        expected == Some(stamp) && self.lsp_context_fresh(context)
    }

    /// An accepted result may transfer to a picker or I/O ticket after its
    /// server request is terminal. The original document/server/revision still
    /// has to be current; the new subsystem owns cancellation after transfer.
    pub(crate) fn lsp_context_fresh(&self, context: &ReplyContext) -> bool {
        let stamp = context.stamp;
        let newer = if context.kind == RequestKind::Hover {
            self.lsp_state.hover
        } else {
            self.lsp_state.navigation
        };
        !self.docs.is_empty()
            && stamp.document == self.current()
            && newer.is_none_or(|owner| owner == stamp)
            && self
                .docs
                .get(stamp.document)
                .is_some_and(|d| d.buf.revision() == stamp.revision)
            && self
                .lsp_state
                .bindings
                .get(&stamp.document)
                .is_some_and(|b| b.server == stamp.server && b.revision == stamp.revision)
    }

    pub(super) fn finish_lsp_reply(&mut self, context: &ReplyContext) -> bool {
        let fresh = self.lsp_reply_fresh(context);
        let slot = if context.kind == RequestKind::Hover {
            &mut self.lsp_state.hover
        } else {
            &mut self.lsp_state.navigation
        };
        if *slot == Some(context.stamp) {
            *slot = None;
        }
        fresh
    }

    pub(super) fn lsp_request(&mut self, kind: RequestKind) {
        self.lsp_request_with(kind, None);
    }

    /// Change-producing requests (0043): rename carries its new name on
    /// the admitted input so the tape relaunches the identical payload;
    /// format is document-wide and records the configured tab width on
    /// the pending request for the same reason.
    pub(super) fn lsp_change_request(&mut self, kind: RequestKind, rename_to: Option<String>) {
        self.lsp_request_with(kind, rename_to);
    }

    fn lsp_request_with(&mut self, kind: RequestKind, rename_to: Option<String>) {
        let hover = kind == RequestKind::Hover;
        if hover {
            self.lsp_state.hover = None;
        } else {
            self.lsp_state.navigation = None;
            self.cancel_open(strop_core::worker::CancelReason::Superseded);
        }
        let Some(doc) = self.lsp_current_doc_path() else {
            self.message =
                "language services require a complete file buffer, not a partial/follow view"
                    .into();
            return;
        };
        let Some(language) = self.lsp_doc_language(self.current(), &doc.path) else {
            self.message = "no language server for this file type".into();
            return;
        };
        let Some((server, _)) =
            self.lsp_server_for(self.current(), &doc.path, &language, &doc.filesystem)
        else {
            self.message = match doc.filesystem {
                strop_workspace::Filesystem::Local => {
                    // 0049 §4.6: a server that simply doesn't cover this
                    // path is a different story from one that isn't
                    // installed — name the way in, honestly.
                    let covered_language = self
                        .lsp_state
                        .attach
                        .attached
                        .iter()
                        .any(|a| a.language == language);
                    if covered_language {
                        "no language context for this file — reach it via gd from a                          served file, or add its root to languages.toml"
                            .into()
                    } else {
                        "no language server — install it or fix languages.toml".into()
                    }
                }
                strop_workspace::Filesystem::Remote(endpoint) => {
                    format!(
                        "no language server on {endpoint} — install it there or fix languages.toml"
                    )
                }
                strop_workspace::Filesystem::Container(_) => {
                    "language services in containers are not wired yet".into()
                }
            };
            return;
        };
        self.lsp_did_open_current();
        self.lsp_sync_changed();
        let Some(doc) = self.lsp_current_doc_path() else {
            return;
        };
        let line = self.buf().line_of(self.head());
        let input = RequestInput {
            document: self.current(),
            revision: self.buf().revision(),
            path: doc.path.clone(),
            line: LineIndex::new(line),
            byte_col: ByteColumn::new(self.buf().col_of(self.head())),
            line_text: strop_lsp::FrozenLine::from_slice(
                self.buf()
                    .text()
                    .byte_slice(self.buf().line_start(line)..self.buf().line_end(line)),
            ),
            kind,
            rename_to,
        };
        let native_input = input.clone();
        let prepared = self.tape.call("lsp.prepare", &input, || {
            let client = self
                .lsp_live_client(server)
                .ok_or(RequestRefusal::NotOpen)?;
            client.prepare_request(native_input)
        });
        match prepared {
            Ok(Ok(mut prepared)) => {
                if kind == RequestKind::Format {
                    // Rides the admitted record so replay relaunches the
                    // identical payload (tab width included).
                    prepared.tab_width = Some(self.cur_indent().width);
                }
                // Register the owner stamp before launching; replayed
                // replies validate against exactly this stamp.
                if hover {
                    self.lsp_state.hover = Some(prepared.stamp);
                } else {
                    self.lsp_state.navigation = Some(prepared.stamp);
                }
                if matches!(
                    kind,
                    RequestKind::Locations(_)
                        | RequestKind::Format
                        | RequestKind::Rename
                        | RequestKind::CodeAction
                ) {
                    let label = match kind {
                        RequestKind::Locations(k) => k.label(),
                        other => other.label(),
                    };
                    self.message = format!("lsp: {label}");
                }
                match self.tape.request("lsp.launch", &prepared) {
                    Ok(true) => {
                        if let Some(client) = self.lsp_live_client(server) {
                            client.launch_request(prepared);
                        }
                    }
                    Ok(false) => {}
                    Err(error) => {
                        if hover {
                            self.lsp_state.hover = None;
                        } else {
                            self.lsp_state.navigation = None;
                        }
                        self.message = format!("lsp request diverged from trace: {error}");
                    }
                }
            }
            Ok(Err(refusal)) => {
                self.message = match refusal {
                    RequestRefusal::NotOpen => {
                        "lsp: the document is not open on this server".into()
                    }
                    RequestRefusal::StaleRevision => format!(
                        "lsp: buffer changed while syncing — repeat {}",
                        kind.label()
                    ),
                    RequestRefusal::Unsupported => {
                        format!("lsp: {} is not supported by this server", kind.label())
                    }
                    RequestRefusal::IdentityExhausted => "lsp: request identities exhausted".into(),
                };
            }
            Err(error) => self.message = format!("lsp prepare diverged from trace: {error}"),
        }
    }

    pub(super) fn lsp_failed(&mut self, server: ServerId) {
        let mut docs: Vec<_> = self
            .lsp_state
            .bindings
            .iter()
            .filter_map(|(&id, b)| (b.server == server).then_some(id))
            .collect();
        docs.sort();
        for document in docs {
            self.lsp_close_document(document);
        }
        self.lsp_state
            .attach
            .attached
            .retain(|a| a.server != server);
        self.lsp_state
            .jump_contexts
            .retain(|_, context| context.server != server);
        if let Some(index) = self.lsp_servers.iter().position(|s| s.id == server) {
            let connection = self.lsp_servers.remove(index);
            if let Some(client) = connection.client {
                // Joining a dead/failed server never blocks the input thread.
                std::thread::spawn(move || {
                    client.shutdown();
                    client.wait(std::time::Duration::from_secs(2));
                });
            }
        }
    }
}