lspresso 0.2.3

lsp testing and benchmarking
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
mod timings;
mod transport;

use std::{
    process::{Command, ExitStatus},
    time::{Duration, Instant},
};

use crossbeam_channel::RecvTimeoutError;
use gen_lsp_types::*;
use lsp_server::{Message, RequestId};

pub use self::timings::Timings;
use self::transport::{Incoming, Transport};
use crate::{
    Awaited, Error, Protocol, Result,
    core::{
        self, ClientState, DocumentTracker, Effect,
        notification_buffer::{NotificationBuffer, notification},
        text,
    },
    error::{ErrorKind, deadline_after, elapsed_ms},
};

const EXIT_POLL_INTERVAL: Duration = Duration::from_millis(1);
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(15);

macro_rules! assert_client_to_server {
    ($item:ty) => {
        const {
            assert!(matches!(
                <$item>::MESSAGE_DIRECTION,
                MessageDirection::ClientToServer | MessageDirection::Both
            ));
        }
    };
}

macro_rules! assert_server_to_client {
    ($item:ty) => {
        const {
            assert!(matches!(
                <$item>::MESSAGE_DIRECTION,
                MessageDirection::ServerToClient | MessageDirection::Both
            ));
        }
    };
}

#[derive(Debug, Clone, Default)]
pub struct Initialize {
    pub capabilities: ClientCapabilities,
    pub options: Option<LspAny>,
}

impl From<ClientCapabilities> for Initialize {
    fn from(capabilities: ClientCapabilities) -> Self {
        Self {
            capabilities,
            options: None,
        }
    }
}

#[derive(Debug)]
pub struct Client {
    transport: Transport,
    state: ClientState,
    docs: DocumentTracker,
    background_errors: Vec<Error>,
    timeout: Duration,
    exit_timeout: Duration,
    server_capabilities: Option<ServerCapabilities>,
    notifications: NotificationBuffer,
}

impl Client {
    pub fn spawn(command: Command) -> Result<Self> {
        Ok(Self {
            transport: Transport::spawn(command)?,
            state: ClientState::default(),
            docs: DocumentTracker::default(),
            background_errors: Vec::new(),
            timeout: DEFAULT_TIMEOUT,
            exit_timeout: DEFAULT_TIMEOUT,
            server_capabilities: None,
            notifications: NotificationBuffer::default(),
        })
    }

    pub fn spawn_initialized(command: Command, init: impl Into<Initialize>) -> Result<Self> {
        let mut client = Self::spawn(command)?;
        client.initialize(init)?;
        Ok(client)
    }

    /// How many notifications to buffer before discarding them. Defaults to 4096
    #[must_use]
    pub fn with_notification_capacity(mut self, capacity: usize) -> Self {
        self.notifications.set_capacity(capacity);
        self
    }

    /// How long to wait for a response or a notification
    #[must_use]
    pub const fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// How long [`Client::wait_for_exit`] waits for the process to exit. Separate
    /// from [`Client::with_timeout`] since teardown can be slower than a round trip
    #[must_use]
    pub const fn with_exit_timeout(mut self, timeout: Duration) -> Self {
        self.exit_timeout = timeout;
        self
    }

    pub fn initialize(&mut self, init: impl Into<Initialize>) -> Result<InitializeResult> {
        let init = init.into();
        let now = Instant::now();
        let mut params = core::capabilities::initialize_params(init.capabilities);
        params.initialization_options = init.options;
        let params = serde_json::to_value(params).expect("serializing as JSON cannot fail");
        let (id, message) = self.state.start_initialize(params, now, self.timeout)?;
        self.send_request(&id, &message, now)?;
        let result = self.wait_for_resolution(&id, InitializeRequest::METHOD)?;
        let result: InitializeResult =
            Self::deserialize_response(result, InitializeRequest::METHOD)
                .inspect_err(|_| self.state.rollback_initialize())?;
        self.transport.settle(now);
        self.send_notification::<InitializedNotification>(InitializedParams::default())
            .inspect_err(|_| self.state.rollback_initialize())?;

        self.server_capabilities = Some(result.capabilities.clone());

        Ok(result)
    }

    pub fn shutdown(&mut self) -> Result<()> {
        let now = Instant::now();
        let (id, message) = self.state.start_shutdown(now, self.timeout)?;
        self.send_request(&id, &message, now)?;
        self.wait_for_resolution(&id, ShutdownRequest::METHOD)?;

        self.send_notification::<ExitNotification>(())?;

        Ok(())
    }

    pub fn wait_for_exit(&mut self) -> Result<ExitStatus> {
        let start = Instant::now();
        let deadline = deadline_after(start, self.exit_timeout);
        let mut stdout_closed = false;
        loop {
            if let Some(status) = self.transport.try_wait()? {
                return Ok(status);
            }
            let now = Instant::now();
            if now >= deadline {
                return Err(ErrorKind::ExitTimeout {
                    after_ms: elapsed_ms(start, now),
                }
                .into());
            }
            // While stdout is open, closing it is what wakes us; after that
            // there's nothing left to read, so poll the process itself.
            if stdout_closed {
                std::thread::sleep((deadline - now).min(EXIT_POLL_INTERVAL));
            } else {
                match self.recv_and_dispatch(Some(deadline), None) {
                    RecvOutcome::Closed(_) => stdout_closed = true,
                    RecvOutcome::Resolved(_) | RecvOutcome::Handled | RecvOutcome::TimedOut => {}
                }
            }
        }
    }

