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