]> git.proxmox.com Git - rustc.git/blob - src/bootstrap/builder.rs
New upstream version 1.41.1+dfsg1
[rustc.git] / src / bootstrap / builder.rs
1 use std::any::Any;
2 use std::cell::{Cell, RefCell};
3 use std::collections::BTreeSet;
4 use std::collections::HashMap;
5 use std::env;
6 use std::ffi::OsStr;
7 use std::fmt::Debug;
8 use std::fs;
9 use std::hash::Hash;
10 use std::ops::Deref;
11 use std::path::{Path, PathBuf};
12 use std::process::Command;
13 use std::time::{Duration, Instant};
14
15 use build_helper::t;
16
17 use crate::cache::{Cache, Interned, INTERNER};
18 use crate::check;
19 use crate::compile;
20 use crate::dist;
21 use crate::doc;
22 use crate::flags::Subcommand;
23 use crate::install;
24 use crate::native;
25 use crate::test;
26 use crate::tool;
27 use crate::util::{self, add_lib_path, exe, libdir};
28 use crate::{Build, DocTests, Mode, GitRepo};
29
30 pub use crate::Compiler;
31
32 use petgraph::graph::NodeIndex;
33 use petgraph::Graph;
34
35 pub struct Builder<'a> {
36 pub build: &'a Build,
37 pub top_stage: u32,
38 pub kind: Kind,
39 cache: Cache,
40 stack: RefCell<Vec<Box<dyn Any>>>,
41 time_spent_on_dependencies: Cell<Duration>,
42 pub paths: Vec<PathBuf>,
43 graph_nodes: RefCell<HashMap<String, NodeIndex>>,
44 graph: RefCell<Graph<String, bool>>,
45 parent: Cell<Option<NodeIndex>>,
46 }
47
48 impl<'a> Deref for Builder<'a> {
49 type Target = Build;
50
51 fn deref(&self) -> &Self::Target {
52 self.build
53 }
54 }
55
56 pub trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
57 /// `PathBuf` when directories are created or to return a `Compiler` once
58 /// it's been assembled.
59 type Output: Clone;
60
61 const DEFAULT: bool = false;
62
63 /// If true, then this rule should be skipped if --target was specified, but --host was not
64 const ONLY_HOSTS: bool = false;
65
66 /// Primary function to execute this rule. Can call `builder.ensure()`
67 /// with other steps to run those.
68 fn run(self, builder: &Builder<'_>) -> Self::Output;
69
70 /// When bootstrap is passed a set of paths, this controls whether this rule
71 /// will execute. However, it does not get called in a "default" context
72 /// when we are not passed any paths; in that case, `make_run` is called
73 /// directly.
74 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_>;
75
76 /// Builds up a "root" rule, either as a default rule or from a path passed
77 /// to us.
78 ///
79 /// When path is `None`, we are executing in a context where no paths were
80 /// passed. When `./x.py build` is run, for example, this rule could get
81 /// called if it is in the correct list below with a path of `None`.
82 fn make_run(_run: RunConfig<'_>) {
83 // It is reasonable to not have an implementation of make_run for rules
84 // who do not want to get called from the root context. This means that
85 // they are likely dependencies (e.g., sysroot creation) or similar, and
86 // as such calling them from ./x.py isn't logical.
87 unimplemented!()
88 }
89 }
90
91 pub struct RunConfig<'a> {
92 pub builder: &'a Builder<'a>,
93 pub host: Interned<String>,
94 pub target: Interned<String>,
95 pub path: PathBuf,
96 }
97
98 struct StepDescription {
99 default: bool,
100 only_hosts: bool,
101 should_run: fn(ShouldRun<'_>) -> ShouldRun<'_>,
102 make_run: fn(RunConfig<'_>),
103 name: &'static str,
104 }
105
106 #[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
107 pub enum PathSet {
108 Set(BTreeSet<PathBuf>),
109 Suite(PathBuf),
110 }
111
112 impl PathSet {
113 fn empty() -> PathSet {
114 PathSet::Set(BTreeSet::new())
115 }
116
117 fn one<P: Into<PathBuf>>(path: P) -> PathSet {
118 let mut set = BTreeSet::new();
119 set.insert(path.into());
120 PathSet::Set(set)
121 }
122
123 fn has(&self, needle: &Path) -> bool {
124 match self {
125 PathSet::Set(set) => set.iter().any(|p| p.ends_with(needle)),
126 PathSet::Suite(suite) => suite.ends_with(needle),
127 }
128 }
129
130 fn path(&self, builder: &Builder<'_>) -> PathBuf {
131 match self {
132 PathSet::Set(set) => set
133 .iter()
134 .next()
135 .unwrap_or(&builder.build.src)
136 .to_path_buf(),
137 PathSet::Suite(path) => PathBuf::from(path),
138 }
139 }
140 }
141
142 impl StepDescription {
143 fn from<S: Step>() -> StepDescription {
144 StepDescription {
145 default: S::DEFAULT,
146 only_hosts: S::ONLY_HOSTS,
147 should_run: S::should_run,
148 make_run: S::make_run,
149 name: std::any::type_name::<S>(),
150 }
151 }
152
153 fn maybe_run(&self, builder: &Builder<'_>, pathset: &PathSet) {
154 if builder.config.exclude.iter().any(|e| pathset.has(e)) {
155 eprintln!("Skipping {:?} because it is excluded", pathset);
156 return;
157 } else if !builder.config.exclude.is_empty() {
158 eprintln!(
159 "{:?} not skipped for {:?} -- not in {:?}",
160 pathset, self.name, builder.config.exclude
161 );
162 }
163 let hosts = &builder.hosts;
164
165 // Determine the targets participating in this rule.
166 let targets = if self.only_hosts {
167 if builder.config.skip_only_host_steps {
168 return; // don't run anything
169 } else {
170 &builder.hosts
171 }
172 } else {
173 &builder.targets
174 };
175
176 for host in hosts {
177 for target in targets {
178 let run = RunConfig {
179 builder,
180 path: pathset.path(builder),
181 host: *host,
182 target: *target,
183 };
184 (self.make_run)(run);
185 }
186 }
187 }
188
189 fn run(v: &[StepDescription], builder: &Builder<'_>, paths: &[PathBuf]) {
190 let should_runs = v
191 .iter()
192 .map(|desc| (desc.should_run)(ShouldRun::new(builder)))
193 .collect::<Vec<_>>();
194
195 // sanity checks on rules
196 for (desc, should_run) in v.iter().zip(&should_runs) {
197 assert!(
198 !should_run.paths.is_empty(),
199 "{:?} should have at least one pathset",
200 desc.name
201 );
202 }
203
204 if paths.is_empty() {
205 for (desc, should_run) in v.iter().zip(should_runs) {
206 if desc.default && should_run.is_really_default {
207 for pathset in &should_run.paths {
208 desc.maybe_run(builder, pathset);
209 }
210 }
211 }
212 } else {
213 for path in paths {
214 // strip CurDir prefix if present
215 let path = match path.strip_prefix(".") {
216 Ok(p) => p,
217 Err(_) => path,
218 };
219
220 let mut attempted_run = false;
221 for (desc, should_run) in v.iter().zip(&should_runs) {
222 if let Some(suite) = should_run.is_suite_path(path) {
223 attempted_run = true;
224 desc.maybe_run(builder, suite);
225 } else if let Some(pathset) = should_run.pathset_for_path(path) {
226 attempted_run = true;
227 desc.maybe_run(builder, pathset);
228 }
229 }
230
231 if !attempted_run {
232 panic!("Error: no rules matched {}.", path.display());
233 }
234 }
235 }
236 }
237 }
238
239 #[derive(Clone)]
240 pub struct ShouldRun<'a> {
241 pub builder: &'a Builder<'a>,
242 // use a BTreeSet to maintain sort order
243 paths: BTreeSet<PathSet>,
244
245 // If this is a default rule, this is an additional constraint placed on
246 // its run. Generally something like compiler docs being enabled.
247 is_really_default: bool,
248 }
249
250 impl<'a> ShouldRun<'a> {
251 fn new(builder: &'a Builder<'_>) -> ShouldRun<'a> {
252 ShouldRun {
253 builder,
254 paths: BTreeSet::new(),
255 is_really_default: true, // by default no additional conditions
256 }
257 }
258
259 pub fn default_condition(mut self, cond: bool) -> Self {
260 self.is_really_default = cond;
261 self
262 }
263
264 // Unlike `krate` this will create just one pathset. As such, it probably shouldn't actually
265 // ever be used, but as we transition to having all rules properly handle passing krate(...) by
266 // actually doing something different for every crate passed.
267 pub fn all_krates(mut self, name: &str) -> Self {
268 let mut set = BTreeSet::new();
269 for krate in self.builder.in_tree_crates(name) {
270 set.insert(PathBuf::from(&krate.path));
271 }
272 self.paths.insert(PathSet::Set(set));
273 self
274 }
275
276 pub fn krate(mut self, name: &str) -> Self {
277 for krate in self.builder.in_tree_crates(name) {
278 self.paths.insert(PathSet::one(&krate.path));
279 }
280 self
281 }
282
283 // single, non-aliased path
284 pub fn path(self, path: &str) -> Self {
285 self.paths(&[path])
286 }
287
288 // multiple aliases for the same job
289 pub fn paths(mut self, paths: &[&str]) -> Self {
290 self.paths
291 .insert(PathSet::Set(paths.iter().map(PathBuf::from).collect()));
292 self
293 }
294
295 pub fn is_suite_path(&self, path: &Path) -> Option<&PathSet> {
296 self.paths.iter().find(|pathset| match pathset {
297 PathSet::Suite(p) => path.starts_with(p),
298 PathSet::Set(_) => false,
299 })
300 }
301
302 pub fn suite_path(mut self, suite: &str) -> Self {
303 self.paths.insert(PathSet::Suite(PathBuf::from(suite)));
304 self
305 }
306
307 // allows being more explicit about why should_run in Step returns the value passed to it
308 pub fn never(mut self) -> ShouldRun<'a> {
309 self.paths.insert(PathSet::empty());
310 self
311 }
312
313 fn pathset_for_path(&self, path: &Path) -> Option<&PathSet> {
314 self.paths.iter().find(|pathset| pathset.has(path))
315 }
316 }
317
318 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
319 pub enum Kind {
320 Build,
321 Check,
322 Clippy,
323 Fix,
324 Test,
325 Bench,
326 Dist,
327 Doc,
328 Install,
329 }
330
331 impl<'a> Builder<'a> {
332 fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
333 macro_rules! describe {
334 ($($rule:ty),+ $(,)?) => {{
335 vec![$(StepDescription::from::<$rule>()),+]
336 }};
337 }
338 match kind {
339 Kind::Build => describe!(
340 compile::Std,
341 compile::Rustc,
342 compile::StartupObjects,
343 tool::BuildManifest,
344 tool::Rustbook,
345 tool::ErrorIndex,
346 tool::UnstableBookGen,
347 tool::Tidy,
348 tool::Linkchecker,
349 tool::CargoTest,
350 tool::Compiletest,
351 tool::RemoteTestServer,
352 tool::RemoteTestClient,
353 tool::RustInstaller,
354 tool::Cargo,
355 tool::Rls,
356 tool::Rustdoc,
357 tool::Clippy,
358 native::Llvm,
359 tool::Rustfmt,
360 tool::Miri,
361 native::Lld
362 ),
363 Kind::Check | Kind::Clippy | Kind::Fix => describe!(
364 check::Std,
365 check::Rustc,
366 check::Rustdoc
367 ),
368 Kind::Test => describe!(
369 crate::toolstate::ToolStateCheck,
370 test::Tidy,
371 test::Ui,
372 test::CompileFail,
373 test::RunFail,
374 test::RunPassValgrind,
375 test::MirOpt,
376 test::Codegen,
377 test::CodegenUnits,
378 test::Assembly,
379 test::Incremental,
380 test::Debuginfo,
381 test::UiFullDeps,
382 test::Rustdoc,
383 test::Pretty,
384 test::RunFailPretty,
385 test::RunPassValgrindPretty,
386 test::Crate,
387 test::CrateLibrustc,
388 test::CrateRustdoc,
389 test::Linkcheck,
390 test::Cargotest,
391 test::Cargo,
392 test::Rls,
393 test::ErrorIndex,
394 test::Distcheck,
395 test::RunMakeFullDeps,
396 test::Nomicon,
397 test::Reference,
398 test::RustdocBook,
399 test::RustByExample,
400 test::TheBook,
401 test::UnstableBook,
402 test::RustcBook,
403 test::RustcGuide,
404 test::EmbeddedBook,
405 test::EditionGuide,
406 test::Rustfmt,
407 test::Miri,
408 test::Clippy,
409 test::CompiletestTest,
410 test::RustdocJSStd,
411 test::RustdocJSNotStd,
412 test::RustdocTheme,
413 test::RustdocUi,
414 // Run bootstrap close to the end as it's unlikely to fail
415 test::Bootstrap,
416 // Run run-make last, since these won't pass without make on Windows
417 test::RunMake,
418 ),
419 Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
420 Kind::Doc => describe!(
421 doc::UnstableBook,
422 doc::UnstableBookGen,
423 doc::TheBook,
424 doc::Standalone,
425 doc::Std,
426 doc::Rustc,
427 doc::Rustdoc,
428 doc::ErrorIndex,
429 doc::Nomicon,
430 doc::Reference,
431 doc::RustdocBook,
432 doc::RustByExample,
433 doc::RustcBook,
434 doc::CargoBook,
435 doc::EmbeddedBook,
436 doc::EditionGuide,
437 ),
438 Kind::Dist => describe!(
439 dist::Docs,
440 dist::RustcDocs,
441 dist::Mingw,
442 dist::Rustc,
443 dist::DebuggerScripts,
444 dist::Std,
445 dist::RustcDev,
446 dist::Analysis,
447 dist::Src,
448 dist::PlainSourceTarball,
449 dist::Cargo,
450 dist::Rls,
451 dist::Rustfmt,
452 dist::Clippy,
453 dist::Miri,
454 dist::LlvmTools,
455 dist::Lldb,
456 dist::Extended,
457 dist::HashSign
458 ),
459 Kind::Install => describe!(
460 install::Docs,
461 install::Std,
462 install::Cargo,
463 install::Rls,
464 install::Rustfmt,
465 install::Clippy,
466 install::Miri,
467 install::Analysis,
468 install::Src,
469 install::Rustc
470 ),
471 }
472 }
473
474 pub fn get_help(build: &Build, subcommand: &str) -> Option<String> {
475 let kind = match subcommand {
476 "build" => Kind::Build,
477 "doc" => Kind::Doc,
478 "test" => Kind::Test,
479 "bench" => Kind::Bench,
480 "dist" => Kind::Dist,
481 "install" => Kind::Install,
482 _ => return None,
483 };
484
485 let builder = Builder {
486 build,
487 top_stage: build.config.stage.unwrap_or(2),
488 kind,
489 cache: Cache::new(),
490 stack: RefCell::new(Vec::new()),
491 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
492 paths: vec![],
493 graph_nodes: RefCell::new(HashMap::new()),
494 graph: RefCell::new(Graph::new()),
495 parent: Cell::new(None),
496 };
497
498 let builder = &builder;
499 let mut should_run = ShouldRun::new(builder);
500 for desc in Builder::get_step_descriptions(builder.kind) {
501 should_run = (desc.should_run)(should_run);
502 }
503 let mut help = String::from("Available paths:\n");
504 for pathset in should_run.paths {
505 if let PathSet::Set(set) = pathset {
506 set.iter().for_each(|path| {
507 help.push_str(
508 format!(" ./x.py {} {}\n", subcommand, path.display()).as_str(),
509 )
510 })
511 }
512 }
513 Some(help)
514 }
515
516 pub fn new(build: &Build) -> Builder<'_> {
517 let (kind, paths) = match build.config.cmd {
518 Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
519 Subcommand::Check { ref paths } => (Kind::Check, &paths[..]),
520 Subcommand::Clippy { ref paths } => (Kind::Clippy, &paths[..]),
521 Subcommand::Fix { ref paths } => (Kind::Fix, &paths[..]),
522 Subcommand::Doc { ref paths } => (Kind::Doc, &paths[..]),
523 Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
524 Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
525 Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
526 Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
527 Subcommand::Clean { .. } => panic!(),
528 };
529
530 let builder = Builder {
531 build,
532 top_stage: build.config.stage.unwrap_or(2),
533 kind,
534 cache: Cache::new(),
535 stack: RefCell::new(Vec::new()),
536 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
537 paths: paths.to_owned(),
538 graph_nodes: RefCell::new(HashMap::new()),
539 graph: RefCell::new(Graph::new()),
540 parent: Cell::new(None),
541 };
542
543 builder
544 }
545
546 pub fn execute_cli(&self) -> Graph<String, bool> {
547 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
548 self.graph.borrow().clone()
549 }
550
551 pub fn default_doc(&self, paths: Option<&[PathBuf]>) {
552 let paths = paths.unwrap_or(&[]);
553 self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
554 }
555
556 fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
557 StepDescription::run(v, self, paths);
558 }
559
560 /// Obtain a compiler at a given stage and for a given host. Explicitly does
561 /// not take `Compiler` since all `Compiler` instances are meant to be
562 /// obtained through this function, since it ensures that they are valid
563 /// (i.e., built and assembled).
564 pub fn compiler(&self, stage: u32, host: Interned<String>) -> Compiler {
565 self.ensure(compile::Assemble {
566 target_compiler: Compiler { stage, host },
567 })
568 }
569
570 /// Similar to `compiler`, except handles the full-bootstrap option to
571 /// silently use the stage1 compiler instead of a stage2 compiler if one is
572 /// requested.
573 ///
574 /// Note that this does *not* have the side effect of creating
575 /// `compiler(stage, host)`, unlike `compiler` above which does have such
576 /// a side effect. The returned compiler here can only be used to compile
577 /// new artifacts, it can't be used to rely on the presence of a particular
578 /// sysroot.
579 ///
580 /// See `force_use_stage1` for documentation on what each argument is.
581 pub fn compiler_for(
582 &self,
583 stage: u32,
584 host: Interned<String>,
585 target: Interned<String>,
586 ) -> Compiler {
587 if self.build.force_use_stage1(Compiler { stage, host }, target) {
588 self.compiler(1, self.config.build)
589 } else {
590 self.compiler(stage, host)
591 }
592 }
593
594 pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
595 self.ensure(compile::Sysroot { compiler })
596 }
597
598 /// Returns the libdir where the standard library and other artifacts are
599 /// found for a compiler's sysroot.
600 pub fn sysroot_libdir(
601 &self,
602 compiler: Compiler,
603 target: Interned<String>,
604 ) -> Interned<PathBuf> {
605 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
606 struct Libdir {
607 compiler: Compiler,
608 target: Interned<String>,
609 }
610 impl Step for Libdir {
611 type Output = Interned<PathBuf>;
612
613 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
614 run.never()
615 }
616
617 fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
618 let lib = builder.sysroot_libdir_relative(self.compiler);
619 let sysroot = builder
620 .sysroot(self.compiler)
621 .join(lib)
622 .join("rustlib")
623 .join(self.target)
624 .join("lib");
625 let _ = fs::remove_dir_all(&sysroot);
626 t!(fs::create_dir_all(&sysroot));
627 INTERNER.intern_path(sysroot)
628 }
629 }
630 self.ensure(Libdir { compiler, target })
631 }
632
633 /// Returns the compiler's libdir where it stores the dynamic libraries that
634 /// it itself links against.
635 ///
636 /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
637 /// Windows.
638 pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
639 if compiler.is_snapshot(self) {
640 self.rustc_snapshot_libdir()
641 } else {
642 match self.config.libdir_relative() {
643 Some(relative_libdir) if compiler.stage >= 1
644 => self.sysroot(compiler).join(relative_libdir),
645 _ => self.sysroot(compiler).join(libdir(&compiler.host))
646 }
647 }
648 }
649
650 /// Returns the compiler's relative libdir where it stores the dynamic libraries that
651 /// it itself links against.
652 ///
653 /// For example this returns `lib` on Unix and `bin` on
654 /// Windows.
655 pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
656 if compiler.is_snapshot(self) {
657 libdir(&self.config.build).as_ref()
658 } else {
659 match self.config.libdir_relative() {
660 Some(relative_libdir) if compiler.stage >= 1
661 => relative_libdir,
662 _ => libdir(&compiler.host).as_ref()
663 }
664 }
665 }
666
667 /// Returns the compiler's relative libdir where the standard library and other artifacts are
668 /// found for a compiler's sysroot.
669 ///
670 /// For example this returns `lib` on Unix and Windows.
671 pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
672 match self.config.libdir_relative() {
673 Some(relative_libdir) if compiler.stage >= 1
674 => relative_libdir,
675 _ => Path::new("lib")
676 }
677 }
678
679 /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
680 /// library lookup path.
681 pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Cargo) {
682 // Windows doesn't need dylib path munging because the dlls for the
683 // compiler live next to the compiler and the system will find them
684 // automatically.
685 if cfg!(windows) {
686 return;
687 }
688
689 add_lib_path(vec![self.rustc_libdir(compiler)], &mut cmd.command);
690 }
691
692 /// Gets a path to the compiler specified.
693 pub fn rustc(&self, compiler: Compiler) -> PathBuf {
694 if compiler.is_snapshot(self) {
695 self.initial_rustc.clone()
696 } else {
697 self.sysroot(compiler)
698 .join("bin")
699 .join(exe("rustc", &compiler.host))
700 }
701 }
702
703 pub fn rustdoc(&self, compiler: Compiler) -> PathBuf {
704 self.ensure(tool::Rustdoc { compiler })
705 }
706
707 pub fn rustdoc_cmd(&self, compiler: Compiler) -> Command {
708 let mut cmd = Command::new(&self.out.join("bootstrap/debug/rustdoc"));
709 cmd.env("RUSTC_STAGE", compiler.stage.to_string())
710 .env("RUSTC_SYSROOT", self.sysroot(compiler))
711 // Note that this is *not* the sysroot_libdir because rustdoc must be linked
712 // equivalently to rustc.
713 .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
714 .env("CFG_RELEASE_CHANNEL", &self.config.channel)
715 .env("RUSTDOC_REAL", self.rustdoc(compiler))
716 .env("RUSTDOC_CRATE_VERSION", self.rust_version())
717 .env("RUSTC_BOOTSTRAP", "1");
718
719 // Remove make-related flags that can cause jobserver problems.
720 cmd.env_remove("MAKEFLAGS");
721 cmd.env_remove("MFLAGS");
722
723 if let Some(linker) = self.linker(compiler.host) {
724 cmd.env("RUSTC_TARGET_LINKER", linker);
725 }
726 cmd
727 }
728
729 /// Prepares an invocation of `cargo` to be run.
730 ///
731 /// This will create a `Command` that represents a pending execution of
732 /// Cargo. This cargo will be configured to use `compiler` as the actual
733 /// rustc compiler, its output will be scoped by `mode`'s output directory,
734 /// it will pass the `--target` flag for the specified `target`, and will be
735 /// executing the Cargo command `cmd`.
736 pub fn cargo(
737 &self,
738 compiler: Compiler,
739 mode: Mode,
740 target: Interned<String>,
741 cmd: &str,
742 ) -> Cargo {
743 let mut cargo = Command::new(&self.initial_cargo);
744 let out_dir = self.stage_out(compiler, mode);
745
746 if cmd == "doc" || cmd == "rustdoc" {
747 let my_out = match mode {
748 // This is the intended out directory for compiler documentation.
749 Mode::Rustc | Mode::ToolRustc | Mode::Codegen => self.compiler_doc_out(target),
750 _ => self.crate_doc_out(target),
751 };
752 let rustdoc = self.rustdoc(compiler);
753 self.clear_if_dirty(&my_out, &rustdoc);
754 }
755
756 cargo
757 .env("CARGO_TARGET_DIR", out_dir)
758 .arg(cmd)
759 .arg("-Zconfig-profile");
760
761 let profile_var = |name: &str| {
762 let profile = if self.config.rust_optimize {
763 "RELEASE"
764 } else {
765 "DEV"
766 };
767 format!("CARGO_PROFILE_{}_{}", profile, name)
768 };
769
770 // See comment in librustc_llvm/build.rs for why this is necessary, largely llvm-config
771 // needs to not accidentally link to libLLVM in stage0/lib.
772 cargo.env("REAL_LIBRARY_PATH_VAR", &util::dylib_path_var());
773 if let Some(e) = env::var_os(util::dylib_path_var()) {
774 cargo.env("REAL_LIBRARY_PATH", e);
775 }
776
777 if cmd != "install" {
778 cargo.arg("--target")
779 .arg(target);
780 } else {
781 assert_eq!(target, compiler.host);
782 }
783
784 // Set a flag for `check`/`clippy`/`fix`, so that certain build
785 // scripts can do less work (e.g. not building/requiring LLVM).
786 if cmd == "check" || cmd == "clippy" || cmd == "fix" {
787 cargo.env("RUST_CHECK", "1");
788 }
789
790 let stage;
791 if compiler.stage == 0 && self.local_rebuild {
792 // Assume the local-rebuild rustc already has stage1 features.
793 stage = 1;
794 } else {
795 stage = compiler.stage;
796 }
797
798 let mut rustflags = Rustflags::new(&target);
799 if stage != 0 {
800 if let Ok(s) = env::var("CARGOFLAGS_NOT_BOOTSTRAP") {
801 cargo.args(s.split_whitespace());
802 }
803 rustflags.env("RUSTFLAGS_NOT_BOOTSTRAP");
804 } else {
805 if let Ok(s) = env::var("CARGOFLAGS_BOOTSTRAP") {
806 cargo.args(s.split_whitespace());
807 }
808 rustflags.env("RUSTFLAGS_BOOTSTRAP");
809 rustflags.arg("--cfg=bootstrap");
810 }
811
812 if let Ok(s) = env::var("CARGOFLAGS") {
813 cargo.args(s.split_whitespace());
814 }
815
816 match mode {
817 Mode::Std | Mode::ToolBootstrap | Mode::ToolStd => {},
818 Mode::Rustc | Mode::Codegen | Mode::ToolRustc => {
819 // Build proc macros both for the host and the target
820 if target != compiler.host && cmd != "check" {
821 cargo.arg("-Zdual-proc-macros");
822 rustflags.arg("-Zdual-proc-macros");
823 }
824 },
825 }
826
827 // This tells Cargo (and in turn, rustc) to output more complete
828 // dependency information. Most importantly for rustbuild, this
829 // includes sysroot artifacts, like libstd, which means that we don't
830 // need to track those in rustbuild (an error prone process!). This
831 // feature is currently unstable as there may be some bugs and such, but
832 // it represents a big improvement in rustbuild's reliability on
833 // rebuilds, so we're using it here.
834 //
835 // For some additional context, see #63470 (the PR originally adding
836 // this), as well as #63012 which is the tracking issue for this
837 // feature on the rustc side.
838 cargo.arg("-Zbinary-dep-depinfo");
839
840 cargo.arg("-j").arg(self.jobs().to_string());
841 // Remove make-related flags to ensure Cargo can correctly set things up
842 cargo.env_remove("MAKEFLAGS");
843 cargo.env_remove("MFLAGS");
844
845 // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
846 // Force cargo to output binaries with disambiguating hashes in the name
847 let mut metadata = if compiler.stage == 0 {
848 // Treat stage0 like a special channel, whether it's a normal prior-
849 // release rustc or a local rebuild with the same version, so we
850 // never mix these libraries by accident.
851 "bootstrap".to_string()
852 } else {
853 self.config.channel.to_string()
854 };
855 // We want to make sure that none of the dependencies between
856 // std/test/rustc unify with one another. This is done for weird linkage
857 // reasons but the gist of the problem is that if librustc, libtest, and
858 // libstd all depend on libc from crates.io (which they actually do) we
859 // want to make sure they all get distinct versions. Things get really
860 // weird if we try to unify all these dependencies right now, namely
861 // around how many times the library is linked in dynamic libraries and
862 // such. If rustc were a static executable or if we didn't ship dylibs
863 // this wouldn't be a problem, but we do, so it is. This is in general
864 // just here to make sure things build right. If you can remove this and
865 // things still build right, please do!
866 match mode {
867 Mode::Std => metadata.push_str("std"),
868 // When we're building rustc tools, they're built with a search path
869 // that contains things built during the rustc build. For example,
870 // bitflags is built during the rustc build, and is a dependency of
871 // rustdoc as well. We're building rustdoc in a different target
872 // directory, though, which means that Cargo will rebuild the
873 // dependency. When we go on to build rustdoc, we'll look for
874 // bitflags, and find two different copies: one built during the
875 // rustc step and one that we just built. This isn't always a
876 // problem, somehow -- not really clear why -- but we know that this
877 // fixes things.
878 Mode::ToolRustc => metadata.push_str("tool-rustc"),
879 _ => {}
880 }
881 cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
882
883 if cmd == "clippy" {
884 rustflags.arg("-Zforce-unstable-if-unmarked");
885 }
886
887 rustflags.arg("-Zexternal-macro-backtrace");
888
889 let want_rustdoc = self.doc_tests != DocTests::No;
890
891 // We synthetically interpret a stage0 compiler used to build tools as a
892 // "raw" compiler in that it's the exact snapshot we download. Normally
893 // the stage0 build means it uses libraries build by the stage0
894 // compiler, but for tools we just use the precompiled libraries that
895 // we've downloaded
896 let use_snapshot = mode == Mode::ToolBootstrap;
897 assert!(!use_snapshot || stage == 0 || self.local_rebuild);
898
899 let maybe_sysroot = self.sysroot(compiler);
900 let sysroot = if use_snapshot {
901 self.rustc_snapshot_sysroot()
902 } else {
903 &maybe_sysroot
904 };
905 let libdir = self.rustc_libdir(compiler);
906
907 // Customize the compiler we're running. Specify the compiler to cargo
908 // as our shim and then pass it some various options used to configure
909 // how the actual compiler itself is called.
910 //
911 // These variables are primarily all read by
912 // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
913 cargo
914 .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
915 .env("RUSTC", self.out.join("bootstrap/debug/rustc"))
916 .env("RUSTC_REAL", self.rustc(compiler))
917 .env("RUSTC_STAGE", stage.to_string())
918 .env(
919 "RUSTC_DEBUG_ASSERTIONS",
920 self.config.rust_debug_assertions.to_string(),
921 )
922 .env("RUSTC_SYSROOT", &sysroot)
923 .env("RUSTC_LIBDIR", &libdir)
924 .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
925 .env(
926 "RUSTDOC_REAL",
927 if cmd == "doc" || cmd == "rustdoc" || (cmd == "test" && want_rustdoc) {
928 self.rustdoc(compiler)
929 } else {
930 PathBuf::from("/path/to/nowhere/rustdoc/not/required")
931 },
932 )
933 .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir())
934 .env("RUSTC_BREAK_ON_ICE", "1");
935
936 // Dealing with rpath here is a little special, so let's go into some
937 // detail. First off, `-rpath` is a linker option on Unix platforms
938 // which adds to the runtime dynamic loader path when looking for
939 // dynamic libraries. We use this by default on Unix platforms to ensure
940 // that our nightlies behave the same on Windows, that is they work out
941 // of the box. This can be disabled, of course, but basically that's why
942 // we're gated on RUSTC_RPATH here.
943 //
944 // Ok, so the astute might be wondering "why isn't `-C rpath` used
945 // here?" and that is indeed a good question to task. This codegen
946 // option is the compiler's current interface to generating an rpath.
947 // Unfortunately it doesn't quite suffice for us. The flag currently
948 // takes no value as an argument, so the compiler calculates what it
949 // should pass to the linker as `-rpath`. This unfortunately is based on
950 // the **compile time** directory structure which when building with
951 // Cargo will be very different than the runtime directory structure.
952 //
953 // All that's a really long winded way of saying that if we use
954 // `-Crpath` then the executables generated have the wrong rpath of
955 // something like `$ORIGIN/deps` when in fact the way we distribute
956 // rustc requires the rpath to be `$ORIGIN/../lib`.
957 //
958 // So, all in all, to set up the correct rpath we pass the linker
959 // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
960 // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
961 // to change a flag in a binary?
962 if self.config.rust_rpath && util::use_host_linker(&target) {
963 let rpath = if target.contains("apple") {
964
965 // Note that we need to take one extra step on macOS to also pass
966 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
967 // do that we pass a weird flag to the compiler to get it to do
968 // so. Note that this is definitely a hack, and we should likely
969 // flesh out rpath support more fully in the future.
970 rustflags.arg("-Zosx-rpath-install-name");
971 Some("-Wl,-rpath,@loader_path/../lib")
972 } else if !target.contains("windows") {
973 Some("-Wl,-rpath,$ORIGIN/../lib")
974 } else {
975 None
976 };
977 if let Some(rpath) = rpath {
978 rustflags.arg(&format!("-Clink-args={}", rpath));
979 }
980 }
981
982 if let Some(host_linker) = self.linker(compiler.host) {
983 cargo.env("RUSTC_HOST_LINKER", host_linker);
984 }
985 if let Some(target_linker) = self.linker(target) {
986 let target = crate::envify(&target);
987 cargo.env(&format!("CARGO_TARGET_{}_LINKER", target), target_linker);
988 }
989 if !(["build", "check", "clippy", "fix", "rustc"].contains(&cmd)) && want_rustdoc {
990 cargo.env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler));
991 }
992
993 let debuginfo_level = match mode {
994 Mode::Rustc | Mode::Codegen => self.config.rust_debuginfo_level_rustc,
995 Mode::Std => self.config.rust_debuginfo_level_std,
996 Mode::ToolBootstrap | Mode::ToolStd |
997 Mode::ToolRustc => self.config.rust_debuginfo_level_tools,
998 };
999 cargo.env(profile_var("DEBUG"), debuginfo_level.to_string());
1000
1001 if !mode.is_tool() {
1002 cargo.env("RUSTC_FORCE_UNSTABLE", "1");
1003 }
1004
1005 if let Some(x) = self.crt_static(target) {
1006 if x {
1007 rustflags.arg("-Ctarget-feature=+crt-static");
1008 } else {
1009 rustflags.arg("-Ctarget-feature=-crt-static");
1010 }
1011 }
1012
1013 if let Some(x) = self.crt_static(compiler.host) {
1014 cargo.env("RUSTC_HOST_CRT_STATIC", x.to_string());
1015 }
1016
1017 if let Some(map) = self.build.debuginfo_map(GitRepo::Rustc) {
1018 cargo.env("RUSTC_DEBUGINFO_MAP", map);
1019 }
1020
1021 // Enable usage of unstable features
1022 cargo.env("RUSTC_BOOTSTRAP", "1");
1023 self.add_rust_test_threads(&mut cargo);
1024
1025 // Almost all of the crates that we compile as part of the bootstrap may
1026 // have a build script, including the standard library. To compile a
1027 // build script, however, it itself needs a standard library! This
1028 // introduces a bit of a pickle when we're compiling the standard
1029 // library itself.
1030 //
1031 // To work around this we actually end up using the snapshot compiler
1032 // (stage0) for compiling build scripts of the standard library itself.
1033 // The stage0 compiler is guaranteed to have a libstd available for use.
1034 //
1035 // For other crates, however, we know that we've already got a standard
1036 // library up and running, so we can use the normal compiler to compile
1037 // build scripts in that situation.
1038 if mode == Mode::Std {
1039 cargo
1040 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
1041 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
1042 } else {
1043 cargo
1044 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
1045 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
1046 }
1047
1048 if self.config.incremental {
1049 cargo.env("CARGO_INCREMENTAL", "1");
1050 } else {
1051 // Don't rely on any default setting for incr. comp. in Cargo
1052 cargo.env("CARGO_INCREMENTAL", "0");
1053 }
1054
1055 if let Some(ref on_fail) = self.config.on_fail {
1056 cargo.env("RUSTC_ON_FAIL", on_fail);
1057 }
1058
1059 if self.config.print_step_timings {
1060 cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
1061 }
1062
1063 if self.config.backtrace_on_ice {
1064 cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
1065 }
1066
1067 cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
1068
1069 if !mode.is_tool() {
1070 // When extending this list, add the new lints to the RUSTFLAGS of the
1071 // build_bootstrap function of src/bootstrap/bootstrap.py as well as
1072 // some code doesn't go through this `rustc` wrapper.
1073 rustflags.arg("-Wrust_2018_idioms");
1074 rustflags.arg("-Wunused_lifetimes");
1075
1076 if self.config.deny_warnings {
1077 rustflags.arg("-Dwarnings");
1078 }
1079 }
1080
1081 if let Mode::Rustc | Mode::Codegen = mode {
1082 rustflags.arg("-Zunstable-options");
1083 rustflags.arg("-Wrustc::internal");
1084 }
1085
1086 // Throughout the build Cargo can execute a number of build scripts
1087 // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
1088 // obtained previously to those build scripts.
1089 // Build scripts use either the `cc` crate or `configure/make` so we pass
1090 // the options through environment variables that are fetched and understood by both.
1091 //
1092 // FIXME: the guard against msvc shouldn't need to be here
1093 if target.contains("msvc") {
1094 if let Some(ref cl) = self.config.llvm_clang_cl {
1095 cargo.env("CC", cl).env("CXX", cl);
1096 }
1097 } else {
1098 let ccache = self.config.ccache.as_ref();
1099 let ccacheify = |s: &Path| {
1100 let ccache = match ccache {
1101 Some(ref s) => s,
1102 None => return s.display().to_string(),
1103 };
1104 // FIXME: the cc-rs crate only recognizes the literal strings
1105 // `ccache` and `sccache` when doing caching compilations, so we
1106 // mirror that here. It should probably be fixed upstream to
1107 // accept a new env var or otherwise work with custom ccache
1108 // vars.
1109 match &ccache[..] {
1110 "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
1111 _ => s.display().to_string(),
1112 }
1113 };
1114 let cc = ccacheify(&self.cc(target));
1115 cargo.env(format!("CC_{}", target), &cc);
1116
1117 let cflags = self.cflags(target, GitRepo::Rustc).join(" ");
1118 cargo
1119 .env(format!("CFLAGS_{}", target), cflags.clone());
1120
1121 if let Some(ar) = self.ar(target) {
1122 let ranlib = format!("{} s", ar.display());
1123 cargo
1124 .env(format!("AR_{}", target), ar)
1125 .env(format!("RANLIB_{}", target), ranlib);
1126 }
1127
1128 if let Ok(cxx) = self.cxx(target) {
1129 let cxx = ccacheify(&cxx);
1130 cargo
1131 .env(format!("CXX_{}", target), &cxx)
1132 .env(format!("CXXFLAGS_{}", target), cflags);
1133 }
1134 }
1135
1136 if mode == Mode::Std
1137 && self.config.extended
1138 && compiler.is_final_stage(self)
1139 {
1140 rustflags.arg("-Zsave-analysis");
1141 cargo.env("RUST_SAVE_ANALYSIS_CONFIG",
1142 "{\"output_file\": null,\"full_docs\": false,\
1143 \"pub_only\": true,\"reachable_only\": false,\
1144 \"distro_crate\": true,\"signatures\": false,\"borrow_data\": false}");
1145 }
1146
1147 // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1148 cargo.env("RUSTDOC_CRATE_VERSION", self.rust_version());
1149
1150 // Environment variables *required* throughout the build
1151 //
1152 // FIXME: should update code to not require this env var
1153 cargo.env("CFG_COMPILER_HOST_TRIPLE", target);
1154
1155 // Set this for all builds to make sure doc builds also get it.
1156 cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1157
1158 // This one's a bit tricky. As of the time of this writing the compiler
1159 // links to the `winapi` crate on crates.io. This crate provides raw
1160 // bindings to Windows system functions, sort of like libc does for
1161 // Unix. This crate also, however, provides "import libraries" for the
1162 // MinGW targets. There's an import library per dll in the windows
1163 // distribution which is what's linked to. These custom import libraries
1164 // are used because the winapi crate can reference Windows functions not
1165 // present in the MinGW import libraries.
1166 //
1167 // For example MinGW may ship libdbghelp.a, but it may not have
1168 // references to all the functions in the dbghelp dll. Instead the
1169 // custom import library for dbghelp in the winapi crates has all this
1170 // information.
1171 //
1172 // Unfortunately for us though the import libraries are linked by
1173 // default via `-ldylib=winapi_foo`. That is, they're linked with the
1174 // `dylib` type with a `winapi_` prefix (so the winapi ones don't
1175 // conflict with the system MinGW ones). This consequently means that
1176 // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
1177 // DLL) when linked against *again*, for example with procedural macros
1178 // or plugins, will trigger the propagation logic of `-ldylib`, passing
1179 // `-lwinapi_foo` to the linker again. This isn't actually available in
1180 // our distribution, however, so the link fails.
1181 //
1182 // To solve this problem we tell winapi to not use its bundled import
1183 // libraries. This means that it will link to the system MinGW import
1184 // libraries by default, and the `-ldylib=foo` directives will still get
1185 // passed to the final linker, but they'll look like `-lfoo` which can
1186 // be resolved because MinGW has the import library. The downside is we
1187 // don't get newer functions from Windows, but we don't use any of them
1188 // anyway.
1189 if !mode.is_tool() {
1190 cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1191 }
1192
1193 for _ in 1..self.verbosity {
1194 cargo.arg("-v");
1195 }
1196
1197 match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {
1198 (Mode::Std, Some(n), _) |
1199 (_, _, Some(n)) => {
1200 cargo.env(profile_var("CODEGEN_UNITS"), n.to_string());
1201 }
1202 _ => {
1203 // Don't set anything
1204 }
1205 }
1206
1207 if self.config.rust_optimize {
1208 // FIXME: cargo bench/install do not accept `--release`
1209 if cmd != "bench" && cmd != "install" {
1210 cargo.arg("--release");
1211 }
1212 }
1213
1214 if self.config.locked_deps {
1215 cargo.arg("--locked");
1216 }
1217 if self.config.vendor || self.is_sudo {
1218 cargo.arg("--frozen");
1219 }
1220
1221 // Try to use a sysroot-relative bindir, in case it was configured absolutely.
1222 cargo.env("RUSTC_INSTALL_BINDIR", self.config.bindir_relative());
1223
1224 self.ci_env.force_coloring_in_ci(&mut cargo);
1225
1226 // When we build Rust dylibs they're all intended for intermediate
1227 // usage, so make sure we pass the -Cprefer-dynamic flag instead of
1228 // linking all deps statically into the dylib.
1229 if let Mode::Std | Mode::Rustc | Mode::Codegen = mode {
1230 rustflags.arg("-Cprefer-dynamic");
1231 }
1232
1233 Cargo {
1234 command: cargo,
1235 rustflags,
1236 }
1237 }
1238
1239 /// Ensure that a given step is built, returning its output. This will
1240 /// cache the step, so it is safe (and good!) to call this as often as
1241 /// needed to ensure that all dependencies are built.
1242 pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1243 {
1244 let mut stack = self.stack.borrow_mut();
1245 for stack_step in stack.iter() {
1246 // should skip
1247 if stack_step
1248 .downcast_ref::<S>()
1249 .map_or(true, |stack_step| *stack_step != step)
1250 {
1251 continue;
1252 }
1253 let mut out = String::new();
1254 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
1255 for el in stack.iter().rev() {
1256 out += &format!("\t{:?}\n", el);
1257 }
1258 panic!(out);
1259 }
1260 if let Some(out) = self.cache.get(&step) {
1261 self.verbose(&format!("{}c {:?}", " ".repeat(stack.len()), step));
1262
1263 {
1264 let mut graph = self.graph.borrow_mut();
1265 let parent = self.parent.get();
1266 let us = *self
1267 .graph_nodes
1268 .borrow_mut()
1269 .entry(format!("{:?}", step))
1270 .or_insert_with(|| graph.add_node(format!("{:?}", step)));
1271 if let Some(parent) = parent {
1272 graph.add_edge(parent, us, false);
1273 }
1274 }
1275
1276 return out;
1277 }
1278 self.verbose(&format!("{}> {:?}", " ".repeat(stack.len()), step));
1279 stack.push(Box::new(step.clone()));
1280 }
1281
1282 let prev_parent = self.parent.get();
1283
1284 {
1285 let mut graph = self.graph.borrow_mut();
1286 let parent = self.parent.get();
1287 let us = *self
1288 .graph_nodes
1289 .borrow_mut()
1290 .entry(format!("{:?}", step))
1291 .or_insert_with(|| graph.add_node(format!("{:?}", step)));
1292 self.parent.set(Some(us));
1293 if let Some(parent) = parent {
1294 graph.add_edge(parent, us, true);
1295 }
1296 }
1297
1298 let (out, dur) = {
1299 let start = Instant::now();
1300 let zero = Duration::new(0, 0);
1301 let parent = self.time_spent_on_dependencies.replace(zero);
1302 let out = step.clone().run(self);
1303 let dur = start.elapsed();
1304 let deps = self.time_spent_on_dependencies.replace(parent + dur);
1305 (out, dur - deps)
1306 };
1307
1308 self.parent.set(prev_parent);
1309
1310 if self.config.print_step_timings && dur > Duration::from_millis(100) {
1311 println!(
1312 "[TIMING] {:?} -- {}.{:03}",
1313 step,
1314 dur.as_secs(),
1315 dur.subsec_nanos() / 1_000_000
1316 );
1317 }
1318
1319 {
1320 let mut stack = self.stack.borrow_mut();
1321 let cur_step = stack.pop().expect("step stack empty");
1322 assert_eq!(cur_step.downcast_ref(), Some(&step));
1323 }
1324 self.verbose(&format!(
1325 "{}< {:?}",
1326 " ".repeat(self.stack.borrow().len()),
1327 step
1328 ));
1329 self.cache.put(step, out.clone());
1330 out
1331 }
1332 }
1333
1334 #[cfg(test)]
1335 mod tests;
1336
1337 #[derive(Debug)]
1338 struct Rustflags(String);
1339
1340 impl Rustflags {
1341 fn new(target: &str) -> Rustflags {
1342 let mut ret = Rustflags(String::new());
1343
1344 // Inherit `RUSTFLAGS` by default ...
1345 ret.env("RUSTFLAGS");
1346
1347 // ... and also handle target-specific env RUSTFLAGS if they're
1348 // configured.
1349 let target_specific = format!("CARGO_TARGET_{}_RUSTFLAGS", crate::envify(target));
1350 ret.env(&target_specific);
1351
1352 ret
1353 }
1354
1355 fn env(&mut self, env: &str) {
1356 if let Ok(s) = env::var(env) {
1357 for part in s.split_whitespace() {
1358 self.arg(part);
1359 }
1360 }
1361 }
1362
1363 fn arg(&mut self, arg: &str) -> &mut Self {
1364 assert_eq!(arg.split_whitespace().count(), 1);
1365 if self.0.len() > 0 {
1366 self.0.push_str(" ");
1367 }
1368 self.0.push_str(arg);
1369 self
1370 }
1371 }
1372
1373 #[derive(Debug)]
1374 pub struct Cargo {
1375 command: Command,
1376 rustflags: Rustflags,
1377 }
1378
1379 impl Cargo {
1380 pub fn rustflag(&mut self, arg: &str) -> &mut Cargo {
1381 self.rustflags.arg(arg);
1382 self
1383 }
1384
1385 pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Cargo {
1386 self.command.arg(arg.as_ref());
1387 self
1388 }
1389
1390 pub fn args<I, S>(&mut self, args: I) -> &mut Cargo
1391 where I: IntoIterator<Item=S>, S: AsRef<OsStr>
1392 {
1393 for arg in args {
1394 self.arg(arg.as_ref());
1395 }
1396 self
1397 }
1398
1399 pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Cargo {
1400 self.command.env(key.as_ref(), value.as_ref());
1401 self
1402 }
1403 }
1404
1405 impl From<Cargo> for Command {
1406 fn from(mut cargo: Cargo) -> Command {
1407 cargo.command.env("RUSTFLAGS", &cargo.rustflags.0);
1408 cargo.command
1409 }
1410 }