1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
use std::collections::{HashMap, HashSet};
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use crate::core::compiler::unit_dependencies::build_unit_dependencies;
use crate::core::compiler::unit_graph::{self, UnitDep, UnitGraph};
use crate::core::compiler::{standard_lib, CrateType, TargetInfo};
use crate::core::compiler::{BuildConfig, BuildContext, Compilation, Context};
use crate::core::compiler::{CompileKind, CompileMode, CompileTarget, RustcTargetData, Unit};
use crate::core::compiler::{DefaultExecutor, Executor, UnitInterner};
use crate::core::profiles::Profiles;
use crate::core::resolver::features::{self, CliFeatures, FeaturesFor};
use crate::core::resolver::{HasDevUnits, Resolve};
use crate::core::{PackageId, PackageSet, SourceId, TargetKind, Workspace};
use crate::drop_println;
use crate::ops;
use crate::ops::resolve::WorkspaceResolve;
use crate::util::config::Config;
use crate::util::interning::InternedString;
use crate::util::{profile, CargoResult, StableHasher};
mod compile_filter;
pub use compile_filter::{CompileFilter, FilterRule, LibRule};
mod unit_generator;
use unit_generator::UnitGenerator;
mod packages;
pub use packages::Packages;
#[derive(Debug, Clone)]
pub struct CompileOptions {
pub build_config: BuildConfig,
pub cli_features: CliFeatures,
pub spec: Packages,
pub filter: CompileFilter,
pub target_rustdoc_args: Option<Vec<String>>,
pub target_rustc_args: Option<Vec<String>>,
pub target_rustc_crate_types: Option<Vec<String>>,
pub rustdoc_document_private_items: bool,
pub honor_rust_version: bool,
}
impl CompileOptions {
pub fn new(config: &Config, mode: CompileMode) -> CargoResult<CompileOptions> {
let jobs = None;
let keep_going = false;
Ok(CompileOptions {
build_config: BuildConfig::new(config, jobs, keep_going, &[], mode)?,
cli_features: CliFeatures::new_all(false),
spec: ops::Packages::Packages(Vec::new()),
filter: CompileFilter::Default {
required_features_filterable: false,
},
target_rustdoc_args: None,
target_rustc_args: None,
target_rustc_crate_types: None,
rustdoc_document_private_items: false,
honor_rust_version: true,
})
}
}
pub fn compile<'a>(ws: &Workspace<'a>, options: &CompileOptions) -> CargoResult<Compilation<'a>> {
let exec: Arc<dyn Executor> = Arc::new(DefaultExecutor);
compile_with_exec(ws, options, &exec)
}
pub fn compile_with_exec<'a>(
ws: &Workspace<'a>,
options: &CompileOptions,
exec: &Arc<dyn Executor>,
) -> CargoResult<Compilation<'a>> {
ws.emit_warnings()?;
compile_ws(ws, options, exec)
}
pub fn compile_ws<'a>(
ws: &Workspace<'a>,
options: &CompileOptions,
exec: &Arc<dyn Executor>,
) -> CargoResult<Compilation<'a>> {
let interner = UnitInterner::new();
let bcx = create_bcx(ws, options, &interner)?;
if options.build_config.unit_graph {
unit_graph::emit_serialized_unit_graph(&bcx.roots, &bcx.unit_graph, ws.config())?;
return Compilation::new(&bcx);
}
let _p = profile::start("compiling");
let cx = Context::new(&bcx)?;
cx.compile(exec)
}
pub fn print<'a>(
ws: &Workspace<'a>,
options: &CompileOptions,
print_opt_value: &str,
) -> CargoResult<()> {
let CompileOptions {
ref build_config,
ref target_rustc_args,
..
} = *options;
let config = ws.config();
let rustc = config.load_global_rustc(Some(ws))?;
for (index, kind) in build_config.requested_kinds.iter().enumerate() {
if index != 0 {
drop_println!(config);
}
let target_info = TargetInfo::new(config, &build_config.requested_kinds, &rustc, *kind)?;
let mut process = rustc.process();
process.args(&target_info.rustflags);
if let Some(args) = target_rustc_args {
process.args(args);
}
if let CompileKind::Target(t) = kind {
process.arg("--target").arg(t.short_name());
}
process.arg("--print").arg(print_opt_value);
process.exec()?;
}
Ok(())
}
pub fn create_bcx<'a, 'cfg>(
ws: &'a Workspace<'cfg>,
options: &'a CompileOptions,
interner: &'a UnitInterner,
) -> CargoResult<BuildContext<'a, 'cfg>> {
let CompileOptions {
ref build_config,
ref spec,
ref cli_features,
ref filter,
ref target_rustdoc_args,
ref target_rustc_args,
ref target_rustc_crate_types,
rustdoc_document_private_items,
honor_rust_version,
} = *options;
let config = ws.config();
match build_config.mode {
CompileMode::Test
| CompileMode::Build
| CompileMode::Check { .. }
| CompileMode::Bench
| CompileMode::RunCustomBuild => {
if std::env::var("RUST_FLAGS").is_ok() {
config.shell().warn(
"Cargo does not read `RUST_FLAGS` environment variable. Did you mean `RUSTFLAGS`?",
)?;
}
}
CompileMode::Doc { .. } | CompileMode::Doctest | CompileMode::Docscrape => {
if std::env::var("RUSTDOC_FLAGS").is_ok() {
config.shell().warn(
"Cargo does not read `RUSTDOC_FLAGS` environment variable. Did you mean `RUSTDOCFLAGS`?"
)?;
}
}
}
config.validate_term_config()?;
let target_data = RustcTargetData::new(ws, &build_config.requested_kinds)?;
let specs = spec.to_package_id_specs(ws)?;
let has_dev_units = {
let any_pkg_has_scrape_enabled = ws
.members_with_features(&specs, cli_features)?
.iter()
.any(|(pkg, _)| {
pkg.targets()
.iter()
.any(|target| target.is_example() && target.doc_scrape_examples().is_enabled())
});
if filter.need_dev_deps(build_config.mode)
|| (build_config.mode.is_doc() && any_pkg_has_scrape_enabled)
{
HasDevUnits::Yes
} else {
HasDevUnits::No
}
};
let resolve = ops::resolve_ws_with_opts(
ws,
&target_data,
&build_config.requested_kinds,
cli_features,
&specs,
has_dev_units,
crate::core::resolver::features::ForceAllTargets::No,
)?;
let WorkspaceResolve {
mut pkg_set,
workspace_resolve,
targeted_resolve: resolve,
resolved_features,
} = resolve;
let std_resolve_features = if let Some(crates) = &config.cli_unstable().build_std {
let (std_package_set, std_resolve, std_features) =
standard_lib::resolve_std(ws, &target_data, &build_config, crates)?;
pkg_set.add_set(std_package_set);
Some((std_resolve, std_features))
} else {
None
};
let to_build_ids = resolve.specs_to_ids(&specs)?;
let mut to_builds = pkg_set.get_many(to_build_ids)?;
to_builds.sort_by_key(|p| p.package_id());
for pkg in to_builds.iter() {
pkg.manifest().print_teapot(config);
if build_config.mode.is_any_test()
&& !ws.is_member(pkg)
&& pkg.dependencies().iter().any(|dep| !dep.is_transitive())
{
anyhow::bail!(
"package `{}` cannot be tested because it requires dev-dependencies \
and is not a member of the workspace",
pkg.name()
);
}
}
let (extra_args, extra_args_name) = match (target_rustc_args, target_rustdoc_args) {
(&Some(ref args), _) => (Some(args.clone()), "rustc"),
(_, &Some(ref args)) => (Some(args.clone()), "rustdoc"),
_ => (None, ""),
};
if extra_args.is_some() && to_builds.len() != 1 {
panic!(
"`{}` should not accept multiple `-p` flags",
extra_args_name
);
}
let profiles = Profiles::new(ws, build_config.requested_profile)?;
profiles.validate_packages(
ws.profiles(),
&mut config.shell(),
workspace_resolve.as_ref().unwrap_or(&resolve),
)?;
let explicit_host_kind = CompileKind::Target(CompileTarget::new(&target_data.rustc.host)?);
let explicit_host_kinds: Vec<_> = build_config
.requested_kinds
.iter()
.map(|kind| match kind {
CompileKind::Host => explicit_host_kind,
CompileKind::Target(t) => CompileKind::Target(*t),
})
.collect();
let generator = UnitGenerator {
ws,
packages: &to_builds,
filter,
requested_kinds: &build_config.requested_kinds,
explicit_host_kind,
mode: build_config.mode,
resolve: &resolve,
workspace_resolve: &workspace_resolve,
resolved_features: &resolved_features,
package_set: &pkg_set,
profiles: &profiles,
interner,
has_dev_units,
};
let mut units = generator.generate_root_units()?;
if let Some(args) = target_rustc_crate_types {
override_rustc_crate_types(&mut units, args, interner)?;
}
let should_scrape = build_config.mode.is_doc() && config.cli_unstable().rustdoc_scrape_examples;
let mut scrape_units = if should_scrape {
UnitGenerator {
mode: CompileMode::Docscrape,
..generator
}
.generate_scrape_units(&units)?
} else {
Vec::new()
};
let std_roots = if let Some(crates) = standard_lib::std_crates(config, Some(&units)) {
let (std_resolve, std_features) = std_resolve_features.as_ref().unwrap();
standard_lib::generate_std_roots(
&crates,
std_resolve,
std_features,
&explicit_host_kinds,
&pkg_set,
interner,
&profiles,
)?
} else {
Default::default()
};
let mut unit_graph = build_unit_dependencies(
ws,
&pkg_set,
&resolve,
&resolved_features,
std_resolve_features.as_ref(),
&units,
&scrape_units,
&std_roots,
build_config.mode,
&target_data,
&profiles,
interner,
)?;
if build_config.mode == (CompileMode::Doc { deps: true }) {
remove_duplicate_doc(build_config, &units, &mut unit_graph);
}
let host_kind_requested = build_config
.requested_kinds
.iter()
.any(CompileKind::is_host);
let should_share_deps = host_kind_requested
|| config.cli_unstable().bindeps
&& unit_graph
.iter()
.any(|(unit, _)| unit.artifact_target_for_features.is_some());
if should_share_deps {
let new_graph = rebuild_unit_graph_shared(
interner,
unit_graph,
&units,
&scrape_units,
host_kind_requested.then_some(explicit_host_kind),
);
units = new_graph.0;
scrape_units = new_graph.1;
unit_graph = new_graph.2;
}
let mut extra_compiler_args = HashMap::new();
if let Some(args) = extra_args {
if units.len() != 1 {
anyhow::bail!(
"extra arguments to `{}` can only be passed to one \
target, consider filtering\nthe package by passing, \
e.g., `--lib` or `--bin NAME` to specify a single target",
extra_args_name
);
}
extra_compiler_args.insert(units[0].clone(), args);
}
for unit in units
.iter()
.filter(|unit| unit.mode.is_doc() || unit.mode.is_doc_test())
.filter(|unit| rustdoc_document_private_items || unit.target.is_bin())
{
let mut args = vec!["--document-private-items".into()];
if unit.target.is_bin() {
args.push("-Arustdoc::private-intra-doc-links".into());
}
extra_compiler_args
.entry(unit.clone())
.or_default()
.extend(args);
}
if honor_rust_version {
let current_version = &target_data.rustc.version;
let untagged_version = semver::Version::new(
current_version.major,
current_version.minor,
current_version.patch,
);
for unit in unit_graph.keys() {
let version = match unit.pkg.rust_version() {
Some(v) => v,
None => continue,
};
let req = semver::VersionReq::parse(version).unwrap();
if req.matches(&untagged_version) {
continue;
}
let guidance = if ws.is_ephemeral() {
if ws.ignore_lock() {
"Try re-running cargo install with `--locked`".to_string()
} else {
String::new()
}
} else if !unit.is_local() {
format!(
"Either upgrade to rustc {} or newer, or use\n\
cargo update -p {}@{} --precise ver\n\
where `ver` is the latest version of `{}` supporting rustc {}",
version,
unit.pkg.name(),
unit.pkg.version(),
unit.pkg.name(),
current_version,
)
} else {
String::new()
};
anyhow::bail!(
"package `{}` cannot be built because it requires rustc {} or newer, \
while the currently active rustc version is {}\n{}",
unit.pkg,
version,
current_version,
guidance,
);
}
}
let bcx = BuildContext::new(
ws,
pkg_set,
build_config,
profiles,
extra_compiler_args,
target_data,
units,
unit_graph,
scrape_units,
)?;
Ok(bcx)
}
fn rebuild_unit_graph_shared(
interner: &UnitInterner,
unit_graph: UnitGraph,
roots: &[Unit],
scrape_units: &[Unit],
to_host: Option<CompileKind>,
) -> (Vec<Unit>, Vec<Unit>, UnitGraph) {
let mut result = UnitGraph::new();
let mut memo = HashMap::new();
let new_roots = roots
.iter()
.map(|root| {
traverse_and_share(interner, &mut memo, &mut result, &unit_graph, root, to_host)
})
.collect();
let new_scrape_units = scrape_units
.iter()
.map(|unit| memo.get(unit).unwrap().clone())
.collect();
(new_roots, new_scrape_units, result)
}
fn traverse_and_share(
interner: &UnitInterner,
memo: &mut HashMap<Unit, Unit>,
new_graph: &mut UnitGraph,
unit_graph: &UnitGraph,
unit: &Unit,
to_host: Option<CompileKind>,
) -> Unit {
if let Some(new_unit) = memo.get(unit) {
return new_unit.clone();
}
let mut dep_hash = StableHasher::new();
let new_deps: Vec<_> = unit_graph[unit]
.iter()
.map(|dep| {
let new_dep_unit =
traverse_and_share(interner, memo, new_graph, unit_graph, &dep.unit, to_host);
new_dep_unit.hash(&mut dep_hash);
UnitDep {
unit: new_dep_unit,
..dep.clone()
}
})
.collect();
let new_dep_hash = dep_hash.finish();
let new_kind = match to_host {
Some(to_host) if to_host == unit.kind => CompileKind::Host,
_ => unit.kind,
};
let new_unit = interner.intern(
&unit.pkg,
&unit.target,
unit.profile.clone(),
new_kind,
unit.mode,
unit.features.clone(),
unit.is_std,
new_dep_hash,
unit.artifact,
None,
);
assert!(memo.insert(unit.clone(), new_unit.clone()).is_none());
new_graph.entry(new_unit.clone()).or_insert(new_deps);
new_unit
}
fn remove_duplicate_doc(
build_config: &BuildConfig,
root_units: &[Unit],
unit_graph: &mut UnitGraph,
) {
let mut all_docs: HashMap<String, Vec<Unit>> = HashMap::new();
for unit in unit_graph.keys() {
if unit.mode.is_doc() {
all_docs
.entry(unit.target.crate_name())
.or_default()
.push(unit.clone());
}
}
let mut removed_units: HashSet<Unit> = HashSet::new();
let mut remove = |units: Vec<Unit>, reason: &str, cb: &dyn Fn(&Unit) -> bool| -> Vec<Unit> {
let (to_remove, remaining_units): (Vec<Unit>, Vec<Unit>) = units
.into_iter()
.partition(|unit| cb(unit) && !root_units.contains(unit));
for unit in to_remove {
log::debug!(
"removing duplicate doc due to {} for package {} target `{}`",
reason,
unit.pkg,
unit.target.name()
);
unit_graph.remove(&unit);
removed_units.insert(unit);
}
remaining_units
};
for (_crate_name, mut units) in all_docs {
if units.len() == 1 {
continue;
}
if build_config
.requested_kinds
.iter()
.all(CompileKind::is_host)
{
units = remove(units, "host/target merger", &|unit| unit.kind.is_host());
if units.len() == 1 {
continue;
}
}
let mut source_map: HashMap<(InternedString, SourceId, CompileKind), Vec<Unit>> =
HashMap::new();
for unit in units {
let pkg_id = unit.pkg.package_id();
source_map
.entry((pkg_id.name(), pkg_id.source_id(), unit.kind))
.or_default()
.push(unit);
}
let mut remaining_units = Vec::new();
for (_key, mut units) in source_map {
if units.len() > 1 {
units.sort_by(|a, b| a.pkg.version().partial_cmp(b.pkg.version()).unwrap());
let newest_version = units.last().unwrap().pkg.version().clone();
let keep_units = remove(units, "older version", &|unit| {
unit.pkg.version() < &newest_version
});
remaining_units.extend(keep_units);
} else {
remaining_units.extend(units);
}
}
if remaining_units.len() == 1 {
continue;
}
}
for unit_deps in unit_graph.values_mut() {
unit_deps.retain(|unit_dep| !removed_units.contains(&unit_dep.unit));
}
let mut visited = HashSet::new();
fn visit(unit: &Unit, graph: &UnitGraph, visited: &mut HashSet<Unit>) {
if !visited.insert(unit.clone()) {
return;
}
for dep in &graph[unit] {
visit(&dep.unit, graph, visited);
}
}
for unit in root_units {
visit(unit, unit_graph, &mut visited);
}
unit_graph.retain(|unit, _| visited.contains(unit));
}
fn override_rustc_crate_types(
units: &mut [Unit],
args: &[String],
interner: &UnitInterner,
) -> CargoResult<()> {
if units.len() != 1 {
anyhow::bail!(
"crate types to rustc can only be passed to one \
target, consider filtering\nthe package by passing, \
e.g., `--lib` or `--example` to specify a single target"
);
}
let unit = &units[0];
let override_unit = |f: fn(Vec<CrateType>) -> TargetKind| {
let crate_types = args.iter().map(|s| s.into()).collect();
let mut target = unit.target.clone();
target.set_kind(f(crate_types));
interner.intern(
&unit.pkg,
&target,
unit.profile.clone(),
unit.kind,
unit.mode,
unit.features.clone(),
unit.is_std,
unit.dep_hash,
unit.artifact,
unit.artifact_target_for_features,
)
};
units[0] = match unit.target.kind() {
TargetKind::Lib(_) => override_unit(TargetKind::Lib),
TargetKind::ExampleLib(_) => override_unit(TargetKind::ExampleLib),
_ => {
anyhow::bail!(
"crate types can only be specified for libraries and example libraries.\n\
Binaries, tests, and benchmarks are always the `bin` crate type"
);
}
};
Ok(())
}
pub fn resolve_all_features(
resolve_with_overrides: &Resolve,
resolved_features: &features::ResolvedFeatures,
package_set: &PackageSet<'_>,
package_id: PackageId,
) -> HashSet<String> {
let mut features: HashSet<String> = resolved_features
.activated_features(package_id, FeaturesFor::NormalOrDev)
.iter()
.map(|s| s.to_string())
.collect();
for (dep_id, deps) in resolve_with_overrides.deps(package_id) {
let is_proc_macro = package_set
.get_one(dep_id)
.expect("packages downloaded")
.proc_macro();
for dep in deps {
let features_for = FeaturesFor::from_for_host(is_proc_macro || dep.is_build());
for feature in resolved_features
.activated_features_unverified(dep_id, features_for)
.unwrap_or_default()
{
features.insert(format!("{}/{}", dep.name_in_toml(), feature));
}
}
}
features
}