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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
//! A Language Server Protocol translator for clients.
#![allow(clippy::unreachable)] // Unavoidable for Enum derivation.
#![allow(clippy::pattern_type_mismatch)] // Marks enums as errors.
mod json_rpc;
mod lsp;

use {
    core::{
        cell::{Cell, RefCell},
        convert::TryInto,
        fmt::{self, Display},
    },
    fehler::{throw, throws},
    log::{error, trace},
    market::{Consumer as _, Failure as _, Producer as _},
    std::{
        process::{self, Command, ExitStatus},
        rc::Rc,
        thread::{self, JoinHandle},
    },
};

/// The languages supported by docuglot.
#[derive(Clone, Copy, Debug, enum_map::Enum, parse_display::Display, PartialEq)]
#[display(style = "lowercase")]
pub enum Language {
    /// Rust.
    Rust,
    /// Plain text.
    Plaintext,
}

/// Manages all of the `Translator`s.
#[derive(Debug)]
pub struct Tongue {
    /// The thread of Tongue.
    thread: JoinHandle<()>,
    /// Triggers the Tongue thread to join.
    joiner: market::sync::Trigger,
    /// Produces statements to be sent to the Translators.
    transmission_channel: market::channel::Channel<market::channel::Crossbeam<ClientStatement>>,
    /// Consumes statements received from the Translators.
    reception_channel: market::channel::Channel<market::channel::Crossbeam<ServerStatement>>,
    /// The statuses of the Translators.
    status_consumer: market::channel::CrossbeamConsumer<ExitStatus>,
}

impl Tongue {
    /// Creates a new `Tongue`.
    #[inline]
    #[throws(market::TakenParticipant)]
    pub fn new(root_dir: &lsp_types::Url) -> Self {
        let dir = root_dir.clone();
        let mut lock = market::sync::Lock::new();
        let mut transmission_channel =
            market::channel::Channel::new(market::channel::Size::Infinite);
        let mut reception_channel = market::channel::Channel::new(market::channel::Size::Infinite);
        let mut status_channel =
            market::channel::Channel::<market::channel::Crossbeam<ExitStatus>>::new(
                market::channel::Size::Infinite,
            );
        let hammer = lock.hammer()?;
        let transmission_consumer = transmission_channel.consumer()?;
        let reception_producer = reception_channel.producer()?;
        let status_producer = status_channel.producer()?;

        Self {
            joiner: lock.trigger()?,
            thread: thread::spawn(move || {
                if let Err(error) = Self::thread(
                    &dir,
                    &hammer,
                    &transmission_consumer,
                    &reception_producer,
                    &status_producer,
                ) {
                    error!("tongue thread error: {}", error);
                }
            }),
            transmission_channel,
            reception_channel,
            status_consumer: status_channel.consumer()?,
        }
    }

    /// Returns the consumer that consumes [`ServerStatement`]s.
    #[inline]
    #[throws(market::TakenParticipant)]
    pub fn consumer(&mut self) -> market::channel::CrossbeamConsumer<ServerStatement> {
        self.reception_channel.consumer()?
    }

    /// Returns the producer that produces [`ClientStatement`]s.
    #[inline]
    #[throws(market::TakenParticipant)]
    pub fn producer(&mut self) -> market::channel::CrossbeamProducer<ClientStatement> {
        self.transmission_channel.producer()?
    }

