brack_language_server/
server.rs

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
use std::str::from_utf8;

use anyhow::{anyhow, Result};
use lsp_types::{ClientCapabilities, Diagnostic, Position, Range};
use serde_json::{from_str, json, Value};
use tokio::io::{stdin, stdout, AsyncReadExt, AsyncWriteExt};

pub struct LanguageServer {
    client_capabilities: ClientCapabilities,
}

impl LanguageServer {
    pub fn new() -> Self {
        Self {
            client_capabilities: ClientCapabilities::default(),
        }
    }

    async fn send_message(&self, msg: &str) -> Result<()> {
        let mut output = stdout();
        output
            .write_all(format!("Content-Length: {}\r\n\r\n{}", msg.len(), msg).as_bytes())
            .await?;
        output.flush().await?;
        Ok(())
    }

    async fn log_message(&self, message: &str) -> Result<()> {
        let response = json!({
            "jsonrpc": "2.0",
            "method": "window/logMessage",
            "params": {
                "type": 3,
                "message": message
            }
        })
        .to_string();
        self.send_message(&response).await
    }

    async fn send_error_response(&self, id: Option<i64>, code: i32, message: &str) -> Result<()> {
        let response = json!({
            "jsonrpc": "2.0",
            "id": id,
            "error": {
                "code": code,
                "message": message,
            }
        })
        .to_string();
        self.send_message(&response).await
    }

    async fn send_invalid_request_response(&self) -> Result<()> {
        self.send_error_response(None, -32600, "received an invalid request")
            .await
    }

    async fn send_method_not_found_response(&self, id: i64, method: &str) -> Result<()> {
        self.send_error_response(Some(id), -32601, &format!("{} is not supported", method))
            .await
    }

    #[allow(dead_code)]
    async fn send_parse_error_response(&self) -> Result<()> {
        self.send_error_response(None, -32700, "received an invalid JSON")
            .await
    }

    async fn send_publish_diagnostics(
        &self,
        uri: &str,
        diagnostics: &Vec<Diagnostic>,
    ) -> Result<()> {
        // check client_capabilities.text_document.publish_diagnostics
        if self
            .client_capabilities
            .text_document
            .as_ref()
            .and_then(|td| td.publish_diagnostics.as_ref())
            .is_none()
        {
            return Ok(());
        }

        let response = json!({
            "jsonrpc": "2.0",
            "method": "textDocument/publishDiagnostics",
            "params": {
                "uri": uri,
                "diagnostics": json!(diagnostics),
            }
        })
        .to_string();
        self.send_message(&response).await
    }

    async fn handle_request(&mut self, msg: &Value, id: i64, method: &str) -> Result<()> {
        match method {
            "initialize" => {
                self.log_message("Brack Language Server is initializing...")
                    .await?;
                self.client_capabilities = serde_json::from_value(
                    msg.get("params")
                        .ok_or_else(|| anyhow!("No params"))?
                        .get("capabilities")
                        .ok_or_else(|| anyhow!("No capabilities"))?
                        .clone(),
                )?;

                // for debugging
                // self.log_message(&format!(
                //     "Client capabilities : {:?}",
                //     self.client_capabilities
                // ))
                // .await?;

                let response = json!({
                    "jsonrpc": "2.0",
                    "id": id,
                    "result": { "capabilities": {
                        "textDocumentSync": 1,
                    } }
                })
                .to_string();
                self.send_message(&response).await
            }
            _ => self.send_method_not_found_response(id, method).await,
        }
    }

    async fn handle_response(&self, _: &Value, _: i64) -> Result<()> {
        Ok(())
    }

    async fn handle_notification_text_document_did_open(&self, msg: &Value) -> Result<()> {
        let text_document = msg
            .get("params")
            .ok_or_else(|| anyhow!("No params"))?
            .get("textDocument")
            .ok_or_else(|| anyhow!("No textDocument"))?;
        let uri = text_document
            .get("uri")
            .and_then(|uri| uri.as_str())
            .ok_or_else(|| anyhow!("No uri"))?;
        let _ = text_document
            .get("text")
            .and_then(|text| text.as_str())
            .ok_or_else(|| anyhow!("No text"))?;
        self.log_message(&format!("Did open {}", uri)).await?;

        Ok(())
    }