    pub fn rss_bytes(&mut self) -> Option<u64> {
        self.transport.rss_bytes()
    }

    pub const fn timings(&self) -> Timings {
        self.transport.timings()
    }

    pub const fn server_capabilities(&self) -> Option<&ServerCapabilities> {
        self.server_capabilities.as_ref()
    }

    pub fn background_errors(&self) -> &[Error] {
        &self.background_errors
    }

    pub(crate) fn require_open_document(&self, uri: &Uri) -> Result<()> {
        self.state.require_initialized()?;
        self.docs.require_open(uri)
    }

    pub(crate) fn open_document_version(&self, uri: &Uri) -> Result<i32> {
        self.state.require_initialized()?;
        self.docs.current_version(uri)
    }

    pub(crate) fn tracked_text(&self, uri: &Uri) -> Result<&str> {
        self.docs.text(uri)
    }

    fn position_encoding(&self) -> PositionEncodingKind {
        match self
            .server_capabilities()
            .and_then(|capabilities| capabilities.position_encoding.as_ref())
        {
            Some(PositionEncodingKind::UTF8) => PositionEncodingKind::UTF8,
            Some(PositionEncodingKind::UTF32) => PositionEncodingKind::UTF32,
            _ => PositionEncodingKind::UTF16,
        }
    }

    pub(crate) fn content_changes(
        &self,
        text: &str,
        edits: &[TextEdit],
    ) -> Result<Vec<TextDocumentContentChangeEvent>> {
        if self.supports_incremental_sync() {
            text::changes(text, edits, &self.position_encoding())
        } else {
            let text = text::apply(text, edits, &self.position_encoding())?;
            Ok(vec![TextDocumentContentChangeWholeDocument { text }.into()])
        }
    }

    pub(crate) fn previous_result_id(&self, uri: &Uri) -> Result<Option<String>> {
        self.docs.previous_result_id(uri)
    }

    pub(crate) fn pulled_items(&self, uri: &Uri) -> Result<Vec<Diagnostic>> {
        self.docs.pulled_items(uri)
    }

    /// Waits up to the client timeout, see [`Client::with_timeout`]
    pub fn wait_for_notification<N: Notification>(&mut self) -> Result<N::Params> {
        self.wait_for_notification_where::<N>(|_| true)
    }

    /// Waits up to the client timeout, see [`Client::with_timeout`]
    pub fn wait_for_notification_where<N: Notification>(
        &mut self,
        mut matches: impl FnMut(&N::Params) -> bool,
    ) -> Result<N::Params> {
        assert_server_to_client!(N);
        self.state.require_initialized()?;
        let start = Instant::now();
        let deadline = deadline_after(start, self.timeout);
        loop {
            if let Some(params) = self.notifications.take::<N>(&mut matches) {
                self.transport.settle(start);
                return Ok(params);
            }
            if let RecvOutcome::Closed(closed) = self.recv_and_dispatch(Some(deadline), None) {
                return Err(closed.into_error(Awaited::Notification(N::METHOD)));
            }
            if let Some(params) = self.notifications.take::<N>(&mut matches) {
                self.transport.settle(start);
                return Ok(params);
            }
            let now = Instant::now();
            if now >= deadline {
                return Err(ErrorKind::NotificationTimeout {
                    method: N::METHOD,
                    after_ms: elapsed_ms(start, now),
                }
                .into());
            }
        }
    }

    fn forget_diagnostics(&mut self, uri: &Uri) {
        self.notifications
            .retain::<PublishDiagnosticsNotification>(|p| p.uri != *uri);
    }

    pub(crate) fn next_open_version(&self, uri: &Uri) -> i32 {
        self.docs.next_open_version(uri)
    }

    pub(crate) fn next_document_version_and_text(&self, uri: &Uri) -> Result<(i32, &str)> {
        self.state.require_initialized()?;
        self.docs.next_version_and_text(uri)
    }

    fn send_request(
        &mut self,
        id: &RequestId,
        message: &Message,
        started_at: Instant,
    ) -> Result<()> {
        self.transport.send(message, started_at).inspect_err(|_| {
            self.state.cancel_pending_request(id);
        })
    }

    fn deserialize_response<T>(
        value: serde_json::Value,
        method: LspRequestMethod<'static>,
    ) -> Result<T>
    where
        T: serde::de::DeserializeOwned,
    {
        serde_json::from_value(value).map_err(|err| {
            ErrorKind::MalformedResponse {
                method,
                message: err.to_string(),
            }
            .into()
        })
    }

