1use std::collections::HashSet;
2use std::{cmp, fmt, hash};
3
4use serde::Deserialize;
5
6use crate::core::compiler::CompileMode;
7use crate::core::interning::InternedString;
8use crate::core::{Features, PackageId, PackageIdSpec, PackageSet, Shell};
9use crate::util::errors::CargoResultExt;
10use crate::util::lev_distance::lev_distance;
11use crate::util::toml::{ProfilePackageSpec, StringOrBool, TomlProfile, TomlProfiles, U32OrBool};
12use crate::util::{CargoResult, Config};
13
14#[derive(Clone, Debug)]
16pub struct Profiles {
17 dev: ProfileMaker,
18 release: ProfileMaker,
19 test: ProfileMaker,
20 bench: ProfileMaker,
21 doc: ProfileMaker,
22}
23
24impl Profiles {
25 pub fn new(
26 profiles: Option<&TomlProfiles>,
27 config: &Config,
28 features: &Features,
29 warnings: &mut Vec<String>,
30 ) -> CargoResult<Profiles> {
31 if let Some(profiles) = profiles {
32 profiles.validate(features, warnings)?;
33 }
34
35 let config_profiles = config.profiles()?;
36 config_profiles.validate(features, warnings)?;
37
38 Ok(Profiles {
39 dev: ProfileMaker {
40 default: Profile::default_dev(),
41 toml: profiles.and_then(|p| p.dev.clone()),
42 config: config_profiles.dev.clone(),
43 },
44 release: ProfileMaker {
45 default: Profile::default_release(),
46 toml: profiles.and_then(|p| p.release.clone()),
47 config: config_profiles.release.clone(),
48 },
49 test: ProfileMaker {
50 default: Profile::default_test(),
51 toml: profiles.and_then(|p| p.test.clone()),
52 config: None,
53 },
54 bench: ProfileMaker {
55 default: Profile::default_bench(),
56 toml: profiles.and_then(|p| p.bench.clone()),
57 config: None,
58 },
59 doc: ProfileMaker {
60 default: Profile::default_doc(),
61 toml: profiles.and_then(|p| p.doc.clone()),
62 config: None,
63 },
64 })
65 }
66
67 pub fn get_profile(
71 &self,
72 pkg_id: PackageId,
73 is_member: bool,
74 unit_for: UnitFor,
75 mode: CompileMode,
76 release: bool,
77 ) -> Profile {
78 let maker = match mode {
79 CompileMode::Test | CompileMode::Bench => {
80 if release {
81 &self.bench
82 } else {
83 &self.test
84 }
85 }
86 CompileMode::Build
87 | CompileMode::Check { .. }
88 | CompileMode::Doctest
89 | CompileMode::RunCustomBuild => {
90 if release {
95 &self.release
96 } else {
97 &self.dev
98 }
99 }
100 CompileMode::Doc { .. } => &self.doc,
101 };
102 let mut profile = maker.get_profile(Some(pkg_id), is_member, unit_for);
103 if !unit_for.is_panic_ok() || mode.is_any_test() {
106 profile.panic = None;
107 }
108 profile
109 }
110
111 pub fn get_profile_run_custom_build(&self, for_unit_profile: &Profile) -> Profile {
117 let mut result = Profile::default();
118 result.debuginfo = for_unit_profile.debuginfo;
119 result.opt_level = for_unit_profile.opt_level;
120 result
121 }
122
123 pub fn base_profile(&self, release: bool) -> Profile {
127 if release {
128 self.release.get_profile(None, true, UnitFor::new_normal())
129 } else {
130 self.dev.get_profile(None, true, UnitFor::new_normal())
131 }
132 }
133
134 pub fn validate_packages(
136 &self,
137 shell: &mut Shell,
138 packages: &PackageSet<'_>,
139 ) -> CargoResult<()> {
140 self.dev.validate_packages(shell, packages)?;
141 self.release.validate_packages(shell, packages)?;
142 self.test.validate_packages(shell, packages)?;
143 self.bench.validate_packages(shell, packages)?;
144 self.doc.validate_packages(shell, packages)?;
145 Ok(())
146 }
147}
148
149#[derive(Debug, Clone)]
160struct ProfileMaker {
161 default: Profile,
163 toml: Option<TomlProfile>,
165 config: Option<TomlProfile>,
167}
168
169impl ProfileMaker {
170 fn get_profile(
171 &self,
172 pkg_id: Option<PackageId>,
173 is_member: bool,
174 unit_for: UnitFor,
175 ) -> Profile {
176 let mut profile = self.default;
177 if let Some(ref toml) = self.toml {
178 merge_toml(pkg_id, is_member, unit_for, &mut profile, toml);
179 }
180 if let Some(ref toml) = self.config {
181 merge_toml(pkg_id, is_member, unit_for, &mut profile, toml);
182 }
183 profile
184 }
185
186 fn validate_packages(&self, shell: &mut Shell, packages: &PackageSet<'_>) -> CargoResult<()> {
187 self.validate_packages_toml(shell, packages, &self.toml, true)?;
188 self.validate_packages_toml(shell, packages, &self.config, false)?;
189 Ok(())
190 }
191
192 fn validate_packages_toml(
193 &self,
194 shell: &mut Shell,
195 packages: &PackageSet<'_>,
196 toml: &Option<TomlProfile>,
197 warn_unmatched: bool,
198 ) -> CargoResult<()> {
199 let toml = match *toml {
200 Some(ref toml) => toml,
201 None => return Ok(()),
202 };
203 let overrides = match toml.overrides {
204 Some(ref overrides) => overrides,
205 None => return Ok(()),
206 };
207 let mut found = HashSet::new();
209 for pkg_id in packages.package_ids() {
210 let matches: Vec<&PackageIdSpec> = overrides
211 .keys()
212 .filter_map(|key| match *key {
213 ProfilePackageSpec::All => None,
214 ProfilePackageSpec::Spec(ref spec) => {
215 if spec.matches(pkg_id) {
216 Some(spec)
217 } else {
218 None
219 }
220 }
221 })
222 .collect();
223 match matches.len() {
224 0 => {}
225 1 => {
226 found.insert(matches[0].clone());
227 }
228 _ => {
229 let specs = matches
230 .iter()
231 .map(|spec| spec.to_string())
232 .collect::<Vec<_>>()
233 .join(", ");
234 failure::bail!(
235 "multiple profile overrides in profile `{}` match package `{}`\n\
236 found profile override specs: {}",
237 self.default.name,
238 pkg_id,
239 specs
240 );
241 }
242 }
243 }
244
245 if !warn_unmatched {
246 return Ok(());
247 }
248 let missing_specs = overrides.keys().filter_map(|key| {
250 if let ProfilePackageSpec::Spec(ref spec) = *key {
251 if !found.contains(spec) {
252 return Some(spec);
253 }
254 }
255 None
256 });
257 for spec in missing_specs {
258 let name_matches: Vec<String> = packages
260 .package_ids()
261 .filter_map(|pkg_id| {
262 if pkg_id.name().as_str() == spec.name() {
263 Some(pkg_id.to_string())
264 } else {
265 None
266 }
267 })
268 .collect();
269 if name_matches.is_empty() {
270 let suggestion = packages
271 .package_ids()
272 .map(|p| (lev_distance(spec.name(), &p.name()), p.name()))
273 .filter(|&(d, _)| d < 4)
274 .min_by_key(|p| p.0)
275 .map(|p| p.1);
276 match suggestion {
277 Some(p) => shell.warn(format!(
278 "profile override spec `{}` did not match any packages\n\n\
279 Did you mean `{}`?",
280 spec, p
281 ))?,
282 None => shell.warn(format!(
283 "profile override spec `{}` did not match any packages",
284 spec
285 ))?,
286 }
287 } else {
288 shell.warn(format!(
289 "version or URL in profile override spec `{}` does not \
290 match any of the packages: {}",
291 spec,
292 name_matches.join(", ")
293 ))?;
294 }
295 }
296 Ok(())
297 }
298}
299
300fn merge_toml(
301 pkg_id: Option<PackageId>,
302 is_member: bool,
303 unit_for: UnitFor,
304 profile: &mut Profile,
305 toml: &TomlProfile,
306) {
307 merge_profile(profile, toml);
308 if unit_for.is_custom_build() {
309 if let Some(ref build_override) = toml.build_override {
310 merge_profile(profile, build_override);
311 }
312 }
313 if let Some(ref overrides) = toml.overrides {
314 if !is_member {
315 if let Some(all) = overrides.get(&ProfilePackageSpec::All) {
316 merge_profile(profile, all);
317 }
318 }
319 if let Some(pkg_id) = pkg_id {
320 let mut matches = overrides
321 .iter()
322 .filter_map(|(key, spec_profile)| match *key {
323 ProfilePackageSpec::All => None,
324 ProfilePackageSpec::Spec(ref s) => {
325 if s.matches(pkg_id) {
326 Some(spec_profile)
327 } else {
328 None
329 }
330 }
331 });
332 if let Some(spec_profile) = matches.next() {
333 merge_profile(profile, spec_profile);
334 assert!(
337 matches.next().is_none(),
338 "package `{}` matched multiple profile overrides",
339 pkg_id
340 );
341 }
342 }
343 }
344}
345
346fn merge_profile(profile: &mut Profile, toml: &TomlProfile) {
347 if let Some(ref opt_level) = toml.opt_level {
348 profile.opt_level = InternedString::new(&opt_level.0);
349 }
350 match toml.lto {
351 Some(StringOrBool::Bool(b)) => profile.lto = Lto::Bool(b),
352 Some(StringOrBool::String(ref n)) => profile.lto = Lto::Named(InternedString::new(n)),
353 None => {}
354 }
355 if toml.codegen_units.is_some() {
356 profile.codegen_units = toml.codegen_units;
357 }
358 match toml.debug {
359 Some(U32OrBool::U32(debug)) => profile.debuginfo = Some(debug),
360 Some(U32OrBool::Bool(true)) => profile.debuginfo = Some(2),
361 Some(U32OrBool::Bool(false)) => profile.debuginfo = None,
362 None => {}
363 }
364 if let Some(debug_assertions) = toml.debug_assertions {
365 profile.debug_assertions = debug_assertions;
366 }
367 if let Some(rpath) = toml.rpath {
368 profile.rpath = rpath;
369 }
370 if let Some(ref panic) = toml.panic {
371 profile.panic = Some(InternedString::new(panic));
372 }
373 if let Some(overflow_checks) = toml.overflow_checks {
374 profile.overflow_checks = overflow_checks;
375 }
376 if let Some(incremental) = toml.incremental {
377 profile.incremental = incremental;
378 }
379}
380
381#[derive(Clone, Copy, Eq, PartialOrd, Ord)]
384pub struct Profile {
385 pub name: &'static str,
386 pub opt_level: InternedString,
387 pub lto: Lto,
388 pub codegen_units: Option<u32>,
390 pub debuginfo: Option<u32>,
391 pub debug_assertions: bool,
392 pub overflow_checks: bool,
393 pub rpath: bool,
394 pub incremental: bool,
395 pub panic: Option<InternedString>,
396}
397
398impl Default for Profile {
399 fn default() -> Profile {
400 Profile {
401 name: "",
402 opt_level: InternedString::new("0"),
403 lto: Lto::Bool(false),
404 codegen_units: None,
405 debuginfo: None,
406 debug_assertions: false,
407 overflow_checks: false,
408 rpath: false,
409 incremental: false,
410 panic: None,
411 }
412 }
413}
414
415compact_debug! {
416 impl fmt::Debug for Profile {
417 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
418 let (default, default_name) = match self.name {
419 "dev" => (Profile::default_dev(), "default_dev()"),
420 "release" => (Profile::default_release(), "default_release()"),
421 "test" => (Profile::default_test(), "default_test()"),
422 "bench" => (Profile::default_bench(), "default_bench()"),
423 "doc" => (Profile::default_doc(), "default_doc()"),
424 _ => (Profile::default(), "default()"),
425 };
426 [debug_the_fields(
427 name
428 opt_level
429 lto
430 codegen_units
431 debuginfo
432 debug_assertions
433 overflow_checks
434 rpath
435 incremental
436 panic
437 )]
438 }
439 }
440}
441
442impl fmt::Display for Profile {
443 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
444 write!(f, "Profile({})", self.name)
445 }
446}
447
448impl hash::Hash for Profile {
449 fn hash<H>(&self, state: &mut H)
450 where
451 H: hash::Hasher,
452 {
453 self.comparable().hash(state);
454 }
455}
456
457impl cmp::PartialEq for Profile {
458 fn eq(&self, other: &Self) -> bool {
459 self.comparable() == other.comparable()
460 }
461}
462
463impl Profile {
464 fn default_dev() -> Profile {
465 Profile {
466 name: "dev",
467 debuginfo: Some(2),
468 debug_assertions: true,
469 overflow_checks: true,
470 incremental: true,
471 ..Profile::default()
472 }
473 }
474
475 fn default_release() -> Profile {
476 Profile {
477 name: "release",
478 opt_level: InternedString::new("3"),
479 ..Profile::default()
480 }
481 }
482
483 fn default_test() -> Profile {
484 Profile {
485 name: "test",
486 ..Profile::default_dev()
487 }
488 }
489
490 fn default_bench() -> Profile {
491 Profile {
492 name: "bench",
493 ..Profile::default_release()
494 }
495 }
496
497 fn default_doc() -> Profile {
498 Profile {
499 name: "doc",
500 ..Profile::default_dev()
501 }
502 }
503
504 fn comparable(
508 &self,
509 ) -> (
510 &InternedString,
511 &Lto,
512 &Option<u32>,
513 &Option<u32>,
514 &bool,
515 &bool,
516 &bool,
517 &bool,
518 &Option<InternedString>,
519 ) {
520 (
521 &self.opt_level,
522 &self.lto,
523 &self.codegen_units,
524 &self.debuginfo,
525 &self.debug_assertions,
526 &self.overflow_checks,
527 &self.rpath,
528 &self.incremental,
529 &self.panic,
530 )
531 }
532}
533
534#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash, PartialOrd, Ord)]
536pub enum Lto {
537 Bool(bool),
540 Named(InternedString),
542}
543
544#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
547pub struct UnitFor {
548 custom_build: bool,
551 panic_ok: bool,
556}
557
558impl UnitFor {
559 pub fn new_normal() -> UnitFor {
562 UnitFor {
563 custom_build: false,
564 panic_ok: true,
565 }
566 }
567
568 pub fn new_build() -> UnitFor {
570 UnitFor {
571 custom_build: true,
572 panic_ok: false,
573 }
574 }
575
576 pub fn new_compiler() -> UnitFor {
578 UnitFor {
579 custom_build: false,
580 panic_ok: false,
581 }
582 }
583
584 pub fn new_test() -> UnitFor {
586 UnitFor {
587 custom_build: false,
588 panic_ok: false,
589 }
590 }
591
592 pub fn with_for_host(self, for_host: bool) -> UnitFor {
597 UnitFor {
598 custom_build: self.custom_build,
599 panic_ok: self.panic_ok && !for_host,
600 }
601 }
602
603 pub fn is_custom_build(self) -> bool {
606 self.custom_build
607 }
608
609 pub fn is_panic_ok(self) -> bool {
611 self.panic_ok
612 }
613
614 pub fn all_values() -> &'static [UnitFor] {
616 static ALL: [UnitFor; 3] = [
617 UnitFor {
618 custom_build: false,
619 panic_ok: true,
620 },
621 UnitFor {
622 custom_build: true,
623 panic_ok: false,
624 },
625 UnitFor {
626 custom_build: false,
627 panic_ok: false,
628 },
629 ];
630 &ALL
631 }
632}
633
634#[derive(Clone, Debug, Deserialize, Default)]
636pub struct ConfigProfiles {
637 dev: Option<TomlProfile>,
638 release: Option<TomlProfile>,
639}
640
641impl ConfigProfiles {
642 pub fn validate(&self, features: &Features, warnings: &mut Vec<String>) -> CargoResult<()> {
643 if let Some(ref profile) = self.dev {
644 profile
645 .validate("dev", features, warnings)
646 .chain_err(|| failure::format_err!("config profile `profile.dev` is not valid"))?;
647 }
648 if let Some(ref profile) = self.release {
649 profile
650 .validate("release", features, warnings)
651 .chain_err(|| {
652 failure::format_err!("config profile `profile.release` is not valid")
653 })?;
654 }
655 Ok(())
656 }
657}