]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/builder.rs
Add an optional condition to constrain defaults.
[rust.git] / src / bootstrap / builder.rs
1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use std::fmt::Debug;
12 use std::hash::Hash;
13 use std::cell::RefCell;
14 use std::path::{Path, PathBuf};
15 use std::process::Command;
16 use std::fs;
17 use std::ops::Deref;
18 use std::any::Any;
19 use std::collections::BTreeSet;
20
21 use compile;
22 use install;
23 use dist;
24 use util::{exe, libdir, add_lib_path};
25 use {Build, Mode};
26 use cache::{INTERNER, Interned, Cache};
27 use check;
28 use flags::Subcommand;
29 use doc;
30 use tool;
31
32 pub use Compiler;
33
34 pub struct Builder<'a> {
35     pub build: &'a Build,
36     pub top_stage: u32,
37     pub kind: Kind,
38     cache: Cache,
39     stack: RefCell<Vec<Box<Any>>>,
40 }
41
42 impl<'a> Deref for Builder<'a> {
43     type Target = Build;
44
45     fn deref(&self) -> &Self::Target {
46         self.build
47     }
48 }
49
50 pub trait Step: 'static + Clone + Debug + PartialEq + Eq + Hash {
51     /// `PathBuf` when directories are created or to return a `Compiler` once
52     /// it's been assembled.
53     type Output: Clone;
54
55     const DEFAULT: bool = false;
56
57     /// Run this rule for all hosts without cross compiling.
58     const ONLY_HOSTS: bool = false;
59
60     /// Run this rule for all targets, but only with the native host.
61     const ONLY_BUILD_TARGETS: bool = false;
62
63     /// Only run this step with the build triple as host and target.
64     const ONLY_BUILD: 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     /// Build 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(
83         _builder: &Builder,
84         _path: Option<&Path>,
85         _host: Interned<String>,
86         _target: Interned<String>,
87     ) {
88         // It is reasonable to not have an implementation of make_run for rules
89         // who do not want to get called from the root context. This means that
90         // they are likely dependencies (e.g., sysroot creation) or similar, and
91         // as such calling them from ./x.py isn't logical.
92         unimplemented!()
93     }
94 }
95
96 struct StepDescription {
97     default: bool,
98     only_hosts: bool,
99     only_build_targets: bool,
100     only_build: bool,
101     should_run: fn(ShouldRun) -> ShouldRun,
102     make_run: fn(&Builder, Option<&Path>, Interned<String>, Interned<String>),
103 }
104
105 impl StepDescription {
106     fn from<S: Step>() -> StepDescription {
107         StepDescription {
108             default: S::DEFAULT,
109             only_hosts: S::ONLY_HOSTS,
110             only_build_targets: S::ONLY_BUILD_TARGETS,
111             only_build: S::ONLY_BUILD,
112             should_run: S::should_run,
113             make_run: S::make_run,
114         }
115     }
116
117     fn maybe_run(&self, builder: &Builder, path: Option<&Path>) {
118         let build = builder.build;
119         let hosts = if self.only_build_targets || self.only_build {
120             &build.config.host[..1]
121         } else {
122             &build.hosts
123         };
124
125         // Determine the actual targets participating in this rule.
126         // NOTE: We should keep the full projection from build triple to
127         // the hosts for the dist steps, now that the hosts array above is
128         // truncated to avoid duplication of work in that case. Therefore
129         // the original non-shadowed hosts array is used below.
130         let targets = if self.only_hosts {
131             // If --target was specified but --host wasn't specified,
132             // don't run any host-only tests. Also, respect any `--host`
133             // overrides as done for `hosts`.
134             if build.flags.host.len() > 0 {
135                 &build.flags.host[..]
136             } else if build.flags.target.len() > 0 {
137                 &[]
138             } else if self.only_build {
139                 &build.config.host[..1]
140             } else {
141                 &build.config.host[..]
142             }
143         } else {
144             &build.targets
145         };
146
147         for host in hosts {
148             for target in targets {
149                 (self.make_run)(builder, path, *host, *target);
150             }
151         }
152     }
153
154     fn run(v: &[StepDescription], builder: &Builder, paths: &[PathBuf]) {
155         let should_runs = v.iter().map(|desc| {
156             (desc.should_run)(ShouldRun::new(builder))
157         }).collect::<Vec<_>>();
158         if paths.is_empty() {
159             for (desc, should_run) in v.iter().zip(should_runs) {
160                 if desc.default && should_run.is_really_default {
161                     desc.maybe_run(builder, None);
162                 }
163             }
164         } else {
165             for path in paths {
166                 let mut attempted_run = false;
167                 for (desc, should_run) in v.iter().zip(&should_runs) {
168                     if should_run.run(path) {
169                         attempted_run = true;
170                         desc.maybe_run(builder, Some(path));
171                     }
172                 }
173
174                 if !attempted_run {
175                     eprintln!("Warning: no rules matched {}.", path.display());
176                 }
177             }
178         }
179     }
180 }
181
182 #[derive(Clone)]
183 pub struct ShouldRun<'a> {
184     pub builder: &'a Builder<'a>,
185     // use a BTreeSet to maintain sort order
186     paths: BTreeSet<PathBuf>,
187
188     // If this is a default rule, this is an additional constraint placed on
189     // it's run. Generally something like compiler docs being enabled.
190     is_really_default: bool,
191 }
192
193 impl<'a> ShouldRun<'a> {
194     fn new(builder: &'a Builder) -> ShouldRun<'a> {
195         ShouldRun {
196             builder: builder,
197             paths: BTreeSet::new(),
198             is_really_default: true, // by default no additional conditions
199         }
200     }
201
202     pub fn default_condition(mut self, cond: bool) -> Self {
203         self.is_really_default = cond;
204         self
205     }
206
207     pub fn krate(mut self, name: &str) -> Self {
208         for (_, krate_path) in self.builder.crates(name) {
209             self.paths.insert(PathBuf::from(krate_path));
210         }
211         self
212     }
213
214     pub fn path(mut self, path: &str) -> Self {
215         self.paths.insert(PathBuf::from(path));
216         self
217     }
218
219     // allows being more explicit about why should_run in Step returns the value passed to it
220     pub fn never(self) -> ShouldRun<'a> {
221         self
222     }
223
224     fn run(&self, path: &Path) -> bool {
225         self.paths.iter().any(|p| path.ends_with(p))
226     }
227 }
228
229 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
230 pub enum Kind {
231     Build,
232     Test,
233     Bench,
234     Dist,
235     Doc,
236     Install,
237 }
238
239 impl<'a> Builder<'a> {
240     fn get_step_descriptions(kind: Kind) -> Vec<StepDescription> {
241         macro_rules! describe {
242             ($($rule:ty),+ $(,)*) => {{
243                 vec![$(StepDescription::from::<$rule>()),+]
244             }};
245         }
246         match kind {
247             Kind::Build => describe!(compile::Std, compile::Test, compile::Rustc,
248                 compile::StartupObjects, tool::BuildManifest, tool::Rustbook, tool::ErrorIndex,
249                 tool::UnstableBookGen, tool::Tidy, tool::Linkchecker, tool::CargoTest,
250                 tool::Compiletest, tool::RemoteTestServer, tool::RemoteTestClient,
251                 tool::RustInstaller, tool::Cargo, tool::Rls),
252             Kind::Test => describe!(check::Tidy, check::Bootstrap, check::DefaultCompiletest,
253                 check::HostCompiletest, check::Crate, check::CrateLibrustc, check::Linkcheck,
254                 check::Cargotest, check::Cargo, check::Rls, check::Docs, check::ErrorIndex,
255                 check::Distcheck),
256             Kind::Bench => describe!(check::Crate, check::CrateLibrustc),
257             Kind::Doc => describe!(doc::UnstableBook, doc::UnstableBookGen, doc::TheBook,
258                 doc::Standalone, doc::Std, doc::Test, doc::Rustc, doc::ErrorIndex, doc::Nomicon,
259                 doc::Reference),
260             Kind::Dist => describe!(dist::Docs, dist::Mingw, dist::Rustc, dist::DebuggerScripts,
261                 dist::Std, dist::Analysis, dist::Src, dist::PlainSourceTarball, dist::Cargo,
262                 dist::Rls, dist::Extended, dist::HashSign),
263             Kind::Install => describe!(install::Docs, install::Std, install::Cargo, install::Rls,
264                 install::Analysis, install::Src, install::Rustc),
265         }
266     }
267
268     pub fn get_help(build: &Build, subcommand: &str) -> Option<String> {
269         let kind = match subcommand {
270             "build" => Kind::Build,
271             "doc" => Kind::Doc,
272             "test" => Kind::Test,
273             "bench" => Kind::Bench,
274             "dist" => Kind::Dist,
275             "install" => Kind::Install,
276             _ => return None,
277         };
278
279         let builder = Builder {
280             build: build,
281             top_stage: build.flags.stage.unwrap_or(2),
282             kind: kind,
283             cache: Cache::new(),
284             stack: RefCell::new(Vec::new()),
285         };
286
287         let builder = &builder;
288         let mut should_run = ShouldRun::new(builder);
289         for desc in Builder::get_step_descriptions(builder.kind) {
290             should_run = (desc.should_run)(should_run);
291         }
292         let mut help = String::from("Available paths:\n");
293         for path in should_run.paths {
294             help.push_str(format!("    ./x.py {} {}\n", subcommand, path.display()).as_str());
295         }
296         Some(help)
297     }
298
299     pub fn run(build: &Build) {
300         let (kind, paths) = match build.flags.cmd {
301             Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
302             Subcommand::Doc { ref paths } => (Kind::Doc, &paths[..]),
303             Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
304             Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
305             Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
306             Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
307             Subcommand::Clean => panic!(),
308         };
309
310         let builder = Builder {
311             build: build,
312             top_stage: build.flags.stage.unwrap_or(2),
313             kind: kind,
314             cache: Cache::new(),
315             stack: RefCell::new(Vec::new()),
316         };
317
318         StepDescription::run(&Builder::get_step_descriptions(builder.kind), &builder, paths);
319     }
320
321     pub fn default_doc(&self, paths: Option<&[PathBuf]>) {
322         let paths = paths.unwrap_or(&[]);
323         StepDescription::run(&Builder::get_step_descriptions(Kind::Doc), self, paths);
324     }
325
326     /// Obtain a compiler at a given stage and for a given host. Explictly does
327     /// not take `Compiler` since all `Compiler` instances are meant to be
328     /// obtained through this function, since it ensures that they are valid
329     /// (i.e., built and assembled).
330     pub fn compiler(&self, stage: u32, host: Interned<String>) -> Compiler {
331         self.ensure(compile::Assemble { target_compiler: Compiler { stage, host } })
332     }
333
334     pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
335         self.ensure(compile::Sysroot { compiler })
336     }
337
338     /// Returns the libdir where the standard library and other artifacts are
339     /// found for a compiler's sysroot.
340     pub fn sysroot_libdir(
341         &self, compiler: Compiler, target: Interned<String>
342     ) -> Interned<PathBuf> {
343         #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
344         struct Libdir {
345             compiler: Compiler,
346             target: Interned<String>,
347         }
348         impl Step for Libdir {
349             type Output = Interned<PathBuf>;
350
351             fn should_run(run: ShouldRun) -> ShouldRun {
352                 run.never()
353             }
354
355             fn run(self, builder: &Builder) -> Interned<PathBuf> {
356                 let compiler = self.compiler;
357                 let lib = if compiler.stage >= 2 && builder.build.config.libdir_relative.is_some() {
358                     builder.build.config.libdir_relative.clone().unwrap()
359                 } else {
360                     PathBuf::from("lib")
361                 };
362                 let sysroot = builder.sysroot(self.compiler).join(lib)
363                     .join("rustlib").join(self.target).join("lib");
364                 let _ = fs::remove_dir_all(&sysroot);
365                 t!(fs::create_dir_all(&sysroot));
366                 INTERNER.intern_path(sysroot)
367             }
368         }
369         self.ensure(Libdir { compiler, target })
370     }
371
372     /// Returns the compiler's libdir where it stores the dynamic libraries that
373     /// it itself links against.
374     ///
375     /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
376     /// Windows.
377     pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
378         if compiler.is_snapshot(self) {
379             self.build.rustc_snapshot_libdir()
380         } else {
381             self.sysroot(compiler).join(libdir(&compiler.host))
382         }
383     }
384
385     /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
386     /// library lookup path.
387     pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Command) {
388         // Windows doesn't need dylib path munging because the dlls for the
389         // compiler live next to the compiler and the system will find them
390         // automatically.
391         if cfg!(windows) {
392             return
393         }
394
395         add_lib_path(vec![self.rustc_libdir(compiler)], cmd);
396     }
397
398     /// Get a path to the compiler specified.
399     pub fn rustc(&self, compiler: Compiler) -> PathBuf {
400         if compiler.is_snapshot(self) {
401             self.initial_rustc.clone()
402         } else {
403             self.sysroot(compiler).join("bin").join(exe("rustc", &compiler.host))
404         }
405     }
406
407     /// Get the `rustdoc` executable next to the specified compiler
408     pub fn rustdoc(&self, compiler: Compiler) -> PathBuf {
409         let mut rustdoc = self.rustc(compiler);
410         rustdoc.pop();
411         rustdoc.push(exe("rustdoc", &compiler.host));
412         rustdoc
413     }
414
415     /// Prepares an invocation of `cargo` to be run.
416     ///
417     /// This will create a `Command` that represents a pending execution of
418     /// Cargo. This cargo will be configured to use `compiler` as the actual
419     /// rustc compiler, its output will be scoped by `mode`'s output directory,
420     /// it will pass the `--target` flag for the specified `target`, and will be
421     /// executing the Cargo command `cmd`.
422     pub fn cargo(&self,
423              compiler: Compiler,
424              mode: Mode,
425              target: Interned<String>,
426              cmd: &str) -> Command {
427         let mut cargo = Command::new(&self.initial_cargo);
428         let out_dir = self.stage_out(compiler, mode);
429         cargo.env("CARGO_TARGET_DIR", out_dir)
430              .arg(cmd)
431              .arg("-j").arg(self.jobs().to_string())
432              .arg("--target").arg(target);
433
434         // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
435         // Force cargo to output binaries with disambiguating hashes in the name
436         cargo.env("__CARGO_DEFAULT_LIB_METADATA", &self.config.channel);
437
438         let stage;
439         if compiler.stage == 0 && self.local_rebuild {
440             // Assume the local-rebuild rustc already has stage1 features.
441             stage = 1;
442         } else {
443             stage = compiler.stage;
444         }
445
446         // Customize the compiler we're running. Specify the compiler to cargo
447         // as our shim and then pass it some various options used to configure
448         // how the actual compiler itself is called.
449         //
450         // These variables are primarily all read by
451         // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
452         cargo.env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
453              .env("RUSTC", self.out.join("bootstrap/debug/rustc"))
454              .env("RUSTC_REAL", self.rustc(compiler))
455              .env("RUSTC_STAGE", stage.to_string())
456              .env("RUSTC_CODEGEN_UNITS",
457                   self.config.rust_codegen_units.to_string())
458              .env("RUSTC_DEBUG_ASSERTIONS",
459                   self.config.rust_debug_assertions.to_string())
460              .env("RUSTC_SYSROOT", self.sysroot(compiler))
461              .env("RUSTC_LIBDIR", self.rustc_libdir(compiler))
462              .env("RUSTC_RPATH", self.config.rust_rpath.to_string())
463              .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
464              .env("RUSTDOC_REAL", self.rustdoc(compiler))
465              .env("RUSTC_FLAGS", self.rustc_flags(target).join(" "));
466
467         if mode != Mode::Tool {
468             // Tools don't get debuginfo right now, e.g. cargo and rls don't
469             // get compiled with debuginfo.
470             cargo.env("RUSTC_DEBUGINFO", self.config.rust_debuginfo.to_string())
471                  .env("RUSTC_DEBUGINFO_LINES", self.config.rust_debuginfo_lines.to_string())
472                  .env("RUSTC_FORCE_UNSTABLE", "1");
473
474             // Currently the compiler depends on crates from crates.io, and
475             // then other crates can depend on the compiler (e.g. proc-macro
476             // crates). Let's say, for example that rustc itself depends on the
477             // bitflags crate. If an external crate then depends on the
478             // bitflags crate as well, we need to make sure they don't
479             // conflict, even if they pick the same verison of bitflags. We'll
480             // want to make sure that e.g. a plugin and rustc each get their
481             // own copy of bitflags.
482
483             // Cargo ensures that this works in general through the -C metadata
484             // flag. This flag will frob the symbols in the binary to make sure
485             // they're different, even though the source code is the exact
486             // same. To solve this problem for the compiler we extend Cargo's
487             // already-passed -C metadata flag with our own. Our rustc.rs
488             // wrapper around the actual rustc will detect -C metadata being
489             // passed and frob it with this extra string we're passing in.
490             cargo.env("RUSTC_METADATA_SUFFIX", "rustc");
491         }
492
493         // Enable usage of unstable features
494         cargo.env("RUSTC_BOOTSTRAP", "1");
495         self.add_rust_test_threads(&mut cargo);
496
497         // Almost all of the crates that we compile as part of the bootstrap may
498         // have a build script, including the standard library. To compile a
499         // build script, however, it itself needs a standard library! This
500         // introduces a bit of a pickle when we're compiling the standard
501         // library itself.
502         //
503         // To work around this we actually end up using the snapshot compiler
504         // (stage0) for compiling build scripts of the standard library itself.
505         // The stage0 compiler is guaranteed to have a libstd available for use.
506         //
507         // For other crates, however, we know that we've already got a standard
508         // library up and running, so we can use the normal compiler to compile
509         // build scripts in that situation.
510         if mode == Mode::Libstd {
511             cargo.env("RUSTC_SNAPSHOT", &self.initial_rustc)
512                  .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
513         } else {
514             cargo.env("RUSTC_SNAPSHOT", self.rustc(compiler))
515                  .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
516         }
517
518         // Ignore incremental modes except for stage0, since we're
519         // not guaranteeing correctness across builds if the compiler
520         // is changing under your feet.`
521         if self.flags.incremental && compiler.stage == 0 {
522             let incr_dir = self.incremental_dir(compiler);
523             cargo.env("RUSTC_INCREMENTAL", incr_dir);
524         }
525
526         if let Some(ref on_fail) = self.flags.on_fail {
527             cargo.env("RUSTC_ON_FAIL", on_fail);
528         }
529
530         cargo.env("RUSTC_VERBOSE", format!("{}", self.verbosity));
531
532         // Specify some various options for build scripts used throughout
533         // the build.
534         //
535         // FIXME: the guard against msvc shouldn't need to be here
536         if !target.contains("msvc") {
537             cargo.env(format!("CC_{}", target), self.cc(target))
538                  .env(format!("AR_{}", target), self.ar(target).unwrap()) // only msvc is None
539                  .env(format!("CFLAGS_{}", target), self.cflags(target).join(" "));
540
541             if let Ok(cxx) = self.cxx(target) {
542                  cargo.env(format!("CXX_{}", target), cxx);
543             }
544         }
545
546         if mode == Mode::Libstd && self.config.extended && compiler.is_final_stage(self) {
547             cargo.env("RUSTC_SAVE_ANALYSIS", "api".to_string());
548         }
549
550         // Environment variables *required* throughout the build
551         //
552         // FIXME: should update code to not require this env var
553         cargo.env("CFG_COMPILER_HOST_TRIPLE", target);
554
555         if self.is_verbose() {
556             cargo.arg("-v");
557         }
558         // FIXME: cargo bench does not accept `--release`
559         if self.config.rust_optimize && cmd != "bench" {
560             cargo.arg("--release");
561         }
562         if self.config.locked_deps {
563             cargo.arg("--locked");
564         }
565         if self.config.vendor || self.is_sudo {
566             cargo.arg("--frozen");
567         }
568
569         self.ci_env.force_coloring_in_ci(&mut cargo);
570
571         cargo
572     }
573
574     /// Ensure that a given step is built, returning it's output. This will
575     /// cache the step, so it is safe (and good!) to call this as often as
576     /// needed to ensure that all dependencies are built.
577     pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
578         {
579             let mut stack = self.stack.borrow_mut();
580             for stack_step in stack.iter() {
581                 // should skip
582                 if stack_step.downcast_ref::<S>().map_or(true, |stack_step| *stack_step != step) {
583                     continue;
584                 }
585                 let mut out = String::new();
586                 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
587                 for el in stack.iter().rev() {
588                     out += &format!("\t{:?}\n", el);
589                 }
590                 panic!(out);
591             }
592             if let Some(out) = self.cache.get(&step) {
593                 self.build.verbose(&format!("{}c {:?}", "  ".repeat(stack.len()), step));
594
595                 return out;
596             }
597             self.build.verbose(&format!("{}> {:?}", "  ".repeat(stack.len()), step));
598             stack.push(Box::new(step.clone()));
599         }
600         let out = step.clone().run(self);
601         {
602             let mut stack = self.stack.borrow_mut();
603             let cur_step = stack.pop().expect("step stack empty");
604             assert_eq!(cur_step.downcast_ref(), Some(&step));
605         }
606         self.build.verbose(&format!("{}< {:?}", "  ".repeat(self.stack.borrow().len()), step));
607         self.cache.put(step, out.clone());
608         out
609     }
610 }