    async fn handle_notification_text_document_did_change(&self, msg: &Value) -> Result<()> {
        let uri = msg
            .get("params")
            .ok_or_else(|| anyhow!("No params"))?
            .get("textDocument")
            .ok_or_else(|| anyhow!("No textDocument"))?
            .get("uri")
            .and_then(|uri| uri.as_str())
            .ok_or_else(|| anyhow!("No uri"))?;
        let index = msg
            .get("params")
            .ok_or_else(|| anyhow!("No params"))?
            .get("contentChanges")
            .and_then(|content_changes| content_changes.as_array())
            .and_then(|content_changes| content_changes.len().checked_sub(1))
            .ok_or_else(|| anyhow!("No contentChanges"))?;
        let _ = msg
            .get("params")
            .ok_or_else(|| anyhow!("No params"))?
            .get("contentChanges")
            .and_then(|content_changes| content_changes.get(index))
            .and_then(|content_change| content_change.get("text"))
            .and_then(|text| text.as_str())
            .ok_or_else(|| anyhow!("No text"))?;
        self.log_message(&format!("Did change {}", uri)).await?;

        let diagnostics = vec![Diagnostic {
            range: Range {
                start: Position {
                    line: 0,
                    character: 0,
                },
                end: Position {
                    line: 0,
                    character: 3,
                },
            },
            message: "This is a test diagnostic message 2!".to_string(),
            ..Default::default()
        }];
        self.log_message(&format!("{:?}", diagnostics)).await?;
        self.send_publish_diagnostics(uri, &diagnostics).await
    }

    async fn handle_notification(&mut self, msg: &Value, method: &str) -> Result<()> {
        match method {
            "initialized" => {
                self.log_message("Brack Language Server has been initialized!")
                    .await?;
                Ok(())
            }
            "textDocument/didOpen" => self.handle_notification_text_document_did_open(msg).await,
            "textDocument/didChange" => {
                self.handle_notification_text_document_did_change(msg).await
            }
            _ => Ok(()),
        }
    }

    async fn dispatch(&mut self, msg: Value) -> Result<()> {
        match (
            msg.get("id").and_then(|i| i.as_i64()),
            msg.get("method").and_then(|m| m.as_str()),
        ) {
            (Some(id), Some(method)) => self.handle_request(&msg, id, method).await,
            (Some(id), None) => self.handle_response(&msg, id).await,
            (None, Some(method)) => self.handle_notification(&msg, method).await,
            _ => self.send_invalid_request_response().await,
        }
    }

    pub async fn run(&mut self) -> Result<()> {
        let mut stdin = stdin();
        let mut buffer = Vec::new();

        loop {
            let mut tmp_buffer = [0; 1024];

            let chunk = stdin.read(&mut tmp_buffer).await?;

            if chunk == 0 {
                break;
            }
            buffer.extend_from_slice(&tmp_buffer[..chunk]);

            let buffer_string = from_utf8(&buffer)?;
            if !buffer_string.contains("\r\n\r\n") {
                continue;
            }

            let splitted_buffer = buffer_string.split("\r\n\r\n").collect::<Vec<&str>>();
            let header_string = splitted_buffer[0];

            let mut content_length = -1;
            let header_length = header_string.len() + 4;
            for line in header_string.split("\r\n") {
                let splitted_line = line.split(": ").collect::<Vec<&str>>();
                let key = splitted_line[0];
                let value = splitted_line[1];
                if key == "Content-Length" {
                    content_length = value.parse::<i32>()?;
                }
            }

            if content_length == -1 {
                continue;
            }
            let total_length = header_length + content_length as usize;

            if buffer.len() < total_length {
                continue;
            }

            let msg: Value = from_str(&buffer_string[header_length..total_length])?;
            self.dispatch(msg).await?;
            buffer.drain(0..total_length);
        }

        Ok(())
    }
}