strop-lsp 0.34.0

strop lsp: async-lsp client, server registry, diagnostics store
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
//! Shared request ownership, diagnostics and negotiated coordinate domains.
use std::path::PathBuf;
use strop_core::id::{BufferRevision, ByteColumn, DocumentId, LineIndex};
use strop_workspace::ResourceLocation;

/// Diagnostic severity (R13): a named domain, never a raw u8. Variant
/// order matches the LSP rank, so `min_by_key` keeps the worst entry.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
)]
pub enum Severity {
    Error,
    Warning,
    Information,
    Hint,
}

impl Severity {
    /// The LSP wire code (1=error … 4=hint) — display/trace boundary only.
    pub const fn code(self) -> u8 {
        match self {
            Self::Error => 1,
            Self::Warning => 2,
            Self::Information => 3,
            Self::Hint => 4,
        }
    }

    /// Gutter/picker letter.
    pub const fn char(self) -> char {
        match self {
            Self::Error => 'E',
            Self::Warning => 'W',
            Self::Information => 'I',
            Self::Hint => 'H',
        }
    }
}

/// A text-document wire version on one connection. Monotonic across
/// reopens so a stale versioned diagnostic can never relabel itself as
/// belonging to a new document incarnation.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
)]
#[serde(transparent)]
pub struct WireVersion(i32);

impl WireVersion {
    pub const fn new(value: i32) -> Self {
        Self(value)
    }
    pub const fn get(self) -> i32 {
        self.0
    }
    pub(crate) fn next(self) -> Option<Self> {
        self.0.checked_add(1).map(Self)
    }
}

/// A diagnostic as the server sent it: server-domain columns until the
/// editor resolves them against its rope with the negotiated encoding.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Diag {
    pub line: LineIndex,
    pub col: ServerColumn,
    pub end_line: LineIndex,
    pub end_col: ServerColumn,
    pub severity: Severity,
    pub message: String,
}

impl Diag {
    /// Convert to the editor's byte domain. Lines beyond the current
    /// document (the server computed on older content) clamp instead of
    /// panicking; empty documents resolve to line 0.
    pub fn resolve(self, encoding: PositionEncoding, buffer: &strop_core::Buffer) -> ResolvedDiag {
        let last = buffer.len_lines().saturating_sub(1);
        let line = LineIndex::new(self.line.get().min(last));
        let end_line = LineIndex::new(self.end_line.get().min(last));
        let start_text = buffer.line_text(line);
        let end_text = if end_line == line {
            start_text.clone()
        } else {
            buffer.line_text(end_line)
        };
        ResolvedDiag {
            line,
            col: to_byte_col(&start_text, self.col, encoding),
            end_line,
            end_col: to_byte_col(&end_text, self.end_col, encoding),
            severity: self.severity,
            message: self.message,
        }
    }
}

/// A diagnostic in the editor's byte domain: columns are UTF-8 byte
/// offsets into the line, ready for gutter/underline math.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ResolvedDiag {
    pub line: LineIndex,
    pub col: ByteColumn,
    pub end_line: LineIndex,
    pub end_col: ByteColumn,
    pub severity: Severity,
    pub message: String,
}

