]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/step.rs
Auto merge of #38702 - philipc:debuginfo-lldb, r=alexcrichton
[rust.git] / src / bootstrap / step.rs
1 // Copyright 2016 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 //! Definition of steps of the build system.
12 //!
13 //! This is where some of the real meat of rustbuild is located, in how we
14 //! define targets and the dependencies amongst them. This file can sort of be
15 //! viewed as just defining targets in a makefile which shell out to predefined
16 //! functions elsewhere about how to execute the target.
17 //!
18 //! The primary function here you're likely interested in is the `build_rules`
19 //! function. This will create a `Rules` structure which basically just lists
20 //! everything that rustbuild can do. Each rule has a human-readable name, a
21 //! path associated with it, some dependencies, and then a closure of how to
22 //! actually perform the rule.
23 //!
24 //! All steps below are defined in self-contained units, so adding a new target
25 //! to the build system should just involve adding the meta information here
26 //! along with the actual implementation elsewhere. You can find more comments
27 //! about how to define rules themselves below.
28
29 use std::collections::{HashMap, HashSet};
30 use std::mem;
31
32 use check::{self, TestKind};
33 use compile;
34 use dist;
35 use doc;
36 use flags::Subcommand;
37 use install;
38 use native;
39 use {Compiler, Build, Mode};
40
41 pub fn run(build: &Build) {
42     let rules = build_rules(build);
43     let steps = rules.plan();
44     rules.run(&steps);
45 }
46
47 pub fn build_rules<'a>(build: &'a Build) -> Rules {
48     let mut rules = Rules::new(build);
49
50     // This is the first rule that we're going to define for rustbuild, which is
51     // used to compile LLVM itself. All rules are added through the `rules`
52     // structure created above and are configured through a builder-style
53     // interface.
54     //
55     // First up we see the `build` method. This represents a rule that's part of
56     // the top-level `build` subcommand. For example `./x.py build` is what this
57     // is associating with. Note that this is normally only relevant if you flag
58     // a rule as `default`, which we'll talk about later.
59     //
60     // Next up we'll see two arguments to this method:
61     //
62     // * `llvm` - this is the "human readable" name of this target. This name is
63     //            not accessed anywhere outside this file itself (e.g. not in
64     //            the CLI nor elsewhere in rustbuild). The purpose of this is to
65     //            easily define dependencies between rules. That is, other rules
66     //            will depend on this with the name "llvm".
67     // * `src/llvm` - this is the relevant path to the rule that we're working
68     //                with. This path is the engine behind how commands like
69     //                `./x.py build src/llvm` work. This should typically point
70     //                to the relevant component, but if there's not really a
71     //                path to be assigned here you can pass something like
72     //                `path/to/nowhere` to ignore it.
73     //
74     // After we create the rule with the `build` method we can then configure
75     // various aspects of it. For example this LLVM rule uses `.host(true)` to
76     // flag that it's a rule only for host targets. In other words, LLVM isn't
77     // compiled for targets configured through `--target` (e.g. those we're just
78     // building a standard library for).
79     //
80     // Next up the `dep` method will add a dependency to this rule. The closure
81     // is yielded the step that represents executing the `llvm` rule itself
82     // (containing information like stage, host, target, ...) and then it must
83     // return a target that the step depends on. Here LLVM is actually
84     // interesting where a cross-compiled LLVM depends on the host LLVM, but
85     // otherwise it has no dependencies.
86     //
87     // To handle this we do a bit of dynamic dispatch to see what the dependency
88     // is. If we're building a LLVM for the build triple, then we don't actually
89     // have any dependencies! To do that we return a dependency on the `Step::noop()`
90     // target which does nothing.
91     //
92     // If we're build a cross-compiled LLVM, however, we need to assemble the
93     // libraries from the previous compiler. This step has the same name as
94     // ours (llvm) but we want it for a different target, so we use the
95     // builder-style methods on `Step` to configure this target to the build
96     // triple.
97     //
98     // Finally, to finish off this rule, we define how to actually execute it.
99     // That logic is all defined in the `native` module so we just delegate to
100     // the relevant function there. The argument to the closure passed to `run`
101     // is a `Step` (defined below) which encapsulates information like the
102     // stage, target, host, etc.
103     rules.build("llvm", "src/llvm")
104          .host(true)
105          .dep(move |s| {
106              if s.target == build.config.build {
107                  Step::noop()
108              } else {
109                  s.target(&build.config.build)
110              }
111          })
112          .run(move |s| native::llvm(build, s.target));
113
114     // Ok! After that example rule  that's hopefully enough to explain what's
115     // going on here. You can check out the API docs below and also see a bunch
116     // more examples of rules directly below as well.
117
118     // the compiler with no target libraries ready to go
119     rules.build("rustc", "src/rustc")
120          .dep(|s| s.name("create-sysroot").target(s.host))
121          .dep(move |s| {
122              if s.stage == 0 {
123                  Step::noop()
124              } else {
125                  s.name("librustc")
126                   .host(&build.config.build)
127                   .stage(s.stage - 1)
128              }
129          })
130          .run(move |s| compile::assemble_rustc(build, s.stage, s.target));
131
132     // Helper for loading an entire DAG of crates, rooted at `name`
133     let krates = |name: &str| {
134         let mut ret = Vec::new();
135         let mut list = vec![name];
136         let mut visited = HashSet::new();
137         while let Some(krate) = list.pop() {
138             let default = krate == name;
139             let krate = &build.crates[krate];
140             let path = krate.path.strip_prefix(&build.src).unwrap();
141             ret.push((krate, path.to_str().unwrap(), default));
142             for dep in krate.deps.iter() {
143                 if visited.insert(dep) && dep != "build_helper" {
144                     list.push(dep);
145                 }
146             }
147         }
148         return ret
149     };
150
151     // ========================================================================
152     // Crate compilations
153     //
154     // Tools used during the build system but not shipped
155     rules.build("create-sysroot", "path/to/nowhere")
156          .run(move |s| compile::create_sysroot(build, &s.compiler()));
157
158     // These rules are "pseudo rules" that don't actually do any work
159     // themselves, but represent a complete sysroot with the relevant compiler
160     // linked into place.
161     //
162     // That is, depending on "libstd" means that when the rule is completed then
163     // the `stage` sysroot for the compiler `host` will be available with a
164     // standard library built for `target` linked in place. Not all rules need
165     // the compiler itself to be available, just the standard library, so
166     // there's a distinction between the two.
167     rules.build("libstd", "src/libstd")
168          .dep(|s| s.name("rustc").target(s.host))
169          .dep(|s| s.name("libstd-link"));
170     rules.build("libtest", "src/libtest")
171          .dep(|s| s.name("libstd"))
172          .dep(|s| s.name("libtest-link"))
173          .default(true);
174     rules.build("librustc", "src/librustc")
175          .dep(|s| s.name("libtest"))
176          .dep(|s| s.name("librustc-link"))
177          .host(true)
178          .default(true);
179
180     // Helper method to define the rules to link a crate into its place in the
181     // sysroot.
182     //
183     // The logic here is a little subtle as there's a few cases to consider.
184     // Not all combinations of (stage, host, target) actually require something
185     // to be compiled, but rather libraries could get propagated from a
186     // different location. For example:
187     //
188     // * Any crate with a `host` that's not the build triple will not actually
189     //   compile something. A different `host` means that the build triple will
190     //   actually compile the libraries, and then we'll copy them over from the
191     //   build triple to the `host` directory.
192     //
193     // * Some crates aren't even compiled by the build triple, but may be copied
194     //   from previous stages. For example if we're not doing a full bootstrap
195     //   then we may just depend on the stage1 versions of libraries to be
196     //   available to get linked forward.
197     //
198     // * Finally, there are some cases, however, which do indeed comiple crates
199     //   and link them into place afterwards.
200     //
201     // The rule definition below mirrors these three cases. The `dep` method
202     // calculates the correct dependency which either comes from stage1, a
203     // different compiler, or from actually building the crate itself (the `dep`
204     // rule). The `run` rule then mirrors these three cases and links the cases
205     // forward into the compiler sysroot specified from the correct location.
206     fn crate_rule<'a, 'b>(build: &'a Build,
207                           rules: &'b mut Rules<'a>,
208                           krate: &'a str,
209                           dep: &'a str,
210                           link: fn(&Build, &Compiler, &Compiler, &str))
211                           -> RuleBuilder<'a, 'b> {
212         let mut rule = rules.build(&krate, "path/to/nowhere");
213         rule.dep(move |s| {
214                 if build.force_use_stage1(&s.compiler(), s.target) {
215                     s.host(&build.config.build).stage(1)
216                 } else if s.host == build.config.build {
217                     s.name(dep)
218                 } else {
219                     s.host(&build.config.build)
220                 }
221             })
222             .run(move |s| {
223                 if build.force_use_stage1(&s.compiler(), s.target) {
224                     link(build,
225                          &s.stage(1).host(&build.config.build).compiler(),
226                          &s.compiler(),
227                          s.target)
228                 } else if s.host == build.config.build {
229                     link(build, &s.compiler(), &s.compiler(), s.target)
230                 } else {
231                     link(build,
232                          &s.host(&build.config.build).compiler(),
233                          &s.compiler(),
234                          s.target)
235                 }
236             });
237             return rule
238     }
239
240     // Similar to the `libstd`, `libtest`, and `librustc` rules above, except
241     // these rules only represent the libraries being available in the sysroot,
242     // not the compiler itself. This is done as not all rules need a compiler in
243     // the sysroot, but may just need the libraries.
244     //
245     // All of these rules use the helper definition above.
246     crate_rule(build,
247                &mut rules,
248                "libstd-link",
249                "build-crate-std_shim",
250                compile::std_link)
251         .dep(|s| s.name("startup-objects"))
252         .dep(|s| s.name("create-sysroot").target(s.host));
253     crate_rule(build,
254                &mut rules,
255                "libtest-link",
256                "build-crate-test_shim",
257                compile::test_link)
258         .dep(|s| s.name("libstd-link"));
259     crate_rule(build,
260                &mut rules,
261                "librustc-link",
262                "build-crate-rustc-main",
263                compile::rustc_link)
264         .dep(|s| s.name("libtest-link"));
265
266     for (krate, path, _default) in krates("std_shim") {
267         rules.build(&krate.build_step, path)
268              .dep(|s| s.name("startup-objects"))
269              .dep(move |s| s.name("rustc").host(&build.config.build).target(s.host))
270              .run(move |s| compile::std(build, s.target, &s.compiler()));
271     }
272     for (krate, path, _default) in krates("test_shim") {
273         rules.build(&krate.build_step, path)
274              .dep(|s| s.name("libstd-link"))
275              .run(move |s| compile::test(build, s.target, &s.compiler()));
276     }
277     for (krate, path, _default) in krates("rustc-main") {
278         rules.build(&krate.build_step, path)
279              .dep(|s| s.name("libtest-link"))
280              .dep(move |s| s.name("llvm").host(&build.config.build).stage(0))
281              .run(move |s| compile::rustc(build, s.target, &s.compiler()));
282     }
283
284     rules.build("startup-objects", "src/rtstartup")
285          .dep(|s| s.name("create-sysroot").target(s.host))
286          .run(move |s| compile::build_startup_objects(build, &s.compiler(), s.target));
287
288     // ========================================================================
289     // Test targets
290     //
291     // Various unit tests and tests suites we can run
292     {
293         let mut suite = |name, path, mode, dir| {
294             rules.test(name, path)
295                  .dep(|s| s.name("libtest"))
296                  .dep(|s| s.name("tool-compiletest").target(s.host).stage(0))
297                  .dep(|s| s.name("test-helpers"))
298                  .dep(|s| s.name("android-copy-libs"))
299                  .default(mode != "pretty") // pretty tests don't run everywhere
300                  .run(move |s| {
301                      check::compiletest(build, &s.compiler(), s.target, mode, dir)
302                  });
303         };
304
305         suite("check-rpass", "src/test/run-pass", "run-pass", "run-pass");
306         suite("check-cfail", "src/test/compile-fail", "compile-fail", "compile-fail");
307         suite("check-pfail", "src/test/parse-fail", "parse-fail", "parse-fail");
308         suite("check-rfail", "src/test/run-fail", "run-fail", "run-fail");
309         suite("check-rpass-valgrind", "src/test/run-pass-valgrind",
310               "run-pass-valgrind", "run-pass-valgrind");
311         suite("check-mir-opt", "src/test/mir-opt", "mir-opt", "mir-opt");
312         if build.config.codegen_tests {
313             suite("check-codegen", "src/test/codegen", "codegen", "codegen");
314         }
315         suite("check-codegen-units", "src/test/codegen-units", "codegen-units",
316               "codegen-units");
317         suite("check-incremental", "src/test/incremental", "incremental",
318               "incremental");
319         suite("check-ui", "src/test/ui", "ui", "ui");
320     }
321
322     if build.config.build.contains("msvc") {
323         // nothing to do for debuginfo tests
324     } else {
325         rules.test("check-debuginfo-lldb", "src/test/debuginfo-lldb")
326              .dep(|s| s.name("libtest"))
327              .dep(|s| s.name("tool-compiletest").target(s.host).stage(0))
328              .dep(|s| s.name("test-helpers"))
329              .dep(|s| s.name("debugger-scripts"))
330              .run(move |s| check::compiletest(build, &s.compiler(), s.target,
331                                          "debuginfo-lldb", "debuginfo"));
332         rules.test("check-debuginfo-gdb", "src/test/debuginfo-gdb")
333              .dep(|s| s.name("libtest"))
334              .dep(|s| s.name("tool-compiletest").target(s.host).stage(0))
335              .dep(|s| s.name("test-helpers"))
336              .dep(|s| s.name("debugger-scripts"))
337              .dep(|s| s.name("android-copy-libs"))
338              .run(move |s| check::compiletest(build, &s.compiler(), s.target,
339                                          "debuginfo-gdb", "debuginfo"));
340         let mut rule = rules.test("check-debuginfo", "src/test/debuginfo");
341         rule.default(true);
342         if build.config.build.contains("apple") {
343             rule.dep(|s| s.name("check-debuginfo-lldb"));
344         } else {
345             rule.dep(|s| s.name("check-debuginfo-gdb"));
346         }
347     }
348
349     rules.test("debugger-scripts", "src/etc/lldb_batchmode.py")
350          .run(move |s| dist::debugger_scripts(build, &build.sysroot(&s.compiler()),
351                                          s.target));
352
353     {
354         let mut suite = |name, path, mode, dir| {
355             rules.test(name, path)
356                  .dep(|s| s.name("librustc"))
357                  .dep(|s| s.name("test-helpers"))
358                  .dep(|s| s.name("tool-compiletest").target(s.host).stage(0))
359                  .default(mode != "pretty")
360                  .host(true)
361                  .run(move |s| {
362                      check::compiletest(build, &s.compiler(), s.target, mode, dir)
363                  });
364         };
365
366         suite("check-rpass-full", "src/test/run-pass-fulldeps",
367               "run-pass", "run-pass-fulldeps");
368         suite("check-cfail-full", "src/test/compile-fail-fulldeps",
369               "compile-fail", "compile-fail-fulldeps");
370         suite("check-rmake", "src/test/run-make", "run-make", "run-make");
371         suite("check-rustdoc", "src/test/rustdoc", "rustdoc", "rustdoc");
372         suite("check-pretty", "src/test/pretty", "pretty", "pretty");
373         suite("check-pretty-rpass", "src/test/run-pass/pretty", "pretty",
374               "run-pass");
375         suite("check-pretty-rfail", "src/test/run-fail/pretty", "pretty",
376               "run-fail");
377         suite("check-pretty-valgrind", "src/test/run-pass-valgrind/pretty", "pretty",
378               "run-pass-valgrind");
379         suite("check-pretty-rpass-full", "src/test/run-pass-fulldeps/pretty",
380               "pretty", "run-pass-fulldeps");
381         suite("check-pretty-rfail-full", "src/test/run-fail-fulldeps/pretty",
382               "pretty", "run-fail-fulldeps");
383     }
384
385     for (krate, path, _default) in krates("std_shim") {
386         rules.test(&krate.test_step, path)
387              .dep(|s| s.name("libtest"))
388              .dep(|s| s.name("android-copy-libs"))
389              .run(move |s| check::krate(build, &s.compiler(), s.target,
390                                         Mode::Libstd, TestKind::Test,
391                                         Some(&krate.name)));
392     }
393     rules.test("check-std-all", "path/to/nowhere")
394          .dep(|s| s.name("libtest"))
395          .dep(|s| s.name("android-copy-libs"))
396          .default(true)
397          .run(move |s| check::krate(build, &s.compiler(), s.target,
398                                     Mode::Libstd, TestKind::Test, None));
399
400     // std benchmarks
401     for (krate, path, _default) in krates("std_shim") {
402         rules.bench(&krate.bench_step, path)
403              .dep(|s| s.name("libtest"))
404              .dep(|s| s.name("android-copy-libs"))
405              .run(move |s| check::krate(build, &s.compiler(), s.target,
406                                         Mode::Libstd, TestKind::Bench,
407                                         Some(&krate.name)));
408     }
409     rules.bench("bench-std-all", "path/to/nowhere")
410          .dep(|s| s.name("libtest"))
411          .dep(|s| s.name("android-copy-libs"))
412          .default(true)
413          .run(move |s| check::krate(build, &s.compiler(), s.target,
414                                     Mode::Libstd, TestKind::Bench, None));
415
416     for (krate, path, _default) in krates("test_shim") {
417         rules.test(&krate.test_step, path)
418              .dep(|s| s.name("libtest"))
419              .dep(|s| s.name("android-copy-libs"))
420              .run(move |s| check::krate(build, &s.compiler(), s.target,
421                                         Mode::Libtest, TestKind::Test,
422                                         Some(&krate.name)));
423     }
424     rules.test("check-test-all", "path/to/nowhere")
425          .dep(|s| s.name("libtest"))
426          .dep(|s| s.name("android-copy-libs"))
427          .default(true)
428          .run(move |s| check::krate(build, &s.compiler(), s.target,
429                                     Mode::Libtest, TestKind::Test, None));
430     for (krate, path, _default) in krates("rustc-main") {
431         rules.test(&krate.test_step, path)
432              .dep(|s| s.name("librustc"))
433              .dep(|s| s.name("android-copy-libs"))
434              .host(true)
435              .run(move |s| check::krate(build, &s.compiler(), s.target,
436                                         Mode::Librustc, TestKind::Test,
437                                         Some(&krate.name)));
438     }
439     rules.test("check-rustc-all", "path/to/nowhere")
440          .dep(|s| s.name("librustc"))
441          .dep(|s| s.name("android-copy-libs"))
442          .default(true)
443          .host(true)
444          .run(move |s| check::krate(build, &s.compiler(), s.target,
445                                     Mode::Librustc, TestKind::Test, None));
446
447     rules.test("check-linkchecker", "src/tools/linkchecker")
448          .dep(|s| s.name("tool-linkchecker").stage(0))
449          .dep(|s| s.name("default:doc"))
450          .default(true)
451          .host(true)
452          .run(move |s| check::linkcheck(build, s.target));
453     rules.test("check-cargotest", "src/tools/cargotest")
454          .dep(|s| s.name("tool-cargotest").stage(0))
455          .dep(|s| s.name("librustc"))
456          .host(true)
457          .run(move |s| check::cargotest(build, s.stage, s.target));
458     rules.test("check-tidy", "src/tools/tidy")
459          .dep(|s| s.name("tool-tidy").stage(0))
460          .default(true)
461          .host(true)
462          .run(move |s| check::tidy(build, s.target));
463     rules.test("check-error-index", "src/tools/error_index_generator")
464          .dep(|s| s.name("libstd"))
465          .dep(|s| s.name("tool-error-index").host(s.host).stage(0))
466          .default(true)
467          .host(true)
468          .run(move |s| check::error_index(build, &s.compiler()));
469     rules.test("check-docs", "src/doc")
470          .dep(|s| s.name("libtest"))
471          .default(true)
472          .host(true)
473          .run(move |s| check::docs(build, &s.compiler()));
474     rules.test("check-distcheck", "distcheck")
475          .dep(|s| s.name("dist-src"))
476          .run(move |_| check::distcheck(build));
477
478
479     rules.build("test-helpers", "src/rt/rust_test_helpers.c")
480          .run(move |s| native::test_helpers(build, s.target));
481     rules.test("android-copy-libs", "path/to/nowhere")
482          .dep(|s| s.name("libtest"))
483          .run(move |s| check::android_copy_libs(build, &s.compiler(), s.target));
484
485     // ========================================================================
486     // Build tools
487     //
488     // Tools used during the build system but not shipped
489     rules.build("tool-rustbook", "src/tools/rustbook")
490          .dep(|s| s.name("librustc"))
491          .run(move |s| compile::tool(build, s.stage, s.target, "rustbook"));
492     rules.build("tool-error-index", "src/tools/error_index_generator")
493          .dep(|s| s.name("librustc"))
494          .run(move |s| compile::tool(build, s.stage, s.target, "error_index_generator"));
495     rules.build("tool-tidy", "src/tools/tidy")
496          .dep(|s| s.name("libstd"))
497          .run(move |s| compile::tool(build, s.stage, s.target, "tidy"));
498     rules.build("tool-linkchecker", "src/tools/linkchecker")
499          .dep(|s| s.name("libstd"))
500          .run(move |s| compile::tool(build, s.stage, s.target, "linkchecker"));
501     rules.build("tool-cargotest", "src/tools/cargotest")
502          .dep(|s| s.name("libstd"))
503          .run(move |s| compile::tool(build, s.stage, s.target, "cargotest"));
504     rules.build("tool-compiletest", "src/tools/compiletest")
505          .dep(|s| s.name("libtest"))
506          .run(move |s| compile::tool(build, s.stage, s.target, "compiletest"));
507
508     // ========================================================================
509     // Documentation targets
510     rules.doc("doc-book", "src/doc/book")
511          .dep(move |s| s.name("tool-rustbook").target(&build.config.build).stage(0))
512          .default(build.config.docs)
513          .run(move |s| doc::rustbook(build, s.target, "book"));
514     rules.doc("doc-nomicon", "src/doc/nomicon")
515          .dep(move |s| s.name("tool-rustbook").target(&build.config.build).stage(0))
516          .default(build.config.docs)
517          .run(move |s| doc::rustbook(build, s.target, "nomicon"));
518     rules.doc("doc-standalone", "src/doc")
519          .dep(move |s| s.name("rustc").host(&build.config.build).target(&build.config.build))
520          .default(build.config.docs)
521          .run(move |s| doc::standalone(build, s.stage, s.target));
522     rules.doc("doc-error-index", "src/tools/error_index_generator")
523          .dep(move |s| s.name("tool-error-index").target(&build.config.build).stage(0))
524          .dep(move |s| s.name("librustc-link").stage(0))
525          .default(build.config.docs)
526          .host(true)
527          .run(move |s| doc::error_index(build, s.target));
528     for (krate, path, default) in krates("std_shim") {
529         rules.doc(&krate.doc_step, path)
530              .dep(|s| s.name("libstd-link"))
531              .default(default && build.config.docs)
532              .run(move |s| doc::std(build, s.stage, s.target));
533     }
534     for (krate, path, default) in krates("test_shim") {
535         rules.doc(&krate.doc_step, path)
536              .dep(|s| s.name("libtest-link"))
537              .default(default && build.config.compiler_docs)
538              .run(move |s| doc::test(build, s.stage, s.target));
539     }
540     for (krate, path, default) in krates("rustc-main") {
541         rules.doc(&krate.doc_step, path)
542              .dep(|s| s.name("librustc-link"))
543              .host(true)
544              .default(default && build.config.compiler_docs)
545              .run(move |s| doc::rustc(build, s.stage, s.target));
546     }
547
548     // ========================================================================
549     // Distribution targets
550     rules.dist("dist-rustc", "src/librustc")
551          .dep(move |s| s.name("rustc").host(&build.config.build))
552          .host(true)
553          .default(true)
554          .run(move |s| dist::rustc(build, s.stage, s.target));
555     rules.dist("dist-std", "src/libstd")
556          .dep(move |s| {
557              // We want to package up as many target libraries as possible
558              // for the `rust-std` package, so if this is a host target we
559              // depend on librustc and otherwise we just depend on libtest.
560              if build.config.host.iter().any(|t| t == s.target) {
561                  s.name("librustc-link")
562              } else {
563                  s.name("libtest-link")
564              }
565          })
566          .default(true)
567          .run(move |s| dist::std(build, &s.compiler(), s.target));
568     rules.dist("dist-mingw", "path/to/nowhere")
569          .default(true)
570          .run(move |s| {
571              if s.target.contains("pc-windows-gnu") {
572                  dist::mingw(build, s.target)
573              }
574          });
575     rules.dist("dist-src", "src")
576          .default(true)
577          .host(true)
578          .run(move |s| dist::rust_src(build, s.target));
579     rules.dist("dist-docs", "src/doc")
580          .default(true)
581          .dep(|s| s.name("default:doc"))
582          .run(move |s| dist::docs(build, s.stage, s.target));
583     rules.dist("dist-analysis", "analysis")
584          .dep(|s| s.name("dist-std"))
585          .default(true)
586          .run(move |s| dist::analysis(build, &s.compiler(), s.target));
587     rules.dist("install", "src")
588          .dep(|s| s.name("default:dist"))
589          .run(move |s| install::install(build, s.stage, s.target));
590
591     rules.verify();
592     return rules;
593 }
594
595 #[derive(PartialEq, Eq, Hash, Clone, Debug)]
596 struct Step<'a> {
597     /// Human readable name of the rule this step is executing. Possible names
598     /// are all defined above in `build_rules`.
599     name: &'a str,
600
601     /// The stage this step is executing in. This is typically 0, 1, or 2.
602     stage: u32,
603
604     /// This step will likely involve a compiler, and the target that compiler
605     /// itself is built for is called the host, this variable. Typically this is
606     /// the target of the build machine itself.
607     host: &'a str,
608
609     /// The target that this step represents generating. If you're building a
610     /// standard library for a new suite of targets, for example, this'll be set
611     /// to those targets.
612     target: &'a str,
613 }
614
615 impl<'a> Step<'a> {
616     fn noop() -> Step<'a> {
617         Step { name: "", stage: 0, host: "", target: "" }
618     }
619
620     /// Creates a new step which is the same as this, except has a new name.
621     fn name(&self, name: &'a str) -> Step<'a> {
622         Step { name: name, ..*self }
623     }
624
625     /// Creates a new step which is the same as this, except has a new stage.
626     fn stage(&self, stage: u32) -> Step<'a> {
627         Step { stage: stage, ..*self }
628     }
629
630     /// Creates a new step which is the same as this, except has a new host.
631     fn host(&self, host: &'a str) -> Step<'a> {
632         Step { host: host, ..*self }
633     }
634
635     /// Creates a new step which is the same as this, except has a new target.
636     fn target(&self, target: &'a str) -> Step<'a> {
637         Step { target: target, ..*self }
638     }
639
640     /// Returns the `Compiler` structure that this step corresponds to.
641     fn compiler(&self) -> Compiler<'a> {
642         Compiler::new(self.stage, self.host)
643     }
644 }
645
646 struct Rule<'a> {
647     /// The human readable name of this target, defined in `build_rules`.
648     name: &'a str,
649
650     /// The path associated with this target, used in the `./x.py` driver for
651     /// easy and ergonomic specification of what to do.
652     path: &'a str,
653
654     /// The "kind" of top-level command that this rule is associated with, only
655     /// relevant if this is a default rule.
656     kind: Kind,
657
658     /// List of dependencies this rule has. Each dependency is a function from a
659     /// step that's being executed to another step that should be executed.
660     deps: Vec<Box<Fn(&Step<'a>) -> Step<'a> + 'a>>,
661
662     /// How to actually execute this rule. Takes a step with contextual
663     /// information and then executes it.
664     run: Box<Fn(&Step<'a>) + 'a>,
665
666     /// Whether or not this is a "default" rule. That basically means that if
667     /// you run, for example, `./x.py test` whether it's included or not.
668     default: bool,
669
670     /// Whether or not this is a "host" rule, or in other words whether this is
671     /// only intended for compiler hosts and not for targets that are being
672     /// generated.
673     host: bool,
674 }
675
676 #[derive(PartialEq)]
677 enum Kind {
678     Build,
679     Test,
680     Bench,
681     Dist,
682     Doc,
683 }
684
685 impl<'a> Rule<'a> {
686     fn new(name: &'a str, path: &'a str, kind: Kind) -> Rule<'a> {
687         Rule {
688             name: name,
689             deps: Vec::new(),
690             run: Box::new(|_| ()),
691             path: path,
692             kind: kind,
693             default: false,
694             host: false,
695         }
696     }
697 }
698
699 /// Builder pattern returned from the various methods on `Rules` which will add
700 /// the rule to the internal list on `Drop`.
701 struct RuleBuilder<'a: 'b, 'b> {
702     rules: &'b mut Rules<'a>,
703     rule: Rule<'a>,
704 }
705
706 impl<'a, 'b> RuleBuilder<'a, 'b> {
707     fn dep<F>(&mut self, f: F) -> &mut Self
708         where F: Fn(&Step<'a>) -> Step<'a> + 'a,
709     {
710         self.rule.deps.push(Box::new(f));
711         self
712     }
713
714     fn run<F>(&mut self, f: F) -> &mut Self
715         where F: Fn(&Step<'a>) + 'a,
716     {
717         self.rule.run = Box::new(f);
718         self
719     }
720
721     fn default(&mut self, default: bool) -> &mut Self {
722         self.rule.default = default;
723         self
724     }
725
726     fn host(&mut self, host: bool) -> &mut Self {
727         self.rule.host = host;
728         self
729     }
730 }
731
732 impl<'a, 'b> Drop for RuleBuilder<'a, 'b> {
733     fn drop(&mut self) {
734         let rule = mem::replace(&mut self.rule, Rule::new("", "", Kind::Build));
735         let prev = self.rules.rules.insert(rule.name, rule);
736         if let Some(prev) = prev {
737             panic!("duplicate rule named: {}", prev.name);
738         }
739     }
740 }
741
742 pub struct Rules<'a> {
743     build: &'a Build,
744     sbuild: Step<'a>,
745     rules: HashMap<&'a str, Rule<'a>>,
746 }
747
748 impl<'a> Rules<'a> {
749     fn new(build: &'a Build) -> Rules<'a> {
750         Rules {
751             build: build,
752             sbuild: Step {
753                 stage: build.flags.stage.unwrap_or(2),
754                 target: &build.config.build,
755                 host: &build.config.build,
756                 name: "",
757             },
758             rules: HashMap::new(),
759         }
760     }
761
762     /// Creates a new rule of `Kind::Build` with the specified human readable
763     /// name and path associated with it.
764     ///
765     /// The builder returned should be configured further with information such
766     /// as how to actually run this rule.
767     fn build<'b>(&'b mut self, name: &'a str, path: &'a str)
768                  -> RuleBuilder<'a, 'b> {
769         self.rule(name, path, Kind::Build)
770     }
771
772     /// Same as `build`, but for `Kind::Test`.
773     fn test<'b>(&'b mut self, name: &'a str, path: &'a str)
774                 -> RuleBuilder<'a, 'b> {
775         self.rule(name, path, Kind::Test)
776     }
777
778     /// Same as `build`, but for `Kind::Bench`.
779     fn bench<'b>(&'b mut self, name: &'a str, path: &'a str)
780                 -> RuleBuilder<'a, 'b> {
781         self.rule(name, path, Kind::Bench)
782     }
783
784     /// Same as `build`, but for `Kind::Doc`.
785     fn doc<'b>(&'b mut self, name: &'a str, path: &'a str)
786                -> RuleBuilder<'a, 'b> {
787         self.rule(name, path, Kind::Doc)
788     }
789
790     /// Same as `build`, but for `Kind::Dist`.
791     fn dist<'b>(&'b mut self, name: &'a str, path: &'a str)
792                 -> RuleBuilder<'a, 'b> {
793         self.rule(name, path, Kind::Dist)
794     }
795
796     fn rule<'b>(&'b mut self,
797                 name: &'a str,
798                 path: &'a str,
799                 kind: Kind) -> RuleBuilder<'a, 'b> {
800         RuleBuilder {
801             rules: self,
802             rule: Rule::new(name, path, kind),
803         }
804     }
805
806     /// Verify the dependency graph defined by all our rules are correct, e.g.
807     /// everything points to a valid something else.
808     fn verify(&self) {
809         for rule in self.rules.values() {
810             for dep in rule.deps.iter() {
811                 let dep = dep(&self.sbuild.name(rule.name));
812                 if self.rules.contains_key(&dep.name) || dep.name.starts_with("default:") {
813                     continue
814                 }
815                 if dep == Step::noop() {
816                     continue
817                 }
818                 panic!("\
819
820 invalid rule dependency graph detected, was a rule added and maybe typo'd?
821
822     `{}` depends on `{}` which does not exist
823
824 ", rule.name, dep.name);
825             }
826         }
827     }
828
829     pub fn print_help(&self, command: &str) {
830         let kind = match command {
831             "build" => Kind::Build,
832             "doc" => Kind::Doc,
833             "test" => Kind::Test,
834             "bench" => Kind::Bench,
835             "dist" => Kind::Dist,
836             _ => return,
837         };
838         let rules = self.rules.values().filter(|r| r.kind == kind);
839         let rules = rules.filter(|r| !r.path.contains("nowhere"));
840         let mut rules = rules.collect::<Vec<_>>();
841         rules.sort_by_key(|r| r.path);
842
843         println!("Available paths:\n");
844         for rule in rules {
845             print!("    ./x.py {} {}", command, rule.path);
846
847             println!("");
848         }
849     }
850
851     /// Construct the top-level build steps that we're going to be executing,
852     /// given the subcommand that our build is performing.
853     fn plan(&self) -> Vec<Step<'a>> {
854         // Ok, the logic here is pretty subtle, and involves quite a few
855         // conditionals. The basic idea here is to:
856         //
857         // 1. First, filter all our rules to the relevant ones. This means that
858         //    the command specified corresponds to one of our `Kind` variants,
859         //    and we filter all rules based on that.
860         //
861         // 2. Next, we determine which rules we're actually executing. If a
862         //    number of path filters were specified on the command line we look
863         //    for those, otherwise we look for anything tagged `default`.
864         //
865         // 3. Finally, we generate some steps with host and target information.
866         //
867         // The last step is by far the most complicated and subtle. The basic
868         // thinking here is that we want to take the cartesian product of
869         // specified hosts and targets and build rules with that. The list of
870         // hosts and targets, if not specified, come from the how this build was
871         // configured. If the rule we're looking at is a host-only rule the we
872         // ignore the list of targets and instead consider the list of hosts
873         // also the list of targets.
874         //
875         // Once the host and target lists are generated we take the cartesian
876         // product of the two and then create a step based off them. Note that
877         // the stage each step is associated was specified with the `--step`
878         // flag on the command line.
879         let (kind, paths) = match self.build.flags.cmd {
880             Subcommand::Build { ref paths } => (Kind::Build, &paths[..]),
881             Subcommand::Doc { ref paths } => (Kind::Doc, &paths[..]),
882             Subcommand::Test { ref paths, test_args: _ } => (Kind::Test, &paths[..]),
883             Subcommand::Bench { ref paths, test_args: _ } => (Kind::Bench, &paths[..]),
884             Subcommand::Dist { install } => {
885                 if install {
886                     return vec![self.sbuild.name("install")]
887                 } else {
888                     (Kind::Dist, &[][..])
889                 }
890             }
891             Subcommand::Clean => panic!(),
892         };
893
894         self.rules.values().filter(|rule| rule.kind == kind).filter(|rule| {
895             (paths.len() == 0 && rule.default) || paths.iter().any(|path| {
896                 path.ends_with(rule.path)
897             })
898         }).flat_map(|rule| {
899             let hosts = if self.build.flags.host.len() > 0 {
900                 &self.build.flags.host
901             } else {
902                 if kind == Kind::Dist {
903                     // For 'dist' steps we only distribute artifacts built from
904                     // the build platform, so only consider that in the hosts
905                     // array.
906                     // NOTE: This relies on the fact that the build triple is
907                     // always placed first, as done in `config.rs`.
908                     &self.build.config.host[..1]
909                 } else {
910                     &self.build.config.host
911                 }
912             };
913             let targets = if self.build.flags.target.len() > 0 {
914                 &self.build.flags.target
915             } else {
916                 &self.build.config.target
917             };
918             // Determine the actual targets participating in this rule.
919             // NOTE: We should keep the full projection from build triple to
920             // the hosts for the dist steps, now that the hosts array above is
921             // truncated to avoid duplication of work in that case. Therefore
922             // the original non-shadowed hosts array is used below.
923             let arr = if rule.host {
924                 // If --target was specified but --host wasn't specified,
925                 // don't run any host-only tests. Also, respect any `--host`
926                 // overrides as done for `hosts`.
927                 if self.build.flags.host.len() > 0 {
928                     &self.build.flags.host[..]
929                 } else if self.build.flags.target.len() > 0 {
930                     &[]
931                 } else {
932                     &self.build.config.host[..]
933                 }
934             } else {
935                 targets
936             };
937
938             hosts.iter().flat_map(move |host| {
939                 arr.iter().map(move |target| {
940                     self.sbuild.name(rule.name).target(target).host(host)
941                 })
942             })
943         }).collect()
944     }
945
946     /// Execute all top-level targets indicated by `steps`.
947     ///
948     /// This will take the list returned by `plan` and then execute each step
949     /// along with all required dependencies as it goes up the chain.
950     fn run(&self, steps: &[Step<'a>]) {
951         self.build.verbose("bootstrap top targets:");
952         for step in steps.iter() {
953             self.build.verbose(&format!("\t{:?}", step));
954         }
955
956         // Using `steps` as the top-level targets, make a topological ordering
957         // of what we need to do.
958         let mut order = Vec::new();
959         let mut added = HashSet::new();
960         added.insert(Step::noop());
961         for step in steps.iter().cloned() {
962             self.fill(step, &mut order, &mut added);
963         }
964
965         // Print out what we're doing for debugging
966         self.build.verbose("bootstrap build plan:");
967         for step in order.iter() {
968             self.build.verbose(&format!("\t{:?}", step));
969         }
970
971         // And finally, iterate over everything and execute it.
972         for step in order.iter() {
973             if self.build.flags.keep_stage.map_or(false, |s| step.stage <= s) {
974                 self.build.verbose(&format!("keeping step {:?}", step));
975                 continue;
976             }
977             self.build.verbose(&format!("executing step {:?}", step));
978             (self.rules[step.name].run)(step);
979         }
980     }
981
982     /// Performs topological sort of dependencies rooted at the `step`
983     /// specified, pushing all results onto the `order` vector provided.
984     ///
985     /// In other words, when this method returns, the `order` vector will
986     /// contain a list of steps which if executed in order will eventually
987     /// complete the `step` specified as well.
988     ///
989     /// The `added` set specified here is the set of steps that are already
990     /// present in `order` (and hence don't need to be added again).
991     fn fill(&self,
992             step: Step<'a>,
993             order: &mut Vec<Step<'a>>,
994             added: &mut HashSet<Step<'a>>) {
995         if !added.insert(step.clone()) {
996             return
997         }
998         for dep in self.rules[step.name].deps.iter() {
999             let dep = dep(&step);
1000             if dep.name.starts_with("default:") {
1001                 let kind = match &dep.name[8..] {
1002                     "doc" => Kind::Doc,
1003                     "dist" => Kind::Dist,
1004                     kind => panic!("unknown kind: `{}`", kind),
1005                 };
1006                 let host = self.build.config.host.iter().any(|h| h == dep.target);
1007                 let rules = self.rules.values().filter(|r| r.default);
1008                 for rule in rules.filter(|r| r.kind == kind && (!r.host || host)) {
1009                     self.fill(dep.name(rule.name), order, added);
1010                 }
1011             } else {
1012                 self.fill(dep, order, added);
1013             }
1014         }
1015         order.push(step);
1016     }
1017 }