]> git.proxmox.com Git - rustc.git/blob - src/tools/rust-analyzer/crates/rust-analyzer/src/reload.rs
e47f70fff39e0a3a48a07947d1b925a4c8ad2282
[rustc.git] / src / tools / rust-analyzer / 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("failed to run build scripts".to_string(), Some(error));
200 }
201
202 let workspaces = self
203 .fetch_workspaces_queue
204 .last_op_result()
205 .iter()
206 .filter_map(|res| res.as_ref().ok().cloned())
207 .collect::<Vec<_>>();
208
209 fn eq_ignore_build_data<'a>(
210 left: &'a ProjectWorkspace,
211 right: &'a ProjectWorkspace,
212 ) -> bool {
213 let key = |p: &'a ProjectWorkspace| match p {
214 ProjectWorkspace::Cargo {
215 cargo,
216 sysroot,
217 rustc,
218 rustc_cfg,
219 cfg_overrides,
220
221 build_scripts: _,
222 toolchain: _,
223 } => Some((cargo, sysroot, rustc, rustc_cfg, cfg_overrides)),
224 _ => None,
225 };
226 match (key(left), key(right)) {
227 (Some(lk), Some(rk)) => lk == rk,
228 _ => left == right,
229 }
230 }
231
232 let same_workspaces = workspaces.len() == self.workspaces.len()
233 && workspaces
234 .iter()
235 .zip(self.workspaces.iter())
236 .all(|(l, r)| eq_ignore_build_data(l, r));
237
238 if same_workspaces {
239 let (workspaces, build_scripts) = self.fetch_build_data_queue.last_op_result();
240 if Arc::ptr_eq(workspaces, &self.workspaces) {
241 tracing::debug!("set build scripts to workspaces");
242
243 let workspaces = workspaces
244 .iter()
245 .cloned()
246 .zip(build_scripts)
247 .map(|(mut ws, bs)| {
248 ws.set_build_scripts(bs.as_ref().ok().cloned().unwrap_or_default());
249 ws
250 })
251 .collect::<Vec<_>>();
252
253 // Workspaces are the same, but we've updated build data.
254 self.workspaces = Arc::new(workspaces);
255 } else {
256 tracing::info!("build scripts do not match the version of the active workspace");
257 // Current build scripts do not match the version of the active
258 // workspace, so there's nothing for us to update.
259 return;
260 }
261 } else {
262 tracing::debug!("abandon build scripts for workspaces");
263
264 // Here, we completely changed the workspace (Cargo.toml edit), so
265 // we don't care about build-script results, they are stale.
266 self.workspaces = Arc::new(workspaces)
267 }
268
269 if let FilesWatcher::Client = self.config.files().watcher {
270 let registration_options = lsp_types::DidChangeWatchedFilesRegistrationOptions {
271 watchers: self
272 .workspaces
273 .iter()
274 .flat_map(|ws| ws.to_roots())
275 .filter(|it| it.is_local)
276 .flat_map(|root| {
277 root.include.into_iter().flat_map(|it| {
278 [
279 format!("{}/**/*.rs", it.display()),
280 format!("{}/**/Cargo.toml", it.display()),
281 format!("{}/**/Cargo.lock", it.display()),
282 ]
283 })
284 })
285 .map(|glob_pattern| lsp_types::FileSystemWatcher { glob_pattern, kind: None })
286 .collect(),
287 };
288 let registration = lsp_types::Registration {
289 id: "workspace/didChangeWatchedFiles".to_string(),
290 method: "workspace/didChangeWatchedFiles".to_string(),
291 register_options: Some(serde_json::to_value(registration_options).unwrap()),
292 };
293 self.send_request::<lsp_types::request::RegisterCapability>(
294 lsp_types::RegistrationParams { registrations: vec![registration] },
295 |_, _| (),
296 );
297 }
298
299 let mut change = Change::new();
300
301 let files_config = self.config.files();
302 let project_folders = ProjectFolders::new(&self.workspaces, &files_config.exclude);
303
304 let standalone_server_name =
305 format!("rust-analyzer-proc-macro-srv{}", std::env::consts::EXE_SUFFIX);
306
307 if self.proc_macro_clients.is_empty() {
308 if let Some((path, args)) = self.config.proc_macro_srv() {
309 tracing::info!("Spawning proc-macro servers");
310 self.proc_macro_clients = self
311 .workspaces
312 .iter()
313 .map(|ws| {
314 let mut args = args.clone();
315 let mut path = path.clone();
316
317 if let ProjectWorkspace::Cargo { sysroot, .. }
318 | ProjectWorkspace::Json { sysroot, .. } = ws
319 {
320 tracing::debug!("Found a cargo workspace...");
321 if let Some(sysroot) = sysroot.as_ref() {
322 tracing::debug!("Found a cargo workspace with a sysroot...");
323 let server_path =
324 sysroot.root().join("libexec").join(&standalone_server_name);
325 if std::fs::metadata(&server_path).is_ok() {
326 tracing::debug!(
327 "And the server exists at {}",
328 server_path.display()
329 );
330 path = server_path;
331 args = vec![];
332 } else {
333 tracing::debug!(
334 "And the server does not exist at {}",
335 server_path.display()
336 );
337 }
338 }
339 }
340
341 tracing::info!(?args, "Using proc-macro server at {}", path.display(),);
342 ProcMacroServer::spawn(path.clone(), args.clone()).map_err(|err| {
343 let error = format!(
344 "Failed to run proc-macro server from path {}, error: {:?}",
345 path.display(),
346 err
347 );
348 tracing::error!(error);
349 error
350 })
351 })
352 .collect()
353 };
354 }
355
356 let watch = match files_config.watcher {
357 FilesWatcher::Client => vec![],
358 FilesWatcher::Server => project_folders.watch,
359 };
360 self.vfs_config_version += 1;
361 self.loader.handle.set_config(vfs::loader::Config {
362 load: project_folders.load,
363 watch,
364 version: self.vfs_config_version,
365 });
366
367 // Create crate graph from all the workspaces
368 let crate_graph = {
369 let dummy_replacements = self.config.dummy_replacements();
370
371 let vfs = &mut self.vfs.write().0;
372 let loader = &mut self.loader;
373 let mem_docs = &self.mem_docs;
374 let mut load = move |path: &AbsPath| {
375 let _p = profile::span("GlobalState::load");
376 let vfs_path = vfs::VfsPath::from(path.to_path_buf());
377 if !mem_docs.contains(&vfs_path) {
378 let contents = loader.handle.load_sync(path);
379 vfs.set_file_contents(vfs_path.clone(), contents);
380 }
381 let res = vfs.file_id(&vfs_path);
382 if res.is_none() {
383 tracing::warn!("failed to load {}", path.display())
384 }
385 res
386 };
387
388 let mut crate_graph = CrateGraph::default();
389 for (idx, ws) in self.workspaces.iter().enumerate() {
390 let proc_macro_client = match self.proc_macro_clients.get(idx) {
391 Some(res) => res.as_ref().map_err(|e| &**e),
392 None => Err("Proc macros are disabled"),
393 };
394 let mut load_proc_macro = move |crate_name: &str, path: &AbsPath| {
395 load_proc_macro(
396 proc_macro_client,
397 path,
398 dummy_replacements.get(crate_name).map(|v| &**v).unwrap_or_default(),
399 )
400 };
401 crate_graph.extend(ws.to_crate_graph(&mut load_proc_macro, &mut load));
402 }
403 crate_graph
404 };
405 change.set_crate_graph(crate_graph);
406
407 self.source_root_config = project_folders.source_root_config;
408
409 self.analysis_host.apply_change(change);
410 self.process_changes();
411 self.reload_flycheck();
412 tracing::info!("did switch workspaces");
413 }
414
415 fn fetch_workspace_error(&self) -> Result<(), String> {
416 let mut buf = String::new();
417
418 for ws in self.fetch_workspaces_queue.last_op_result() {
419 if let Err(err) = ws {
420 stdx::format_to!(buf, "rust-analyzer failed to load workspace: {:#}\n", err);
421 }
422 }
423
424 if buf.is_empty() {
425 return Ok(());
426 }
427
428 Err(buf)
429 }
430
431 fn fetch_build_data_error(&self) -> Result<(), String> {
432 let mut buf = String::new();
433
434 for ws in &self.fetch_build_data_queue.last_op_result().1 {
435 match ws {
436 Ok(data) => match data.error() {
437 Some(stderr) => stdx::format_to!(buf, "{:#}\n", stderr),
438 _ => (),
439 },
440 // io errors
441 Err(err) => stdx::format_to!(buf, "{:#}\n", err),
442 }
443 }
444
445 if buf.is_empty() {
446 Ok(())
447 } else {
448 Err(buf)
449 }
450 }
451
452 fn reload_flycheck(&mut self) {
453 let _p = profile::span("GlobalState::reload_flycheck");
454 let config = match self.config.flycheck() {
455 Some(it) => it,
456 None => {
457 self.flycheck = Vec::new();
458 self.diagnostics.clear_check_all();
459 return;
460 }
461 };
462
463 let sender = self.flycheck_sender.clone();
464 self.flycheck = self
465 .workspaces
466 .iter()
467 .enumerate()
468 .filter_map(|(id, w)| match w {
469 ProjectWorkspace::Cargo { cargo, .. } => Some((id, cargo.workspace_root())),
470 ProjectWorkspace::Json { project, .. } => {
471 // Enable flychecks for json projects if a custom flycheck command was supplied
472 // in the workspace configuration.
473 match config {
474 FlycheckConfig::CustomCommand { .. } => Some((id, project.path())),
475 _ => None,
476 }
477 }
478 ProjectWorkspace::DetachedFiles { .. } => None,
479 })
480 .map(|(id, root)| {
481 let sender = sender.clone();
482 FlycheckHandle::spawn(
483 id,
484 Box::new(move |msg| sender.send(msg).unwrap()),
485 config.clone(),
486 root.to_path_buf(),
487 )
488 })
489 .collect();
490 }
491 }
492
493 #[derive(Default)]
494 pub(crate) struct ProjectFolders {
495 pub(crate) load: Vec<vfs::loader::Entry>,
496 pub(crate) watch: Vec<usize>,
497 pub(crate) source_root_config: SourceRootConfig,
498 }
499
500 impl ProjectFolders {
501 pub(crate) fn new(
502 workspaces: &[ProjectWorkspace],
503 global_excludes: &[AbsPathBuf],
504 ) -> ProjectFolders {
505 let mut res = ProjectFolders::default();
506 let mut fsc = FileSetConfig::builder();
507 let mut local_filesets = vec![];
508
509 for root in workspaces.iter().flat_map(|ws| ws.to_roots()) {
510 let file_set_roots: Vec<VfsPath> =
511 root.include.iter().cloned().map(VfsPath::from).collect();
512
513 let entry = {
514 let mut dirs = vfs::loader::Directories::default();
515 dirs.extensions.push("rs".into());
516 dirs.include.extend(root.include);
517 dirs.exclude.extend(root.exclude);
518 for excl in global_excludes {
519 if dirs
520 .include
521 .iter()
522 .any(|incl| incl.starts_with(excl) || excl.starts_with(incl))
523 {
524 dirs.exclude.push(excl.clone());
525 }
526 }
527
528 vfs::loader::Entry::Directories(dirs)
529 };
530
531 if root.is_local {
532 res.watch.push(res.load.len());
533 }
534 res.load.push(entry);
535
536 if root.is_local {
537 local_filesets.push(fsc.len());
538 }
539 fsc.add_file_set(file_set_roots)
540 }
541
542 let fsc = fsc.build();
543 res.source_root_config = SourceRootConfig { fsc, local_filesets };
544
545 res
546 }
547 }
548
549 #[derive(Default, Debug)]
550 pub(crate) struct SourceRootConfig {
551 pub(crate) fsc: FileSetConfig,
552 pub(crate) local_filesets: Vec<usize>,
553 }
554
555 impl SourceRootConfig {
556 pub(crate) fn partition(&self, vfs: &vfs::Vfs) -> Vec<SourceRoot> {
557 let _p = profile::span("SourceRootConfig::partition");
558 self.fsc
559 .partition(vfs)
560 .into_iter()
561 .enumerate()
562 .map(|(idx, file_set)| {
563 let is_local = self.local_filesets.contains(&idx);
564 if is_local {
565 SourceRoot::new_local(file_set)
566 } else {
567 SourceRoot::new_library(file_set)
568 }
569 })
570 .collect()
571 }
572 }
573
574 /// Load the proc-macros for the given lib path, replacing all expanders whose names are in `dummy_replace`
575 /// with an identity dummy expander.
576 pub(crate) fn load_proc_macro(
577 server: Result<&ProcMacroServer, &str>,
578 path: &AbsPath,
579 dummy_replace: &[Box<str>],
580 ) -> ProcMacroLoadResult {
581 let res: Result<Vec<_>, String> = (|| {
582 let dylib = MacroDylib::new(path.to_path_buf())
583 .map_err(|io| format!("Proc-macro dylib loading failed: {io}"))?;
584 let server = server.map_err(ToOwned::to_owned)?;
585 let vec = server.load_dylib(dylib).map_err(|e| format!("{e}"))?;
586 if vec.is_empty() {
587 return Err("proc macro library returned no proc macros".to_string());
588 }
589 Ok(vec
590 .into_iter()
591 .map(|expander| expander_to_proc_macro(expander, dummy_replace))
592 .collect())
593 })();
594 return match res {
595 Ok(proc_macros) => {
596 tracing::info!(
597 "Loaded proc-macros for {}: {:?}",
598 path.display(),
599 proc_macros.iter().map(|it| it.name.clone()).collect::<Vec<_>>()
600 );
601 Ok(proc_macros)
602 }
603 Err(e) => {
604 tracing::warn!("proc-macro loading for {} failed: {e}", path.display());
605 Err(e)
606 }
607 };
608
609 fn expander_to_proc_macro(
610 expander: proc_macro_api::ProcMacro,
611 dummy_replace: &[Box<str>],
612 ) -> ProcMacro {
613 let name = SmolStr::from(expander.name());
614 let kind = match expander.kind() {
615 proc_macro_api::ProcMacroKind::CustomDerive => ProcMacroKind::CustomDerive,
616 proc_macro_api::ProcMacroKind::FuncLike => ProcMacroKind::FuncLike,
617 proc_macro_api::ProcMacroKind::Attr => ProcMacroKind::Attr,
618 };
619 let expander: Arc<dyn ProcMacroExpander> =
620 if dummy_replace.iter().any(|replace| &**replace == name) {
621 match kind {
622 ProcMacroKind::Attr => Arc::new(IdentityExpander),
623 _ => Arc::new(EmptyExpander),
624 }
625 } else {
626 Arc::new(Expander(expander))
627 };
628 ProcMacro { name, kind, expander }
629 }
630
631 #[derive(Debug)]
632 struct Expander(proc_macro_api::ProcMacro);
633
634 impl ProcMacroExpander for Expander {
635 fn expand(
636 &self,
637 subtree: &tt::Subtree,
638 attrs: Option<&tt::Subtree>,
639 env: &Env,
640 ) -> Result<tt::Subtree, ProcMacroExpansionError> {
641 let env = env.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
642 match self.0.expand(subtree, attrs, env) {
643 Ok(Ok(subtree)) => Ok(subtree),
644 Ok(Err(err)) => Err(ProcMacroExpansionError::Panic(err.0)),
645 Err(err) => Err(ProcMacroExpansionError::System(err.to_string())),
646 }
647 }
648 }
649
650 /// Dummy identity expander, used for attribute proc-macros that are deliberately ignored by the user.
651 #[derive(Debug)]
652 struct IdentityExpander;
653
654 impl ProcMacroExpander for IdentityExpander {
655 fn expand(
656 &self,
657 subtree: &tt::Subtree,
658 _: Option<&tt::Subtree>,
659 _: &Env,
660 ) -> Result<tt::Subtree, ProcMacroExpansionError> {
661 Ok(subtree.clone())
662 }
663 }
664
665 /// Empty expander, used for proc-macros that are deliberately ignored by the user.
666 #[derive(Debug)]
667 struct EmptyExpander;
668
669 impl ProcMacroExpander for EmptyExpander {
670 fn expand(
671 &self,
672 _: &tt::Subtree,
673 _: Option<&tt::Subtree>,
674 _: &Env,
675 ) -> Result<tt::Subtree, ProcMacroExpansionError> {
676 Ok(tt::Subtree::default())
677 }
678 }
679 }
680
681 pub(crate) fn should_refresh_for_change(path: &AbsPath, change_kind: ChangeKind) -> bool {
682 const IMPLICIT_TARGET_FILES: &[&str] = &["build.rs", "src/main.rs", "src/lib.rs"];
683 const IMPLICIT_TARGET_DIRS: &[&str] = &["src/bin", "examples", "tests", "benches"];
684
685 let file_name = match path.file_name().unwrap_or_default().to_str() {
686 Some(it) => it,
687 None => return false,
688 };
689
690 if let "Cargo.toml" | "Cargo.lock" = file_name {
691 return true;
692 }
693 if change_kind == ChangeKind::Modify {
694 return false;
695 }
696
697 // .cargo/config{.toml}
698 if path.extension().unwrap_or_default() != "rs" {
699 let is_cargo_config = matches!(file_name, "config.toml" | "config")
700 && path.parent().map(|parent| parent.as_ref().ends_with(".cargo")).unwrap_or(false);
701 return is_cargo_config;
702 }
703
704 if IMPLICIT_TARGET_FILES.iter().any(|it| path.as_ref().ends_with(it)) {
705 return true;
706 }
707 let parent = match path.parent() {
708 Some(it) => it,
709 None => return false,
710 };
711 if IMPLICIT_TARGET_DIRS.iter().any(|it| parent.as_ref().ends_with(it)) {
712 return true;
713 }
714 if file_name == "main.rs" {
715 let grand_parent = match parent.parent() {
716 Some(it) => it,
717 None => return false,
718 };
719 if IMPLICIT_TARGET_DIRS.iter().any(|it| grand_parent.as_ref().ends_with(it)) {
720 return true;
721 }
722 }
723 false
724 }