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) fn update_configuration(&mut self, config: Config) {
20 let _p = profile::span("GlobalState::update_configuration");
21 let old_config = mem::replace(&mut self.config, config);
22 if self.config.lru_capacity != old_config.lru_capacity {
23 self.analysis_host.update_lru_capacity(old_config.lru_capacity);
25 if self.config.linked_projects != old_config.linked_projects {
26 self.fetch_workspaces()
27 } else if self.config.flycheck != old_config.flycheck {
28 self.reload_flycheck();
31 pub(crate) fn maybe_refresh(&mut self, changes: &[(AbsPathBuf, ChangeKind)]) {
32 if !changes.iter().any(|(path, kind)| is_interesting(path, *kind)) {
36 Status::Loading | Status::NeedsReload => return,
37 Status::Ready | Status::Invalid => (),
39 if self.config.cargo_autoreload {
40 self.fetch_workspaces();
42 self.transition(Status::NeedsReload);
45 fn is_interesting(path: &AbsPath, change_kind: ChangeKind) -> bool {
46 const IMPLICIT_TARGET_FILES: &[&str] = &["build.rs", "src/main.rs", "src/lib.rs"];
47 const IMPLICIT_TARGET_DIRS: &[&str] = &["src/bin", "examples", "tests", "benches"];
49 if path.ends_with("Cargo.toml") || path.ends_with("Cargo.lock") {
52 if change_kind == ChangeKind::Modify {
55 if path.extension().unwrap_or_default() != "rs" {
58 if IMPLICIT_TARGET_FILES.iter().any(|it| path.ends_with(it)) {
61 let parent = match path.parent() {
65 if IMPLICIT_TARGET_DIRS.iter().any(|it| parent.ends_with(it)) {
68 if path.ends_with("main.rs") {
69 let grand_parent = match parent.parent() {
73 if IMPLICIT_TARGET_DIRS.iter().any(|it| grand_parent.ends_with(it)) {
80 pub(crate) fn transition(&mut self, new_status: Status) {
81 self.status = new_status;
82 if self.config.client_caps.status_notification {
83 let lsp_status = match new_status {
84 Status::Loading => lsp_ext::Status::Loading,
85 Status::Ready => lsp_ext::Status::Ready,
86 Status::Invalid => lsp_ext::Status::Invalid,
87 Status::NeedsReload => lsp_ext::Status::NeedsReload,
89 self.send_notification::<lsp_ext::StatusNotification>(StatusParams {
94 pub(crate) fn fetch_workspaces(&mut self) {
95 log::info!("will fetch workspaces");
96 self.task_pool.handle.spawn({
97 let linked_projects = self.config.linked_projects.clone();
98 let cargo_config = self.config.cargo.clone();
100 let workspaces = linked_projects
102 .map(|project| match project {
103 LinkedProject::ProjectManifest(manifest) => {
104 project_model::ProjectWorkspace::load(manifest.clone(), &cargo_config)
106 LinkedProject::InlineJsonProject(it) => {
107 project_model::ProjectWorkspace::load_inline(it.clone())
110 .collect::<Vec<_>>();
111 log::info!("did fetch workspaces {:?}", workspaces);
112 Task::Workspaces(workspaces)
116 pub(crate) fn switch_workspaces(&mut self, workspaces: Vec<anyhow::Result<ProjectWorkspace>>) {
117 let _p = profile::span("GlobalState::switch_workspaces");
118 log::info!("will switch workspaces: {:?}", workspaces);
120 let mut has_errors = false;
121 let workspaces = workspaces
126 log::error!("failed to load workspace: {:#}", err);
127 if self.workspaces.is_empty() {
129 lsp_types::MessageType::Error,
130 format!("rust-analyzer failed to load workspace: {:#}", err),
136 .collect::<Vec<_>>();
138 if &*self.workspaces == &workspaces {
142 if !self.workspaces.is_empty() && has_errors {
146 if let FilesWatcher::Client = self.config.files.watcher {
147 let registration_options = lsp_types::DidChangeWatchedFilesRegistrationOptions {
150 .flat_map(ProjectWorkspace::to_roots)
151 .filter(|it| it.is_member)
153 root.include.into_iter().map(|it| format!("{}/**/*.rs", it.display()))
155 .map(|glob_pattern| lsp_types::FileSystemWatcher { glob_pattern, kind: None })
158 let registration = lsp_types::Registration {
159 id: "workspace/didChangeWatchedFiles".to_string(),
160 method: "workspace/didChangeWatchedFiles".to_string(),
161 register_options: Some(serde_json::to_value(registration_options).unwrap()),
163 self.send_request::<lsp_types::request::RegisterCapability>(
164 lsp_types::RegistrationParams { registrations: vec![registration] },
169 let mut change = Change::new();
171 let project_folders = ProjectFolders::new(&workspaces);
173 self.proc_macro_client = match &self.config.proc_macro_srv {
174 None => ProcMacroClient::dummy(),
175 Some((path, args)) => match ProcMacroClient::extern_process(path.into(), args) {
179 "Failed to run proc_macro_srv from path {}, error: {:?}",
183 ProcMacroClient::dummy()
188 let watch = match self.config.files.watcher {
189 FilesWatcher::Client => vec![],
190 FilesWatcher::Notify => project_folders.watch,
192 self.loader.handle.set_config(vfs::loader::Config { load: project_folders.load, watch });
194 // Create crate graph from all the workspaces
196 let mut crate_graph = CrateGraph::default();
197 let vfs = &mut self.vfs.write().0;
198 let loader = &mut self.loader;
199 let mem_docs = &self.mem_docs;
200 let mut load = |path: &AbsPath| {
201 let vfs_path = vfs::VfsPath::from(path.to_path_buf());
202 if !mem_docs.contains_key(&vfs_path) {
203 let contents = loader.handle.load_sync(path);
204 vfs.set_file_contents(vfs_path.clone(), contents);
206 vfs.file_id(&vfs_path)
208 for ws in workspaces.iter() {
209 crate_graph.extend(ws.to_crate_graph(
210 self.config.cargo.target.as_deref(),
211 &self.proc_macro_client,
218 change.set_crate_graph(crate_graph);
220 self.source_root_config = project_folders.source_root_config;
221 self.workspaces = Arc::new(workspaces);
223 self.analysis_host.apply_change(change);
224 self.process_changes();
225 self.reload_flycheck();
226 log::info!("did switch workspaces");
229 fn reload_flycheck(&mut self) {
230 let config = match self.config.flycheck.clone() {
233 self.flycheck = Vec::new();
238 let sender = self.flycheck_sender.clone();
243 .filter_map(|(id, w)| match w {
244 ProjectWorkspace::Cargo { cargo, sysroot: _, rustc: _ } => {
245 Some((id, cargo.workspace_root()))
247 ProjectWorkspace::Json { project, .. } => {
248 // Enable flychecks for json projects if a custom flycheck command was supplied
249 // in the workspace configuration.
251 FlycheckConfig::CustomCommand { .. } => Some((id, project.path())),
257 let sender = sender.clone();
258 FlycheckHandle::spawn(
260 Box::new(move |msg| sender.send(msg).unwrap()),
262 root.to_path_buf().into(),
270 pub(crate) struct ProjectFolders {
271 pub(crate) load: Vec<vfs::loader::Entry>,
272 pub(crate) watch: Vec<usize>,
273 pub(crate) source_root_config: SourceRootConfig,
276 impl ProjectFolders {
277 pub(crate) fn new(workspaces: &[ProjectWorkspace]) -> ProjectFolders {
278 let mut res = ProjectFolders::default();
279 let mut fsc = FileSetConfig::builder();
280 let mut local_filesets = vec![];
282 for root in workspaces.iter().flat_map(|it| it.to_roots()) {
283 let file_set_roots: Vec<VfsPath> =
284 root.include.iter().cloned().map(VfsPath::from).collect();
287 let mut dirs = vfs::loader::Directories::default();
288 dirs.extensions.push("rs".into());
289 dirs.include.extend(root.include);
290 dirs.exclude.extend(root.exclude);
291 vfs::loader::Entry::Directories(dirs)
295 res.watch.push(res.load.len());
297 res.load.push(entry);
300 local_filesets.push(fsc.len());
302 fsc.add_file_set(file_set_roots)
305 let fsc = fsc.build();
306 res.source_root_config = SourceRootConfig { fsc, local_filesets };
312 #[derive(Default, Debug)]
313 pub(crate) struct SourceRootConfig {
314 pub(crate) fsc: FileSetConfig,
315 pub(crate) local_filesets: Vec<usize>,
318 impl SourceRootConfig {
319 pub(crate) fn partition(&self, vfs: &vfs::Vfs) -> Vec<SourceRoot> {
320 let _p = profile::span("SourceRootConfig::partition");
325 .map(|(idx, file_set)| {
326 let is_local = self.local_filesets.contains(&idx);
328 SourceRoot::new_local(file_set)
330 SourceRoot::new_library(file_set)