impl ResolvedDiag {
    pub fn severity_char(&self) -> char {
        self.severity.char()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
pub struct ServerId(u64);
impl ServerId {
    pub const fn new(value: u64) -> Self {
        Self(value)
    }
    pub const fn get(self) -> u64 {
        self.0
    }
    pub(crate) fn allocate() -> Self {
        static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        match NEXT.fetch_update(
            std::sync::atomic::Ordering::Relaxed,
            std::sync::atomic::Ordering::Relaxed,
            |n| n.checked_add(1),
        ) {
            Ok(value) => Self(value),
            Err(_) => panic!("LSP server identity exhausted"),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
pub struct RequestId(u64);
impl RequestId {
    pub const fn new(value: u64) -> Self {
        Self(value)
    }
    pub const fn get(self) -> u64 {
        self.0
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct RequestStamp {
    pub request: RequestId,
    pub server: ServerId,
    pub document: DocumentId,
    pub revision: BufferRevision,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum PositionEncoding {
    Utf8,
    Utf16,
}

/// Byte column → server column for one line's text.
pub fn to_server_col(line: &str, byte_col: ByteColumn, enc: PositionEncoding) -> ServerColumn {
    crate::to_server_col_slice(line.into(), byte_col, enc)
}

/// Server column → byte column for one line's text.
pub fn to_byte_col(line: &str, server_col: ServerColumn, enc: PositionEncoding) -> ByteColumn {
    crate::to_byte_col_slice(line.into(), server_col, enc)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum LocKind {
    References,
    Implementation,
    TypeDefinition,
    Declaration,
}
impl LocKind {
    pub fn label(self) -> &'static str {
        match self {
            Self::References => "references",
            Self::Implementation => "implementation",
            Self::TypeDefinition => "type definition",
            Self::Declaration => "declaration",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum RequestKind {
    Goto,
    Hover,
    SwitchHeader,
    Locations(LocKind),
    Format,
    Rename,
    CodeAction,
    /// All symbols in one document — no position rides the request.
    DocumentSymbols,
    /// All symbols in the workspace matching a query string —
    /// document-free (0063 §2).
    WorkspaceSymbols,
}

impl RequestKind {
    pub fn label(self) -> &'static str {
        match self {
            Self::Goto => "goto definition",
            Self::Hover => "hover",
            Self::SwitchHeader => "switch source/header",
            Self::Locations(kind) => kind.label(),
            Self::Format => "format",
            Self::Rename => "rename",
            Self::CodeAction => "code action",
            Self::DocumentSymbols => "document symbols",
            Self::WorkspaceSymbols => "workspace symbols",
        }
    }
}

/// Why a request was never admitted (R9: no silent `None`). Refused
/// requests get no stamp and no wire traffic; the caller reports them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum RequestRefusal {
    /// The document is not open on this connection.
    NotOpen,
    /// The buffer moved past the captured revision — re-request.
    StaleRevision,
    /// The server advertised no provider for this request kind.
    Unsupported,
    /// The server has not finished initializing — ask again later.
    NotReady,
    /// The monotonic request-id domain has no unused identity.
    IdentityExhausted,
    /// The bounded wire queue is full — the connection is not
    /// draining (0056 AR06). Visible refusal, never a silent drop.
    Overloaded,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
pub struct ServerColumn(usize);
impl ServerColumn {
    pub const fn new(value: usize) -> Self {
        Self(value)
    }
    pub const fn get(self) -> usize {
        self.0
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ServerPosition {
    pub line: LineIndex,
    pub column: ServerColumn,
}

/// One document-symbol row, flattened from either reply shape:
/// hierarchical `DocumentSymbol[]` (container = ancestor path) or
/// legacy flat `SymbolInformation[]` (container = its containerName).
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ProtoSymbol {
    pub name: String,
    pub container: String,
    /// SymbolKind's LSP name (`Function`, `Struct`, …).
    pub kind: String,
    pub location: ServerLocation,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ServerLocation {
    /// Endpoint-scoped identity of the target: a remote location can
    /// never alias the analogous local path.
    pub doc: ResourceLocation,
    pub position: ServerPosition,
}

/// One text replacement in the server domain: lines/columns are the
/// server's negotiated coordinates until the editor resolves them
/// against its rope, exactly like [`Diag`].
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ServerEdit {
    pub start: ServerPosition,
    pub end: ServerPosition,
    pub new_text: String,
}

/// A code action's usable payload. Command-only actions carry
/// `edits: None` with `has_external_command: true`. An action whose
/// edit cannot be applied (file operations, unverifiable versions)
/// keeps its title with `edits: None` and `has_external_command:
/// false` — the editor lists it but marks it inapplicable.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ProtoAction {
    pub title: String,
    pub edits: Option<Vec<(ResourceLocation, Vec<ServerEdit>)>>,
    pub has_external_command: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ReplyContext {
    pub stamp: RequestStamp,
    pub encoding: PositionEncoding,
    pub kind: RequestKind,
}

/// Source position remains byte-native until initialize negotiates
/// encoding. Serializable: the replay tape records admissions and
/// relaunches against the identical payload.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RequestInput {
    pub document: DocumentId,
    pub revision: BufferRevision,
    #[serde(with = "strop_core::path_serde")]
    pub path: PathBuf,
    pub line: LineIndex,
    pub byte_col: ByteColumn,
    pub line_text: crate::FrozenLine,
    pub kind: RequestKind,
    /// The rename target; `None` for every non-rename request. Old
    /// tapes decode without it.
    #[serde(default)]
    pub rename_to: Option<String>,
}

/// An admitted request: its owning stamp plus the captured input.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PendingRequest {
    pub stamp: RequestStamp,
    pub input: RequestInput,
    /// Format options ride the admission record, not the input: a
    /// formatting request has no cursor position, and the tape
    /// serializes this record at `lsp.launch`, so a replayed format
    /// relaunches with the recorded tab width. `None` for non-format
    /// requests; old tapes decode without it.
    #[serde(default)]
    pub tab_width: Option<usize>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct DiagnosticContext {
    pub server: ServerId,
    pub document: DocumentId,
    /// Current sent revision at receipt, not proof of computation freshness
    /// for versionless diagnostics.
    pub revision: BufferRevision,
    pub encoding: PositionEncoding,
    pub version: Option<WireVersion>,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum LspEvent {
    Diagnostics {
        context: DiagnosticContext,
        /// The diagnosed document: endpoint-scoped, so remote
        /// diagnostics never collide with same-bytes local paths.
        doc: ResourceLocation,
        diags: Vec<Diag>,
    },
    Ready {
        server: ServerId,
        name: String,
    },
    Failed {
        server: ServerId,
        name: String,
        hint: String,
    },
    /// A server-initiated `window/showMessage`: user-facing, from the
    /// owning server. `window/logMessage` stays in the trace — it is
    /// logging, not a message.
    ServerMessage {
        server: ServerId,
        name: String,
        text: String,
    },
    HoverText {
        context: ReplyContext,
        text: String,
    },
    GotoLocation {
        context: ReplyContext,
        location: ServerLocation,
    },
    Locations {
        context: ReplyContext,
        kind: LocKind,
        items: Vec<ServerLocation>,
    },
    /// Formatting reply: the document's replacement spans in
    /// server-domain positions (empty when the server has no changes).
    Edits {
        context: ReplyContext,
        edits: Vec<ServerEdit>,
    },
    /// Rename or an edit-bearing code action: per-resource edit groups
    /// in server-domain positions.
    WorkspaceEdits {
        context: ReplyContext,
        edits: Vec<(ResourceLocation, Vec<ServerEdit>)>,
    },
    /// Code-action reply: the server's listed actions with their
    /// usable payloads.
    ActionList {
        context: ReplyContext,
        actions: Vec<ProtoAction>,
    },
    /// Document-symbol reply: the flattened tree (0047 §1) — both
    /// server reply shapes land in the same row form.
    Symbols {
        context: ReplyContext,
        symbols: Vec<ProtoSymbol>,
    },
    /// Workspace-symbol reply (0063 §2): document-free, so ownership
    /// rides the caller's generation, not a document stamp.
    WorkspaceSymbols {
        server: ServerId,
        generation: u64,
        symbols: Vec<ProtoSymbol>,
    },
    /// The workspace-symbol request failed on this server (R9: the
    /// request still ends in exactly one terminal event).
    WorkspaceSymbolsFailed {
        server: ServerId,
        generation: u64,
        reason: String,
    },
    /// context is the ORIGINAL request's — never re-derived.
    Note {
        context: ReplyContext,
        text: String,
    },
}