]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/doc.rs
Rollup merge of #101923 - jsha:aux-pages-no-rustdoc-css, r=Mark-Simulacrum
[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::fs;
11 use std::io;
12 use std::path::{Path, PathBuf};
13
14 use crate::builder::{Builder, Compiler, Kind, RunConfig, ShouldRun, Step};
15 use crate::cache::{Interned, INTERNER};
16 use crate::compile;
17 use crate::config::{Config, TargetSelection};
18 use crate::tool::{self, prepare_tool_cargo, SourceType, Tool};
19 use crate::util::{symlink_dir, t, up_to_date};
20 use crate::Mode;
21
22 macro_rules! submodule_helper {
23     ($path:expr, submodule) => {
24         $path
25     };
26     ($path:expr, submodule = $submodule:literal) => {
27         $submodule
28     };
29 }
30
31 macro_rules! book {
32     ($($name:ident, $path:expr, $book_name:expr $(, submodule $(= $submodule:literal)? )? ;)+) => {
33         $(
34             #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
35         pub struct $name {
36             target: TargetSelection,
37         }
38
39         impl Step for $name {
40             type Output = ();
41             const DEFAULT: bool = true;
42
43             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
44                 let builder = run.builder;
45                 run.path($path).default_condition(builder.config.docs)
46             }
47
48             fn make_run(run: RunConfig<'_>) {
49                 run.builder.ensure($name {
50                     target: run.target,
51                 });
52             }
53
54             fn run(self, builder: &Builder<'_>) {
55                 $(
56                     let path = Path::new(submodule_helper!( $path, submodule $( = $submodule )? ));
57                     builder.update_submodule(&path);
58                 )?
59                 builder.ensure(RustbookSrc {
60                     target: self.target,
61                     name: INTERNER.intern_str($book_name),
62                     src: INTERNER.intern_path(builder.src.join($path)),
63                 })
64             }
65         }
66         )+
67     }
68 }
69
70 // NOTE: When adding a book here, make sure to ALSO build the book by
71 // adding a build step in `src/bootstrap/builder.rs`!
72 // NOTE: Make sure to add the corresponding submodule when adding a new book.
73 // FIXME: Make checking for a submodule automatic somehow (maybe by having a list of all submodules
74 // and checking against it?).
75 book!(
76     CargoBook, "src/tools/cargo/src/doc", "cargo", submodule = "src/tools/cargo";
77     ClippyBook, "src/tools/clippy/book", "clippy";
78     EditionGuide, "src/doc/edition-guide", "edition-guide", submodule;
79     EmbeddedBook, "src/doc/embedded-book", "embedded-book", submodule;
80     Nomicon, "src/doc/nomicon", "nomicon", submodule;
81     Reference, "src/doc/reference", "reference", submodule;
82     RustByExample, "src/doc/rust-by-example", "rust-by-example", submodule;
83     RustdocBook, "src/doc/rustdoc", "rustdoc";
84 );
85
86 fn open(builder: &Builder<'_>, path: impl AsRef<Path>) {
87     if builder.config.dry_run || !builder.config.cmd.open() {
88         return;
89     }
90
91     let path = path.as_ref();
92     builder.info(&format!("Opening doc {}", path.display()));
93     if let Err(err) = opener::open(path) {
94         builder.info(&format!("{}\n", err));
95     }
96 }
97
98 // "library/std" -> ["library", "std"]
99 //
100 // Used for deciding whether a particular step is one requested by the user on
101 // the `x.py doc` command line, which determines whether `--open` will open that
102 // page.
103 pub(crate) fn components_simplified(path: &PathBuf) -> Vec<&str> {
104     path.iter().map(|component| component.to_str().unwrap_or("???")).collect()
105 }
106
107 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
108 pub struct UnstableBook {
109     target: TargetSelection,
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 { target: run.target });
123     }
124
125     fn run(self, builder: &Builder<'_>) {
126         builder.ensure(UnstableBookGen { target: self.target });
127         builder.ensure(RustbookSrc {
128             target: self.target,
129             name: INTERNER.intern_str("unstable-book"),
130             src: INTERNER.intern_path(builder.md_doc_out(self.target).join("unstable-book")),
131         })
132     }
133 }
134
135 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
136 struct RustbookSrc {
137     target: TargetSelection,
138     name: Interned<String>,
139     src: Interned<PathBuf>,
140 }
141
142 impl Step for RustbookSrc {
143     type Output = ();
144
145     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
146         run.never()
147     }
148
149     /// Invoke `rustbook` for `target` for the doc book `name` from the `src` path.
150     ///
151     /// This will not actually generate any documentation if the documentation has
152     /// already been generated.
153     fn run(self, builder: &Builder<'_>) {
154         let target = self.target;
155         let name = self.name;
156         let src = self.src;
157         let out = builder.doc_out(target);
158         t!(fs::create_dir_all(&out));
159
160         let out = out.join(name);
161         let index = out.join("index.html");
162         let rustbook = builder.tool_exe(Tool::Rustbook);
163         let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook);
164         if builder.config.dry_run || up_to_date(&src, &index) && up_to_date(&rustbook, &index) {
165             return;
166         }
167         builder.info(&format!("Rustbook ({}) - {}", target, name));
168         let _ = fs::remove_dir_all(&out);
169
170         builder.run(rustbook_cmd.arg("build").arg(&src).arg("-d").arg(out));
171     }
172 }
173
174 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
175 pub struct TheBook {
176     compiler: Compiler,
177     target: TargetSelection,
178 }
179
180 impl Step for TheBook {
181     type Output = ();
182     const DEFAULT: bool = true;
183
184     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
185         let builder = run.builder;
186         run.path("src/doc/book").default_condition(builder.config.docs)
187     }
188
189     fn make_run(run: RunConfig<'_>) {
190         run.builder.ensure(TheBook {
191             compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
192             target: run.target,
193         });
194     }
195
196     /// Builds the book and associated stuff.
197     ///
198     /// We need to build:
199     ///
200     /// * Book
201     /// * Older edition redirects
202     /// * Version info and CSS
203     /// * Index page
204     /// * Redirect pages
205     fn run(self, builder: &Builder<'_>) {
206         let relative_path = Path::new("src").join("doc").join("book");
207         builder.update_submodule(&relative_path);
208
209         let compiler = self.compiler;
210         let target = self.target;
211
212         // build book
213         builder.ensure(RustbookSrc {
214             target,
215             name: INTERNER.intern_str("book"),
216             src: INTERNER.intern_path(builder.src.join(&relative_path)),
217         });
218
219         // building older edition redirects
220         for edition in &["first-edition", "second-edition", "2018-edition"] {
221             builder.ensure(RustbookSrc {
222                 target,
223                 name: INTERNER.intern_string(format!("book/{}", edition)),
224                 src: INTERNER.intern_path(builder.src.join(&relative_path).join(edition)),
225             });
226         }
227
228         // build the version info page and CSS
229         builder.ensure(Standalone { compiler, target });
230
231         // build the redirect pages
232         builder.info(&format!("Documenting book redirect pages ({})", target));
233         for file in t!(fs::read_dir(builder.src.join(&relative_path).join("redirects"))) {
234             let file = t!(file);
235             let path = file.path();
236             let path = path.to_str().unwrap();
237
238             invoke_rustdoc(builder, compiler, target, path);
239         }
240
241         if builder.was_invoked_explicitly::<Self>(Kind::Doc) {
242             let out = builder.doc_out(target);
243             let index = out.join("book").join("index.html");
244             open(builder, &index);
245         }
246     }
247 }
248
249 fn invoke_rustdoc(
250     builder: &Builder<'_>,
251     compiler: Compiler,
252     target: TargetSelection,
253     markdown: &str,
254 ) {
255     let out = builder.doc_out(target);
256
257     let path = builder.src.join("src/doc").join(markdown);
258
259     let header = builder.src.join("src/doc/redirect.inc");
260     let footer = builder.src.join("src/doc/footer.inc");
261     let version_info = out.join("version_info.html");
262
263     let mut cmd = builder.rustdoc_cmd(compiler);
264
265     let out = out.join("book");
266
267     cmd.arg("--html-after-content")
268         .arg(&footer)
269         .arg("--html-before-content")
270         .arg(&version_info)
271         .arg("--html-in-header")
272         .arg(&header)
273         .arg("--markdown-no-toc")
274         .arg("--markdown-playground-url")
275         .arg("https://play.rust-lang.org/")
276         .arg("-o")
277         .arg(&out)
278         .arg(&path)
279         .arg("--markdown-css")
280         .arg("../rust.css");
281
282     if !builder.config.docs_minification {
283         cmd.arg("-Z").arg("unstable-options").arg("--disable-minification");
284     }
285
286     builder.run(&mut cmd);
287 }
288
289 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
290 pub struct Standalone {
291     compiler: Compiler,
292     target: TargetSelection,
293 }
294
295 impl Step for Standalone {
296     type Output = ();
297     const DEFAULT: bool = true;
298
299     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
300         let builder = run.builder;
301         run.path("src/doc").default_condition(builder.config.docs)
302     }
303
304     fn make_run(run: RunConfig<'_>) {
305         run.builder.ensure(Standalone {
306             compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
307             target: run.target,
308         });
309     }
310
311     /// Generates all standalone documentation as compiled by the rustdoc in `stage`
312     /// for the `target` into `out`.
313     ///
314     /// This will list all of `src/doc` looking for markdown files and appropriately
315     /// perform transformations like substituting `VERSION`, `SHORT_HASH`, and
316     /// `STAMP` along with providing the various header/footer HTML we've customized.
317     ///
318     /// In the end, this is just a glorified wrapper around rustdoc!
319     fn run(self, builder: &Builder<'_>) {
320         let target = self.target;
321         let compiler = self.compiler;
322         builder.info(&format!("Documenting standalone ({})", target));
323         let out = builder.doc_out(target);
324         t!(fs::create_dir_all(&out));
325
326         let favicon = builder.src.join("src/doc/favicon.inc");
327         let footer = builder.src.join("src/doc/footer.inc");
328         let full_toc = builder.src.join("src/doc/full-toc.inc");
329         t!(fs::copy(builder.src.join("src/doc/rust.css"), out.join("rust.css")));
330
331         let version_input = builder.src.join("src/doc/version_info.html.template");
332         let version_info = out.join("version_info.html");
333
334         if !builder.config.dry_run && !up_to_date(&version_input, &version_info) {
335             let info = t!(fs::read_to_string(&version_input))
336                 .replace("VERSION", &builder.rust_release())
337                 .replace("SHORT_HASH", builder.rust_info.sha_short().unwrap_or(""))
338                 .replace("STAMP", builder.rust_info.sha().unwrap_or(""));
339             t!(fs::write(&version_info, &info));
340         }
341
342         for file in t!(fs::read_dir(builder.src.join("src/doc"))) {
343             let file = t!(file);
344             let path = file.path();
345             let filename = path.file_name().unwrap().to_str().unwrap();
346             if !filename.ends_with(".md") || filename == "README.md" {
347                 continue;
348             }
349
350             let html = out.join(filename).with_extension("html");
351             let rustdoc = builder.rustdoc(compiler);
352             if up_to_date(&path, &html)
353                 && up_to_date(&footer, &html)
354                 && up_to_date(&favicon, &html)
355                 && up_to_date(&full_toc, &html)
356                 && (builder.config.dry_run || up_to_date(&version_info, &html))
357                 && (builder.config.dry_run || up_to_date(&rustdoc, &html))
358             {
359                 continue;
360             }
361
362             let mut cmd = builder.rustdoc_cmd(compiler);
363             // Needed for --index-page flag
364             cmd.arg("-Z").arg("unstable-options");
365
366             cmd.arg("--html-after-content")
367                 .arg(&footer)
368                 .arg("--html-before-content")
369                 .arg(&version_info)
370                 .arg("--html-in-header")
371                 .arg(&favicon)
372                 .arg("--markdown-no-toc")
373                 .arg("--index-page")
374                 .arg(&builder.src.join("src/doc/index.md"))
375                 .arg("--markdown-playground-url")
376                 .arg("https://play.rust-lang.org/")
377                 .arg("-o")
378                 .arg(&out)
379                 .arg(&path);
380
381             if !builder.config.docs_minification {
382                 cmd.arg("--disable-minification");
383             }
384
385             if filename == "not_found.md" {
386                 cmd.arg("--markdown-css").arg("https://doc.rust-lang.org/rust.css");
387             } else {
388                 cmd.arg("--markdown-css").arg("rust.css");
389             }
390             builder.run(&mut cmd);
391         }
392
393         // We open doc/index.html as the default if invoked as `x.py doc --open`
394         // with no particular explicit doc requested (e.g. library/core).
395         if builder.paths.is_empty() || builder.was_invoked_explicitly::<Self>(Kind::Doc) {
396             let index = out.join("index.html");
397             open(builder, &index);
398         }
399     }
400 }
401
402 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
403 pub struct Std {
404     pub stage: u32,
405     pub target: TargetSelection,
406 }
407
408 impl Step for Std {
409     type Output = ();
410     const DEFAULT: bool = true;
411
412     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
413         let builder = run.builder;
414         run.all_krates("test").path("library").default_condition(builder.config.docs)
415     }
416
417     fn make_run(run: RunConfig<'_>) {
418         run.builder.ensure(Std { stage: run.builder.top_stage, target: run.target });
419     }
420
421     /// Compile all standard library documentation.
422     ///
423     /// This will generate all documentation for the standard library and its
424     /// dependencies. This is largely just a wrapper around `cargo doc`.
425     fn run(self, builder: &Builder<'_>) {
426         let stage = self.stage;
427         let target = self.target;
428         builder.info(&format!("Documenting stage{} std ({})", stage, target));
429         if builder.no_std(target) == Some(true) {
430             panic!(
431                 "building std documentation for no_std target {target} is not supported\n\
432                  Set `docs = false` in the config to disable documentation."
433             );
434         }
435         let out = builder.doc_out(target);
436         t!(fs::create_dir_all(&out));
437         let compiler = builder.compiler(stage, builder.config.build);
438
439         let out_dir = builder.stage_out(compiler, Mode::Std).join(target.triple).join("doc");
440
441         t!(fs::copy(builder.src.join("src/doc/rust.css"), out.join("rust.css")));
442
443         let run_cargo_rustdoc_for = |package: &str| {
444             let mut cargo =
445                 builder.cargo(compiler, Mode::Std, SourceType::InTree, target, "rustdoc");
446             compile::std_cargo(builder, target, compiler.stage, &mut cargo);
447
448             cargo
449                 .arg("-p")
450                 .arg(package)
451                 .arg("-Zskip-rustdoc-fingerprint")
452                 .arg("--")
453                 .arg("--markdown-css")
454                 .arg("rust.css")
455                 .arg("--markdown-no-toc")
456                 .arg("-Z")
457                 .arg("unstable-options")
458                 .arg("--resource-suffix")
459                 .arg(&builder.version)
460                 .arg("--index-page")
461                 .arg(&builder.src.join("src/doc/index.md"));
462
463             if !builder.config.docs_minification {
464                 cargo.arg("--disable-minification");
465             }
466
467             builder.run(&mut cargo.into());
468         };
469
470         let paths = builder
471             .paths
472             .iter()
473             .map(components_simplified)
474             .filter_map(|path| {
475                 if path.len() >= 2 && path.get(0) == Some(&"library") {
476                     // single crate
477                     Some(path[1].to_owned())
478                 } else if !path.is_empty() {
479                     // ??
480                     Some(path[0].to_owned())
481                 } else {
482                     // all library crates
483                     None
484                 }
485             })
486             .collect::<Vec<_>>();
487
488         // Only build the following crates. While we could just iterate over the
489         // folder structure, that would also build internal crates that we do
490         // not want to show in documentation. These crates will later be visited
491         // by the rustc step, so internal documentation will show them.
492         //
493         // Note that the order here is important! The crates need to be
494         // processed starting from the leaves, otherwise rustdoc will not
495         // create correct links between crates because rustdoc depends on the
496         // existence of the output directories to know if it should be a local
497         // or remote link.
498         let krates = ["core", "alloc", "std", "proc_macro", "test"];
499         for krate in &krates {
500             run_cargo_rustdoc_for(krate);
501             if paths.iter().any(|p| p == krate) {
502                 // No need to document more of the libraries if we have the one we want.
503                 break;
504             }
505         }
506         builder.cp_r(&out_dir, &out);
507
508         // Look for library/std, library/core etc in the `x.py doc` arguments and
509         // open the corresponding rendered docs.
510         for requested_crate in paths {
511             if krates.iter().any(|k| *k == requested_crate.as_str()) {
512                 let index = out.join(requested_crate).join("index.html");
513                 open(builder, &index);
514             }
515         }
516     }
517 }
518
519 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
520 pub struct Rustc {
521     pub stage: u32,
522     pub target: TargetSelection,
523 }
524
525 impl Step for Rustc {
526     type Output = ();
527     const DEFAULT: bool = true;
528     const ONLY_HOSTS: bool = true;
529
530     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
531         let builder = run.builder;
532         run.crate_or_deps("rustc-main")
533             .path("compiler")
534             .default_condition(builder.config.compiler_docs)
535     }
536
537     fn make_run(run: RunConfig<'_>) {
538         run.builder.ensure(Rustc { stage: run.builder.top_stage, target: run.target });
539     }
540
541     /// Generates compiler documentation.
542     ///
543     /// This will generate all documentation for compiler and dependencies.
544     /// Compiler documentation is distributed separately, so we make sure
545     /// we do not merge it with the other documentation from std, test and
546     /// proc_macros. This is largely just a wrapper around `cargo doc`.
547     fn run(self, builder: &Builder<'_>) {
548         let stage = self.stage;
549         let target = self.target;
550
551         let paths = builder
552             .paths
553             .iter()
554             .filter(|path| {
555                 let components = components_simplified(path);
556                 components.len() >= 2 && components[0] == "compiler"
557             })
558             .collect::<Vec<_>>();
559
560         // This is the intended out directory for compiler documentation.
561         let out = builder.compiler_doc_out(target);
562         t!(fs::create_dir_all(&out));
563
564         // Build the standard library, so that proc-macros can use it.
565         // (Normally, only the metadata would be necessary, but proc-macros are special since they run at compile-time.)
566         let compiler = builder.compiler(stage, builder.config.build);
567         builder.ensure(compile::Std::new(compiler, builder.config.build));
568
569         builder.info(&format!("Documenting stage{} compiler ({})", stage, target));
570
571         // This uses a shared directory so that librustdoc documentation gets
572         // correctly built and merged with the rustc documentation. This is
573         // needed because rustdoc is built in a different directory from
574         // rustc. rustdoc needs to be able to see everything, for example when
575         // merging the search index, or generating local (relative) links.
576         let out_dir = builder.stage_out(compiler, Mode::Rustc).join(target.triple).join("doc");
577         t!(symlink_dir_force(&builder.config, &out, &out_dir));
578         // Cargo puts proc macros in `target/doc` even if you pass `--target`
579         // explicitly (https://github.com/rust-lang/cargo/issues/7677).
580         let proc_macro_out_dir = builder.stage_out(compiler, Mode::Rustc).join("doc");
581         t!(symlink_dir_force(&builder.config, &out, &proc_macro_out_dir));
582
583         // Build cargo command.
584         let mut cargo = builder.cargo(compiler, Mode::Rustc, SourceType::InTree, target, "doc");
585         cargo.rustdocflag("--document-private-items");
586         // Since we always pass --document-private-items, there's no need to warn about linking to private items.
587         cargo.rustdocflag("-Arustdoc::private-intra-doc-links");
588         cargo.rustdocflag("--enable-index-page");
589         cargo.rustdocflag("-Zunstable-options");
590         cargo.rustdocflag("-Znormalize-docs");
591         cargo.rustdocflag("--show-type-layout");
592         cargo.rustdocflag("--generate-link-to-definition");
593         compile::rustc_cargo(builder, &mut cargo, target);
594         cargo.arg("-Zunstable-options");
595         cargo.arg("-Zskip-rustdoc-fingerprint");
596
597         // Only include compiler crates, no dependencies of those, such as `libc`.
598         // Do link to dependencies on `docs.rs` however using `rustdoc-map`.
599         cargo.arg("--no-deps");
600         cargo.arg("-Zrustdoc-map");
601
602         // FIXME: `-Zrustdoc-map` does not yet correctly work for transitive dependencies,
603         // once this is no longer an issue the special case for `ena` can be removed.
604         cargo.rustdocflag("--extern-html-root-url");
605         cargo.rustdocflag("ena=https://docs.rs/ena/latest/");
606
607         let root_crates = if paths.is_empty() {
608             vec![
609                 INTERNER.intern_str("rustc_driver"),
610                 INTERNER.intern_str("rustc_codegen_llvm"),
611                 INTERNER.intern_str("rustc_codegen_ssa"),
612             ]
613         } else {
614             paths.into_iter().map(|p| builder.crate_paths[p]).collect()
615         };
616         // Find dependencies for top level crates.
617         let compiler_crates = root_crates.iter().flat_map(|krate| {
618             builder.in_tree_crates(krate, Some(target)).into_iter().map(|krate| krate.name)
619         });
620
621         let mut to_open = None;
622         for krate in compiler_crates {
623             // Create all crate output directories first to make sure rustdoc uses
624             // relative links.
625             // FIXME: Cargo should probably do this itself.
626             t!(fs::create_dir_all(out_dir.join(krate)));
627             cargo.arg("-p").arg(krate);
628             if to_open.is_none() {
629                 to_open = Some(krate);
630             }
631         }
632
633         builder.run(&mut cargo.into());
634         // Let's open the first crate documentation page:
635         if let Some(krate) = to_open {
636             let index = out.join(krate).join("index.html");
637             open(builder, &index);
638         }
639     }
640 }
641
642 macro_rules! tool_doc {
643     ($tool: ident, $should_run: literal, $path: literal, [$($krate: literal),+ $(,)?], in_tree = $in_tree:expr $(,)?) => {
644         #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
645         pub struct $tool {
646             target: TargetSelection,
647         }
648
649         impl Step for $tool {
650             type Output = ();
651             const DEFAULT: bool = true;
652             const ONLY_HOSTS: bool = true;
653
654             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
655                 let builder = run.builder;
656                 run.crate_or_deps($should_run).default_condition(builder.config.compiler_docs)
657             }
658
659             fn make_run(run: RunConfig<'_>) {
660                 run.builder.ensure($tool { target: run.target });
661             }
662
663             /// Generates compiler documentation.
664             ///
665             /// This will generate all documentation for compiler and dependencies.
666             /// Compiler documentation is distributed separately, so we make sure
667             /// we do not merge it with the other documentation from std, test and
668             /// proc_macros. This is largely just a wrapper around `cargo doc`.
669             fn run(self, builder: &Builder<'_>) {
670                 let stage = builder.top_stage;
671                 let target = self.target;
672
673                 // This is the intended out directory for compiler documentation.
674                 let out = builder.compiler_doc_out(target);
675                 t!(fs::create_dir_all(&out));
676
677                 // Build rustc docs so that we generate relative links.
678                 builder.ensure(Rustc { stage, target });
679                 // Rustdoc needs the rustc sysroot available to build.
680                 // FIXME: is there a way to only ensure `check::Rustc` here? Last time I tried it failed
681                 // with strange errors, but only on a full bors test ...
682                 let compiler = builder.compiler(stage, builder.config.build);
683                 builder.ensure(compile::Rustc::new(compiler, target));
684
685                 builder.info(
686                     &format!(
687                         "Documenting stage{} {} ({})",
688                         stage,
689                         stringify!($tool).to_lowercase(),
690                         target,
691                     ),
692                 );
693
694                 // Symlink compiler docs to the output directory of rustdoc documentation.
695                 let out_dir = builder.stage_out(compiler, Mode::ToolRustc).join(target.triple).join("doc");
696                 t!(fs::create_dir_all(&out_dir));
697                 t!(symlink_dir_force(&builder.config, &out, &out_dir));
698
699                 let source_type = if $in_tree == true {
700                     SourceType::InTree
701                 } else {
702                     SourceType::Submodule
703                 };
704
705                 // Build cargo command.
706                 let mut cargo = prepare_tool_cargo(
707                     builder,
708                     compiler,
709                     Mode::ToolRustc,
710                     target,
711                     "doc",
712                     $path,
713                     source_type,
714                     &[],
715                 );
716
717                 cargo.arg("-Zskip-rustdoc-fingerprint");
718                 // Only include compiler crates, no dependencies of those, such as `libc`.
719                 cargo.arg("--no-deps");
720                 $(
721                     cargo.arg("-p").arg($krate);
722                 )+
723
724                 cargo.rustdocflag("--document-private-items");
725                 cargo.rustdocflag("--enable-index-page");
726                 cargo.rustdocflag("--show-type-layout");
727                 cargo.rustdocflag("--generate-link-to-definition");
728                 cargo.rustdocflag("-Zunstable-options");
729                 if $in_tree == true {
730                     builder.run(&mut cargo.into());
731                 } else {
732                     // Allow out-of-tree docs to fail (since the tool might be in a broken state).
733                     if !builder.try_run(&mut cargo.into()) {
734                         builder.info(&format!(
735                             "WARNING: tool {} failed to document; ignoring failure because it is an out-of-tree tool",
736                             stringify!($tool).to_lowercase(),
737                         ));
738                     }
739                 }
740             }
741         }
742     }
743 }
744
745 tool_doc!(
746     Rustdoc,
747     "rustdoc-tool",
748     "src/tools/rustdoc",
749     ["rustdoc", "rustdoc-json-types"],
750     in_tree = true
751 );
752 tool_doc!(
753     Rustfmt,
754     "rustfmt-nightly",
755     "src/tools/rustfmt",
756     ["rustfmt-nightly", "rustfmt-config_proc_macro"],
757     in_tree = true
758 );
759 tool_doc!(Clippy, "clippy", "src/tools/clippy", ["clippy_utils"], in_tree = true);
760 tool_doc!(Miri, "miri", "src/tools/miri", ["miri"], in_tree = false);
761
762 #[derive(Ord, PartialOrd, Debug, Copy, Clone, Hash, PartialEq, Eq)]
763 pub struct ErrorIndex {
764     pub target: TargetSelection,
765 }
766
767 impl Step for ErrorIndex {
768     type Output = ();
769     const DEFAULT: bool = true;
770     const ONLY_HOSTS: bool = true;
771
772     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
773         let builder = run.builder;
774         run.path("src/tools/error_index_generator").default_condition(builder.config.docs)
775     }
776
777     fn make_run(run: RunConfig<'_>) {
778         let target = run.target;
779         run.builder.ensure(ErrorIndex { target });
780     }
781
782     /// Generates the HTML rendered error-index by running the
783     /// `error_index_generator` tool.
784     fn run(self, builder: &Builder<'_>) {
785         builder.info(&format!("Documenting error index ({})", self.target));
786         let out = builder.doc_out(self.target);
787         t!(fs::create_dir_all(&out));
788         let mut index = tool::ErrorIndex::command(builder);
789         index.arg("html");
790         index.arg(out);
791         index.arg(&builder.version);
792
793         builder.run(&mut index);
794     }
795 }
796
797 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
798 pub struct UnstableBookGen {
799     target: TargetSelection,
800 }
801
802 impl Step for UnstableBookGen {
803     type Output = ();
804     const DEFAULT: bool = true;
805     const ONLY_HOSTS: bool = true;
806
807     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
808         let builder = run.builder;
809         run.path("src/tools/unstable-book-gen").default_condition(builder.config.docs)
810     }
811
812     fn make_run(run: RunConfig<'_>) {
813         run.builder.ensure(UnstableBookGen { target: run.target });
814     }
815
816     fn run(self, builder: &Builder<'_>) {
817         let target = self.target;
818
819         builder.info(&format!("Generating unstable book md files ({})", target));
820         let out = builder.md_doc_out(target).join("unstable-book");
821         builder.create_dir(&out);
822         builder.remove_dir(&out);
823         let mut cmd = builder.tool_cmd(Tool::UnstableBookGen);
824         cmd.arg(builder.src.join("library"));
825         cmd.arg(builder.src.join("compiler"));
826         cmd.arg(builder.src.join("src"));
827         cmd.arg(out);
828
829         builder.run(&mut cmd);
830     }
831 }
832
833 fn symlink_dir_force(config: &Config, src: &Path, dst: &Path) -> io::Result<()> {
834     if config.dry_run {
835         return Ok(());
836     }
837     if let Ok(m) = fs::symlink_metadata(dst) {
838         if m.file_type().is_dir() {
839             fs::remove_dir_all(dst)?;
840         } else {
841             // handle directory junctions on windows by falling back to
842             // `remove_dir`.
843             fs::remove_file(dst).or_else(|_| fs::remove_dir(dst))?;
844         }
845     }
846
847     symlink_dir(config, src, dst)
848 }
849
850 #[derive(Ord, PartialOrd, Debug, Copy, Clone, Hash, PartialEq, Eq)]
851 pub struct RustcBook {
852     pub compiler: Compiler,
853     pub target: TargetSelection,
854     pub validate: bool,
855 }
856
857 impl Step for RustcBook {
858     type Output = ();
859     const DEFAULT: bool = true;
860     const ONLY_HOSTS: bool = true;
861
862     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
863         let builder = run.builder;
864         run.path("src/doc/rustc").default_condition(builder.config.docs)
865     }
866
867     fn make_run(run: RunConfig<'_>) {
868         run.builder.ensure(RustcBook {
869             compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
870             target: run.target,
871             validate: false,
872         });
873     }
874
875     /// Builds the rustc book.
876     ///
877     /// The lints are auto-generated by a tool, and then merged into the book
878     /// in the "md-doc" directory in the build output directory. Then
879     /// "rustbook" is used to convert it to HTML.
880     fn run(self, builder: &Builder<'_>) {
881         let out_base = builder.md_doc_out(self.target).join("rustc");
882         t!(fs::create_dir_all(&out_base));
883         let out_listing = out_base.join("src/lints");
884         builder.cp_r(&builder.src.join("src/doc/rustc"), &out_base);
885         builder.info(&format!("Generating lint docs ({})", self.target));
886
887         let rustc = builder.rustc(self.compiler);
888         // The tool runs `rustc` for extracting output examples, so it needs a
889         // functional sysroot.
890         builder.ensure(compile::Std::new(self.compiler, self.target));
891         let mut cmd = builder.tool_cmd(Tool::LintDocs);
892         cmd.arg("--src");
893         cmd.arg(builder.src.join("compiler"));
894         cmd.arg("--out");
895         cmd.arg(&out_listing);
896         cmd.arg("--rustc");
897         cmd.arg(&rustc);
898         cmd.arg("--rustc-target").arg(&self.target.rustc_target_arg());
899         if builder.config.verbose() {
900             cmd.arg("--verbose");
901         }
902         if self.validate {
903             cmd.arg("--validate");
904         }
905         if !builder.unstable_features() {
906             // We need to validate nightly features, even on the stable channel.
907             cmd.env("RUSTC_BOOTSTRAP", "1");
908         }
909         // If the lib directories are in an unusual location (changed in
910         // config.toml), then this needs to explicitly update the dylib search
911         // path.
912         builder.add_rustc_lib_path(self.compiler, &mut cmd);
913         builder.run(&mut cmd);
914         // Run rustbook/mdbook to generate the HTML pages.
915         builder.ensure(RustbookSrc {
916             target: self.target,
917             name: INTERNER.intern_str("rustc"),
918             src: INTERNER.intern_path(out_base),
919         });
920         if builder.was_invoked_explicitly::<Self>(Kind::Doc) {
921             let out = builder.doc_out(self.target);
922             let index = out.join("rustc").join("index.html");
923             open(builder, &index);
924         }
925     }
926 }