aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_lsp_server/src/main_loop
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_lsp_server/src/main_loop')
-rw-r--r--crates/ra_lsp_server/src/main_loop/handlers.rs206
-rw-r--r--crates/ra_lsp_server/src/main_loop/mod.rs161
-rw-r--r--crates/ra_lsp_server/src/main_loop/subscriptions.rs6
3 files changed, 197 insertions, 176 deletions
diff --git a/crates/ra_lsp_server/src/main_loop/handlers.rs b/crates/ra_lsp_server/src/main_loop/handlers.rs
index 5acb39b60..c25b63852 100644
--- a/crates/ra_lsp_server/src/main_loop/handlers.rs
+++ b/crates/ra_lsp_server/src/main_loop/handlers.rs
@@ -1,23 +1,20 @@
1use rustc_hash::FxHashMap; 1use rustc_hash::FxHashMap;
2 2
3use languageserver_types::{ 3use languageserver_types::{
4 Diagnostic, DiagnosticSeverity, DocumentSymbol, 4 CodeActionResponse, Command, CompletionItem, CompletionItemKind, Diagnostic,
5 CodeActionResponse, Command, TextDocumentIdentifier, 5 DiagnosticSeverity, DocumentSymbol, FoldingRange, FoldingRangeKind, FoldingRangeParams,
6 SymbolInformation, Position, Location, TextEdit, 6 InsertTextFormat, Location, Position, SymbolInformation, TextDocumentIdentifier, TextEdit,
7 CompletionItem, InsertTextFormat, CompletionItemKind,
8 FoldingRange, FoldingRangeParams, FoldingRangeKind
9}; 7};
8use ra_analysis::{FileId, FoldKind, JobToken, Query, RunnableKind};
9use ra_syntax::text_utils::contains_offset_nonstrict;
10use serde_json::to_value; 10use serde_json::to_value;
11use ra_analysis::{Query, FileId, RunnableKind, JobToken, FoldKind};
12use ra_syntax::{
13 text_utils::contains_offset_nonstrict
14};
15 11
16use crate::{ 12use crate::{
17 req::{self, Decoration}, Result, 13 conv::{to_location, Conv, ConvWith, MapConvWith, TryConvWith},
18 conv::{Conv, ConvWith, TryConvWith, MapConvWith, to_location},
19 server_world::ServerWorld,
20 project_model::TargetKind, 14 project_model::TargetKind,
15 req::{self, Decoration},
16 server_world::ServerWorld,
17 Result,
21}; 18};
22 19
23pub fn handle_syntax_tree( 20pub fn handle_syntax_tree(
@@ -38,7 +35,9 @@ pub fn handle_extend_selection(
38 let file_id = params.text_document.try_conv_with(&world)?; 35 let file_id = params.text_document.try_conv_with(&world)?;
39 let file = world.analysis().file_syntax(file_id); 36 let file = world.analysis().file_syntax(file_id);
40 let line_index = world.analysis().file_line_index(file_id); 37 let line_index = world.analysis().file_line_index(file_id);
41 let selections = params.selections.into_iter() 38 let selections = params
39 .selections
40 .into_iter()
42 .map_conv_with(&line_index) 41 .map_conv_with(&line_index)
43 .map(|r| world.analysis().extend_selection(&file, r)) 42 .map(|r| world.analysis().extend_selection(&file, r))
44 .map_conv_with(&line_index) 43 .map_conv_with(&line_index)
@@ -54,11 +53,15 @@ pub fn handle_find_matching_brace(
54 let file_id = params.text_document.try_conv_with(&world)?; 53 let file_id = params.text_document.try_conv_with(&world)?;
55 let file = world.analysis().file_syntax(file_id); 54 let file = world.analysis().file_syntax(file_id);
56 let line_index = world.analysis().file_line_index(file_id); 55 let line_index = world.analysis().file_line_index(file_id);
57 let res = params.offsets 56 let res = params
57 .offsets
58 .into_iter() 58 .into_iter()
59 .map_conv_with(&line_index) 59 .map_conv_with(&line_index)
60 .map(|offset| { 60 .map(|offset| {
61 world.analysis().matching_brace(&file, offset).unwrap_or(offset) 61 world
62 .analysis()
63 .matching_brace(&file, offset)
64 .unwrap_or(offset)
62 }) 65 })
63 .map_conv_with(&line_index) 66 .map_conv_with(&line_index)
64 .collect(); 67 .collect();
@@ -73,7 +76,9 @@ pub fn handle_join_lines(
73 let file_id = params.text_document.try_conv_with(&world)?; 76 let file_id = params.text_document.try_conv_with(&world)?;
74 let line_index = world.analysis().file_line_index(file_id); 77 let line_index = world.analysis().file_line_index(file_id);
75 let range = params.range.conv_with(&line_index); 78 let range = params.range.conv_with(&line_index);
76 world.analysis().join_lines(file_id, range) 79 world
80 .analysis()
81 .join_lines(file_id, range)
77 .try_conv_with(&world) 82 .try_conv_with(&world)
78} 83}
79 84
@@ -87,7 +92,7 @@ pub fn handle_on_enter(
87 let offset = params.position.conv_with(&line_index); 92 let offset = params.position.conv_with(&line_index);
88 match world.analysis().on_enter(file_id, offset) { 93 match world.analysis().on_enter(file_id, offset) {
89 None => Ok(None), 94 None => Ok(None),
90 Some(edit) => Ok(Some(edit.try_conv_with(&world)?)) 95 Some(edit) => Ok(Some(edit.try_conv_with(&world)?)),
91 } 96 }
92} 97}
93 98
@@ -158,7 +163,9 @@ pub fn handle_workspace_symbol(
158 let all_symbols = params.query.contains("#"); 163 let all_symbols = params.query.contains("#");
159 let libs = params.query.contains("*"); 164 let libs = params.query.contains("*");
160 let query = { 165 let query = {
161 let query: String = params.query.chars() 166 let query: String = params
167 .query
168 .chars()
162 .filter(|&c| c != '#' && c != '*') 169 .filter(|&c| c != '#' && c != '*')
163 .collect(); 170 .collect();
164 let mut q = Query::new(query); 171 let mut q = Query::new(query);
@@ -180,22 +187,23 @@ pub fn handle_workspace_symbol(
180 187
181 return Ok(Some(res)); 188 return Ok(Some(res));
182 189
183 fn exec_query(world: &ServerWorld, query: Query, token: &JobToken) -> Result<Vec<SymbolInformation>> { 190 fn exec_query(
191 world: &ServerWorld,
192 query: Query,
193 token: &JobToken,
194 ) -> Result<Vec<SymbolInformation>> {
184 let mut res = Vec::new(); 195 let mut res = Vec::new();
185 for (file_id, symbol) in world.analysis().symbol_search(query, token) { 196 for (file_id, symbol) in world.analysis().symbol_search(query, token) {
186 let line_index = world.analysis().file_line_index(file_id); 197 let line_index = world.analysis().file_line_index(file_id);
187 let info = SymbolInformation { 198 let info = SymbolInformation {
188 name: symbol.name.to_string(), 199 name: symbol.name.to_string(),
189 kind: symbol.kind.conv(), 200 kind: symbol.kind.conv(),
190 location: to_location( 201 location: to_location(file_id, symbol.node_range, world, &line_index)?,
191 file_id, symbol.node_range,
192 world, &line_index
193 )?,
194 container_name: None, 202 container_name: None,
195 deprecated: None, 203 deprecated: None,
196 }; 204 };
197 res.push(info); 205 res.push(info);
198 }; 206 }
199 Ok(res) 207 Ok(res)
200 } 208 }
201} 209}
@@ -209,12 +217,12 @@ pub fn handle_goto_definition(
209 let line_index = world.analysis().file_line_index(file_id); 217 let line_index = world.analysis().file_line_index(file_id);
210 let offset = params.position.conv_with(&line_index); 218 let offset = params.position.conv_with(&line_index);
211 let mut res = Vec::new(); 219 let mut res = Vec::new();
212 for (file_id, symbol) in world.analysis().approximately_resolve_symbol(file_id, offset, &token) { 220 for (file_id, symbol) in world
221 .analysis()
222 .approximately_resolve_symbol(file_id, offset, &token)
223 {
213 let line_index = world.analysis().file_line_index(file_id); 224 let line_index = world.analysis().file_line_index(file_id);
214 let location = to_location( 225 let location = to_location(file_id, symbol.node_range, &world, &line_index)?;
215 file_id, symbol.node_range,
216 &world, &line_index,
217 )?;
218 res.push(location) 226 res.push(location)
219 } 227 }
220 Ok(Some(req::GotoDefinitionResponse::Array(res))) 228 Ok(Some(req::GotoDefinitionResponse::Array(res)))
@@ -229,10 +237,7 @@ pub fn handle_parent_module(
229 let mut res = Vec::new(); 237 let mut res = Vec::new();
230 for (file_id, symbol) in world.analysis().parent_module(file_id) { 238 for (file_id, symbol) in world.analysis().parent_module(file_id) {
231 let line_index = world.analysis().file_line_index(file_id); 239 let line_index = world.analysis().file_line_index(file_id);
232 let location = to_location( 240 let location = to_location(file_id, symbol.node_range, &world, &line_index)?;
233 file_id, symbol.node_range,
234 &world, &line_index
235 )?;
236 res.push(location); 241 res.push(location);
237 } 242 }
238 Ok(res) 243 Ok(res)
@@ -259,21 +264,16 @@ pub fn handle_runnables(
259 let r = req::Runnable { 264 let r = req::Runnable {
260 range: runnable.range.conv_with(&line_index), 265 range: runnable.range.conv_with(&line_index),
261 label: match &runnable.kind { 266 label: match &runnable.kind {
262 RunnableKind::Test { name } => 267 RunnableKind::Test { name } => format!("test {}", name),
263 format!("test {}", name), 268 RunnableKind::Bin => "run binary".to_string(),
264 RunnableKind::Bin =>
265 "run binary".to_string(),
266 }, 269 },
267 bin: "cargo".to_string(), 270 bin: "cargo".to_string(),
268 args, 271 args,
269 env: { 272 env: {
270 let mut m = FxHashMap::default(); 273 let mut m = FxHashMap::default();
271 m.insert( 274 m.insert("RUST_BACKTRACE".to_string(), "short".to_string());
272 "RUST_BACKTRACE".to_string(),
273 "short".to_string(),
274 );
275 m 275 m
276 } 276 },
277 }; 277 };
278 res.push(r); 278 res.push(r);
279 } 279 }
@@ -283,10 +283,16 @@ pub fn handle_runnables(
283 let spec = if let Some(&crate_id) = world.analysis().crate_for(file_id).first() { 283 let spec = if let Some(&crate_id) = world.analysis().crate_for(file_id).first() {
284 let file_id = world.analysis().crate_root(crate_id); 284 let file_id = world.analysis().crate_root(crate_id);
285 let path = world.path_map.get_path(file_id); 285 let path = world.path_map.get_path(file_id);
286 world.workspaces.iter() 286 world
287 .workspaces
288 .iter()
287 .filter_map(|ws| { 289 .filter_map(|ws| {
288 let tgt = ws.target_by_root(path)?; 290 let tgt = ws.target_by_root(path)?;
289 Some((tgt.package(ws).name(ws).clone(), tgt.name(ws).clone(), tgt.kind(ws))) 291 Some((
292 tgt.package(ws).name(ws).clone(),
293 tgt.name(ws).clone(),
294 tgt.kind(ws),
295 ))
290 }) 296 })
291 .next() 297 .next()
292 } else { 298 } else {
@@ -294,22 +300,22 @@ pub fn handle_runnables(
294 }; 300 };
295 let mut res = Vec::new(); 301 let mut res = Vec::new();
296 match kind { 302 match kind {
297 RunnableKind::Test { name } => { 303 RunnableKind::Test { name } => {
298 res.push("test".to_string()); 304 res.push("test".to_string());
299 if let Some((pkg_name, tgt_name, tgt_kind)) = spec { 305 if let Some((pkg_name, tgt_name, tgt_kind)) = spec {
300 spec_args(pkg_name, tgt_name, tgt_kind, &mut res); 306 spec_args(pkg_name, tgt_name, tgt_kind, &mut res);
301 }
302 res.push("--".to_string());
303 res.push(name.to_string());
304 res.push("--nocapture".to_string());
305 } 307 }
306 RunnableKind::Bin => { 308 res.push("--".to_string());
307 res.push("run".to_string()); 309 res.push(name.to_string());
308 if let Some((pkg_name, tgt_name, tgt_kind)) = spec { 310 res.push("--nocapture".to_string());
309 spec_args(pkg_name, tgt_name, tgt_kind, &mut res); 311 }
310 } 312 RunnableKind::Bin => {
313 res.push("run".to_string());
314 if let Some((pkg_name, tgt_name, tgt_kind)) = spec {
315 spec_args(pkg_name, tgt_name, tgt_kind, &mut res);
311 } 316 }
312 } 317 }
318 }
313 res 319 res
314 } 320 }
315 321
@@ -362,12 +368,13 @@ pub fn handle_completion(
362 None => return Ok(None), 368 None => return Ok(None),
363 Some(items) => items, 369 Some(items) => items,
364 }; 370 };
365 let items = items.into_iter() 371 let items = items
372 .into_iter()
366 .map(|item| { 373 .map(|item| {
367 let mut res = CompletionItem { 374 let mut res = CompletionItem {
368 label: item.label, 375 label: item.label,
369 filter_text: item.lookup, 376 filter_text: item.lookup,
370 .. Default::default() 377 ..Default::default()
371 }; 378 };
372 if let Some(snip) = item.snippet { 379 if let Some(snip) = item.snippet {
373 res.insert_text = Some(snip); 380 res.insert_text = Some(snip);
@@ -389,24 +396,27 @@ pub fn handle_folding_range(
389 let file_id = params.text_document.try_conv_with(&world)?; 396 let file_id = params.text_document.try_conv_with(&world)?;
390 let line_index = world.analysis().file_line_index(file_id); 397 let line_index = world.analysis().file_line_index(file_id);
391 398
392 let res = Some(world.analysis() 399 let res = Some(
393 .folding_ranges(file_id) 400 world
394 .into_iter() 401 .analysis()
395 .map(|fold| { 402 .folding_ranges(file_id)
396 let kind = match fold.kind { 403 .into_iter()
397 FoldKind::Comment => FoldingRangeKind::Comment, 404 .map(|fold| {
398 FoldKind::Imports => FoldingRangeKind::Imports 405 let kind = match fold.kind {
399 }; 406 FoldKind::Comment => FoldingRangeKind::Comment,
400 let range = fold.range.conv_with(&line_index); 407 FoldKind::Imports => FoldingRangeKind::Imports,
401 FoldingRange { 408 };
402 start_line: range.start.line, 409 let range = fold.range.conv_with(&line_index);
403 start_character: Some(range.start.character), 410 FoldingRange {
404 end_line: range.end.line, 411 start_line: range.start.line,
405 end_character: Some(range.start.character), 412 start_character: Some(range.start.character),
406 kind: Some(kind) 413 end_line: range.end.line,
407 } 414 end_character: Some(range.start.character),
408 }) 415 kind: Some(kind),
409 .collect()); 416 }
417 })
418 .collect(),
419 );
410 420
411 Ok(res) 421 Ok(res)
412} 422}
@@ -422,25 +432,28 @@ pub fn handle_signature_help(
422 let line_index = world.analysis().file_line_index(file_id); 432 let line_index = world.analysis().file_line_index(file_id);
423 let offset = params.position.conv_with(&line_index); 433 let offset = params.position.conv_with(&line_index);
424 434
425 if let Some((descriptor, active_param)) = world.analysis().resolve_callable(file_id, offset, &token) { 435 if let Some((descriptor, active_param)) =
426 let parameters : Vec<ParameterInformation> = 436 world.analysis().resolve_callable(file_id, offset, &token)
427 descriptor.params.iter().map(|param| 437 {
428 ParameterInformation { 438 let parameters: Vec<ParameterInformation> = descriptor
429 label: param.clone(), 439 .params
430 documentation: None 440 .iter()
431 } 441 .map(|param| ParameterInformation {
432 ).collect(); 442 label: param.clone(),
443 documentation: None,
444 })
445 .collect();
433 446
434 let sig_info = SignatureInformation { 447 let sig_info = SignatureInformation {
435 label: descriptor.label, 448 label: descriptor.label,
436 documentation: None, 449 documentation: None,
437 parameters: Some(parameters) 450 parameters: Some(parameters),
438 }; 451 };
439 452
440 Ok(Some(req::SignatureHelp { 453 Ok(Some(req::SignatureHelp {
441 signatures: vec![sig_info], 454 signatures: vec![sig_info],
442 active_signature: Some(0), 455 active_signature: Some(0),
443 active_parameter: active_param.map(|a| a as u64) 456 active_parameter: active_param.map(|a| a as u64),
444 })) 457 }))
445 } else { 458 } else {
446 Ok(None) 459 Ok(None)
@@ -457,7 +470,10 @@ pub fn handle_code_action(
457 let range = params.range.conv_with(&line_index); 470 let range = params.range.conv_with(&line_index);
458 471
459 let assists = world.analysis().assists(file_id, range).into_iter(); 472 let assists = world.analysis().assists(file_id, range).into_iter();
460 let fixes = world.analysis().diagnostics(file_id).into_iter() 473 let fixes = world
474 .analysis()
475 .diagnostics(file_id)
476 .into_iter()
461 .filter_map(|d| Some((d.range, d.fix?))) 477 .filter_map(|d| Some((d.range, d.fix?)))
462 .filter(|(range, _fix)| contains_offset_nonstrict(*range, range.start())) 478 .filter(|(range, _fix)| contains_offset_nonstrict(*range, range.start()))
463 .map(|(_range, fix)| fix); 479 .map(|(_range, fix)| fix);
@@ -483,7 +499,9 @@ pub fn publish_diagnostics(
483) -> Result<req::PublishDiagnosticsParams> { 499) -> Result<req::PublishDiagnosticsParams> {
484 let uri = world.file_id_to_uri(file_id)?; 500 let uri = world.file_id_to_uri(file_id)?;
485 let line_index = world.analysis().file_line_index(file_id); 501 let line_index = world.analysis().file_line_index(file_id);
486 let diagnostics = world.analysis().diagnostics(file_id) 502 let diagnostics = world
503 .analysis()
504 .diagnostics(file_id)
487 .into_iter() 505 .into_iter()
488 .map(|d| Diagnostic { 506 .map(|d| Diagnostic {
489 range: d.range.conv_with(&line_index), 507 range: d.range.conv_with(&line_index),
@@ -492,7 +510,8 @@ pub fn publish_diagnostics(
492 source: Some("rust-analyzer".to_string()), 510 source: Some("rust-analyzer".to_string()),
493 message: d.message, 511 message: d.message,
494 related_information: None, 512 related_information: None,
495 }).collect(); 513 })
514 .collect();
496 Ok(req::PublishDiagnosticsParams { uri, diagnostics }) 515 Ok(req::PublishDiagnosticsParams { uri, diagnostics })
497} 516}
498 517
@@ -509,10 +528,13 @@ pub fn publish_decorations(
509 528
510fn highlight(world: &ServerWorld, file_id: FileId) -> Vec<Decoration> { 529fn highlight(world: &ServerWorld, file_id: FileId) -> Vec<Decoration> {
511 let line_index = world.analysis().file_line_index(file_id); 530 let line_index = world.analysis().file_line_index(file_id);
512 world.analysis().highlight(file_id) 531 world
532 .analysis()
533 .highlight(file_id)
513 .into_iter() 534 .into_iter()
514 .map(|h| Decoration { 535 .map(|h| Decoration {
515 range: h.range.conv_with(&line_index), 536 range: h.range.conv_with(&line_index),
516 tag: h.tag, 537 tag: h.tag,
517 }).collect() 538 })
539 .collect()
518} 540}
diff --git a/crates/ra_lsp_server/src/main_loop/mod.rs b/crates/ra_lsp_server/src/main_loop/mod.rs
index cf2477cb5..a11baf4aa 100644
--- a/crates/ra_lsp_server/src/main_loop/mod.rs
+++ b/crates/ra_lsp_server/src/main_loop/mod.rs
@@ -1,29 +1,26 @@
1mod handlers; 1mod handlers;
2mod subscriptions; 2mod subscriptions;
3 3
4use std::{ 4use std::path::PathBuf;
5 path::PathBuf,
6};
7 5
8use serde::{Serialize, de::DeserializeOwned}; 6use crossbeam_channel::{unbounded, Receiver, Sender};
9use crossbeam_channel::{unbounded, Sender, Receiver};
10use rayon::{self, ThreadPool};
11use languageserver_types::{NumberOrString};
12use ra_analysis::{FileId, JobHandle, JobToken, LibraryData};
13use gen_lsp_server::{ 7use gen_lsp_server::{
14 RawRequest, RawNotification, RawMessage, RawResponse, ErrorCode, 8 handle_shutdown, ErrorCode, RawMessage, RawNotification, RawRequest, RawResponse,
15 handle_shutdown,
16}; 9};
10use languageserver_types::NumberOrString;
11use ra_analysis::{FileId, JobHandle, JobToken, LibraryData};
12use rayon::{self, ThreadPool};
17use rustc_hash::FxHashMap; 13use rustc_hash::FxHashMap;
14use serde::{de::DeserializeOwned, Serialize};
18 15
19use crate::{ 16use crate::{
17 main_loop::subscriptions::Subscriptions,
18 project_model::{workspace_loader, CargoWorkspace},
20 req, 19 req,
21 Result, 20 server_world::{ServerWorld, ServerWorldState},
22 vfs::{self, FileEvent},
23 server_world::{ServerWorldState, ServerWorld},
24 main_loop::subscriptions::{Subscriptions},
25 project_model::{CargoWorkspace, workspace_loader},
26 thread_watcher::Worker, 21 thread_watcher::Worker,
22 vfs::{self, FileEvent},
23 Result,
27}; 24};
28 25
29#[derive(Debug)] 26#[derive(Debug)]
@@ -147,56 +144,50 @@ fn main_loop_inner(
147 } 144 }
148 state_changed = true; 145 state_changed = true;
149 } 146 }
150 Event::Ws(ws) => { 147 Event::Ws(ws) => match ws {
151 match ws { 148 Ok(ws) => {
152 Ok(ws) => { 149 let workspaces = vec![ws];
153 let workspaces = vec![ws]; 150 feedback(internal_mode, "workspace loaded", msg_sender);
154 feedback(internal_mode, "workspace loaded", msg_sender); 151 for ws in workspaces.iter() {
155 for ws in workspaces.iter() { 152 for pkg in ws.packages().filter(|pkg| !pkg.is_member(ws)) {
156 for pkg in ws.packages().filter(|pkg| !pkg.is_member(ws)) { 153 debug!("sending root, {}", pkg.root(ws).to_path_buf().display());
157 debug!("sending root, {}", pkg.root(ws).to_path_buf().display()); 154 fs_worker.send(pkg.root(ws).to_path_buf());
158 fs_worker.send(pkg.root(ws).to_path_buf());
159 }
160 } 155 }
161 state.set_workspaces(workspaces);
162 state_changed = true;
163 } 156 }
164 Err(e) => warn!("loading workspace failed: {}", e), 157 state.set_workspaces(workspaces);
158 state_changed = true;
165 } 159 }
166 } 160 Err(e) => warn!("loading workspace failed: {}", e),
161 },
167 Event::Lib(lib) => { 162 Event::Lib(lib) => {
168 feedback(internal_mode, "library loaded", msg_sender); 163 feedback(internal_mode, "library loaded", msg_sender);
169 state.add_lib(lib); 164 state.add_lib(lib);
170 } 165 }
171 Event::Msg(msg) => { 166 Event::Msg(msg) => match msg {
172 match msg { 167 RawMessage::Request(req) => {
173 RawMessage::Request(req) => { 168 let req = match handle_shutdown(req, msg_sender) {
174 let req = match handle_shutdown(req, msg_sender) { 169 Some(req) => req,
175 Some(req) => req, 170 None => return Ok(()),
176 None => return Ok(()), 171 };
177 }; 172 match on_request(state, pending_requests, pool, &task_sender, req)? {
178 match on_request(state, pending_requests, pool, &task_sender, req)? { 173 None => (),
179 None => (), 174 Some(req) => {
180 Some(req) => { 175 error!("unknown request: {:?}", req);
181 error!("unknown request: {:?}", req); 176 let resp = RawResponse::err(
182 let resp = RawResponse::err( 177 req.id,
183 req.id, 178 ErrorCode::MethodNotFound as i32,
184 ErrorCode::MethodNotFound as i32, 179 "unknown request".to_string(),
185 "unknown request".to_string(), 180 );
186 ); 181 msg_sender.send(RawMessage::Response(resp))
187 msg_sender.send(RawMessage::Response(resp))
188 }
189 } 182 }
190 } 183 }
191 RawMessage::Notification(not) => {
192 on_notification(msg_sender, state, pending_requests, subs, not)?;
193 state_changed = true;
194 }
195 RawMessage::Response(resp) => {
196 error!("unexpected response: {:?}", resp)
197 }
198 } 184 }
199 } 185 RawMessage::Notification(not) => {
186 on_notification(msg_sender, state, pending_requests, subs, not)?;
187 state_changed = true;
188 }
189 RawMessage::Response(resp) => error!("unexpected response: {:?}", resp),
190 },
200 }; 191 };
201 192
202 if state_changed { 193 if state_changed {
@@ -222,8 +213,7 @@ fn on_task(
222 } 213 }
223 msg_sender.send(RawMessage::Response(response)) 214 msg_sender.send(RawMessage::Response(response))
224 } 215 }
225 Task::Notify(n) => 216 Task::Notify(n) => msg_sender.send(RawMessage::Notification(n)),
226 msg_sender.send(RawMessage::Notification(n)),
227 } 217 }
228} 218}
229 219
@@ -237,7 +227,9 @@ fn on_request(
237 let mut pool_dispatcher = PoolDispatcher { 227 let mut pool_dispatcher = PoolDispatcher {
238 req: Some(req), 228 req: Some(req),
239 res: None, 229 res: None,
240 pool, world, sender 230 pool,
231 world,
232 sender,
241 }; 233 };
242 let req = pool_dispatcher 234 let req = pool_dispatcher
243 .on::<req::SyntaxTree>(handlers::handle_syntax_tree)? 235 .on::<req::SyntaxTree>(handlers::handle_syntax_tree)?
@@ -262,7 +254,7 @@ fn on_request(
262 let inserted = pending_requests.insert(id, handle).is_none(); 254 let inserted = pending_requests.insert(id, handle).is_none();
263 assert!(inserted, "duplicate request: {}", id); 255 assert!(inserted, "duplicate request: {}", id);
264 Ok(None) 256 Ok(None)
265 }, 257 }
266 Err(req) => Ok(Some(req)), 258 Err(req) => Ok(Some(req)),
267 } 259 }
268} 260}
@@ -285,45 +277,53 @@ fn on_notification(
285 if let Some(handle) = pending_requests.remove(&id) { 277 if let Some(handle) = pending_requests.remove(&id) {
286 handle.cancel(); 278 handle.cancel();
287 } 279 }
288 return Ok(()) 280 return Ok(());
289 } 281 }
290 Err(not) => not, 282 Err(not) => not,
291 }; 283 };
292 let not = match not.cast::<req::DidOpenTextDocument>() { 284 let not = match not.cast::<req::DidOpenTextDocument>() {
293 Ok(params) => { 285 Ok(params) => {
294 let uri = params.text_document.uri; 286 let uri = params.text_document.uri;
295 let path = uri.to_file_path() 287 let path = uri
288 .to_file_path()
296 .map_err(|()| format_err!("invalid uri: {}", uri))?; 289 .map_err(|()| format_err!("invalid uri: {}", uri))?;
297 let file_id = state.add_mem_file(path, params.text_document.text); 290 let file_id = state.add_mem_file(path, params.text_document.text);
298 subs.add_sub(file_id); 291 subs.add_sub(file_id);
299 return Ok(()) 292 return Ok(());
300 } 293 }
301 Err(not) => not, 294 Err(not) => not,
302 }; 295 };
303 let not = match not.cast::<req::DidChangeTextDocument>() { 296 let not = match not.cast::<req::DidChangeTextDocument>() {
304 Ok(mut params) => { 297 Ok(mut params) => {
305 let uri = params.text_document.uri; 298 let uri = params.text_document.uri;
306 let path = uri.to_file_path() 299 let path = uri
300 .to_file_path()
307 .map_err(|()| format_err!("invalid uri: {}", uri))?; 301 .map_err(|()| format_err!("invalid uri: {}", uri))?;
308 let text = params.content_changes.pop() 302 let text = params
303 .content_changes
304 .pop()
309 .ok_or_else(|| format_err!("empty changes"))? 305 .ok_or_else(|| format_err!("empty changes"))?
310 .text; 306 .text;
311 state.change_mem_file(path.as_path(), text)?; 307 state.change_mem_file(path.as_path(), text)?;
312 return Ok(()) 308 return Ok(());
313 } 309 }
314 Err(not) => not, 310 Err(not) => not,
315 }; 311 };
316 let not = match not.cast::<req::DidCloseTextDocument>() { 312 let not = match not.cast::<req::DidCloseTextDocument>() {
317 Ok(params) => { 313 Ok(params) => {
318 let uri = params.text_document.uri; 314 let uri = params.text_document.uri;
319 let path = uri.to_file_path() 315 let path = uri
316 .to_file_path()
320 .map_err(|()| format_err!("invalid uri: {}", uri))?; 317 .map_err(|()| format_err!("invalid uri: {}", uri))?;
321 let file_id = state.remove_mem_file(path.as_path())?; 318 let file_id = state.remove_mem_file(path.as_path())?;
322 subs.remove_sub(file_id); 319 subs.remove_sub(file_id);
323 let params = req::PublishDiagnosticsParams { uri, diagnostics: Vec::new() }; 320 let params = req::PublishDiagnosticsParams {
321 uri,
322 diagnostics: Vec::new(),
323 };
324 let not = RawNotification::new::<req::PublishDiagnostics>(&params); 324 let not = RawNotification::new::<req::PublishDiagnostics>(&params);
325 msg_sender.send(RawMessage::Notification(not)); 325 msg_sender.send(RawMessage::Notification(not));
326 return Ok(()) 326 return Ok(());
327 } 327 }
328 Err(not) => not, 328 Err(not) => not,
329 }; 329 };
@@ -342,11 +342,12 @@ struct PoolDispatcher<'a> {
342impl<'a> PoolDispatcher<'a> { 342impl<'a> PoolDispatcher<'a> {
343 fn on<'b, R>( 343 fn on<'b, R>(
344 &'b mut self, 344 &'b mut self,
345 f: fn(ServerWorld, R::Params, JobToken) -> Result<R::Result> 345 f: fn(ServerWorld, R::Params, JobToken) -> Result<R::Result>,
346 ) -> Result<&'b mut Self> 346 ) -> Result<&'b mut Self>
347 where R: req::Request, 347 where
348 R::Params: DeserializeOwned + Send + 'static, 348 R: req::Request,
349 R::Result: Serialize + 'static, 349 R::Params: DeserializeOwned + Send + 'static,
350 R::Result: Serialize + 'static,
350 { 351 {
351 let req = match self.req.take() { 352 let req = match self.req.take() {
352 None => return Ok(self), 353 None => return Ok(self),
@@ -360,16 +361,16 @@ impl<'a> PoolDispatcher<'a> {
360 self.pool.spawn(move || { 361 self.pool.spawn(move || {
361 let resp = match f(world, params, token) { 362 let resp = match f(world, params, token) {
362 Ok(resp) => RawResponse::ok::<R>(id, &resp), 363 Ok(resp) => RawResponse::ok::<R>(id, &resp),
363 Err(e) => RawResponse::err(id, ErrorCode::InternalError as i32, e.to_string()), 364 Err(e) => {
365 RawResponse::err(id, ErrorCode::InternalError as i32, e.to_string())
366 }
364 }; 367 };
365 let task = Task::Respond(resp); 368 let task = Task::Respond(resp);
366 sender.send(task); 369 sender.send(task);
367 }); 370 });
368 self.res = Some((id, handle)); 371 self.res = Some((id, handle));
369 } 372 }
370 Err(req) => { 373 Err(req) => self.req = Some(req),
371 self.req = Some(req)
372 }
373 } 374 }
374 Ok(self) 375 Ok(self)
375 } 376 }
@@ -392,18 +393,14 @@ fn update_file_notifications_on_threadpool(
392 pool.spawn(move || { 393 pool.spawn(move || {
393 for file_id in subscriptions { 394 for file_id in subscriptions {
394 match handlers::publish_diagnostics(&world, file_id) { 395 match handlers::publish_diagnostics(&world, file_id) {
395 Err(e) => { 396 Err(e) => error!("failed to compute diagnostics: {:?}", e),
396 error!("failed to compute diagnostics: {:?}", e)
397 }
398 Ok(params) => { 397 Ok(params) => {
399 let not = RawNotification::new::<req::PublishDiagnostics>(&params); 398 let not = RawNotification::new::<req::PublishDiagnostics>(&params);
400 sender.send(Task::Notify(not)); 399 sender.send(Task::Notify(not));
401 } 400 }
402 } 401 }
403 match handlers::publish_decorations(&world, file_id) { 402 match handlers::publish_decorations(&world, file_id) {
404 Err(e) => { 403 Err(e) => error!("failed to compute decorations: {:?}", e),
405 error!("failed to compute decorations: {:?}", e)
406 }
407 Ok(params) => { 404 Ok(params) => {
408 let not = RawNotification::new::<req::PublishDecorations>(&params); 405 let not = RawNotification::new::<req::PublishDecorations>(&params);
409 sender.send(Task::Notify(not)) 406 sender.send(Task::Notify(not))
diff --git a/crates/ra_lsp_server/src/main_loop/subscriptions.rs b/crates/ra_lsp_server/src/main_loop/subscriptions.rs
index 310153382..03f41e870 100644
--- a/crates/ra_lsp_server/src/main_loop/subscriptions.rs
+++ b/crates/ra_lsp_server/src/main_loop/subscriptions.rs
@@ -1,5 +1,5 @@
1use rustc_hash::FxHashSet;
2use ra_analysis::FileId; 1use ra_analysis::FileId;
2use rustc_hash::FxHashSet;
3 3
4pub struct Subscriptions { 4pub struct Subscriptions {
5 subs: FxHashSet<FileId>, 5 subs: FxHashSet<FileId>,
@@ -7,7 +7,9 @@ pub struct Subscriptions {
7 7
8impl Subscriptions { 8impl Subscriptions {
9 pub fn new() -> Subscriptions { 9 pub fn new() -> Subscriptions {
10 Subscriptions { subs: FxHashSet::default() } 10 Subscriptions {
11 subs: FxHashSet::default(),
12 }
11 } 13 }
12 pub fn add_sub(&mut self, file_id: FileId) { 14 pub fn add_sub(&mut self, file_id: FileId) {
13 self.subs.insert(file_id); 15 self.subs.insert(file_id);