    fn send_notification<N: Notification>(&mut self, params: N::Params) -> Result<()> {
        let started_at = Instant::now();
        let notification = notification::<N>(params);
        let commit =
            self.docs
                .prepare(N::METHOD, &notification.params, &self.position_encoding())?;
        self.transport
            .send(&Message::Notification(notification), started_at)?;
        if let Some(uri) = commit.invalidates() {
            let uri = uri.clone();
            self.forget_diagnostics(&uri);
        }
        self.docs.commit(commit);
        Ok(())
    }

    fn wait_for_resolution(
        &mut self,
        id: &RequestId,
        method: LspRequestMethod<'static>,
    ) -> Result<serde_json::Value> {
        loop {
            match self.recv_and_dispatch(None, Some(id)) {
                RecvOutcome::Resolved(result) => return result,
                RecvOutcome::Closed(closed) => {
                    self.state.cancel_pending_request(id);
                    return Err(closed.into_error(Awaited::Response(method)));
                }
                RecvOutcome::Handled | RecvOutcome::TimedOut => {}
            }
        }
    }

    /// Receives until `until` or the next request deadline, dispatches what arrived through the core, then ticks it --
    /// after every receive, not just timeouts, since a server streaming
    /// notifications never lets a receive time out.
    fn recv_and_dispatch(
        &mut self,
        until: Option<Instant>,
        waiting_for: Option<&RequestId>,
    ) -> RecvOutcome {
        let deadline = until.into_iter().chain(self.state.next_deadline()).min();
        let outcome = match self.transport.recv_until(deadline) {
            Ok(Incoming::Message(message)) => {
                if let Message::Notification(notification) = &message {
                    self.notifications.record(notification);
                }
                let effects = self.state.on_message(&message);
                if let Some(result) = self.apply_effects(effects, waiting_for) {
                    return RecvOutcome::Resolved(result);
                }
                RecvOutcome::Handled
            }
            // A closed stream outranks a timeout landing on the same pass.
            Ok(Incoming::Malformed(source)) => {
                return RecvOutcome::Closed(CloseReason::Malformed(source));
            }
            Err(RecvTimeoutError::Disconnected) => {
                return RecvOutcome::Closed(CloseReason::Disconnected);
            }
            Err(RecvTimeoutError::Timeout) => RecvOutcome::TimedOut,
        };
        let effects = self.state.expire_timed_out_requests(Instant::now());
        self.apply_effects(effects, waiting_for)
            .map_or(outcome, RecvOutcome::Resolved)
    }

    fn apply_effects(
        &mut self,
        effects: Vec<Effect>,
        waiting_for: Option<&RequestId>,
    ) -> Option<Result<serde_json::Value>> {
        let mut resolved = None;
        for effect in effects {
            if let Some(result) = self.apply_effect(effect, waiting_for) {
                resolved = Some(result);
            }
        }
        resolved
    }

    fn apply_effect(
        &mut self,
        effect: Effect,
        waiting_for: Option<&RequestId>,
    ) -> Option<Result<serde_json::Value>> {
        match effect {
            Effect::Resolved(resolved_id, result) if Some(&resolved_id) == waiting_for => {
                Some(result)
            }
            Effect::Resolved(..) => None,
            Effect::Error(err) => {
                self.background_errors.push(err);
                None
            }
            Effect::Reply(message) => {
                if let Err(err) = self.transport.send(&message, Instant::now()) {
                    self.background_errors.push(err);
                }
                None
            }
        }
    }
}

impl Protocol for Client {
    fn request<R: Request>(&mut self, params: R::Params) -> Result<R::Result> {
        assert_client_to_server!(R);
        let now = Instant::now();
        let timeout = self.timeout;
        let method = R::METHOD;
        let params =
            serde_json::to_value(params).expect("serializing request params as JSON cannot fail");
        self.state.require_initialized()?;
        let pulled = self.docs.check_request(method, &params)?;
        let (id, message) = self.state.start_generic(method, params, now, timeout)?;
        self.send_request(&id, &message, now)?;
        let result = self.wait_for_resolution(&id, method)?;
        if let Some(uri) = pulled {
            self.docs.record_pulled(&uri, &result);
        }
        let result = Self::deserialize_response(result, method)?;
        self.transport.settle(now);
        Ok(result)
    }

    fn notify<N: Notification>(&mut self, params: N::Params) -> Result<()> {
        assert_client_to_server!(N);
        self.state.require_initialized()?;
        self.send_notification::<N>(params)
    }
}

enum RecvOutcome {
    Resolved(Result<serde_json::Value>),
    Closed(CloseReason),
    /// A notification, a server request (already answered), or a response
    /// for no one.
    Handled,
    TimedOut,
}

enum CloseReason {
    Malformed(std::io::Error),
    Disconnected,
}

impl CloseReason {
    fn into_error(self, awaited: Awaited) -> Error {
        match self {
            Self::Malformed(source) => ErrorKind::MalformedMessage { awaited, source }.into(),
            Self::Disconnected => ErrorKind::Disconnected { awaited }.into(),
        }
    }
}