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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
//! Implements the language server protocol functionality of docuglot.
// TODO: This should be moved to only occur on cur (functionality exists in master but not 1.46.0.
#![allow(clippy::wildcard_imports)] // cur is designed to use wildcard import.
use {
    crate::json_rpc::{
        self, InsertRequestError, Kind, MethodHandlers, Object, Outcome, Params,
        ProcessResponseError, Request, ResponseHandlers,
    },
    conventus::AssembleFrom,
    core::{
        fmt::{self, Display},
        str::Utf8Error,
    },
    fehler::{throw, throws},
    lsp_types::{
        DidCloseTextDocumentParams, DidOpenTextDocumentParams, DocumentSymbolClientCapabilities,
        DocumentSymbolParams, DocumentSymbolResponse, InitializeParams, InitializeResult,
        InitializedParams, RegistrationParams, TextDocumentSyncClientCapabilities, Url,
    },
    market::{
        channel::{WithdrawnDemandFault, WithdrawnSupplyFault},
        io::{ReadFault, WriteFault},
        process::Process,
        ConsumeFault, Consumer, Failure, ProduceFailure, Producer,
    },
    serde_json::Value,
    std::process::{self, Command},
};

use cur::*;

/// The header field name that maps to the length of the content.
static HEADER_CONTENT_LENGTH: &str = "Content-Length";
/// Delimiter between a header field and value.
static HEADER_FIELD_NAME_DELIMITER: &str = ": ";
/// The end of the header.
static HEADER_END: &str = "\r\n\r\n";
/// The end of a header field.
static HEADER_FIELD_DELIMITER: &str = "\r\n";

game!(TCHAR = '!' | '#' | '$' | '%' | '&' | '\'' | '*' | '+' | '-' | '.' | '^' | '_' |'`' | '|' | '~' | '0'..='9' | 'A'..='Z' | 'a'..='z');
game!(MESSAGE = ([(name @ [TCHAR; 1..], HEADER_FIELD_NAME_DELIMITER, (value @ [_; ..]), HEADER_FIELD_DELIMITER); 1..], "\r\n", content @ [_; ..]));

/// Returns an initialize params for the tool.
fn initialize_params(root_dir: &Url) -> InitializeParams {
    #[allow(deprecated)] // root_path is required by InitializeParams.
    InitializeParams {
        process_id: Some(process::id()),
        root_path: None,
        root_uri: Some(root_dir.clone()),
        initialization_options: None,
        capabilities: lsp_types::ClientCapabilities {
            workspace: None,
            text_document: Some(lsp_types::TextDocumentClientCapabilities {
                synchronization: Some(TextDocumentSyncClientCapabilities {
                    dynamic_registration: None,
                    will_save: None,
                    will_save_wait_until: None,
                    did_save: None,
                }),
                completion: None,
                hover: None,
                signature_help: None,
                references: None,
                document_highlight: None,
                document_symbol: Some(DocumentSymbolClientCapabilities {
                    dynamic_registration: None,
                    symbol_kind: None,
                    hierarchical_document_symbol_support: Some(true),
                    tag_support: None,
                }),
                formatting: None,
                range_formatting: None,
                on_type_formatting: None,
                declaration: None,
                definition: None,
                type_definition: None,
                implementation: None,
                code_action: None,
                code_lens: None,
                document_link: None,
                color_provider: None,
                rename: None,
                publish_diagnostics: None,
                folding_range: None,
                selection_range: None,
                linked_editing_range: None,
                call_hierarchy: None,
                semantic_tokens: None,
                moniker: None,
            }),
            window: None,
            general: None,
            experimental: None,
        },
        trace: None,
        workspace_folders: None,
        client_info: None,
        locale: None,
    }
}

/// Describes events that the client must process.
#[derive(Debug, parse_display::Display)]
pub(crate) enum Event {
    /// The tool wants to send a message to the server.
    #[display("send message")]
    SendMessages(Vec<ClientMessage>),
    /// The tool encountered an error.
    #[display("error")]
    Error(TranslationError),
    /// The tool received a document symbol.
    #[display("")]
    DocumentSymbol(DocumentSymbolResponse),
}

