]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/builder.rs
Rollup merge of #44562 - eddyb:ugh-rustdoc, r=nikomatsakis
[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 use native;
32
33 pub use Compiler;
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<Any>>>,
41 }
42
43 impl<'a> Deref for Builder<'a> {
44     type Target = Build;
45
46     fn deref(&self) -> &Self::Target {
47         self.build
48     }
49 }
50
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.
54     type Output: Clone;
55
56     const DEFAULT: bool = false;
57
58     /// Run this rule for all hosts without cross compiling.
59     const ONLY_HOSTS: bool = false;
60
61     /// Run this rule for all targets, but only with the native host.
62     const ONLY_BUILD_TARGETS: bool = false;
63
64     /// Only run this step with the build triple as host and target.
65     const ONLY_BUILD: bool = false;
66
67     /// Primary function to execute this rule. Can call `builder.ensure(...)`
68     /// with other steps to run those.
69     fn run(self, builder: &Builder) -> Self::Output;
70
71     /// When bootstrap is passed a set of paths, this controls whether this rule
72     /// will execute. However, it does not get called in a "default" context
73     /// when we are not passed any paths; in that case, make_run is called
74     /// directly.
75     fn should_run(run: ShouldRun) -> ShouldRun;
76
77     /// Build up a "root" rule, either as a default rule or from a path passed
78     /// to us.
79     ///
80     /// When path is `None`, we are executing in a context where no paths were
81     /// passed. When `./x.py build` is run, for example, this rule could get
82     /// called if it is in the correct list below with a path of `None`.
83     fn make_run(_run: RunConfig) {
84         // It is reasonable to not have an implementation of make_run for rules
85         // who do not want to get called from the root context. This means that
86         // they are likely dependencies (e.g., sysroot creation) or similar, and
87         // as such calling them from ./x.py isn't logical.
88         unimplemented!()
89     }
90 }
91
92 pub struct RunConfig<'a> {
93     pub builder: &'a Builder<'a>,
94     pub host: Interned<String>,
95     pub target: Interned<String>,
96     pub path: Option<&'a Path>,
97 }
98
99 struct StepDescription {
100     default: bool,
101     only_hosts: bool,
102     only_build_targets: bool,
103     only_build: bool,
104     should_run: fn(ShouldRun) -> ShouldRun,
105     make_run: fn(RunConfig),
106 }
107
108 impl StepDescription {
109     fn from<S: Step>() -> StepDescription {
110         StepDescription {
111             default: S::DEFAULT,
112             only_hosts: S::ONLY_HOSTS,
113             only_build_targets: S::ONLY_BUILD_TARGETS,
114             only_build: S::ONLY_BUILD,
115             should_run: S::should_run,
116             make_run: S::make_run,
117         }
118     }
119
120     fn maybe_run(&self, builder: &Builder, path: Option<&Path>) {
121         let build = builder.build;
122         let hosts = if self.only_build_targets || self.only_build {
123             build.build_triple()
124         } else {
125             &build.hosts
126         };
127
128         // Determine the targets participating in this rule.
129         let targets = if self.only_hosts {
130             if build.config.run_host_only {
131                 &[]
132             } else if self.only_build {
133                 build.build_triple()
134             } else {
135                 &build.hosts
136             }
137         } else {
138             &build.targets
139         };
140
141         for host in hosts {
142             for target in targets {
143                 let run = RunConfig {
144                     builder,
145                     path,
146                     host: *host,
147                     target: *target,
148                 };
149                 (self.make_run)(run);
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,
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, tool::Rustdoc, tool::Clippy,
252                 native::Llvm, tool::Rustfmt),
253             Kind::Test => describe!(check::Tidy, check::Bootstrap, check::DefaultCompiletest,
254                 check::HostCompiletest, check::Crate, check::CrateLibrustc, check::Rustdoc,
255                 check::Linkcheck, check::Cargotest, check::Cargo, check::Rls, check::Docs,
256                 check::ErrorIndex, check::Distcheck, check::Rustfmt),
257             Kind::Bench => describe!(check::Crate, check::CrateLibrustc),
258             Kind::Doc => describe!(doc::UnstableBook, doc::UnstableBookGen, doc::TheBook,
259                 doc::Standalone, doc::Std, doc::Test, doc::Rustc, doc::ErrorIndex, doc::Nomicon,
260                 doc::Reference, doc::Rustdoc, doc::CargoBook),
261             Kind::Dist => describe!(dist::Docs, dist::Mingw, dist::Rustc, dist::DebuggerScripts,
262                 dist::Std, dist::Analysis, dist::Src, dist::PlainSourceTarball, dist::Cargo,
263                 dist::Rls, dist::Extended, dist::HashSign),
264             Kind::Install => describe!(install::Docs, install::Std, install::Cargo, install::Rls,
265                 install::Analysis, install::Src, install::Rustc),
266         }
267     }
268
269     pub fn get_help(build: &Build, subcommand: &str) -> Option<String> {
270         let kind = match subcommand {
271             "build" => Kind::Build,
272             "doc" => Kind::Doc,
273             "test" => Kind::Test,
274             "bench" => Kind::Bench,
275             "dist" => Kind::Dist,
276             "install" => Kind::Install,
277             _ => return None,
278         };
279
280         let builder = Builder {
281             build,
282             top_stage: build.config.stage.unwrap_or(2),
283             kind,
284             cache: Cache::new(),
285             stack: RefCell::new(Vec::new()),
286         };
287
288         let builder = &builder;
289         let mut should_run = ShouldRun::new(builder);
290         for desc in Builder::get_step_descriptions(builder.kind) {
291             should_run = (desc.should_run)(should_run);
292         }
293         let mut help = String::from("Available paths:\n");
294         for path in should_run.paths {
295             help.push_str(format!("    ./x.py {} {}\n", subcommand, path.display()).as_str());
296         }
297         Some(help)
298     }
299
300     pub fn run(build: &Build) {
301         let (kind, paths) = match build.config.cmd {
302             Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
303             Subcommand::Doc { ref paths } => (Kind::Doc, &paths[..]),
304             Subcommand::Test { ref paths, .. } => (Kind::Test, &paths[..]),
305             Subcommand::Bench { ref paths, .. } => (Kind::Bench, &paths[..]),
306             Subcommand::Dist { ref paths } => (Kind::Dist, &paths[..]),
307             Subcommand::Install { ref paths } => (Kind::Install, &paths[..]),
308             Subcommand::Clean => panic!(),
309         };
310
311         let builder = Builder {
312             build,
313             top_stage: build.config.stage.unwrap_or(2),
314             kind,
315             cache: Cache::new(),
316             stack: RefCell::new(Vec::new()),
317         };
318
319         StepDescription::run(&Builder::get_step_descriptions(builder.kind), &builder, paths);
320     }
321
322     pub fn default_doc(&self, paths: Option<&[PathBuf]>) {
323         let paths = paths.unwrap_or(&[]);
324         StepDescription::run(&Builder::get_step_descriptions(Kind::Doc), self, paths);
325     }
326
327     /// Obtain a compiler at a given stage and for a given host. Explicitly does
328     /// not take `Compiler` since all `Compiler` instances are meant to be
329     /// obtained through this function, since it ensures that they are valid
330     /// (i.e., built and assembled).
331     pub fn compiler(&self, stage: u32, host: Interned<String>) -> Compiler {
332         self.ensure(compile::Assemble { target_compiler: Compiler { stage, host } })
333     }
334
335     pub fn sysroot(&self, compiler: Compiler) -> Interned<PathBuf> {
336         self.ensure(compile::Sysroot { compiler })
337     }
338
339     /// Returns the libdir where the standard library and other artifacts are
340     /// found for a compiler's sysroot.
341     pub fn sysroot_libdir(
342         &self, compiler: Compiler, target: Interned<String>
343     ) -> Interned<PathBuf> {
344         #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
345         struct Libdir {
346             compiler: Compiler,
347             target: Interned<String>,
348         }
349         impl Step for Libdir {
350             type Output = Interned<PathBuf>;
351
352             fn should_run(run: ShouldRun) -> ShouldRun {
353                 run.never()
354             }
355
356             fn run(self, builder: &Builder) -> Interned<PathBuf> {
357                 let compiler = self.compiler;
358                 let lib = if compiler.stage >= 2 && builder.build.config.libdir_relative.is_some() {
359                     builder.build.config.libdir_relative.clone().unwrap()
360                 } else {
361                     PathBuf::from("lib")
362                 };
363                 let sysroot = builder.sysroot(self.compiler).join(lib)
364                     .join("rustlib").join(self.target).join("lib");
365                 let _ = fs::remove_dir_all(&sysroot);
366                 t!(fs::create_dir_all(&sysroot));
367                 INTERNER.intern_path(sysroot)
368             }
369         }
370         self.ensure(Libdir { compiler, target })
371     }
372
373     /// Returns the compiler's libdir where it stores the dynamic libraries that
374     /// it itself links against.
375     ///
376     /// For example this returns `<sysroot>/lib` on Unix and `<sysroot>/bin` on
377     /// Windows.
378     pub fn rustc_libdir(&self, compiler: Compiler) -> PathBuf {
379         if compiler.is_snapshot(self) {
380             self.build.rustc_snapshot_libdir()
381         } else {
382             self.sysroot(compiler).join(libdir(&compiler.host))
383         }
384     }
385
386     /// Adds the compiler's directory of dynamic libraries to `cmd`'s dynamic
387     /// library lookup path.
388     pub fn add_rustc_lib_path(&self, compiler: Compiler, cmd: &mut Command) {
389         // Windows doesn't need dylib path munging because the dlls for the
390         // compiler live next to the compiler and the system will find them
391         // automatically.
392         if cfg!(windows) {
393             return
394         }
395
396         add_lib_path(vec![self.rustc_libdir(compiler)], cmd);
397     }
398
399     /// Get a path to the compiler specified.
400     pub fn rustc(&self, compiler: Compiler) -> PathBuf {
401         if compiler.is_snapshot(self) {
402             self.initial_rustc.clone()
403         } else {
404             self.sysroot(compiler).join("bin").join(exe("rustc", &compiler.host))
405         }
406     }
407
408     pub fn rustdoc(&self, host: Interned<String>) -> PathBuf {
409         self.ensure(tool::Rustdoc { host })
410     }
411
412     pub fn rustdoc_cmd(&self, host: Interned<String>) -> Command {
413         let mut cmd = Command::new(&self.out.join("bootstrap/debug/rustdoc"));
414         let compiler = self.compiler(self.top_stage, host);
415         cmd
416             .env("RUSTC_STAGE", compiler.stage.to_string())
417             .env("RUSTC_SYSROOT", self.sysroot(compiler))
418             .env("RUSTC_LIBDIR", self.sysroot_libdir(compiler, self.build.build))
419             .env("CFG_RELEASE_CHANNEL", &self.build.config.channel)
420             .env("RUSTDOC_REAL", self.rustdoc(host));
421         cmd
422     }
423
424     /// Prepares an invocation of `cargo` to be run.
425     ///
426     /// This will create a `Command` that represents a pending execution of
427     /// Cargo. This cargo will be configured to use `compiler` as the actual
428     /// rustc compiler, its output will be scoped by `mode`'s output directory,
429     /// it will pass the `--target` flag for the specified `target`, and will be
430     /// executing the Cargo command `cmd`.
431     pub fn cargo(&self,
432              compiler: Compiler,
433              mode: Mode,
434              target: Interned<String>,
435              cmd: &str) -> Command {
436         let mut cargo = Command::new(&self.initial_cargo);
437         let out_dir = self.stage_out(compiler, mode);
438         cargo.env("CARGO_TARGET_DIR", out_dir)
439              .arg(cmd)
440              .arg("-j").arg(self.jobs().to_string())
441              .arg("--target").arg(target);
442
443         // FIXME: Temporary fix for https://github.com/rust-lang/cargo/issues/3005
444         // Force cargo to output binaries with disambiguating hashes in the name
445         cargo.env("__CARGO_DEFAULT_LIB_METADATA", &self.config.channel);
446
447         let stage;
448         if compiler.stage == 0 && self.local_rebuild {
449             // Assume the local-rebuild rustc already has stage1 features.
450             stage = 1;
451         } else {
452             stage = compiler.stage;
453         }
454
455         // Customize the compiler we're running. Specify the compiler to cargo
456         // as our shim and then pass it some various options used to configure
457         // how the actual compiler itself is called.
458         //
459         // These variables are primarily all read by
460         // src/bootstrap/bin/{rustc.rs,rustdoc.rs}
461         cargo.env("RUSTBUILD_NATIVE_DIR", self.native_dir(target))
462              .env("RUSTC", self.out.join("bootstrap/debug/rustc"))
463              .env("RUSTC_REAL", self.rustc(compiler))
464              .env("RUSTC_STAGE", stage.to_string())
465              .env("RUSTC_CODEGEN_UNITS",
466                   self.config.rust_codegen_units.to_string())
467              .env("RUSTC_DEBUG_ASSERTIONS",
468                   self.config.rust_debug_assertions.to_string())
469              .env("RUSTC_SYSROOT", self.sysroot(compiler))
470              .env("RUSTC_LIBDIR", self.rustc_libdir(compiler))
471              .env("RUSTC_RPATH", self.config.rust_rpath.to_string())
472              .env("RUSTDOC", self.out.join("bootstrap/debug/rustdoc"))
473              .env("RUSTDOC_REAL", if cmd == "doc" || cmd == "test" {
474                  self.rustdoc(compiler.host)
475              } else {
476                  PathBuf::from("/path/to/nowhere/rustdoc/not/required")
477              })
478              .env("RUSTC_FLAGS", self.rustc_flags(target).join(" "));
479
480         if mode != Mode::Tool {
481             // Tools don't get debuginfo right now, e.g. cargo and rls don't
482             // get compiled with debuginfo.
483             cargo.env("RUSTC_DEBUGINFO", self.config.rust_debuginfo.to_string())
484                  .env("RUSTC_DEBUGINFO_LINES", self.config.rust_debuginfo_lines.to_string())
485                  .env("RUSTC_FORCE_UNSTABLE", "1");
486
487             // Currently the compiler depends on crates from crates.io, and
488             // then other crates can depend on the compiler (e.g. proc-macro
489             // crates). Let's say, for example that rustc itself depends on the
490             // bitflags crate. If an external crate then depends on the
491             // bitflags crate as well, we need to make sure they don't
492             // conflict, even if they pick the same version of bitflags. We'll
493             // want to make sure that e.g. a plugin and rustc each get their
494             // own copy of bitflags.
495
496             // Cargo ensures that this works in general through the -C metadata
497             // flag. This flag will frob the symbols in the binary to make sure
498             // they're different, even though the source code is the exact
499             // same. To solve this problem for the compiler we extend Cargo's
500             // already-passed -C metadata flag with our own. Our rustc.rs
501             // wrapper around the actual rustc will detect -C metadata being
502             // passed and frob it with this extra string we're passing in.
503             cargo.env("RUSTC_METADATA_SUFFIX", "rustc");
504         }
505
506         if let Some(x) = self.crt_static(target) {
507             cargo.env("RUSTC_CRT_STATIC", x.to_string());
508         }
509
510         // Enable usage of unstable features
511         cargo.env("RUSTC_BOOTSTRAP", "1");
512         self.add_rust_test_threads(&mut cargo);
513
514         // Almost all of the crates that we compile as part of the bootstrap may
515         // have a build script, including the standard library. To compile a
516         // build script, however, it itself needs a standard library! This
517         // introduces a bit of a pickle when we're compiling the standard
518         // library itself.
519         //
520         // To work around this we actually end up using the snapshot compiler
521         // (stage0) for compiling build scripts of the standard library itself.
522         // The stage0 compiler is guaranteed to have a libstd available for use.
523         //
524         // For other crates, however, we know that we've already got a standard
525         // library up and running, so we can use the normal compiler to compile
526         // build scripts in that situation.
527         if mode == Mode::Libstd {
528             cargo.env("RUSTC_SNAPSHOT", &self.initial_rustc)
529                  .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_snapshot_libdir());
530         } else {
531             cargo.env("RUSTC_SNAPSHOT", self.rustc(compiler))
532                  .env("RUSTC_SNAPSHOT_LIBDIR", self.rustc_libdir(compiler));
533         }
534
535         // Ignore incremental modes except for stage0, since we're
536         // not guaranteeing correctness across builds if the compiler
537         // is changing under your feet.`
538         if self.config.incremental && compiler.stage == 0 {
539             let incr_dir = self.incremental_dir(compiler);
540             cargo.env("RUSTC_INCREMENTAL", incr_dir);
541         }
542
543         if let Some(ref on_fail) = self.config.on_fail {
544             cargo.env("RUSTC_ON_FAIL", on_fail);
545         }
546
547         cargo.env("RUSTC_VERBOSE", format!("{}", self.verbosity));
548
549         // Specify some various options for build scripts used throughout
550         // the build.
551         //
552         // FIXME: the guard against msvc shouldn't need to be here
553         if !target.contains("msvc") {
554             cargo.env(format!("CC_{}", target), self.cc(target))
555                  .env(format!("AR_{}", target), self.ar(target).unwrap()) // only msvc is None
556                  .env(format!("CFLAGS_{}", target), self.cflags(target).join(" "));
557
558             if let Ok(cxx) = self.cxx(target) {
559                  cargo.env(format!("CXX_{}", target), cxx);
560             }
561         }
562
563         if mode == Mode::Libstd && self.config.extended && compiler.is_final_stage(self) {
564             cargo.env("RUSTC_SAVE_ANALYSIS", "api".to_string());
565         }
566
567         // Environment variables *required* throughout the build
568         //
569         // FIXME: should update code to not require this env var
570         cargo.env("CFG_COMPILER_HOST_TRIPLE", target);
571
572         // Set this for all builds to make sure doc builds also get it.
573         cargo.env("CFG_RELEASE_CHANNEL", &self.build.config.channel);
574
575         if self.is_verbose() {
576             cargo.arg("-v");
577         }
578         // FIXME: cargo bench does not accept `--release`
579         if self.config.rust_optimize && cmd != "bench" {
580             cargo.arg("--release");
581         }
582         if self.config.locked_deps {
583             cargo.arg("--locked");
584         }
585         if self.config.vendor || self.is_sudo {
586             cargo.arg("--frozen");
587         }
588
589         self.ci_env.force_coloring_in_ci(&mut cargo);
590
591         cargo
592     }
593
594     /// Ensure that a given step is built, returning it's output. This will
595     /// cache the step, so it is safe (and good!) to call this as often as
596     /// needed to ensure that all dependencies are built.
597     pub fn ensure<S: Step>(&'a self, step: S) -> S::Output {
598         {
599             let mut stack = self.stack.borrow_mut();
600             for stack_step in stack.iter() {
601                 // should skip
602                 if stack_step.downcast_ref::<S>().map_or(true, |stack_step| *stack_step != step) {
603                     continue;
604                 }
605                 let mut out = String::new();
606                 out += &format!("\n\nCycle in build detected when adding {:?}\n", step);
607                 for el in stack.iter().rev() {
608                     out += &format!("\t{:?}\n", el);
609                 }
610                 panic!(out);
611             }
612             if let Some(out) = self.cache.get(&step) {
613                 self.build.verbose(&format!("{}c {:?}", "  ".repeat(stack.len()), step));
614
615                 return out;
616             }
617             self.build.verbose(&format!("{}> {:?}", "  ".repeat(stack.len()), step));
618             stack.push(Box::new(step.clone()));
619         }
620         let out = step.clone().run(self);
621         {
622             let mut stack = self.stack.borrow_mut();
623             let cur_step = stack.pop().expect("step stack empty");
624             assert_eq!(cur_step.downcast_ref(), Some(&step));
625         }
626         self.build.verbose(&format!("{}< {:?}", "  ".repeat(self.stack.borrow().len()), step));
627         self.cache.put(step, out.clone());
628         out
629     }
630 }