cargo/ops/cargo_compile/
mod.rs

1//! The entry point for starting the compilation process for commands like
2//! `build`, `test`, `doc`, `rustc`, etc.
3//!
4//! The [`compile`] function will do all the work to compile a workspace. A
5//! rough outline is:
6//!
7//! 1. Resolve the dependency graph (see [`ops::resolve`]).
8//! 2. Download any packages needed (see [`PackageSet`]).
9//! 3. Generate a list of top-level "units" of work for the targets the user
10//!   requested on the command-line. Each [`Unit`] corresponds to a compiler
11//!   invocation. This is done in this module ([`UnitGenerator::generate_root_units`]).
12//! 4. Starting from the root [`Unit`]s, generate the [`UnitGraph`] by walking the dependency graph
13//!   from the resolver.  See also [`unit_dependencies`].
14//! 5. Construct the [`BuildContext`] with all of the information collected so
15//!   far. This is the end of the "front end" of compilation.
16//! 6. Create a [`BuildRunner`] which coordinates the compilation process
17//!   and will perform the following steps:
18//!     1. Prepare the `target` directory (see [`Layout`]).
19//!     2. Create a [`JobQueue`]. The queue checks the
20//!       fingerprint of each `Unit` to determine if it should run or be
21//!       skipped.
22//!     3. Execute the queue via [`drain_the_queue`]. Each leaf in the queue's dependency graph is
23//!        executed, and then removed from the graph when finished. This repeats until the queue is
24//!        empty.  Note that this is the only point in cargo that currently uses threads.
25//! 7. The result of the compilation is stored in the [`Compilation`] struct. This can be used for
26//!    various things, such as running tests after the compilation  has finished.
27//!
28//! **Note**: "target" inside this module generally refers to ["Cargo Target"],
29//! which corresponds to artifact that will be built in a package. Not to be
30//! confused with target-triple or target architecture.
31//!
32//! [`unit_dependencies`]: crate::core::compiler::unit_dependencies
33//! [`Layout`]: crate::core::compiler::Layout
34//! [`JobQueue`]: crate::core::compiler::job_queue
35//! [`drain_the_queue`]: crate::core::compiler::job_queue
36//! ["Cargo Target"]: https://doc.rust-lang.org/nightly/cargo/reference/cargo-targets.html
37
38use std::collections::{HashMap, HashSet};
39use std::hash::{Hash, Hasher};
40use std::sync::Arc;
41
42use crate::core::compiler::UserIntent;
43use crate::core::compiler::unit_dependencies::build_unit_dependencies;
44use crate::core::compiler::unit_graph::{self, UnitDep, UnitGraph};
45use crate::core::compiler::{BuildConfig, BuildContext, BuildRunner, Compilation};
46use crate::core::compiler::{CompileKind, CompileTarget, RustcTargetData, Unit};
47use crate::core::compiler::{CrateType, TargetInfo, apply_env_config, standard_lib};
48use crate::core::compiler::{DefaultExecutor, Executor, UnitInterner};
49use crate::core::profiles::Profiles;
50use crate::core::resolver::features::{self, CliFeatures, FeaturesFor};
51use crate::core::resolver::{HasDevUnits, Resolve};
52use crate::core::{PackageId, PackageSet, SourceId, TargetKind, Workspace};
53use crate::drop_println;
54use crate::ops;
55use crate::ops::resolve::{SpecsAndResolvedFeatures, WorkspaceResolve};
56use crate::util::BuildLogger;
57use crate::util::context::{GlobalContext, WarningHandling};
58use crate::util::interning::InternedString;
59use crate::util::log_message::LogMessage;
60use crate::util::{CargoResult, StableHasher};
61
62mod compile_filter;
63use annotate_snippets::{Group, Level, Origin};
64pub use compile_filter::{CompileFilter, FilterRule, LibRule};
65
66pub(super) mod unit_generator;
67use itertools::Itertools as _;
68use unit_generator::UnitGenerator;
69
70mod packages;
71
72pub use packages::Packages;
73
74/// Contains information about how a package should be compiled.
75///
76/// Note on distinction between `CompileOptions` and [`BuildConfig`]:
77/// `BuildConfig` contains values that need to be retained after
78/// [`BuildContext`] is created. The other fields are no longer necessary. Think
79/// of it as `CompileOptions` are high-level settings requested on the
80/// command-line, and `BuildConfig` are low-level settings for actually
81/// driving `rustc`.
82#[derive(Debug, Clone)]
83pub struct CompileOptions {
84    /// Configuration information for a rustc build
85    pub build_config: BuildConfig,
86    /// Feature flags requested by the user.
87    pub cli_features: CliFeatures,
88    /// A set of packages to build.
89    pub spec: Packages,
90    /// Filter to apply to the root package to select which targets will be
91    /// built.
92    pub filter: CompileFilter,
93    /// Extra arguments to be passed to rustdoc (single target only)
94    pub target_rustdoc_args: Option<Vec<String>>,
95    /// The specified target will be compiled with all the available arguments,
96    /// note that this only accounts for the *final* invocation of rustc
97    pub target_rustc_args: Option<Vec<String>>,
98    /// Crate types to be passed to rustc (single target only)
99    pub target_rustc_crate_types: Option<Vec<String>>,
100    /// Whether the `--document-private-items` flags was specified and should
101    /// be forwarded to `rustdoc`.
102    pub rustdoc_document_private_items: bool,
103    /// Whether the build process should check the minimum Rust version
104    /// defined in the cargo metadata for a crate.
105    pub honor_rust_version: Option<bool>,
106}
107
108impl CompileOptions {
109    pub fn new(gctx: &GlobalContext, intent: UserIntent) -> CargoResult<CompileOptions> {
110        let jobs = None;
111        let keep_going = false;
112        Ok(CompileOptions {
113            build_config: BuildConfig::new(gctx, jobs, keep_going, &[], intent)?,
114            cli_features: CliFeatures::new_all(false),
115            spec: ops::Packages::Packages(Vec::new()),
116            filter: CompileFilter::Default {
117                required_features_filterable: false,
118            },
119            target_rustdoc_args: None,
120            target_rustc_args: None,
121            target_rustc_crate_types: None,
122            rustdoc_document_private_items: false,
123            honor_rust_version: None,
124        })
125    }
126}
127
128/// Compiles!
129///
130/// This uses the [`DefaultExecutor`]. To use a custom [`Executor`], see [`compile_with_exec`].
131pub fn compile<'a>(ws: &Workspace<'a>, options: &CompileOptions) -> CargoResult<Compilation<'a>> {
132    let exec: Arc<dyn Executor> = Arc::new(DefaultExecutor);
133    compile_with_exec(ws, options, &exec)
134}
135
136/// Like [`compile`] but allows specifying a custom [`Executor`]
137/// that will be able to intercept build calls and add custom logic.
138///
139/// [`compile`] uses [`DefaultExecutor`] which just passes calls through.
140pub fn compile_with_exec<'a>(
141    ws: &Workspace<'a>,
142    options: &CompileOptions,
143    exec: &Arc<dyn Executor>,
144) -> CargoResult<Compilation<'a>> {
145    ws.emit_warnings()?;
146    let compilation = compile_ws(ws, options, exec)?;
147    if ws.gctx().warning_handling()? == WarningHandling::Deny && compilation.lint_warning_count > 0
148    {
149        anyhow::bail!("warnings are denied by `build.warnings` configuration")
150    }
151    Ok(compilation)
152}
153
154/// Like [`compile_with_exec`] but without warnings from manifest parsing.
155#[tracing::instrument(skip_all)]
156pub fn compile_ws<'a>(
157    ws: &Workspace<'a>,
158    options: &CompileOptions,
159    exec: &Arc<dyn Executor>,
160) -> CargoResult<Compilation<'a>> {
161    let interner = UnitInterner::new();
162    let logger = BuildLogger::maybe_new(ws)?;
163
164    if let Some(ref logger) = logger {
165        let rustc = ws.gctx().load_global_rustc(Some(ws))?;
166        let num_cpus = std::thread::available_parallelism()
167            .ok()
168            .map(|x| x.get() as u64);
169        logger.log(LogMessage::BuildStarted {
170            cwd: ws.gctx().cwd().to_path_buf(),
171            host: rustc.host.to_string(),
172            jobs: options.build_config.jobs,
173            num_cpus,
174            profile: options.build_config.requested_profile.to_string(),
175            rustc_version: rustc.version.to_string(),
176            rustc_version_verbose: rustc.verbose_version.clone(),
177            target_dir: ws.target_dir().as_path_unlocked().to_path_buf(),
178            workspace_root: ws.root().to_path_buf(),
179        });
180    }
181
182    let bcx = create_bcx(ws, options, &interner, logger.as_ref())?;
183
184    if options.build_config.unit_graph {
185        unit_graph::emit_serialized_unit_graph(&bcx.roots, &bcx.unit_graph, ws.gctx())?;
186        return Compilation::new(&bcx);
187    }
188    crate::core::gc::auto_gc(bcx.gctx);
189    let build_runner = BuildRunner::new(&bcx)?;
190    if options.build_config.dry_run {
191        build_runner.dry_run()
192    } else {
193        build_runner.compile(exec)
194    }
195}
196
197/// Executes `rustc --print <VALUE>`.
198///
199/// * `print_opt_value` is the VALUE passed through.
200pub fn print<'a>(
201    ws: &Workspace<'a>,
202    options: &CompileOptions,
203    print_opt_value: &str,
204) -> CargoResult<()> {
205    let CompileOptions {
206        ref build_config,
207        ref target_rustc_args,
208        ..
209    } = *options;
210    let gctx = ws.gctx();
211    let rustc = gctx.load_global_rustc(Some(ws))?;
212    for (index, kind) in build_config.requested_kinds.iter().enumerate() {
213        if index != 0 {
214            drop_println!(gctx);
215        }
216        let target_info = TargetInfo::new(gctx, &build_config.requested_kinds, &rustc, *kind)?;
217        let mut process = rustc.process();
218        apply_env_config(gctx, &mut process)?;
219        process.args(&target_info.rustflags);
220        if let Some(args) = target_rustc_args {
221            process.args(args);
222        }
223        if let CompileKind::Target(t) = kind {
224            process.arg("--target").arg(t.rustc_target());
225        }
226        process.arg("--print").arg(print_opt_value);
227        process.exec()?;
228    }
229    Ok(())
230}
231
232/// Prepares all required information for the actual compilation.
233///
234/// For how it works and what data it collects,
235/// please see the [module-level documentation](self).
236#[tracing::instrument(skip_all)]
237pub fn create_bcx<'a, 'gctx>(
238    ws: &'a Workspace<'gctx>,
239    options: &'a CompileOptions,
240    interner: &'a UnitInterner,
241    logger: Option<&'a BuildLogger>,
242) -> CargoResult<BuildContext<'a, 'gctx>> {
243    let CompileOptions {
244        ref build_config,
245        ref spec,
246        ref cli_features,
247        ref filter,
248        ref target_rustdoc_args,
249        ref target_rustc_args,
250        ref target_rustc_crate_types,
251        rustdoc_document_private_items,
252        honor_rust_version,
253    } = *options;
254    let gctx = ws.gctx();
255
256    // Perform some pre-flight validation.
257    match build_config.intent {
258        UserIntent::Test | UserIntent::Build | UserIntent::Check { .. } | UserIntent::Bench => {
259            if ws.gctx().get_env("RUST_FLAGS").is_ok() {
260                gctx.shell().print_report(
261                    &[Level::WARNING
262                        .secondary_title("ignoring environment variable `RUST_FLAGS`")
263                        .element(Level::HELP.message("rust flags are passed via `RUSTFLAGS`"))],
264                    false,
265                )?;
266            }
267        }
268        UserIntent::Doc { .. } | UserIntent::Doctest => {
269            if ws.gctx().get_env("RUSTDOC_FLAGS").is_ok() {
270                gctx.shell().print_report(
271                    &[Level::WARNING
272                        .secondary_title("ignoring environment variable `RUSTDOC_FLAGS`")
273                        .element(
274                            Level::HELP.message("rustdoc flags are passed via `RUSTDOCFLAGS`"),
275                        )],
276                    false,
277                )?;
278            }
279        }
280    }
281    gctx.validate_term_config()?;
282
283    let mut target_data = RustcTargetData::new(ws, &build_config.requested_kinds)?;
284
285    let specs = spec.to_package_id_specs(ws)?;
286    let has_dev_units = {
287        // Rustdoc itself doesn't need dev-dependencies. But to scrape examples from packages in the
288        // workspace, if any of those packages need dev-dependencies, then we need include dev-dependencies
289        // to scrape those packages.
290        let any_pkg_has_scrape_enabled = ws
291            .members_with_features(&specs, cli_features)?
292            .iter()
293            .any(|(pkg, _)| {
294                pkg.targets()
295                    .iter()
296                    .any(|target| target.is_example() && target.doc_scrape_examples().is_enabled())
297            });
298
299        if filter.need_dev_deps(build_config.intent)
300            || (build_config.intent.is_doc() && any_pkg_has_scrape_enabled)
301        {
302            HasDevUnits::Yes
303        } else {
304            HasDevUnits::No
305        }
306    };
307    let dry_run = false;
308
309    if let Some(logger) = logger {
310        let elapsed = ws.gctx().creation_time().elapsed().as_secs_f64();
311        logger.log(LogMessage::ResolutionStarted { elapsed });
312    }
313    let resolve = ops::resolve_ws_with_opts(
314        ws,
315        &mut target_data,
316        &build_config.requested_kinds,
317        cli_features,
318        &specs,
319        has_dev_units,
320        crate::core::resolver::features::ForceAllTargets::No,
321        dry_run,
322    )?;
323    let WorkspaceResolve {
324        mut pkg_set,
325        workspace_resolve,
326        targeted_resolve: resolve,
327        specs_and_features,
328    } = resolve;
329
330    if let Some(logger) = logger {
331        let elapsed = ws.gctx().creation_time().elapsed().as_secs_f64();
332        logger.log(LogMessage::ResolutionFinished { elapsed });
333    }
334
335    let std_resolve_features = if let Some(crates) = &gctx.cli_unstable().build_std {
336        let (std_package_set, std_resolve, std_features) = standard_lib::resolve_std(
337            ws,
338            &mut target_data,
339            &build_config,
340            crates,
341            &build_config.requested_kinds,
342        )?;
343        pkg_set.add_set(std_package_set);
344        Some((std_resolve, std_features))
345    } else {
346        None
347    };
348
349    // Find the packages in the resolver that the user wants to build (those
350    // passed in with `-p` or the defaults from the workspace), and convert
351    // Vec<PackageIdSpec> to a Vec<PackageId>.
352    let to_build_ids = resolve.specs_to_ids(&specs)?;
353    // Now get the `Package` for each `PackageId`. This may trigger a download
354    // if the user specified `-p` for a dependency that is not downloaded.
355    // Dependencies will be downloaded during build_unit_dependencies.
356    let mut to_builds = pkg_set.get_many(to_build_ids)?;
357
358    // The ordering here affects some error messages coming out of cargo, so
359    // let's be test and CLI friendly by always printing in the same order if
360    // there's an error.
361    to_builds.sort_by_key(|p| p.package_id());
362
363    for pkg in to_builds.iter() {
364        pkg.manifest().print_teapot(gctx);
365
366        if build_config.intent.is_any_test()
367            && !ws.is_member(pkg)
368            && pkg.dependencies().iter().any(|dep| !dep.is_transitive())
369        {
370            anyhow::bail!(
371                "package `{}` cannot be tested because it requires dev-dependencies \
372                 and is not a member of the workspace",
373                pkg.name()
374            );
375        }
376    }
377
378    let (extra_args, extra_args_name) = match (target_rustc_args, target_rustdoc_args) {
379        (Some(args), _) => (Some(args.clone()), "rustc"),
380        (_, Some(args)) => (Some(args.clone()), "rustdoc"),
381        _ => (None, ""),
382    };
383
384    if extra_args.is_some() && to_builds.len() != 1 {
385        panic!(
386            "`{}` should not accept multiple `-p` flags",
387            extra_args_name
388        );
389    }
390
391    let profiles = Profiles::new(ws, build_config.requested_profile)?;
392    profiles.validate_packages(
393        ws.profiles(),
394        &mut gctx.shell(),
395        workspace_resolve.as_ref().unwrap_or(&resolve),
396    )?;
397
398    // If `--target` has not been specified, then the unit graph is built
399    // assuming `--target $HOST` was specified. See
400    // `rebuild_unit_graph_shared` for more on why this is done.
401    let explicit_host_kind = CompileKind::Target(CompileTarget::new(&target_data.rustc.host)?);
402    let explicit_host_kinds: Vec<_> = build_config
403        .requested_kinds
404        .iter()
405        .map(|kind| match kind {
406            CompileKind::Host => explicit_host_kind,
407            CompileKind::Target(t) => CompileKind::Target(*t),
408        })
409        .collect();
410
411    let mut root_units = Vec::new();
412    let mut unit_graph = HashMap::new();
413    let mut scrape_units = Vec::new();
414
415    if let Some(logger) = logger {
416        let elapsed = ws.gctx().creation_time().elapsed().as_secs_f64();
417        logger.log(LogMessage::UnitGraphStarted { elapsed });
418    }
419
420    for SpecsAndResolvedFeatures {
421        specs,
422        resolved_features,
423    } in &specs_and_features
424    {
425        // Passing `build_config.requested_kinds` instead of
426        // `explicit_host_kinds` here so that `generate_root_units` can do
427        // its own special handling of `CompileKind::Host`. It will
428        // internally replace the host kind by the `explicit_host_kind`
429        // before setting as a unit.
430        let spec_names = specs.iter().map(|spec| spec.name()).collect::<Vec<_>>();
431        let packages = to_builds
432            .iter()
433            .filter(|package| spec_names.contains(&package.name().as_str()))
434            .cloned()
435            .collect::<Vec<_>>();
436        let generator = UnitGenerator {
437            ws,
438            packages: &packages,
439            spec,
440            target_data: &target_data,
441            filter,
442            requested_kinds: &build_config.requested_kinds,
443            explicit_host_kind,
444            intent: build_config.intent,
445            resolve: &resolve,
446            workspace_resolve: &workspace_resolve,
447            resolved_features: &resolved_features,
448            package_set: &pkg_set,
449            profiles: &profiles,
450            interner,
451            has_dev_units,
452        };
453        let mut targeted_root_units = generator.generate_root_units()?;
454
455        if let Some(args) = target_rustc_crate_types {
456            override_rustc_crate_types(&mut targeted_root_units, args, interner)?;
457        }
458
459        let should_scrape =
460            build_config.intent.is_doc() && gctx.cli_unstable().rustdoc_scrape_examples;
461        let targeted_scrape_units = if should_scrape {
462            generator.generate_scrape_units(&targeted_root_units)?
463        } else {
464            Vec::new()
465        };
466
467        let std_roots = if let Some(crates) = gctx.cli_unstable().build_std.as_ref() {
468            let (std_resolve, std_features) = std_resolve_features.as_ref().unwrap();
469            standard_lib::generate_std_roots(
470                &crates,
471                &targeted_root_units,
472                std_resolve,
473                std_features,
474                &explicit_host_kinds,
475                &pkg_set,
476                interner,
477                &profiles,
478                &target_data,
479            )?
480        } else {
481            Default::default()
482        };
483
484        unit_graph.extend(build_unit_dependencies(
485            ws,
486            &pkg_set,
487            &resolve,
488            &resolved_features,
489            std_resolve_features.as_ref(),
490            &targeted_root_units,
491            &targeted_scrape_units,
492            &std_roots,
493            build_config.intent,
494            &target_data,
495            &profiles,
496            interner,
497        )?);
498        root_units.extend(targeted_root_units);
499        scrape_units.extend(targeted_scrape_units);
500    }
501
502    // TODO: In theory, Cargo should also dedupe the roots, but I'm uncertain
503    // what heuristics to use in that case.
504    if build_config.intent.wants_deps_docs() {
505        remove_duplicate_doc(build_config, &root_units, &mut unit_graph);
506    }
507
508    let host_kind_requested = build_config
509        .requested_kinds
510        .iter()
511        .any(CompileKind::is_host);
512    // Rebuild the unit graph, replacing the explicit host targets with
513    // CompileKind::Host, removing `artifact_target_for_features` and merging any dependencies
514    // shared with build and artifact dependencies.
515    //
516    // NOTE: after this point, all units and the unit graph must be immutable.
517    let (root_units, scrape_units, unit_graph) = rebuild_unit_graph_shared(
518        interner,
519        unit_graph,
520        &root_units,
521        &scrape_units,
522        host_kind_requested.then_some(explicit_host_kind),
523        build_config.compile_time_deps_only,
524    );
525
526    let units: Vec<_> = unit_graph.keys().sorted().collect();
527    let unit_to_index: HashMap<_, _> = units
528        .iter()
529        .enumerate()
530        .map(|(i, &unit)| (unit.clone(), i as u64))
531        .collect();
532    if let Some(logger) = logger {
533        let root_unit_indexes: HashSet<_> =
534            root_units.iter().map(|unit| unit_to_index[&unit]).collect();
535
536        for (index, unit) in units.into_iter().enumerate() {
537            let index = index as u64;
538            let dependencies = unit_graph
539                .get(unit)
540                .map(|deps| {
541                    deps.iter()
542                        .filter_map(|dep| unit_to_index.get(&dep.unit).copied())
543                        .collect()
544                })
545                .unwrap_or_default();
546            logger.log(LogMessage::UnitRegistered {
547                package_id: unit.pkg.package_id().to_spec(),
548                target: (&unit.target).into(),
549                mode: unit.mode,
550                platform: target_data.short_name(&unit.kind).to_owned(),
551                index,
552                features: unit
553                    .features
554                    .iter()
555                    .map(|s| s.as_str().to_owned())
556                    .collect(),
557                requested: root_unit_indexes.contains(&index),
558                dependencies,
559            });
560        }
561        let elapsed = ws.gctx().creation_time().elapsed().as_secs_f64();
562        logger.log(LogMessage::UnitGraphFinished { elapsed });
563    }
564
565    let mut extra_compiler_args = HashMap::new();
566    if let Some(args) = extra_args {
567        if root_units.len() != 1 {
568            anyhow::bail!(
569                "extra arguments to `{}` can only be passed to one \
570                 target, consider filtering\nthe package by passing, \
571                 e.g., `--lib` or `--bin NAME` to specify a single target",
572                extra_args_name
573            );
574        }
575        extra_compiler_args.insert(root_units[0].clone(), args);
576    }
577
578    for unit in root_units
579        .iter()
580        .filter(|unit| unit.mode.is_doc() || unit.mode.is_doc_test())
581        .filter(|unit| rustdoc_document_private_items || unit.target.is_bin())
582    {
583        // Add `--document-private-items` rustdoc flag if requested or if
584        // the target is a binary. Binary crates get their private items
585        // documented by default.
586        let mut args = vec!["--document-private-items".into()];
587        if unit.target.is_bin() {
588            // This warning only makes sense if it's possible to document private items
589            // sometimes and ignore them at other times. But cargo consistently passes
590            // `--document-private-items`, so the warning isn't useful.
591            args.push("-Arustdoc::private-intra-doc-links".into());
592        }
593        extra_compiler_args
594            .entry(unit.clone())
595            .or_default()
596            .extend(args);
597    }
598
599    // Validate target src path for each root unit
600    let mut error_count: usize = 0;
601    for unit in &root_units {
602        if let Some(target_src_path) = unit.target.src_path().path() {
603            validate_target_path_as_source_file(
604                gctx,
605                target_src_path,
606                unit.target.name(),
607                unit.target.kind(),
608                unit.pkg.manifest_path(),
609                &mut error_count,
610            )?
611        }
612    }
613    if error_count > 0 {
614        let plural: &str = if error_count > 1 { "s" } else { "" };
615        anyhow::bail!(
616            "could not compile due to {error_count} previous target resolution error{plural}"
617        );
618    }
619
620    if honor_rust_version.unwrap_or(true) {
621        let rustc_version = target_data.rustc.version.clone().into();
622
623        let mut incompatible = Vec::new();
624        let mut local_incompatible = false;
625        for unit in unit_graph.keys() {
626            let Some(pkg_msrv) = unit.pkg.rust_version() else {
627                continue;
628            };
629
630            if pkg_msrv.is_compatible_with(&rustc_version) {
631                continue;
632            }
633
634            local_incompatible |= unit.is_local();
635            incompatible.push((unit, pkg_msrv));
636        }
637        if !incompatible.is_empty() {
638            use std::fmt::Write as _;
639
640            let plural = if incompatible.len() == 1 { "" } else { "s" };
641            let mut message = format!(
642                "rustc {rustc_version} is not supported by the following package{plural}:\n"
643            );
644            incompatible.sort_by_key(|(unit, _)| (unit.pkg.name(), unit.pkg.version()));
645            for (unit, msrv) in incompatible {
646                let name = &unit.pkg.name();
647                let version = &unit.pkg.version();
648                writeln!(&mut message, "  {name}@{version} requires rustc {msrv}").unwrap();
649            }
650            if ws.is_ephemeral() {
651                if ws.ignore_lock() {
652                    writeln!(
653                        &mut message,
654                        "Try re-running `cargo install` with `--locked`"
655                    )
656                    .unwrap();
657                }
658            } else if !local_incompatible {
659                writeln!(
660                    &mut message,
661                    "Either upgrade rustc or select compatible dependency versions with
662`cargo update <name>@<current-ver> --precise <compatible-ver>`
663where `<compatible-ver>` is the latest version supporting rustc {rustc_version}",
664                )
665                .unwrap();
666            }
667            return Err(anyhow::Error::msg(message));
668        }
669    }
670
671    let bcx = BuildContext::new(
672        ws,
673        logger,
674        pkg_set,
675        build_config,
676        profiles,
677        extra_compiler_args,
678        target_data,
679        root_units,
680        unit_graph,
681        unit_to_index,
682        scrape_units,
683    )?;
684
685    Ok(bcx)
686}
687
688// Checks if a target path exists and is a source file, not a directory
689fn validate_target_path_as_source_file(
690    gctx: &GlobalContext,
691    target_path: &std::path::Path,
692    target_name: &str,
693    target_kind: &TargetKind,
694    unit_manifest_path: &std::path::Path,
695    error_count: &mut usize,
696) -> CargoResult<()> {
697    if !target_path.exists() {
698        *error_count += 1;
699
700        let err_msg = format!(
701            "can't find {} `{}` at path `{}`",
702            target_kind.description(),
703            target_name,
704            target_path.display()
705        );
706
707        let group = Group::with_title(Level::ERROR.primary_title(err_msg)).element(Origin::path(
708            unit_manifest_path.to_str().unwrap_or_default(),
709        ));
710
711        gctx.shell().print_report(&[group], true)?;
712    } else if target_path.is_dir() {
713        *error_count += 1;
714
715        // suggest setting the path to a likely entrypoint
716        let main_rs = target_path.join("main.rs");
717        let lib_rs = target_path.join("lib.rs");
718
719        let suggested_files_opt = match target_kind {
720            TargetKind::Lib(_) => {
721                if lib_rs.exists() {
722                    Some(format!("`{}`", lib_rs.display()))
723                } else {
724                    None
725                }
726            }
727            TargetKind::Bin => {
728                if main_rs.exists() {
729                    Some(format!("`{}`", main_rs.display()))
730                } else {
731                    None
732                }
733            }
734            TargetKind::Test => {
735                if main_rs.exists() {
736                    Some(format!("`{}`", main_rs.display()))
737                } else {
738                    None
739                }
740            }
741            TargetKind::ExampleBin => {
742                if main_rs.exists() {
743                    Some(format!("`{}`", main_rs.display()))
744                } else {
745                    None
746                }
747            }
748            TargetKind::Bench => {
749                if main_rs.exists() {
750                    Some(format!("`{}`", main_rs.display()))
751                } else {
752                    None
753                }
754            }
755            TargetKind::ExampleLib(_) => {
756                if lib_rs.exists() {
757                    Some(format!("`{}`", lib_rs.display()))
758                } else {
759                    None
760                }
761            }
762            TargetKind::CustomBuild => None,
763        };
764
765        let err_msg = format!(
766            "path `{}` for {} `{}` is a directory, but a source file was expected.",
767            target_path.display(),
768            target_kind.description(),
769            target_name,
770        );
771        let mut group = Group::with_title(Level::ERROR.primary_title(err_msg)).element(
772            Origin::path(unit_manifest_path.to_str().unwrap_or_default()),
773        );
774
775        if let Some(suggested_files) = suggested_files_opt {
776            group = group.element(
777                Level::HELP.message(format!("an entry point exists at {}", suggested_files)),
778            );
779        }
780
781        gctx.shell().print_report(&[group], true)?;
782    }
783
784    Ok(())
785}
786
787/// This is used to rebuild the unit graph, sharing host dependencies if possible,
788/// and applying other unit adjustments based on the whole graph.
789///
790/// This will translate any unit's `CompileKind::Target(host)` to
791/// `CompileKind::Host` if `to_host` is not `None` and the kind is equal to `to_host`.
792/// This also handles generating the unit `dep_hash`, and merging shared units if possible.
793///
794/// This is necessary because if normal dependencies used `CompileKind::Host`,
795/// there would be no way to distinguish those units from build-dependency
796/// units or artifact dependency units.
797/// This can cause a problem if a shared normal/build/artifact dependency needs
798/// to link to another dependency whose features differ based on whether or
799/// not it is a normal, build or artifact dependency. If all units used
800/// `CompileKind::Host`, then they would end up being identical, causing a
801/// collision in the `UnitGraph`, and Cargo would end up randomly choosing one
802/// value or the other.
803///
804/// The solution is to keep normal, build and artifact dependencies separate when
805/// building the unit graph, and then run this second pass which will try to
806/// combine shared dependencies safely. By adding a hash of the dependencies
807/// to the `Unit`, this allows the `CompileKind` to be changed back to `Host`
808/// and `artifact_target_for_features` to be removed without fear of an unwanted
809/// collision for build or artifact dependencies.
810///
811/// This is also responsible for adjusting the `strip` profile option to
812/// opportunistically strip if debug is 0 for all dependencies. This helps
813/// remove debuginfo added by the standard library.
814///
815/// This is also responsible for adjusting the `debug` setting for host
816/// dependencies, turning off debug if the user has not explicitly enabled it,
817/// and the unit is not shared with a target unit.
818///
819/// This is also responsible for adjusting whether each unit should be compiled
820/// or not regarding `--compile-time-deps` flag.
821fn rebuild_unit_graph_shared(
822    interner: &UnitInterner,
823    unit_graph: UnitGraph,
824    roots: &[Unit],
825    scrape_units: &[Unit],
826    to_host: Option<CompileKind>,
827    compile_time_deps_only: bool,
828) -> (Vec<Unit>, Vec<Unit>, UnitGraph) {
829    let mut result = UnitGraph::new();
830    // Map of the old unit to the new unit, used to avoid recursing into units
831    // that have already been computed to improve performance.
832    let mut memo = HashMap::new();
833    let new_roots = roots
834        .iter()
835        .map(|root| {
836            traverse_and_share(
837                interner,
838                &mut memo,
839                &mut result,
840                &unit_graph,
841                root,
842                true,
843                false,
844                to_host,
845                compile_time_deps_only,
846            )
847        })
848        .collect();
849    // If no unit in the unit graph ended up having scrape units attached as dependencies,
850    // then they won't have been discovered in traverse_and_share and hence won't be in
851    // memo. So we filter out missing scrape units.
852    let new_scrape_units = scrape_units
853        .iter()
854        .map(|unit| memo.get(unit).unwrap().clone())
855        .collect();
856    (new_roots, new_scrape_units, result)
857}
858
859/// Recursive function for rebuilding the graph.
860///
861/// This walks `unit_graph`, starting at the given `unit`. It inserts the new
862/// units into `new_graph`, and returns a new updated version of the given
863/// unit (`dep_hash` is filled in, and `kind` switched if necessary).
864fn traverse_and_share(
865    interner: &UnitInterner,
866    memo: &mut HashMap<Unit, Unit>,
867    new_graph: &mut UnitGraph,
868    unit_graph: &UnitGraph,
869    unit: &Unit,
870    unit_is_root: bool,
871    unit_is_for_host: bool,
872    to_host: Option<CompileKind>,
873    compile_time_deps_only: bool,
874) -> Unit {
875    if let Some(new_unit) = memo.get(unit) {
876        // Already computed, no need to recompute.
877        return new_unit.clone();
878    }
879    let mut dep_hash = StableHasher::new();
880    let skip_non_compile_time_deps = compile_time_deps_only
881        && (!unit.target.is_compile_time_dependency() ||
882            // Root unit is not a dependency unless other units are dependant
883            // to it.
884            unit_is_root);
885    let new_deps: Vec<_> = unit_graph[unit]
886        .iter()
887        .map(|dep| {
888            let new_dep_unit = traverse_and_share(
889                interner,
890                memo,
891                new_graph,
892                unit_graph,
893                &dep.unit,
894                false,
895                dep.unit_for.is_for_host(),
896                to_host,
897                // If we should compile the current unit, we should also compile
898                // its dependencies. And if not, we should compile compile time
899                // dependencies only.
900                skip_non_compile_time_deps,
901            );
902            new_dep_unit.hash(&mut dep_hash);
903            UnitDep {
904                unit: new_dep_unit,
905                ..dep.clone()
906            }
907        })
908        .collect();
909    // Here, we have recursively traversed this unit's dependencies, and hashed them: we can
910    // finalize the dep hash.
911    let new_dep_hash = Hasher::finish(&dep_hash);
912
913    // This is the key part of the sharing process: if the unit is a runtime dependency, whose
914    // target is the same as the host, we canonicalize the compile kind to `CompileKind::Host`.
915    // A possible host dependency counterpart to this unit would have that kind, and if such a unit
916    // exists in the current `unit_graph`, they will unify in the new unit graph map `new_graph`.
917    // The resulting unit graph will be optimized with less units, thanks to sharing these host
918    // dependencies.
919    let canonical_kind = match to_host {
920        Some(to_host) if to_host == unit.kind => CompileKind::Host,
921        _ => unit.kind,
922    };
923
924    let mut profile = unit.profile.clone();
925    if profile.strip.is_deferred() {
926        // If strip was not manually set, and all dependencies of this unit together
927        // with this unit have debuginfo turned off, we enable debuginfo stripping.
928        // This will remove pre-existing debug symbols coming from the standard library.
929        if !profile.debuginfo.is_turned_on()
930            && new_deps
931                .iter()
932                .all(|dep| !dep.unit.profile.debuginfo.is_turned_on())
933        {
934            profile.strip = profile.strip.strip_debuginfo();
935        }
936    }
937
938    // If this is a build dependency, and it's not shared with runtime dependencies, we can weaken
939    // its debuginfo level to optimize build times. We do nothing if it's an artifact dependency,
940    // as it and its debuginfo may end up embedded in the main program.
941    if unit_is_for_host
942        && to_host.is_some()
943        && profile.debuginfo.is_deferred()
944        && !unit.artifact.is_true()
945    {
946        // We create a "probe" test to see if a unit with the same explicit debuginfo level exists
947        // in the graph. This is the level we'd expect if it was set manually or the default value
948        // set by a profile for a runtime dependency: its canonical value.
949        let canonical_debuginfo = profile.debuginfo.finalize();
950        let mut canonical_profile = profile.clone();
951        canonical_profile.debuginfo = canonical_debuginfo;
952        let unit_probe = interner.intern(
953            &unit.pkg,
954            &unit.target,
955            canonical_profile,
956            to_host.unwrap(),
957            unit.mode,
958            unit.features.clone(),
959            unit.rustflags.clone(),
960            unit.rustdocflags.clone(),
961            unit.links_overrides.clone(),
962            unit.is_std,
963            unit.dep_hash,
964            unit.artifact,
965            unit.artifact_target_for_features,
966            unit.skip_non_compile_time_dep,
967        );
968
969        // We can now turn the deferred value into its actual final value.
970        profile.debuginfo = if unit_graph.contains_key(&unit_probe) {
971            // The unit is present in both build time and runtime subgraphs: we canonicalize its
972            // level to the other unit's, thus ensuring reuse between the two to optimize build times.
973            canonical_debuginfo
974        } else {
975            // The unit is only present in the build time subgraph, we can weaken its debuginfo
976            // level to optimize build times.
977            canonical_debuginfo.weaken()
978        }
979    }
980
981    let new_unit = interner.intern(
982        &unit.pkg,
983        &unit.target,
984        profile,
985        canonical_kind,
986        unit.mode,
987        unit.features.clone(),
988        unit.rustflags.clone(),
989        unit.rustdocflags.clone(),
990        unit.links_overrides.clone(),
991        unit.is_std,
992        new_dep_hash,
993        unit.artifact,
994        // Since `dep_hash` is now filled in, there's no need to specify the artifact target
995        // for target-dependent feature resolution
996        None,
997        skip_non_compile_time_deps,
998    );
999    if !unit_is_root || !compile_time_deps_only {
1000        assert!(memo.insert(unit.clone(), new_unit.clone()).is_none());
1001    }
1002    new_graph.entry(new_unit.clone()).or_insert(new_deps);
1003    new_unit
1004}
1005
1006/// Removes duplicate `CompileMode::Doc` units that would cause problems with
1007/// filename collisions.
1008///
1009/// Rustdoc only separates units by crate name in the file directory
1010/// structure. If any two units with the same crate name exist, this would
1011/// cause a filename collision, causing different rustdoc invocations to stomp
1012/// on one another's files.
1013///
1014/// Unfortunately this does not remove all duplicates, as some of them are
1015/// either user error, or difficult to remove. Cases that I can think of:
1016///
1017/// - Same target name in different packages. See the `collision_doc` test.
1018/// - Different sources. See `collision_doc_sources` test.
1019///
1020/// Ideally this would not be necessary.
1021fn remove_duplicate_doc(
1022    build_config: &BuildConfig,
1023    root_units: &[Unit],
1024    unit_graph: &mut UnitGraph,
1025) {
1026    // First, create a mapping of crate_name -> Unit so we can see where the
1027    // duplicates are.
1028    let mut all_docs: HashMap<String, Vec<Unit>> = HashMap::new();
1029    for unit in unit_graph.keys() {
1030        if unit.mode.is_doc() {
1031            all_docs
1032                .entry(unit.target.crate_name())
1033                .or_default()
1034                .push(unit.clone());
1035        }
1036    }
1037    // Keep track of units to remove so that they can be efficiently removed
1038    // from the unit_deps.
1039    let mut removed_units: HashSet<Unit> = HashSet::new();
1040    let mut remove = |units: Vec<Unit>, reason: &str, cb: &dyn Fn(&Unit) -> bool| -> Vec<Unit> {
1041        let (to_remove, remaining_units): (Vec<Unit>, Vec<Unit>) = units
1042            .into_iter()
1043            .partition(|unit| cb(unit) && !root_units.contains(unit));
1044        for unit in to_remove {
1045            tracing::debug!(
1046                "removing duplicate doc due to {} for package {} target `{}`",
1047                reason,
1048                unit.pkg,
1049                unit.target.name()
1050            );
1051            unit_graph.remove(&unit);
1052            removed_units.insert(unit);
1053        }
1054        remaining_units
1055    };
1056    // Iterate over the duplicates and try to remove them from unit_graph.
1057    for (_crate_name, mut units) in all_docs {
1058        if units.len() == 1 {
1059            continue;
1060        }
1061        // Prefer target over host if --target was not specified.
1062        if build_config
1063            .requested_kinds
1064            .iter()
1065            .all(CompileKind::is_host)
1066        {
1067            // Note these duplicates may not be real duplicates, since they
1068            // might get merged in rebuild_unit_graph_shared. Either way, it
1069            // shouldn't hurt to remove them early (although the report in the
1070            // log might be confusing).
1071            units = remove(units, "host/target merger", &|unit| unit.kind.is_host());
1072            if units.len() == 1 {
1073                continue;
1074            }
1075        }
1076        // Prefer newer versions over older.
1077        let mut source_map: HashMap<(InternedString, SourceId, CompileKind), Vec<Unit>> =
1078            HashMap::new();
1079        for unit in units {
1080            let pkg_id = unit.pkg.package_id();
1081            // Note, this does not detect duplicates from different sources.
1082            source_map
1083                .entry((pkg_id.name(), pkg_id.source_id(), unit.kind))
1084                .or_default()
1085                .push(unit);
1086        }
1087        let mut remaining_units = Vec::new();
1088        for (_key, mut units) in source_map {
1089            if units.len() > 1 {
1090                units.sort_by(|a, b| a.pkg.version().partial_cmp(b.pkg.version()).unwrap());
1091                // Remove any entries with version < newest.
1092                let newest_version = units.last().unwrap().pkg.version().clone();
1093                let keep_units = remove(units, "older version", &|unit| {
1094                    unit.pkg.version() < &newest_version
1095                });
1096                remaining_units.extend(keep_units);
1097            } else {
1098                remaining_units.extend(units);
1099            }
1100        }
1101        if remaining_units.len() == 1 {
1102            continue;
1103        }
1104        // Are there other heuristics to remove duplicates that would make
1105        // sense? Maybe prefer path sources over all others?
1106    }
1107    // Also remove units from the unit_deps so there aren't any dangling edges.
1108    for unit_deps in unit_graph.values_mut() {
1109        unit_deps.retain(|unit_dep| !removed_units.contains(&unit_dep.unit));
1110    }
1111    // Remove any orphan units that were detached from the graph.
1112    let mut visited = HashSet::new();
1113    fn visit(unit: &Unit, graph: &UnitGraph, visited: &mut HashSet<Unit>) {
1114        if !visited.insert(unit.clone()) {
1115            return;
1116        }
1117        for dep in &graph[unit] {
1118            visit(&dep.unit, graph, visited);
1119        }
1120    }
1121    for unit in root_units {
1122        visit(unit, unit_graph, &mut visited);
1123    }
1124    unit_graph.retain(|unit, _| visited.contains(unit));
1125}
1126
1127/// Override crate types for given units.
1128///
1129/// This is primarily used by `cargo rustc --crate-type`.
1130fn override_rustc_crate_types(
1131    units: &mut [Unit],
1132    args: &[String],
1133    interner: &UnitInterner,
1134) -> CargoResult<()> {
1135    if units.len() != 1 {
1136        anyhow::bail!(
1137            "crate types to rustc can only be passed to one \
1138            target, consider filtering\nthe package by passing, \
1139            e.g., `--lib` or `--example` to specify a single target"
1140        );
1141    }
1142
1143    let unit = &units[0];
1144    let override_unit = |f: fn(Vec<CrateType>) -> TargetKind| {
1145        let crate_types = args.iter().map(|s| s.into()).collect();
1146        let mut target = unit.target.clone();
1147        target.set_kind(f(crate_types));
1148        interner.intern(
1149            &unit.pkg,
1150            &target,
1151            unit.profile.clone(),
1152            unit.kind,
1153            unit.mode,
1154            unit.features.clone(),
1155            unit.rustflags.clone(),
1156            unit.rustdocflags.clone(),
1157            unit.links_overrides.clone(),
1158            unit.is_std,
1159            unit.dep_hash,
1160            unit.artifact,
1161            unit.artifact_target_for_features,
1162            unit.skip_non_compile_time_dep,
1163        )
1164    };
1165    units[0] = match unit.target.kind() {
1166        TargetKind::Lib(_) => override_unit(TargetKind::Lib),
1167        TargetKind::ExampleLib(_) => override_unit(TargetKind::ExampleLib),
1168        _ => {
1169            anyhow::bail!(
1170                "crate types can only be specified for libraries and example libraries.\n\
1171                Binaries, tests, and benchmarks are always the `bin` crate type"
1172            );
1173        }
1174    };
1175
1176    Ok(())
1177}
1178
1179/// Gets all of the features enabled for a package, plus its dependencies'
1180/// features.
1181///
1182/// Dependencies are added as `dep_name/feat_name` because `required-features`
1183/// wants to support that syntax.
1184pub fn resolve_all_features(
1185    resolve_with_overrides: &Resolve,
1186    resolved_features: &features::ResolvedFeatures,
1187    package_set: &PackageSet<'_>,
1188    package_id: PackageId,
1189) -> HashSet<String> {
1190    let mut features: HashSet<String> = resolved_features
1191        .activated_features(package_id, FeaturesFor::NormalOrDev)
1192        .iter()
1193        .map(|s| s.to_string())
1194        .collect();
1195
1196    // Include features enabled for use by dependencies so targets can also use them with the
1197    // required-features field when deciding whether to be built or skipped.
1198    for (dep_id, deps) in resolve_with_overrides.deps(package_id) {
1199        let is_proc_macro = package_set
1200            .get_one(dep_id)
1201            .expect("packages downloaded")
1202            .proc_macro();
1203        for dep in deps {
1204            let features_for = FeaturesFor::from_for_host(is_proc_macro || dep.is_build());
1205            for feature in resolved_features
1206                .activated_features_unverified(dep_id, features_for)
1207                .unwrap_or_default()
1208            {
1209                features.insert(format!("{}/{}", dep.name_in_toml(), feature));
1210            }
1211        }
1212    }
1213
1214    features
1215}