use std::{
io,
time::{Duration, Instant},
};
use displaydoc::Display;
use gen_lsp_types::*;
use lsp_server::RequestId;
#[derive(thiserror::Error)]
#[error(transparent)]
pub struct Error(Box<ErrorKind>);
impl std::fmt::Debug for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self, f)
}
}
impl From<ErrorKind> for Error {
fn from(value: ErrorKind) -> Self {
Self(Box::new(value))
}
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Self {
ErrorKind::Io(err).into()
}
}
impl From<Error> for ErrorKind {
fn from(err: Error) -> Self {
*err.0
}
}
impl std::ops::Deref for Error {
type Target = ErrorKind;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Error {
pub fn kind(&self) -> &ErrorKind {
&self.0
}
}
#[derive(Display, thiserror::Error, Debug)]
pub enum ErrorKind {
Io(#[from] io::Error),
Spawn {
program: String,
#[source]
source: io::Error,
},
Disconnected { awaited: Awaited },
MalformedMessage {
awaited: Awaited,
#[source]
source: io::Error,
},
Response {
code: i32,
message: String,
method: LspRequestMethod<'static>,
id: RequestId,
data: Option<serde_json::Value>,
},
ResponseTimeout {
method: LspRequestMethod<'static>,
id: RequestId,
after_ms: u64,
},
NotificationTimeout {
method: LspNotificationMethod<'static>,
after_ms: u64,
},
AlreadyShutdown,
ExitTimeout { after_ms: u64 },
NotInitialized,
AlreadyInitialized,
UnmatchedResponseId { id: RequestId },
AlreadyOpen { uri: Uri },
NotOpen { uri: Uri },
InvalidEdit { index: usize, range: Range },
OverlappingEdits,
MalformedResponse {
method: LspRequestMethod<'static>,
message: String,
},
}
#[derive(Display, Debug, Clone, Copy, PartialEq, Eq)]
pub enum Awaited {
Response(LspRequestMethod<'static>),
Notification(LspNotificationMethod<'static>),
}
pub(crate) fn deadline_after(start: Instant, timeout: Duration) -> Instant {
const CAP: Duration = Duration::from_hours(100 * 365 * 24);
start + timeout.min(CAP)
}
pub(crate) fn elapsed_ms(start: Instant, now: Instant) -> u64 {
now.duration_since(start)
.as_millis()
.try_into()
.unwrap_or(u64::MAX)
}
pub type Result<T> = std::result::Result<T, Error>;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn debug_prints_the_message() {
let err: Error = ErrorKind::ExitTimeout { after_ms: 7 }.into();
assert_eq!(
format!("{err:?}"),
"timed out after 7ms waiting for the server process to exit"
);
}
#[test]
fn deadlines_cap_instead_of_overflowing() {
let start = Instant::now();
assert!(deadline_after(start, Duration::MAX) > start);
assert_eq!(
deadline_after(start, Duration::from_secs(1)),
start + Duration::from_secs(1)
);
}
}