    /// The main thread of a Tongue.
    #[throws(TranslationError)]
    fn thread(
        root_dir: &lsp_types::Url,
        hammer: &market::sync::Hammer,
        transmission_consumer: &market::channel::CrossbeamConsumer<ClientStatement>,
        reception_producer: &market::channel::CrossbeamProducer<ServerStatement>,
        status_producer: &market::channel::CrossbeamProducer<ExitStatus>,
    ) {
        let rust_translator = Rc::new(RefCell::new(Translator::new(
            Client::new(Command::new("rust-analyzer"))?,
            root_dir.clone(),
        )));
        // TODO: Currently plaintext_translator is a hack to deal with all files that do not have a known language. Ideally, this would run its own language server.
        let plaintext_translator = Rc::new(RefCell::new(Translator::new(
            Client::new(Command::new("echo"))?,
            root_dir.clone(),
        )));
        plaintext_translator.borrow_mut().state = State::WaitingExit;
        let translators = enum_map::enum_map! {
            Language::Rust => Rc::clone(&rust_translator),
            Language::Plaintext => Rc::clone(&plaintext_translator),
        };

        while !translators
            .values()
            .map(|t| t.borrow().state == State::WaitingExit)
            .all(|x| x)
        {
            let will_shutdown = hammer.consume().is_ok();

            for transmission in transmission_consumer.consume_all()? {
                #[allow(clippy::indexing_slicing)]
                // translators is an EnumMap so index will not panic.
                translators[transmission.language()]
                    .borrow_mut()
                    .send_message(transmission.into())?;
            }

            for (_, translator) in &translators {
                if let Some(input) = translator.borrow_mut().translate()? {
                    reception_producer.produce(input)?;
                }

                translator.borrow().log_errors();

                if will_shutdown {
                    translator.borrow_mut().shutdown()?;
                }
            }
        }

        for (_, translator) in translators {
            status_producer.produce(translator.borrow().waiter().demand()?)?;
        }
    }

    /// Joins the thread.
    #[inline]
    #[throws(market::ProduceFailure<market::channel::DisconnectedFault>)]
    pub fn join(&self) {
        self.joiner.produce(())?;

        // TODO: This appears to cause an error currently.
        //for _ in 0..2 {
        //    self.status_consumer.consume().expect("Failed to finish translator");
        //}
    }
}

/// A statement from the server.
#[derive(Clone, Copy, Debug, parse_display::Display)]
#[display(style = "CamelCase")]
pub enum ServerStatement {
    /// The server exited.
    Exit,
}

/// A statement from the client.
#[derive(Debug, parse_display::Display)]
#[display("")]
pub enum ClientStatement {
    /// The tool opened `doc`.
    OpenDoc {
        /// The document that was opened.
        doc: lsp_types::TextDocumentItem,
    },
    /// The tool closed `doc`.
    CloseDoc {
        /// The document that was closed.
        doc: lsp_types::TextDocumentIdentifier,
    },
}

impl ClientStatement {
    /// Creates a `didOpen` `ClientStatement`.
    #[inline]
    #[must_use]
    pub const fn open_doc(doc: lsp_types::TextDocumentItem) -> Self {
        Self::OpenDoc { doc }
    }

    /// Creates a `didClose` `ClientStatement`.
    #[inline]
    #[must_use]
    pub const fn close_doc(doc: lsp_types::TextDocumentIdentifier) -> Self {
        Self::CloseDoc { doc }
    }

    /// Returns the language of `self`.
    #[allow(clippy::unused_self)] // Will require self in the future.
    const fn language(&self) -> Language {
        Language::Rust
    }
}

impl From<ClientStatement> for ClientMessage {
    #[inline]
    fn from(value: ClientStatement) -> Self {
        match value {
            ClientStatement::OpenDoc { doc } => Self::Notification(ClientNotification::OpenDoc(
                lsp_types::DidOpenTextDocumentParams { text_document: doc },
            )),
            ClientStatement::CloseDoc { doc } => Self::Notification(ClientNotification::CloseDoc(
                lsp_types::DidCloseTextDocumentParams { text_document: doc },
            )),
        }
    }
}

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

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

impl conventus::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)
    }
}

