summaryrefslogtreecommitdiff
path: root/support/texlab/src/dispatch.rs
blob: a08001648070b20ac862751b591aa5407b82ac64 (plain)
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
use anyhow::Result;
use log::warn;
use lsp_server::{ErrorCode, Notification, Request, RequestId, Response};
use serde::de::DeserializeOwned;

pub struct NotificationDispatcher {
    not: Option<Notification>,
}

impl NotificationDispatcher {
    pub fn new(not: Notification) -> Self {
        Self { not: Some(not) }
    }

    pub fn on<N, F>(mut self, handler: F) -> Result<Self>
    where
        N: lsp_types::notification::Notification,
        N::Params: DeserializeOwned,
        F: FnOnce(N::Params) -> Result<()>,
    {
        if let Some(not) = self.not {
            match not.extract::<N::Params>(N::METHOD) {
                Ok(params) => {
                    handler(params)?;
                    self.not = None;
                }
                Err(not) => {
                    self.not = Some(not);
                }
            };
        }
        Ok(self)
    }

    pub fn default(self) {
        if let Some(not) = &self.not {
            warn!("Unknown notification: {}", not.method);
        }
    }
}

pub struct RequestDispatcher {
    req: Option<Request>,
}

impl RequestDispatcher {
    pub fn new(req: Request) -> Self {
        Self { req: Some(req) }
    }

    pub fn on<R, F>(mut self, handler: F) -> Result<Self>
    where
        R: lsp_types::request::Request,
        R::Params: DeserializeOwned,
        F: FnOnce(RequestId, R::Params) -> Result<()>,
    {
        if let Some(req) = self.req {
            match req.extract::<R::Params>(R::METHOD) {
                Ok((id, params)) => {
                    handler(id, params)?;
                    self.req = None;
                }
                Err(req) => {
                    self.req = Some(req);
                }
            }
        }
        Ok(self)
    }

    pub fn default(self) -> Option<Response> {
        self.req.map(|req| {
            warn!("Unknown request: {}", req.method);
            Response::new_err(
                req.id,
                ErrorCode::MethodNotFound as i32,
                "method not found".to_string(),
            )
        })
    }
}