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
use std::fmt::Display;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use futures::sync::mpsc::Sender;
use futures::{Future, Sink};
use jsonrpc_core::types::{request, Id, Version};
use log::{error, trace};
use lsp_types::notification::{Notification, *};
use lsp_types::request::{ApplyWorkspaceEdit, RegisterCapability, Request, UnregisterCapability};
use lsp_types::*;
use serde::Serialize;
use serde_json::Value;
#[derive(Debug)]
pub struct Printer {
buffer: Sender<String>,
initialized: Arc<AtomicBool>,
request_id: AtomicU64,
}
impl Printer {
pub(super) const fn new(buffer: Sender<String>, initialized: Arc<AtomicBool>) -> Self {
Printer {
buffer,
initialized,
request_id: AtomicU64::new(0),
}
}
pub fn log_message<M: Display>(&self, typ: MessageType, message: M) {
self.send_message(make_notification::<LogMessage>(LogMessageParams {
typ,
message: message.to_string(),
}));
}
pub fn show_message<M: Display>(&self, typ: MessageType, message: M) {
self.send_message(make_notification::<ShowMessage>(ShowMessageParams {
typ,
message: message.to_string(),
}));
}
pub fn telemetry_event<S: Serialize>(&self, data: S) {
match serde_json::to_value(data) {
Err(e) => error!("invalid JSON in `telemetry/event` notification: {}", e),
Ok(value) => {
if !value.is_null() && !value.is_array() && !value.is_object() {
let value = Value::Array(vec![value]);
self.send_message(make_notification::<TelemetryEvent>(value));
} else {
self.send_message(make_notification::<TelemetryEvent>(value));
}
}
}
}
pub fn register_capability(&self, registrations: Vec<Registration>) {
let id = self.request_id.fetch_add(1, Ordering::SeqCst);
self.send_message_initialized(make_request::<RegisterCapability>(
id,
RegistrationParams { registrations },
))
}
pub fn unregister_capability(&self, unregisterations: Vec<Unregistration>) {
let id = self.request_id.fetch_add(1, Ordering::SeqCst);
self.send_message_initialized(make_request::<UnregisterCapability>(
id,
UnregistrationParams { unregisterations },
))
}
pub fn apply_edit(&self, edit: WorkspaceEdit) -> bool {
let id = self.request_id.fetch_add(1, Ordering::SeqCst);
self.send_message_initialized(make_request::<ApplyWorkspaceEdit>(
id,
ApplyWorkspaceEditParams { edit },
));
true
}
pub fn publish_diagnostics(&self, uri: Url, diagnostics: Vec<Diagnostic>) {
self.send_message_initialized(make_notification::<PublishDiagnostics>(
PublishDiagnosticsParams::new(uri, diagnostics),
));
}
fn send_message(&self, message: String) {
tokio_executor::spawn(
self.buffer
.clone()
.send(message)
.map(|_| ())
.map_err(|_| error!("failed to send message")),
);
}
fn send_message_initialized(&self, message: String) {
if self.initialized.load(Ordering::SeqCst) {
self.send_message(message)
} else {
trace!("server not initialized, supressing message: {}", message);
}
}
}
fn make_request<N>(id: u64, params: N::Params) -> String
where
N: Request,
N::Params: Serialize,
{
let output = serde_json::to_string(¶ms).unwrap();
let params = serde_json::from_str(&output).unwrap();
serde_json::to_string(&request::MethodCall {
jsonrpc: Some(Version::V2),
id: Id::Num(id),
method: N::METHOD.to_owned(),
params,
})
.unwrap()
}
fn make_notification<N>(params: N::Params) -> String
where
N: Notification,
N::Params: Serialize,
{
let output = serde_json::to_string(¶ms).unwrap();
let params = serde_json::from_str(&output).unwrap();
serde_json::to_string(&request::Notification {
jsonrpc: Some(Version::V2),
method: N::METHOD.to_owned(),
params,
})
.unwrap()
}
#[cfg(test)]
mod tests {
use futures::{future, sync::mpsc, Stream};
use serde_json::json;
use tokio::runtime::current_thread;
use super::*;
fn assert_printer_messages<F: FnOnce(Printer)>(f: F, expected: String) {
let (tx, rx) = mpsc::channel(1);
let printer = Printer::new(tx, Arc::new(AtomicBool::new(true)));
current_thread::block_on_all(
future::lazy(move || {
f(printer);
rx.collect()
})
.and_then(move |messages| {
assert_eq!(messages, vec![expected]);
Ok(())
}),
)
.unwrap();
}
#[test]
fn log_message() {
let (typ, message) = (MessageType::Log, "foo bar".to_owned());
let expected = make_notification::<LogMessage>(LogMessageParams {
typ,
message: message.clone(),
});
assert_printer_messages(|p| p.log_message(typ, message), expected);
}
#[test]
fn show_message() {
let (typ, message) = (MessageType::Log, "foo bar".to_owned());
let expected = make_notification::<ShowMessage>(ShowMessageParams {
typ,
message: message.clone(),
});
assert_printer_messages(|p| p.show_message(typ, message), expected);
}
#[test]
fn telemetry_event() {
let null = json!(null);
let expected = make_notification::<TelemetryEvent>(null.clone());
assert_printer_messages(|p| p.telemetry_event(null), expected);
let array = json!([1, 2, 3]);
let expected = make_notification::<TelemetryEvent>(array.clone());
assert_printer_messages(|p| p.telemetry_event(array), expected);
let object = json!({});
let expected = make_notification::<TelemetryEvent>(object.clone());
assert_printer_messages(|p| p.telemetry_event(object), expected);
let anything_else = json!("hello");
let wrapped = Value::Array(vec![anything_else.clone()]);
let expected = make_notification::<TelemetryEvent>(wrapped);
assert_printer_messages(|p| p.telemetry_event(anything_else), expected);
}
#[test]
fn publish_diagnostics() {
let uri: Url = "file:///path/to/file".parse().unwrap();
let diagnostics = vec![Diagnostic::new_simple(Default::default(), "example".into())];
let params = PublishDiagnosticsParams::new(uri.clone(), diagnostics.clone());
let expected = make_notification::<PublishDiagnostics>(params);
assert_printer_messages(|p| p.publish_diagnostics(uri, diagnostics), expected);
}
}