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(InternedString::new(predef_name)) {
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 (InternedString::new("dev"), InternedString::new("debug")),
123 (InternedString::new("test"), InternedString::new("debug")),
124 (InternedString::new("bench"), InternedString::new("release")),
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 InternedString::new("dev"),
138 ProfileMaker::new(Profile::default_dev(), profiles.get("dev").cloned()),
139 );
140
141 profile_makers.by_name.insert(
142 InternedString::new("release"),
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, InternedString::new(dir_name));
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 = InternedString::new(&inherits_name);
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(InternedString::new("unpacked"));
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 = InternedString::new("0");
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 = InternedString::new(&opt_level.0);
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(InternedString::new(n)),
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(InternedString::new(split_debuginfo));
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 profile.strip = match toml.strip {
581 Some(StringOrBool::Bool(true)) => {
582 Strip::Resolved(StripInner::Named(InternedString::new("symbols")))
583 }
584 Some(StringOrBool::Bool(false)) => Strip::Resolved(StripInner::None),
585 Some(StringOrBool::String(ref n)) if n.as_str() == "none" => {
586 Strip::Resolved(StripInner::None)
587 }
588 Some(StringOrBool::String(ref n)) => {
589 Strip::Resolved(StripInner::Named(InternedString::new(n)))
590 }
591 None => Strip::Deferred(StripInner::None),
592 };
593}
594
595/// The root profile (dev/release).
596///
597/// This is currently only used for the `PROFILE` env var for build scripts
598/// for backwards compatibility. We should probably deprecate `PROFILE` and
599/// encourage using things like `DEBUG` and `OPT_LEVEL` instead.
600#[derive(Clone, Copy, Eq, PartialOrd, Ord, PartialEq, Debug)]
601pub enum ProfileRoot {
602 Release,
603 Debug,
604}
605
606/// Profile settings used to determine which compiler flags to use for a
607/// target.
608#[derive(Clone, Eq, PartialOrd, Ord, serde::Serialize)]
609pub struct Profile {
610 pub name: InternedString,
611 pub opt_level: InternedString,
612 #[serde(skip)] // named profiles are unstable
613 pub root: ProfileRoot,
614 pub lto: Lto,
615 // `None` means use rustc default.
616 pub codegen_backend: Option<InternedString>,
617 // `None` means use rustc default.
618 pub codegen_units: Option<u32>,
619 pub debuginfo: DebugInfo,
620 pub split_debuginfo: Option<InternedString>,
621 pub debug_assertions: bool,
622 pub overflow_checks: bool,
623 pub rpath: bool,
624 pub incremental: bool,
625 pub panic: PanicStrategy,
626 pub strip: Strip,
627 #[serde(skip_serializing_if = "Vec::is_empty")] // remove when `rustflags` is stablized
628 // Note that `rustflags` is used for the cargo-feature `profile_rustflags`
629 pub rustflags: Vec<InternedString>,
630 // remove when `-Ztrim-paths` is stablized
631 #[serde(skip_serializing_if = "Option::is_none")]
632 pub trim_paths: Option<TomlTrimPaths>,
633}
634
635impl Default for Profile {
636 fn default() -> Profile {
637 Profile {
638 name: InternedString::new(""),
639 opt_level: InternedString::new("0"),
640 root: ProfileRoot::Debug,
641 lto: Lto::Bool(false),
642 codegen_backend: None,
643 codegen_units: None,
644 debuginfo: DebugInfo::Resolved(TomlDebugInfo::None),
645 debug_assertions: false,
646 split_debuginfo: None,
647 overflow_checks: false,
648 rpath: false,
649 incremental: false,
650 panic: PanicStrategy::Unwind,
651 strip: Strip::Deferred(StripInner::None),
652 rustflags: vec![],
653 trim_paths: None,
654 }
655 }
656}
657
658compact_debug! {
659 impl fmt::Debug for Profile {
660 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
661 let (default, default_name) = match self.name.as_str() {
662 "dev" => (Profile::default_dev(), "default_dev()"),
663 "release" => (Profile::default_release(false), "default_release()"),
664 _ => (Profile::default(), "default()"),
665 };
666 [debug_the_fields(
667 name
668 opt_level
669 lto
670 root
671 codegen_backend
672 codegen_units
673 debuginfo
674 split_debuginfo
675 debug_assertions
676 overflow_checks
677 rpath
678 incremental
679 panic
680 strip
681 rustflags
682 trim_paths
683 )]
684 }
685 }
686}
687
688impl fmt::Display for Profile {
689 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
690 write!(f, "Profile({})", self.name)
691 }
692}
693
694impl hash::Hash for Profile {
695 fn hash<H>(&self, state: &mut H)
696 where
697 H: hash::Hasher,
698 {
699 self.comparable().hash(state);
700 }
701}
702
703impl cmp::PartialEq for Profile {
704 fn eq(&self, other: &Self) -> bool {
705 self.comparable() == other.comparable()
706 }
707}
708
709impl Profile {
710 /// Returns a built-in `dev` profile.
711 fn default_dev() -> Profile {
712 Profile {
713 name: InternedString::new("dev"),
714 root: ProfileRoot::Debug,
715 debuginfo: DebugInfo::Resolved(TomlDebugInfo::Full),
716 debug_assertions: true,
717 overflow_checks: true,
718 incremental: true,
719 ..Profile::default()
720 }
721 }
722
723 /// Returns a built-in `release` profile.
724 fn default_release(trim_paths_enabled: bool) -> Profile {
725 let trim_paths = trim_paths_enabled.then(|| TomlTrimPathsValue::Object.into());
726 Profile {
727 name: InternedString::new("release"),
728 root: ProfileRoot::Release,
729 opt_level: InternedString::new("3"),
730 trim_paths,
731 ..Profile::default()
732 }
733 }
734
735 /// Compares all fields except `name`, which doesn't affect compilation.
736 /// This is necessary for `Unit` deduplication for things like "test" and
737 /// "dev" which are essentially the same.
738 fn comparable(&self) -> impl Hash + Eq + '_ {
739 (
740 self.opt_level,
741 self.lto,
742 self.codegen_backend,
743 self.codegen_units,
744 self.debuginfo,
745 self.split_debuginfo,
746 self.debug_assertions,
747 self.overflow_checks,
748 self.rpath,
749 (self.incremental, self.panic, self.strip),
750 &self.rustflags,
751 &self.trim_paths,
752 )
753 }
754}
755
756/// The debuginfo level setting.
757///
758/// This is semantically a [`TomlDebugInfo`], and should be used as so via the
759/// [`DebugInfo::into_inner`] method for all intents and purposes.
760///
761/// Internally, it's used to model a debuginfo level whose value can be deferred
762/// for optimization purposes: host dependencies usually don't need the same
763/// level as target dependencies. For dependencies that are shared between the
764/// two however, that value also affects reuse: different debuginfo levels would
765/// cause to build a unit twice. By deferring the choice until we know
766/// whether to choose the optimized value or the default value, we can make sure
767/// the unit is only built once and the unit graph is still optimized.
768#[derive(Debug, Copy, Clone, serde::Serialize)]
769#[serde(untagged)]
770pub enum DebugInfo {
771 /// A debuginfo level that is fixed and will not change.
772 ///
773 /// This can be set by a profile, user, or default value.
774 Resolved(TomlDebugInfo),
775 /// For internal purposes: a deferred debuginfo level that can be optimized
776 /// away, but has this value otherwise.
777 ///
778 /// Behaves like `Resolved` in all situations except for the default build
779 /// dependencies profile: whenever a build dependency is not shared with
780 /// runtime dependencies, this level is weakened to a lower level that is
781 /// faster to build (see [`DebugInfo::weaken`]).
782 ///
783 /// In all other situations, this level value will be the one to use.
784 Deferred(TomlDebugInfo),
785}
786
787impl DebugInfo {
788 /// The main way to interact with this debuginfo level, turning it into a [`TomlDebugInfo`].
789 pub fn into_inner(self) -> TomlDebugInfo {
790 match self {
791 DebugInfo::Resolved(v) | DebugInfo::Deferred(v) => v,
792 }
793 }
794
795 /// Returns true if any debuginfo will be generated. Helper
796 /// for a common operation on the usual `Option` representation.
797 pub(crate) fn is_turned_on(&self) -> bool {
798 !matches!(self.into_inner(), TomlDebugInfo::None)
799 }
800
801 pub(crate) fn is_deferred(&self) -> bool {
802 matches!(self, DebugInfo::Deferred(_))
803 }
804
805 /// Force the deferred, preferred, debuginfo level to a finalized explicit value.
806 pub(crate) fn finalize(self) -> Self {
807 match self {
808 DebugInfo::Deferred(v) => DebugInfo::Resolved(v),
809 _ => self,
810 }
811 }
812
813 /// Reset to the lowest level: no debuginfo.
814 pub(crate) fn weaken(self) -> Self {
815 DebugInfo::Resolved(TomlDebugInfo::None)
816 }
817}
818
819impl PartialEq for DebugInfo {
820 fn eq(&self, other: &DebugInfo) -> bool {
821 self.into_inner().eq(&other.into_inner())
822 }
823}
824
825impl Eq for DebugInfo {}
826
827impl Hash for DebugInfo {
828 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
829 self.into_inner().hash(state);
830 }
831}
832
833impl PartialOrd for DebugInfo {
834 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
835 self.into_inner().partial_cmp(&other.into_inner())
836 }
837}
838
839impl Ord for DebugInfo {
840 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
841 self.into_inner().cmp(&other.into_inner())
842 }
843}
844
845/// The link-time-optimization setting.
846#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash, PartialOrd, Ord)]
847pub enum Lto {
848 /// Explicitly no LTO, disables thin-LTO.
849 Off,
850 /// True = "Fat" LTO
851 /// False = rustc default (no args), currently "thin LTO"
852 Bool(bool),
853 /// Named LTO settings like "thin".
854 Named(InternedString),
855}
856
857impl serde::ser::Serialize for Lto {
858 fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
859 where
860 S: serde::ser::Serializer,
861 {
862 match self {
863 Lto::Off => "off".serialize(s),
864 Lto::Bool(b) => b.to_string().serialize(s),
865 Lto::Named(n) => n.serialize(s),
866 }
867 }
868}
869
870/// The `panic` setting.
871#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash, PartialOrd, Ord, serde::Serialize)]
872#[serde(rename_all = "lowercase")]
873pub enum PanicStrategy {
874 Unwind,
875 Abort,
876}
877
878impl fmt::Display for PanicStrategy {
879 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
880 match *self {
881 PanicStrategy::Unwind => "unwind",
882 PanicStrategy::Abort => "abort",
883 }
884 .fmt(f)
885 }
886}
887
888#[derive(
889 Clone, Copy, PartialEq, Eq, Debug, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
890)]
891pub enum StripInner {
892 /// Don't remove any symbols
893 None,
894 /// Named Strip settings
895 Named(InternedString),
896}
897
898impl fmt::Display for StripInner {
899 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
900 match *self {
901 StripInner::None => "none",
902 StripInner::Named(s) => s.as_str(),
903 }
904 .fmt(f)
905 }
906}
907
908/// The setting for choosing which symbols to strip.
909///
910/// This is semantically a [`StripInner`], and should be used as so via the
911/// [`Strip::into_inner`] method for all intents and purposes.
912///
913/// Internally, it's used to model a strip option whose value can be deferred
914/// for optimization purposes: when no package being compiled requires debuginfo,
915/// then we can strip debuginfo to remove pre-existing debug symbols from the
916/// standard library.
917#[derive(Clone, Copy, Debug, Eq, serde::Serialize, serde::Deserialize)]
918#[serde(rename_all = "lowercase")]
919pub enum Strip {
920 /// A strip option that is fixed and will not change.
921 Resolved(StripInner),
922 /// A strip option that might be overridden by Cargo for optimization
923 /// purposes.
924 Deferred(StripInner),
925}
926
927impl Strip {
928 /// The main way to interact with this strip option, turning it into a [`StripInner`].
929 pub fn into_inner(self) -> StripInner {
930 match self {
931 Strip::Resolved(v) | Strip::Deferred(v) => v,
932 }
933 }
934
935 pub(crate) fn is_deferred(&self) -> bool {
936 matches!(self, Strip::Deferred(_))
937 }
938
939 /// Reset to stripping debuginfo.
940 pub(crate) fn strip_debuginfo(self) -> Self {
941 Strip::Resolved(StripInner::Named("debuginfo".into()))
942 }
943}
944
945impl PartialEq for Strip {
946 fn eq(&self, other: &Self) -> bool {
947 self.into_inner().eq(&other.into_inner())
948 }
949}
950
951impl Hash for Strip {
952 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
953 self.into_inner().hash(state);
954 }
955}
956
957impl PartialOrd for Strip {
958 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
959 self.into_inner().partial_cmp(&other.into_inner())
960 }
961}
962
963impl Ord for Strip {
964 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
965 self.into_inner().cmp(&other.into_inner())
966 }
967}
968
969/// Flags used in creating `Unit`s to indicate the purpose for the target, and
970/// to ensure the target's dependencies have the correct settings.
971///
972/// This means these are passed down from the root of the dependency tree to apply
973/// to most child dependencies.
974#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
975pub struct UnitFor {
976 /// A target for `build.rs` or any of its dependencies, or a proc-macro or
977 /// any of its dependencies. This enables `build-override` profiles for
978 /// these targets.
979 ///
980 /// An invariant is that if `host_features` is true, `host` must be true.
981 ///
982 /// Note that this is `true` for `RunCustomBuild` units, even though that
983 /// unit should *not* use build-override profiles. This is a bit of a
984 /// special case. When computing the `RunCustomBuild` unit, it manually
985 /// uses the `get_profile_run_custom_build` method to get the correct
986 /// profile information for the unit. `host` needs to be true so that all
987 /// of the dependencies of that `RunCustomBuild` unit have this flag be
988 /// sticky (and forced to `true` for all further dependencies) — which is
989 /// the whole point of `UnitFor`.
990 host: bool,
991 /// A target for a build dependency or proc-macro (or any of its
992 /// dependencies). This is used for computing features of build
993 /// dependencies and proc-macros independently of other dependency kinds.
994 ///
995 /// The subtle difference between this and `host` is that the build script
996 /// for a non-host package sets this to `false` because it wants the
997 /// features of the non-host package (whereas `host` is true because the
998 /// build script is being built for the host). `host_features` becomes
999 /// `true` for build-dependencies or proc-macros, or any of their
1000 /// dependencies. For example, with this dependency tree:
1001 ///
1002 /// ```text
1003 /// foo
1004 /// ├── foo build.rs
1005 /// │ └── shared_dep (BUILD dependency)
1006 /// │ └── shared_dep build.rs
1007 /// └── shared_dep (Normal dependency)
1008 /// └── shared_dep build.rs
1009 /// ```
1010 ///
1011 /// In this example, `foo build.rs` is `HOST=true`, `HOST_FEATURES=false`.
1012 /// This is so that `foo build.rs` gets the profile settings for build
1013 /// scripts (`HOST=true`) and features of foo (`HOST_FEATURES=false`) because
1014 /// build scripts need to know which features their package is being built
1015 /// with.
1016 ///
1017 /// But in the case of `shared_dep`, when built as a build dependency,
1018 /// both flags are true (it only wants the build-dependency features).
1019 /// When `shared_dep` is built as a normal dependency, then `shared_dep
1020 /// build.rs` is `HOST=true`, `HOST_FEATURES=false` for the same reasons that
1021 /// foo's build script is set that way.
1022 host_features: bool,
1023 /// How Cargo processes the `panic` setting or profiles.
1024 panic_setting: PanicSetting,
1025
1026 /// The compile kind of the root unit for which artifact dependencies are built.
1027 /// This is required particularly for the `target = "target"` setting of artifact
1028 /// dependencies which mean to inherit the `--target` specified on the command-line.
1029 /// However, that is a multi-value argument and root units are already created to
1030 /// reflect one unit per --target. Thus we have to build one artifact with the
1031 /// correct target for each of these trees.
1032 /// Note that this will always be set as we don't initially know if there are
1033 /// artifacts that make use of it.
1034 root_compile_kind: CompileKind,
1035
1036 /// This is only set for artifact dependencies which have their
1037 /// `<target-triple>|target` set.
1038 /// If so, this information is used as part of the key for resolving their features,
1039 /// allowing for target-dependent feature resolution within the entire dependency tree.
1040 /// Note that this target corresponds to the target used to build the units in that
1041 /// dependency tree, too, but this copy of it is specifically used for feature lookup.
1042 artifact_target_for_features: Option<CompileTarget>,
1043}
1044
1045/// How Cargo processes the `panic` setting or profiles.
1046///
1047/// This is done to handle test/benches inheriting from dev/release,
1048/// as well as forcing `for_host` units to always unwind.
1049/// It also interacts with [`-Z panic-abort-tests`].
1050///
1051/// [`-Z panic-abort-tests`]: https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#panic-abort-tests
1052#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
1053enum PanicSetting {
1054 /// Used to force a unit to always be compiled with the `panic=unwind`
1055 /// strategy, notably for build scripts, proc macros, etc.
1056 AlwaysUnwind,
1057
1058 /// Indicates that this unit will read its `profile` setting and use
1059 /// whatever is configured there.
1060 ReadProfile,
1061}
1062
1063impl UnitFor {
1064 /// A unit for a normal target/dependency (i.e., not custom build,
1065 /// proc macro/plugin, or test/bench).
1066 pub fn new_normal(root_compile_kind: CompileKind) -> UnitFor {
1067 UnitFor {
1068 host: false,
1069 host_features: false,
1070 panic_setting: PanicSetting::ReadProfile,
1071 root_compile_kind,
1072 artifact_target_for_features: None,
1073 }
1074 }
1075
1076 /// A unit for a custom build script or proc-macro or its dependencies.
1077 ///
1078 /// The `host_features` parameter is whether or not this is for a build
1079 /// dependency or proc-macro (something that requires being built "on the
1080 /// host"). Build scripts for non-host units should use `false` because
1081 /// they want to use the features of the package they are running for.
1082 pub fn new_host(host_features: bool, root_compile_kind: CompileKind) -> UnitFor {
1083 UnitFor {
1084 host: true,
1085 host_features,
1086 // Force build scripts to always use `panic=unwind` for now to
1087 // maximally share dependencies with procedural macros.
1088 panic_setting: PanicSetting::AlwaysUnwind,
1089 root_compile_kind,
1090 artifact_target_for_features: None,
1091 }
1092 }
1093
1094 /// A unit for a compiler plugin or their dependencies.
1095 pub fn new_compiler(root_compile_kind: CompileKind) -> UnitFor {
1096 UnitFor {
1097 host: false,
1098 // The feature resolver doesn't know which dependencies are
1099 // plugins, so for now plugins don't split features. Since plugins
1100 // are mostly deprecated, just leave this as false.
1101 host_features: false,
1102 // Force plugins to use `panic=abort` so panics in the compiler do
1103 // not abort the process but instead end with a reasonable error
1104 // message that involves catching the panic in the compiler.
1105 panic_setting: PanicSetting::AlwaysUnwind,
1106 root_compile_kind,
1107 artifact_target_for_features: None,
1108 }
1109 }
1110
1111 /// A unit for a test/bench target or their dependencies.
1112 ///
1113 /// Note that `config` is taken here for unstable CLI features to detect
1114 /// whether `panic=abort` is supported for tests. Historical versions of
1115 /// rustc did not support this, but newer versions do with an unstable
1116 /// compiler flag.
1117 pub fn new_test(gctx: &GlobalContext, root_compile_kind: CompileKind) -> UnitFor {
1118 UnitFor {
1119 host: false,
1120 host_features: false,
1121 // We're testing out an unstable feature (`-Zpanic-abort-tests`)
1122 // which inherits the panic setting from the dev/release profile
1123 // (basically avoid recompiles) but historical defaults required
1124 // that we always unwound.
1125 panic_setting: if gctx.cli_unstable().panic_abort_tests {
1126 PanicSetting::ReadProfile
1127 } else {
1128 PanicSetting::AlwaysUnwind
1129 },
1130 root_compile_kind,
1131 artifact_target_for_features: None,
1132 }
1133 }
1134
1135 /// This is a special case for unit tests of a proc-macro.
1136 ///
1137 /// Proc-macro unit tests are forced to be run on the host.
1138 pub fn new_host_test(gctx: &GlobalContext, root_compile_kind: CompileKind) -> UnitFor {
1139 let mut unit_for = UnitFor::new_test(gctx, root_compile_kind);
1140 unit_for.host = true;
1141 unit_for.host_features = true;
1142 unit_for
1143 }
1144
1145 /// Returns a new copy updated based on the target dependency.
1146 ///
1147 /// This is where the magic happens that the `host`/`host_features` settings
1148 /// transition in a sticky fashion. As the dependency graph is being
1149 /// built, once those flags are set, they stay set for the duration of
1150 /// that portion of tree.
1151 pub fn with_dependency(
1152 self,
1153 parent: &Unit,
1154 dep_target: &Target,
1155 root_compile_kind: CompileKind,
1156 ) -> UnitFor {
1157 // A build script or proc-macro transitions this to being built for the host.
1158 let dep_for_host = dep_target.for_host();
1159 // This is where feature decoupling of host versus target happens.
1160 //
1161 // Once host features are desired, they are always desired.
1162 //
1163 // A proc-macro should always use host features.
1164 //
1165 // Dependencies of a build script should use host features (subtle
1166 // point: the build script itself does *not* use host features, that's
1167 // why the parent is checked here, and not the dependency).
1168 let host_features =
1169 self.host_features || parent.target.is_custom_build() || dep_target.proc_macro();
1170 // Build scripts and proc macros, and all of their dependencies are
1171 // AlwaysUnwind.
1172 let panic_setting = if dep_for_host {
1173 PanicSetting::AlwaysUnwind
1174 } else {
1175 self.panic_setting
1176 };
1177 UnitFor {
1178 host: self.host || dep_for_host,
1179 host_features,
1180 panic_setting,
1181 root_compile_kind,
1182 artifact_target_for_features: self.artifact_target_for_features,
1183 }
1184 }
1185
1186 pub fn for_custom_build(self) -> UnitFor {
1187 UnitFor {
1188 host: true,
1189 host_features: self.host_features,
1190 // Force build scripts to always use `panic=unwind` for now to
1191 // maximally share dependencies with procedural macros.
1192 panic_setting: PanicSetting::AlwaysUnwind,
1193 root_compile_kind: self.root_compile_kind,
1194 artifact_target_for_features: self.artifact_target_for_features,
1195 }
1196 }
1197
1198 /// Set the artifact compile target for use in features using the given `artifact`.
1199 pub(crate) fn with_artifact_features(mut self, artifact: &Artifact) -> UnitFor {
1200 self.artifact_target_for_features = artifact.target().and_then(|t| t.to_compile_target());
1201 self
1202 }
1203
1204 /// Set the artifact compile target as determined by a resolved compile target. This is used if `target = "target"`.
1205 pub(crate) fn with_artifact_features_from_resolved_compile_kind(
1206 mut self,
1207 kind: Option<CompileKind>,
1208 ) -> UnitFor {
1209 self.artifact_target_for_features = kind.and_then(|kind| match kind {
1210 CompileKind::Host => None,
1211 CompileKind::Target(triple) => Some(triple),
1212 });
1213 self
1214 }
1215
1216 /// Returns `true` if this unit is for a build script or any of its
1217 /// dependencies, or a proc macro or any of its dependencies.
1218 pub fn is_for_host(&self) -> bool {
1219 self.host
1220 }
1221
1222 pub fn is_for_host_features(&self) -> bool {
1223 self.host_features
1224 }
1225
1226 /// Returns how `panic` settings should be handled for this profile
1227 fn panic_setting(&self) -> PanicSetting {
1228 self.panic_setting
1229 }
1230
1231 /// We might contain a parent artifact compile kind for features already, but will
1232 /// gladly accept the one of this dependency as an override as it defines how
1233 /// the artifact is built.
1234 /// If we are an artifact but don't specify a `target`, we assume the default
1235 /// compile kind that is suitable in this situation.
1236 pub(crate) fn map_to_features_for(&self, dep_artifact: Option<&Artifact>) -> FeaturesFor {
1237 FeaturesFor::from_for_host_or_artifact_target(
1238 self.is_for_host_features(),
1239 match dep_artifact {
1240 Some(artifact) => artifact
1241 .target()
1242 .and_then(|t| t.to_resolved_compile_target(self.root_compile_kind)),
1243 None => self.artifact_target_for_features,
1244 },
1245 )
1246 }
1247
1248 pub(crate) fn root_compile_kind(&self) -> CompileKind {
1249 self.root_compile_kind
1250 }
1251}
1252
1253/// Takes the manifest profiles, and overlays the config profiles on-top.
1254///
1255/// Returns a new copy of the profile map with all the mergers complete.
1256fn merge_config_profiles(
1257 ws: &Workspace<'_>,
1258 requested_profile: InternedString,
1259) -> CargoResult<BTreeMap<InternedString, TomlProfile>> {
1260 let mut profiles = match ws.profiles() {
1261 Some(profiles) => profiles
1262 .get_all()
1263 .iter()
1264 .map(|(k, v)| (InternedString::new(k), v.clone()))
1265 .collect(),
1266 None => BTreeMap::new(),
1267 };
1268 // Set of profile names to check if defined in config only.
1269 let mut check_to_add = HashSet::new();
1270 check_to_add.insert(requested_profile);
1271 // Merge config onto manifest profiles.
1272 for (name, profile) in &mut profiles {
1273 if let Some(config_profile) = get_config_profile(ws, name)? {
1274 profile.merge(&config_profile);
1275 }
1276 if let Some(inherits) = &profile.inherits {
1277 check_to_add.insert(InternedString::new(inherits));
1278 }
1279 }
1280 // Add the built-in profiles. This is important for things like `cargo
1281 // test` which implicitly use the "dev" profile for dependencies.
1282 for name in &["dev", "release", "test", "bench"] {
1283 check_to_add.insert(InternedString::new(name));
1284 }
1285 // Add config-only profiles.
1286 // Need to iterate repeatedly to get all the inherits values.
1287 let mut current = HashSet::new();
1288 while !check_to_add.is_empty() {
1289 std::mem::swap(&mut current, &mut check_to_add);
1290 for name in current.drain() {
1291 if !profiles.contains_key(name.as_str()) {
1292 if let Some(config_profile) = get_config_profile(ws, &name)? {
1293 if let Some(inherits) = &config_profile.inherits {
1294 check_to_add.insert(InternedString::new(inherits));
1295 }
1296 profiles.insert(name, config_profile);
1297 }
1298 }
1299 }
1300 }
1301 Ok(profiles)
1302}
1303
1304/// Helper for fetching a profile from config.
1305fn get_config_profile(ws: &Workspace<'_>, name: &str) -> CargoResult<Option<TomlProfile>> {
1306 let profile: Option<context::Value<TomlProfile>> =
1307 ws.gctx().get(&format!("profile.{}", name))?;
1308 let Some(profile) = profile else {
1309 return Ok(None);
1310 };
1311 let mut warnings = Vec::new();
1312 validate_profile(
1313 &profile.val,
1314 name,
1315 ws.gctx().cli_unstable(),
1316 ws.unstable_features(),
1317 &mut warnings,
1318 )
1319 .with_context(|| {
1320 format!(
1321 "config profile `{}` is not valid (defined in `{}`)",
1322 name, profile.definition
1323 )
1324 })?;
1325 for warning in warnings {
1326 ws.gctx().shell().warn(warning)?;
1327 }
1328 Ok(Some(profile.val))
1329}
1330
1331/// Validate that a package does not match multiple package override specs.
1332///
1333/// For example `[profile.dev.package.bar]` and `[profile.dev.package."bar:0.5.0"]`
1334/// would both match `bar:0.5.0` which would be ambiguous.
1335fn validate_packages_unique(
1336 resolve: &Resolve,
1337 name: &str,
1338 toml: &Option<TomlProfile>,
1339) -> CargoResult<HashSet<PackageIdSpec>> {
1340 let Some(toml) = toml else {
1341 return Ok(HashSet::new());
1342 };
1343 let Some(overrides) = toml.package.as_ref() else {
1344 return Ok(HashSet::new());
1345 };
1346 // Verify that a package doesn't match multiple spec overrides.
1347 let mut found = HashSet::new();
1348 for pkg_id in resolve.iter() {
1349 let matches: Vec<&PackageIdSpec> = overrides
1350 .keys()
1351 .filter_map(|key| match *key {
1352 ProfilePackageSpec::All => None,
1353 ProfilePackageSpec::Spec(ref spec) => {
1354 if spec.matches(pkg_id) {
1355 Some(spec)
1356 } else {
1357 None
1358 }
1359 }
1360 })
1361 .collect();
1362 match matches.len() {
1363 0 => {}
1364 1 => {
1365 found.insert(matches[0].clone());
1366 }
1367 _ => {
1368 let specs = matches
1369 .iter()
1370 .map(|spec| spec.to_string())
1371 .collect::<Vec<_>>()
1372 .join(", ");
1373 bail!(
1374 "multiple package overrides in profile `{}` match package `{}`\n\
1375 found package specs: {}",
1376 name,
1377 pkg_id,
1378 specs
1379 );
1380 }
1381 }
1382 }
1383 Ok(found)
1384}
1385
1386/// Check for any profile override specs that do not match any known packages.
1387///
1388/// This helps check for typos and mistakes.
1389fn validate_packages_unmatched(
1390 shell: &mut Shell,
1391 resolve: &Resolve,
1392 name: &str,
1393 toml: &TomlProfile,
1394 found: &HashSet<PackageIdSpec>,
1395) -> CargoResult<()> {
1396 let Some(overrides) = toml.package.as_ref() else {
1397 return Ok(());
1398 };
1399
1400 // Verify every override matches at least one package.
1401 let missing_specs = overrides.keys().filter_map(|key| {
1402 if let ProfilePackageSpec::Spec(ref spec) = *key {
1403 if !found.contains(spec) {
1404 return Some(spec);
1405 }
1406 }
1407 None
1408 });
1409 for spec in missing_specs {
1410 // See if there is an exact name match.
1411 let name_matches: Vec<String> = resolve
1412 .iter()
1413 .filter_map(|pkg_id| {
1414 if pkg_id.name() == spec.name() {
1415 Some(pkg_id.to_string())
1416 } else {
1417 None
1418 }
1419 })
1420 .collect();
1421 if name_matches.is_empty() {
1422 let suggestion = closest_msg(
1423 &spec.name(),
1424 resolve.iter(),
1425 |p| p.name().as_str(),
1426 "package",
1427 );
1428 shell.warn(format!(
1429 "profile package spec `{}` in profile `{}` did not match any packages{}",
1430 spec, name, suggestion
1431 ))?;
1432 } else {
1433 shell.warn(format!(
1434 "profile package spec `{}` in profile `{}` \
1435 has a version or URL that does not match any of the packages: {}",
1436 spec,
1437 name,
1438 name_matches.join(", ")
1439 ))?;
1440 }
1441 }
1442 Ok(())
1443}
1444
1445/// Returns `true` if a string is a toggle that turns an option off.
1446fn is_off(s: &str) -> bool {
1447 matches!(s, "off" | "n" | "no" | "none")
1448}