-
Notifications
You must be signed in to change notification settings - Fork 178
Expand file tree
/
Copy pathnative_bridge.rs
More file actions
342 lines (296 loc) · 12.6 KB
/
native_bridge.rs
File metadata and controls
342 lines (296 loc) · 12.6 KB
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
use std::sync::mpsc::{Receiver, Sender};
use std::sync::{Arc, Mutex};
use clarity_lsp::backend::{
process_mutating_request, process_notification, process_request, EditorStateInput,
LspNotification, LspNotificationResponse, LspRequest, LspRequestResponse,
};
use clarity_lsp::lsp_types::{
DocumentSymbolParams, DocumentSymbolResponse, GotoDefinitionParams, GotoDefinitionResponse,
SignatureHelp, SignatureHelpParams,
};
use clarity_lsp::state::EditorState;
use crossbeam_channel::{Receiver as MultiplexableReceiver, Select, Sender as MultiplexableSender};
use serde_json::Value;
use tower_lsp_server::jsonrpc::{Error, ErrorCode, Result};
use tower_lsp_server::lsp_types::{
CompletionParams, CompletionResponse, DidChangeTextDocumentParams, DidCloseTextDocumentParams,
DidOpenTextDocumentParams, DidSaveTextDocumentParams, DocumentFormattingParams,
DocumentRangeFormattingParams, ExecuteCommandParams, Hover, HoverParams, InitializeParams,
InitializeResult, InitializedParams, MessageType, TextEdit,
};
use tower_lsp_server::{Client, LanguageServer};
use super::utils;
use crate::lsp::clarity_diagnostics_to_tower_lsp_type;
pub enum LspResponse {
Notification(LspNotificationResponse),
Request(LspRequestResponse),
}
pub async fn start_language_server(
notification_rx: MultiplexableReceiver<LspNotification>,
request_rx: MultiplexableReceiver<LspRequest>,
response_tx: Sender<LspResponse>,
) {
let mut editor_state = EditorStateInput::Owned(EditorState::new());
let mut sel = Select::new();
let notifications_oper = sel.recv(¬ification_rx);
let requests_oper = sel.recv(&request_rx);
loop {
let oper = sel.select();
match oper.index() {
i if i == notifications_oper => match oper.recv(¬ification_rx) {
Ok(notification) => {
let result = process_notification(notification, &mut editor_state, None).await;
if let Ok(response) = result {
let _ = response_tx.send(LspResponse::Notification(response));
}
}
Err(_e) => {
continue;
}
},
i if i == requests_oper => match oper.recv(&request_rx) {
Ok(request) => {
let request_result = match request {
LspRequest::Initialize(_) => {
process_mutating_request(request, &mut editor_state)
}
_ => process_request(request, &editor_state),
};
if let Ok(response) = request_result {
let _ = response_tx.send(LspResponse::Request(response));
}
}
Err(_e) => {
continue;
}
},
_ => unreachable!(),
}
}
}
#[derive(Debug)]
pub struct LspNativeBridge {
client: Client,
notification_tx: Arc<Mutex<MultiplexableSender<LspNotification>>>,
request_tx: Arc<Mutex<MultiplexableSender<LspRequest>>>,
response_rx: Arc<Mutex<Receiver<LspResponse>>>,
}
impl LspNativeBridge {
pub fn new(
client: Client,
notification_tx: MultiplexableSender<LspNotification>,
request_tx: MultiplexableSender<LspRequest>,
response_rx: Receiver<LspResponse>,
) -> Self {
Self {
client,
notification_tx: Arc::new(Mutex::new(notification_tx)),
request_tx: Arc::new(Mutex::new(request_tx)),
response_rx: Arc::new(Mutex::new(response_rx)),
}
}
// Call after receiving `LspNotification` message
async fn after_receive_lsp_notification(&self) {
let mut aggregated_diagnostics = vec![];
let mut notification = None;
if let Ok(response_rx) = self.response_rx.lock() {
if let Ok(LspResponse::Notification(ref mut notification_response)) = response_rx.recv()
{
aggregated_diagnostics.append(&mut notification_response.aggregated_diagnostics);
notification = notification_response.notification.take();
}
}
for (location, diags) in aggregated_diagnostics {
if let Ok(url) = location.to_url_string() {
self.client
.publish_diagnostics(
url.parse().expect("Failed to parse URL"),
clarity_diagnostics_to_tower_lsp_type(&diags),
None,
)
.await;
}
}
if let Some((level, message)) = notification {
self.client.show_message(level, message).await;
}
}
}
impl LanguageServer for LspNativeBridge {
async fn initialize(&self, params: InitializeParams) -> Result<InitializeResult> {
let _ = match self.request_tx.lock() {
Ok(tx) => tx.send(LspRequest::Initialize(Box::new(params))),
Err(_) => return Err(Error::new(ErrorCode::InternalError)),
};
let response_rx = self.response_rx.lock().expect("failed to lock response_rx");
let response = &response_rx.recv().expect("failed to get value from recv");
if let LspResponse::Request(LspRequestResponse::Initialize(initialize)) = response {
return Ok(*initialize.to_owned());
}
Err(Error::new(ErrorCode::InternalError))
}
async fn initialized(&self, _params: InitializedParams) {}
async fn shutdown(&self) -> Result<()> {
Ok(())
}
async fn execute_command(&self, _: ExecuteCommandParams) -> Result<Option<Value>> {
Ok(None)
}
async fn completion(&self, params: CompletionParams) -> Result<Option<CompletionResponse>> {
let _ = match self.request_tx.lock() {
Ok(tx) => tx.send(LspRequest::Completion(params)),
Err(_) => return Ok(None),
};
let response_rx = self.response_rx.lock().expect("failed to lock response_rx");
let response = &response_rx.recv().expect("failed to get value from recv");
if let LspResponse::Request(LspRequestResponse::CompletionItems(items)) = response {
return Ok(Some(CompletionResponse::from(items.to_vec())));
}
Ok(None)
}
async fn goto_definition(
&self,
params: GotoDefinitionParams,
) -> Result<Option<GotoDefinitionResponse>> {
let _ = match self.request_tx.lock() {
Ok(tx) => tx.send(LspRequest::Definition(params)),
Err(_) => return Ok(None),
};
let response_rx = self.response_rx.lock().expect("failed to lock response_rx");
let response = &response_rx.recv().expect("failed to get value from recv");
if let LspResponse::Request(LspRequestResponse::Definition(Some(data))) = response {
return Ok(Some(GotoDefinitionResponse::Scalar(data.to_owned())));
}
Ok(None)
}
async fn document_symbol(
&self,
params: DocumentSymbolParams,
) -> Result<Option<DocumentSymbolResponse>> {
let _ = match self.request_tx.lock() {
Ok(tx) => tx.send(LspRequest::DocumentSymbol(params)),
Err(_) => return Ok(None),
};
let response_rx = self.response_rx.lock().expect("failed to lock response_rx");
let response = &response_rx.recv().expect("failed to get value from recv");
if let LspResponse::Request(LspRequestResponse::DocumentSymbol(symbols)) = response {
return Ok(Some(DocumentSymbolResponse::Nested(symbols.to_vec())));
}
Ok(None)
}
async fn hover(&self, params: HoverParams) -> Result<Option<Hover>> {
let _ = match self.request_tx.lock() {
Ok(tx) => tx.send(LspRequest::Hover(params)),
Err(_) => return Ok(None),
};
let response_rx = self.response_rx.lock().expect("failed to lock response_rx");
let response = &response_rx.recv().expect("failed to get value from recv");
if let LspResponse::Request(LspRequestResponse::Hover(data)) = response {
return Ok(data.to_owned());
}
Ok(None)
}
async fn signature_help(&self, params: SignatureHelpParams) -> Result<Option<SignatureHelp>> {
let _ = match self.request_tx.lock() {
Ok(tx) => tx.send(LspRequest::SignatureHelp(params)),
Err(_) => return Ok(None),
};
let response_rx = self.response_rx.lock().expect("failed to lock response_rx");
let response = &response_rx.recv().expect("failed to get value from recv");
if let LspResponse::Request(LspRequestResponse::SignatureHelp(data)) = response {
return Ok(data.to_owned());
}
Ok(None)
}
async fn formatting(&self, params: DocumentFormattingParams) -> Result<Option<Vec<TextEdit>>> {
let _ = match self.request_tx.lock() {
Ok(tx) => tx.send(LspRequest::DocumentFormatting(params)),
Err(_) => return Ok(None),
};
let response_rx = self.response_rx.lock().expect("failed to lock response_rx");
let response = &response_rx.recv().expect("failed to get value from recv");
if let LspResponse::Request(LspRequestResponse::DocumentFormatting(data)) = response {
return Ok(data.to_owned());
}
Ok(None)
}
async fn range_formatting(
&self,
params: DocumentRangeFormattingParams,
) -> Result<Option<Vec<TextEdit>>> {
let _ = match self.request_tx.lock() {
Ok(tx) => tx.send(LspRequest::DocumentRangeFormatting(params)),
Err(_) => return Ok(None),
};
let response_rx = self.response_rx.lock().expect("failed to lock response_rx");
let response = &response_rx.recv().expect("failed to get value from recv");
if let LspResponse::Request(LspRequestResponse::DocumentRangeFormatting(data)) = response {
return Ok(data.to_owned());
}
Ok(None)
}
async fn did_open(&self, params: DidOpenTextDocumentParams) {
if let Some(contract_location) = utils::get_contract_location(¶ms.text_document.uri) {
let _ = match self.notification_tx.lock() {
Ok(tx) => tx.send(LspNotification::ContractOpened(contract_location)),
Err(_) => return,
};
} else if let Some(manifest_location) =
utils::get_manifest_location(¶ms.text_document.uri)
{
let _ = match self.notification_tx.lock() {
Ok(tx) => tx.send(LspNotification::ManifestOpened(manifest_location)),
Err(_) => return,
};
} else {
self.client
.log_message(MessageType::WARNING, "Unsupported file opened")
.await;
return;
};
self.client
.log_message(
MessageType::WARNING,
"Command submitted to background thread",
)
.await;
self.after_receive_lsp_notification().await;
}
async fn did_save(&self, params: DidSaveTextDocumentParams) {
if let Some(contract_location) = utils::get_contract_location(¶ms.text_document.uri) {
let _ = match self.notification_tx.lock() {
Ok(tx) => tx.send(LspNotification::ContractSaved(contract_location)),
Err(_) => return,
};
} else if let Some(manifest_location) =
utils::get_manifest_location(¶ms.text_document.uri)
{
let _ = match self.notification_tx.lock() {
Ok(tx) => tx.send(LspNotification::ManifestSaved(manifest_location)),
Err(_) => return,
};
} else {
return;
};
self.after_receive_lsp_notification().await;
}
async fn did_change(&self, params: DidChangeTextDocumentParams) {
if let Some(contract_location) = utils::get_contract_location(¶ms.text_document.uri) {
if let Ok(tx) = self.notification_tx.lock() {
let _ = tx.send(LspNotification::ContractChanged(
contract_location,
params.content_changes[0].text.to_string(),
));
};
}
self.after_receive_lsp_notification().await;
}
async fn did_close(&self, params: DidCloseTextDocumentParams) {
if let Some(contract_location) = utils::get_contract_location(¶ms.text_document.uri) {
if let Ok(tx) = self.notification_tx.lock() {
let _ = tx.send(LspNotification::ContractClosed(contract_location));
};
}
self.after_receive_lsp_notification().await;
}
}