Skip to main content

cargo/workspace/
profiles.rs

1//! Handles built-in and customizable compiler flag presets.
2//!
3//! [`Profiles`] is a collections of built-in profiles, and profiles defined
4//! in the root manifest and configurations.
5//!
6//! To start using a profile, most of the time you start from [`Profiles::new`],
7//! which does the followings:
8//!
9//! - Create a `Profiles` by merging profiles from configs onto the profile
10//!   from root manifest (see [`merge_config_profiles`]).
11//! - Add built-in profiles onto it (see [`Profiles::add_root_profiles`]).
12//! - Process profile inheritance for each profiles. (see [`Profiles::add_maker`]).
13//!
14//! Then you can query a [`Profile`] via [`Profiles::get_profile`], which respects
15//! the profile overridden hierarchy described in below. The [`Profile`] you get
16//! is basically an immutable struct containing the compiler flag presets.
17//!
18//! ## Profile overridden hierarchy
19//!
20//! Profile settings can be overridden for specific packages and build-time crates.
21//! The precedence is explained in [`ProfileMaker`].
22//! The algorithm happens within [`ProfileMaker::get_profile`].
23
24use crate::compiler::{CompileKind, CompileTarget, Unit};
25use crate::context;
26use crate::resolver::Resolve;
27use crate::resolver::features::FeaturesFor;
28use crate::util::interning::InternedString;
29use crate::util::{CargoResult, GlobalContext, closest_msg};
30use crate::workspace::dependency::Artifact;
31use crate::workspace::parser::validate_profile;
32use crate::workspace::{PackageId, PackageIdSpec, PackageIdSpecQuery, Target, Workspace};
33use anyhow::{Context as _, bail};
34use cargo_util::collections::{HashMap, HashSet};
35use cargo_util::is_ci;
36use cargo_util_schemas::manifest::{Hints, TomlTrimPaths};
37use cargo_util_schemas::manifest::{
38    ProfilePackageSpec, StringOrBool, TomlDebugInfo, TomlProfile, TomlProfiles,
39};
40use cargo_util_terminal::Shell;
41use std::collections::BTreeMap;
42use std::hash::Hash;
43use std::ops::RangeInclusive;
44use std::{cmp, fmt, hash};
45
46/// Collection of all profiles.
47///
48/// To get a specific [`Profile`], you usually create this and call [`get_profile`] then.
49///
50/// [`get_profile`]: Profiles::get_profile
51#[derive(Clone, Debug)]
52pub struct Profiles {
53    /// Incremental compilation can be overridden globally via:
54    /// - `CARGO_INCREMENTAL` environment variable.
55    /// - `build.incremental` config value.
56    incremental: Option<bool>,
57    /// Map of profile name to directory name for that profile.
58    dir_names: HashMap<InternedString, InternedString>,
59    /// The profile makers. Key is the profile name.
60    by_name: HashMap<InternedString, ProfileMaker>,
61    /// The original profiles written by the user in the manifest and config.
62    ///
63    /// This is here to assist with error reporting, as the `ProfileMaker`
64    /// values have the inherits chains all merged together.
65    original_profiles: BTreeMap<InternedString, TomlProfile>,
66    /// The profile the user requested to use.
67    requested_profile: InternedString,
68    /// The host target for rustc being used by this `Profiles`.
69    rustc_host: InternedString,
70    /// Whether `-Zhint-min-opt-level` was passed, enabling the
71    /// `hints.min-opt-level` manifest key.
72    hint_min_opt_level: bool,
73}
74
75impl Profiles {
76    pub fn new(ws: &Workspace<'_>, requested_profile: InternedString) -> CargoResult<Profiles> {
77        let gctx = ws.gctx();
78        let incremental = match gctx.get_env_os("CARGO_INCREMENTAL") {
79            Some(v) => Some(v == "1"),
80            None => gctx
81                .build_config()?
82                .incremental
83                .or_else(|| is_ci().then_some(false)),
84        };
85        let mut profiles = merge_config_profiles(ws, requested_profile)?;
86        let rustc_host = ws.gctx().load_global_rustc(Some(ws))?.host;
87
88        let mut profile_makers = Profiles {
89            incremental,
90            dir_names: Self::predefined_dir_names(),
91            by_name: HashMap::default(),
92            original_profiles: profiles.clone(),
93            requested_profile,
94            rustc_host,
95            hint_min_opt_level: gctx.cli_unstable().hint_min_opt_level,
96        };
97
98        Self::add_root_profiles(&mut profile_makers, &profiles);
99
100        // Merge with predefined profiles.
101        use std::collections::btree_map::Entry;
102        for (predef_name, mut predef_prof) in Self::predefined_profiles().into_iter() {
103            match profiles.entry(predef_name.into()) {
104                Entry::Vacant(vac) => {
105                    vac.insert(predef_prof);
106                }
107                Entry::Occupied(mut oc) => {
108                    // Override predefined with the user-provided Toml.
109                    let r = oc.get_mut();
110                    predef_prof.merge(r);
111                    *r = predef_prof;
112                }
113            }
114        }
115
116        for (name, profile) in &profiles {
117            profile_makers.add_maker(*name, profile, &profiles)?;
118        }
119        // Verify that the requested profile is defined *somewhere*.
120        // This simplifies the API (no need for CargoResult), and enforces
121        // assumptions about how config profiles are loaded.
122        profile_makers.get_profile_maker(&requested_profile)?;
123        Ok(profile_makers)
124    }
125
126    /// Returns the hard-coded directory names for built-in profiles.
127    fn predefined_dir_names() -> HashMap<InternedString, InternedString> {
128        HashMap::from_iter([
129            ("dev".into(), "debug".into()),
130            ("test".into(), "debug".into()),
131            ("bench".into(), "release".into()),
132        ])
133    }
134
135    /// Initialize `by_name` with the two "root" profiles, `dev`, and
136    /// `release` given the user's definition.
137    fn add_root_profiles(
138        profile_makers: &mut Profiles,
139        profiles: &BTreeMap<InternedString, TomlProfile>,
140    ) {
141        profile_makers.by_name.insert(
142            "dev".into(),
143            ProfileMaker::new(Profile::default_dev(), profiles.get("dev").cloned()),
144        );
145
146        profile_makers.by_name.insert(
147            "release".into(),
148            ProfileMaker::new(Profile::default_release(), profiles.get("release").cloned()),
149        );
150    }
151
152    /// Returns the built-in profiles (not including dev/release, which are
153    /// "root" profiles).
154    fn predefined_profiles() -> Vec<(&'static str, TomlProfile)> {
155        vec![
156            (
157                "debug",
158                TomlProfile {
159                    inherits: Some(String::from("dev")),
160                    debug: Some(TomlDebugInfo::Full),
161                    ..TomlProfile::default()
162                },
163            ),
164            (
165                "bench",
166                TomlProfile {
167                    inherits: Some(String::from("release")),
168                    ..TomlProfile::default()
169                },
170            ),
171            (
172                "test",
173                TomlProfile {
174                    inherits: Some(String::from("dev")),
175                    ..TomlProfile::default()
176                },
177            ),
178            (
179                "doc",
180                TomlProfile {
181                    inherits: Some(String::from("dev")),
182                    ..TomlProfile::default()
183                },
184            ),
185        ]
186    }
187
188    /// Creates a `ProfileMaker`, and inserts it into `self.by_name`.
189    fn add_maker(
190        &mut self,
191        name: InternedString,
192        profile: &TomlProfile,
193        profiles: &BTreeMap<InternedString, TomlProfile>,
194    ) -> CargoResult<()> {
195        match &profile.dir_name {
196            None => {}
197            Some(dir_name) => {
198                self.dir_names.insert(name, dir_name.into());
199            }
200        }
201
202        // dev/release are "roots" and don't inherit.
203        if name == "dev" || name == "release" {
204            if profile.inherits.is_some() {
205                bail!(
206                    "`inherits` must not be specified in root profile `{}`",
207                    name
208                );
209            }
210            // Already inserted from `add_root_profiles`, no need to do anything.
211            return Ok(());
212        }
213
214        // Keep track for inherits cycles.
215        let mut set = HashSet::default();
216        set.insert(name);
217        let maker = self.process_chain(name, profile, &mut set, profiles)?;
218        self.by_name.insert(name, maker);
219        Ok(())
220    }
221
222    /// Build a `ProfileMaker` by recursively following the `inherits` setting.
223    ///
224    /// * `name`: The name of the profile being processed.
225    /// * `profile`: The TOML profile being processed.
226    /// * `set`: Set of profiles that have been visited, used to detect cycles.
227    /// * `profiles`: Map of all TOML profiles.
228    ///
229    /// Returns a `ProfileMaker` to be used for the given named profile.
230    fn process_chain(
231        &mut self,
232        name: InternedString,
233        profile: &TomlProfile,
234        set: &mut HashSet<InternedString>,
235        profiles: &BTreeMap<InternedString, TomlProfile>,
236    ) -> CargoResult<ProfileMaker> {
237        let mut maker = match &profile.inherits {
238            Some(inherits_name) if inherits_name == "dev" || inherits_name == "release" => {
239                // These are the root profiles added in `add_root_profiles`.
240                self.get_profile_maker(&inherits_name).unwrap().clone()
241            }
242            Some(inherits_name) => {
243                let inherits_name = inherits_name.into();
244                if !set.insert(inherits_name) {
245                    bail!(
246                        "profile inheritance loop detected with profile `{}` inheriting `{}`",
247                        name,
248                        inherits_name
249                    );
250                }
251
252                match profiles.get(&inherits_name) {
253                    None => {
254                        bail!(
255                            "profile `{}` inherits from `{}`, but that profile is not defined",
256                            name,
257                            inherits_name
258                        );
259                    }
260                    Some(parent) => self.process_chain(inherits_name, parent, set, profiles)?,
261                }
262            }
263            None => {
264                bail!(
265                    "profile `{}` is missing an `inherits` directive \
266                     (`inherits` is required for all profiles except `dev` or `release`)",
267                    name
268                );
269            }
270        };
271        match &mut maker.toml {
272            Some(toml) => toml.merge(profile),
273            None => maker.toml = Some(profile.clone()),
274        };
275        Ok(maker)
276    }
277
278    /// Retrieves the profile for a target.
279    /// `is_member` is whether or not this package is a member of the
280    /// workspace.
281    pub fn get_profile(
282        &self,
283        pkg_id: PackageId,
284        pkg_hints: Option<&Hints>,
285        is_member: bool,
286        is_local: bool,
287        unit_for: UnitFor,
288        kind: CompileKind,
289    ) -> Profile {
290        let maker = self.get_profile_maker(&self.requested_profile).unwrap();
291        let min_opt_level = if self.hint_min_opt_level {
292            parse_min_opt_level_hint(pkg_hints.and_then(|hints| hints.min_opt_level.as_ref()))
293                .ok()
294                .flatten()
295        } else {
296            // The `min_opt_level_hint` parse pass rule warns that the hint is being ignored.
297            None
298        };
299
300        let mut profile = maker.get_profile(
301            Some(pkg_id),
302            is_member,
303            unit_for.is_for_host(),
304            min_opt_level,
305        );
306
307        // Dealing with `panic=abort` and `panic=unwind` requires some special
308        // treatment. Be sure to process all the various options here.
309        match unit_for.panic_setting() {
310            PanicSetting::AlwaysUnwind => profile.panic = PanicStrategy::Unwind,
311            PanicSetting::ReadProfile => {}
312        }
313
314        // Default macOS debug information to being stored in the "unpacked"
315        // split-debuginfo format. At the time of this writing that's the only
316        // platform which has a stable `-Csplit-debuginfo` option for rustc,
317        // and it's typically much faster than running `dsymutil` on all builds
318        // in incremental cases.
319        if profile.debuginfo.is_turned_on() && profile.split_debuginfo.is_none() {
320            let target = match &kind {
321                CompileKind::Host => self.rustc_host.as_str(),
322                CompileKind::Target(target) => target.short_name(),
323            };
324            if target.contains("-apple-") {
325                profile.split_debuginfo = Some("unpacked".into());
326            }
327        }
328
329        // Incremental can be globally overridden.
330        if let Some(v) = self.incremental {
331            profile.incremental = v;
332        }
333
334        // Only enable incremental compilation for sources the user can
335        // modify (aka path sources). For things that change infrequently,
336        // non-incremental builds yield better performance in the compiler
337        // itself (aka crates.io / git dependencies)
338        //
339        // (see also https://github.com/rust-lang/cargo/issues/3972)
340        if !is_local {
341            profile.incremental = false;
342        }
343        profile.name = self.requested_profile;
344        profile
345    }
346
347    /// The profile for *running* a `build.rs` script is only used for setting
348    /// a few environment variables. To ensure proper de-duplication of the
349    /// running `Unit`, this uses a stripped-down profile (so that unrelated
350    /// profile flags don't cause `build.rs` to needlessly run multiple
351    /// times).
352    pub fn get_profile_run_custom_build(&self, for_unit_profile: &Profile) -> Profile {
353        let mut result = Profile::default();
354        result.name = for_unit_profile.name;
355        result.root = for_unit_profile.root;
356        result.debuginfo = for_unit_profile.debuginfo;
357        result.opt_level = for_unit_profile.opt_level;
358        result.debug_assertions = for_unit_profile.debug_assertions;
359        result.trim_paths = for_unit_profile.trim_paths.clone();
360        result
361    }
362
363    /// This returns the base profile. This is currently used for the
364    /// `[Finished]` line. It is not entirely accurate, since it doesn't
365    /// select for the package that was actually built.
366    pub fn base_profile(&self) -> Profile {
367        let profile_name = self.requested_profile;
368        let maker = self.get_profile_maker(&profile_name).unwrap();
369        maker.get_profile(
370            None, /*is_member*/ true, /*is_for_host*/ false, None,
371        )
372    }
373
374    /// Gets the directory name for a profile, like `debug` or `release`.
375    pub fn get_dir_name(&self) -> InternedString {
376        *self
377            .dir_names
378            .get(&self.requested_profile)
379            .unwrap_or(&self.requested_profile)
380    }
381
382    /// Used to check for overrides for non-existing packages.
383    pub fn validate_packages(
384        &self,
385        profiles: Option<&TomlProfiles>,
386        shell: &mut Shell,
387        resolve: &Resolve,
388    ) -> CargoResult<()> {
389        for (name, profile) in &self.by_name {
390            // If the user did not specify an override, skip this. This is here
391            // to avoid generating errors for inherited profiles which don't
392            // specify package overrides. The `by_name` profile has had the inherits
393            // chain merged, so we need to look at the original source to check
394            // if an override was specified.
395            if self
396                .original_profiles
397                .get(name)
398                .and_then(|orig| orig.package.as_ref())
399                .is_none()
400            {
401                continue;
402            }
403            let found = validate_packages_unique(resolve, name, &profile.toml)?;
404            // We intentionally do not validate unmatched packages for config
405            // profiles, in case they are defined in a central location. This
406            // iterates over the manifest profiles only.
407            if let Some(profiles) = profiles {
408                if let Some(toml_profile) = profiles.get(name) {
409                    validate_packages_unmatched(shell, resolve, name, toml_profile, &found)?;
410                }
411            }
412        }
413        Ok(())
414    }
415
416    /// Returns the profile maker for the given profile name.
417    fn get_profile_maker(&self, name: &str) -> CargoResult<&ProfileMaker> {
418        self.by_name
419            .get(name)
420            .ok_or_else(|| anyhow::format_err!("profile `{}` is not defined", name))
421    }
422
423    /// Returns an iterator over all profile names known to Cargo.
424    pub fn profile_names(&self) -> impl Iterator<Item = InternedString> + '_ {
425        self.by_name.keys().copied()
426    }
427}
428
429pub(crate) enum MinOptLevelHintError {
430    OutOfRange {
431        level: i64,
432        expected: RangeInclusive<i64>,
433    },
434    WrongType(&'static str),
435}
436
437pub(crate) fn parse_min_opt_level_hint(
438    value: Option<&toml::Value>,
439) -> Result<Option<u32>, MinOptLevelHintError> {
440    let Some(value) = value else {
441        return Ok(None);
442    };
443    let Some(level) = value.as_integer() else {
444        return Err(MinOptLevelHintError::WrongType(value.type_str()));
445    };
446    let expected = 0..=3;
447    if expected.contains(&level) {
448        Ok(Some(level as u32))
449    } else {
450        Err(MinOptLevelHintError::OutOfRange { level, expected })
451    }
452}
453
454/// An object used for handling the profile hierarchy.
455///
456/// The precedence of profiles are (first one wins):
457///
458/// - Profiles in `.cargo/config` files (using same order as below).
459/// - `[profile.dev.package.name]` -- a named package.
460/// - `[profile.dev.package."*"]` -- this cannot apply to workspace members.
461/// - `[profile.dev.build-override]` -- this can only apply to `build.rs` scripts
462///   and their dependencies.
463/// - `[profile.dev]`
464/// - Default (hard-coded) values.
465#[derive(Debug, Clone)]
466struct ProfileMaker {
467    /// The starting, hard-coded defaults for the profile.
468    default: Profile,
469    /// The TOML profile defined in `Cargo.toml` or config.
470    ///
471    /// This is None if the user did not specify one, in which case the
472    /// `default` is used. Note that the built-in defaults for test/bench/doc
473    /// always set this since they need to declare the `inherits` value.
474    toml: Option<TomlProfile>,
475}
476
477impl ProfileMaker {
478    /// Creates a new `ProfileMaker`.
479    ///
480    /// Note that this does not process `inherits`, the caller is responsible for that.
481    fn new(default: Profile, toml: Option<TomlProfile>) -> ProfileMaker {
482        ProfileMaker { default, toml }
483    }
484
485    /// Generates a new `Profile`.
486    fn get_profile(
487        &self,
488        pkg_id: Option<PackageId>,
489        is_member: bool,
490        is_for_host: bool,
491        min_opt_level: Option<u32>,
492    ) -> Profile {
493        let mut profile = self.default.clone();
494
495        // First apply profile-specific settings, things like
496        // `[profile.release]`
497        if let Some(toml) = &self.toml {
498            merge_profile(&mut profile, toml);
499        }
500
501        // Next start overriding those settings. First comes build dependencies
502        // which default to opt-level 0...
503        if is_for_host {
504            // For-host units are things like procedural macros, build scripts, and
505            // their dependencies. For these units most projects simply want them
506            // to compile quickly and the runtime doesn't matter too much since
507            // they tend to process very little data. For this reason we default
508            // them to a "compile as quickly as possible" mode which for now means
509            // basically turning down the optimization level and avoid limiting
510            // codegen units. This ensures that we spend little time optimizing as
511            // well as enabling parallelism by not constraining codegen units.
512            profile.opt_level = "0".into();
513            profile.codegen_units = None;
514
515            // For build dependencies, we usually don't need debuginfo, and
516            // removing it will compile faster. However, that can conflict with
517            // a unit graph optimization, reusing units that are shared between
518            // build dependencies and runtime dependencies: when the runtime
519            // target is the same as the build host, we only need to build a
520            // dependency once and reuse the results, instead of building twice.
521            // We defer the choice of the debuginfo level until we can check if
522            // a unit is shared. If that's the case, we'll use the deferred value
523            // below so the unit can be reused, otherwise we can avoid emitting
524            // the unit's debuginfo.
525            profile.debuginfo = DebugInfo::Deferred(profile.debuginfo.into_inner());
526        }
527        if let (Some(min_opt_level), Ok(opt_level)) =
528            (min_opt_level, profile.opt_level.as_str().parse::<u32>())
529        {
530            if opt_level < min_opt_level {
531                profile.opt_level = min_opt_level.to_string().into();
532            }
533        }
534        // ... and next comes any other sorts of overrides specified in
535        // profiles, such as `[profile.release.build-override]` or
536        // `[profile.release.package.foo]`
537        if let Some(toml) = &self.toml {
538            merge_toml_overrides(pkg_id, is_member, is_for_host, &mut profile, toml);
539        }
540        profile
541    }
542}
543
544/// Merge package and build overrides from the given TOML profile into the given `Profile`.
545fn merge_toml_overrides(
546    pkg_id: Option<PackageId>,
547    is_member: bool,
548    is_for_host: bool,
549    profile: &mut Profile,
550    toml: &TomlProfile,
551) {
552    if is_for_host {
553        if let Some(build_override) = &toml.build_override {
554            merge_profile(profile, build_override);
555        }
556    }
557    if let Some(overrides) = toml.package.as_ref() {
558        if !is_member {
559            if let Some(all) = overrides.get(&ProfilePackageSpec::All) {
560                merge_profile(profile, all);
561            }
562        }
563        if let Some(pkg_id) = pkg_id {
564            let mut matches = overrides
565                .iter()
566                .filter_map(|(key, spec_profile)| match *key {
567                    ProfilePackageSpec::All => None,
568                    ProfilePackageSpec::Spec(ref s) => {
569                        if s.matches(pkg_id) {
570                            Some(spec_profile)
571                        } else {
572                            None
573                        }
574                    }
575                });
576            if let Some(spec_profile) = matches.next() {
577                merge_profile(profile, spec_profile);
578                // `validate_packages` should ensure that there are
579                // no additional matches.
580                assert!(
581                    matches.next().is_none(),
582                    "package `{}` matched multiple package profile overrides",
583                    pkg_id
584                );
585            }
586        }
587    }
588}
589
590/// Merge the given TOML profile into the given `Profile`.
591///
592/// Does not merge overrides (see `merge_toml_overrides`).
593fn merge_profile(profile: &mut Profile, toml: &TomlProfile) {
594    if let Some(ref opt_level) = toml.opt_level {
595        profile.opt_level = opt_level.0.as_str().into();
596    }
597    match toml.lto {
598        Some(StringOrBool::Bool(b)) => profile.lto = Lto::Bool(b),
599        Some(StringOrBool::String(ref n)) if is_off(n.as_str()) => profile.lto = Lto::Off,
600        Some(StringOrBool::String(ref n)) => profile.lto = Lto::Named(n.into()),
601        None => {}
602    }
603    if toml.codegen_backend.is_some() {
604        profile.codegen_backend = toml.codegen_backend.as_ref().map(InternedString::from);
605    }
606    if toml.codegen_units.is_some() {
607        profile.codegen_units = toml.codegen_units;
608    }
609    if let Some(debuginfo) = toml.debug {
610        profile.debuginfo = DebugInfo::Resolved(debuginfo);
611    }
612    if let Some(debug_assertions) = toml.debug_assertions {
613        profile.debug_assertions = debug_assertions;
614    }
615    if let Some(split_debuginfo) = &toml.split_debuginfo {
616        profile.split_debuginfo = Some(split_debuginfo.into());
617    }
618    if let Some(rpath) = toml.rpath {
619        profile.rpath = rpath;
620    }
621    if let Some(panic) = &toml.panic {
622        profile.panic = match panic.as_str() {
623            "unwind" => PanicStrategy::Unwind,
624            "abort" => PanicStrategy::Abort,
625            "immediate-abort" => PanicStrategy::ImmediateAbort,
626            // This should be validated in TomlProfile::validate
627            _ => panic!("Unexpected panic setting `{}`", panic),
628        };
629    }
630    if let Some(overflow_checks) = toml.overflow_checks {
631        profile.overflow_checks = overflow_checks;
632    }
633    if let Some(incremental) = toml.incremental {
634        profile.incremental = incremental;
635    }
636    if let Some(flags) = &toml.rustflags {
637        profile.rustflags = flags.iter().map(InternedString::from).collect();
638    }
639    if let Some(trim_paths) = &toml.trim_paths {
640        profile.trim_paths = trim_paths.clone();
641    }
642    if let Some(hint_mostly_unused) = toml.hint_mostly_unused {
643        profile.hint_mostly_unused = Some(hint_mostly_unused);
644    }
645    profile.strip = match toml.strip {
646        Some(StringOrBool::Bool(true)) => Strip::Resolved(StripInner::Named("symbols".into())),
647        Some(StringOrBool::Bool(false)) => Strip::Resolved(StripInner::None),
648        Some(StringOrBool::String(ref n)) if n.as_str() == "none" => {
649            Strip::Resolved(StripInner::None)
650        }
651        Some(StringOrBool::String(ref n)) => Strip::Resolved(StripInner::Named(n.into())),
652        None => profile.strip,
653    };
654}
655
656/// The root profile (dev/release).
657///
658/// This is currently only used for the `PROFILE` env var for build scripts
659/// for backwards compatibility. We should probably deprecate `PROFILE` and
660/// encourage using things like `DEBUG` and `OPT_LEVEL` instead.
661#[derive(Clone, Copy, Eq, PartialOrd, Ord, PartialEq, Debug)]
662pub enum ProfileRoot {
663    Release,
664    Debug,
665}
666
667/// Profile settings used to determine which compiler flags to use for a
668/// target.
669#[derive(Clone, Eq, PartialOrd, Ord, serde::Serialize)]
670pub struct Profile {
671    pub name: InternedString,
672    pub opt_level: InternedString,
673    #[serde(skip)] // named profiles are unstable
674    pub root: ProfileRoot,
675    pub lto: Lto,
676    // `None` means use rustc default.
677    pub codegen_backend: Option<InternedString>,
678    // `None` means use rustc default.
679    pub codegen_units: Option<u32>,
680    pub debuginfo: DebugInfo,
681    pub split_debuginfo: Option<InternedString>,
682    pub debug_assertions: bool,
683    pub overflow_checks: bool,
684    pub rpath: bool,
685    pub incremental: bool,
686    pub panic: PanicStrategy,
687    pub strip: Strip,
688    #[serde(skip_serializing_if = "Vec::is_empty")] // remove when `rustflags` is stabilized
689    // Note that `rustflags` is used for the cargo-feature `profile_rustflags`
690    pub rustflags: Vec<InternedString>,
691    pub trim_paths: TomlTrimPaths,
692    #[serde(skip_serializing_if = "Option::is_none")]
693    pub hint_mostly_unused: Option<bool>,
694}
695
696impl Default for Profile {
697    fn default() -> Profile {
698        Profile {
699            name: "".into(),
700            opt_level: "0".into(),
701            root: ProfileRoot::Debug,
702            lto: Lto::Bool(false),
703            codegen_backend: None,
704            codegen_units: None,
705            debuginfo: DebugInfo::Resolved(TomlDebugInfo::None),
706            debug_assertions: false,
707            split_debuginfo: None,
708            overflow_checks: false,
709            rpath: false,
710            incremental: false,
711            panic: PanicStrategy::Unwind,
712            strip: Strip::Deferred(StripInner::None),
713            rustflags: vec![],
714            trim_paths: TomlTrimPaths::None,
715            hint_mostly_unused: None,
716        }
717    }
718}
719
720compact_debug! {
721    impl fmt::Debug for Profile {
722        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
723            let (default, default_name) = match self.name.as_str() {
724                "dev" => (Profile::default_dev(), "default_dev()"),
725                "release" => (Profile::default_release(), "default_release()"),
726                _ => (Profile::default(), "default()"),
727            };
728            [debug_the_fields(
729                name
730                opt_level
731                lto
732                root
733                codegen_backend
734                codegen_units
735                debuginfo
736                split_debuginfo
737                debug_assertions
738                overflow_checks
739                rpath
740                incremental
741                panic
742                strip
743                rustflags
744                trim_paths
745                hint_mostly_unused
746            )]
747        }
748    }
749}
750
751impl fmt::Display for Profile {
752    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
753        write!(f, "Profile({})", self.name)
754    }
755}
756
757impl hash::Hash for Profile {
758    fn hash<H>(&self, state: &mut H)
759    where
760        H: hash::Hasher,
761    {
762        self.comparable().hash(state);
763    }
764}
765
766impl cmp::PartialEq for Profile {
767    fn eq(&self, other: &Self) -> bool {
768        self.comparable() == other.comparable()
769    }
770}
771
772impl Profile {
773    /// Returns a built-in `dev` profile.
774    fn default_dev() -> Profile {
775        Profile {
776            name: "dev".into(),
777            root: ProfileRoot::Debug,
778            debuginfo: DebugInfo::Resolved(TomlDebugInfo::LineTablesOnly),
779            debug_assertions: true,
780            overflow_checks: true,
781            incremental: true,
782            ..Profile::default()
783        }
784    }
785
786    /// Returns a built-in `release` profile.
787    fn default_release() -> Profile {
788        Profile {
789            name: "release".into(),
790            root: ProfileRoot::Release,
791            opt_level: "3".into(),
792            ..Profile::default()
793        }
794    }
795
796    /// Compares all fields except `name`, which doesn't affect compilation.
797    /// This is necessary for `Unit` deduplication for things like "test" and
798    /// "dev" which are essentially the same.
799    fn comparable(&self) -> impl Hash + Eq + '_ {
800        (
801            self.opt_level,
802            self.lto,
803            self.codegen_backend,
804            self.codegen_units,
805            self.debuginfo,
806            self.split_debuginfo,
807            self.debug_assertions,
808            self.overflow_checks,
809            self.rpath,
810            (self.incremental, self.panic, self.strip),
811            &self.rustflags,
812            &self.trim_paths,
813        )
814    }
815}
816
817/// The debuginfo level setting.
818///
819/// This is semantically a [`TomlDebugInfo`], and should be used as so via the
820/// [`DebugInfo::into_inner`] method for all intents and purposes.
821///
822/// Internally, it's used to model a debuginfo level whose value can be deferred
823/// for optimization purposes: host dependencies usually don't need the same
824/// level as target dependencies. For dependencies that are shared between the
825/// two however, that value also affects reuse: different debuginfo levels would
826/// cause to build a unit twice. By deferring the choice until we know
827/// whether to choose the optimized value or the default value, we can make sure
828/// the unit is only built once and the unit graph is still optimized.
829#[derive(Debug, Copy, Clone, serde::Serialize)]
830#[serde(untagged)]
831pub enum DebugInfo {
832    /// A debuginfo level that is fixed and will not change.
833    ///
834    /// This can be set by a profile, user, or default value.
835    Resolved(TomlDebugInfo),
836    /// For internal purposes: a deferred debuginfo level that can be optimized
837    /// away, but has this value otherwise.
838    ///
839    /// Behaves like `Resolved` in all situations except for the default build
840    /// dependencies profile: whenever a build dependency is not shared with
841    /// runtime dependencies, this level is weakened to a lower level that is
842    /// faster to build (see [`DebugInfo::weaken`]).
843    ///
844    /// In all other situations, this level value will be the one to use.
845    Deferred(TomlDebugInfo),
846}
847
848impl DebugInfo {
849    /// The main way to interact with this debuginfo level, turning it into a [`TomlDebugInfo`].
850    pub fn into_inner(self) -> TomlDebugInfo {
851        match self {
852            DebugInfo::Resolved(v) | DebugInfo::Deferred(v) => v,
853        }
854    }
855
856    /// Returns true if any debuginfo will be generated. Helper
857    /// for a common operation on the usual `Option` representation.
858    pub(crate) fn is_turned_on(&self) -> bool {
859        !matches!(self.into_inner(), TomlDebugInfo::None)
860    }
861
862    pub(crate) fn is_deferred(&self) -> bool {
863        matches!(self, DebugInfo::Deferred(_))
864    }
865
866    /// Force the deferred, preferred, debuginfo level to a finalized explicit value.
867    pub(crate) fn finalize(self) -> Self {
868        match self {
869            DebugInfo::Deferred(v) => DebugInfo::Resolved(v),
870            _ => self,
871        }
872    }
873
874    /// Reset to the lowest level: no debuginfo.
875    pub(crate) fn weaken(self) -> Self {
876        DebugInfo::Resolved(TomlDebugInfo::None)
877    }
878}
879
880impl PartialEq for DebugInfo {
881    fn eq(&self, other: &DebugInfo) -> bool {
882        self.into_inner().eq(&other.into_inner())
883    }
884}
885
886impl Eq for DebugInfo {}
887
888impl Hash for DebugInfo {
889    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
890        self.into_inner().hash(state);
891    }
892}
893
894impl PartialOrd for DebugInfo {
895    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
896        self.into_inner().partial_cmp(&other.into_inner())
897    }
898}
899
900impl Ord for DebugInfo {
901    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
902        self.into_inner().cmp(&other.into_inner())
903    }
904}
905
906/// The link-time-optimization setting.
907#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash, PartialOrd, Ord)]
908pub enum Lto {
909    /// Explicitly no LTO, disables thin-LTO.
910    Off,
911    /// True = "Fat" LTO
912    /// False = rustc default (no args), currently "thin LTO"
913    Bool(bool),
914    /// Named LTO settings like "thin".
915    Named(InternedString),
916}
917
918impl serde::ser::Serialize for Lto {
919    fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
920    where
921        S: serde::ser::Serializer,
922    {
923        match self {
924            Lto::Off => "off".serialize(s),
925            Lto::Bool(b) => b.to_string().serialize(s),
926            Lto::Named(n) => n.serialize(s),
927        }
928    }
929}
930
931/// The `panic` setting.
932#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash, PartialOrd, Ord, serde::Serialize)]
933#[serde(rename_all = "kebab-case")]
934pub enum PanicStrategy {
935    Unwind,
936    Abort,
937    ImmediateAbort,
938}
939
940impl fmt::Display for PanicStrategy {
941    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
942        match *self {
943            PanicStrategy::Unwind => "unwind",
944            PanicStrategy::Abort => "abort",
945            PanicStrategy::ImmediateAbort => "immediate-abort",
946        }
947        .fmt(f)
948    }
949}
950
951#[derive(
952    Clone, Copy, PartialEq, Eq, Debug, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
953)]
954pub enum StripInner {
955    /// Don't remove any symbols
956    None,
957    /// Named Strip settings
958    Named(InternedString),
959}
960
961impl fmt::Display for StripInner {
962    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
963        match *self {
964            StripInner::None => "none",
965            StripInner::Named(s) => s.as_str(),
966        }
967        .fmt(f)
968    }
969}
970
971/// The setting for choosing which symbols to strip.
972///
973/// This is semantically a [`StripInner`], and should be used as so via the
974/// [`Strip::into_inner`] method for all intents and purposes.
975///
976/// Internally, it's used to model a strip option whose value can be deferred
977/// for optimization purposes: when no package being compiled requires debuginfo,
978/// then we can strip debuginfo to remove pre-existing debug symbols from the
979/// standard library.
980#[derive(Clone, Copy, Debug, Eq, serde::Serialize, serde::Deserialize)]
981#[serde(rename_all = "lowercase")]
982pub enum Strip {
983    /// A strip option that is fixed and will not change.
984    Resolved(StripInner),
985    /// A strip option that might be overridden by Cargo for optimization
986    /// purposes.
987    Deferred(StripInner),
988}
989
990impl Strip {
991    /// The main way to interact with this strip option, turning it into a [`StripInner`].
992    pub fn into_inner(self) -> StripInner {
993        match self {
994            Strip::Resolved(v) | Strip::Deferred(v) => v,
995        }
996    }
997
998    pub(crate) fn is_deferred(&self) -> bool {
999        matches!(self, Strip::Deferred(_))
1000    }
1001
1002    /// Reset to stripping debuginfo.
1003    pub(crate) fn strip_debuginfo(self) -> Self {
1004        Strip::Resolved(StripInner::Named("debuginfo".into()))
1005    }
1006}
1007
1008impl PartialEq for Strip {
1009    fn eq(&self, other: &Self) -> bool {
1010        self.into_inner().eq(&other.into_inner())
1011    }
1012}
1013
1014impl Hash for Strip {
1015    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1016        self.into_inner().hash(state);
1017    }
1018}
1019
1020impl PartialOrd for Strip {
1021    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1022        self.into_inner().partial_cmp(&other.into_inner())
1023    }
1024}
1025
1026impl Ord for Strip {
1027    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1028        self.into_inner().cmp(&other.into_inner())
1029    }
1030}
1031
1032/// Flags used in creating `Unit`s to indicate the purpose for the target, and
1033/// to ensure the target's dependencies have the correct settings.
1034///
1035/// This means these are passed down from the root of the dependency tree to apply
1036/// to most child dependencies.
1037#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
1038pub struct UnitFor {
1039    /// A target for `build.rs` or any of its dependencies, or a proc-macro or
1040    /// any of its dependencies. This enables `build-override` profiles for
1041    /// these targets.
1042    ///
1043    /// An invariant is that if `host_features` is true, `host` must be true.
1044    ///
1045    /// Note that this is `true` for `RunCustomBuild` units, even though that
1046    /// unit should *not* use build-override profiles. This is a bit of a
1047    /// special case. When computing the `RunCustomBuild` unit, it manually
1048    /// uses the `get_profile_run_custom_build` method to get the correct
1049    /// profile information for the unit. `host` needs to be true so that all
1050    /// of the dependencies of that `RunCustomBuild` unit have this flag be
1051    /// sticky (and forced to `true` for all further dependencies) — which is
1052    /// the whole point of `UnitFor`.
1053    host: bool,
1054    /// A target for a build dependency or proc-macro (or any of its
1055    /// dependencies). This is used for computing features of build
1056    /// dependencies and proc-macros independently of other dependency kinds.
1057    ///
1058    /// The subtle difference between this and `host` is that the build script
1059    /// for a non-host package sets this to `false` because it wants the
1060    /// features of the non-host package (whereas `host` is true because the
1061    /// build script is being built for the host). `host_features` becomes
1062    /// `true` for build-dependencies or proc-macros, or any of their
1063    /// dependencies. For example, with this dependency tree:
1064    ///
1065    /// ```text
1066    /// foo
1067    /// ├── foo build.rs
1068    /// │   └── shared_dep (BUILD dependency)
1069    /// │       └── shared_dep build.rs
1070    /// └── shared_dep (Normal dependency)
1071    ///     └── shared_dep build.rs
1072    /// ```
1073    ///
1074    /// In this example, `foo build.rs` is `HOST=true`, `HOST_FEATURES=false`.
1075    /// This is so that `foo build.rs` gets the profile settings for build
1076    /// scripts (`HOST=true`) and features of foo (`HOST_FEATURES=false`) because
1077    /// build scripts need to know which features their package is being built
1078    /// with.
1079    ///
1080    /// But in the case of `shared_dep`, when built as a build dependency,
1081    /// both flags are true (it only wants the build-dependency features).
1082    /// When `shared_dep` is built as a normal dependency, then `shared_dep
1083    /// build.rs` is `HOST=true`, `HOST_FEATURES=false` for the same reasons that
1084    /// foo's build script is set that way.
1085    host_features: bool,
1086    /// How Cargo processes the `panic` setting or profiles.
1087    panic_setting: PanicSetting,
1088
1089    /// The compile kind of the root unit for which artifact dependencies are built.
1090    /// This is required particularly for the `target = "target"` setting of artifact
1091    /// dependencies which mean to inherit the `--target` specified on the command-line.
1092    /// However, that is a multi-value argument and root units are already created to
1093    /// reflect one unit per --target. Thus we have to build one artifact with the
1094    /// correct target for each of these trees.
1095    /// Note that this will always be set as we don't initially know if there are
1096    /// artifacts that make use of it.
1097    root_compile_kind: CompileKind,
1098
1099    /// This is only set for artifact dependencies which have their
1100    /// `<target-tuple>|target` set.
1101    /// If so, this information is used as part of the key for resolving their features,
1102    /// allowing for target-dependent feature resolution within the entire dependency tree.
1103    /// Note that this target corresponds to the target used to build the units in that
1104    /// dependency tree, too, but this copy of it is specifically used for feature lookup.
1105    artifact_target_for_features: Option<CompileTarget>,
1106}
1107
1108/// How Cargo processes the `panic` setting or profiles.
1109///
1110/// This is done to handle test/benches inheriting from dev/release,
1111/// as well as forcing `for_host` units to always unwind.
1112/// It also interacts with [`-Z panic-abort-tests`].
1113///
1114/// [`-Z panic-abort-tests`]: https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#panic-abort-tests
1115#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
1116enum PanicSetting {
1117    /// Used to force a unit to always be compiled with the `panic=unwind`
1118    /// strategy, notably for build scripts, proc macros, etc.
1119    AlwaysUnwind,
1120
1121    /// Indicates that this unit will read its `profile` setting and use
1122    /// whatever is configured there.
1123    ReadProfile,
1124}
1125
1126impl UnitFor {
1127    /// A unit for a normal target/dependency (i.e., not custom build,
1128    /// proc macro/plugin, or test/bench).
1129    pub fn new_normal(root_compile_kind: CompileKind) -> UnitFor {
1130        UnitFor {
1131            host: false,
1132            host_features: false,
1133            panic_setting: PanicSetting::ReadProfile,
1134            root_compile_kind,
1135            artifact_target_for_features: None,
1136        }
1137    }
1138
1139    /// A unit for a custom build script or proc-macro or its dependencies.
1140    ///
1141    /// The `host_features` parameter is whether or not this is for a build
1142    /// dependency or proc-macro (something that requires being built "on the
1143    /// host"). Build scripts for non-host units should use `false` because
1144    /// they want to use the features of the package they are running for.
1145    pub fn new_host(host_features: bool, root_compile_kind: CompileKind) -> UnitFor {
1146        UnitFor {
1147            host: true,
1148            host_features,
1149            // Force build scripts to always use `panic=unwind` for now to
1150            // maximally share dependencies with procedural macros.
1151            panic_setting: PanicSetting::AlwaysUnwind,
1152            root_compile_kind,
1153            artifact_target_for_features: None,
1154        }
1155    }
1156
1157    /// A unit for a compiler plugin or their dependencies.
1158    pub fn new_compiler(root_compile_kind: CompileKind) -> UnitFor {
1159        UnitFor {
1160            host: false,
1161            // The feature resolver doesn't know which dependencies are
1162            // plugins, so for now plugins don't split features. Since plugins
1163            // are mostly deprecated, just leave this as false.
1164            host_features: false,
1165            // Force plugins to use `panic=abort` so panics in the compiler do
1166            // not abort the process but instead end with a reasonable error
1167            // message that involves catching the panic in the compiler.
1168            panic_setting: PanicSetting::AlwaysUnwind,
1169            root_compile_kind,
1170            artifact_target_for_features: None,
1171        }
1172    }
1173
1174    /// A unit for a test/bench target or their dependencies.
1175    ///
1176    /// Note that `config` is taken here for unstable CLI features to detect
1177    /// whether `panic=abort` is supported for tests. Historical versions of
1178    /// rustc did not support this, but newer versions do with an unstable
1179    /// compiler flag.
1180    pub fn new_test(gctx: &GlobalContext, root_compile_kind: CompileKind) -> UnitFor {
1181        UnitFor {
1182            host: false,
1183            host_features: false,
1184            // We're testing out an unstable feature (`-Zpanic-abort-tests`)
1185            // which inherits the panic setting from the dev/release profile
1186            // (basically avoid recompiles) but historical defaults required
1187            // that we always unwound.
1188            panic_setting: if gctx.cli_unstable().panic_abort_tests {
1189                PanicSetting::ReadProfile
1190            } else {
1191                PanicSetting::AlwaysUnwind
1192            },
1193            root_compile_kind,
1194            artifact_target_for_features: None,
1195        }
1196    }
1197
1198    /// This is a special case for unit tests of a proc-macro.
1199    ///
1200    /// Proc-macro unit tests are forced to be run on the host.
1201    pub fn new_host_test(gctx: &GlobalContext, root_compile_kind: CompileKind) -> UnitFor {
1202        let mut unit_for = UnitFor::new_test(gctx, root_compile_kind);
1203        unit_for.host = true;
1204        unit_for.host_features = true;
1205        unit_for
1206    }
1207
1208    /// Returns a new copy updated based on the target dependency.
1209    ///
1210    /// This is where the magic happens that the `host`/`host_features` settings
1211    /// transition in a sticky fashion. As the dependency graph is being
1212    /// built, once those flags are set, they stay set for the duration of
1213    /// that portion of tree.
1214    pub fn with_dependency(
1215        self,
1216        parent: &Unit,
1217        dep_target: &Target,
1218        root_compile_kind: CompileKind,
1219    ) -> UnitFor {
1220        // A build script or proc-macro transitions this to being built for the host.
1221        let dep_for_host = dep_target.for_host();
1222        // This is where feature decoupling of host versus target happens.
1223        //
1224        // Once host features are desired, they are always desired.
1225        //
1226        // A proc-macro should always use host features.
1227        //
1228        // Dependencies of a build script should use host features (subtle
1229        // point: the build script itself does *not* use host features, that's
1230        // why the parent is checked here, and not the dependency).
1231        let host_features =
1232            self.host_features || parent.target.is_custom_build() || dep_target.proc_macro();
1233        // Build scripts and proc macros, and all of their dependencies are
1234        // AlwaysUnwind.
1235        let panic_setting = if dep_for_host {
1236            PanicSetting::AlwaysUnwind
1237        } else {
1238            self.panic_setting
1239        };
1240        let artifact_target_for_features =
1241            // build.rs and proc-macros are always for host.
1242            if dep_target.proc_macro() || parent.target.is_custom_build() {
1243                None
1244            } else {
1245                self.artifact_target_for_features
1246            };
1247        UnitFor {
1248            host: self.host || dep_for_host,
1249            host_features,
1250            panic_setting,
1251            root_compile_kind,
1252            artifact_target_for_features,
1253        }
1254    }
1255
1256    pub fn for_custom_build(self) -> UnitFor {
1257        UnitFor {
1258            host: true,
1259            host_features: self.host_features,
1260            // Force build scripts to always use `panic=unwind` for now to
1261            // maximally share dependencies with procedural macros.
1262            panic_setting: PanicSetting::AlwaysUnwind,
1263            root_compile_kind: self.root_compile_kind,
1264            artifact_target_for_features: self.artifact_target_for_features,
1265        }
1266    }
1267
1268    /// Set the artifact compile target for use in features using the given `artifact`.
1269    pub(crate) fn with_artifact_features(mut self, artifact: &Artifact) -> UnitFor {
1270        self.artifact_target_for_features = artifact.target().and_then(|t| t.to_compile_target());
1271        self
1272    }
1273
1274    /// Set the artifact compile target as determined by a resolved compile target. This is used if `target = "target"`.
1275    pub(crate) fn with_artifact_features_from_resolved_compile_kind(
1276        mut self,
1277        kind: Option<CompileKind>,
1278    ) -> UnitFor {
1279        self.artifact_target_for_features = kind.and_then(|kind| match kind {
1280            CompileKind::Host => None,
1281            CompileKind::Target(triple) => Some(triple),
1282        });
1283        self
1284    }
1285
1286    /// Returns `true` if this unit is for a build script or any of its
1287    /// dependencies, or a proc macro or any of its dependencies.
1288    pub fn is_for_host(&self) -> bool {
1289        self.host
1290    }
1291
1292    pub fn is_for_host_features(&self) -> bool {
1293        self.host_features
1294    }
1295
1296    /// Returns how `panic` settings should be handled for this profile
1297    fn panic_setting(&self) -> PanicSetting {
1298        self.panic_setting
1299    }
1300
1301    /// We might contain a parent artifact compile kind for features already, but will
1302    /// gladly accept the one of this dependency as an override as it defines how
1303    /// the artifact is built.
1304    /// If we are an artifact but don't specify a `target`, we assume the default
1305    /// compile kind that is suitable in this situation.
1306    pub(crate) fn map_to_features_for(&self, dep_artifact: Option<&Artifact>) -> FeaturesFor {
1307        FeaturesFor::from_for_host_or_artifact_target(
1308            self.is_for_host_features(),
1309            match dep_artifact {
1310                Some(artifact) => artifact
1311                    .target()
1312                    .and_then(|t| t.to_resolved_compile_target(self.root_compile_kind)),
1313                None => self.artifact_target_for_features,
1314            },
1315        )
1316    }
1317
1318    pub(crate) fn root_compile_kind(&self) -> CompileKind {
1319        self.root_compile_kind
1320    }
1321}
1322
1323/// Takes the manifest profiles, and overlays the config profiles on-top.
1324///
1325/// Returns a new copy of the profile map with all the mergers complete.
1326fn merge_config_profiles(
1327    ws: &Workspace<'_>,
1328    requested_profile: InternedString,
1329) -> CargoResult<BTreeMap<InternedString, TomlProfile>> {
1330    let mut profiles = match ws.profiles() {
1331        Some(profiles) => profiles
1332            .get_all()
1333            .iter()
1334            .map(|(k, v)| (InternedString::new(k), v.clone()))
1335            .collect(),
1336        None => BTreeMap::new(),
1337    };
1338    // Set of profile names to check if defined in config only.
1339    let mut check_to_add = HashSet::default();
1340    check_to_add.insert(requested_profile);
1341    // Merge config onto manifest profiles.
1342    for (name, profile) in &mut profiles {
1343        if let Some(config_profile) = get_config_profile(ws, name)? {
1344            profile.merge(&config_profile);
1345        }
1346        if let Some(inherits) = &profile.inherits {
1347            check_to_add.insert(inherits.into());
1348        }
1349    }
1350    // Add the built-in profiles. This is important for things like `cargo
1351    // test` which implicitly use the "dev" profile for dependencies.
1352    for name in ["dev", "release", "debug", "test", "bench"] {
1353        check_to_add.insert(name.into());
1354    }
1355    // Add config-only profiles.
1356    // Need to iterate repeatedly to get all the inherits values.
1357    let mut current = HashSet::default();
1358    while !check_to_add.is_empty() {
1359        std::mem::swap(&mut current, &mut check_to_add);
1360        for name in current.drain() {
1361            if !profiles.contains_key(name.as_str()) {
1362                if let Some(config_profile) = get_config_profile(ws, &name)? {
1363                    if let Some(inherits) = &config_profile.inherits {
1364                        check_to_add.insert(inherits.into());
1365                    }
1366                    profiles.insert(name, config_profile);
1367                }
1368            }
1369        }
1370    }
1371    Ok(profiles)
1372}
1373
1374/// Helper for fetching a profile from config.
1375fn get_config_profile(ws: &Workspace<'_>, name: &str) -> CargoResult<Option<TomlProfile>> {
1376    let profile: Option<context::Value<TomlProfile>> = ws.gctx().get(["profile", name])?;
1377    let Some(profile) = profile else {
1378        return Ok(None);
1379    };
1380    let mut warnings = Vec::new();
1381    validate_profile(
1382        &profile.val,
1383        name,
1384        ws.gctx().cli_unstable(),
1385        ws.unstable_features(),
1386        &mut warnings,
1387    )
1388    .with_context(|| {
1389        format!(
1390            "config profile `{}` is not valid (defined in `{}`)",
1391            name, profile.definition
1392        )
1393    })?;
1394    warn_ignored_hint_mostly_unused(ws.gctx(), &profile, name, &mut warnings)?;
1395    for warning in warnings {
1396        ws.gctx().shell().warn(warning)?;
1397    }
1398    Ok(Some(profile.val))
1399}
1400
1401/// Warns about each `hint-mostly-unused = true` in a config profile, which is ignored without
1402/// `-Zprofile-hint-mostly-unused`. Manifest profiles are covered by the parse pass instead, see
1403/// [`crate::diagnostics::rules::PARSE_PASS_RULES`].
1404fn warn_ignored_hint_mostly_unused(
1405    gctx: &GlobalContext,
1406    profile: &context::Value<TomlProfile>,
1407    name: &str,
1408    warnings: &mut Vec<String>,
1409) -> CargoResult<()> {
1410    if gctx.cli_unstable().profile_hint_mostly_unused {
1411        return Ok(());
1412    }
1413    let mut key = context::ConfigKey::from_parts(["profile"]);
1414    key.push(name);
1415    let mut tables = vec![(&profile.val, key.clone())];
1416    if let Some(build_override) = &profile.val.build_override {
1417        let mut key = key.clone();
1418        key.push("build-override");
1419        tables.push((build_override, key));
1420    }
1421    for (spec, package) in profile.val.package.iter().flatten() {
1422        let mut key = key.clone();
1423        key.push("package");
1424        key.push(&spec.to_string());
1425        tables.push((package, key));
1426    }
1427    for (table, key) in tables {
1428        if table.hint_mostly_unused == Some(true) {
1429            // Config sources are merged key by key, so `profile.definition` may not be where this
1430            // key was set. A legacy spec like `"foo:1.0.0"` is normalized by `to_string`, so its
1431            // lookup misses and the profile's definition is used instead.
1432            let mut hint_key = key.clone();
1433            hint_key.push("hint-mostly-unused");
1434            let hint = gctx.get_cv_with_env(&hint_key)?;
1435            let definition = hint
1436                .as_ref()
1437                .map_or(&profile.definition, |hint| hint.definition());
1438            warnings.push(format!(
1439                "ignoring `hint-mostly-unused` in `{key}` (defined in {definition}), \
1440                 pass `-Zprofile-hint-mostly-unused` to enable it"
1441            ));
1442        }
1443    }
1444    Ok(())
1445}
1446
1447/// Validate that a package does not match multiple package override specs.
1448///
1449/// For example `[profile.dev.package.bar]` and `[profile.dev.package."bar:0.5.0"]`
1450/// would both match `bar:0.5.0` which would be ambiguous.
1451fn validate_packages_unique(
1452    resolve: &Resolve,
1453    name: &str,
1454    toml: &Option<TomlProfile>,
1455) -> CargoResult<HashSet<PackageIdSpec>> {
1456    let Some(toml) = toml else {
1457        return Ok(HashSet::default());
1458    };
1459    let Some(overrides) = toml.package.as_ref() else {
1460        return Ok(HashSet::default());
1461    };
1462    // Verify that a package doesn't match multiple spec overrides.
1463    let mut found = HashSet::default();
1464    for pkg_id in resolve.iter() {
1465        let matches: Vec<&PackageIdSpec> = overrides
1466            .keys()
1467            .filter_map(|key| match *key {
1468                ProfilePackageSpec::All => None,
1469                ProfilePackageSpec::Spec(ref spec) => {
1470                    if spec.matches(pkg_id) {
1471                        Some(spec)
1472                    } else {
1473                        None
1474                    }
1475                }
1476            })
1477            .collect();
1478        match matches.len() {
1479            0 => {}
1480            1 => {
1481                found.insert(matches[0].clone());
1482            }
1483            _ => {
1484                let specs = matches
1485                    .iter()
1486                    .map(|spec| spec.to_string())
1487                    .collect::<Vec<_>>()
1488                    .join(", ");
1489                bail!(
1490                    "multiple package overrides in profile `{}` match package `{}`\n\
1491                     found package specs: {}",
1492                    name,
1493                    pkg_id,
1494                    specs
1495                );
1496            }
1497        }
1498    }
1499    Ok(found)
1500}
1501
1502/// Check for any profile override specs that do not match any known packages.
1503///
1504/// This helps check for typos and mistakes.
1505fn validate_packages_unmatched(
1506    shell: &mut Shell,
1507    resolve: &Resolve,
1508    name: &str,
1509    toml: &TomlProfile,
1510    found: &HashSet<PackageIdSpec>,
1511) -> CargoResult<()> {
1512    let Some(overrides) = toml.package.as_ref() else {
1513        return Ok(());
1514    };
1515
1516    // Verify every override matches at least one package.
1517    let missing_specs = overrides.keys().filter_map(|key| {
1518        if let ProfilePackageSpec::Spec(ref spec) = *key {
1519            if !found.contains(spec) {
1520                return Some(spec);
1521            }
1522        }
1523        None
1524    });
1525    for spec in missing_specs {
1526        // See if there is an exact name match.
1527        let name_matches: Vec<String> = resolve
1528            .iter()
1529            .filter_map(|pkg_id| {
1530                if pkg_id.name() == spec.name() {
1531                    Some(pkg_id.to_string())
1532                } else {
1533                    None
1534                }
1535            })
1536            .collect();
1537        if name_matches.is_empty() {
1538            let suggestion = closest_msg(
1539                &spec.name(),
1540                resolve.iter(),
1541                |p| p.name().as_str(),
1542                "package",
1543            );
1544            shell.warn(format!(
1545                "profile package spec `{}` in profile `{}` did not match any packages{}",
1546                spec, name, suggestion
1547            ))?;
1548        } else {
1549            shell.warn(format!(
1550                "profile package spec `{}` in profile `{}` \
1551                 has a version or URL that does not match any of the packages: {}",
1552                spec,
1553                name,
1554                name_matches.join(", ")
1555            ))?;
1556        }
1557    }
1558    Ok(())
1559}
1560
1561/// Returns `true` if a string is a toggle that turns an option off.
1562fn is_off(s: &str) -> bool {
1563    matches!(s, "off" | "n" | "no" | "none")
1564}