/// An error during translation.
#[derive(Debug, thiserror::Error)]
pub enum TranslationError {
    /// Failure while transmitting a client message.
    #[error(transparent)]
    Transmission(#[from] market::ProduceFailure<market::io::WriteError<lsp::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),
    /// Failure while collecting outputs.
    #[error(transparent)]
    CollectOutputs(#[from] market::channel::DisconnectedFault),
    /// Attempted to process an event in an invalid state.
    #[error("Invalid state: Cannot {0} while {1}")]
    InvalidState(Box<Event>, State),
    /// Failed to store output.
    #[error(transparent)]
    Storage(#[from] market::ProduceFailure<market::channel::DisconnectedFault>),
}

/// Describes events that the client must process.
#[derive(Debug, parse_display::Display, PartialEq)]
pub enum Event {
    /// The tool wants to send a message to the server.
    #[display("send message")]
    SendMessage(ClientMessage),
    /// THe server has completed initialization.
    #[display("process initialization")]
    Initialized(lsp_types::InitializeResult),
    /// The server has registered capabilities with the client.
    #[display("register capability")]
    RegisterCapability(json_rpc::Id, lsp_types::RegistrationParams),
    /// The server has completed shutdown.
    #[display("complete shutdown")]
    CompletedShutdown,
    /// The tool wants to kill the server.
    #[display("exit")]
    Exit,
}

/// 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: lsp_types::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<lsp_types::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,
}

/// Manages the client of a language server.
pub(crate) struct Translator {
    /// The client.
    client: Client,
    /// The state.
    state: State,
}

impl Translator {
    /// Creates a new `Translator`.
    const fn new(client: Client, root_dir: lsp_types::Url) -> Self {
        Self {
            client,
            state: State::Uninitialized { root_dir },
        }
    }

    /// Sends `message` to the server.
    ///
    /// If not done immediately, the client will send the message as soon as possible.
    #[throws(TranslationError)]
    fn send_message(&mut self, message: ClientMessage) {
        self.process(Event::SendMessage(message))?
    }

    /// Translates the input consumed by the client to a `ServerStatement`.
    #[throws(TranslationError)]
    fn translate(&mut self) -> Option<ServerStatement> {
        match self.client.consume() {
            Ok(message) => {
                match message {
                    lsp::ServerMessage::Request { id, request } => match request {
                        lsp::ServerRequest::RegisterCapability(registration) => {
                            self.process(Event::RegisterCapability(id, registration))?;
                        }
                    },
                    lsp::ServerMessage::Response(response) => match response {
                        lsp::ServerResponse::Initialize(initialize) => {
                            self.process(Event::Initialized(initialize))?;
                        }
                        lsp::ServerResponse::Shutdown => {
                            self.process(Event::CompletedShutdown)?;
                        }
                    },
                    lsp::ServerMessage::Notification(notification) => match notification {
                        lsp::ServerNotification::PublishDiagnostics(_diagnostics) => {
                            // TODO: Send diagnostics to tool.
                        }
                    },
                }
            }
            Err(failure) => {
                if let market::ConsumeFailure::Fault(fault) = failure {
                    throw!(TranslationError::from(fault));
                }
            }
        }

        None
    }

    /// Processes `event`.
    #[throws(TranslationError)]
    fn process(&mut self, event: Event) {
        match self.state {
            State::Uninitialized { ref root_dir } => match event {
                Event::SendMessage(message) => {
                    self.client.initialize(root_dir)?;
                    self.state = State::WaitingInitialization {
                        messages: vec![message],
                    }
                }
                Event::Initialized(_)
                | Event::CompletedShutdown
                | Event::RegisterCapability(..) => {
                    throw!(TranslationError::InvalidState(
                        Box::new(event),
                        self.state.clone()
                    ));
                }
                Event::Exit => {
                    self.client
                        .produce(ClientMessage::Notification(ClientNotification::Exit))?;
                    self.state = State::WaitingExit
                }
            },
            State::WaitingInitialization { ref messages } => match event {
                Event::SendMessage(message) => {
                    let mut new_messages = messages.clone();
                    new_messages.push(message);
                    self.state = State::WaitingInitialization {
                        messages: new_messages,
                    }
                }
                Event::Initialized(server_state) => {
                    self.client
                        .produce(ClientMessage::Notification(ClientNotification::Initialized))?;

                    for message in messages {
                        self.client.produce(message.clone())?;
                    }

                    self.state = State::Running {
                        server_state: Box::new(server_state),
                        registrations: Vec::new(),
                    }
                }
                Event::CompletedShutdown | Event::RegisterCapability(..) => {
                    throw!(TranslationError::InvalidState(
                        Box::new(event),
                        self.state.clone()
                    ));
                }
                Event::Exit => {
                    // TODO: Figure out how to handle this case.
                }
            },
            State::Running {
                ref server_state,
                ref registrations,
            } => match event {
                Event::SendMessage(message) => {
                    self.client.produce(message)?;
                }
                Event::RegisterCapability(id, mut register) => {
                    let mut new_registrations = registrations.clone();
                    new_registrations.append(&mut register.registrations);
                    self.state = State::Running {
                        server_state: server_state.clone(),
                        registrations: new_registrations,
                    };
                    self.client.produce(ClientMessage::Response {
                        id,
                        response: ClientResponse::RegisterCapability,
                    })?;
                }
                Event::Initialized(_) | Event::CompletedShutdown => {
                    throw!(TranslationError::InvalidState(
                        Box::new(event),
                        self.state.clone()
                    ));
                }
                Event::Exit => {
                    self.client
                        .produce(ClientMessage::Request(ClientRequest::Shutdown))?;
                    self.state = State::WaitingShutdown;
                }
            },
            State::WaitingShutdown => match event {
                Event::SendMessage(_)
                | Event::Initialized(_)
                | Event::Exit
                | Event::RegisterCapability(..) => {
                    throw!(TranslationError::InvalidState(
                        Box::new(event),
                        self.state.clone()
                    ));
                }
                Event::CompletedShutdown => {
                    self.client
                        .produce(ClientMessage::Notification(ClientNotification::Exit))?;
                    self.state = State::WaitingExit;
                }
            },
            State::WaitingExit => self.while_waiting_exit(event)?,
        }
    }

    /// Processes `event` while in [`State::WaitingExit`].
    #[throws(TranslationError)]
    fn while_waiting_exit(&self, event: Event) {
        if event != Event::Exit {
            throw!(TranslationError::InvalidState(
                Box::new(event),
                self.state.clone(),
            ));
        }
    }

    /// Logs all messages that have currently been received on stderr.
    fn log_errors(&self) {
        match self.client.stderr().consume_all() {
            Ok(messages) => {
                for message in messages {
                    error!("lsp stderr: {}", message);
                }
            }
            Err(error) => {
                error!("error logger: {}", error);
            }
        }
    }

    /// Shuts down the client.
    #[throws(TranslationError)]
    fn shutdown(&mut self) {
        self.process(Event::Exit)?;
    }

    /// The client's `Waiter`.
    const fn waiter(&self) -> &market::process::Waiter<lsp::Message, lsp::Message, ErrorMessage> {
        self.client.waiter()
    }
}

/// A client to a language server.
pub(crate) struct Client {
    /// The server.
    server: market::process::Process<lsp::Message, lsp::Message, ErrorMessage>,
    /// The `Id` of the next request.
    next_id: Cell<u64>,
}

impl Client {
    /// Creates a new [`Client`] for `language`.
    #[throws(CreateClientError)]
    fn new(command: Command) -> Self {
        Self {
            server: market::process::Process::new(command)?,
            next_id: Cell::new(1),
        }
    }

    /// Sends an initialize request to the server.
    #[throws(TranslationError)]
    fn initialize(&self, root_dir: &lsp_types::Url) {
        #[allow(deprecated)] // InitializeParams.root_path is required.
        self.produce(ClientMessage::Request(ClientRequest::Initialize(
            lsp_types::InitializeParams {
                process_id: Some(u64::from(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(lsp_types::SynchronizationCapability {
                            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: 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,
                    }),
                    window: None,
                    experimental: None,
                },
                trace: None,
                workspace_folders: None,
                client_info: None,
            },
        )))?;
    }

    /// The server's `Waiter`.
    const fn waiter(&self) -> &market::process::Waiter<lsp::Message, lsp::Message, ErrorMessage> {
        self.server.waiter()
    }

    /// The server's stderr.
    const fn stderr(&self) -> &Rc<market::io::Reader<ErrorMessage>> {
        self.server.stderr()
    }

    /// Returns the `Id` of the next request sent by `self`.
    fn next_id(&self) -> json_rpc::Id {
        let id = self.next_id.get();
        self.next_id.set(id.wrapping_add(1));
        json_rpc::Id::Num(serde_json::Number::from(id))
    }
}

impl market::Consumer for Client {
    type Good = lsp::ServerMessage;
    type Failure = market::ConsumeFailure<ConsumeServerMessageError>;

    #[throws(Self::Failure)]
    fn consume(&self) -> Self::Good {
        let good = self
            .server
            .consume()
            .map_err(market::ConsumeFailure::map_from)?
            .try_into()
            .map_err(|failure| {
                market::ConsumeFailure::Fault(market::Fault::<Self::Failure>::from(failure))
            })?;
        trace!("LSP Rx: {}", good);
        good
    }
}

impl market::Producer for Client {
    type Good = ClientMessage;
    type Failure = market::ProduceFailure<market::io::WriteError<lsp::Message>>;

    #[throws(Self::Failure)]
    fn produce(&self, good: Self::Good) {
        trace!("LSP Tx: {}", good);
        let message = lsp::Message::from(match good {
            ClientMessage::Response { id, response } => json_rpc::Object::response(id, &response),
            ClientMessage::Request(request) => json_rpc::Object::request(self.next_id(), &request),
            ClientMessage::Notification(notification) => {
                json_rpc::Object::notification(&notification)
            }
        });

        self.server
            .produce(message)
            .map_err(market::ProduceFailure::map_into)?
    }
}

/// A message to the language server.
#[derive(Clone, Debug, PartialEq)]
pub enum ClientMessage {
    /// A request.
    Request(ClientRequest),
    /// A response.
    Response {
        /// The id of the matching request.
        id: json_rpc::Id,
        /// The response.
        response: ClientResponse,
    },
    /// A notification.
    Notification(ClientNotification),
}

impl Display for ClientMessage {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}",
            match *self {
                Self::Request(ref request) => format!("{}: {}", "Request", request),
                Self::Response { ref response, .. } => format!("{}: {}", "Response", response),
                Self::Notification(ref notification) =>
                    format!("{}: {}", "Notification", notification),
            }
        )
    }
}

