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