-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathclient_builder.rs
More file actions
177 lines (159 loc) · 5.9 KB
/
client_builder.rs
File metadata and controls
177 lines (159 loc) · 5.9 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
use std::ops::ControlFlow;
use std::path::Path;
use std::process::Stdio;
use async_lsp::concurrency::ConcurrencyLayer;
use async_lsp::panic::CatchUnwindLayer;
use async_lsp::router::Router;
use async_lsp::tracing::TracingLayer;
use async_lsp::{Error, ErrorCode, LanguageServer};
use futures::channel::oneshot;
use lsp_types::notification::{Progress, PublishDiagnostics, ShowMessage};
use lsp_types::{
ClientCapabilities, DidOpenTextDocumentParams, HoverContents, HoverParams, InitializeParams,
InitializedParams, MarkupContent, NumberOrString, Position, ProgressParamsValue,
TextDocumentIdentifier, TextDocumentItem, TextDocumentPositionParams, Url,
WindowClientCapabilities, WorkDoneProgress, WorkDoneProgressParams, WorkspaceFolder,
};
use tower::ServiceBuilder;
use tracing::{info, Level};
const TEST_ROOT: &str = "tests/client_test_data";
// Old and new token names.
const RA_INDEXING_TOKENS: &[&str] = &["rustAnalyzer/Indexing", "rustAnalyzer/cachePriming"];
struct ClientState {
indexed_tx: Option<oneshot::Sender<()>>,
}
struct Stop;
#[tokio::main(flavor = "current_thread")]
async fn main() {
let root_dir = Path::new(TEST_ROOT)
.canonicalize()
.expect("test root should be valid");
let (indexed_tx, indexed_rx) = oneshot::channel();
let (mainloop, mut server) = async_lsp::MainLoop::new_client(|_server| {
let mut router = Router::new(ClientState {
indexed_tx: Some(indexed_tx),
});
router
.notification::<Progress>(|this, prog| {
tracing::info!("{:?} {:?}", prog.token, prog.value);
if matches!(prog.token, NumberOrString::String(s) if RA_INDEXING_TOKENS.contains(&&*s))
&& matches!(
prog.value,
ProgressParamsValue::WorkDone(WorkDoneProgress::End(_))
)
{
// Sometimes rust-analyzer auto-index multiple times?
if let Some(tx) = this.indexed_tx.take() {
let _: Result<_, _> = tx.send(());
}
}
ControlFlow::Continue(())
})
.notification::<PublishDiagnostics>(|_, _| ControlFlow::Continue(()))
.notification::<ShowMessage>(|_, params| {
tracing::info!("Message {:?}: {}", params.typ, params.message);
ControlFlow::Continue(())
})
.event(|_, _: Stop| ControlFlow::Break(Ok(())));
ServiceBuilder::new()
.layer(TracingLayer::default())
.layer(CatchUnwindLayer::default())
.layer(ConcurrencyLayer::default())
.service(router)
});
tracing_subscriber::fmt()
.with_max_level(Level::INFO)
.with_ansi(false)
.with_writer(std::io::stderr)
.init();
let child = async_process::Command::new("rust-analyzer")
.current_dir(&root_dir)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.kill_on_drop(true)
.spawn()
.expect("Failed run rust-analyzer");
let stdout = child.stdout.unwrap();
let stdin = child.stdin.unwrap();
let mainloop_fut = tokio::spawn(async move {
mainloop.run_buffered(stdout, stdin).await.unwrap();
});
// Initialize.
let init_ret = server
.initialize(InitializeParams {
workspace_folders: Some(vec![WorkspaceFolder {
uri: Url::from_file_path(&root_dir).unwrap(),
name: "root".into(),
}]),
capabilities: ClientCapabilities {
window: Some(WindowClientCapabilities {
work_done_progress: Some(true),
..WindowClientCapabilities::default()
}),
..ClientCapabilities::default()
},
..InitializeParams::default()
})
.await
.unwrap();
info!("Initialized: {init_ret:?}");
server.initialized(InitializedParams {}).unwrap();
// Synchronize documents.
let file_uri = Url::from_file_path(root_dir.join("src/lib.rs")).unwrap();
let text = "#![no_std] fn func() { let var = 1; }";
server
.did_open(DidOpenTextDocumentParams {
text_document: TextDocumentItem {
uri: file_uri.clone(),
language_id: "rust".into(),
version: 0,
text: text.into(),
},
})
.unwrap();
// Wait until indexed.
indexed_rx.await.unwrap();
// Query.
let var_pos = text.find("var").unwrap();
let hover = loop {
let ret = server
.hover(HoverParams {
text_document_position_params: TextDocumentPositionParams {
text_document: TextDocumentIdentifier {
uri: file_uri.clone(),
},
position: Position::new(0, var_pos as _),
},
work_done_progress_params: WorkDoneProgressParams::default(),
})
.await;
match ret {
Ok(resp) => break resp.expect("no hover"),
// Sometimes rust-analyzer replies CONTENT_MODIFIED if it's not completely ready yet.
Err(Error::Response(resp)) if resp.code == ErrorCode::CONTENT_MODIFIED => {
continue;
}
Err(err) => panic!("request failed: {err}"),
}
};
info!("Hover result: {hover:?}");
assert!(
matches!(
hover.contents,
HoverContents::Markup(MarkupContent { value, .. })
if value.contains("let var: i32")
),
"should show the type of `var`",
);
// Shutdown.
server.shutdown(()).await.unwrap();
server.exit(()).unwrap();
server.emit(Stop).unwrap();
mainloop_fut.await.unwrap();
}
#[test]
#[ignore = "invokes rust-analyzer"]
fn rust_analyzer() {
main()
}