/// A request from the client.
#[derive(Clone, Debug, parse_display::Display, PartialEq)]
pub enum ClientRequest {
    /// The client is initializing the server.
    #[display("Initialize w/ {0:?}")]
    Initialize(lsp_types::InitializeParams),
    /// The client is shutting down the server.
    Shutdown,
}

impl json_rpc::Method for ClientRequest {
    fn method(&self) -> String {
        match *self {
            Self::Initialize(_) => "initialize",
            Self::Shutdown => "shutdown",
        }
        .to_string()
    }

    fn params(&self) -> json_rpc::Params {
        match *self {
            Self::Initialize(ref params) => {
                #[allow(clippy::expect_used)] // InitializeParams can be serialized to JSON.
                json_rpc::Params::from(
                    serde_json::to_value(params)
                        .expect("Converting InitializeParams to JSON Value"),
                )
            }
            Self::Shutdown => json_rpc::Params::None,
        }
    }
}

/// A notification from the client.
#[derive(Clone, Debug, parse_display::Display, PartialEq)]
pub enum ClientNotification {
    /// The client received the server's initialization response.
    Initialized,
    /// The client requests the server to exit.
    Exit,
    /// The client opened a document.
    #[display("OpenDoc w/ {0:?}")]
    OpenDoc(lsp_types::DidOpenTextDocumentParams),
    /// The client closed a document.
    #[display("CloseDoc w/ {0:?}")]
    CloseDoc(lsp_types::DidCloseTextDocumentParams),
}

