1 //! Project loading & configuration updates
2 use std::{mem, sync::Arc};
4 use flycheck::{FlycheckConfig, FlycheckHandle};
6 use ide_db::base_db::{CrateGraph, SourceRoot, VfsPath};
7 use project_model::{ProcMacroClient, ProjectWorkspace};
8 use vfs::{file_set::FileSetConfig, AbsPath, AbsPathBuf, ChangeKind};
11 config::{Config, FilesWatcher, LinkedProject},
12 global_state::{GlobalState, Status},
16 use lsp_ext::StatusParams;
19 pub(crate) enum ProjectWorkspaceProgress {
22 End(Vec<anyhow::Result<ProjectWorkspace>>),
26 pub(crate) fn update_configuration(&mut self, config: Config) {
27 let _p = profile::span("GlobalState::update_configuration");
28 let old_config = mem::replace(&mut self.config, Arc::new(config));
29 if self.config.lru_capacity() != old_config.lru_capacity() {
30 self.analysis_host.update_lru_capacity(self.config.lru_capacity());
32 if self.config.linked_projects() != old_config.linked_projects() {
33 self.fetch_workspaces_request()
34 } else if self.config.flycheck() != old_config.flycheck() {
35 self.reload_flycheck();
38 pub(crate) fn maybe_refresh(&mut self, changes: &[(AbsPathBuf, ChangeKind)]) {
39 if !changes.iter().any(|(path, kind)| is_interesting(path, *kind)) {
43 Status::Loading | Status::NeedsReload => return,
44 Status::Ready | Status::Invalid => (),
46 if self.config.cargo_autoreload() {
47 self.fetch_workspaces_request();
49 self.transition(Status::NeedsReload);
52 fn is_interesting(path: &AbsPath, change_kind: ChangeKind) -> bool {
53 const IMPLICIT_TARGET_FILES: &[&str] = &["build.rs", "src/main.rs", "src/lib.rs"];
54 const IMPLICIT_TARGET_DIRS: &[&str] = &["src/bin", "examples", "tests", "benches"];
56 if path.ends_with("Cargo.toml") || path.ends_with("Cargo.lock") {
59 if change_kind == ChangeKind::Modify {
62 if path.extension().unwrap_or_default() != "rs" {
65 if IMPLICIT_TARGET_FILES.iter().any(|it| path.ends_with(it)) {
68 let parent = match path.parent() {
72 if IMPLICIT_TARGET_DIRS.iter().any(|it| parent.ends_with(it)) {
75 if path.ends_with("main.rs") {
76 let grand_parent = match parent.parent() {
80 if IMPLICIT_TARGET_DIRS.iter().any(|it| grand_parent.ends_with(it)) {
87 pub(crate) fn transition(&mut self, new_status: Status) {
88 self.status = new_status;
89 if self.config.status_notification() {
90 let lsp_status = match new_status {
91 Status::Loading => lsp_ext::Status::Loading,
92 Status::Ready => lsp_ext::Status::Ready,
93 Status::Invalid => lsp_ext::Status::Invalid,
94 Status::NeedsReload => lsp_ext::Status::NeedsReload,
96 self.send_notification::<lsp_ext::StatusNotification>(StatusParams {
102 pub(crate) fn fetch_workspaces_request(&mut self) {
103 self.fetch_workspaces_queue.request_op()
105 pub(crate) fn fetch_workspaces_if_needed(&mut self) {
106 if !self.fetch_workspaces_queue.should_start_op() {
109 log::info!("will fetch workspaces");
111 self.task_pool.handle.spawn_with_sender({
112 let linked_projects = self.config.linked_projects();
113 let cargo_config = self.config.cargo();
117 let sender = sender.clone();
120 .send(Task::FetchWorkspace(ProjectWorkspaceProgress::Report(msg)))
125 sender.send(Task::FetchWorkspace(ProjectWorkspaceProgress::Begin)).unwrap();
127 let workspaces = linked_projects
129 .map(|project| match project {
130 LinkedProject::ProjectManifest(manifest) => {
131 project_model::ProjectWorkspace::load(
137 LinkedProject::InlineJsonProject(it) => {
138 project_model::ProjectWorkspace::load_inline(
140 cargo_config.target.as_deref(),
144 .collect::<Vec<_>>();
146 log::info!("did fetch workspaces {:?}", workspaces);
148 .send(Task::FetchWorkspace(ProjectWorkspaceProgress::End(workspaces)))
153 pub(crate) fn fetch_workspaces_completed(&mut self) {
154 self.fetch_workspaces_queue.op_completed()
157 pub(crate) fn switch_workspaces(&mut self, workspaces: Vec<anyhow::Result<ProjectWorkspace>>) {
158 let _p = profile::span("GlobalState::switch_workspaces");
159 log::info!("will switch workspaces: {:?}", workspaces);
161 let mut has_errors = false;
162 let workspaces = workspaces
167 log::error!("failed to load workspace: {:#}", err);
168 if self.workspaces.is_empty() {
170 lsp_types::MessageType::Error,
171 format!("rust-analyzer failed to load workspace: {:#}", err),
177 .collect::<Vec<_>>();
179 if &*self.workspaces == &workspaces {
183 if !self.workspaces.is_empty() && has_errors {
187 if let FilesWatcher::Client = self.config.files().watcher {
188 if self.config.did_change_watched_files_dynamic_registration() {
189 let registration_options = lsp_types::DidChangeWatchedFilesRegistrationOptions {
192 .flat_map(ProjectWorkspace::to_roots)
193 .filter(|it| it.is_member)
195 root.include.into_iter().map(|it| format!("{}/**/*.rs", it.display()))
197 .map(|glob_pattern| lsp_types::FileSystemWatcher {
203 let registration = lsp_types::Registration {
204 id: "workspace/didChangeWatchedFiles".to_string(),
205 method: "workspace/didChangeWatchedFiles".to_string(),
206 register_options: Some(serde_json::to_value(registration_options).unwrap()),
208 self.send_request::<lsp_types::request::RegisterCapability>(
209 lsp_types::RegistrationParams { registrations: vec![registration] },
215 let mut change = Change::new();
217 let files_config = self.config.files();
218 let project_folders = ProjectFolders::new(&workspaces, &files_config.exclude);
220 self.proc_macro_client = match self.config.proc_macro_srv() {
222 Some((path, args)) => match ProcMacroClient::extern_process(path.clone(), args) {
226 "Failed to run proc_macro_srv from path {}, error: {:?}",
235 let watch = match files_config.watcher {
236 FilesWatcher::Client => vec![],
237 FilesWatcher::Notify => project_folders.watch,
239 self.loader.handle.set_config(vfs::loader::Config { load: project_folders.load, watch });
241 // Create crate graph from all the workspaces
243 let mut crate_graph = CrateGraph::default();
244 let vfs = &mut self.vfs.write().0;
245 let loader = &mut self.loader;
246 let mem_docs = &self.mem_docs;
247 let mut load = |path: &AbsPath| {
248 let vfs_path = vfs::VfsPath::from(path.to_path_buf());
249 if !mem_docs.contains_key(&vfs_path) {
250 let contents = loader.handle.load_sync(path);
251 vfs.set_file_contents(vfs_path.clone(), contents);
253 let res = vfs.file_id(&vfs_path);
255 log::warn!("failed to load {}", path.display())
259 for ws in workspaces.iter() {
260 crate_graph.extend(ws.to_crate_graph(self.proc_macro_client.as_ref(), &mut load));
265 change.set_crate_graph(crate_graph);
267 self.source_root_config = project_folders.source_root_config;
268 self.workspaces = Arc::new(workspaces);
270 self.analysis_host.apply_change(change);
271 self.process_changes();
272 self.reload_flycheck();
273 log::info!("did switch workspaces");
276 fn reload_flycheck(&mut self) {
277 let _p = profile::span("GlobalState::reload_flycheck");
278 let config = match self.config.flycheck() {
281 self.flycheck = Vec::new();
286 let sender = self.flycheck_sender.clone();
291 .filter_map(|(id, w)| match w {
292 ProjectWorkspace::Cargo { cargo, .. } => Some((id, cargo.workspace_root())),
293 ProjectWorkspace::Json { project, .. } => {
294 // Enable flychecks for json projects if a custom flycheck command was supplied
295 // in the workspace configuration.
297 FlycheckConfig::CustomCommand { .. } => Some((id, project.path())),
303 let sender = sender.clone();
304 FlycheckHandle::spawn(
306 Box::new(move |msg| sender.send(msg).unwrap()),
308 root.to_path_buf().into(),
316 pub(crate) struct ProjectFolders {
317 pub(crate) load: Vec<vfs::loader::Entry>,
318 pub(crate) watch: Vec<usize>,
319 pub(crate) source_root_config: SourceRootConfig,
322 impl ProjectFolders {
324 workspaces: &[ProjectWorkspace],
325 global_excludes: &[AbsPathBuf],
326 ) -> ProjectFolders {
327 let mut res = ProjectFolders::default();
328 let mut fsc = FileSetConfig::builder();
329 let mut local_filesets = vec![];
331 for root in workspaces.iter().flat_map(|it| it.to_roots()) {
332 let file_set_roots: Vec<VfsPath> =
333 root.include.iter().cloned().map(VfsPath::from).collect();
336 let mut dirs = vfs::loader::Directories::default();
337 dirs.extensions.push("rs".into());
338 dirs.include.extend(root.include);
339 dirs.exclude.extend(root.exclude);
340 for excl in global_excludes {
341 if dirs.include.iter().any(|incl| incl.starts_with(excl)) {
342 dirs.exclude.push(excl.clone());
346 vfs::loader::Entry::Directories(dirs)
350 res.watch.push(res.load.len());
352 res.load.push(entry);
355 local_filesets.push(fsc.len());
357 fsc.add_file_set(file_set_roots)
360 let fsc = fsc.build();
361 res.source_root_config = SourceRootConfig { fsc, local_filesets };
367 #[derive(Default, Debug)]
368 pub(crate) struct SourceRootConfig {
369 pub(crate) fsc: FileSetConfig,
370 pub(crate) local_filesets: Vec<usize>,
373 impl SourceRootConfig {
374 pub(crate) fn partition(&self, vfs: &vfs::Vfs) -> Vec<SourceRoot> {
375 let _p = profile::span("SourceRootConfig::partition");
380 .map(|(idx, file_set)| {
381 let is_local = self.local_filesets.contains(&idx);
383 SourceRoot::new_local(file_set)
385 SourceRoot::new_library(file_set)