]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/main_loop.rs
Handle semantic token deltas
[rust.git] / crates / rust-analyzer / src / main_loop.rs
1 //! The main loop of `rust-analyzer` responsible for dispatching LSP
2 //! requests/replies and notifications back to the client.
3 use std::{
4     borrow::Cow,
5     env, fmt, panic,
6     time::{Duration, Instant},
7 };
8
9 use crossbeam_channel::{select, Receiver};
10 use lsp_server::{Connection, Notification, Request, Response};
11 use lsp_types::{notification::Notification as _, DidChangeTextDocumentParams};
12 use ra_db::VfsPath;
13 use ra_ide::{Canceled, FileId};
14 use ra_prof::profile;
15
16 use crate::{
17     config::Config,
18     dispatch::{NotificationDispatcher, RequestDispatcher},
19     document::DocumentData,
20     from_proto,
21     global_state::{file_id_to_url, url_to_file_id, GlobalState, Status},
22     handlers, lsp_ext,
23     lsp_utils::{apply_document_changes, is_canceled, notification_is, Progress},
24     Result,
25 };
26 use ra_project_model::ProjectWorkspace;
27 use vfs::ChangeKind;
28
29 pub fn main_loop(config: Config, connection: Connection) -> Result<()> {
30     log::info!("initial config: {:#?}", config);
31
32     // Windows scheduler implements priority boosts: if thread waits for an
33     // event (like a condvar), and event fires, priority of the thread is
34     // temporary bumped. This optimization backfires in our case: each time the
35     // `main_loop` schedules a task to run on a threadpool, the worker threads
36     // gets a higher priority, and (on a machine with fewer cores) displaces the
37     // main loop! We work-around this by marking the main loop as a
38     // higher-priority thread.
39     //
40     // https://docs.microsoft.com/en-us/windows/win32/procthread/scheduling-priorities
41     // https://docs.microsoft.com/en-us/windows/win32/procthread/priority-boosts
42     // https://github.com/rust-analyzer/rust-analyzer/issues/2835
43     #[cfg(windows)]
44     unsafe {
45         use winapi::um::processthreadsapi::*;
46         let thread = GetCurrentThread();
47         let thread_priority_above_normal = 1;
48         SetThreadPriority(thread, thread_priority_above_normal);
49     }
50
51     GlobalState::new(connection.sender.clone(), config).run(connection.receiver)
52 }
53
54 enum Event {
55     Lsp(lsp_server::Message),
56     Task(Task),
57     Vfs(vfs::loader::Message),
58     Flycheck(flycheck::Message),
59 }
60
61 #[derive(Debug)]
62 pub(crate) enum Task {
63     Response(Response),
64     Diagnostics(Vec<(FileId, Vec<lsp_types::Diagnostic>)>),
65     Workspaces(Vec<anyhow::Result<ProjectWorkspace>>),
66     Unit,
67 }
68
69 impl fmt::Debug for Event {
70     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
71         let debug_verbose_not = |not: &Notification, f: &mut fmt::Formatter| {
72             f.debug_struct("Notification").field("method", &not.method).finish()
73         };
74
75         match self {
76             Event::Lsp(lsp_server::Message::Notification(not)) => {
77                 if notification_is::<lsp_types::notification::DidOpenTextDocument>(not)
78                     || notification_is::<lsp_types::notification::DidChangeTextDocument>(not)
79                 {
80                     return debug_verbose_not(not, f);
81                 }
82             }
83             Event::Task(Task::Response(resp)) => {
84                 return f
85                     .debug_struct("Response")
86                     .field("id", &resp.id)
87                     .field("error", &resp.error)
88                     .finish();
89             }
90             _ => (),
91         }
92         match self {
93             Event::Lsp(it) => fmt::Debug::fmt(it, f),
94             Event::Task(it) => fmt::Debug::fmt(it, f),
95             Event::Vfs(it) => fmt::Debug::fmt(it, f),
96             Event::Flycheck(it) => fmt::Debug::fmt(it, f),
97         }
98     }
99 }
100
101 impl GlobalState {
102     fn run(mut self, inbox: Receiver<lsp_server::Message>) -> Result<()> {
103         if self.config.linked_projects.is_empty() && self.config.notifications.cargo_toml_not_found
104         {
105             self.show_message(
106                 lsp_types::MessageType::Error,
107                 "rust-analyzer failed to discover workspace".to_string(),
108             );
109         };
110
111         let save_registration_options = lsp_types::TextDocumentSaveRegistrationOptions {
112             include_text: Some(false),
113             text_document_registration_options: lsp_types::TextDocumentRegistrationOptions {
114                 document_selector: Some(vec![
115                     lsp_types::DocumentFilter {
116                         language: None,
117                         scheme: None,
118                         pattern: Some("**/*.rs".into()),
119                     },
120                     lsp_types::DocumentFilter {
121                         language: None,
122                         scheme: None,
123                         pattern: Some("**/Cargo.toml".into()),
124                     },
125                     lsp_types::DocumentFilter {
126                         language: None,
127                         scheme: None,
128                         pattern: Some("**/Cargo.lock".into()),
129                     },
130                 ]),
131             },
132         };
133
134         let registration = lsp_types::Registration {
135             id: "textDocument/didSave".to_string(),
136             method: "textDocument/didSave".to_string(),
137             register_options: Some(serde_json::to_value(save_registration_options).unwrap()),
138         };
139         self.send_request::<lsp_types::request::RegisterCapability>(
140             lsp_types::RegistrationParams { registrations: vec![registration] },
141             |_, _| (),
142         );
143
144         self.fetch_workspaces();
145
146         while let Some(event) = self.next_event(&inbox) {
147             if let Event::Lsp(lsp_server::Message::Notification(not)) = &event {
148                 if not.method == lsp_types::notification::Exit::METHOD {
149                     return Ok(());
150                 }
151             }
152             self.handle_event(event)?
153         }
154
155         Err("client exited without proper shutdown sequence")?
156     }
157
158     fn next_event(&self, inbox: &Receiver<lsp_server::Message>) -> Option<Event> {
159         select! {
160             recv(inbox) -> msg =>
161                 msg.ok().map(Event::Lsp),
162
163             recv(self.task_pool.receiver) -> task =>
164                 Some(Event::Task(task.unwrap())),
165
166             recv(self.loader.receiver) -> task =>
167                 Some(Event::Vfs(task.unwrap())),
168
169             recv(self.flycheck_receiver) -> task =>
170                 Some(Event::Flycheck(task.unwrap())),
171         }
172     }
173
174     fn handle_event(&mut self, event: Event) -> Result<()> {
175         let loop_start = Instant::now();
176         // NOTE: don't count blocking select! call as a loop-turn time
177         let _p = profile("GlobalState::handle_event");
178
179         log::info!("handle_event({:?})", event);
180         let queue_count = self.task_pool.handle.len();
181         if queue_count > 0 {
182             log::info!("queued count = {}", queue_count);
183         }
184
185         let prev_status = self.status;
186         match event {
187             Event::Lsp(msg) => match msg {
188                 lsp_server::Message::Request(req) => self.on_request(loop_start, req)?,
189                 lsp_server::Message::Notification(not) => {
190                     self.on_notification(not)?;
191                 }
192                 lsp_server::Message::Response(resp) => self.complete_request(resp),
193             },
194             Event::Task(task) => {
195                 match task {
196                     Task::Response(response) => self.respond(response),
197                     Task::Diagnostics(diagnostics_per_file) => {
198                         for (file_id, diagnostics) in diagnostics_per_file {
199                             self.diagnostics.set_native_diagnostics(file_id, diagnostics)
200                         }
201                     }
202                     Task::Workspaces(workspaces) => self.switch_workspaces(workspaces),
203                     Task::Unit => (),
204                 }
205                 self.analysis_host.maybe_collect_garbage();
206             }
207             Event::Vfs(mut task) => {
208                 let _p = profile("GlobalState::handle_event/vfs");
209                 loop {
210                     match task {
211                         vfs::loader::Message::Loaded { files } => {
212                             let vfs = &mut self.vfs.write().0;
213                             for (path, contents) in files {
214                                 let path = VfsPath::from(path);
215                                 if !self.mem_docs.contains_key(&path) {
216                                     vfs.set_file_contents(path, contents)
217                                 }
218                             }
219                         }
220                         vfs::loader::Message::Progress { n_total, n_done } => {
221                             if n_total == 0 {
222                                 self.transition(Status::Invalid);
223                             } else {
224                                 let state = if n_done == 0 {
225                                     self.transition(Status::Loading);
226                                     Progress::Begin
227                                 } else if n_done < n_total {
228                                     Progress::Report
229                                 } else {
230                                     assert_eq!(n_done, n_total);
231                                     self.transition(Status::Ready);
232                                     Progress::End
233                                 };
234                                 self.report_progress(
235                                     "roots scanned",
236                                     state,
237                                     Some(format!("{}/{}", n_done, n_total)),
238                                     Some(Progress::percentage(n_done, n_total)),
239                                 )
240                             }
241                         }
242                     }
243                     // Coalesce many VFS event into a single loop turn
244                     task = match self.loader.receiver.try_recv() {
245                         Ok(task) => task,
246                         Err(_) => break,
247                     }
248                 }
249             }
250             Event::Flycheck(task) => match task {
251                 flycheck::Message::AddDiagnostic { workspace_root, diagnostic } => {
252                     let diagnostics = crate::diagnostics::to_proto::map_rust_diagnostic_to_lsp(
253                         &self.config.diagnostics,
254                         &diagnostic,
255                         &workspace_root,
256                     );
257                     for diag in diagnostics {
258                         match url_to_file_id(&self.vfs.read().0, &diag.url) {
259                             Ok(file_id) => self.diagnostics.add_check_diagnostic(
260                                 file_id,
261                                 diag.diagnostic,
262                                 diag.fixes,
263                             ),
264                             Err(err) => {
265                                 log::error!("File with cargo diagnostic not found in VFS: {}", err);
266                             }
267                         };
268                     }
269                 }
270
271                 flycheck::Message::Progress(status) => {
272                     let (state, message) = match status {
273                         flycheck::Progress::DidStart => {
274                             self.diagnostics.clear_check();
275                             (Progress::Begin, None)
276                         }
277                         flycheck::Progress::DidCheckCrate(target) => {
278                             (Progress::Report, Some(target))
279                         }
280                         flycheck::Progress::DidCancel => (Progress::End, None),
281                         flycheck::Progress::DidFinish(result) => {
282                             if let Err(err) = result {
283                                 log::error!("cargo check failed: {}", err)
284                             }
285                             (Progress::End, None)
286                         }
287                     };
288
289                     self.report_progress("cargo check", state, message, None);
290                 }
291             },
292         }
293
294         let state_changed = self.process_changes();
295         if prev_status == Status::Loading && self.status == Status::Ready {
296             if let Some(flycheck) = &self.flycheck {
297                 flycheck.update();
298             }
299         }
300
301         if self.status == Status::Ready && (state_changed || prev_status == Status::Loading) {
302             let subscriptions = self
303                 .mem_docs
304                 .keys()
305                 .map(|path| self.vfs.read().0.file_id(&path).unwrap())
306                 .collect::<Vec<_>>();
307
308             self.update_file_notifications_on_threadpool(subscriptions);
309         }
310
311         if let Some(diagnostic_changes) = self.diagnostics.take_changes() {
312             for file_id in diagnostic_changes {
313                 let url = file_id_to_url(&self.vfs.read().0, file_id);
314                 let diagnostics = self.diagnostics.diagnostics_for(file_id).cloned().collect();
315                 let version = from_proto::vfs_path(&url)
316                     .map(|path| self.mem_docs.get(&path)?.version)
317                     .unwrap_or_default();
318
319                 self.send_notification::<lsp_types::notification::PublishDiagnostics>(
320                     lsp_types::PublishDiagnosticsParams { uri: url, diagnostics, version },
321                 );
322             }
323         }
324
325         let loop_duration = loop_start.elapsed();
326         if loop_duration > Duration::from_millis(100) {
327             log::warn!("overly long loop turn: {:?}", loop_duration);
328             if env::var("RA_PROFILE").is_ok() {
329                 self.show_message(
330                     lsp_types::MessageType::Error,
331                     format!("overly long loop turn: {:?}", loop_duration),
332                 )
333             }
334         }
335         Ok(())
336     }
337
338     fn on_request(&mut self, request_received: Instant, req: Request) -> Result<()> {
339         self.register_request(&req, request_received);
340
341         RequestDispatcher { req: Some(req), global_state: self }
342             .on_sync::<lsp_ext::ReloadWorkspace>(|s, ()| Ok(s.fetch_workspaces()))?
343             .on_sync::<lsp_ext::JoinLines>(|s, p| handlers::handle_join_lines(s.snapshot(), p))?
344             .on_sync::<lsp_ext::OnEnter>(|s, p| handlers::handle_on_enter(s.snapshot(), p))?
345             .on_sync::<lsp_types::request::Shutdown>(|_, ()| Ok(()))?
346             .on_sync::<lsp_types::request::SelectionRangeRequest>(|s, p| {
347                 handlers::handle_selection_range(s.snapshot(), p)
348             })?
349             .on_sync::<lsp_ext::MatchingBrace>(|s, p| {
350                 handlers::handle_matching_brace(s.snapshot(), p)
351             })?
352             .on_sync::<lsp_ext::MemoryUsage>(|s, p| handlers::handle_memory_usage(s, p))?
353             .on::<lsp_ext::AnalyzerStatus>(handlers::handle_analyzer_status)?
354             .on::<lsp_ext::SyntaxTree>(handlers::handle_syntax_tree)?
355             .on::<lsp_ext::ExpandMacro>(handlers::handle_expand_macro)?
356             .on::<lsp_ext::ParentModule>(handlers::handle_parent_module)?
357             .on::<lsp_ext::Runnables>(handlers::handle_runnables)?
358             .on::<lsp_ext::InlayHints>(handlers::handle_inlay_hints)?
359             .on::<lsp_ext::CodeActionRequest>(handlers::handle_code_action)?
360             .on::<lsp_ext::ResolveCodeActionRequest>(handlers::handle_resolve_code_action)?
361             .on::<lsp_ext::HoverRequest>(handlers::handle_hover)?
362             .on::<lsp_types::request::OnTypeFormatting>(handlers::handle_on_type_formatting)?
363             .on::<lsp_types::request::DocumentSymbolRequest>(handlers::handle_document_symbol)?
364             .on::<lsp_types::request::WorkspaceSymbol>(handlers::handle_workspace_symbol)?
365             .on::<lsp_types::request::GotoDefinition>(handlers::handle_goto_definition)?
366             .on::<lsp_types::request::GotoImplementation>(handlers::handle_goto_implementation)?
367             .on::<lsp_types::request::GotoTypeDefinition>(handlers::handle_goto_type_definition)?
368             .on::<lsp_types::request::Completion>(handlers::handle_completion)?
369             .on::<lsp_types::request::CodeLensRequest>(handlers::handle_code_lens)?
370             .on::<lsp_types::request::CodeLensResolve>(handlers::handle_code_lens_resolve)?
371             .on::<lsp_types::request::FoldingRangeRequest>(handlers::handle_folding_range)?
372             .on::<lsp_types::request::SignatureHelpRequest>(handlers::handle_signature_help)?
373             .on::<lsp_types::request::PrepareRenameRequest>(handlers::handle_prepare_rename)?
374             .on::<lsp_types::request::Rename>(handlers::handle_rename)?
375             .on::<lsp_types::request::References>(handlers::handle_references)?
376             .on::<lsp_types::request::Formatting>(handlers::handle_formatting)?
377             .on::<lsp_types::request::DocumentHighlightRequest>(
378                 handlers::handle_document_highlight,
379             )?
380             .on::<lsp_types::request::CallHierarchyPrepare>(
381                 handlers::handle_call_hierarchy_prepare,
382             )?
383             .on::<lsp_types::request::CallHierarchyIncomingCalls>(
384                 handlers::handle_call_hierarchy_incoming,
385             )?
386             .on::<lsp_types::request::CallHierarchyOutgoingCalls>(
387                 handlers::handle_call_hierarchy_outgoing,
388             )?
389             .on::<lsp_types::request::SemanticTokensRequest>(handlers::handle_semantic_tokens)?
390             .on::<lsp_types::request::SemanticTokensEditsRequest>(
391                 handlers::handle_semantic_tokens_edits,
392             )?
393             .on::<lsp_types::request::SemanticTokensRangeRequest>(
394                 handlers::handle_semantic_tokens_range,
395             )?
396             .on::<lsp_ext::Ssr>(handlers::handle_ssr)?
397             .finish();
398         Ok(())
399     }
400     fn on_notification(&mut self, not: Notification) -> Result<()> {
401         NotificationDispatcher { not: Some(not), global_state: self }
402             .on::<lsp_types::notification::Cancel>(|this, params| {
403                 let id: lsp_server::RequestId = match params.id {
404                     lsp_types::NumberOrString::Number(id) => id.into(),
405                     lsp_types::NumberOrString::String(id) => id.into(),
406                 };
407                 this.cancel(id);
408                 Ok(())
409             })?
410             .on::<lsp_types::notification::DidOpenTextDocument>(|this, params| {
411                 if let Ok(path) = from_proto::vfs_path(&params.text_document.uri) {
412                     if this
413                         .mem_docs
414                         .insert(path.clone(), DocumentData::new(params.text_document.version))
415                         .is_some()
416                     {
417                         log::error!("duplicate DidOpenTextDocument: {}", path)
418                     }
419                     this.vfs
420                         .write()
421                         .0
422                         .set_file_contents(path, Some(params.text_document.text.into_bytes()));
423                 }
424                 Ok(())
425             })?
426             .on::<lsp_types::notification::DidChangeTextDocument>(|this, params| {
427                 if let Ok(path) = from_proto::vfs_path(&params.text_document.uri) {
428                     let DidChangeTextDocumentParams { text_document, content_changes } = params;
429                     let vfs = &mut this.vfs.write().0;
430                     let world = this.snapshot();
431                     let file_id = vfs.file_id(&path).unwrap();
432
433                     // let file_id = vfs.file_id(&path).unwrap();
434                     let mut text = String::from_utf8(vfs.file_contents(file_id).to_vec()).unwrap();
435                     let line_index = world.analysis.file_line_index(file_id)?;
436                     apply_document_changes(&mut text, content_changes, Cow::Borrowed(&line_index));
437
438                     // The version passed in DidChangeTextDocument is the version after all edits are applied
439                     // so we should apply it before the vfs is notified.
440                     let doc = this.mem_docs.get_mut(&path).unwrap();
441                     doc.version = text_document.version;
442
443                     vfs.set_file_contents(path.clone(), Some(text.into_bytes()));
444                 }
445                 Ok(())
446             })?
447             .on::<lsp_types::notification::DidCloseTextDocument>(|this, params| {
448                 let mut version = None;
449                 if let Ok(path) = from_proto::vfs_path(&params.text_document.uri) {
450                     match this.mem_docs.remove(&path) {
451                         Some(doc) => version = doc.version,
452                         None => log::error!("orphan DidCloseTextDocument: {}", path),
453                     }
454
455                     this.semantic_tokens_cache.lock().unwrap().remove(&params.text_document.uri);
456
457                     if let Some(path) = path.as_path() {
458                         this.loader.handle.invalidate(path.to_path_buf());
459                     }
460                 }
461
462                 // Clear the diagnostics for the previously known version of the file.
463                 // This prevents stale "cargo check" diagnostics if the file is
464                 // closed, "cargo check" is run and then the file is reopened.
465                 this.send_notification::<lsp_types::notification::PublishDiagnostics>(
466                     lsp_types::PublishDiagnosticsParams {
467                         uri: params.text_document.uri,
468                         diagnostics: Vec::new(),
469                         version,
470                     },
471                 );
472                 Ok(())
473             })?
474             .on::<lsp_types::notification::DidSaveTextDocument>(|this, params| {
475                 if let Some(flycheck) = &this.flycheck {
476                     flycheck.update();
477                 }
478                 if let Ok(abs_path) = from_proto::abs_path(&params.text_document.uri) {
479                     this.maybe_refresh(&[(abs_path, ChangeKind::Modify)]);
480                 }
481                 Ok(())
482             })?
483             .on::<lsp_types::notification::DidChangeConfiguration>(|this, _params| {
484                 // As stated in https://github.com/microsoft/language-server-protocol/issues/676,
485                 // this notification's parameters should be ignored and the actual config queried separately.
486                 this.send_request::<lsp_types::request::WorkspaceConfiguration>(
487                     lsp_types::ConfigurationParams {
488                         items: vec![lsp_types::ConfigurationItem {
489                             scope_uri: None,
490                             section: Some("rust-analyzer".to_string()),
491                         }],
492                     },
493                     |this, resp| {
494                         log::debug!("config update response: '{:?}", resp);
495                         let Response { error, result, .. } = resp;
496
497                         match (error, result) {
498                             (Some(err), _) => {
499                                 log::error!("failed to fetch the server settings: {:?}", err)
500                             }
501                             (None, Some(mut configs)) => {
502                                 if let Some(json) = configs.get_mut(0) {
503                                     // Note that json can be null according to the spec if the client can't
504                                     // provide a configuration. This is handled in Config::update below.
505                                     let mut config = this.config.clone();
506                                     config.update(json.take());
507                                     this.update_configuration(config);
508                                 }
509                             }
510                             (None, None) => log::error!(
511                                 "received empty server settings response from the client"
512                             ),
513                         }
514                     },
515                 );
516
517                 return Ok(());
518             })?
519             .on::<lsp_types::notification::DidChangeWatchedFiles>(|this, params| {
520                 for change in params.changes {
521                     if let Ok(path) = from_proto::abs_path(&change.uri) {
522                         this.loader.handle.invalidate(path);
523                     }
524                 }
525                 Ok(())
526             })?
527             .finish();
528         Ok(())
529     }
530     fn update_file_notifications_on_threadpool(&mut self, subscriptions: Vec<FileId>) {
531         log::trace!("updating notifications for {:?}", subscriptions);
532         if self.config.publish_diagnostics {
533             let snapshot = self.snapshot();
534             let subscriptions = subscriptions.clone();
535             self.task_pool.handle.spawn(move || {
536                 let diagnostics = subscriptions
537                     .into_iter()
538                     .filter_map(|file_id| {
539                         handlers::publish_diagnostics(&snapshot, file_id)
540                             .map_err(|err| {
541                                 if !is_canceled(&*err) {
542                                     log::error!("failed to compute diagnostics: {:?}", err);
543                                 }
544                                 ()
545                             })
546                             .ok()
547                             .map(|diags| (file_id, diags))
548                     })
549                     .collect::<Vec<_>>();
550                 Task::Diagnostics(diagnostics)
551             })
552         }
553         self.task_pool.handle.spawn({
554             let subs = subscriptions;
555             let snap = self.snapshot();
556             move || {
557                 snap.analysis.prime_caches(subs).unwrap_or_else(|_: Canceled| ());
558                 Task::Unit
559             }
560         });
561     }
562 }