]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/doc.rs
Rollup merge of #93862 - Mark-Simulacrum:apple-split, r=pietroalbini
[rust.git] / src / bootstrap / doc.rs
1 //! Documentation generation for rustbuilder.
2 //!
3 //! This module implements generation for all bits and pieces of documentation
4 //! for the Rust project. This notably includes suites like the rust book, the
5 //! nomicon, rust by example, standalone documentation, etc.
6 //!
7 //! Everything here is basically just a shim around calling either `rustbook` or
8 //! `rustdoc`.
9
10 use std::collections::HashSet;
11 use std::fs;
12 use std::io;
13 use std::path::{Path, PathBuf};
14
15 use crate::Mode;
16 use build_helper::{t, up_to_date};
17
18 use crate::builder::{Builder, Compiler, Kind, RunConfig, ShouldRun, Step};
19 use crate::cache::{Interned, INTERNER};
20 use crate::compile;
21 use crate::config::{Config, TargetSelection};
22 use crate::tool::{self, prepare_tool_cargo, SourceType, Tool};
23 use crate::util::symlink_dir;
24
25 macro_rules! submodule_helper {
26     ($path:expr, submodule) => {
27         $path
28     };
29     ($path:expr, submodule = $submodule:literal) => {
30         $submodule
31     };
32 }
33
34 macro_rules! book {
35     ($($name:ident, $path:expr, $book_name:expr $(, submodule $(= $submodule:literal)? )? ;)+) => {
36         $(
37             #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
38         pub struct $name {
39             target: TargetSelection,
40         }
41
42         impl Step for $name {
43             type Output = ();
44             const DEFAULT: bool = true;
45
46             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
47                 let builder = run.builder;
48                 run.path($path).default_condition(builder.config.docs)
49             }
50
51             fn make_run(run: RunConfig<'_>) {
52                 run.builder.ensure($name {
53                     target: run.target,
54                 });
55             }
56
57             fn run(self, builder: &Builder<'_>) {
58                 $(
59                     let path = Path::new(submodule_helper!( $path, submodule $( = $submodule )? ));
60                     builder.update_submodule(&path);
61                 )?
62                 builder.ensure(RustbookSrc {
63                     target: self.target,
64                     name: INTERNER.intern_str($book_name),
65                     src: INTERNER.intern_path(builder.src.join($path)),
66                 })
67             }
68         }
69         )+
70     }
71 }
72
73 // NOTE: When adding a book here, make sure to ALSO build the book by
74 // adding a build step in `src/bootstrap/builder.rs`!
75 // NOTE: Make sure to add the corresponding submodule when adding a new book.
76 // FIXME: Make checking for a submodule automatic somehow (maybe by having a list of all submodules
77 // and checking against it?).
78 book!(
79     CargoBook, "src/tools/cargo/src/doc", "cargo", submodule = "src/tools/cargo";
80     EditionGuide, "src/doc/edition-guide", "edition-guide", submodule;
81     EmbeddedBook, "src/doc/embedded-book", "embedded-book", submodule;
82     Nomicon, "src/doc/nomicon", "nomicon", submodule;
83     Reference, "src/doc/reference", "reference", submodule;
84     RustByExample, "src/doc/rust-by-example", "rust-by-example", submodule;
85     RustdocBook, "src/doc/rustdoc", "rustdoc";
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")
389                     .arg(format!("https://doc.rust-lang.org/rustdoc{}.css", &builder.version))
390                     .arg("--markdown-css")
391                     .arg("https://doc.rust-lang.org/rust.css");
392             } else {
393                 cmd.arg("--markdown-css")
394                     .arg(format!("rustdoc{}.css", &builder.version))
395                     .arg("--markdown-css")
396                     .arg("rust.css");
397             }
398             builder.run(&mut cmd);
399         }
400
401         // We open doc/index.html as the default if invoked as `x.py doc --open`
402         // with no particular explicit doc requested (e.g. library/core).
403         if builder.paths.is_empty() || builder.was_invoked_explicitly::<Self>(Kind::Doc) {
404             let index = out.join("index.html");
405             open(builder, &index);
406         }
407     }
408 }
409
410 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
411 pub struct Std {
412     pub stage: u32,
413     pub target: TargetSelection,
414 }
415
416 impl Step for Std {
417     type Output = ();
418     const DEFAULT: bool = true;
419
420     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
421         let builder = run.builder;
422         run.all_krates("test").default_condition(builder.config.docs)
423     }
424
425     fn make_run(run: RunConfig<'_>) {
426         run.builder.ensure(Std { stage: run.builder.top_stage, target: run.target });
427     }
428
429     /// Compile all standard library documentation.
430     ///
431     /// This will generate all documentation for the standard library and its
432     /// dependencies. This is largely just a wrapper around `cargo doc`.
433     fn run(self, builder: &Builder<'_>) {
434         let stage = self.stage;
435         let target = self.target;
436         builder.info(&format!("Documenting stage{} std ({})", stage, target));
437         let out = builder.doc_out(target);
438         t!(fs::create_dir_all(&out));
439         let compiler = builder.compiler(stage, builder.config.build);
440
441         builder.ensure(compile::Std { compiler, target });
442         let out_dir = builder.stage_out(compiler, Mode::Std).join(target.triple).join("doc");
443
444         t!(fs::copy(builder.src.join("src/doc/rust.css"), out.join("rust.css")));
445
446         let run_cargo_rustdoc_for = |package: &str| {
447             let mut cargo =
448                 builder.cargo(compiler, Mode::Std, SourceType::InTree, target, "rustdoc");
449             compile::std_cargo(builder, target, compiler.stage, &mut cargo);
450
451             cargo
452                 .arg("-p")
453                 .arg(package)
454                 .arg("-Zskip-rustdoc-fingerprint")
455                 .arg("--")
456                 .arg("--markdown-css")
457                 .arg("rust.css")
458                 .arg("--markdown-no-toc")
459                 .arg("-Z")
460                 .arg("unstable-options")
461                 .arg("--resource-suffix")
462                 .arg(&builder.version)
463                 .arg("--index-page")
464                 .arg(&builder.src.join("src/doc/index.md"));
465
466             if !builder.config.docs_minification {
467                 cargo.arg("--disable-minification");
468             }
469
470             builder.run(&mut cargo.into());
471         };
472
473         let paths = builder
474             .paths
475             .iter()
476             .map(components_simplified)
477             .filter_map(|path| {
478                 if path.get(0) == Some(&"library") {
479                     Some(path[1].to_owned())
480                 } else if !path.is_empty() {
481                     Some(path[0].to_owned())
482                 } else {
483                     None
484                 }
485             })
486             .collect::<Vec<_>>();
487
488         // Only build the following crates. While we could just iterate over the
489         // folder structure, that would also build internal crates that we do
490         // not want to show in documentation. These crates will later be visited
491         // by the rustc step, so internal documentation will show them.
492         //
493         // Note that the order here is important! The crates need to be
494         // processed starting from the leaves, otherwise rustdoc will not
495         // create correct links between crates because rustdoc depends on the
496         // existence of the output directories to know if it should be a local
497         // or remote link.
498         let krates = ["core", "alloc", "std", "proc_macro", "test"];
499         for krate in &krates {
500             run_cargo_rustdoc_for(krate);
501             if paths.iter().any(|p| p == krate) {
502                 // No need to document more of the libraries if we have the one we want.
503                 break;
504             }
505         }
506         builder.cp_r(&out_dir, &out);
507
508         // Look for library/std, library/core etc in the `x.py doc` arguments and
509         // open the corresponding rendered docs.
510         for requested_crate in paths {
511             if krates.iter().any(|k| *k == requested_crate.as_str()) {
512                 let index = out.join(requested_crate).join("index.html");
513                 open(builder, &index);
514             }
515         }
516     }
517 }
518
519 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
520 pub struct Rustc {
521     pub stage: u32,
522     pub target: TargetSelection,
523 }
524
525 impl Step for Rustc {
526     type Output = ();
527     const DEFAULT: bool = true;
528     const ONLY_HOSTS: bool = true;
529
530     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
531         let builder = run.builder;
532         run.krate("rustc-main").path("compiler").default_condition(builder.config.compiler_docs)
533     }
534
535     fn make_run(run: RunConfig<'_>) {
536         run.builder.ensure(Rustc { stage: run.builder.top_stage, target: run.target });
537     }
538
539     /// Generates compiler documentation.
540     ///
541     /// This will generate all documentation for compiler and dependencies.
542     /// Compiler documentation is distributed separately, so we make sure
543     /// we do not merge it with the other documentation from std, test and
544     /// proc_macros. This is largely just a wrapper around `cargo doc`.
545     fn run(self, builder: &Builder<'_>) {
546         let stage = self.stage;
547         let target = self.target;
548         builder.info(&format!("Documenting stage{} compiler ({})", stage, target));
549
550         let paths = builder
551             .paths
552             .iter()
553             .map(components_simplified)
554             .filter_map(|path| {
555                 if path.get(0) == Some(&"compiler") {
556                     path.get(1).map(|p| p.to_owned())
557                 } else {
558                     None
559                 }
560             })
561             .collect::<Vec<_>>();
562
563         // This is the intended out directory for compiler documentation.
564         let out = builder.compiler_doc_out(target);
565         t!(fs::create_dir_all(&out));
566
567         // Build rustc.
568         let compiler = builder.compiler(stage, builder.config.build);
569         builder.ensure(compile::Rustc { compiler, target });
570
571         // This uses a shared directory so that librustdoc documentation gets
572         // correctly built and merged with the rustc documentation. This is
573         // needed because rustdoc is built in a different directory from
574         // rustc. rustdoc needs to be able to see everything, for example when
575         // merging the search index, or generating local (relative) links.
576         let out_dir = builder.stage_out(compiler, Mode::Rustc).join(target.triple).join("doc");
577         t!(symlink_dir_force(&builder.config, &out, &out_dir));
578         // Cargo puts proc macros in `target/doc` even if you pass `--target`
579         // explicitly (https://github.com/rust-lang/cargo/issues/7677).
580         let proc_macro_out_dir = builder.stage_out(compiler, Mode::Rustc).join("doc");
581         t!(symlink_dir_force(&builder.config, &out, &proc_macro_out_dir));
582
583         // Build cargo command.
584         let mut cargo = builder.cargo(compiler, Mode::Rustc, SourceType::InTree, target, "doc");
585         cargo.rustdocflag("--document-private-items");
586         // Since we always pass --document-private-items, there's no need to warn about linking to private items.
587         cargo.rustdocflag("-Arustdoc::private-intra-doc-links");
588         cargo.rustdocflag("--enable-index-page");
589         cargo.rustdocflag("-Zunstable-options");
590         cargo.rustdocflag("-Znormalize-docs");
591         cargo.rustdocflag("--show-type-layout");
592         cargo.rustdocflag("--generate-link-to-definition");
593         compile::rustc_cargo(builder, &mut cargo, target);
594         cargo.arg("-Zunstable-options");
595         cargo.arg("-Zskip-rustdoc-fingerprint");
596
597         // Only include compiler crates, no dependencies of those, such as `libc`.
598         // Do link to dependencies on `docs.rs` however using `rustdoc-map`.
599         cargo.arg("--no-deps");
600         cargo.arg("-Zrustdoc-map");
601
602         // FIXME: `-Zrustdoc-map` does not yet correctly work for transitive dependencies,
603         // once this is no longer an issue the special case for `ena` can be removed.
604         cargo.rustdocflag("--extern-html-root-url");
605         cargo.rustdocflag("ena=https://docs.rs/ena/latest/");
606
607         let mut compiler_crates = HashSet::new();
608
609         if paths.is_empty() {
610             // Find dependencies for top level crates.
611             for root_crate in &["rustc_driver", "rustc_codegen_llvm", "rustc_codegen_ssa"] {
612                 compiler_crates.extend(
613                     builder
614                         .in_tree_crates(root_crate, Some(target))
615                         .into_iter()
616                         .map(|krate| krate.name),
617                 );
618             }
619         } else {
620             for root_crate in paths {
621                 if !builder.src.join("compiler").join(&root_crate).exists() {
622                     builder.info(&format!(
623                         "\tskipping - compiler/{} (unknown compiler crate)",
624                         root_crate
625                     ));
626                 } else {
627                     compiler_crates.extend(
628                         builder
629                             .in_tree_crates(root_crate, Some(target))
630                             .into_iter()
631                             .map(|krate| krate.name),
632                     );
633                 }
634             }
635         }
636
637         let mut to_open = None;
638         for krate in &compiler_crates {
639             // Create all crate output directories first to make sure rustdoc uses
640             // relative links.
641             // FIXME: Cargo should probably do this itself.
642             t!(fs::create_dir_all(out_dir.join(krate)));
643             cargo.arg("-p").arg(krate);
644             if to_open.is_none() {
645                 to_open = Some(krate);
646             }
647         }
648
649         builder.run(&mut cargo.into());
650         // Let's open the first crate documentation page:
651         if let Some(krate) = to_open {
652             let index = out.join(krate).join("index.html");
653             open(builder, &index);
654         }
655     }
656 }
657
658 macro_rules! tool_doc {
659     ($tool: ident, $should_run: literal, $path: literal, [$($krate: literal),+ $(,)?] $(,)?) => {
660         #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
661         pub struct $tool {
662             stage: u32,
663             target: TargetSelection,
664         }
665
666         impl Step for $tool {
667             type Output = ();
668             const DEFAULT: bool = true;
669             const ONLY_HOSTS: bool = true;
670
671             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
672                 let builder = run.builder;
673                 run.krate($should_run).default_condition(builder.config.compiler_docs)
674             }
675
676             fn make_run(run: RunConfig<'_>) {
677                 run.builder.ensure($tool { stage: run.builder.top_stage, target: run.target });
678             }
679
680             /// Generates compiler documentation.
681             ///
682             /// This will generate all documentation for compiler and dependencies.
683             /// Compiler documentation is distributed separately, so we make sure
684             /// we do not merge it with the other documentation from std, test and
685             /// proc_macros. This is largely just a wrapper around `cargo doc`.
686             fn run(self, builder: &Builder<'_>) {
687                 let stage = self.stage;
688                 let target = self.target;
689                 builder.info(
690                     &format!(
691                         "Documenting stage{} {} ({})",
692                         stage,
693                         stringify!($tool).to_lowercase(),
694                         target,
695                     ),
696                 );
697
698                 // This is the intended out directory for compiler documentation.
699                 let out = builder.compiler_doc_out(target);
700                 t!(fs::create_dir_all(&out));
701
702                 let compiler = builder.compiler(stage, builder.config.build);
703
704                 // Build rustc docs so that we generate relative links.
705                 builder.ensure(Rustc { stage, target });
706
707                 // Symlink compiler docs to the output directory of rustdoc documentation.
708                 let out_dir = builder.stage_out(compiler, Mode::ToolRustc).join(target.triple).join("doc");
709                 t!(fs::create_dir_all(&out_dir));
710                 t!(symlink_dir_force(&builder.config, &out, &out_dir));
711
712                 // Build cargo command.
713                 let mut cargo = prepare_tool_cargo(
714                     builder,
715                     compiler,
716                     Mode::ToolRustc,
717                     target,
718                     "doc",
719                     $path,
720                     SourceType::InTree,
721                     &[],
722                 );
723
724                 cargo.arg("-Zskip-rustdoc-fingerprint");
725                 // Only include compiler crates, no dependencies of those, such as `libc`.
726                 cargo.arg("--no-deps");
727                 $(
728                     cargo.arg("-p").arg($krate);
729                 )+
730
731                 cargo.rustdocflag("--document-private-items");
732                 cargo.rustdocflag("--enable-index-page");
733                 cargo.rustdocflag("--show-type-layout");
734                 cargo.rustdocflag("--generate-link-to-definition");
735                 cargo.rustdocflag("-Zunstable-options");
736                 builder.run(&mut cargo.into());
737             }
738         }
739     }
740 }
741
742 tool_doc!(Rustdoc, "rustdoc-tool", "src/tools/rustdoc", ["rustdoc", "rustdoc-json-types"]);
743 tool_doc!(
744     Rustfmt,
745     "rustfmt-nightly",
746     "src/tools/rustfmt",
747     ["rustfmt-nightly", "rustfmt-config_proc_macro"],
748 );
749 tool_doc!(Clippy, "clippy", "src/tools/clippy", ["clippy_utils"]);
750
751 #[derive(Ord, PartialOrd, Debug, Copy, Clone, Hash, PartialEq, Eq)]
752 pub struct ErrorIndex {
753     pub target: TargetSelection,
754 }
755
756 impl Step for ErrorIndex {
757     type Output = ();
758     const DEFAULT: bool = true;
759     const ONLY_HOSTS: bool = true;
760
761     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
762         let builder = run.builder;
763         run.path("src/tools/error_index_generator").default_condition(builder.config.docs)
764     }
765
766     fn make_run(run: RunConfig<'_>) {
767         let target = run.target;
768         run.builder.ensure(ErrorIndex { target });
769     }
770
771     /// Generates the HTML rendered error-index by running the
772     /// `error_index_generator` tool.
773     fn run(self, builder: &Builder<'_>) {
774         builder.info(&format!("Documenting error index ({})", self.target));
775         let out = builder.doc_out(self.target);
776         t!(fs::create_dir_all(&out));
777         let mut index = tool::ErrorIndex::command(builder);
778         index.arg("html");
779         index.arg(out.join("error-index.html"));
780         index.arg(&builder.version);
781
782         builder.run(&mut index);
783     }
784 }
785
786 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
787 pub struct UnstableBookGen {
788     target: TargetSelection,
789 }
790
791 impl Step for UnstableBookGen {
792     type Output = ();
793     const DEFAULT: bool = true;
794     const ONLY_HOSTS: bool = true;
795
796     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
797         let builder = run.builder;
798         run.path("src/tools/unstable-book-gen").default_condition(builder.config.docs)
799     }
800
801     fn make_run(run: RunConfig<'_>) {
802         run.builder.ensure(UnstableBookGen { target: run.target });
803     }
804
805     fn run(self, builder: &Builder<'_>) {
806         let target = self.target;
807
808         builder.info(&format!("Generating unstable book md files ({})", target));
809         let out = builder.md_doc_out(target).join("unstable-book");
810         builder.create_dir(&out);
811         builder.remove_dir(&out);
812         let mut cmd = builder.tool_cmd(Tool::UnstableBookGen);
813         cmd.arg(builder.src.join("library"));
814         cmd.arg(builder.src.join("compiler"));
815         cmd.arg(builder.src.join("src"));
816         cmd.arg(out);
817
818         builder.run(&mut cmd);
819     }
820 }
821
822 fn symlink_dir_force(config: &Config, src: &Path, dst: &Path) -> io::Result<()> {
823     if config.dry_run {
824         return Ok(());
825     }
826     if let Ok(m) = fs::symlink_metadata(dst) {
827         if m.file_type().is_dir() {
828             fs::remove_dir_all(dst)?;
829         } else {
830             // handle directory junctions on windows by falling back to
831             // `remove_dir`.
832             fs::remove_file(dst).or_else(|_| fs::remove_dir(dst))?;
833         }
834     }
835
836     symlink_dir(config, src, dst)
837 }
838
839 #[derive(Ord, PartialOrd, Debug, Copy, Clone, Hash, PartialEq, Eq)]
840 pub struct RustcBook {
841     pub compiler: Compiler,
842     pub target: TargetSelection,
843     pub validate: bool,
844 }
845
846 impl Step for RustcBook {
847     type Output = ();
848     const DEFAULT: bool = true;
849     const ONLY_HOSTS: bool = true;
850
851     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
852         let builder = run.builder;
853         run.path("src/doc/rustc").default_condition(builder.config.docs)
854     }
855
856     fn make_run(run: RunConfig<'_>) {
857         run.builder.ensure(RustcBook {
858             compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
859             target: run.target,
860             validate: false,
861         });
862     }
863
864     /// Builds the rustc book.
865     ///
866     /// The lints are auto-generated by a tool, and then merged into the book
867     /// in the "md-doc" directory in the build output directory. Then
868     /// "rustbook" is used to convert it to HTML.
869     fn run(self, builder: &Builder<'_>) {
870         let out_base = builder.md_doc_out(self.target).join("rustc");
871         t!(fs::create_dir_all(&out_base));
872         let out_listing = out_base.join("src/lints");
873         builder.cp_r(&builder.src.join("src/doc/rustc"), &out_base);
874         builder.info(&format!("Generating lint docs ({})", self.target));
875
876         let rustc = builder.rustc(self.compiler);
877         // The tool runs `rustc` for extracting output examples, so it needs a
878         // functional sysroot.
879         builder.ensure(compile::Std { compiler: self.compiler, target: self.target });
880         let mut cmd = builder.tool_cmd(Tool::LintDocs);
881         cmd.arg("--src");
882         cmd.arg(builder.src.join("compiler"));
883         cmd.arg("--out");
884         cmd.arg(&out_listing);
885         cmd.arg("--rustc");
886         cmd.arg(&rustc);
887         cmd.arg("--rustc-target").arg(&self.target.rustc_target_arg());
888         if builder.config.verbose() {
889             cmd.arg("--verbose");
890         }
891         if self.validate {
892             cmd.arg("--validate");
893         }
894         // If the lib directories are in an unusual location (changed in
895         // config.toml), then this needs to explicitly update the dylib search
896         // path.
897         builder.add_rustc_lib_path(self.compiler, &mut cmd);
898         builder.run(&mut cmd);
899         // Run rustbook/mdbook to generate the HTML pages.
900         builder.ensure(RustbookSrc {
901             target: self.target,
902             name: INTERNER.intern_str("rustc"),
903             src: INTERNER.intern_path(out_base),
904         });
905         if builder.was_invoked_explicitly::<Self>(Kind::Doc) {
906             let out = builder.doc_out(self.target);
907             let index = out.join("rustc").join("index.html");
908             open(builder, &index);
909         }
910     }
911 }