/// An error during translation.
#[derive(Debug, ConsumeFault, thiserror::Error)]
pub enum TranslationError {
    /// Failure while transmitting a client message.
    #[error(transparent)]
    Transmission(#[from] WriteFault<Message>),
    /// Failure while receiving a server message.
    #[error(transparent)]
    Reception(#[from] ConsumeServerMessageError),
    /// Failure while creating client.
    #[error(transparent)]
    CreateClient(#[from] CreateClientError),
    /// Failure while waiting for process.
    #[error(transparent)]
    Wait(#[from] market::process::WaitFault),
    /// Attempted to consume on channel with no supply.
    #[error(transparent)]
    NoSupply(#[from] WithdrawnSupplyFault),
    /// Attempted to produce on channel with dropped [`Consumer`].
    #[error(transparent)]
    NoDemand(#[from] ProduceFailure<WithdrawnDemandFault>),
    /// An error serializing a message.
    #[error(transparent)]
    Serialize(#[from] serde_json::Error),
    /// An error reading the message.
    #[error(transparent)]
    Read(#[from] ReadFault<Message>),
    /// A JSON-RPC error.
    #[error(transparent)]
    ProcessResponse(#[from] ProcessResponseError),
    /// An invalid state.
    #[error("LSP client in invalid state: {0}")]
    InvalidState(State),
}

/// A message to the language server.
#[derive(Clone, Debug, parse_display::Display, PartialEq)]
pub enum ClientMessage {
    /// The client received the initialization.
    #[display("Initialized")]
    Initialized,
    /// The client is shutting down.
    #[display("Shutdown")]
    Shutdown,
    /// The client is exiting.
    #[display("Exit")]
    Exit,
    /// The client requests a document symbol.
    #[display("DocumentSymbol {0:?}")]
    DocumentSymbol(DocumentSymbolParams),
    /// The client opened a document.
    #[display("OpenDoc w/ {0:?}")]
    OpenDoc(DidOpenTextDocumentParams),
    /// The client closed a document.
    #[display("CloseDoc w/ {0:?}")]
    CloseDoc(DidCloseTextDocumentParams),
}

/// An error message.
#[derive(Clone, Debug)]
pub(crate) struct ErrorMessage {
    /// The message.
    line: String,
}

/// An error while composing an error message.
#[derive(Clone, Copy, ConsumeFault, Debug, thiserror::Error)]
#[error("Error while composing error message")]
pub(crate) struct ErrorMessageCompositionError;

impl AssembleFrom<u8> for ErrorMessage {
    type Error = ErrorMessageCompositionError;

    #[inline]
    #[throws(conventus::AssembleFailure<Self::Error>)]
    fn assemble_from(parts: &mut Vec<u8>) -> Self {
        if let Ok(s) = std::str::from_utf8_mut(parts) {
            if let Some(index) = s.find('\n') {
                let (l, remainder) = s.split_at_mut(index);
                let (_, new_parts) = remainder.split_at_mut(1);
                let line = (*l).to_string();
                *parts = new_parts.as_bytes().to_vec();

                Self { line }
            } else {
                // parts does not contain a new line.
                throw!(conventus::AssembleFailure::Incomplete);
            }
        } else {
            // parts has some invalid uft8.
            *parts = Vec::new();
            throw!(ErrorMessageCompositionError);
        }
    }
}

impl Display for ErrorMessage {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.line)
    }
}

/// Describes the state of the client.
#[derive(Clone, Debug, parse_display::Display, PartialEq)]
pub enum State {
    /// Server has not been initialized.
    #[display("uninitialized")]
    Uninitialized {
        /// The desired root directory of the server.
        root_dir: Url,
    },
    /// Waiting for the server to confirm initialization.
    #[display("waiting initialization")]
    WaitingInitialization {
        /// Messages to be sent after initialization is confirmed.
        messages: Vec<ClientMessage>,
    },
    /// Normal running state.
    #[display("running")]
    Running {
        /// The state of the server.
        server_state: Box<InitializeResult>,
        /// The registrations.
        registrations: Vec<lsp_types::Registration>,
    },
    /// Waiting for the server to confirm shutdown.
    #[display("waiting shutdown")]
    WaitingShutdown,
    /// Waiting for the server to exit.
    #[display("waiting exit")]
    WaitingExit,
}

/// The LSP client.
pub(crate) struct Tool {
    /// The LSP server process.
    lsp_server: Process<Message, Message, ErrorMessage>,
    /// The JSON-RPC client.
    rpc_client: json_rpc::Client<State, Event>,
    /// The JSON-RPC server.
    rpc_server: json_rpc::Server<State>,
    /// Defines the current state of `Self`.
    state: State,
}

impl Tool {
    /// Creates a new `Tool`.
    #[throws(CreateClientError)]
    pub(crate) fn new(command: Command, root_dir: Url) -> Self {
        Self {
            lsp_server: market::process::Process::new(command)?,
            state: State::Uninitialized { root_dir },
            rpc_client: json_rpc::Client::new(),
            rpc_server: json_rpc::Server::new(vec![RegistrationParams {
                registrations: vec![],
            }])?,
        }
    }

    /// Creates a new [`Tool`] that is already waiting to exit.
    #[throws(CreateClientError)]
    pub(crate) fn new_finished(command: Command) -> Self {
        Self {
            lsp_server: market::process::Process::new(command)?,
            state: State::WaitingExit,
            rpc_client: json_rpc::Client::new(),
            rpc_server: json_rpc::Server::new(vec![RegistrationParams {
                registrations: vec![],
            }])?,
        }
    }

    /// Transmits `messages` to the LSP server.
    #[throws(TranslationError)]
    pub(crate) fn transmit(&mut self, mut messages: Vec<ClientMessage>) {
        match &mut self.state {
            State::Uninitialized { ref root_dir } => {
                self.lsp_server.input().produce(Message::from(Object::from(
                    self.rpc_client.request(&initialize_params(root_dir))?,
                )))?;
                self.state = State::WaitingInitialization { messages };
            }
            State::WaitingInitialization {
                messages: pending_messages,
            } => {
                pending_messages.append(&mut messages);
            }
            State::Running { .. } => {
                for message in messages {
                    self.lsp_server
                        .input()
                        .produce(Message::from(match message {
                            ClientMessage::Initialized => {
                                Object::from(self.rpc_client.request(&InitializedParams {})?)
                            }
                            ClientMessage::Shutdown => {
                                Object::from(self.rpc_client.request(&ShutdownParams)?)
                            }
                            ClientMessage::Exit => {
                                Object::from(self.rpc_client.request(&ExitParams {})?)
                            }
                            ClientMessage::DocumentSymbol(params) => {
                                Object::from(self.rpc_client.request(&params)?)
                            }
                            ClientMessage::OpenDoc(params) => {
                                Object::from(self.rpc_client.request(&params)?)
                            }
                            ClientMessage::CloseDoc(params) => {
                                Object::from(self.rpc_client.request(&params)?)
                            }
                        }))?;
                }
            }
            State::WaitingShutdown | State::WaitingExit => {
                throw!(TranslationError::InvalidState(self.state.clone()));
            }
        }
    }

    /// Processes all receptions from LSP server.
    #[throws(TranslationError)]
    pub(crate) fn process_receptions(&mut self) -> Vec<Event> {
        let mut receptions = Vec::new();

        for good in self.lsp_server.output().goods() {
            if let Some(reception) = match good?.into() {
                Kind::Request(request_object) => {
                    if let Some(response) = self
                        .rpc_server
                        .process_request(&mut self.state, request_object)
                    {
                        self.lsp_server
                            .input()
                            .produce(Message::from(Object::from(response)))?;
                    }

                    None
                }
                Kind::Response(response) => self
                    .rpc_client
                    .process_response(&mut self.state, response)?,
            } {
                receptions.push(reception);
            }
        }

        receptions
    }

    /// Logs all messages that have currently been received on stderr.
    pub(crate) fn log_errors(&self) {
        for good in self.lsp_server.error().goods() {
            match good {
                Ok(message) => log::error!("lsp stderr: {}", message),
                Err(error) => log::error!("error logger: {}", error),
            }
        }
    }

    /// Returns the server process.
    pub(crate) const fn server(&self) -> &Process<Message, Message, ErrorMessage> {
        &self.lsp_server
    }

    /// If state of `self` is waiting exit.
    pub(crate) fn is_waiting_exit(&self) -> bool {
        self.state == State::WaitingExit
    }
}

impl Request<State, Event> for InitializeParams {
    const METHOD: &'static str = "initialize";

    #[throws(serde_json::Error)]
    fn params(&self) -> Params {
        Params::from(serde_json::to_value(self)?)
    }

    fn response_handlers(&self) -> Option<ResponseHandlers<State, Event>> {
        Some((
            |mut state, value| {
                Some(match &mut state {
                    State::Uninitialized { .. }
                    | State::Running { .. }
                    | State::WaitingShutdown
                    | State::WaitingExit => {
                        Ok(Event::Error(TranslationError::InvalidState(state.clone())))
                    }
                    State::WaitingInitialization { messages } => {
                        match serde_json::from_value::<InitializeResult>(value) {
                            Ok(initialize_result) => {
                                let mut new_messages = vec![ClientMessage::Initialized];
                                new_messages.append(messages);

                                *state = State::Running {
                                    server_state: Box::new(initialize_result),
                                    registrations: Vec::new(),
                                };

                                Ok(Event::SendMessages(new_messages))
                            }
                            Err(error) => Err(error),
                        }
                    }
                })
            },
            |_, _| None,
        ))
    }
}

impl Request<State, Event> for DocumentSymbolParams {
    const METHOD: &'static str = "textDocument/documentSymbol";

    #[throws(serde_json::Error)]
    fn params(&self) -> Params {
        Params::from(serde_json::to_value(self)?)
    }

    fn response_handlers(&self) -> Option<ResponseHandlers<State, Event>> {
        Some((
            |_, value| Some(serde_json::from_value(value).map(Event::DocumentSymbol)),
            |_, _| None,
        ))
    }
}

/// Params of "shutdown" method.
struct ShutdownParams;

impl Request<State, Event> for ShutdownParams {
    const METHOD: &'static str = "shutdown";

    #[throws(serde_json::Error)]
    fn params(&self) -> Params {
        Params::from(serde_json::to_value(())?)
    }

    fn response_handlers(&self) -> Option<ResponseHandlers<State, Event>> {
        Some((
            |mut state, _| {
                Some(match &mut state {
                    State::Uninitialized { .. }
                    | State::Running { .. }
                    | State::WaitingInitialization { .. }
                    | State::WaitingExit => {
                        Ok(Event::Error(TranslationError::InvalidState(state.clone())))
                    }
                    State::WaitingShutdown => {
                        *state = State::WaitingExit;
                        Ok(Event::SendMessages(vec![ClientMessage::Exit]))
                    }
                })
            },
            |_, _| None,
        ))
    }
}

impl Request<State, Event> for InitializedParams {
    const METHOD: &'static str = "initialized";

    #[throws(serde_json::Error)]
    fn params(&self) -> Params {
        Params::from(serde_json::to_value(())?)
    }
}

impl Request<State, Event> for DidOpenTextDocumentParams {
    const METHOD: &'static str = "textDocument/didOpen";

    #[throws(serde_json::Error)]
    fn params(&self) -> Params {
        Params::from(serde_json::to_value(self)?)
    }
}

impl Request<State, Event> for DidCloseTextDocumentParams {
    const METHOD: &'static str = "textDocument/didClose";

    #[throws(serde_json::Error)]
    fn params(&self) -> Params {
        Params::from(serde_json::to_value(self)?)
    }
}

/// Params of "exit" method.
struct ExitParams;

impl Request<State, Event> for ExitParams {
    const METHOD: &'static str = "exit";

    #[throws(serde_json::Error)]
    fn params(&self) -> Params {
        Params::from(serde_json::to_value(())?)
    }
}

impl Request<State, Event> for RegistrationParams {
    const METHOD: &'static str = "client/registerCapability";

    #[throws(serde_json::Error)]
    fn params(&self) -> Params {
        Params::from(serde_json::to_value(self)?)
    }

    fn response_handlers(&self) -> Option<ResponseHandlers<State, Event>> {
        Some((|_, _| None, |_, _| None))
    }

    fn method_handlers(&self) -> MethodHandlers<State> {
        (
            Some(|mut state, params| match &mut state {
                State::Running { registrations, .. } => {
                    match serde_json::from_value::<Self>(params.into()) {
                        Ok(mut register) => {
                            registrations.append(&mut register.registrations);
                            Outcome::Result(Value::Null)
                        }
                        Err(error) => Outcome::invalid_params(&error),
                    }
                }
                State::Uninitialized { .. }
                | State::WaitingInitialization { .. }
                | State::WaitingExit
                | State::WaitingShutdown => Outcome::invalid_state(),
            }),
            None,
        )
    }
}

/// Represents an LSP message.
// Do not use parse_display::Display as this requires Object be public.
#[derive(Debug)]
pub struct Message {
    /// The JSON-RPC object of the message.
    content: Object,
}

impl Message {
    /// Returns the header contained in `string`.
    fn header(string: &str) -> Option<&str> {
        string
            .find(HEADER_END)
            .and_then(|header_length| string.get(..header_length))
    }
}

impl AssembleFrom<u8> for Message {
    type Error = AssembleMessageError;

    #[inline]
    #[throws(conventus::AssembleFailure<AssembleMessageError>)]
    fn assemble_from(parts: &mut Vec<u8>) -> Self {
        // TODO: This would probably be simpler with a regex.
        let mut length = 0;

        let string = std::str::from_utf8(parts).map_err(Self::Error::from)?;
        let header = Self::header(string).ok_or(conventus::AssembleFailure::Incomplete)?;
        // saturating_add will not reach end due to full header_len needing to exist in string.
        let header_len = header.len().saturating_add(HEADER_END.len());
        let mut content_length: Option<usize> = None;

        for field in header.split(HEADER_FIELD_DELIMITER) {
            let mut items = field.split(": ");

            if items.next() == Some(HEADER_CONTENT_LENGTH) {
                if let Some(content_length_str) = items.next() {
                    if let Ok(value) = content_length_str.parse() {
                        content_length = Some(value);
                    }
                }

                break;
            }
        }

        // Cannot return from function until after parts.drain() is called.
        let object: Result<Object, _> = match content_length {
            None => {
                length = header_len;
                Err(conventus::AssembleFailure::Error(
                    AssembleMessageError::MissingContentLength,
                ))
            }
            Some(content_length) => {
                #[allow(clippy::option_if_let_else)]
                // False trigger. See https://github.com/rust-lang/rust-clippy/issues/5822.
                if let Some(total_len) = header_len.checked_add(content_length) {
                    if parts.len() < total_len {
                        Err(conventus::AssembleFailure::Incomplete)
                    } else if let Some(content) = string.get(header_len..total_len) {
                        length = total_len;
                        serde_json::from_str(content).map_err(|error| {
                            conventus::AssembleFailure::Error(AssembleMessageError::from(error))
                        })
                    } else {
                        length = header_len;
                        Err(conventus::AssembleFailure::Error(
                            AssembleMessageError::InvalidContentLength,
                        ))
                    }
                } else {
                    length = header_len;
                    Err(conventus::AssembleFailure::Error(
                        AssembleMessageError::InvalidContentLength,
                    ))
                }
            }
        };

        let _ = parts.drain(..length);
        object?.into()
    }
}

impl Display for Message {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.content)
    }
}

impl From<Message> for Kind {
    fn from(message: Message) -> Self {
        message.content.into()
    }
}

impl From<Object> for Message {
    #[inline]
    fn from(value: Object) -> Self {
        Self { content: value }
    }
}

// Used to be able to implement Failure on DisassembleFrom<Message>::Error.
/// Error disassembling message.
#[derive(Debug, thiserror::Error)]
pub enum DisassembleMessageFault {
    /// Error serializing message.
    #[error(transparent)]
    Serialize(#[from] serde_json::Error),
}

impl Failure for DisassembleMessageFault {
    type Fault = Self;
}

#[allow(clippy::use_self)] // False positive on format!.
impl conventus::DisassembleFrom<Message> for u8 {
    type Error = DisassembleMessageFault;

    #[inline]
    #[throws(Self::Error)]
    fn disassemble_from(good: Message) -> Vec<Self> {
        let content = serde_json::to_string(&good.content)?;

        format!(
            "{}{}{}{}{}",
            HEADER_CONTENT_LENGTH,
            HEADER_FIELD_NAME_DELIMITER,
            content.len(),
            HEADER_END,
            content
        )
        .as_bytes()
        .to_vec()
    }
}

/// Error while assembling a `Message`.
#[derive(ConsumeFault, Debug, thiserror::Error)]
pub enum AssembleMessageError {
    /// Received bytes were not valid utf8.
    #[error(transparent)]
    Utf8(#[from] Utf8Error),
    /// Content length was not found in header.
    #[error("Header is missing content length")]
    MissingContentLength,
    /// Content length is invalid.
    #[error("content length is invalid")]
    InvalidContentLength,
    /// Unable to convert message.
    #[error("messge content is invalid: {0}")]
    InvalidContent(#[from] serde_json::Error),
}

/// Failed to create `Client`.
#[derive(Debug, thiserror::Error)]
pub enum CreateClientError {
    /// Failed to create server process.
    #[error(transparent)]
    CreateProcess(#[from] market::process::CreateProcessError),
    /// Failed to insert request.
    #[error(transparent)]
    InsertRequest(#[from] InsertRequestError),
}

/// Client failed to consume `lsp::ServerMessage`.
#[derive(ConsumeFault, Debug, thiserror::Error)]
pub enum ConsumeServerMessageError {
    /// Client failed to consume lsp::Message from server.
    #[error(transparent)]
    Consume(#[from] ReadFault<Message>),
}