cargo/core/compiler/build_runner/
mod.rs

1//! [`BuildRunner`] is the mutable state used during the build process.
2
3use std::collections::{HashMap, HashSet};
4use std::path::{Path, PathBuf};
5use std::sync::{Arc, Mutex};
6
7use crate::core::PackageId;
8use crate::core::compiler::compilation::{self, UnitOutput};
9use crate::core::compiler::{self, Unit, artifact};
10use crate::util::cache_lock::CacheLockMode;
11use crate::util::errors::CargoResult;
12use annotate_snippets::{Level, Message};
13use anyhow::{Context as _, bail};
14use cargo_util::paths;
15use filetime::FileTime;
16use itertools::Itertools;
17use jobserver::Client;
18
19use super::custom_build::{self, BuildDeps, BuildScriptOutputs, BuildScripts};
20use super::fingerprint::{Checksum, Fingerprint};
21use super::job_queue::JobQueue;
22use super::layout::Layout;
23use super::lto::Lto;
24use super::unit_graph::UnitDep;
25use super::{
26    BuildContext, Compilation, CompileKind, CompileMode, Executor, FileFlavor, RustDocFingerprint,
27};
28
29mod compilation_files;
30use self::compilation_files::CompilationFiles;
31pub use self::compilation_files::{Metadata, OutputFile, UnitHash};
32
33/// Collection of all the stuff that is needed to perform a build.
34///
35/// Different from the [`BuildContext`], `Context` is a _mutable_ state used
36/// throughout the entire build process. Everything is coordinated through this.
37///
38/// [`BuildContext`]: crate::core::compiler::BuildContext
39pub struct BuildRunner<'a, 'gctx> {
40    /// Mostly static information about the build task.
41    pub bcx: &'a BuildContext<'a, 'gctx>,
42    /// A large collection of information about the result of the entire compilation.
43    pub compilation: Compilation<'gctx>,
44    /// Output from build scripts, updated after each build script runs.
45    pub build_script_outputs: Arc<Mutex<BuildScriptOutputs>>,
46    /// Dependencies (like rerun-if-changed) declared by a build script.
47    /// This is *only* populated from the output from previous runs.
48    /// If the build script hasn't ever been run, then it must be run.
49    pub build_explicit_deps: HashMap<Unit, BuildDeps>,
50    /// Fingerprints used to detect if a unit is out-of-date.
51    pub fingerprints: HashMap<Unit, Arc<Fingerprint>>,
52    /// Cache of file mtimes to reduce filesystem hits.
53    pub mtime_cache: HashMap<PathBuf, FileTime>,
54    /// Cache of file checksums to reduce filesystem reads.
55    pub checksum_cache: HashMap<PathBuf, Checksum>,
56    /// A set used to track which units have been compiled.
57    /// A unit may appear in the job graph multiple times as a dependency of
58    /// multiple packages, but it only needs to run once.
59    pub compiled: HashSet<Unit>,
60    /// Linking information for each `Unit`.
61    /// See `build_map` for details.
62    pub build_scripts: HashMap<Unit, Arc<BuildScripts>>,
63    /// Job server client to manage concurrency with other processes.
64    pub jobserver: Client,
65    /// "Primary" packages are the ones the user selected on the command-line
66    /// with `-p` flags. If no flags are specified, then it is the defaults
67    /// based on the current directory and the default workspace members.
68    primary_packages: HashSet<PackageId>,
69    /// An abstraction of the files and directories that will be generated by
70    /// the compilation. This is `None` until after `unit_dependencies` has
71    /// been computed.
72    files: Option<CompilationFiles<'a, 'gctx>>,
73
74    /// A set of units which are compiling rlibs and are expected to produce
75    /// metadata files in addition to the rlib itself.
76    rmeta_required: HashSet<Unit>,
77
78    /// Map of the LTO-status of each unit. This indicates what sort of
79    /// compilation is happening (only object, only bitcode, both, etc), and is
80    /// precalculated early on.
81    pub lto: HashMap<Unit, Lto>,
82
83    /// Map of Doc/Docscrape units to metadata for their -Cmetadata flag.
84    /// See `Context::find_metadata_units` for more details.
85    pub metadata_for_doc_units: HashMap<Unit, Metadata>,
86
87    /// Set of metadata of Docscrape units that fail before completion, e.g.
88    /// because the target has a type error. This is in an Arc<Mutex<..>>
89    /// because it is continuously updated as the job progresses.
90    pub failed_scrape_units: Arc<Mutex<HashSet<UnitHash>>>,
91}
92
93impl<'a, 'gctx> BuildRunner<'a, 'gctx> {
94    pub fn new(bcx: &'a BuildContext<'a, 'gctx>) -> CargoResult<Self> {
95        // Load up the jobserver that we'll use to manage our parallelism. This
96        // is the same as the GNU make implementation of a jobserver, and
97        // intentionally so! It's hoped that we can interact with GNU make and
98        // all share the same jobserver.
99        //
100        // Note that if we don't have a jobserver in our environment then we
101        // create our own, and we create it with `n` tokens, but immediately
102        // acquire one, because one token is ourself, a running process.
103        let jobserver = match bcx.gctx.jobserver_from_env() {
104            Some(c) => c.clone(),
105            None => {
106                let client =
107                    Client::new(bcx.jobs() as usize).context("failed to create jobserver")?;
108                client.acquire_raw()?;
109                client
110            }
111        };
112
113        Ok(Self {
114            bcx,
115            compilation: Compilation::new(bcx)?,
116            build_script_outputs: Arc::new(Mutex::new(BuildScriptOutputs::default())),
117            fingerprints: HashMap::new(),
118            mtime_cache: HashMap::new(),
119            checksum_cache: HashMap::new(),
120            compiled: HashSet::new(),
121            build_scripts: HashMap::new(),
122            build_explicit_deps: HashMap::new(),
123            jobserver,
124            primary_packages: HashSet::new(),
125            files: None,
126            rmeta_required: HashSet::new(),
127            lto: HashMap::new(),
128            metadata_for_doc_units: HashMap::new(),
129            failed_scrape_units: Arc::new(Mutex::new(HashSet::new())),
130        })
131    }
132
133    /// Dry-run the compilation without actually running it.
134    ///
135    /// This is expected to collect information like the location of output artifacts.
136    /// Please keep in sync with non-compilation part in [`BuildRunner::compile`].
137    pub fn dry_run(mut self) -> CargoResult<Compilation<'gctx>> {
138        let _lock = self
139            .bcx
140            .gctx
141            .acquire_package_cache_lock(CacheLockMode::Shared)?;
142        self.lto = super::lto::generate(self.bcx)?;
143        self.prepare_units()?;
144        self.prepare()?;
145        self.check_collisions()?;
146
147        for unit in &self.bcx.roots {
148            self.collect_tests_and_executables(unit)?;
149        }
150
151        Ok(self.compilation)
152    }
153
154    /// Starts compilation, waits for it to finish, and returns information
155    /// about the result of compilation.
156    ///
157    /// See [`ops::cargo_compile`] for a higher-level view of the compile process.
158    ///
159    /// [`ops::cargo_compile`]: crate::ops::cargo_compile
160    #[tracing::instrument(skip_all)]
161    pub fn compile(mut self, exec: &Arc<dyn Executor>) -> CargoResult<Compilation<'gctx>> {
162        // A shared lock is held during the duration of the build since rustc
163        // needs to read from the `src` cache, and we don't want other
164        // commands modifying the `src` cache while it is running.
165        let _lock = self
166            .bcx
167            .gctx
168            .acquire_package_cache_lock(CacheLockMode::Shared)?;
169        let mut queue = JobQueue::new(self.bcx);
170        self.lto = super::lto::generate(self.bcx)?;
171        self.prepare_units()?;
172        self.prepare()?;
173        custom_build::build_map(&mut self)?;
174        self.check_collisions()?;
175        self.compute_metadata_for_doc_units();
176
177        // We need to make sure that if there were any previous docs
178        // already compiled, they were compiled with the same Rustc version that we're currently
179        // using. Otherwise we must remove the `doc/` folder and compile again forcing a rebuild.
180        //
181        // This is important because the `.js`/`.html` & `.css` files that are generated by Rustc don't have
182        // any versioning (See https://github.com/rust-lang/cargo/issues/8461).
183        // Therefore, we can end up with weird bugs and behaviours if we mix different
184        // versions of these files.
185        if self.bcx.build_config.intent.is_doc() {
186            RustDocFingerprint::check_rustdoc_fingerprint(&self)?
187        }
188
189        for unit in &self.bcx.roots {
190            let force_rebuild = self.bcx.build_config.force_rebuild;
191            super::compile(&mut self, &mut queue, unit, exec, force_rebuild)?;
192        }
193
194        // Now that we've got the full job queue and we've done all our
195        // fingerprint analysis to determine what to run, bust all the memoized
196        // fingerprint hashes to ensure that during the build they all get the
197        // most up-to-date values. In theory we only need to bust hashes that
198        // transitively depend on a dirty build script, but it shouldn't matter
199        // that much for performance anyway.
200        for fingerprint in self.fingerprints.values() {
201            fingerprint.clear_memoized();
202        }
203
204        // Now that we've figured out everything that we're going to do, do it!
205        queue.execute(&mut self)?;
206
207        // Add `OUT_DIR` to env vars if unit has a build script.
208        let units_with_build_script = &self
209            .bcx
210            .roots
211            .iter()
212            .filter(|unit| self.build_scripts.contains_key(unit))
213            .dedup_by(|x, y| x.pkg.package_id() == y.pkg.package_id())
214            .collect::<Vec<_>>();
215        for unit in units_with_build_script {
216            for dep in &self.bcx.unit_graph[unit] {
217                if dep.unit.mode.is_run_custom_build() {
218                    let out_dir = self
219                        .files()
220                        .build_script_out_dir(&dep.unit)
221                        .display()
222                        .to_string();
223                    let script_meta = self.get_run_build_script_metadata(&dep.unit);
224                    self.compilation
225                        .extra_env
226                        .entry(script_meta)
227                        .or_insert_with(Vec::new)
228                        .push(("OUT_DIR".to_string(), out_dir));
229                }
230            }
231        }
232
233        // Collect the result of the build into `self.compilation`.
234        for unit in &self.bcx.roots {
235            self.collect_tests_and_executables(unit)?;
236
237            // Collect information for `rustdoc --test`.
238            if unit.mode.is_doc_test() {
239                let mut unstable_opts = false;
240                let mut args = compiler::extern_args(&self, unit, &mut unstable_opts)?;
241                args.extend(compiler::lto_args(&self, unit));
242                args.extend(compiler::features_args(unit));
243                args.extend(compiler::check_cfg_args(unit));
244
245                let script_metas = self.find_build_script_metadatas(unit);
246                if let Some(meta_vec) = script_metas.clone() {
247                    for meta in meta_vec {
248                        if let Some(output) = self.build_script_outputs.lock().unwrap().get(meta) {
249                            for cfg in &output.cfgs {
250                                args.push("--cfg".into());
251                                args.push(cfg.into());
252                            }
253
254                            for check_cfg in &output.check_cfgs {
255                                args.push("--check-cfg".into());
256                                args.push(check_cfg.into());
257                            }
258
259                            for (lt, arg) in &output.linker_args {
260                                if lt.applies_to(&unit.target, unit.mode) {
261                                    args.push("-C".into());
262                                    args.push(format!("link-arg={}", arg).into());
263                                }
264                            }
265                        }
266                    }
267                }
268                args.extend(unit.rustdocflags.iter().map(Into::into));
269
270                use super::MessageFormat;
271                let format = match self.bcx.build_config.message_format {
272                    MessageFormat::Short => "short",
273                    MessageFormat::Human => "human",
274                    MessageFormat::Json { .. } => "json",
275                };
276                args.push("--error-format".into());
277                args.push(format.into());
278
279                self.compilation.to_doc_test.push(compilation::Doctest {
280                    unit: unit.clone(),
281                    args,
282                    unstable_opts,
283                    linker: self.compilation.target_linker(unit.kind).clone(),
284                    script_metas,
285                    env: artifact::get_env(&self, self.unit_deps(unit))?,
286                });
287            }
288
289            super::output_depinfo(&mut self, unit)?;
290        }
291
292        for (script_meta, output) in self.build_script_outputs.lock().unwrap().iter() {
293            self.compilation
294                .extra_env
295                .entry(*script_meta)
296                .or_insert_with(Vec::new)
297                .extend(output.env.iter().cloned());
298
299            for dir in output.library_paths.iter() {
300                self.compilation
301                    .native_dirs
302                    .insert(dir.clone().into_path_buf());
303            }
304        }
305        Ok(self.compilation)
306    }
307
308    fn collect_tests_and_executables(&mut self, unit: &Unit) -> CargoResult<()> {
309        for output in self.outputs(unit)?.iter() {
310            if matches!(
311                output.flavor,
312                FileFlavor::DebugInfo | FileFlavor::Auxiliary | FileFlavor::Sbom
313            ) {
314                continue;
315            }
316
317            let bindst = output.bin_dst();
318
319            if unit.mode == CompileMode::Test {
320                self.compilation
321                    .tests
322                    .push(self.unit_output(unit, &output.path));
323            } else if unit.target.is_executable() {
324                self.compilation
325                    .binaries
326                    .push(self.unit_output(unit, bindst));
327            } else if unit.target.is_cdylib()
328                && !self.compilation.cdylibs.iter().any(|uo| uo.unit == *unit)
329            {
330                self.compilation
331                    .cdylibs
332                    .push(self.unit_output(unit, bindst));
333            }
334        }
335        Ok(())
336    }
337
338    /// Returns the executable for the specified unit (if any).
339    pub fn get_executable(&mut self, unit: &Unit) -> CargoResult<Option<PathBuf>> {
340        let is_binary = unit.target.is_executable();
341        let is_test = unit.mode.is_any_test();
342        if !unit.mode.generates_executable() || !(is_binary || is_test) {
343            return Ok(None);
344        }
345        Ok(self
346            .outputs(unit)?
347            .iter()
348            .find(|o| o.flavor == FileFlavor::Normal)
349            .map(|output| output.bin_dst().clone()))
350    }
351
352    #[tracing::instrument(skip_all)]
353    pub fn prepare_units(&mut self) -> CargoResult<()> {
354        let dest = self.bcx.profiles.get_dir_name();
355        let host_layout = Layout::new(self.bcx.ws, None, &dest)?;
356        let mut targets = HashMap::new();
357        for kind in self.bcx.all_kinds.iter() {
358            if let CompileKind::Target(target) = *kind {
359                let layout = Layout::new(self.bcx.ws, Some(target), &dest)?;
360                targets.insert(target, layout);
361            }
362        }
363        self.primary_packages
364            .extend(self.bcx.roots.iter().map(|u| u.pkg.package_id()));
365        self.compilation
366            .root_crate_names
367            .extend(self.bcx.roots.iter().map(|u| u.target.crate_name()));
368
369        self.record_units_requiring_metadata();
370
371        let files = CompilationFiles::new(self, host_layout, targets);
372        self.files = Some(files);
373        Ok(())
374    }
375
376    /// Prepare this context, ensuring that all filesystem directories are in
377    /// place.
378    #[tracing::instrument(skip_all)]
379    pub fn prepare(&mut self) -> CargoResult<()> {
380        self.files
381            .as_mut()
382            .unwrap()
383            .host
384            .prepare()
385            .context("couldn't prepare build directories")?;
386        for target in self.files.as_mut().unwrap().target.values_mut() {
387            target
388                .prepare()
389                .context("couldn't prepare build directories")?;
390        }
391
392        let files = self.files.as_ref().unwrap();
393        for &kind in self.bcx.all_kinds.iter() {
394            let layout = files.layout(kind);
395            self.compilation
396                .root_output
397                .insert(kind, layout.artifact_dir().dest().to_path_buf());
398            if self.bcx.gctx.cli_unstable().build_dir_new_layout {
399                for (unit, _) in self.bcx.unit_graph.iter() {
400                    let dep_dir = self.files().deps_dir(unit);
401                    paths::create_dir_all(&dep_dir)?;
402                    self.compilation.deps_output.insert(kind, dep_dir);
403                }
404            } else {
405                self.compilation
406                    .deps_output
407                    .insert(kind, layout.build_dir().legacy_deps().to_path_buf());
408            }
409        }
410        Ok(())
411    }
412
413    pub fn files(&self) -> &CompilationFiles<'a, 'gctx> {
414        self.files.as_ref().unwrap()
415    }
416
417    /// Returns the filenames that the given unit will generate.
418    pub fn outputs(&self, unit: &Unit) -> CargoResult<Arc<Vec<OutputFile>>> {
419        self.files.as_ref().unwrap().outputs(unit, self.bcx)
420    }
421
422    /// Direct dependencies for the given unit.
423    pub fn unit_deps(&self, unit: &Unit) -> &[UnitDep] {
424        &self.bcx.unit_graph[unit]
425    }
426
427    /// Returns the `RunCustomBuild` Units associated with the given Unit.
428    ///
429    /// If the package does not have a build script, this returns None.
430    pub fn find_build_script_units(&self, unit: &Unit) -> Option<Vec<Unit>> {
431        if unit.mode.is_run_custom_build() {
432            return Some(vec![unit.clone()]);
433        }
434
435        let build_script_units: Vec<Unit> = self.bcx.unit_graph[unit]
436            .iter()
437            .filter(|unit_dep| {
438                unit_dep.unit.mode.is_run_custom_build()
439                    && unit_dep.unit.pkg.package_id() == unit.pkg.package_id()
440            })
441            .map(|unit_dep| unit_dep.unit.clone())
442            .collect();
443        if build_script_units.is_empty() {
444            None
445        } else {
446            Some(build_script_units)
447        }
448    }
449
450    /// Returns the metadata hash for the `RunCustomBuild` Unit associated with
451    /// the given unit.
452    ///
453    /// If the package does not have a build script, this returns None.
454    pub fn find_build_script_metadatas(&self, unit: &Unit) -> Option<Vec<UnitHash>> {
455        self.find_build_script_units(unit).map(|units| {
456            units
457                .iter()
458                .map(|u| self.get_run_build_script_metadata(u))
459                .collect()
460        })
461    }
462
463    /// Returns the metadata hash for a `RunCustomBuild` unit.
464    pub fn get_run_build_script_metadata(&self, unit: &Unit) -> UnitHash {
465        assert!(unit.mode.is_run_custom_build());
466        self.files().metadata(unit).unit_id()
467    }
468
469    /// Returns the list of SBOM output file paths for a given [`Unit`].
470    pub fn sbom_output_files(&self, unit: &Unit) -> CargoResult<Vec<PathBuf>> {
471        Ok(self
472            .outputs(unit)?
473            .iter()
474            .filter(|o| o.flavor == FileFlavor::Sbom)
475            .map(|o| o.path.clone())
476            .collect())
477    }
478
479    pub fn is_primary_package(&self, unit: &Unit) -> bool {
480        self.primary_packages.contains(&unit.pkg.package_id())
481    }
482
483    /// Returns a [`UnitOutput`] which represents some information about the
484    /// output of a unit.
485    pub fn unit_output(&self, unit: &Unit, path: &Path) -> UnitOutput {
486        let script_metas = self.find_build_script_metadatas(unit);
487        UnitOutput {
488            unit: unit.clone(),
489            path: path.to_path_buf(),
490            script_metas,
491        }
492    }
493
494    /// Check if any output file name collision happens.
495    /// See <https://github.com/rust-lang/cargo/issues/6313> for more.
496    #[tracing::instrument(skip_all)]
497    fn check_collisions(&self) -> CargoResult<()> {
498        let mut output_collisions = HashMap::new();
499        let describe_collision = |unit: &Unit, other_unit: &Unit| -> String {
500            format!(
501                "the {} target `{}` in package `{}` has the same output filename as the {} target `{}` in package `{}`",
502                unit.target.kind().description(),
503                unit.target.name(),
504                unit.pkg.package_id(),
505                other_unit.target.kind().description(),
506                other_unit.target.name(),
507                other_unit.pkg.package_id(),
508            )
509        };
510        let suggestion = [
511            Level::NOTE.message("this may become a hard error in the future; see <https://github.com/rust-lang/cargo/issues/6313>"),
512            Level::HELP.message("consider changing their names to be unique or compiling them separately")
513        ];
514        let rustdoc_suggestion = [
515            Level::NOTE.message("this is a known bug where multiple crates with the same name use the same path; see <https://github.com/rust-lang/cargo/issues/6313>")
516        ];
517        let report_collision = |unit: &Unit,
518                                other_unit: &Unit,
519                                path: &PathBuf,
520                                messages: &[Message<'_>]|
521         -> CargoResult<()> {
522            if unit.target.name() == other_unit.target.name() {
523                self.bcx.gctx.shell().print_report(
524                    &[Level::WARNING
525                        .secondary_title(format!("output filename collision at {}", path.display()))
526                        .elements(
527                            [Level::NOTE.message(describe_collision(unit, other_unit))]
528                                .into_iter()
529                                .chain(messages.iter().cloned()),
530                        )],
531                    false,
532                )
533            } else {
534                self.bcx.gctx.shell().print_report(
535                    &[Level::WARNING
536                        .secondary_title(format!("output filename collision at {}", path.display()))
537                        .elements([
538                            Level::NOTE.message(describe_collision(unit, other_unit)),
539                            Level::NOTE.message("if this looks unexpected, it may be a bug in Cargo. Please file a bug \
540                                report at https://github.com/rust-lang/cargo/issues/ with as much information as you \
541                                can provide."),
542                            Level::NOTE.message(format!("cargo {} running on `{}` target `{}`",
543                                crate::version(), self.bcx.host_triple(), self.bcx.target_data.short_name(&unit.kind))),
544                            Level::NOTE.message(format!("first unit: {unit:?}")),
545                            Level::NOTE.message(format!("second unit: {other_unit:?}")),
546                        ])],
547                    false,
548                )
549            }
550        };
551
552        fn doc_collision_error(unit: &Unit, other_unit: &Unit) -> CargoResult<()> {
553            bail!(
554                "document output filename collision\n\
555                 The {} `{}` in package `{}` has the same name as the {} `{}` in package `{}`.\n\
556                 Only one may be documented at once since they output to the same path.\n\
557                 Consider documenting only one, renaming one, \
558                 or marking one with `doc = false` in Cargo.toml.",
559                unit.target.kind().description(),
560                unit.target.name(),
561                unit.pkg,
562                other_unit.target.kind().description(),
563                other_unit.target.name(),
564                other_unit.pkg,
565            );
566        }
567
568        let mut keys = self
569            .bcx
570            .unit_graph
571            .keys()
572            .filter(|unit| !unit.mode.is_run_custom_build())
573            .collect::<Vec<_>>();
574        // Sort for consistent error messages.
575        keys.sort_unstable();
576        // These are kept separate to retain compatibility with older
577        // versions, which generated an error when there was a duplicate lib
578        // or bin (but the old code did not check bin<->lib collisions). To
579        // retain backwards compatibility, this only generates an error for
580        // duplicate libs or duplicate bins (but not both). Ideally this
581        // shouldn't be here, but since there isn't a complete workaround,
582        // yet, this retains the old behavior.
583        let mut doc_libs = HashMap::new();
584        let mut doc_bins = HashMap::new();
585        for unit in keys {
586            if unit.mode.is_doc() && self.is_primary_package(unit) {
587                // These situations have been an error since before 1.0, so it
588                // is not a warning like the other situations.
589                if unit.target.is_lib() {
590                    if let Some(prev) = doc_libs.insert((unit.target.crate_name(), unit.kind), unit)
591                    {
592                        doc_collision_error(unit, prev)?;
593                    }
594                } else if let Some(prev) =
595                    doc_bins.insert((unit.target.crate_name(), unit.kind), unit)
596                {
597                    doc_collision_error(unit, prev)?;
598                }
599            }
600            for output in self.outputs(unit)?.iter() {
601                if let Some(other_unit) = output_collisions.insert(output.path.clone(), unit) {
602                    if unit.mode.is_doc() {
603                        // See https://github.com/rust-lang/rust/issues/56169
604                        // and https://github.com/rust-lang/rust/issues/61378
605                        report_collision(unit, other_unit, &output.path, &rustdoc_suggestion)?;
606                    } else {
607                        report_collision(unit, other_unit, &output.path, &suggestion)?;
608                    }
609                }
610                if let Some(hardlink) = output.hardlink.as_ref() {
611                    if let Some(other_unit) = output_collisions.insert(hardlink.clone(), unit) {
612                        report_collision(unit, other_unit, hardlink, &suggestion)?;
613                    }
614                }
615                if let Some(ref export_path) = output.export_path {
616                    if let Some(other_unit) = output_collisions.insert(export_path.clone(), unit) {
617                        self.bcx.gctx.shell().print_report(
618                            &[Level::WARNING
619                                .secondary_title(format!(
620                                    "`--artifact-dir` filename collision at {}",
621                                    export_path.display()
622                                ))
623                                .elements(
624                                    [Level::NOTE.message(describe_collision(unit, other_unit))]
625                                        .into_iter()
626                                        .chain(suggestion.iter().cloned()),
627                                )],
628                            false,
629                        )?;
630                    }
631                }
632            }
633        }
634        Ok(())
635    }
636
637    /// Records the list of units which are required to emit metadata.
638    ///
639    /// Units which depend only on the metadata of others requires the others to
640    /// actually produce metadata, so we'll record that here.
641    fn record_units_requiring_metadata(&mut self) {
642        for (key, deps) in self.bcx.unit_graph.iter() {
643            for dep in deps {
644                if self.only_requires_rmeta(key, &dep.unit) {
645                    self.rmeta_required.insert(dep.unit.clone());
646                }
647            }
648        }
649    }
650
651    /// Returns whether when `parent` depends on `dep` if it only requires the
652    /// metadata file from `dep`.
653    pub fn only_requires_rmeta(&self, parent: &Unit, dep: &Unit) -> bool {
654        // We're only a candidate for requiring an `rmeta` file if we
655        // ourselves are building an rlib,
656        !parent.requires_upstream_objects()
657            && parent.mode == CompileMode::Build
658            // Our dependency must also be built as an rlib, otherwise the
659            // object code must be useful in some fashion
660            && !dep.requires_upstream_objects()
661            && dep.mode == CompileMode::Build
662    }
663
664    /// Returns whether when `unit` is built whether it should emit metadata as
665    /// well because some compilations rely on that.
666    pub fn rmeta_required(&self, unit: &Unit) -> bool {
667        self.rmeta_required.contains(unit)
668    }
669
670    /// Finds metadata for Doc/Docscrape units.
671    ///
672    /// rustdoc needs a -Cmetadata flag in order to recognize StableCrateIds that refer to
673    /// items in the crate being documented. The -Cmetadata flag used by reverse-dependencies
674    /// will be the metadata of the Cargo unit that generated the current library's rmeta file,
675    /// which should be a Check unit.
676    ///
677    /// If the current crate has reverse-dependencies, such a Check unit should exist, and so
678    /// we use that crate's metadata. If not, we use the crate's Doc unit so at least examples
679    /// scraped from the current crate can be used when documenting the current crate.
680    #[tracing::instrument(skip_all)]
681    pub fn compute_metadata_for_doc_units(&mut self) {
682        for unit in self.bcx.unit_graph.keys() {
683            if !unit.mode.is_doc() && !unit.mode.is_doc_scrape() {
684                continue;
685            }
686
687            let matching_units = self
688                .bcx
689                .unit_graph
690                .keys()
691                .filter(|other| {
692                    unit.pkg == other.pkg
693                        && unit.target == other.target
694                        && !other.mode.is_doc_scrape()
695                })
696                .collect::<Vec<_>>();
697            let metadata_unit = matching_units
698                .iter()
699                .find(|other| other.mode.is_check())
700                .or_else(|| matching_units.iter().find(|other| other.mode.is_doc()))
701                .unwrap_or(&unit);
702            self.metadata_for_doc_units
703                .insert(unit.clone(), self.files().metadata(metadata_unit));
704        }
705    }
706}