]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/reload.rs
c90291eb5e29ad337dba58b8117eeed2bffbf76d
[rust.git] / crates / rust-analyzer / src / reload.rs
1 //! Project loading & configuration updates.
2 //!
3 //! This is quite tricky. The main problem is time and changes -- there's no
4 //! fixed "project" rust-analyzer is working with, "current project" is itself
5 //! mutable state. For example, when the user edits `Cargo.toml` by adding a new
6 //! dependency, project model changes. What's more, switching project model is
7 //! not instantaneous -- it takes time to run `cargo metadata` and (for proc
8 //! macros) `cargo check`.
9 //!
10 //! The main guiding principle here is, as elsewhere in rust-analyzer,
11 //! robustness. We try not to assume that the project model exists or is
12 //! correct. Instead, we try to provide a best-effort service. Even if the
13 //! project is currently loading and we don't have a full project model, we
14 //! still want to respond to various  requests.
15 use std::{mem, sync::Arc};
16
17 use flycheck::{FlycheckConfig, FlycheckHandle};
18 use hir::db::DefDatabase;
19 use ide::Change;
20 use ide_db::base_db::{
21     CrateGraph, Env, ProcMacro, ProcMacroExpander, ProcMacroExpansionError, ProcMacroKind,
22     ProcMacroLoadResult, SourceRoot, VfsPath,
23 };
24 use proc_macro_api::{MacroDylib, ProcMacroServer};
25 use project_model::{ProjectWorkspace, WorkspaceBuildScripts};
26 use syntax::SmolStr;
27 use vfs::{file_set::FileSetConfig, AbsPath, AbsPathBuf, ChangeKind};
28
29 use crate::{
30     config::{Config, FilesWatcher, LinkedProject},
31     global_state::GlobalState,
32     lsp_ext,
33     main_loop::Task,
34     op_queue::Cause,
35 };
36
37 #[derive(Debug)]
38 pub(crate) enum ProjectWorkspaceProgress {
39     Begin,
40     Report(String),
41     End(Vec<anyhow::Result<ProjectWorkspace>>),
42 }
43
44 #[derive(Debug)]
45 pub(crate) enum BuildDataProgress {
46     Begin,
47     Report(String),
48     End((Arc<Vec<ProjectWorkspace>>, Vec<anyhow::Result<WorkspaceBuildScripts>>)),
49 }
50
51 impl GlobalState {
52     pub(crate) fn is_quiescent(&self) -> bool {
53         !(self.fetch_workspaces_queue.op_in_progress()
54             || self.fetch_build_data_queue.op_in_progress()
55             || self.vfs_progress_config_version < self.vfs_config_version
56             || self.vfs_progress_n_done < self.vfs_progress_n_total)
57     }
58
59     pub(crate) fn update_configuration(&mut self, config: Config) {
60         let _p = profile::span("GlobalState::update_configuration");
61         let old_config = mem::replace(&mut self.config, Arc::new(config));
62         if self.config.lru_capacity() != old_config.lru_capacity() {
63             self.analysis_host.update_lru_capacity(self.config.lru_capacity());
64         }
65         if self.config.linked_projects() != old_config.linked_projects() {
66             self.fetch_workspaces_queue.request_op("linked projects changed".to_string())
67         } else if self.config.flycheck() != old_config.flycheck() {
68             self.reload_flycheck();
69         }
70
71         if self.analysis_host.raw_database().enable_proc_attr_macros()
72             != self.config.expand_proc_attr_macros()
73         {
74             self.analysis_host
75                 .raw_database_mut()
76                 .set_enable_proc_attr_macros(self.config.expand_proc_attr_macros());
77         }
78     }
79
80     pub(crate) fn current_status(&self) -> lsp_ext::ServerStatusParams {
81         let mut status = lsp_ext::ServerStatusParams {
82             health: lsp_ext::Health::Ok,
83             quiescent: self.is_quiescent(),
84             message: None,
85         };
86
87         if self.proc_macro_changed {
88             status.health = lsp_ext::Health::Warning;
89             status.message =
90                 Some("Reload required due to source changes of a procedural macro.".into())
91         }
92         if let Err(_) = self.fetch_build_data_error() {
93             status.health = lsp_ext::Health::Warning;
94             status.message =
95                 Some("Failed to run build scripts of some packages, check the logs.".to_string());
96         }
97         if !self.config.cargo_autoreload()
98             && self.is_quiescent()
99             && self.fetch_workspaces_queue.op_requested()
100         {
101             status.health = lsp_ext::Health::Warning;
102             status.message = Some("Workspace reload required".to_string())
103         }
104
105         if let Err(error) = self.fetch_workspace_error() {
106             status.health = lsp_ext::Health::Error;
107             status.message = Some(error)
108         }
109         status
110     }
111
112     pub(crate) fn fetch_workspaces(&mut self, cause: Cause) {
113         tracing::info!(%cause, "will fetch workspaces");
114
115         self.task_pool.handle.spawn_with_sender({
116             let linked_projects = self.config.linked_projects();
117             let detached_files = self.config.detached_files().to_vec();
118             let cargo_config = self.config.cargo();
119
120             move |sender| {
121                 let progress = {
122                     let sender = sender.clone();
123                     move |msg| {
124                         sender
125                             .send(Task::FetchWorkspace(ProjectWorkspaceProgress::Report(msg)))
126                             .unwrap()
127                     }
128                 };
129
130                 sender.send(Task::FetchWorkspace(ProjectWorkspaceProgress::Begin)).unwrap();
131
132                 let mut workspaces = linked_projects
133                     .iter()
134                     .map(|project| match project {
135                         LinkedProject::ProjectManifest(manifest) => {
136                             project_model::ProjectWorkspace::load(
137                                 manifest.clone(),
138                                 &cargo_config,
139                                 &progress,
140                             )
141                         }
142                         LinkedProject::InlineJsonProject(it) => {
143                             project_model::ProjectWorkspace::load_inline(
144                                 it.clone(),
145                                 cargo_config.target.as_deref(),
146                             )
147                         }
148                     })
149                     .collect::<Vec<_>>();
150
151                 if !detached_files.is_empty() {
152                     workspaces
153                         .push(project_model::ProjectWorkspace::load_detached_files(detached_files));
154                 }
155
156                 tracing::info!("did fetch workspaces {:?}", workspaces);
157                 sender
158                     .send(Task::FetchWorkspace(ProjectWorkspaceProgress::End(workspaces)))
159                     .unwrap();
160             }
161         });
162     }
163
164     pub(crate) fn fetch_build_data(&mut self, cause: Cause) {
165         tracing::info!(%cause, "will fetch build data");
166         let workspaces = Arc::clone(&self.workspaces);
167         let config = self.config.cargo();
168         self.task_pool.handle.spawn_with_sender(move |sender| {
169             sender.send(Task::FetchBuildData(BuildDataProgress::Begin)).unwrap();
170
171             let progress = {
172                 let sender = sender.clone();
173                 move |msg| {
174                     sender.send(Task::FetchBuildData(BuildDataProgress::Report(msg))).unwrap()
175                 }
176             };
177             let mut res = Vec::new();
178             for ws in workspaces.iter() {
179                 res.push(ws.run_build_scripts(&config, &progress));
180             }
181             sender.send(Task::FetchBuildData(BuildDataProgress::End((workspaces, res)))).unwrap();
182         });
183     }
184
185     pub(crate) fn switch_workspaces(&mut self, cause: Cause) {
186         let _p = profile::span("GlobalState::switch_workspaces");
187         tracing::info!(%cause, "will switch workspaces");
188
189         if let Err(error_message) = self.fetch_workspace_error() {
190             self.show_and_log_error(error_message, None);
191             if !self.workspaces.is_empty() {
192                 // It only makes sense to switch to a partially broken workspace
193                 // if we don't have any workspace at all yet.
194                 return;
195             }
196         }
197
198         if let Err(error) = self.fetch_build_data_error() {
199             self.show_and_log_error(
200                 "rust-analyzer failed to run build scripts".to_string(),
201                 Some(error),
202             );
203         }
204
205         let workspaces = self
206             .fetch_workspaces_queue
207             .last_op_result()
208             .iter()
209             .filter_map(|res| res.as_ref().ok().cloned())
210             .collect::<Vec<_>>();
211
212         fn eq_ignore_build_data<'a>(
213             left: &'a ProjectWorkspace,
214             right: &'a ProjectWorkspace,
215         ) -> bool {
216             let key = |p: &'a ProjectWorkspace| match p {
217                 ProjectWorkspace::Cargo {
218                     cargo,
219                     sysroot,
220                     rustc,
221                     rustc_cfg,
222                     cfg_overrides,
223
224                     build_scripts: _,
225                 } => Some((cargo, sysroot, rustc, rustc_cfg, cfg_overrides)),
226                 _ => None,
227             };
228             match (key(left), key(right)) {
229                 (Some(lk), Some(rk)) => lk == rk,
230                 _ => left == right,
231             }
232         }
233
234         let same_workspaces = workspaces.len() == self.workspaces.len()
235             && workspaces
236                 .iter()
237                 .zip(self.workspaces.iter())
238                 .all(|(l, r)| eq_ignore_build_data(l, r));
239
240         if same_workspaces {
241             let (workspaces, build_scripts) = self.fetch_build_data_queue.last_op_result();
242             if Arc::ptr_eq(workspaces, &self.workspaces) {
243                 tracing::debug!("set build scripts to workspaces");
244
245                 let workspaces = workspaces
246                     .iter()
247                     .cloned()
248                     .zip(build_scripts)
249                     .map(|(mut ws, bs)| {
250                         ws.set_build_scripts(bs.as_ref().ok().cloned().unwrap_or_default());
251                         ws
252                     })
253                     .collect::<Vec<_>>();
254
255                 // Workspaces are the same, but we've updated build data.
256                 self.workspaces = Arc::new(workspaces);
257             } else {
258                 tracing::info!("build scripts do not match the version of the active workspace");
259                 // Current build scripts do not match the version of the active
260                 // workspace, so there's nothing for us to update.
261                 return;
262             }
263         } else {
264             tracing::debug!("abandon build scripts for workspaces");
265
266             // Here, we completely changed the workspace (Cargo.toml edit), so
267             // we don't care about build-script results, they are stale.
268             self.workspaces = Arc::new(workspaces)
269         }
270
271         if let FilesWatcher::Client = self.config.files().watcher {
272             let registration_options = lsp_types::DidChangeWatchedFilesRegistrationOptions {
273                 watchers: self
274                     .workspaces
275                     .iter()
276                     .flat_map(|ws| ws.to_roots())
277                     .filter(|it| it.is_local)
278                     .flat_map(|root| {
279                         root.include.into_iter().flat_map(|it| {
280                             [
281                                 format!("{}/**/*.rs", it.display()),
282                                 format!("{}/**/Cargo.toml", it.display()),
283                                 format!("{}/**/Cargo.lock", it.display()),
284                             ]
285                         })
286                     })
287                     .map(|glob_pattern| lsp_types::FileSystemWatcher { glob_pattern, kind: None })
288                     .collect(),
289             };
290             let registration = lsp_types::Registration {
291                 id: "workspace/didChangeWatchedFiles".to_string(),
292                 method: "workspace/didChangeWatchedFiles".to_string(),
293                 register_options: Some(serde_json::to_value(registration_options).unwrap()),
294             };
295             self.send_request::<lsp_types::request::RegisterCapability>(
296                 lsp_types::RegistrationParams { registrations: vec![registration] },
297                 |_, _| (),
298             );
299         }
300
301         let mut change = Change::new();
302
303         let files_config = self.config.files();
304         let project_folders = ProjectFolders::new(&self.workspaces, &files_config.exclude);
305
306         let standalone_server_name =
307             format!("rust-analyzer-proc-macro-srv{}", std::env::consts::EXE_SUFFIX);
308
309         if self.proc_macro_clients.is_empty() {
310             if let Some((path, args)) = self.config.proc_macro_srv() {
311                 self.proc_macro_clients = self
312                     .workspaces
313                     .iter()
314                     .map(|ws| {
315                         let mut args = args.clone();
316                         let mut path = path.clone();
317
318                         if let ProjectWorkspace::Cargo { sysroot, .. } = ws {
319                             tracing::info!("Found a cargo workspace...");
320                             if let Some(sysroot) = sysroot.as_ref() {
321                                 tracing::info!("Found a cargo workspace with a sysroot...");
322                                 let server_path =
323                                     sysroot.root().join("libexec").join(&standalone_server_name);
324                                 if std::fs::metadata(&server_path).is_ok() {
325                                     tracing::info!(
326                                         "And the server exists at {}",
327                                         server_path.display()
328                                     );
329                                     path = server_path;
330                                     args = vec![];
331                                 } else {
332                                     tracing::info!(
333                                         "And the server does not exist at {}",
334                                         server_path.display()
335                                     );
336                                 }
337                             }
338                         }
339
340                         tracing::info!(
341                             "Using proc-macro server at {} with args {:?}",
342                             path.display(),
343                             args
344                         );
345                         ProcMacroServer::spawn(path.clone(), args.clone()).map_err(|err| {
346                             let error = format!(
347                                 "Failed to run proc_macro_srv from path {}, error: {:?}",
348                                 path.display(),
349                                 err
350                             );
351                             tracing::error!(error);
352                             error
353                         })
354                     })
355                     .collect();
356             }
357         }
358
359         let watch = match files_config.watcher {
360             FilesWatcher::Client => vec![],
361             FilesWatcher::Server => project_folders.watch,
362         };
363         self.vfs_config_version += 1;
364         self.loader.handle.set_config(vfs::loader::Config {
365             load: project_folders.load,
366             watch,
367             version: self.vfs_config_version,
368         });
369
370         // Create crate graph from all the workspaces
371         let crate_graph = {
372             let dummy_replacements = self.config.dummy_replacements();
373
374             let vfs = &mut self.vfs.write().0;
375             let loader = &mut self.loader;
376             let mem_docs = &self.mem_docs;
377             let mut load = move |path: &AbsPath| {
378                 let _p = profile::span("GlobalState::load");
379                 let vfs_path = vfs::VfsPath::from(path.to_path_buf());
380                 if !mem_docs.contains(&vfs_path) {
381                     let contents = loader.handle.load_sync(path);
382                     vfs.set_file_contents(vfs_path.clone(), contents);
383                 }
384                 let res = vfs.file_id(&vfs_path);
385                 if res.is_none() {
386                     tracing::warn!("failed to load {}", path.display())
387                 }
388                 res
389             };
390
391             let mut crate_graph = CrateGraph::default();
392             for (idx, ws) in self.workspaces.iter().enumerate() {
393                 let proc_macro_client = match self.proc_macro_clients.get(idx) {
394                     Some(res) => res.as_ref().map_err(|e| &**e),
395                     None => Err("Proc macros are disabled"),
396                 };
397                 let mut load_proc_macro = move |crate_name: &str, path: &AbsPath| {
398                     load_proc_macro(
399                         proc_macro_client,
400                         path,
401                         dummy_replacements.get(crate_name).map(|v| &**v).unwrap_or_default(),
402                     )
403                 };
404                 crate_graph.extend(ws.to_crate_graph(&mut load_proc_macro, &mut load));
405             }
406             crate_graph
407         };
408         change.set_crate_graph(crate_graph);
409
410         self.source_root_config = project_folders.source_root_config;
411
412         self.analysis_host.apply_change(change);
413         self.process_changes();
414         self.reload_flycheck();
415         tracing::info!("did switch workspaces");
416     }
417
418     fn fetch_workspace_error(&self) -> Result<(), String> {
419         let mut buf = String::new();
420
421         for ws in self.fetch_workspaces_queue.last_op_result() {
422             if let Err(err) = ws {
423                 stdx::format_to!(buf, "rust-analyzer failed to load workspace: {:#}\n", err);
424             }
425         }
426
427         if buf.is_empty() {
428             return Ok(());
429         }
430
431         Err(buf)
432     }
433
434     fn fetch_build_data_error(&self) -> Result<(), String> {
435         let mut buf = String::new();
436
437         for ws in &self.fetch_build_data_queue.last_op_result().1 {
438             match ws {
439                 Ok(data) => match data.error() {
440                     Some(stderr) => stdx::format_to!(buf, "{:#}\n", stderr),
441                     _ => (),
442                 },
443                 // io errors
444                 Err(err) => stdx::format_to!(buf, "{:#}\n", err),
445             }
446         }
447
448         if buf.is_empty() {
449             Ok(())
450         } else {
451             Err(buf)
452         }
453     }
454
455     fn reload_flycheck(&mut self) {
456         let _p = profile::span("GlobalState::reload_flycheck");
457         let config = match self.config.flycheck() {
458             Some(it) => it,
459             None => {
460                 self.flycheck = Vec::new();
461                 self.diagnostics.clear_check_all();
462                 return;
463             }
464         };
465
466         let sender = self.flycheck_sender.clone();
467         self.flycheck = self
468             .workspaces
469             .iter()
470             .enumerate()
471             .filter_map(|(id, w)| match w {
472                 ProjectWorkspace::Cargo { cargo, .. } => Some((id, cargo.workspace_root())),
473                 ProjectWorkspace::Json { project, .. } => {
474                     // Enable flychecks for json projects if a custom flycheck command was supplied
475                     // in the workspace configuration.
476                     match config {
477                         FlycheckConfig::CustomCommand { .. } => Some((id, project.path())),
478                         _ => None,
479                     }
480                 }
481                 ProjectWorkspace::DetachedFiles { .. } => None,
482             })
483             .map(|(id, root)| {
484                 let sender = sender.clone();
485                 FlycheckHandle::spawn(
486                     id,
487                     Box::new(move |msg| sender.send(msg).unwrap()),
488                     config.clone(),
489                     root.to_path_buf(),
490                 )
491             })
492             .collect();
493     }
494 }
495
496 #[derive(Default)]
497 pub(crate) struct ProjectFolders {
498     pub(crate) load: Vec<vfs::loader::Entry>,
499     pub(crate) watch: Vec<usize>,
500     pub(crate) source_root_config: SourceRootConfig,
501 }
502
503 impl ProjectFolders {
504     pub(crate) fn new(
505         workspaces: &[ProjectWorkspace],
506         global_excludes: &[AbsPathBuf],
507     ) -> ProjectFolders {
508         let mut res = ProjectFolders::default();
509         let mut fsc = FileSetConfig::builder();
510         let mut local_filesets = vec![];
511
512         for root in workspaces.iter().flat_map(|ws| ws.to_roots()) {
513             let file_set_roots: Vec<VfsPath> =
514                 root.include.iter().cloned().map(VfsPath::from).collect();
515
516             let entry = {
517                 let mut dirs = vfs::loader::Directories::default();
518                 dirs.extensions.push("rs".into());
519                 dirs.include.extend(root.include);
520                 dirs.exclude.extend(root.exclude);
521                 for excl in global_excludes {
522                     if dirs
523                         .include
524                         .iter()
525                         .any(|incl| incl.starts_with(excl) || excl.starts_with(incl))
526                     {
527                         dirs.exclude.push(excl.clone());
528                     }
529                 }
530
531                 vfs::loader::Entry::Directories(dirs)
532             };
533
534             if root.is_local {
535                 res.watch.push(res.load.len());
536             }
537             res.load.push(entry);
538
539             if root.is_local {
540                 local_filesets.push(fsc.len());
541             }
542             fsc.add_file_set(file_set_roots)
543         }
544
545         let fsc = fsc.build();
546         res.source_root_config = SourceRootConfig { fsc, local_filesets };
547
548         res
549     }
550 }
551
552 #[derive(Default, Debug)]
553 pub(crate) struct SourceRootConfig {
554     pub(crate) fsc: FileSetConfig,
555     pub(crate) local_filesets: Vec<usize>,
556 }
557
558 impl SourceRootConfig {
559     pub(crate) fn partition(&self, vfs: &vfs::Vfs) -> Vec<SourceRoot> {
560         let _p = profile::span("SourceRootConfig::partition");
561         self.fsc
562             .partition(vfs)
563             .into_iter()
564             .enumerate()
565             .map(|(idx, file_set)| {
566                 let is_local = self.local_filesets.contains(&idx);
567                 if is_local {
568                     SourceRoot::new_local(file_set)
569                 } else {
570                     SourceRoot::new_library(file_set)
571                 }
572             })
573             .collect()
574     }
575 }
576
577 /// Load the proc-macros for the given lib path, replacing all expanders whose names are in `dummy_replace`
578 /// with an identity dummy expander.
579 pub(crate) fn load_proc_macro(
580     server: Result<&ProcMacroServer, &str>,
581     path: &AbsPath,
582     dummy_replace: &[Box<str>],
583 ) -> ProcMacroLoadResult {
584     let res: Result<Vec<_>, String> = (|| {
585         let dylib = MacroDylib::new(path.to_path_buf())
586             .map_err(|io| format!("Proc-macro dylib loading failed: {io}"))?;
587         let server = server.map_err(ToOwned::to_owned)?;
588         let vec = server.load_dylib(dylib).map_err(|e| format!("{e}"))?;
589         if vec.is_empty() {
590             return Err("proc macro library returned no proc macros".to_string());
591         }
592         Ok(vec
593             .into_iter()
594             .map(|expander| expander_to_proc_macro(expander, dummy_replace))
595             .collect())
596     })();
597     return match res {
598         Ok(proc_macros) => {
599             tracing::info!(
600                 "Loaded proc-macros for {}: {:?}",
601                 path.display(),
602                 proc_macros.iter().map(|it| it.name.clone()).collect::<Vec<_>>()
603             );
604             Ok(proc_macros)
605         }
606         Err(e) => {
607             tracing::warn!("proc-macro loading for {} failed: {e}", path.display());
608             Err(e)
609         }
610     };
611
612     fn expander_to_proc_macro(
613         expander: proc_macro_api::ProcMacro,
614         dummy_replace: &[Box<str>],
615     ) -> ProcMacro {
616         let name = SmolStr::from(expander.name());
617         let kind = match expander.kind() {
618             proc_macro_api::ProcMacroKind::CustomDerive => ProcMacroKind::CustomDerive,
619             proc_macro_api::ProcMacroKind::FuncLike => ProcMacroKind::FuncLike,
620             proc_macro_api::ProcMacroKind::Attr => ProcMacroKind::Attr,
621         };
622         let expander: Arc<dyn ProcMacroExpander> =
623             if dummy_replace.iter().any(|replace| &**replace == name) {
624                 match kind {
625                     ProcMacroKind::Attr => Arc::new(IdentityExpander),
626                     _ => Arc::new(EmptyExpander),
627                 }
628             } else {
629                 Arc::new(Expander(expander))
630             };
631         ProcMacro { name, kind, expander }
632     }
633
634     #[derive(Debug)]
635     struct Expander(proc_macro_api::ProcMacro);
636
637     impl ProcMacroExpander for Expander {
638         fn expand(
639             &self,
640             subtree: &tt::Subtree,
641             attrs: Option<&tt::Subtree>,
642             env: &Env,
643         ) -> Result<tt::Subtree, ProcMacroExpansionError> {
644             let env = env.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
645             match self.0.expand(subtree, attrs, env) {
646                 Ok(Ok(subtree)) => Ok(subtree),
647                 Ok(Err(err)) => Err(ProcMacroExpansionError::Panic(err.0)),
648                 Err(err) => Err(ProcMacroExpansionError::System(err.to_string())),
649             }
650         }
651     }
652
653     /// Dummy identity expander, used for attribute proc-macros that are deliberately ignored by the user.
654     #[derive(Debug)]
655     struct IdentityExpander;
656
657     impl ProcMacroExpander for IdentityExpander {
658         fn expand(
659             &self,
660             subtree: &tt::Subtree,
661             _: Option<&tt::Subtree>,
662             _: &Env,
663         ) -> Result<tt::Subtree, ProcMacroExpansionError> {
664             Ok(subtree.clone())
665         }
666     }
667
668     /// Empty expander, used for proc-macros that are deliberately ignored by the user.
669     #[derive(Debug)]
670     struct EmptyExpander;
671
672     impl ProcMacroExpander for EmptyExpander {
673         fn expand(
674             &self,
675             _: &tt::Subtree,
676             _: Option<&tt::Subtree>,
677             _: &Env,
678         ) -> Result<tt::Subtree, ProcMacroExpansionError> {
679             Ok(tt::Subtree::default())
680         }
681     }
682 }
683
684 pub(crate) fn should_refresh_for_change(path: &AbsPath, change_kind: ChangeKind) -> bool {
685     const IMPLICIT_TARGET_FILES: &[&str] = &["build.rs", "src/main.rs", "src/lib.rs"];
686     const IMPLICIT_TARGET_DIRS: &[&str] = &["src/bin", "examples", "tests", "benches"];
687     let file_name = path.file_name().unwrap_or_default();
688
689     if file_name == "Cargo.toml" || file_name == "Cargo.lock" {
690         return true;
691     }
692     if change_kind == ChangeKind::Modify {
693         return false;
694     }
695     if path.extension().unwrap_or_default() != "rs" {
696         if (file_name == "config.toml" || file_name == "config")
697             && path.parent().map(|parent| parent.as_ref().ends_with(".cargo")) == Some(true)
698         {
699             return true;
700         }
701         return false;
702     }
703     if IMPLICIT_TARGET_FILES.iter().any(|it| path.as_ref().ends_with(it)) {
704         return true;
705     }
706     let parent = match path.parent() {
707         Some(it) => it,
708         None => return false,
709     };
710     if IMPLICIT_TARGET_DIRS.iter().any(|it| parent.as_ref().ends_with(it)) {
711         return true;
712     }
713     if file_name == "main.rs" {
714         let grand_parent = match parent.parent() {
715             Some(it) => it,
716             None => return false,
717         };
718         if IMPLICIT_TARGET_DIRS.iter().any(|it| grand_parent.as_ref().ends_with(it)) {
719             return true;
720         }
721     }
722     false
723 }