]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/doc.rs
Auto merge of #56863 - arielb1:supertrait-self-4, r=nikomatsakis
[rust.git] / src / bootstrap / doc.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 //! Documentation generation for rustbuilder.
12 //!
13 //! This module implements generation for all bits and pieces of documentation
14 //! for the Rust project. This notably includes suites like the rust book, the
15 //! nomicon, rust by example, standalone documentation, etc.
16 //!
17 //! Everything here is basically just a shim around calling either `rustbook` or
18 //! `rustdoc`.
19
20 use std::collections::HashSet;
21 use std::fs;
22 use std::io;
23 use std::path::{PathBuf, Path};
24
25 use crate::Mode;
26 use build_helper::up_to_date;
27
28 use crate::util::symlink_dir;
29 use crate::builder::{Builder, Compiler, RunConfig, ShouldRun, Step};
30 use crate::tool::{self, prepare_tool_cargo, Tool, SourceType};
31 use crate::compile;
32 use crate::cache::{INTERNER, Interned};
33 use crate::config::Config;
34
35 macro_rules! book {
36     ($($name:ident, $path:expr, $book_name:expr;)+) => {
37         $(
38             #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
39         pub struct $name {
40             target: Interned<String>,
41         }
42
43         impl Step for $name {
44             type Output = ();
45             const DEFAULT: bool = true;
46
47             fn should_run(run: ShouldRun) -> ShouldRun {
48                 let builder = run.builder;
49                 run.path($path).default_condition(builder.config.docs)
50             }
51
52             fn make_run(run: RunConfig) {
53                 run.builder.ensure($name {
54                     target: run.target,
55                 });
56             }
57
58             fn run(self, builder: &Builder) {
59                 builder.ensure(Rustbook {
60                     target: self.target,
61                     name: INTERNER.intern_str($book_name),
62                 })
63             }
64         }
65         )+
66     }
67 }
68
69 book!(
70     Nomicon, "src/doc/nomicon", "nomicon";
71     Reference, "src/doc/reference", "reference";
72     EditionGuide, "src/doc/edition-guide", "edition-guide";
73     RustdocBook, "src/doc/rustdoc", "rustdoc";
74     RustcBook, "src/doc/rustc", "rustc";
75     RustByExample, "src/doc/rust-by-example", "rust-by-example";
76 );
77
78 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
79 struct Rustbook {
80     target: Interned<String>,
81     name: Interned<String>,
82 }
83
84 impl Step for Rustbook {
85     type Output = ();
86
87     // rustbook is never directly called, and only serves as a shim for the nomicon and the
88     // reference.
89     fn should_run(run: ShouldRun) -> ShouldRun {
90         run.never()
91     }
92
93     /// Invoke `rustbook` for `target` for the doc book `name`.
94     ///
95     /// This will not actually generate any documentation if the documentation has
96     /// already been generated.
97     fn run(self, builder: &Builder) {
98         let src = builder.src.join("src/doc");
99         builder.ensure(RustbookSrc {
100             target: self.target,
101             name: self.name,
102             src: INTERNER.intern_path(src),
103         });
104     }
105 }
106
107 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
108 pub struct UnstableBook {
109     target: Interned<String>,
110 }
111
112 impl Step for UnstableBook {
113     type Output = ();
114     const DEFAULT: bool = true;
115
116     fn should_run(run: ShouldRun) -> ShouldRun {
117         let builder = run.builder;
118         run.path("src/doc/unstable-book").default_condition(builder.config.docs)
119     }
120
121     fn make_run(run: RunConfig) {
122         run.builder.ensure(UnstableBook {
123             target: run.target,
124         });
125     }
126
127     fn run(self, builder: &Builder) {
128         builder.ensure(UnstableBookGen {
129             target: self.target,
130         });
131         builder.ensure(RustbookSrc {
132             target: self.target,
133             name: INTERNER.intern_str("unstable-book"),
134             src: builder.md_doc_out(self.target),
135         })
136     }
137 }
138
139 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
140 pub struct CargoBook {
141     target: Interned<String>,
142     name: Interned<String>,
143 }
144
145 impl Step for CargoBook {
146     type Output = ();
147     const DEFAULT: bool = true;
148
149     fn should_run(run: ShouldRun) -> ShouldRun {
150         let builder = run.builder;
151         run.path("src/tools/cargo/src/doc/book").default_condition(builder.config.docs)
152     }
153
154     fn make_run(run: RunConfig) {
155         run.builder.ensure(CargoBook {
156             target: run.target,
157             name: INTERNER.intern_str("cargo"),
158         });
159     }
160
161     fn run(self, builder: &Builder) {
162         let target = self.target;
163         let name = self.name;
164         let src = builder.src.join("src/tools/cargo/src/doc");
165
166         let out = builder.doc_out(target);
167         t!(fs::create_dir_all(&out));
168
169         let out = out.join(name);
170
171         builder.info(&format!("Cargo Book ({}) - {}", target, name));
172
173         let _ = fs::remove_dir_all(&out);
174
175         builder.run(builder.tool_cmd(Tool::Rustbook)
176                        .arg("build")
177                        .arg(&src)
178                        .arg("-d")
179                        .arg(out));
180     }
181 }
182
183 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
184 struct RustbookSrc {
185     target: Interned<String>,
186     name: Interned<String>,
187     src: Interned<PathBuf>,
188 }
189
190 impl Step for RustbookSrc {
191     type Output = ();
192
193     fn should_run(run: ShouldRun) -> ShouldRun {
194         run.never()
195     }
196
197     /// Invoke `rustbook` for `target` for the doc book `name` from the `src` path.
198     ///
199     /// This will not actually generate any documentation if the documentation has
200     /// already been generated.
201     fn run(self, builder: &Builder) {
202         let target = self.target;
203         let name = self.name;
204         let src = self.src;
205         let out = builder.doc_out(target);
206         t!(fs::create_dir_all(&out));
207
208         let out = out.join(name);
209         let src = src.join(name);
210         let index = out.join("index.html");
211         let rustbook = builder.tool_exe(Tool::Rustbook);
212         let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook);
213         if up_to_date(&src, &index) && up_to_date(&rustbook, &index) {
214             return
215         }
216         builder.info(&format!("Rustbook ({}) - {}", target, name));
217         let _ = fs::remove_dir_all(&out);
218         builder.run(rustbook_cmd
219                        .arg("build")
220                        .arg(&src)
221                        .arg("-d")
222                        .arg(out));
223     }
224 }
225
226 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
227 pub struct TheBook {
228     compiler: Compiler,
229     target: Interned<String>,
230     name: &'static str,
231 }
232
233 impl Step for TheBook {
234     type Output = ();
235     const DEFAULT: bool = true;
236
237     fn should_run(run: ShouldRun) -> ShouldRun {
238         let builder = run.builder;
239         run.path("src/doc/book").default_condition(builder.config.docs)
240     }
241
242     fn make_run(run: RunConfig) {
243         run.builder.ensure(TheBook {
244             compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
245             target: run.target,
246             name: "book",
247         });
248     }
249
250     /// Build the book and associated stuff.
251     ///
252     /// We need to build:
253     ///
254     /// * Book (first edition)
255     /// * Book (second edition)
256     /// * Version info and CSS
257     /// * Index page
258     /// * Redirect pages
259     fn run(self, builder: &Builder) {
260         let compiler = self.compiler;
261         let target = self.target;
262         let name = self.name;
263
264         // build book
265         builder.ensure(Rustbook {
266             target,
267             name: INTERNER.intern_string(name.to_string()),
268         });
269
270         // building older edition redirects
271
272         let source_name = format!("{}/first-edition", name);
273         builder.ensure(Rustbook {
274             target,
275             name: INTERNER.intern_string(source_name),
276         });
277
278         let source_name = format!("{}/second-edition", name);
279         builder.ensure(Rustbook {
280             target,
281             name: INTERNER.intern_string(source_name),
282         });
283
284         let source_name = format!("{}/2018-edition", name);
285         builder.ensure(Rustbook {
286             target,
287             name: INTERNER.intern_string(source_name),
288         });
289
290         // build the version info page and CSS
291         builder.ensure(Standalone {
292             compiler,
293             target,
294         });
295
296         // build the redirect pages
297         builder.info(&format!("Documenting book redirect pages ({})", target));
298         for file in t!(fs::read_dir(builder.src.join("src/doc/book/redirects"))) {
299             let file = t!(file);
300             let path = file.path();
301             let path = path.to_str().unwrap();
302
303             invoke_rustdoc(builder, compiler, target, path);
304         }
305     }
306 }
307
308 fn invoke_rustdoc(builder: &Builder, compiler: Compiler, target: Interned<String>, markdown: &str) {
309     let out = builder.doc_out(target);
310
311     let path = builder.src.join("src/doc").join(markdown);
312
313     let favicon = builder.src.join("src/doc/favicon.inc");
314     let footer = builder.src.join("src/doc/footer.inc");
315     let version_info = out.join("version_info.html");
316
317     let mut cmd = builder.rustdoc_cmd(compiler.host);
318
319     let out = out.join("book");
320
321     cmd.arg("--html-after-content").arg(&footer)
322         .arg("--html-before-content").arg(&version_info)
323         .arg("--html-in-header").arg(&favicon)
324         .arg("--markdown-no-toc")
325         .arg("--markdown-playground-url")
326         .arg("https://play.rust-lang.org/")
327         .arg("-o").arg(&out)
328         .arg(&path)
329         .arg("--markdown-css")
330         .arg("../rust.css");
331
332     builder.run(&mut cmd);
333 }
334
335 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
336 pub struct Standalone {
337     compiler: Compiler,
338     target: Interned<String>,
339 }
340
341 impl Step for Standalone {
342     type Output = ();
343     const DEFAULT: bool = true;
344
345     fn should_run(run: ShouldRun) -> ShouldRun {
346         let builder = run.builder;
347         run.path("src/doc").default_condition(builder.config.docs)
348     }
349
350     fn make_run(run: RunConfig) {
351         run.builder.ensure(Standalone {
352             compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
353             target: run.target,
354         });
355     }
356
357     /// Generates all standalone documentation as compiled by the rustdoc in `stage`
358     /// for the `target` into `out`.
359     ///
360     /// This will list all of `src/doc` looking for markdown files and appropriately
361     /// perform transformations like substituting `VERSION`, `SHORT_HASH`, and
362     /// `STAMP` along with providing the various header/footer HTML we've customized.
363     ///
364     /// In the end, this is just a glorified wrapper around rustdoc!
365     fn run(self, builder: &Builder) {
366         let target = self.target;
367         let compiler = self.compiler;
368         builder.info(&format!("Documenting standalone ({})", target));
369         let out = builder.doc_out(target);
370         t!(fs::create_dir_all(&out));
371
372         let favicon = builder.src.join("src/doc/favicon.inc");
373         let footer = builder.src.join("src/doc/footer.inc");
374         let full_toc = builder.src.join("src/doc/full-toc.inc");
375         t!(fs::copy(builder.src.join("src/doc/rust.css"), out.join("rust.css")));
376
377         let version_input = builder.src.join("src/doc/version_info.html.template");
378         let version_info = out.join("version_info.html");
379
380         if !builder.config.dry_run && !up_to_date(&version_input, &version_info) {
381             let info = t!(fs::read_to_string(&version_input))
382                 .replace("VERSION", &builder.rust_release())
383                 .replace("SHORT_HASH", builder.rust_info.sha_short().unwrap_or(""))
384                 .replace("STAMP", builder.rust_info.sha().unwrap_or(""));
385             t!(fs::write(&version_info, &info));
386         }
387
388         for file in t!(fs::read_dir(builder.src.join("src/doc"))) {
389             let file = t!(file);
390             let path = file.path();
391             let filename = path.file_name().unwrap().to_str().unwrap();
392             if !filename.ends_with(".md") || filename == "README.md" {
393                 continue
394             }
395
396             let html = out.join(filename).with_extension("html");
397             let rustdoc = builder.rustdoc(compiler.host);
398             if up_to_date(&path, &html) &&
399                up_to_date(&footer, &html) &&
400                up_to_date(&favicon, &html) &&
401                up_to_date(&full_toc, &html) &&
402                up_to_date(&version_info, &html) &&
403                (builder.config.dry_run || up_to_date(&rustdoc, &html)) {
404                 continue
405             }
406
407             let mut cmd = builder.rustdoc_cmd(compiler.host);
408             cmd.arg("--html-after-content").arg(&footer)
409                .arg("--html-before-content").arg(&version_info)
410                .arg("--html-in-header").arg(&favicon)
411                .arg("--markdown-no-toc")
412                .arg("--index-page").arg(&builder.src.join("src/doc/index.md"))
413                .arg("--markdown-playground-url")
414                .arg("https://play.rust-lang.org/")
415                .arg("-o").arg(&out)
416                .arg(&path);
417
418             if filename == "not_found.md" {
419                 cmd.arg("--markdown-css")
420                    .arg("https://doc.rust-lang.org/rust.css");
421             } else {
422                 cmd.arg("--markdown-css").arg("rust.css");
423             }
424             builder.run(&mut cmd);
425         }
426     }
427 }
428
429 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
430 pub struct Std {
431     pub stage: u32,
432     pub target: Interned<String>,
433 }
434
435 impl Step for Std {
436     type Output = ();
437     const DEFAULT: bool = true;
438
439     fn should_run(run: ShouldRun) -> ShouldRun {
440         let builder = run.builder;
441         run.all_krates("std").default_condition(builder.config.docs)
442     }
443
444     fn make_run(run: RunConfig) {
445         run.builder.ensure(Std {
446             stage: run.builder.top_stage,
447             target: run.target
448         });
449     }
450
451     /// Compile all standard library documentation.
452     ///
453     /// This will generate all documentation for the standard library and its
454     /// dependencies. This is largely just a wrapper around `cargo doc`.
455     fn run(self, builder: &Builder) {
456         let stage = self.stage;
457         let target = self.target;
458         builder.info(&format!("Documenting stage{} std ({})", stage, target));
459         let out = builder.doc_out(target);
460         t!(fs::create_dir_all(&out));
461         let compiler = builder.compiler(stage, builder.config.build);
462         let compiler = if builder.force_use_stage1(compiler, target) {
463             builder.compiler(1, compiler.host)
464         } else {
465             compiler
466         };
467
468         builder.ensure(compile::Std { compiler, target });
469         let out_dir = builder.stage_out(compiler, Mode::Std)
470                            .join(target).join("doc");
471
472         // Here what we're doing is creating a *symlink* (directory junction on
473         // Windows) to the final output location. This is not done as an
474         // optimization but rather for correctness. We've got three trees of
475         // documentation, one for std, one for test, and one for rustc. It's then
476         // our job to merge them all together.
477         //
478         // Unfortunately rustbuild doesn't know nearly as well how to merge doc
479         // trees as rustdoc does itself, so instead of actually having three
480         // separate trees we just have rustdoc output to the same location across
481         // all of them.
482         //
483         // This way rustdoc generates output directly into the output, and rustdoc
484         // will also directly handle merging.
485         let my_out = builder.crate_doc_out(target);
486         t!(symlink_dir_force(&builder.config, &my_out, &out_dir));
487         t!(fs::copy(builder.src.join("src/doc/rust.css"), out.join("rust.css")));
488
489         let run_cargo_rustdoc_for = |package: &str| {
490             let mut cargo = builder.cargo(compiler, Mode::Std, target, "rustdoc");
491             compile::std_cargo(builder, &compiler, target, &mut cargo);
492
493             // Keep a whitelist so we do not build internal stdlib crates, these will be
494             // build by the rustc step later if enabled.
495             cargo.arg("-Z").arg("unstable-options")
496                  .arg("-p").arg(package);
497             // Create all crate output directories first to make sure rustdoc uses
498             // relative links.
499             // FIXME: Cargo should probably do this itself.
500             t!(fs::create_dir_all(out_dir.join(package)));
501             cargo.arg("--")
502                  .arg("--markdown-css").arg("rust.css")
503                  .arg("--markdown-no-toc")
504                  .arg("--index-page").arg(&builder.src.join("src/doc/index.md"));
505
506             builder.run(&mut cargo);
507             builder.cp_r(&my_out, &out);
508         };
509         for krate in &["alloc", "core", "std"] {
510             run_cargo_rustdoc_for(krate);
511         }
512     }
513 }
514
515 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
516 pub struct Test {
517     stage: u32,
518     target: Interned<String>,
519 }
520
521 impl Step for Test {
522     type Output = ();
523     const DEFAULT: bool = true;
524
525     fn should_run(run: ShouldRun) -> ShouldRun {
526         let builder = run.builder;
527         run.krate("test").default_condition(builder.config.docs)
528     }
529
530     fn make_run(run: RunConfig) {
531         run.builder.ensure(Test {
532             stage: run.builder.top_stage,
533             target: run.target,
534         });
535     }
536
537     /// Compile all libtest documentation.
538     ///
539     /// This will generate all documentation for libtest and its dependencies. This
540     /// is largely just a wrapper around `cargo doc`.
541     fn run(self, builder: &Builder) {
542         let stage = self.stage;
543         let target = self.target;
544         builder.info(&format!("Documenting stage{} test ({})", stage, target));
545         let out = builder.doc_out(target);
546         t!(fs::create_dir_all(&out));
547         let compiler = builder.compiler(stage, builder.config.build);
548         let compiler = if builder.force_use_stage1(compiler, target) {
549             builder.compiler(1, compiler.host)
550         } else {
551             compiler
552         };
553
554         // Build libstd docs so that we generate relative links
555         builder.ensure(Std { stage, target });
556
557         builder.ensure(compile::Test { compiler, target });
558         let out_dir = builder.stage_out(compiler, Mode::Test)
559                            .join(target).join("doc");
560
561         // See docs in std above for why we symlink
562         let my_out = builder.crate_doc_out(target);
563         t!(symlink_dir_force(&builder.config, &my_out, &out_dir));
564
565         let mut cargo = builder.cargo(compiler, Mode::Test, target, "doc");
566         compile::test_cargo(builder, &compiler, target, &mut cargo);
567
568         cargo.arg("--no-deps").arg("-p").arg("test");
569
570         builder.run(&mut cargo);
571         builder.cp_r(&my_out, &out);
572     }
573 }
574
575 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
576 pub struct WhitelistedRustc {
577     stage: u32,
578     target: Interned<String>,
579 }
580
581 impl Step for WhitelistedRustc {
582     type Output = ();
583     const DEFAULT: bool = true;
584     const ONLY_HOSTS: bool = true;
585
586     fn should_run(run: ShouldRun) -> ShouldRun {
587         let builder = run.builder;
588         run.krate("rustc-main").default_condition(builder.config.docs)
589     }
590
591     fn make_run(run: RunConfig) {
592         run.builder.ensure(WhitelistedRustc {
593             stage: run.builder.top_stage,
594             target: run.target,
595         });
596     }
597
598     /// Generate whitelisted compiler crate documentation.
599     ///
600     /// This will generate all documentation for crates that are whitelisted
601     /// to be included in the standard documentation. This documentation is
602     /// included in the standard Rust documentation, so we should always
603     /// document it and symlink to merge with the rest of the std and test
604     /// documentation. We don't build other compiler documentation
605     /// here as we want to be able to keep it separate from the standard
606     /// documentation. This is largely just a wrapper around `cargo doc`.
607     fn run(self, builder: &Builder) {
608         let stage = self.stage;
609         let target = self.target;
610         builder.info(&format!("Documenting stage{} whitelisted compiler ({})", stage, target));
611         let out = builder.doc_out(target);
612         t!(fs::create_dir_all(&out));
613         let compiler = builder.compiler(stage, builder.config.build);
614         let compiler = if builder.force_use_stage1(compiler, target) {
615             builder.compiler(1, compiler.host)
616         } else {
617             compiler
618         };
619
620         // Build libstd docs so that we generate relative links
621         builder.ensure(Std { stage, target });
622
623         builder.ensure(compile::Rustc { compiler, target });
624         let out_dir = builder.stage_out(compiler, Mode::Rustc)
625                            .join(target).join("doc");
626
627         // See docs in std above for why we symlink
628         let my_out = builder.crate_doc_out(target);
629         t!(symlink_dir_force(&builder.config, &my_out, &out_dir));
630
631         let mut cargo = builder.cargo(compiler, Mode::Rustc, target, "doc");
632         compile::rustc_cargo(builder, &mut cargo);
633
634         // We don't want to build docs for internal compiler dependencies in this
635         // step (there is another step for that). Therefore, we whitelist the crates
636         // for which docs must be built.
637         cargo.arg("--no-deps");
638         for krate in &["proc_macro"] {
639             cargo.arg("-p").arg(krate);
640         }
641
642         builder.run(&mut cargo);
643         builder.cp_r(&my_out, &out);
644     }
645 }
646
647 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
648 pub struct Rustc {
649     stage: u32,
650     target: Interned<String>,
651 }
652
653 impl Step for Rustc {
654     type Output = ();
655     const DEFAULT: bool = true;
656     const ONLY_HOSTS: bool = true;
657
658     fn should_run(run: ShouldRun) -> ShouldRun {
659         let builder = run.builder;
660         run.krate("rustc-main").default_condition(builder.config.docs)
661     }
662
663     fn make_run(run: RunConfig) {
664         run.builder.ensure(Rustc {
665             stage: run.builder.top_stage,
666             target: run.target,
667         });
668     }
669
670     /// Generate compiler documentation.
671     ///
672     /// This will generate all documentation for compiler and dependencies.
673     /// Compiler documentation is distributed separately, so we make sure
674     /// we do not merge it with the other documentation from std, test and
675     /// proc_macros. This is largely just a wrapper around `cargo doc`.
676     fn run(self, builder: &Builder) {
677         let stage = self.stage;
678         let target = self.target;
679         builder.info(&format!("Documenting stage{} compiler ({})", stage, target));
680
681         // This is the intended out directory for compiler documentation.
682         let out = builder.compiler_doc_out(target);
683         t!(fs::create_dir_all(&out));
684
685         // Get the correct compiler for this stage.
686         let compiler = builder.compiler(stage, builder.config.build);
687         let compiler = if builder.force_use_stage1(compiler, target) {
688             builder.compiler(1, compiler.host)
689         } else {
690             compiler
691         };
692
693         if !builder.config.compiler_docs {
694             builder.info("\tskipping - compiler/librustdoc docs disabled");
695             return;
696         }
697
698         // Build rustc.
699         builder.ensure(compile::Rustc { compiler, target });
700
701         // We do not symlink to the same shared folder that already contains std library
702         // documentation from previous steps as we do not want to include that.
703         let out_dir = builder.stage_out(compiler, Mode::Rustc).join(target).join("doc");
704         t!(symlink_dir_force(&builder.config, &out, &out_dir));
705
706         // Build cargo command.
707         let mut cargo = builder.cargo(compiler, Mode::Rustc, target, "doc");
708         cargo.env("RUSTDOCFLAGS", "--document-private-items");
709         compile::rustc_cargo(builder, &mut cargo);
710
711         // Only include compiler crates, no dependencies of those, such as `libc`.
712         cargo.arg("--no-deps");
713
714         // Find dependencies for top level crates.
715         let mut compiler_crates = HashSet::new();
716         for root_crate in &["rustc_driver", "rustc_codegen_llvm", "rustc_codegen_ssa"] {
717             let interned_root_crate = INTERNER.intern_str(root_crate);
718             find_compiler_crates(builder, &interned_root_crate, &mut compiler_crates);
719         }
720
721         for krate in &compiler_crates {
722             // Create all crate output directories first to make sure rustdoc uses
723             // relative links.
724             // FIXME: Cargo should probably do this itself.
725             t!(fs::create_dir_all(out_dir.join(krate)));
726             cargo.arg("-p").arg(krate);
727         }
728
729         builder.run(&mut cargo);
730     }
731 }
732
733 fn find_compiler_crates(
734     builder: &Builder,
735     name: &Interned<String>,
736     crates: &mut HashSet<Interned<String>>
737 ) {
738     // Add current crate.
739     crates.insert(*name);
740
741     // Look for dependencies.
742     for dep in builder.crates.get(name).unwrap().deps.iter() {
743         if builder.crates.get(dep).unwrap().is_local(builder) {
744             find_compiler_crates(builder, dep, crates);
745         }
746     }
747 }
748
749 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
750 pub struct Rustdoc {
751     stage: u32,
752     target: Interned<String>,
753 }
754
755 impl Step for Rustdoc {
756     type Output = ();
757     const DEFAULT: bool = true;
758     const ONLY_HOSTS: bool = true;
759
760     fn should_run(run: ShouldRun) -> ShouldRun {
761         run.krate("rustdoc-tool")
762     }
763
764     fn make_run(run: RunConfig) {
765         run.builder.ensure(Rustdoc {
766             stage: run.builder.top_stage,
767             target: run.target,
768         });
769     }
770
771     /// Generate compiler documentation.
772     ///
773     /// This will generate all documentation for compiler and dependencies.
774     /// Compiler documentation is distributed separately, so we make sure
775     /// we do not merge it with the other documentation from std, test and
776     /// proc_macros. This is largely just a wrapper around `cargo doc`.
777     fn run(self, builder: &Builder) {
778         let stage = self.stage;
779         let target = self.target;
780         builder.info(&format!("Documenting stage{} rustdoc ({})", stage, target));
781
782         // This is the intended out directory for compiler documentation.
783         let out = builder.compiler_doc_out(target);
784         t!(fs::create_dir_all(&out));
785
786         // Get the correct compiler for this stage.
787         let compiler = builder.compiler(stage, builder.config.build);
788         let compiler = if builder.force_use_stage1(compiler, target) {
789             builder.compiler(1, compiler.host)
790         } else {
791             compiler
792         };
793
794         if !builder.config.compiler_docs {
795             builder.info("\tskipping - compiler/librustdoc docs disabled");
796             return;
797         }
798
799         // Build rustc docs so that we generate relative links.
800         builder.ensure(Rustc { stage, target });
801
802         // Build rustdoc.
803         builder.ensure(tool::Rustdoc { host: compiler.host });
804
805         // Symlink compiler docs to the output directory of rustdoc documentation.
806         let out_dir = builder.stage_out(compiler, Mode::ToolRustc)
807             .join(target)
808             .join("doc");
809         t!(fs::create_dir_all(&out_dir));
810         t!(symlink_dir_force(&builder.config, &out, &out_dir));
811
812         // Build cargo command.
813         let mut cargo = prepare_tool_cargo(
814             builder,
815             compiler,
816             Mode::ToolRustc,
817             target,
818             "doc",
819             "src/tools/rustdoc",
820             SourceType::InTree,
821             &[]
822         );
823
824         // Only include compiler crates, no dependencies of those, such as `libc`.
825         cargo.arg("--no-deps");
826         cargo.arg("-p").arg("rustdoc");
827
828         cargo.env("RUSTDOCFLAGS", "--document-private-items");
829         builder.run(&mut cargo);
830     }
831 }
832
833 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
834 pub struct ErrorIndex {
835     target: Interned<String>,
836 }
837
838 impl Step for ErrorIndex {
839     type Output = ();
840     const DEFAULT: bool = true;
841     const ONLY_HOSTS: bool = true;
842
843     fn should_run(run: ShouldRun) -> ShouldRun {
844         let builder = run.builder;
845         run.path("src/tools/error_index_generator").default_condition(builder.config.docs)
846     }
847
848     fn make_run(run: RunConfig) {
849         run.builder.ensure(ErrorIndex {
850             target: run.target,
851         });
852     }
853
854     /// Generates the HTML rendered error-index by running the
855     /// `error_index_generator` tool.
856     fn run(self, builder: &Builder) {
857         let target = self.target;
858
859         builder.info(&format!("Documenting error index ({})", target));
860         let out = builder.doc_out(target);
861         t!(fs::create_dir_all(&out));
862         let mut index = builder.tool_cmd(Tool::ErrorIndex);
863         index.arg("html");
864         index.arg(out.join("error-index.html"));
865
866         // FIXME: shouldn't have to pass this env var
867         index.env("CFG_BUILD", &builder.config.build)
868              .env("RUSTC_ERROR_METADATA_DST", builder.extended_error_dir());
869
870         builder.run(&mut index);
871     }
872 }
873
874 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
875 pub struct UnstableBookGen {
876     target: Interned<String>,
877 }
878
879 impl Step for UnstableBookGen {
880     type Output = ();
881     const DEFAULT: bool = true;
882     const ONLY_HOSTS: bool = true;
883
884     fn should_run(run: ShouldRun) -> ShouldRun {
885         let builder = run.builder;
886         run.path("src/tools/unstable-book-gen").default_condition(builder.config.docs)
887     }
888
889     fn make_run(run: RunConfig) {
890         run.builder.ensure(UnstableBookGen {
891             target: run.target,
892         });
893     }
894
895     fn run(self, builder: &Builder) {
896         let target = self.target;
897
898         builder.ensure(compile::Std {
899             compiler: builder.compiler(builder.top_stage, builder.config.build),
900             target,
901         });
902
903         builder.info(&format!("Generating unstable book md files ({})", target));
904         let out = builder.md_doc_out(target).join("unstable-book");
905         builder.create_dir(&out);
906         builder.remove_dir(&out);
907         let mut cmd = builder.tool_cmd(Tool::UnstableBookGen);
908         cmd.arg(builder.src.join("src"));
909         cmd.arg(out);
910
911         builder.run(&mut cmd);
912     }
913 }
914
915 fn symlink_dir_force(config: &Config, src: &Path, dst: &Path) -> io::Result<()> {
916     if config.dry_run {
917         return Ok(());
918     }
919     if let Ok(m) = fs::symlink_metadata(dst) {
920         if m.file_type().is_dir() {
921             fs::remove_dir_all(dst)?;
922         } else {
923             // handle directory junctions on windows by falling back to
924             // `remove_dir`.
925             fs::remove_file(dst).or_else(|_| {
926                 fs::remove_dir(dst)
927             })?;
928         }
929     }
930
931     symlink_dir(config, src, dst)
932 }