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
|
use std::{
cell::{Cell, RefCell},
fs,
path::PathBuf,
sync::Once,
time::Duration,
};
use crossbeam_channel::{after, Receiver};
use flexi_logger::Logger;
use gen_lsp_server::{RawMessage, RawNotification, RawRequest};
use languageserver_types::{
notification::DidOpenTextDocument,
request::{Request, Shutdown},
DidOpenTextDocumentParams, TextDocumentIdentifier, TextDocumentItem, Url,
};
use serde::Serialize;
use serde_json::{from_str, to_string_pretty, Value};
use tempdir::TempDir;
use ra_lsp_server::{
main_loop, req,
thread_watcher::{ThreadWatcher, Worker},
};
pub fn project(fixture: &str) -> Server {
static INIT: Once = Once::new();
INIT.call_once(|| Logger::with_env_or_str(crate::LOG).start().unwrap());
let tmp_dir = TempDir::new("test-project").unwrap();
let mut buf = String::new();
let mut file_name = None;
let mut paths = vec![];
macro_rules! flush {
() => {
if let Some(file_name) = file_name {
let path = tmp_dir.path().join(file_name);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path.as_path(), buf.as_bytes()).unwrap();
paths.push((path, buf.clone()));
}
};
};
for line in fixture.lines() {
if line.starts_with("//-") {
flush!();
buf.clear();
file_name = Some(line["//-".len()..].trim());
continue;
}
buf.push_str(line);
buf.push('\n');
}
flush!();
Server::new(tmp_dir, paths)
}
pub struct Server {
req_id: Cell<u64>,
messages: RefCell<Vec<RawMessage>>,
dir: TempDir,
worker: Option<Worker<RawMessage, RawMessage>>,
watcher: Option<ThreadWatcher>,
}
impl Server {
fn new(dir: TempDir, files: Vec<(PathBuf, String)>) -> Server {
let path = dir.path().to_path_buf();
let (worker, watcher) = Worker::<RawMessage, RawMessage>::spawn(
"test server",
128,
move |mut msg_receiver, mut msg_sender| {
main_loop(true, path, &mut msg_receiver, &mut msg_sender).unwrap()
},
);
let res = Server {
req_id: Cell::new(1),
dir,
messages: Default::default(),
worker: Some(worker),
watcher: Some(watcher),
};
for (path, text) in files {
res.send_notification(RawNotification::new::<DidOpenTextDocument>(
&DidOpenTextDocumentParams {
text_document: TextDocumentItem {
uri: Url::from_file_path(path).unwrap(),
language_id: "rust".to_string(),
version: 0,
text,
},
},
))
}
res
}
pub fn doc_id(&self, rel_path: &str) -> TextDocumentIdentifier {
let path = self.dir.path().join(rel_path);
TextDocumentIdentifier {
uri: Url::from_file_path(path).unwrap(),
}
}
pub fn request<R>(&self, params: R::Params, expected_resp: &str)
where
R: Request,
R::Params: Serialize,
{
let id = self.req_id.get();
self.req_id.set(id + 1);
let expected_resp: Value = from_str(expected_resp).unwrap();
let actual = self.send_request::<R>(id, params);
assert_eq!(
expected_resp,
actual,
"Expected:\n{}\n\
Actual:\n{}\n",
to_string_pretty(&expected_resp).unwrap(),
to_string_pretty(&actual).unwrap(),
);
}
fn send_request<R>(&self, id: u64, params: R::Params) -> Value
where
R: Request,
R::Params: Serialize,
{
let r = RawRequest::new::<R>(id, ¶ms);
self.send_request_(r)
}
fn send_request_(&self, r: RawRequest) -> Value {
let id = r.id;
self.worker.as_ref().unwrap().send(RawMessage::Request(r));
while let Some(msg) = self.recv() {
match msg {
RawMessage::Request(req) => panic!("unexpected request: {:?}", req),
RawMessage::Notification(_) => (),
RawMessage::Response(res) => {
assert_eq!(res.id, id);
if let Some(err) = res.error {
panic!("error response: {:#?}", err);
}
return res.result.unwrap();
}
}
}
panic!("no response");
}
pub fn wait_for_feedback(&self, feedback: &str) {
self.wait_for_feedback_n(feedback, 1)
}
pub fn wait_for_feedback_n(&self, feedback: &str, n: usize) {
let f = |msg: &RawMessage| match msg {
RawMessage::Notification(n) if n.method == "internalFeedback" => {
return n.clone().cast::<req::InternalFeedback>().unwrap() == feedback
}
_ => false,
};
let mut total = 0;
for msg in self.messages.borrow().iter() {
if f(msg) {
total += 1
}
}
while total < n {
let msg = self.recv().expect("no response");
if f(&msg) {
total += 1;
}
}
}
fn recv(&self) -> Option<RawMessage> {
recv_timeout(&self.worker.as_ref().unwrap().out).map(|msg| {
self.messages.borrow_mut().push(msg.clone());
msg
})
}
fn send_notification(&self, not: RawNotification) {
self.worker
.as_ref()
.unwrap()
.send(RawMessage::Notification(not));
}
}
impl Drop for Server {
fn drop(&mut self) {
self.send_request::<Shutdown>(666, ());
let receiver = self.worker.take().unwrap().stop();
while let Some(msg) = recv_timeout(&receiver) {
drop(msg);
}
self.watcher.take().unwrap().stop().unwrap();
}
}
fn recv_timeout(receiver: &Receiver<RawMessage>) -> Option<RawMessage> {
let timeout = Duration::from_secs(5);
select! {
recv(receiver, msg) => msg,
recv(after(timeout)) => panic!("timed out"),
}
}
|