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