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