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