2 use std::cell::{Cell, RefCell};
3 use std::collections::BTreeSet;
10 use std::path::{Path, PathBuf};
11 use std::process::Command;
12 use std::time::{Duration, Instant};
14 use build_helper::{output, t};
16 use crate::cache::{Cache, Interned, INTERNER};
19 use crate::config::TargetSelection;
22 use crate::flags::{Color, Subcommand};
27 use crate::tool::{self, SourceType};
28 use crate::util::{self, add_dylib_path, add_link_lib_path, exe, libdir};
29 use crate::{Build, DocTests, GitRepo, Mode};
31 pub use crate::Compiler;
33 pub struct Builder<'a> {
38 stack: RefCell<Vec<Box<dyn Any>>>,
39 time_spent_on_dependencies: Cell<Duration>,
40 pub paths: Vec<PathBuf>,
43 impl<'a> Deref for Builder<'a> {
46 fn deref(&self) -> &Self::Target {
51 pub trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
52 /// `PathBuf` when directories are created or to return a `Compiler` once
53 /// it's been assembled.
56 /// Whether this step is run by default as part of its respective phase.
57 /// `true` here can still be overwritten by `should_run` calling `default_condition`.
58 const DEFAULT: bool = false;
60 /// If true, then this rule should be skipped if --target was specified, but --host was not
61 const ONLY_HOSTS: bool = false;
63 /// Primary function to execute this rule. Can call `builder.ensure()`
64 /// with other steps to run those.
65 fn run(self, builder: &Builder<'_>) -> Self::Output;
67 /// When bootstrap is passed a set of paths, this controls whether this rule
68 /// will execute. However, it does not get called in a "default" context
69 /// when we are not passed any paths; in that case, `make_run` is called
71 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_>;
73 /// Builds up a "root" rule, either as a default rule or from a path passed
76 /// When path is `None`, we are executing in a context where no paths were
77 /// passed. When `./x.py build` is run, for example, this rule could get
78 /// called if it is in the correct list below with a path of `None`.
79 fn make_run(_run: RunConfig<'_>) {
80 // It is reasonable to not have an implementation of make_run for rules
81 // who do not want to get called from the root context. This means that
82 // they are likely dependencies (e.g., sysroot creation) or similar, and
83 // as such calling them from ./x.py isn't logical.
88 pub struct RunConfig<'a> {
89 pub builder: &'a Builder<'a>,
90 pub target: TargetSelection,
95 pub fn build_triple(&self) -> TargetSelection {
96 self.builder.build.build
100 struct StepDescription {
103 should_run: fn(ShouldRun<'_>) -> ShouldRun<'_>,
104 make_run: fn(RunConfig<'_>),
108 /// Collection of paths used to match a task rule.
109 #[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq)]
111 /// A collection of individual paths.
113 /// These are generally matched as a path suffix. For example, a
114 /// command-line value of `libstd` will match if `src/libstd` is in the
116 Set(BTreeSet<PathBuf>),
117 /// A "suite" of paths.
119 /// These can match as a path suffix (like `Set`), or as a prefix. For
120 /// example, a command-line value of `src/test/ui/abi/variadic-ffi.rs`
121 /// will match `src/test/ui`. A command-line value of `ui` would also
122 /// match `src/test/ui`.
127 fn empty() -> PathSet {
128 PathSet::Set(BTreeSet::new())
131 fn one<P: Into<PathBuf>>(path: P) -> PathSet {
132 let mut set = BTreeSet::new();
133 set.insert(path.into());
137 fn has(&self, needle: &Path) -> bool {
139 PathSet::Set(set) => set.iter().any(|p| p.ends_with(needle)),
140 PathSet::Suite(suite) => suite.ends_with(needle),
144 fn path(&self, builder: &Builder<'_>) -> PathBuf {
146 PathSet::Set(set) => set.iter().next().unwrap_or(&builder.build.src).to_path_buf(),
147 PathSet::Suite(path) => PathBuf::from(path),
152 impl StepDescription {
153 fn from<S: Step>() -> StepDescription {
156 only_hosts: S::ONLY_HOSTS,
157 should_run: S::should_run,
158 make_run: S::make_run,
159 name: std::any::type_name::<S>(),
163 fn maybe_run(&self, builder: &Builder<'_>, pathset: &PathSet) {
164 if builder.config.exclude.iter().any(|e| pathset.has(e)) {
165 eprintln!("Skipping {:?} because it is excluded", pathset);
167 } else if !builder.config.exclude.is_empty() {
169 "{:?} not skipped for {:?} -- not in {:?}",
170 pathset, self.name, builder.config.exclude
174 // Determine the targets participating in this rule.
175 let targets = if self.only_hosts { &builder.hosts } else { &builder.targets };
177 for target in targets {
178 let run = RunConfig { builder, path: pathset.path(builder), target: *target };
179 (self.make_run)(run);
183 fn run(v: &[StepDescription], builder: &Builder<'_>, paths: &[PathBuf]) {
185 v.iter().map(|desc| (desc.should_run)(ShouldRun::new(builder))).collect::<Vec<_>>();
187 // sanity checks on rules
188 for (desc, should_run) in v.iter().zip(&should_runs) {
190 !should_run.paths.is_empty(),
191 "{:?} should have at least one pathset",
196 if paths.is_empty() || builder.config.include_default_paths {
197 for (desc, should_run) in v.iter().zip(&should_runs) {
198 if desc.default && should_run.is_really_default {
199 for pathset in &should_run.paths {
200 desc.maybe_run(builder, pathset);
207 // strip CurDir prefix if present
208 let path = match path.strip_prefix(".") {
213 let mut attempted_run = false;
214 for (desc, should_run) in v.iter().zip(&should_runs) {
215 if let Some(suite) = should_run.is_suite_path(path) {
216 attempted_run = true;
217 desc.maybe_run(builder, suite);
218 } else if let Some(pathset) = should_run.pathset_for_path(path) {
219 attempted_run = true;
220 desc.maybe_run(builder, pathset);
225 panic!("error: no rules matched {}", path.display());
232 pub struct ShouldRun<'a> {
233 pub builder: &'a Builder<'a>,
234 // use a BTreeSet to maintain sort order
235 paths: BTreeSet<PathSet>,
237 // If this is a default rule, this is an additional constraint placed on
238 // its run. Generally something like compiler docs being enabled.
239 is_really_default: bool,
242 impl<'a> ShouldRun<'a> {
243 fn new(builder: &'a Builder<'_>) -> ShouldRun<'a> {
246 paths: BTreeSet::new(),
247 is_really_default: true, // by default no additional conditions
251 pub fn default_condition(mut self, cond: bool) -> Self {
252 self.is_really_default = cond;
256 /// Indicates it should run if the command-line selects the given crate or
257 /// any of its (local) dependencies.
259 /// Compared to `krate`, this treats the dependencies as aliases for the
260 /// same job. Generally it is preferred to use `krate`, and treat each
261 /// individual path separately. For example `./x.py test src/liballoc`
262 /// (which uses `krate`) will test just `liballoc`. However, `./x.py check
263 /// src/liballoc` (which uses `all_krates`) will check all of `libtest`.
264 /// `all_krates` should probably be removed at some point.
265 pub fn all_krates(mut self, name: &str) -> Self {
266 let mut set = BTreeSet::new();
267 for krate in self.builder.in_tree_crates(name, None) {
268 let path = krate.local_path(self.builder);
271 self.paths.insert(PathSet::Set(set));
275 /// Indicates it should run if the command-line selects the given crate or
276 /// any of its (local) dependencies.
278 /// `make_run` will be called separately for each matching command-line path.
279 pub fn krate(mut self, name: &str) -> Self {
280 for krate in self.builder.in_tree_crates(name, None) {
281 let path = krate.local_path(self.builder);
282 self.paths.insert(PathSet::one(path));
287 // single, non-aliased path
288 pub fn path(self, path: &str) -> Self {
292 // multiple aliases for the same job
293 pub fn paths(mut self, paths: &[&str]) -> Self {
294 self.paths.insert(PathSet::Set(paths.iter().map(PathBuf::from).collect()));
298 pub fn is_suite_path(&self, path: &Path) -> Option<&PathSet> {
299 self.paths.iter().find(|pathset| match pathset {
300 PathSet::Suite(p) => path.starts_with(p),
301 PathSet::Set(_) => false,
305 pub fn suite_path(mut self, suite: &str) -> Self {
306 self.paths.insert(PathSet::Suite(PathBuf::from(suite)));
310 // allows being more explicit about why should_run in Step returns the value passed to it
311 pub fn never(mut self) -> ShouldRun<'a> {
312 self.paths.insert(PathSet::empty());
316 fn pathset_for_path(&self, path: &Path) -> Option<&PathSet> {
317 self.paths.iter().find(|pathset| pathset.has(path))
321 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
336 impl<'a> Builder<'a> {
337 fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
338 macro_rules! describe {
339 ($($rule:ty),+ $(,)?) => {{
340 vec![$(StepDescription::from::<$rule>()),+]
344 Kind::Build => describe!(
347 compile::CodegenBackend,
348 compile::StartupObjects,
352 tool::UnstableBookGen,
357 tool::RemoteTestServer,
358 tool::RemoteTestClient,
374 Kind::Check | Kind::Clippy { .. } | Kind::Fix | Kind::Format => describe!(
378 check::CodegenBackend,
382 Kind::Test => describe!(
383 crate::toolstate::ToolStateCheck,
384 test::ExpandYamlAnchors,
387 test::RunPassValgrind,
407 test::RunMakeFullDeps,
422 test::CompiletestTest,
424 test::RustdocJSNotStd,
428 // Run bootstrap close to the end as it's unlikely to fail
430 // Run run-make last, since these won't pass without make on Windows
433 Kind::Bench => describe!(test::Crate, test::CrateLibrustc),
434 Kind::Doc => describe!(
436 doc::UnstableBookGen,
452 Kind::Dist => describe!(
457 dist::DebuggerScripts,
462 dist::PlainSourceTarball,
473 dist::ReproducibleArtifacts,
475 Kind::Install => describe!(
480 install::RustAnalyzer,
488 Kind::Run => describe!(run::ExpandYamlAnchors, run::BuildManifest),
492 pub fn get_help(build: &Build, subcommand: &str) -> Option<String> {
493 let kind = match subcommand {
494 "build" => Kind::Build,
496 "test" => Kind::Test,
497 "bench" => Kind::Bench,
498 "dist" => Kind::Dist,
499 "install" => Kind::Install,
503 let builder = Self::new_internal(build, kind, vec![]);
504 let builder = &builder;
505 let mut should_run = ShouldRun::new(builder);
506 for desc in Builder::get_step_descriptions(builder.kind) {
507 should_run = (desc.should_run)(should_run);
509 let mut help = String::from("Available paths:\n");
510 let mut add_path = |path: &Path| {
511 help.push_str(&format!(" ./x.py {} {}\n", subcommand, path.display()));
513 for pathset in should_run.paths {
515 PathSet::Set(set) => {
520 PathSet::Suite(path) => {
521 add_path(&path.join("..."));
528 fn new_internal(build: &Build, kind: Kind, paths: Vec<PathBuf>) -> Builder<'_> {
531 top_stage: build.config.stage,
534 stack: RefCell::new(Vec::new()),
535 time_spent_on_dependencies: Cell::new(Duration::new(0, 0)),
540 pub fn new(build: &Build) -> Builder<'_> {
541 let (kind, paths) = match build.config.cmd {
542 Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
543 Subcommand::Check { ref paths, all_targets: _ } => (Kind::Check, &paths[..]),
544 Subcommand::Clippy { ref paths, .. } => (Kind::Clippy, &paths[..]),
545 Subcommand::Fix { ref paths } => (Kind::Fix, &paths[..]),
546 Subcommand::Doc { ref paths, .. } => (Kind::Doc, &paths[..]),
547 Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
548 Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
549 Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
550 Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
551 Subcommand::Run { ref paths } => (Kind::Run, &paths[..]),
552 Subcommand::Format { .. } | Subcommand::Clean { .. } | Subcommand::Setup { .. } => {
557 Self::new_internal(build, kind, paths.to_owned())
560 pub fn execute_cli(&self) {
561 self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths);
564 pub fn default_doc(&self, paths: Option<&[PathBuf]>) {
565 let paths = paths.unwrap_or(&[]);
566 self.run_step_descriptions(&Builder::get_step_descriptions(Kind::Doc), paths);
569 fn run_step_descriptions(&self, v: &[StepDescription], paths: &[PathBuf]) {
570 StepDescription::run(v, self, paths);
573 /// Obtain a compiler at a given stage and for a given host. Explicitly does
574 /// not take `Compiler` since all `Compiler` instances are meant to be
575 /// obtained through this function, since it ensures that they are valid
576 /// (i.e., built and assembled).
577 pub fn compiler(&self, stage: u32, host: TargetSelection) -> Compiler {
578 self.ensure(compile::Assemble { target_compiler: Compiler { stage, host } })
581 /// Similar to `compiler`, except handles the full-bootstrap option to
582 /// silently use the stage1 compiler instead of a stage2 compiler if one is
585 /// Note that this does *not* have the side effect of creating
586 /// `compiler(stage, host)`, unlike `compiler` above which does have such
587 /// a side effect. The returned compiler here can only be used to compile
588 /// new artifacts, it can't be used to rely on the presence of a particular
591 /// See `force_use_stage1` for documentation on what each argument is.
595 host: TargetSelection,
596 target: TargetSelection,
598 if self.build.force_use_stage1(Compiler { stage, host }, target) {
599 self.compiler(1, self.config.build)
601 self.compiler(stage, host)
605 pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
606 self.ensure(compile::Sysroot { compiler })
609 /// Returns the libdir where the standard library and other artifacts are
610 /// found for a compiler's sysroot.
611 pub fn sysroot_libdir(&self, compiler: Compiler, target: TargetSelection) -> Interned<PathBuf> {
612 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
615 target: TargetSelection,
617 impl Step for Libdir {
618 type Output = Interned<PathBuf>;
620 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
624 fn run(self, builder: &Builder<'_>) -> Interned<PathBuf> {
625 let lib = builder.sysroot_libdir_relative(self.compiler);
626 let sysroot = builder
627 .sysroot(self.compiler)
630 .join(self.target.triple)
632 let _ = fs::remove_dir_all(&sysroot);
633 t!(fs::create_dir_all(&sysroot));
634 INTERNER.intern_path(sysroot)
637 self.ensure(Libdir { compiler, target })
640 pub fn sysroot_codegen_backends(&self, compiler: Compiler) -> PathBuf {
641 self.sysroot_libdir(compiler, compiler.host).with_file_name("codegen-backends")
644 /// Returns the compiler's libdir where it stores the dynamic libraries that
645 /// it itself links against.
647 /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
649 pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
650 if compiler.is_snapshot(self) {
651 self.rustc_snapshot_libdir()
653 match self.config.libdir_relative() {
654 Some(relative_libdir) if compiler.stage >= 1 => {
655 self.sysroot(compiler).join(relative_libdir)
657 _ => self.sysroot(compiler).join(libdir(compiler.host)),
662 /// Returns the compiler's relative libdir where it stores the dynamic libraries that
663 /// it itself links against.
665 /// For example this returns `lib` on Unix and `bin` on
667 pub fn libdir_relative(&self, compiler: Compiler) -> &Path {
668 if compiler.is_snapshot(self) {
669 libdir(self.config.build).as_ref()
671 match self.config.libdir_relative() {
672 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
673 _ => libdir(compiler.host).as_ref(),
678 /// Returns the compiler's relative libdir where the standard library and other artifacts are
679 /// found for a compiler's sysroot.
681 /// For example this returns `lib` on Unix and Windows.
682 pub fn sysroot_libdir_relative(&self, compiler: Compiler) -> &Path {
683 match self.config.libdir_relative() {
684 Some(relative_libdir) if compiler.stage >= 1 => relative_libdir,
685 _ if compiler.stage == 0 => &self.build.initial_libdir,
686 _ => Path::new("lib"),
690 /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
691 /// library lookup path.
692 pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Command) {
693 // Windows doesn't need dylib path munging because the dlls for the
694 // compiler live next to the compiler and the system will find them
700 add_dylib_path(vec![self.rustc_libdir(compiler)], cmd);
703 /// Gets a path to the compiler specified.
704 pub fn rustc(&self, compiler: Compiler) -> PathBuf {
705 if compiler.is_snapshot(self) {
706 self.initial_rustc.clone()
708 self.sysroot(compiler).join("bin").join(exe("rustc", compiler.host))
712 /// Gets the paths to all of the compiler's codegen backends.
713 fn codegen_backends(&self, compiler: Compiler) -> impl Iterator<Item = PathBuf> {
714 fs::read_dir(self.sysroot_codegen_backends(compiler))
717 .filter_map(Result::ok)
718 .map(|entry| entry.path())
721 pub fn rustdoc(&self, compiler: Compiler) -> PathBuf {
722 self.ensure(tool::Rustdoc { compiler })
725 pub fn rustdoc_cmd(&self, compiler: Compiler) -> Command {
726 let mut cmd = Command::new(&self.out.join("bootstrap/debug/rustdoc"));
727 cmd.env("RUSTC_STAGE", compiler.stage.to_string())
728 .env("RUSTC_SYSROOT", self.sysroot(compiler))
729 // Note that this is *not* the sysroot_libdir because rustdoc must be linked
730 // equivalently to rustc.
731 .env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler))
732 .env("CFG_RELEASE_CHANNEL", &self.config.channel)
733 .env("RUSTDOC_REAL", self.rustdoc(compiler))
734 .env("RUSTC_BOOTSTRAP", "1")
735 .arg("-Winvalid_codeblock_attributes");
736 if self.config.deny_warnings {
737 cmd.arg("-Dwarnings");
739 // cfg(not(bootstrap)), can be removed on the next beta bump
740 if compiler.stage != 0 {
741 cmd.arg("-Znormalize-docs");
744 // Remove make-related flags that can cause jobserver problems.
745 cmd.env_remove("MAKEFLAGS");
746 cmd.env_remove("MFLAGS");
748 if let Some(linker) = self.linker(compiler.host) {
749 cmd.env("RUSTDOC_LINKER", linker);
751 if self.is_fuse_ld_lld(compiler.host) {
752 cmd.env("RUSTDOC_FUSE_LD_LLD", "1");
757 /// Return the path to `llvm-config` for the target, if it exists.
759 /// Note that this returns `None` if LLVM is disabled, or if we're in a
760 /// check build or dry-run, where there's no need to build all of LLVM.
761 fn llvm_config(&self, target: TargetSelection) -> Option<PathBuf> {
762 if self.config.llvm_enabled() && self.kind != Kind::Check && !self.config.dry_run {
763 let llvm_config = self.ensure(native::Llvm { target });
764 if llvm_config.is_file() {
765 return Some(llvm_config);
771 /// Prepares an invocation of `cargo` to be run.
773 /// This will create a `Command` that represents a pending execution of
774 /// Cargo. This cargo will be configured to use `compiler` as the actual
775 /// rustc compiler, its output will be scoped by `mode`'s output directory,
776 /// it will pass the `--target` flag for the specified `target`, and will be
777 /// executing the Cargo command `cmd`.
782 source_type: SourceType,
783 target: TargetSelection,
786 let mut cargo = Command::new(&self.initial_cargo);
787 let out_dir = self.stage_out(compiler, mode);
789 // Codegen backends are not yet tracked by -Zbinary-dep-depinfo,
790 // so we need to explicitly clear out if they've been updated.
791 for backend in self.codegen_backends(compiler) {
792 self.clear_if_dirty(&out_dir, &backend);
795 if cmd == "doc" || cmd == "rustdoc" {
796 let my_out = match mode {
797 // This is the intended out directory for compiler documentation.
798 Mode::Rustc | Mode::ToolRustc => self.compiler_doc_out(target),
799 Mode::Std => out_dir.join(target.triple).join("doc"),
800 _ => panic!("doc mode {:?} not expected", mode),
802 let rustdoc = self.rustdoc(compiler);
803 self.clear_if_dirty(&my_out, &rustdoc);
806 cargo.env("CARGO_TARGET_DIR", &out_dir).arg(cmd);
808 let profile_var = |name: &str| {
809 let profile = if self.config.rust_optimize { "RELEASE" } else { "DEV" };
810 format!("CARGO_PROFILE_{}_{}", profile, name)
813 // See comment in rustc_llvm/build.rs for why this is necessary, largely llvm-config
814 // needs to not accidentally link to libLLVM in stage0/lib.
815 cargo.env("REAL_LIBRARY_PATH_VAR", &util::dylib_path_var());
816 if let Some(e) = env::var_os(util::dylib_path_var()) {
817 cargo.env("REAL_LIBRARY_PATH", e);
820 match self.build.config.color {
822 cargo.arg("--color=always");
825 cargo.arg("--color=never");
827 Color::Auto => {} // nothing to do
830 if cmd != "install" {
831 cargo.arg("--target").arg(target.rustc_target_arg());
833 assert_eq!(target, compiler.host);
836 // Set a flag for `check`/`clippy`/`fix`, so that certain build
837 // scripts can do less work (i.e. not building/requiring LLVM).
838 if cmd == "check" || cmd == "clippy" || cmd == "fix" {
839 // If we've not yet built LLVM, or it's stale, then bust
840 // the rustc_llvm cache. That will always work, even though it
841 // may mean that on the next non-check build we'll need to rebuild
842 // rustc_llvm. But if LLVM is stale, that'll be a tiny amount
843 // of work comparitively, and we'd likely need to rebuild it anyway,
845 if crate::native::prebuilt_llvm_config(self, target).is_err() {
846 cargo.env("RUST_CHECK", "1");
850 let stage = if compiler.stage == 0 && self.local_rebuild {
851 // Assume the local-rebuild rustc already has stage1 features.
857 let mut rustflags = Rustflags::new(target);
859 if let Ok(s) = env::var("CARGOFLAGS_NOT_BOOTSTRAP") {
860 cargo.args(s.split_whitespace());
862 rustflags.env("RUSTFLAGS_NOT_BOOTSTRAP");
864 if let Ok(s) = env::var("CARGOFLAGS_BOOTSTRAP") {
865 cargo.args(s.split_whitespace());
867 rustflags.env("RUSTFLAGS_BOOTSTRAP");
869 // clippy overwrites sysroot if we pass it to cargo.
870 // Pass it directly to clippy instead.
871 // NOTE: this can't be fixed in clippy because we explicitly don't set `RUSTC`,
872 // so it has no way of knowing the sysroot.
873 rustflags.arg("--sysroot");
875 self.sysroot(compiler)
878 .expect("sysroot must be valid UTF-8"),
880 // Only run clippy on a very limited subset of crates (in particular, not build scripts).
881 cargo.arg("-Zunstable-options");
882 // Explicitly does *not* set `--cfg=bootstrap`, since we're using a nightly clippy.
883 let host_version = Command::new("rustc").arg("--version").output().map_err(|_| ());
884 let output = host_version.and_then(|output| {
885 if output.status.success() {
890 }).unwrap_or_else(|_| {
892 "error: `x.py clippy` requires a host `rustc` toolchain with the `clippy` component"
894 eprintln!("help: try `rustup component add clippy`");
895 std::process::exit(1);
897 if !t!(std::str::from_utf8(&output.stdout)).contains("nightly") {
898 rustflags.arg("--cfg=bootstrap");
901 rustflags.arg("--cfg=bootstrap");
905 if self.config.rust_new_symbol_mangling {
906 rustflags.arg("-Zsymbol-mangling-version=v0");
909 // FIXME: It might be better to use the same value for both `RUSTFLAGS` and `RUSTDOCFLAGS`,
910 // but this breaks CI. At the very least, stage0 `rustdoc` needs `--cfg bootstrap`. See
912 let mut rustdocflags = rustflags.clone();
914 if let Ok(s) = env::var("CARGOFLAGS") {
915 cargo.args(s.split_whitespace());
919 Mode::Std | Mode::ToolBootstrap | Mode::ToolStd => {}
920 Mode::Rustc | Mode::Codegen | Mode::ToolRustc => {
921 // Build proc macros both for the host and the target
922 if target != compiler.host && cmd != "check" {
923 cargo.arg("-Zdual-proc-macros");
924 rustflags.arg("-Zdual-proc-macros");
929 // This tells Cargo (and in turn, rustc) to output more complete
930 // dependency information. Most importantly for rustbuild, this
931 // includes sysroot artifacts, like libstd, which means that we don't
932 // need to track those in rustbuild (an error prone process!). This
933 // feature is currently unstable as there may be some bugs and such, but
934 // it represents a big improvement in rustbuild's reliability on
935 // rebuilds, so we're using it here.
937 // For some additional context, see #63470 (the PR originally adding
938 // this), as well as #63012 which is the tracking issue for this
939 // feature on the rustc side.
940 cargo.arg("-Zbinary-dep-depinfo");
942 cargo.arg("-j").arg(self.jobs().to_string());
943 // Remove make-related flags to ensure Cargo can correctly set things up
944 cargo.env_remove("MAKEFLAGS");
945 cargo.env_remove("MFLAGS");
947 // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
948 // Force cargo to output binaries with disambiguating hashes in the name
949 let mut metadata = if compiler.stage == 0 {
950 // Treat stage0 like a special channel, whether it's a normal prior-
951 // release rustc or a local rebuild with the same version, so we
952 // never mix these libraries by accident.
953 "bootstrap".to_string()
955 self.config.channel.to_string()
957 // We want to make sure that none of the dependencies between
958 // std/test/rustc unify with one another. This is done for weird linkage
959 // reasons but the gist of the problem is that if librustc, libtest, and
960 // libstd all depend on libc from crates.io (which they actually do) we
961 // want to make sure they all get distinct versions. Things get really
962 // weird if we try to unify all these dependencies right now, namely
963 // around how many times the library is linked in dynamic libraries and
964 // such. If rustc were a static executable or if we didn't ship dylibs
965 // this wouldn't be a problem, but we do, so it is. This is in general
966 // just here to make sure things build right. If you can remove this and
967 // things still build right, please do!
969 Mode::Std => metadata.push_str("std"),
970 // When we're building rustc tools, they're built with a search path
971 // that contains things built during the rustc build. For example,
972 // bitflags is built during the rustc build, and is a dependency of
973 // rustdoc as well. We're building rustdoc in a different target
974 // directory, though, which means that Cargo will rebuild the
975 // dependency. When we go on to build rustdoc, we'll look for
976 // bitflags, and find two different copies: one built during the
977 // rustc step and one that we just built. This isn't always a
978 // problem, somehow -- not really clear why -- but we know that this
980 Mode::ToolRustc => metadata.push_str("tool-rustc"),
981 // Same for codegen backends.
982 Mode::Codegen => metadata.push_str("codegen"),
985 cargo.env("__CARGO_DEFAULT_LIB_METADATA", &metadata);
988 rustflags.arg("-Zforce-unstable-if-unmarked");
991 rustflags.arg("-Zmacro-backtrace");
993 let want_rustdoc = self.doc_tests != DocTests::No;
995 // We synthetically interpret a stage0 compiler used to build tools as a
996 // "raw" compiler in that it's the exact snapshot we download. Normally
997 // the stage0 build means it uses libraries build by the stage0
998 // compiler, but for tools we just use the precompiled libraries that
1000 let use_snapshot = mode == Mode::ToolBootstrap;
1001 assert!(!use_snapshot || stage == 0 || self.local_rebuild);
1003 let maybe_sysroot = self.sysroot(compiler);
1004 let sysroot = if use_snapshot { self.rustc_snapshot_sysroot() } else { &maybe_sysroot };
1005 let libdir = self.rustc_libdir(compiler);
1007 // Clear the output directory if the real rustc we're using has changed;
1008 // Cargo cannot detect this as it thinks rustc is bootstrap/debug/rustc.
1010 // Avoid doing this during dry run as that usually means the relevant
1011 // compiler is not yet linked/copied properly.
1013 // Only clear out the directory if we're compiling std; otherwise, we
1014 // should let Cargo take care of things for us (via depdep info)
1015 if !self.config.dry_run && mode == Mode::Std && cmd == "build" {
1016 self.clear_if_dirty(&out_dir, &self.rustc(compiler));
1019 // Customize the compiler we're running. Specify the compiler to cargo
1020 // as our shim and then pass it some various options used to configure
1021 // how the actual compiler itself is called.
1023 // These variables are primarily all read by
1024 // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
1026 .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
1027 .env("RUSTC_REAL", self.rustc(compiler))
1028 .env("RUSTC_STAGE", stage.to_string())
1029 .env("RUSTC_SYSROOT", &sysroot)
1030 .env("RUSTC_LIBDIR", &libdir)
1031 .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
1034 if cmd == "doc" || cmd == "rustdoc" || (cmd == "test" && want_rustdoc) {
1035 self.rustdoc(compiler)
1037 PathBuf::from("/path/to/nowhere/rustdoc/not/required")
1040 .env("RUSTC_ERROR_METADATA_DST", self.extended_error_dir())
1041 .env("RUSTC_BREAK_ON_ICE", "1");
1042 // Clippy support is a hack and uses the default `cargo-clippy` in path.
1043 // Don't override RUSTC so that the `cargo-clippy` in path will be run.
1044 if cmd != "clippy" {
1045 cargo.env("RUSTC", self.out.join("bootstrap/debug/rustc"));
1048 // Dealing with rpath here is a little special, so let's go into some
1049 // detail. First off, `-rpath` is a linker option on Unix platforms
1050 // which adds to the runtime dynamic loader path when looking for
1051 // dynamic libraries. We use this by default on Unix platforms to ensure
1052 // that our nightlies behave the same on Windows, that is they work out
1053 // of the box. This can be disabled, of course, but basically that's why
1054 // we're gated on RUSTC_RPATH here.
1056 // Ok, so the astute might be wondering "why isn't `-C rpath` used
1057 // here?" and that is indeed a good question to ask. This codegen
1058 // option is the compiler's current interface to generating an rpath.
1059 // Unfortunately it doesn't quite suffice for us. The flag currently
1060 // takes no value as an argument, so the compiler calculates what it
1061 // should pass to the linker as `-rpath`. This unfortunately is based on
1062 // the **compile time** directory structure which when building with
1063 // Cargo will be very different than the runtime directory structure.
1065 // All that's a really long winded way of saying that if we use
1066 // `-Crpath` then the executables generated have the wrong rpath of
1067 // something like `$ORIGIN/deps` when in fact the way we distribute
1068 // rustc requires the rpath to be `$ORIGIN/../lib`.
1070 // So, all in all, to set up the correct rpath we pass the linker
1071 // argument manually via `-C link-args=-Wl,-rpath,...`. Plus isn't it
1072 // fun to pass a flag to a tool to pass a flag to pass a flag to a tool
1073 // to change a flag in a binary?
1074 if self.config.rust_rpath && util::use_host_linker(target) {
1075 let rpath = if target.contains("apple") {
1076 // Note that we need to take one extra step on macOS to also pass
1077 // `-Wl,-instal_name,@rpath/...` to get things to work right. To
1078 // do that we pass a weird flag to the compiler to get it to do
1079 // so. Note that this is definitely a hack, and we should likely
1080 // flesh out rpath support more fully in the future.
1081 rustflags.arg("-Zosx-rpath-install-name");
1082 Some("-Wl,-rpath,@loader_path/../lib")
1083 } else if !target.contains("windows") {
1084 Some("-Wl,-rpath,$ORIGIN/../lib")
1088 if let Some(rpath) = rpath {
1089 rustflags.arg(&format!("-Clink-args={}", rpath));
1093 if let Some(host_linker) = self.linker(compiler.host) {
1094 cargo.env("RUSTC_HOST_LINKER", host_linker);
1096 if self.is_fuse_ld_lld(compiler.host) {
1097 cargo.env("RUSTC_HOST_FUSE_LD_LLD", "1");
1100 if let Some(target_linker) = self.linker(target) {
1101 let target = crate::envify(&target.triple);
1102 cargo.env(&format!("CARGO_TARGET_{}_LINKER", target), target_linker);
1104 if self.is_fuse_ld_lld(target) {
1105 rustflags.arg("-Clink-args=-fuse-ld=lld");
1108 if !(["build", "check", "clippy", "fix", "rustc"].contains(&cmd)) && want_rustdoc {
1109 cargo.env("RUSTDOC_LIBDIR", self.rustc_libdir(compiler));
1112 let debuginfo_level = match mode {
1113 Mode::Rustc | Mode::Codegen => self.config.rust_debuginfo_level_rustc,
1114 Mode::Std => self.config.rust_debuginfo_level_std,
1115 Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolRustc => {
1116 self.config.rust_debuginfo_level_tools
1119 cargo.env(profile_var("DEBUG"), debuginfo_level.to_string());
1121 profile_var("DEBUG_ASSERTIONS"),
1122 if mode == Mode::Std {
1123 self.config.rust_debug_assertions_std.to_string()
1125 self.config.rust_debug_assertions.to_string()
1129 // `dsymutil` adds time to builds on Apple platforms for no clear benefit, and also makes
1130 // it more difficult for debuggers to find debug info. The compiler currently defaults to
1131 // running `dsymutil` to preserve its historical default, but when compiling the compiler
1132 // itself, we skip it by default since we know it's safe to do so in that case.
1133 // See https://github.com/rust-lang/rust/issues/79361 for more info on this flag.
1134 if target.contains("apple") {
1135 if self.config.rust_run_dsymutil {
1136 rustflags.arg("-Zrun-dsymutil=yes");
1138 rustflags.arg("-Zrun-dsymutil=no");
1142 if self.config.cmd.bless() {
1143 // Bless `expect!` tests.
1144 cargo.env("UPDATE_EXPECT", "1");
1147 if !mode.is_tool() {
1148 cargo.env("RUSTC_FORCE_UNSTABLE", "1");
1151 if let Some(x) = self.crt_static(target) {
1153 rustflags.arg("-Ctarget-feature=+crt-static");
1155 rustflags.arg("-Ctarget-feature=-crt-static");
1159 if let Some(x) = self.crt_static(compiler.host) {
1160 cargo.env("RUSTC_HOST_CRT_STATIC", x.to_string());
1163 if let Some(map_to) = self.build.debuginfo_map_to(GitRepo::Rustc) {
1164 let map = format!("{}={}", self.build.src.display(), map_to);
1165 cargo.env("RUSTC_DEBUGINFO_MAP", map);
1167 // `rustc` needs to know the virtual `/rustc/$hash` we're mapping to,
1168 // in order to opportunistically reverse it later.
1169 cargo.env("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR", map_to);
1172 // Enable usage of unstable features
1173 cargo.env("RUSTC_BOOTSTRAP", "1");
1174 self.add_rust_test_threads(&mut cargo);
1176 // Almost all of the crates that we compile as part of the bootstrap may
1177 // have a build script, including the standard library. To compile a
1178 // build script, however, it itself needs a standard library! This
1179 // introduces a bit of a pickle when we're compiling the standard
1182 // To work around this we actually end up using the snapshot compiler
1183 // (stage0) for compiling build scripts of the standard library itself.
1184 // The stage0 compiler is guaranteed to have a libstd available for use.
1186 // For other crates, however, we know that we've already got a standard
1187 // library up and running, so we can use the normal compiler to compile
1188 // build scripts in that situation.
1189 if mode == Mode::Std {
1191 .env("RUSTC_SNAPSHOT", &self.initial_rustc)
1192 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
1195 .env("RUSTC_SNAPSHOT", self.rustc(compiler))
1196 .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
1199 // Tools that use compiler libraries may inherit the `-lLLVM` link
1200 // requirement, but the `-L` library path is not propagated across
1201 // separate Cargo projects. We can add LLVM's library path to the
1202 // platform-specific environment variable as a workaround.
1203 if mode == Mode::ToolRustc {
1204 if let Some(llvm_config) = self.llvm_config(target) {
1205 let llvm_libdir = output(Command::new(&llvm_config).arg("--libdir"));
1206 add_link_lib_path(vec![llvm_libdir.trim().into()], &mut cargo);
1210 // Compile everything except libraries and proc macros with the more
1211 // efficient initial-exec TLS model. This doesn't work with `dlopen`,
1212 // so we can't use it by default in general, but we can use it for tools
1213 // and our own internal libraries.
1214 if !mode.must_support_dlopen() {
1215 rustflags.arg("-Ztls-model=initial-exec");
1218 if self.config.incremental {
1219 cargo.env("CARGO_INCREMENTAL", "1");
1221 // Don't rely on any default setting for incr. comp. in Cargo
1222 cargo.env("CARGO_INCREMENTAL", "0");
1225 if let Some(ref on_fail) = self.config.on_fail {
1226 cargo.env("RUSTC_ON_FAIL", on_fail);
1229 if self.config.print_step_timings {
1230 cargo.env("RUSTC_PRINT_STEP_TIMINGS", "1");
1233 if self.config.backtrace_on_ice {
1234 cargo.env("RUSTC_BACKTRACE_ON_ICE", "1");
1237 cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
1239 if source_type == SourceType::InTree {
1240 let mut lint_flags = Vec::new();
1241 // When extending this list, add the new lints to the RUSTFLAGS of the
1242 // build_bootstrap function of src/bootstrap/bootstrap.py as well as
1243 // some code doesn't go through this `rustc` wrapper.
1244 lint_flags.push("-Wrust_2018_idioms");
1245 lint_flags.push("-Wunused_lifetimes");
1247 if self.config.deny_warnings {
1248 lint_flags.push("-Dwarnings");
1249 rustdocflags.arg("-Dwarnings");
1252 // FIXME(#58633) hide "unused attribute" errors in incremental
1253 // builds of the standard library, as the underlying checks are
1254 // not yet properly integrated with incremental recompilation.
1255 if mode == Mode::Std && compiler.stage == 0 && self.config.incremental {
1256 lint_flags.push("-Aunused-attributes");
1258 // This does not use RUSTFLAGS due to caching issues with Cargo.
1259 // Clippy is treated as an "in tree" tool, but shares the same
1260 // cache as other "submodule" tools. With these options set in
1261 // RUSTFLAGS, that causes *every* shared dependency to be rebuilt.
1262 // By injecting this into the rustc wrapper, this circumvents
1263 // Cargo's fingerprint detection. This is fine because lint flags
1264 // are always ignored in dependencies. Eventually this should be
1265 // fixed via better support from Cargo.
1266 cargo.env("RUSTC_LINT_FLAGS", lint_flags.join(" "));
1268 rustdocflags.arg("-Winvalid_codeblock_attributes");
1271 if mode == Mode::Rustc {
1272 rustflags.arg("-Zunstable-options");
1273 rustflags.arg("-Wrustc::internal");
1276 // Throughout the build Cargo can execute a number of build scripts
1277 // compiling C/C++ code and we need to pass compilers, archivers, flags, etc
1278 // obtained previously to those build scripts.
1279 // Build scripts use either the `cc` crate or `configure/make` so we pass
1280 // the options through environment variables that are fetched and understood by both.
1282 // FIXME: the guard against msvc shouldn't need to be here
1283 if target.contains("msvc") {
1284 if let Some(ref cl) = self.config.llvm_clang_cl {
1285 cargo.env("CC", cl).env("CXX", cl);
1288 let ccache = self.config.ccache.as_ref();
1289 let ccacheify = |s: &Path| {
1290 let ccache = match ccache {
1292 None => return s.display().to_string(),
1294 // FIXME: the cc-rs crate only recognizes the literal strings
1295 // `ccache` and `sccache` when doing caching compilations, so we
1296 // mirror that here. It should probably be fixed upstream to
1297 // accept a new env var or otherwise work with custom ccache
1300 "ccache" | "sccache" => format!("{} {}", ccache, s.display()),
1301 _ => s.display().to_string(),
1304 let cc = ccacheify(&self.cc(target));
1305 cargo.env(format!("CC_{}", target.triple), &cc);
1307 let cflags = self.cflags(target, GitRepo::Rustc).join(" ");
1308 cargo.env(format!("CFLAGS_{}", target.triple), &cflags);
1310 if let Some(ar) = self.ar(target) {
1311 let ranlib = format!("{} s", ar.display());
1313 .env(format!("AR_{}", target.triple), ar)
1314 .env(format!("RANLIB_{}", target.triple), ranlib);
1317 if let Ok(cxx) = self.cxx(target) {
1318 let cxx = ccacheify(&cxx);
1320 .env(format!("CXX_{}", target.triple), &cxx)
1321 .env(format!("CXXFLAGS_{}", target.triple), cflags);
1325 if mode == Mode::Std && self.config.extended && compiler.is_final_stage(self) {
1326 rustflags.arg("-Zsave-analysis");
1328 "RUST_SAVE_ANALYSIS_CONFIG",
1329 "{\"output_file\": null,\"full_docs\": false,\
1330 \"pub_only\": true,\"reachable_only\": false,\
1331 \"distro_crate\": true,\"signatures\": false,\"borrow_data\": false}",
1335 // If Control Flow Guard is enabled, pass the `control-flow-guard` flag to rustc
1336 // when compiling the standard library, since this might be linked into the final outputs
1337 // produced by rustc. Since this mitigation is only available on Windows, only enable it
1338 // for the standard library in case the compiler is run on a non-Windows platform.
1339 // This is not needed for stage 0 artifacts because these will only be used for building
1340 // the stage 1 compiler.
1342 && mode == Mode::Std
1343 && self.config.control_flow_guard
1344 && compiler.stage >= 1
1346 rustflags.arg("-Ccontrol-flow-guard");
1349 // For `cargo doc` invocations, make rustdoc print the Rust version into the docs
1350 // This replaces spaces with newlines because RUSTDOCFLAGS does not
1351 // support arguments with regular spaces. Hopefully someday Cargo will
1352 // have space support.
1353 let rust_version = self.rust_version().replace(' ', "\n");
1354 rustdocflags.arg("--crate-version").arg(&rust_version);
1356 // Environment variables *required* throughout the build
1358 // FIXME: should update code to not require this env var
1359 cargo.env("CFG_COMPILER_HOST_TRIPLE", target.triple);
1361 // Set this for all builds to make sure doc builds also get it.
1362 cargo.env("CFG_RELEASE_CHANNEL", &self.config.channel);
1364 // This one's a bit tricky. As of the time of this writing the compiler
1365 // links to the `winapi` crate on crates.io. This crate provides raw
1366 // bindings to Windows system functions, sort of like libc does for
1367 // Unix. This crate also, however, provides "import libraries" for the
1368 // MinGW targets. There's an import library per dll in the windows
1369 // distribution which is what's linked to. These custom import libraries
1370 // are used because the winapi crate can reference Windows functions not
1371 // present in the MinGW import libraries.
1373 // For example MinGW may ship libdbghelp.a, but it may not have
1374 // references to all the functions in the dbghelp dll. Instead the
1375 // custom import library for dbghelp in the winapi crates has all this
1378 // Unfortunately for us though the import libraries are linked by
1379 // default via `-ldylib=winapi_foo`. That is, they're linked with the
1380 // `dylib` type with a `winapi_` prefix (so the winapi ones don't
1381 // conflict with the system MinGW ones). This consequently means that
1382 // the binaries we ship of things like rustc_codegen_llvm (aka the rustc_codegen_llvm
1383 // DLL) when linked against *again*, for example with procedural macros
1384 // or plugins, will trigger the propagation logic of `-ldylib`, passing
1385 // `-lwinapi_foo` to the linker again. This isn't actually available in
1386 // our distribution, however, so the link fails.
1388 // To solve this problem we tell winapi to not use its bundled import
1389 // libraries. This means that it will link to the system MinGW import
1390 // libraries by default, and the `-ldylib=foo` directives will still get
1391 // passed to the final linker, but they'll look like `-lfoo` which can
1392 // be resolved because MinGW has the import library. The downside is we
1393 // don't get newer functions from Windows, but we don't use any of them
1395 if !mode.is_tool() {
1396 cargo.env("WINAPI_NO_BUNDLED_LIBRARIES", "1");
1399 for _ in 1..self.verbosity {
1403 match (mode, self.config.rust_codegen_units_std, self.config.rust_codegen_units) {
1404 (Mode::Std, Some(n), _) | (_, _, Some(n)) => {
1405 cargo.env(profile_var("CODEGEN_UNITS"), n.to_string());
1408 // Don't set anything
1412 if self.config.rust_optimize {
1413 // FIXME: cargo bench/install do not accept `--release`
1414 if cmd != "bench" && cmd != "install" {
1415 cargo.arg("--release");
1419 if self.config.locked_deps {
1420 cargo.arg("--locked");
1422 if self.config.vendor || self.is_sudo {
1423 cargo.arg("--frozen");
1426 // Try to use a sysroot-relative bindir, in case it was configured absolutely.
1427 cargo.env("RUSTC_INSTALL_BINDIR", self.config.bindir_relative());
1429 self.ci_env.force_coloring_in_ci(&mut cargo);
1431 // When we build Rust dylibs they're all intended for intermediate
1432 // usage, so make sure we pass the -Cprefer-dynamic flag instead of
1433 // linking all deps statically into the dylib.
1434 if matches!(mode, Mode::Std | Mode::Rustc) {
1435 rustflags.arg("-Cprefer-dynamic");
1438 // When building incrementally we default to a lower ThinLTO import limit
1439 // (unless explicitly specified otherwise). This will produce a somewhat
1440 // slower code but give way better compile times.
1442 let limit = match self.config.rust_thin_lto_import_instr_limit {
1443 Some(limit) => Some(limit),
1444 None if self.config.incremental => Some(10),
1448 if let Some(limit) = limit {
1449 rustflags.arg(&format!("-Cllvm-args=-import-instr-limit={}", limit));
1453 Cargo { command: cargo, rustflags, rustdocflags }
1456 /// Ensure that a given step is built, returning its output. This will
1457 /// cache the step, so it is safe (and good!) to call this as often as
1458 /// needed to ensure that all dependencies are built.
1459 pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
1461 let mut stack = self.stack.borrow_mut();
1462 for stack_step in stack.iter() {
1464 if stack_step.downcast_ref::<S>().map_or(true, |stack_step| *stack_step != step) {
1467 let mut out = String::new();
1468 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
1469 for el in stack.iter().rev() {
1470 out += &format!("\t{:?}\n", el);
1474 if let Some(out) = self.cache.get(&step) {
1475 self.verbose(&format!("{}c {:?}", " ".repeat(stack.len()), step));
1479 self.verbose(&format!("{}> {:?}", " ".repeat(stack.len()), step));
1480 stack.push(Box::new(step.clone()));
1484 let start = Instant::now();
1485 let zero = Duration::new(0, 0);
1486 let parent = self.time_spent_on_dependencies.replace(zero);
1487 let out = step.clone().run(self);
1488 let dur = start.elapsed();
1489 let deps = self.time_spent_on_dependencies.replace(parent + dur);
1493 if self.config.print_step_timings && !self.config.dry_run {
1494 println!("[TIMING] {:?} -- {}.{:03}", step, dur.as_secs(), dur.subsec_millis());
1498 let mut stack = self.stack.borrow_mut();
1499 let cur_step = stack.pop().expect("step stack empty");
1500 assert_eq!(cur_step.downcast_ref(), Some(&step));
1502 self.verbose(&format!("{}< {:?}", " ".repeat(self.stack.borrow().len()), step));
1503 self.cache.put(step, out.clone());
1511 #[derive(Debug, Clone)]
1512 struct Rustflags(String);
1515 fn new(target: TargetSelection) -> Rustflags {
1516 let mut ret = Rustflags(String::new());
1518 // Inherit `RUSTFLAGS` by default ...
1519 ret.env("RUSTFLAGS");
1521 // ... and also handle target-specific env RUSTFLAGS if they're
1523 let target_specific = format!("CARGO_TARGET_{}_RUSTFLAGS", crate::envify(&target.triple));
1524 ret.env(&target_specific);
1529 fn env(&mut self, env: &str) {
1530 if let Ok(s) = env::var(env) {
1531 for part in s.split(' ') {
1537 fn arg(&mut self, arg: &str) -> &mut Self {
1538 assert_eq!(arg.split(' ').count(), 1);
1539 if !self.0.is_empty() {
1540 self.0.push_str(" ");
1542 self.0.push_str(arg);
1550 rustflags: Rustflags,
1551 rustdocflags: Rustflags,
1555 pub fn rustdocflag(&mut self, arg: &str) -> &mut Cargo {
1556 self.rustdocflags.arg(arg);
1559 pub fn rustflag(&mut self, arg: &str) -> &mut Cargo {
1560 self.rustflags.arg(arg);
1564 pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Cargo {
1565 self.command.arg(arg.as_ref());
1569 pub fn args<I, S>(&mut self, args: I) -> &mut Cargo
1571 I: IntoIterator<Item = S>,
1575 self.arg(arg.as_ref());
1580 pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Cargo {
1581 // These are managed through rustflag/rustdocflag interfaces.
1582 assert_ne!(key.as_ref(), "RUSTFLAGS");
1583 assert_ne!(key.as_ref(), "RUSTDOCFLAGS");
1584 self.command.env(key.as_ref(), value.as_ref());
1588 pub fn add_rustc_lib_path(&mut self, builder: &Builder<'_>, compiler: Compiler) {
1589 builder.add_rustc_lib_path(compiler, &mut self.command);
1593 impl From<Cargo> for Command {
1594 fn from(mut cargo: Cargo) -> Command {
1595 let rustflags = &cargo.rustflags.0;
1596 if !rustflags.is_empty() {
1597 cargo.command.env("RUSTFLAGS", rustflags);
1600 let rustdocflags = &cargo.rustdocflags.0;
1601 if !rustdocflags.is_empty() {
1602 cargo.command.env("RUSTDOCFLAGS", rustdocflags);