1use std::collections::{HashMap, HashSet};
39use std::hash::{Hash, Hasher};
40use std::sync::Arc;
41
42use crate::core::compiler::UserIntent;
43use crate::core::compiler::unit_dependencies::build_unit_dependencies;
44use crate::core::compiler::unit_graph::{self, UnitDep, UnitGraph};
45use crate::core::compiler::{BuildConfig, BuildContext, BuildRunner, Compilation};
46use crate::core::compiler::{CompileKind, CompileTarget, RustcTargetData, Unit};
47use crate::core::compiler::{CrateType, TargetInfo, apply_env_config, standard_lib};
48use crate::core::compiler::{DefaultExecutor, Executor, UnitInterner};
49use crate::core::profiles::Profiles;
50use crate::core::resolver::features::{self, CliFeatures, FeaturesFor};
51use crate::core::resolver::{HasDevUnits, Resolve};
52use crate::core::{PackageId, PackageSet, SourceId, TargetKind, Workspace};
53use crate::drop_println;
54use crate::ops;
55use crate::ops::resolve::{SpecsAndResolvedFeatures, WorkspaceResolve};
56use crate::util::BuildLogger;
57use crate::util::context::{GlobalContext, WarningHandling};
58use crate::util::interning::InternedString;
59use crate::util::log_message::LogMessage;
60use crate::util::{CargoResult, StableHasher};
61
62mod compile_filter;
63use annotate_snippets::{Group, Level, Origin};
64pub use compile_filter::{CompileFilter, FilterRule, LibRule};
65
66pub(super) mod unit_generator;
67use itertools::Itertools as _;
68use unit_generator::UnitGenerator;
69
70mod packages;
71
72pub use packages::Packages;
73
74#[derive(Debug, Clone)]
83pub struct CompileOptions {
84 pub build_config: BuildConfig,
86 pub cli_features: CliFeatures,
88 pub spec: Packages,
90 pub filter: CompileFilter,
93 pub target_rustdoc_args: Option<Vec<String>>,
95 pub target_rustc_args: Option<Vec<String>>,
98 pub target_rustc_crate_types: Option<Vec<String>>,
100 pub rustdoc_document_private_items: bool,
103 pub honor_rust_version: Option<bool>,
106}
107
108impl CompileOptions {
109 pub fn new(gctx: &GlobalContext, intent: UserIntent) -> CargoResult<CompileOptions> {
110 let jobs = None;
111 let keep_going = false;
112 Ok(CompileOptions {
113 build_config: BuildConfig::new(gctx, jobs, keep_going, &[], intent)?,
114 cli_features: CliFeatures::new_all(false),
115 spec: ops::Packages::Packages(Vec::new()),
116 filter: CompileFilter::Default {
117 required_features_filterable: false,
118 },
119 target_rustdoc_args: None,
120 target_rustc_args: None,
121 target_rustc_crate_types: None,
122 rustdoc_document_private_items: false,
123 honor_rust_version: None,
124 })
125 }
126}
127
128pub fn compile<'a>(ws: &Workspace<'a>, options: &CompileOptions) -> CargoResult<Compilation<'a>> {
132 let exec: Arc<dyn Executor> = Arc::new(DefaultExecutor);
133 compile_with_exec(ws, options, &exec)
134}
135
136pub fn compile_with_exec<'a>(
141 ws: &Workspace<'a>,
142 options: &CompileOptions,
143 exec: &Arc<dyn Executor>,
144) -> CargoResult<Compilation<'a>> {
145 ws.emit_warnings()?;
146 let compilation = compile_ws(ws, options, exec)?;
147 if ws.gctx().warning_handling()? == WarningHandling::Deny && compilation.lint_warning_count > 0
148 {
149 anyhow::bail!("warnings are denied by `build.warnings` configuration")
150 }
151 Ok(compilation)
152}
153
154#[tracing::instrument(skip_all)]
156pub fn compile_ws<'a>(
157 ws: &Workspace<'a>,
158 options: &CompileOptions,
159 exec: &Arc<dyn Executor>,
160) -> CargoResult<Compilation<'a>> {
161 let interner = UnitInterner::new();
162 let logger = BuildLogger::maybe_new(ws)?;
163
164 if let Some(ref logger) = logger {
165 let rustc = ws.gctx().load_global_rustc(Some(ws))?;
166 let num_cpus = std::thread::available_parallelism()
167 .ok()
168 .map(|x| x.get() as u64);
169 logger.log(LogMessage::BuildStarted {
170 cwd: ws.gctx().cwd().to_path_buf(),
171 host: rustc.host.to_string(),
172 jobs: options.build_config.jobs,
173 num_cpus,
174 profile: options.build_config.requested_profile.to_string(),
175 rustc_version: rustc.version.to_string(),
176 rustc_version_verbose: rustc.verbose_version.clone(),
177 target_dir: ws.target_dir().as_path_unlocked().to_path_buf(),
178 workspace_root: ws.root().to_path_buf(),
179 });
180 }
181
182 let bcx = create_bcx(ws, options, &interner, logger.as_ref())?;
183
184 if options.build_config.unit_graph {
185 unit_graph::emit_serialized_unit_graph(&bcx.roots, &bcx.unit_graph, ws.gctx())?;
186 return Compilation::new(&bcx);
187 }
188 crate::core::gc::auto_gc(bcx.gctx);
189 let build_runner = BuildRunner::new(&bcx)?;
190 if options.build_config.dry_run {
191 build_runner.dry_run()
192 } else {
193 build_runner.compile(exec)
194 }
195}
196
197pub fn print<'a>(
201 ws: &Workspace<'a>,
202 options: &CompileOptions,
203 print_opt_value: &str,
204) -> CargoResult<()> {
205 let CompileOptions {
206 ref build_config,
207 ref target_rustc_args,
208 ..
209 } = *options;
210 let gctx = ws.gctx();
211 let rustc = gctx.load_global_rustc(Some(ws))?;
212 for (index, kind) in build_config.requested_kinds.iter().enumerate() {
213 if index != 0 {
214 drop_println!(gctx);
215 }
216 let target_info = TargetInfo::new(gctx, &build_config.requested_kinds, &rustc, *kind)?;
217 let mut process = rustc.process();
218 apply_env_config(gctx, &mut process)?;
219 process.args(&target_info.rustflags);
220 if let Some(args) = target_rustc_args {
221 process.args(args);
222 }
223 if let CompileKind::Target(t) = kind {
224 process.arg("--target").arg(t.rustc_target());
225 }
226 process.arg("--print").arg(print_opt_value);
227 process.exec()?;
228 }
229 Ok(())
230}
231
232#[tracing::instrument(skip_all)]
237pub fn create_bcx<'a, 'gctx>(
238 ws: &'a Workspace<'gctx>,
239 options: &'a CompileOptions,
240 interner: &'a UnitInterner,
241 logger: Option<&'a BuildLogger>,
242) -> CargoResult<BuildContext<'a, 'gctx>> {
243 let CompileOptions {
244 ref build_config,
245 ref spec,
246 ref cli_features,
247 ref filter,
248 ref target_rustdoc_args,
249 ref target_rustc_args,
250 ref target_rustc_crate_types,
251 rustdoc_document_private_items,
252 honor_rust_version,
253 } = *options;
254 let gctx = ws.gctx();
255
256 match build_config.intent {
258 UserIntent::Test | UserIntent::Build | UserIntent::Check { .. } | UserIntent::Bench => {
259 if ws.gctx().get_env("RUST_FLAGS").is_ok() {
260 gctx.shell().print_report(
261 &[Level::WARNING
262 .secondary_title("ignoring environment variable `RUST_FLAGS`")
263 .element(Level::HELP.message("rust flags are passed via `RUSTFLAGS`"))],
264 false,
265 )?;
266 }
267 }
268 UserIntent::Doc { .. } | UserIntent::Doctest => {
269 if ws.gctx().get_env("RUSTDOC_FLAGS").is_ok() {
270 gctx.shell().print_report(
271 &[Level::WARNING
272 .secondary_title("ignoring environment variable `RUSTDOC_FLAGS`")
273 .element(
274 Level::HELP.message("rustdoc flags are passed via `RUSTDOCFLAGS`"),
275 )],
276 false,
277 )?;
278 }
279 }
280 }
281 gctx.validate_term_config()?;
282
283 let mut target_data = RustcTargetData::new(ws, &build_config.requested_kinds)?;
284
285 let specs = spec.to_package_id_specs(ws)?;
286 let has_dev_units = {
287 let any_pkg_has_scrape_enabled = ws
291 .members_with_features(&specs, cli_features)?
292 .iter()
293 .any(|(pkg, _)| {
294 pkg.targets()
295 .iter()
296 .any(|target| target.is_example() && target.doc_scrape_examples().is_enabled())
297 });
298
299 if filter.need_dev_deps(build_config.intent)
300 || (build_config.intent.is_doc() && any_pkg_has_scrape_enabled)
301 {
302 HasDevUnits::Yes
303 } else {
304 HasDevUnits::No
305 }
306 };
307 let dry_run = false;
308
309 if let Some(logger) = logger {
310 let elapsed = ws.gctx().creation_time().elapsed().as_secs_f64();
311 logger.log(LogMessage::ResolutionStarted { elapsed });
312 }
313 let resolve = ops::resolve_ws_with_opts(
314 ws,
315 &mut target_data,
316 &build_config.requested_kinds,
317 cli_features,
318 &specs,
319 has_dev_units,
320 crate::core::resolver::features::ForceAllTargets::No,
321 dry_run,
322 )?;
323 let WorkspaceResolve {
324 mut pkg_set,
325 workspace_resolve,
326 targeted_resolve: resolve,
327 specs_and_features,
328 } = resolve;
329
330 if let Some(logger) = logger {
331 let elapsed = ws.gctx().creation_time().elapsed().as_secs_f64();
332 logger.log(LogMessage::ResolutionFinished { elapsed });
333 }
334
335 let std_resolve_features = if let Some(crates) = &gctx.cli_unstable().build_std {
336 let (std_package_set, std_resolve, std_features) = standard_lib::resolve_std(
337 ws,
338 &mut target_data,
339 &build_config,
340 crates,
341 &build_config.requested_kinds,
342 )?;
343 pkg_set.add_set(std_package_set);
344 Some((std_resolve, std_features))
345 } else {
346 None
347 };
348
349 let to_build_ids = resolve.specs_to_ids(&specs)?;
353 let mut to_builds = pkg_set.get_many(to_build_ids)?;
357
358 to_builds.sort_by_key(|p| p.package_id());
362
363 for pkg in to_builds.iter() {
364 pkg.manifest().print_teapot(gctx);
365
366 if build_config.intent.is_any_test()
367 && !ws.is_member(pkg)
368 && pkg.dependencies().iter().any(|dep| !dep.is_transitive())
369 {
370 anyhow::bail!(
371 "package `{}` cannot be tested because it requires dev-dependencies \
372 and is not a member of the workspace",
373 pkg.name()
374 );
375 }
376 }
377
378 let (extra_args, extra_args_name) = match (target_rustc_args, target_rustdoc_args) {
379 (Some(args), _) => (Some(args.clone()), "rustc"),
380 (_, Some(args)) => (Some(args.clone()), "rustdoc"),
381 _ => (None, ""),
382 };
383
384 if extra_args.is_some() && to_builds.len() != 1 {
385 panic!(
386 "`{}` should not accept multiple `-p` flags",
387 extra_args_name
388 );
389 }
390
391 let profiles = Profiles::new(ws, build_config.requested_profile)?;
392 profiles.validate_packages(
393 ws.profiles(),
394 &mut gctx.shell(),
395 workspace_resolve.as_ref().unwrap_or(&resolve),
396 )?;
397
398 let explicit_host_kind = CompileKind::Target(CompileTarget::new(&target_data.rustc.host)?);
402 let explicit_host_kinds: Vec<_> = build_config
403 .requested_kinds
404 .iter()
405 .map(|kind| match kind {
406 CompileKind::Host => explicit_host_kind,
407 CompileKind::Target(t) => CompileKind::Target(*t),
408 })
409 .collect();
410
411 let mut root_units = Vec::new();
412 let mut unit_graph = HashMap::new();
413 let mut scrape_units = Vec::new();
414
415 if let Some(logger) = logger {
416 let elapsed = ws.gctx().creation_time().elapsed().as_secs_f64();
417 logger.log(LogMessage::UnitGraphStarted { elapsed });
418 }
419
420 for SpecsAndResolvedFeatures {
421 specs,
422 resolved_features,
423 } in &specs_and_features
424 {
425 let spec_names = specs.iter().map(|spec| spec.name()).collect::<Vec<_>>();
431 let packages = to_builds
432 .iter()
433 .filter(|package| spec_names.contains(&package.name().as_str()))
434 .cloned()
435 .collect::<Vec<_>>();
436 let generator = UnitGenerator {
437 ws,
438 packages: &packages,
439 spec,
440 target_data: &target_data,
441 filter,
442 requested_kinds: &build_config.requested_kinds,
443 explicit_host_kind,
444 intent: build_config.intent,
445 resolve: &resolve,
446 workspace_resolve: &workspace_resolve,
447 resolved_features: &resolved_features,
448 package_set: &pkg_set,
449 profiles: &profiles,
450 interner,
451 has_dev_units,
452 };
453 let mut targeted_root_units = generator.generate_root_units()?;
454
455 if let Some(args) = target_rustc_crate_types {
456 override_rustc_crate_types(&mut targeted_root_units, args, interner)?;
457 }
458
459 let should_scrape =
460 build_config.intent.is_doc() && gctx.cli_unstable().rustdoc_scrape_examples;
461 let targeted_scrape_units = if should_scrape {
462 generator.generate_scrape_units(&targeted_root_units)?
463 } else {
464 Vec::new()
465 };
466
467 let std_roots = if let Some(crates) = gctx.cli_unstable().build_std.as_ref() {
468 let (std_resolve, std_features) = std_resolve_features.as_ref().unwrap();
469 standard_lib::generate_std_roots(
470 &crates,
471 &targeted_root_units,
472 std_resolve,
473 std_features,
474 &explicit_host_kinds,
475 &pkg_set,
476 interner,
477 &profiles,
478 &target_data,
479 )?
480 } else {
481 Default::default()
482 };
483
484 unit_graph.extend(build_unit_dependencies(
485 ws,
486 &pkg_set,
487 &resolve,
488 &resolved_features,
489 std_resolve_features.as_ref(),
490 &targeted_root_units,
491 &targeted_scrape_units,
492 &std_roots,
493 build_config.intent,
494 &target_data,
495 &profiles,
496 interner,
497 )?);
498 root_units.extend(targeted_root_units);
499 scrape_units.extend(targeted_scrape_units);
500 }
501
502 if build_config.intent.wants_deps_docs() {
505 remove_duplicate_doc(build_config, &root_units, &mut unit_graph);
506 }
507
508 let host_kind_requested = build_config
509 .requested_kinds
510 .iter()
511 .any(CompileKind::is_host);
512 let (root_units, scrape_units, unit_graph) = rebuild_unit_graph_shared(
518 interner,
519 unit_graph,
520 &root_units,
521 &scrape_units,
522 host_kind_requested.then_some(explicit_host_kind),
523 build_config.compile_time_deps_only,
524 );
525
526 let units: Vec<_> = unit_graph.keys().sorted().collect();
527 let unit_to_index: HashMap<_, _> = units
528 .iter()
529 .enumerate()
530 .map(|(i, &unit)| (unit.clone(), i as u64))
531 .collect();
532 if let Some(logger) = logger {
533 let root_unit_indexes: HashSet<_> =
534 root_units.iter().map(|unit| unit_to_index[&unit]).collect();
535
536 for (index, unit) in units.into_iter().enumerate() {
537 let index = index as u64;
538 let dependencies = unit_graph
539 .get(unit)
540 .map(|deps| {
541 deps.iter()
542 .filter_map(|dep| unit_to_index.get(&dep.unit).copied())
543 .collect()
544 })
545 .unwrap_or_default();
546 logger.log(LogMessage::UnitRegistered {
547 package_id: unit.pkg.package_id().to_spec(),
548 target: (&unit.target).into(),
549 mode: unit.mode,
550 platform: target_data.short_name(&unit.kind).to_owned(),
551 index,
552 features: unit
553 .features
554 .iter()
555 .map(|s| s.as_str().to_owned())
556 .collect(),
557 requested: root_unit_indexes.contains(&index),
558 dependencies,
559 });
560 }
561 let elapsed = ws.gctx().creation_time().elapsed().as_secs_f64();
562 logger.log(LogMessage::UnitGraphFinished { elapsed });
563 }
564
565 let mut extra_compiler_args = HashMap::new();
566 if let Some(args) = extra_args {
567 if root_units.len() != 1 {
568 anyhow::bail!(
569 "extra arguments to `{}` can only be passed to one \
570 target, consider filtering\nthe package by passing, \
571 e.g., `--lib` or `--bin NAME` to specify a single target",
572 extra_args_name
573 );
574 }
575 extra_compiler_args.insert(root_units[0].clone(), args);
576 }
577
578 for unit in root_units
579 .iter()
580 .filter(|unit| unit.mode.is_doc() || unit.mode.is_doc_test())
581 .filter(|unit| rustdoc_document_private_items || unit.target.is_bin())
582 {
583 let mut args = vec!["--document-private-items".into()];
587 if unit.target.is_bin() {
588 args.push("-Arustdoc::private-intra-doc-links".into());
592 }
593 extra_compiler_args
594 .entry(unit.clone())
595 .or_default()
596 .extend(args);
597 }
598
599 let mut error_count: usize = 0;
601 for unit in &root_units {
602 if let Some(target_src_path) = unit.target.src_path().path() {
603 validate_target_path_as_source_file(
604 gctx,
605 target_src_path,
606 unit.target.name(),
607 unit.target.kind(),
608 unit.pkg.manifest_path(),
609 &mut error_count,
610 )?
611 }
612 }
613 if error_count > 0 {
614 let plural: &str = if error_count > 1 { "s" } else { "" };
615 anyhow::bail!(
616 "could not compile due to {error_count} previous target resolution error{plural}"
617 );
618 }
619
620 if honor_rust_version.unwrap_or(true) {
621 let rustc_version = target_data.rustc.version.clone().into();
622
623 let mut incompatible = Vec::new();
624 let mut local_incompatible = false;
625 for unit in unit_graph.keys() {
626 let Some(pkg_msrv) = unit.pkg.rust_version() else {
627 continue;
628 };
629
630 if pkg_msrv.is_compatible_with(&rustc_version) {
631 continue;
632 }
633
634 local_incompatible |= unit.is_local();
635 incompatible.push((unit, pkg_msrv));
636 }
637 if !incompatible.is_empty() {
638 use std::fmt::Write as _;
639
640 let plural = if incompatible.len() == 1 { "" } else { "s" };
641 let mut message = format!(
642 "rustc {rustc_version} is not supported by the following package{plural}:\n"
643 );
644 incompatible.sort_by_key(|(unit, _)| (unit.pkg.name(), unit.pkg.version()));
645 for (unit, msrv) in incompatible {
646 let name = &unit.pkg.name();
647 let version = &unit.pkg.version();
648 writeln!(&mut message, " {name}@{version} requires rustc {msrv}").unwrap();
649 }
650 if ws.is_ephemeral() {
651 if ws.ignore_lock() {
652 writeln!(
653 &mut message,
654 "Try re-running `cargo install` with `--locked`"
655 )
656 .unwrap();
657 }
658 } else if !local_incompatible {
659 writeln!(
660 &mut message,
661 "Either upgrade rustc or select compatible dependency versions with
662`cargo update <name>@<current-ver> --precise <compatible-ver>`
663where `<compatible-ver>` is the latest version supporting rustc {rustc_version}",
664 )
665 .unwrap();
666 }
667 return Err(anyhow::Error::msg(message));
668 }
669 }
670
671 let bcx = BuildContext::new(
672 ws,
673 logger,
674 pkg_set,
675 build_config,
676 profiles,
677 extra_compiler_args,
678 target_data,
679 root_units,
680 unit_graph,
681 unit_to_index,
682 scrape_units,
683 )?;
684
685 Ok(bcx)
686}
687
688fn validate_target_path_as_source_file(
690 gctx: &GlobalContext,
691 target_path: &std::path::Path,
692 target_name: &str,
693 target_kind: &TargetKind,
694 unit_manifest_path: &std::path::Path,
695 error_count: &mut usize,
696) -> CargoResult<()> {
697 if !target_path.exists() {
698 *error_count += 1;
699
700 let err_msg = format!(
701 "can't find {} `{}` at path `{}`",
702 target_kind.description(),
703 target_name,
704 target_path.display()
705 );
706
707 let group = Group::with_title(Level::ERROR.primary_title(err_msg)).element(Origin::path(
708 unit_manifest_path.to_str().unwrap_or_default(),
709 ));
710
711 gctx.shell().print_report(&[group], true)?;
712 } else if target_path.is_dir() {
713 *error_count += 1;
714
715 let main_rs = target_path.join("main.rs");
717 let lib_rs = target_path.join("lib.rs");
718
719 let suggested_files_opt = match target_kind {
720 TargetKind::Lib(_) => {
721 if lib_rs.exists() {
722 Some(format!("`{}`", lib_rs.display()))
723 } else {
724 None
725 }
726 }
727 TargetKind::Bin => {
728 if main_rs.exists() {
729 Some(format!("`{}`", main_rs.display()))
730 } else {
731 None
732 }
733 }
734 TargetKind::Test => {
735 if main_rs.exists() {
736 Some(format!("`{}`", main_rs.display()))
737 } else {
738 None
739 }
740 }
741 TargetKind::ExampleBin => {
742 if main_rs.exists() {
743 Some(format!("`{}`", main_rs.display()))
744 } else {
745 None
746 }
747 }
748 TargetKind::Bench => {
749 if main_rs.exists() {
750 Some(format!("`{}`", main_rs.display()))
751 } else {
752 None
753 }
754 }
755 TargetKind::ExampleLib(_) => {
756 if lib_rs.exists() {
757 Some(format!("`{}`", lib_rs.display()))
758 } else {
759 None
760 }
761 }
762 TargetKind::CustomBuild => None,
763 };
764
765 let err_msg = format!(
766 "path `{}` for {} `{}` is a directory, but a source file was expected.",
767 target_path.display(),
768 target_kind.description(),
769 target_name,
770 );
771 let mut group = Group::with_title(Level::ERROR.primary_title(err_msg)).element(
772 Origin::path(unit_manifest_path.to_str().unwrap_or_default()),
773 );
774
775 if let Some(suggested_files) = suggested_files_opt {
776 group = group.element(
777 Level::HELP.message(format!("an entry point exists at {}", suggested_files)),
778 );
779 }
780
781 gctx.shell().print_report(&[group], true)?;
782 }
783
784 Ok(())
785}
786
787fn rebuild_unit_graph_shared(
822 interner: &UnitInterner,
823 unit_graph: UnitGraph,
824 roots: &[Unit],
825 scrape_units: &[Unit],
826 to_host: Option<CompileKind>,
827 compile_time_deps_only: bool,
828) -> (Vec<Unit>, Vec<Unit>, UnitGraph) {
829 let mut result = UnitGraph::new();
830 let mut memo = HashMap::new();
833 let new_roots = roots
834 .iter()
835 .map(|root| {
836 traverse_and_share(
837 interner,
838 &mut memo,
839 &mut result,
840 &unit_graph,
841 root,
842 true,
843 false,
844 to_host,
845 compile_time_deps_only,
846 )
847 })
848 .collect();
849 let new_scrape_units = scrape_units
853 .iter()
854 .map(|unit| memo.get(unit).unwrap().clone())
855 .collect();
856 (new_roots, new_scrape_units, result)
857}
858
859fn traverse_and_share(
865 interner: &UnitInterner,
866 memo: &mut HashMap<Unit, Unit>,
867 new_graph: &mut UnitGraph,
868 unit_graph: &UnitGraph,
869 unit: &Unit,
870 unit_is_root: bool,
871 unit_is_for_host: bool,
872 to_host: Option<CompileKind>,
873 compile_time_deps_only: bool,
874) -> Unit {
875 if let Some(new_unit) = memo.get(unit) {
876 return new_unit.clone();
878 }
879 let mut dep_hash = StableHasher::new();
880 let skip_non_compile_time_deps = compile_time_deps_only
881 && (!unit.target.is_compile_time_dependency() ||
882 unit_is_root);
885 let new_deps: Vec<_> = unit_graph[unit]
886 .iter()
887 .map(|dep| {
888 let new_dep_unit = traverse_and_share(
889 interner,
890 memo,
891 new_graph,
892 unit_graph,
893 &dep.unit,
894 false,
895 dep.unit_for.is_for_host(),
896 to_host,
897 skip_non_compile_time_deps,
901 );
902 new_dep_unit.hash(&mut dep_hash);
903 UnitDep {
904 unit: new_dep_unit,
905 ..dep.clone()
906 }
907 })
908 .collect();
909 let new_dep_hash = Hasher::finish(&dep_hash);
912
913 let canonical_kind = match to_host {
920 Some(to_host) if to_host == unit.kind => CompileKind::Host,
921 _ => unit.kind,
922 };
923
924 let mut profile = unit.profile.clone();
925 if profile.strip.is_deferred() {
926 if !profile.debuginfo.is_turned_on()
930 && new_deps
931 .iter()
932 .all(|dep| !dep.unit.profile.debuginfo.is_turned_on())
933 {
934 profile.strip = profile.strip.strip_debuginfo();
935 }
936 }
937
938 if unit_is_for_host
942 && to_host.is_some()
943 && profile.debuginfo.is_deferred()
944 && !unit.artifact.is_true()
945 {
946 let canonical_debuginfo = profile.debuginfo.finalize();
950 let mut canonical_profile = profile.clone();
951 canonical_profile.debuginfo = canonical_debuginfo;
952 let unit_probe = interner.intern(
953 &unit.pkg,
954 &unit.target,
955 canonical_profile,
956 to_host.unwrap(),
957 unit.mode,
958 unit.features.clone(),
959 unit.rustflags.clone(),
960 unit.rustdocflags.clone(),
961 unit.links_overrides.clone(),
962 unit.is_std,
963 unit.dep_hash,
964 unit.artifact,
965 unit.artifact_target_for_features,
966 unit.skip_non_compile_time_dep,
967 );
968
969 profile.debuginfo = if unit_graph.contains_key(&unit_probe) {
971 canonical_debuginfo
974 } else {
975 canonical_debuginfo.weaken()
978 }
979 }
980
981 let new_unit = interner.intern(
982 &unit.pkg,
983 &unit.target,
984 profile,
985 canonical_kind,
986 unit.mode,
987 unit.features.clone(),
988 unit.rustflags.clone(),
989 unit.rustdocflags.clone(),
990 unit.links_overrides.clone(),
991 unit.is_std,
992 new_dep_hash,
993 unit.artifact,
994 None,
997 skip_non_compile_time_deps,
998 );
999 if !unit_is_root || !compile_time_deps_only {
1000 assert!(memo.insert(unit.clone(), new_unit.clone()).is_none());
1001 }
1002 new_graph.entry(new_unit.clone()).or_insert(new_deps);
1003 new_unit
1004}
1005
1006fn remove_duplicate_doc(
1022 build_config: &BuildConfig,
1023 root_units: &[Unit],
1024 unit_graph: &mut UnitGraph,
1025) {
1026 let mut all_docs: HashMap<String, Vec<Unit>> = HashMap::new();
1029 for unit in unit_graph.keys() {
1030 if unit.mode.is_doc() {
1031 all_docs
1032 .entry(unit.target.crate_name())
1033 .or_default()
1034 .push(unit.clone());
1035 }
1036 }
1037 let mut removed_units: HashSet<Unit> = HashSet::new();
1040 let mut remove = |units: Vec<Unit>, reason: &str, cb: &dyn Fn(&Unit) -> bool| -> Vec<Unit> {
1041 let (to_remove, remaining_units): (Vec<Unit>, Vec<Unit>) = units
1042 .into_iter()
1043 .partition(|unit| cb(unit) && !root_units.contains(unit));
1044 for unit in to_remove {
1045 tracing::debug!(
1046 "removing duplicate doc due to {} for package {} target `{}`",
1047 reason,
1048 unit.pkg,
1049 unit.target.name()
1050 );
1051 unit_graph.remove(&unit);
1052 removed_units.insert(unit);
1053 }
1054 remaining_units
1055 };
1056 for (_crate_name, mut units) in all_docs {
1058 if units.len() == 1 {
1059 continue;
1060 }
1061 if build_config
1063 .requested_kinds
1064 .iter()
1065 .all(CompileKind::is_host)
1066 {
1067 units = remove(units, "host/target merger", &|unit| unit.kind.is_host());
1072 if units.len() == 1 {
1073 continue;
1074 }
1075 }
1076 let mut source_map: HashMap<(InternedString, SourceId, CompileKind), Vec<Unit>> =
1078 HashMap::new();
1079 for unit in units {
1080 let pkg_id = unit.pkg.package_id();
1081 source_map
1083 .entry((pkg_id.name(), pkg_id.source_id(), unit.kind))
1084 .or_default()
1085 .push(unit);
1086 }
1087 let mut remaining_units = Vec::new();
1088 for (_key, mut units) in source_map {
1089 if units.len() > 1 {
1090 units.sort_by(|a, b| a.pkg.version().partial_cmp(b.pkg.version()).unwrap());
1091 let newest_version = units.last().unwrap().pkg.version().clone();
1093 let keep_units = remove(units, "older version", &|unit| {
1094 unit.pkg.version() < &newest_version
1095 });
1096 remaining_units.extend(keep_units);
1097 } else {
1098 remaining_units.extend(units);
1099 }
1100 }
1101 if remaining_units.len() == 1 {
1102 continue;
1103 }
1104 }
1107 for unit_deps in unit_graph.values_mut() {
1109 unit_deps.retain(|unit_dep| !removed_units.contains(&unit_dep.unit));
1110 }
1111 let mut visited = HashSet::new();
1113 fn visit(unit: &Unit, graph: &UnitGraph, visited: &mut HashSet<Unit>) {
1114 if !visited.insert(unit.clone()) {
1115 return;
1116 }
1117 for dep in &graph[unit] {
1118 visit(&dep.unit, graph, visited);
1119 }
1120 }
1121 for unit in root_units {
1122 visit(unit, unit_graph, &mut visited);
1123 }
1124 unit_graph.retain(|unit, _| visited.contains(unit));
1125}
1126
1127fn override_rustc_crate_types(
1131 units: &mut [Unit],
1132 args: &[String],
1133 interner: &UnitInterner,
1134) -> CargoResult<()> {
1135 if units.len() != 1 {
1136 anyhow::bail!(
1137 "crate types to rustc can only be passed to one \
1138 target, consider filtering\nthe package by passing, \
1139 e.g., `--lib` or `--example` to specify a single target"
1140 );
1141 }
1142
1143 let unit = &units[0];
1144 let override_unit = |f: fn(Vec<CrateType>) -> TargetKind| {
1145 let crate_types = args.iter().map(|s| s.into()).collect();
1146 let mut target = unit.target.clone();
1147 target.set_kind(f(crate_types));
1148 interner.intern(
1149 &unit.pkg,
1150 &target,
1151 unit.profile.clone(),
1152 unit.kind,
1153 unit.mode,
1154 unit.features.clone(),
1155 unit.rustflags.clone(),
1156 unit.rustdocflags.clone(),
1157 unit.links_overrides.clone(),
1158 unit.is_std,
1159 unit.dep_hash,
1160 unit.artifact,
1161 unit.artifact_target_for_features,
1162 unit.skip_non_compile_time_dep,
1163 )
1164 };
1165 units[0] = match unit.target.kind() {
1166 TargetKind::Lib(_) => override_unit(TargetKind::Lib),
1167 TargetKind::ExampleLib(_) => override_unit(TargetKind::ExampleLib),
1168 _ => {
1169 anyhow::bail!(
1170 "crate types can only be specified for libraries and example libraries.\n\
1171 Binaries, tests, and benchmarks are always the `bin` crate type"
1172 );
1173 }
1174 };
1175
1176 Ok(())
1177}
1178
1179pub fn resolve_all_features(
1185 resolve_with_overrides: &Resolve,
1186 resolved_features: &features::ResolvedFeatures,
1187 package_set: &PackageSet<'_>,
1188 package_id: PackageId,
1189) -> HashSet<String> {
1190 let mut features: HashSet<String> = resolved_features
1191 .activated_features(package_id, FeaturesFor::NormalOrDev)
1192 .iter()
1193 .map(|s| s.to_string())
1194 .collect();
1195
1196 for (dep_id, deps) in resolve_with_overrides.deps(package_id) {
1199 let is_proc_macro = package_set
1200 .get_one(dep_id)
1201 .expect("packages downloaded")
1202 .proc_macro();
1203 for dep in deps {
1204 let features_for = FeaturesFor::from_for_host(is_proc_macro || dep.is_build());
1205 for feature in resolved_features
1206 .activated_features_unverified(dep_id, features_for)
1207 .unwrap_or_default()
1208 {
1209 features.insert(format!("{}/{}", dep.name_in_toml(), feature));
1210 }
1211 }
1212 }
1213
1214 features
1215}