Skip to main content

lsp_types_max/protocol/
mod.rs

1use crate::types::NumberOrString;
2use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
3
4/// A request message to describe a request between the client and the server.
5/// Every request starts with an internal id.
6#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
7pub struct RequestMessage {
8    /// The protocol version. Always "2.0"
9    pub jsonrpc: String,
10
11    /// The request id.
12    pub id: NumberOrString,
13
14    /// The method to be invoked.
15    pub method: String,
16
17    /// The method's params.
18    #[serde(skip_serializing_if = "Option::is_none")]
19    pub params: Option<serde_json::Value>,
20}
21
22/// A response message is sent as a result of a request.
23#[derive(Debug, PartialEq, Clone)]
24pub enum ResponseMessage {
25    Success {
26        /// The protocol version. Always "2.0"
27        jsonrpc: String,
28        /// The request id.
29        id: Option<NumberOrString>,
30        /// The result of a request.
31        result: serde_json::Value,
32    },
33    Error {
34        /// The protocol version. Always "2.0"
35        jsonrpc: String,
36        /// The request id.
37        id: Option<NumberOrString>,
38        /// The error object in case a request fails.
39        error: ResponseError,
40    },
41}
42
43impl Serialize for ResponseMessage {
44    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
45    where
46        S: Serializer,
47    {
48        use serde::ser::SerializeStruct;
49        let mut state = serializer.serialize_struct("ResponseMessage", 3)?;
50        match self {
51            ResponseMessage::Success {
52                jsonrpc,
53                id,
54                result,
55            } => {
56                state.serialize_field("jsonrpc", jsonrpc)?;
57                state.serialize_field("id", id)?;
58                state.serialize_field("result", result)?;
59            }
60            ResponseMessage::Error { jsonrpc, id, error } => {
61                state.serialize_field("jsonrpc", jsonrpc)?;
62                state.serialize_field("id", id)?;
63                state.serialize_field("error", error)?;
64            }
65        }
66        state.end()
67    }
68}
69
70impl<'de> Deserialize<'de> for ResponseMessage {
71    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
72    where
73        D: Deserializer<'de>,
74    {
75        let value = serde_json::Value::deserialize(deserializer)?;
76
77        let jsonrpc = value
78            .get("jsonrpc")
79            .and_then(|v| v.as_str())
80            .ok_or_else(|| de::Error::missing_field("jsonrpc"))?
81            .to_string();
82
83        let id_val = value
84            .get("id")
85            .ok_or_else(|| de::Error::missing_field("id"))?;
86        let id = if id_val.is_null() {
87            None
88        } else {
89            Some(serde_json::from_value(id_val.clone()).map_err(de::Error::custom)?)
90        };
91
92        let has_result = value.get("result").is_some();
93        let has_error = value.get("error").is_some();
94
95        if has_result && has_error {
96            return Err(de::Error::custom(
97                "ResponseMessage cannot contain both 'result' and 'error'",
98            ));
99        } else if !has_result && !has_error {
100            return Err(de::Error::custom(
101                "ResponseMessage must contain either 'result' or 'error'",
102            ));
103        }
104
105        if has_result {
106            let result = value.get("result").unwrap().clone();
107            Ok(ResponseMessage::Success {
108                jsonrpc,
109                id,
110                result,
111            })
112        } else {
113            let error = serde_json::from_value(value.get("error").unwrap().clone())
114                .map_err(de::Error::custom)?;
115            Ok(ResponseMessage::Error { jsonrpc, id, error })
116        }
117    }
118}
119
120/// A NotificationMessage works like an event and does not send a response back.
121#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
122pub struct NotificationMessage {
123    /// The protocol version. Always "2.0"
124    pub jsonrpc: String,
125
126    /// The method to be invoked.
127    pub method: String,
128
129    /// The notification's params.
130    #[serde(skip_serializing_if = "Option::is_none")]
131    pub params: Option<serde_json::Value>,
132}
133
134/// The error object in case a request fails.
135#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
136pub struct ResponseError {
137    /// A number indicating the error type that occurred.
138    pub code: i32,
139
140    /// A string providing a short description of the error.
141    pub message: String,
142
143    /// A primitive or structured value that contains additional
144    /// information about the error. Can be omitted.
145    #[serde(skip_serializing_if = "Option::is_none")]
146    pub data: Option<serde_json::Value>,
147}