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