]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/doc.rs
fix out dir being wrong in json
[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         let shared_assets = builder.ensure(SharedAssets { 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, &shared_assets, 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     shared_assets: &SharedAssetsPaths,
255     target: TargetSelection,
256     markdown: &str,
257 ) {
258     let out = builder.doc_out(target);
259
260     let path = builder.src.join("src/doc").join(markdown);
261
262     let header = builder.src.join("src/doc/redirect.inc");
263     let footer = builder.src.join("src/doc/footer.inc");
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(&shared_assets.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").alias("standalone").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 version_info = builder.ensure(SharedAssets { target: self.target }).version_info;
329
330         let favicon = builder.src.join("src/doc/favicon.inc");
331         let footer = builder.src.join("src/doc/footer.inc");
332         let full_toc = builder.src.join("src/doc/full-toc.inc");
333
334         for file in t!(fs::read_dir(builder.src.join("src/doc"))) {
335             let file = t!(file);
336             let path = file.path();
337             let filename = path.file_name().unwrap().to_str().unwrap();
338             if !filename.ends_with(".md") || filename == "README.md" {
339                 continue;
340             }
341
342             let html = out.join(filename).with_extension("html");
343             let rustdoc = builder.rustdoc(compiler);
344             if up_to_date(&path, &html)
345                 && up_to_date(&footer, &html)
346                 && up_to_date(&favicon, &html)
347                 && up_to_date(&full_toc, &html)
348                 && (builder.config.dry_run || up_to_date(&version_info, &html))
349                 && (builder.config.dry_run || up_to_date(&rustdoc, &html))
350             {
351                 continue;
352             }
353
354             let mut cmd = builder.rustdoc_cmd(compiler);
355             // Needed for --index-page flag
356             cmd.arg("-Z").arg("unstable-options");
357
358             cmd.arg("--html-after-content")
359                 .arg(&footer)
360                 .arg("--html-before-content")
361                 .arg(&version_info)
362                 .arg("--html-in-header")
363                 .arg(&favicon)
364                 .arg("--markdown-no-toc")
365                 .arg("--index-page")
366                 .arg(&builder.src.join("src/doc/index.md"))
367                 .arg("--markdown-playground-url")
368                 .arg("https://play.rust-lang.org/")
369                 .arg("-o")
370                 .arg(&out)
371                 .arg(&path);
372
373             if !builder.config.docs_minification {
374                 cmd.arg("--disable-minification");
375             }
376
377             if filename == "not_found.md" {
378                 cmd.arg("--markdown-css").arg("https://doc.rust-lang.org/rust.css");
379             } else {
380                 cmd.arg("--markdown-css").arg("rust.css");
381             }
382             builder.run(&mut cmd);
383         }
384
385         // We open doc/index.html as the default if invoked as `x.py doc --open`
386         // with no particular explicit doc requested (e.g. library/core).
387         if builder.paths.is_empty() || builder.was_invoked_explicitly::<Self>(Kind::Doc) {
388             let index = out.join("index.html");
389             open(builder, &index);
390         }
391     }
392 }
393
394 #[derive(Debug, Clone)]
395 pub struct SharedAssetsPaths {
396     pub version_info: PathBuf,
397 }
398
399 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
400 pub struct SharedAssets {
401     target: TargetSelection,
402 }
403
404 impl Step for SharedAssets {
405     type Output = SharedAssetsPaths;
406     const DEFAULT: bool = false;
407
408     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
409         // Other tasks depend on this, no need to execute it on its own
410         run.never()
411     }
412
413     // Generate shared resources used by other pieces of documentation.
414     fn run(self, builder: &Builder<'_>) -> Self::Output {
415         let out = builder.doc_out(self.target);
416
417         let version_input = builder.src.join("src").join("doc").join("version_info.html.template");
418         let version_info = out.join("version_info.html");
419         if !builder.config.dry_run && !up_to_date(&version_input, &version_info) {
420             let info = t!(fs::read_to_string(&version_input))
421                 .replace("VERSION", &builder.rust_release())
422                 .replace("SHORT_HASH", builder.rust_info.sha_short().unwrap_or(""))
423                 .replace("STAMP", builder.rust_info.sha().unwrap_or(""));
424             t!(fs::write(&version_info, &info));
425         }
426
427         builder.copy(&builder.src.join("src").join("doc").join("rust.css"), &out.join("rust.css"));
428
429         SharedAssetsPaths { version_info }
430     }
431 }
432
433 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
434 pub struct Std {
435     pub stage: u32,
436     pub target: TargetSelection,
437     pub format: DocumentationFormat,
438 }
439
440 impl Step for Std {
441     type Output = ();
442     const DEFAULT: bool = true;
443
444     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
445         let builder = run.builder;
446         run.all_krates("test").path("library").default_condition(builder.config.docs)
447     }
448
449     fn make_run(run: RunConfig<'_>) {
450         run.builder.ensure(Std {
451             stage: run.builder.top_stage,
452             target: run.target,
453             format: if run.builder.config.cmd.json() {
454                 DocumentationFormat::JSON
455             } else {
456                 DocumentationFormat::HTML
457             },
458         });
459     }
460
461     /// Compile all standard library documentation.
462     ///
463     /// This will generate all documentation for the standard library and its
464     /// dependencies. This is largely just a wrapper around `cargo doc`.
465     fn run(self, builder: &Builder<'_>) {
466         let stage = self.stage;
467         let target = self.target;
468         let out = match self.format {
469             DocumentationFormat::HTML => builder.doc_out(target),
470             DocumentationFormat::JSON => builder.json_doc_out(target),
471         };
472
473         t!(fs::create_dir_all(&out));
474
475         builder.ensure(SharedAssets { target: self.target });
476
477         let index_page = builder.src.join("src/doc/index.md").into_os_string();
478         let mut extra_args = match self.format {
479             DocumentationFormat::HTML => vec![
480                 OsStr::new("--markdown-css"),
481                 OsStr::new("rust.css"),
482                 OsStr::new("--markdown-no-toc"),
483                 OsStr::new("--index-page"),
484                 &index_page,
485             ],
486             DocumentationFormat::JSON => vec![OsStr::new("--output-format"), OsStr::new("json")],
487         };
488
489         if !builder.config.docs_minification {
490             extra_args.push(OsStr::new("--disable-minification"));
491         }
492
493         let requested_crates = builder
494             .paths
495             .iter()
496             .map(components_simplified)
497             .filter_map(|path| {
498                 if path.len() >= 2 && path.get(0) == Some(&"library") {
499                     // single crate
500                     Some(path[1].to_owned())
501                 } else if !path.is_empty() {
502                     // ??
503                     Some(path[0].to_owned())
504                 } else {
505                     // all library crates
506                     None
507                 }
508             })
509             .collect::<Vec<_>>();
510
511         doc_std(builder, self.format, stage, target, &out, &extra_args, &requested_crates);
512
513         // Don't open if the format is json
514         if let DocumentationFormat::JSON = self.format {
515             return;
516         }
517
518         // Look for library/std, library/core etc in the `x.py doc` arguments and
519         // open the corresponding rendered docs.
520         for requested_crate in requested_crates {
521             if STD_PUBLIC_CRATES.iter().any(|k| *k == requested_crate.as_str()) {
522                 let index = out.join(requested_crate).join("index.html");
523                 open(builder, &index);
524             }
525         }
526     }
527 }
528
529 /// Name of the crates that are visible to consumers of the standard library.
530 /// Documentation for internal crates is handled by the rustc step, so internal crates will show
531 /// up there.
532 ///
533 /// Order here is important!
534 /// Crates need to be processed starting from the leaves, otherwise rustdoc will not
535 /// create correct links between crates because rustdoc depends on the
536 /// existence of the output directories to know if it should be a local
537 /// or remote link.
538 const STD_PUBLIC_CRATES: [&str; 5] = ["core", "alloc", "std", "proc_macro", "test"];
539
540 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
541 pub enum DocumentationFormat {
542     HTML,
543     JSON,
544 }
545
546 impl DocumentationFormat {
547     fn as_str(&self) -> &str {
548         match self {
549             DocumentationFormat::HTML => "HTML",
550             DocumentationFormat::JSON => "JSON",
551         }
552     }
553 }
554
555 /// Build the documentation for public standard library crates.
556 ///
557 /// `requested_crates` can be used to build only a subset of the crates. If empty, all crates will
558 /// be built.
559 fn doc_std(
560     builder: &Builder<'_>,
561     format: DocumentationFormat,
562     stage: u32,
563     target: TargetSelection,
564     out: &Path,
565     extra_args: &[&OsStr],
566     requested_crates: &[String],
567 ) {
568     builder.info(&format!(
569         "Documenting stage{} std ({}) in {} format",
570         stage,
571         target,
572         format.as_str()
573     ));
574     if builder.no_std(target) == Some(true) {
575         panic!(
576             "building std documentation for no_std target {target} is not supported\n\
577              Set `docs = false` in the config to disable documentation."
578         );
579     }
580     let compiler = builder.compiler(stage, builder.config.build);
581     // This is directory where the compiler will place the output of the command.
582     // We will then copy the files from this directory into the final `out` directory, the specified
583     // as a function parameter.
584     let out_dir = builder.stage_out(compiler, Mode::Std).join(target.triple).join("doc");
585     // `cargo` uses the same directory for both JSON docs and HTML docs.
586     // This could lead to cross-contamination when copying files into the specified `out` directory.
587     // For example:
588     // ```bash
589     // x doc std
590     // x doc std --json
591     // ```
592     // could lead to HTML docs being copied into the JSON docs output directory.
593     // To avoid this issue, we clean the doc folder before invoking `cargo`.
594     if out_dir.exists() {
595         builder.remove_dir(&out_dir);
596     }
597
598     let run_cargo_rustdoc_for = |package: &str| {
599         let mut cargo = builder.cargo(compiler, Mode::Std, SourceType::InTree, target, "rustdoc");
600         compile::std_cargo(builder, target, compiler.stage, &mut cargo);
601         cargo
602             .arg("-p")
603             .arg(package)
604             .arg("-Zskip-rustdoc-fingerprint")
605             .arg("--")
606             .arg("-Z")
607             .arg("unstable-options")
608             .arg("--resource-suffix")
609             .arg(&builder.version)
610             .args(extra_args);
611         builder.run(&mut cargo.into());
612     };
613
614     for krate in STD_PUBLIC_CRATES {
615         run_cargo_rustdoc_for(krate);
616         if requested_crates.iter().any(|p| p == krate) {
617             // No need to document more of the libraries if we have the one we want.
618             break;
619         }
620     }
621
622     builder.cp_r(&out_dir, &out);
623 }
624
625 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
626 pub struct Rustc {
627     pub stage: u32,
628     pub target: TargetSelection,
629 }
630
631 impl Step for Rustc {
632     type Output = ();
633     const DEFAULT: bool = true;
634     const ONLY_HOSTS: bool = true;
635
636     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
637         let builder = run.builder;
638         run.crate_or_deps("rustc-main")
639             .path("compiler")
640             .default_condition(builder.config.compiler_docs)
641     }
642
643     fn make_run(run: RunConfig<'_>) {
644         run.builder.ensure(Rustc { stage: run.builder.top_stage, target: run.target });
645     }
646
647     /// Generates compiler documentation.
648     ///
649     /// This will generate all documentation for compiler and dependencies.
650     /// Compiler documentation is distributed separately, so we make sure
651     /// we do not merge it with the other documentation from std, test and
652     /// proc_macros. This is largely just a wrapper around `cargo doc`.
653     fn run(self, builder: &Builder<'_>) {
654         let stage = self.stage;
655         let target = self.target;
656
657         let paths = builder
658             .paths
659             .iter()
660             .filter(|path| {
661                 let components = components_simplified(path);
662                 components.len() >= 2 && components[0] == "compiler"
663             })
664             .collect::<Vec<_>>();
665
666         // This is the intended out directory for compiler documentation.
667         let out = builder.compiler_doc_out(target);
668         t!(fs::create_dir_all(&out));
669
670         // Build the standard library, so that proc-macros can use it.
671         // (Normally, only the metadata would be necessary, but proc-macros are special since they run at compile-time.)
672         let compiler = builder.compiler(stage, builder.config.build);
673         builder.ensure(compile::Std::new(compiler, builder.config.build));
674
675         builder.info(&format!("Documenting stage{} compiler ({})", stage, target));
676
677         // This uses a shared directory so that librustdoc documentation gets
678         // correctly built and merged with the rustc documentation. This is
679         // needed because rustdoc is built in a different directory from
680         // rustc. rustdoc needs to be able to see everything, for example when
681         // merging the search index, or generating local (relative) links.
682         let out_dir = builder.stage_out(compiler, Mode::Rustc).join(target.triple).join("doc");
683         t!(symlink_dir_force(&builder.config, &out, &out_dir));
684         // Cargo puts proc macros in `target/doc` even if you pass `--target`
685         // explicitly (https://github.com/rust-lang/cargo/issues/7677).
686         let proc_macro_out_dir = builder.stage_out(compiler, Mode::Rustc).join("doc");
687         t!(symlink_dir_force(&builder.config, &out, &proc_macro_out_dir));
688
689         // Build cargo command.
690         let mut cargo = builder.cargo(compiler, Mode::Rustc, SourceType::InTree, target, "doc");
691         cargo.rustdocflag("--document-private-items");
692         // Since we always pass --document-private-items, there's no need to warn about linking to private items.
693         cargo.rustdocflag("-Arustdoc::private-intra-doc-links");
694         cargo.rustdocflag("--enable-index-page");
695         cargo.rustdocflag("-Zunstable-options");
696         cargo.rustdocflag("-Znormalize-docs");
697         cargo.rustdocflag("--show-type-layout");
698         cargo.rustdocflag("--generate-link-to-definition");
699         compile::rustc_cargo(builder, &mut cargo, target);
700         cargo.arg("-Zunstable-options");
701         cargo.arg("-Zskip-rustdoc-fingerprint");
702
703         // Only include compiler crates, no dependencies of those, such as `libc`.
704         // Do link to dependencies on `docs.rs` however using `rustdoc-map`.
705         cargo.arg("--no-deps");
706         cargo.arg("-Zrustdoc-map");
707
708         // FIXME: `-Zrustdoc-map` does not yet correctly work for transitive dependencies,
709         // once this is no longer an issue the special case for `ena` can be removed.
710         cargo.rustdocflag("--extern-html-root-url");
711         cargo.rustdocflag("ena=https://docs.rs/ena/latest/");
712
713         let root_crates = if paths.is_empty() {
714             vec![
715                 INTERNER.intern_str("rustc_driver"),
716                 INTERNER.intern_str("rustc_codegen_llvm"),
717                 INTERNER.intern_str("rustc_codegen_ssa"),
718             ]
719         } else {
720             paths.into_iter().map(|p| builder.crate_paths[p]).collect()
721         };
722         // Find dependencies for top level crates.
723         let compiler_crates = root_crates.iter().flat_map(|krate| {
724             builder.in_tree_crates(krate, Some(target)).into_iter().map(|krate| krate.name)
725         });
726
727         let mut to_open = None;
728         for krate in compiler_crates {
729             // Create all crate output directories first to make sure rustdoc uses
730             // relative links.
731             // FIXME: Cargo should probably do this itself.
732             t!(fs::create_dir_all(out_dir.join(krate)));
733             cargo.arg("-p").arg(krate);
734             if to_open.is_none() {
735                 to_open = Some(krate);
736             }
737         }
738
739         builder.run(&mut cargo.into());
740         // Let's open the first crate documentation page:
741         if let Some(krate) = to_open {
742             let index = out.join(krate).join("index.html");
743             open(builder, &index);
744         }
745     }
746 }
747
748 macro_rules! tool_doc {
749     ($tool: ident, $should_run: literal, $path: literal, [$($krate: literal),+ $(,)?] $(,)?) => {
750         #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
751         pub struct $tool {
752             target: TargetSelection,
753         }
754
755         impl Step for $tool {
756             type Output = ();
757             const DEFAULT: bool = true;
758             const ONLY_HOSTS: bool = true;
759
760             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
761                 let builder = run.builder;
762                 run.crate_or_deps($should_run).default_condition(builder.config.compiler_docs)
763             }
764
765             fn make_run(run: RunConfig<'_>) {
766                 run.builder.ensure($tool { target: run.target });
767             }
768
769             /// Generates compiler documentation.
770             ///
771             /// This will generate all documentation for compiler and dependencies.
772             /// Compiler documentation is distributed separately, so we make sure
773             /// we do not merge it with the other documentation from std, test and
774             /// proc_macros. This is largely just a wrapper around `cargo doc`.
775             fn run(self, builder: &Builder<'_>) {
776                 let stage = builder.top_stage;
777                 let target = self.target;
778
779                 // This is the intended out directory for compiler documentation.
780                 let out = builder.compiler_doc_out(target);
781                 t!(fs::create_dir_all(&out));
782
783                 // Build rustc docs so that we generate relative links.
784                 builder.ensure(Rustc { stage, target });
785                 // Rustdoc needs the rustc sysroot available to build.
786                 // FIXME: is there a way to only ensure `check::Rustc` here? Last time I tried it failed
787                 // with strange errors, but only on a full bors test ...
788                 let compiler = builder.compiler(stage, builder.config.build);
789                 builder.ensure(compile::Rustc::new(compiler, target));
790
791                 builder.info(
792                     &format!(
793                         "Documenting stage{} {} ({})",
794                         stage,
795                         stringify!($tool).to_lowercase(),
796                         target,
797                     ),
798                 );
799
800                 // Symlink compiler docs to the output directory of rustdoc documentation.
801                 let out_dir = builder.stage_out(compiler, Mode::ToolRustc).join(target.triple).join("doc");
802                 t!(fs::create_dir_all(&out_dir));
803                 t!(symlink_dir_force(&builder.config, &out, &out_dir));
804
805                 // Build cargo command.
806                 let mut cargo = prepare_tool_cargo(
807                     builder,
808                     compiler,
809                     Mode::ToolRustc,
810                     target,
811                     "doc",
812                     $path,
813                     SourceType::InTree,
814                     &[],
815                 );
816
817                 cargo.arg("-Zskip-rustdoc-fingerprint");
818                 // Only include compiler crates, no dependencies of those, such as `libc`.
819                 cargo.arg("--no-deps");
820                 $(
821                     cargo.arg("-p").arg($krate);
822                 )+
823
824                 cargo.rustdocflag("--document-private-items");
825                 cargo.rustdocflag("--enable-index-page");
826                 cargo.rustdocflag("--show-type-layout");
827                 cargo.rustdocflag("--generate-link-to-definition");
828                 cargo.rustdocflag("-Zunstable-options");
829                 builder.run(&mut cargo.into());
830             }
831         }
832     }
833 }
834
835 tool_doc!(Rustdoc, "rustdoc-tool", "src/tools/rustdoc", ["rustdoc", "rustdoc-json-types"],);
836 tool_doc!(
837     Rustfmt,
838     "rustfmt-nightly",
839     "src/tools/rustfmt",
840     ["rustfmt-nightly", "rustfmt-config_proc_macro"],
841 );
842 tool_doc!(Clippy, "clippy", "src/tools/clippy", ["clippy_utils"]);
843 tool_doc!(Miri, "miri", "src/tools/miri", ["miri"]);
844
845 #[derive(Ord, PartialOrd, Debug, Copy, Clone, Hash, PartialEq, Eq)]
846 pub struct ErrorIndex {
847     pub target: TargetSelection,
848 }
849
850 impl Step for ErrorIndex {
851     type Output = ();
852     const DEFAULT: bool = true;
853     const ONLY_HOSTS: bool = true;
854
855     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
856         let builder = run.builder;
857         run.path("src/tools/error_index_generator").default_condition(builder.config.docs)
858     }
859
860     fn make_run(run: RunConfig<'_>) {
861         let target = run.target;
862         run.builder.ensure(ErrorIndex { target });
863     }
864
865     /// Generates the HTML rendered error-index by running the
866     /// `error_index_generator` tool.
867     fn run(self, builder: &Builder<'_>) {
868         builder.info(&format!("Documenting error index ({})", self.target));
869         let out = builder.doc_out(self.target);
870         t!(fs::create_dir_all(&out));
871         let mut index = tool::ErrorIndex::command(builder);
872         index.arg("html");
873         index.arg(out);
874         index.arg(&builder.version);
875
876         builder.run(&mut index);
877     }
878 }
879
880 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
881 pub struct UnstableBookGen {
882     target: TargetSelection,
883 }
884
885 impl Step for UnstableBookGen {
886     type Output = ();
887     const DEFAULT: bool = true;
888     const ONLY_HOSTS: bool = true;
889
890     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
891         let builder = run.builder;
892         run.path("src/tools/unstable-book-gen").default_condition(builder.config.docs)
893     }
894
895     fn make_run(run: RunConfig<'_>) {
896         run.builder.ensure(UnstableBookGen { target: run.target });
897     }
898
899     fn run(self, builder: &Builder<'_>) {
900         let target = self.target;
901
902         builder.info(&format!("Generating unstable book md files ({})", target));
903         let out = builder.md_doc_out(target).join("unstable-book");
904         builder.create_dir(&out);
905         builder.remove_dir(&out);
906         let mut cmd = builder.tool_cmd(Tool::UnstableBookGen);
907         cmd.arg(builder.src.join("library"));
908         cmd.arg(builder.src.join("compiler"));
909         cmd.arg(builder.src.join("src"));
910         cmd.arg(out);
911
912         builder.run(&mut cmd);
913     }
914 }
915
916 fn symlink_dir_force(config: &Config, src: &Path, dst: &Path) -> io::Result<()> {
917     if config.dry_run {
918         return Ok(());
919     }
920     if let Ok(m) = fs::symlink_metadata(dst) {
921         if m.file_type().is_dir() {
922             fs::remove_dir_all(dst)?;
923         } else {
924             // handle directory junctions on windows by falling back to
925             // `remove_dir`.
926             fs::remove_file(dst).or_else(|_| fs::remove_dir(dst))?;
927         }
928     }
929
930     symlink_dir(config, src, dst)
931 }
932
933 #[derive(Ord, PartialOrd, Debug, Copy, Clone, Hash, PartialEq, Eq)]
934 pub struct RustcBook {
935     pub compiler: Compiler,
936     pub target: TargetSelection,
937     pub validate: bool,
938 }
939
940 impl Step for RustcBook {
941     type Output = ();
942     const DEFAULT: bool = true;
943     const ONLY_HOSTS: bool = true;
944
945     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
946         let builder = run.builder;
947         run.path("src/doc/rustc").default_condition(builder.config.docs)
948     }
949
950     fn make_run(run: RunConfig<'_>) {
951         run.builder.ensure(RustcBook {
952             compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
953             target: run.target,
954             validate: false,
955         });
956     }
957
958     /// Builds the rustc book.
959     ///
960     /// The lints are auto-generated by a tool, and then merged into the book
961     /// in the "md-doc" directory in the build output directory. Then
962     /// "rustbook" is used to convert it to HTML.
963     fn run(self, builder: &Builder<'_>) {
964         let out_base = builder.md_doc_out(self.target).join("rustc");
965         t!(fs::create_dir_all(&out_base));
966         let out_listing = out_base.join("src/lints");
967         builder.cp_r(&builder.src.join("src/doc/rustc"), &out_base);
968         builder.info(&format!("Generating lint docs ({})", self.target));
969
970         let rustc = builder.rustc(self.compiler);
971         // The tool runs `rustc` for extracting output examples, so it needs a
972         // functional sysroot.
973         builder.ensure(compile::Std::new(self.compiler, self.target));
974         let mut cmd = builder.tool_cmd(Tool::LintDocs);
975         cmd.arg("--src");
976         cmd.arg(builder.src.join("compiler"));
977         cmd.arg("--out");
978         cmd.arg(&out_listing);
979         cmd.arg("--rustc");
980         cmd.arg(&rustc);
981         cmd.arg("--rustc-target").arg(&self.target.rustc_target_arg());
982         if builder.config.verbose() {
983             cmd.arg("--verbose");
984         }
985         if self.validate {
986             cmd.arg("--validate");
987         }
988         if !builder.unstable_features() {
989             // We need to validate nightly features, even on the stable channel.
990             cmd.env("RUSTC_BOOTSTRAP", "1");
991         }
992         // If the lib directories are in an unusual location (changed in
993         // config.toml), then this needs to explicitly update the dylib search
994         // path.
995         builder.add_rustc_lib_path(self.compiler, &mut cmd);
996         builder.run(&mut cmd);
997         // Run rustbook/mdbook to generate the HTML pages.
998         builder.ensure(RustbookSrc {
999             target: self.target,
1000             name: INTERNER.intern_str("rustc"),
1001             src: INTERNER.intern_path(out_base),
1002         });
1003         if builder.was_invoked_explicitly::<Self>(Kind::Doc) {
1004             let out = builder.doc_out(self.target);
1005             let index = out.join("rustc").join("index.html");
1006             open(builder, &index);
1007         }
1008     }
1009 }