impl json_rpc::Method for ClientNotification {
    fn method(&self) -> String {
        match *self {
            Self::Initialized => "initialized",
            Self::Exit => "exit",
            Self::OpenDoc(_) => "textDocument/didOpen",
            Self::CloseDoc(_) => "textDocument/didClose",
        }
        .to_string()
    }

    fn params(&self) -> json_rpc::Params {
        match *self {
            Self::Initialized | Self::Exit => json_rpc::Params::None,
            Self::OpenDoc(ref params) => {
                #[allow(clippy::expect_used)]
                // DidOpenTextDocumentParams can be serialized to JSON.
                json_rpc::Params::from(
                    serde_json::to_value(params)
                        .expect("Converting DidOpenTextDocumentParams to JSON Value"),
                )
            }
            Self::CloseDoc(ref params) => {
                #[allow(clippy::expect_used)]
                // DidCloseTextDocumentParams can be serialized to JSON.
                json_rpc::Params::from(
                    serde_json::to_value(params)
                        .expect("Converting DidCloseTextDocumentParams to JSON Value"),
                )
            }
        }
    }
}

/// A response from the client.
#[derive(Clone, Copy, Debug, parse_display::Display, PartialEq)]
pub enum ClientResponse {
    /// Confirms client registered capabilities.
    RegisterCapability,
}

impl json_rpc::Success for ClientResponse {
    fn result(&self) -> serde_json::Value {
        match *self {
            Self::RegisterCapability => serde_json::Value::Null,
        }
    }
}

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

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