1 //! Documentation generation for rustbuilder.
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.
7 //! Everything here is basically just a shim around calling either `rustbook` or
10 use std::collections::HashSet;
13 use std::path::{Path, PathBuf};
16 use build_helper::{t, up_to_date};
18 use crate::builder::{Builder, Compiler, RunConfig, ShouldRun, Step};
19 use crate::cache::{Interned, INTERNER};
21 use crate::config::{Config, TargetSelection};
22 use crate::tool::{self, prepare_tool_cargo, SourceType, Tool};
23 use crate::util::symlink_dir;
26 ($($name:ident, $path:expr, $book_name:expr;)+) => {
28 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
30 target: TargetSelection,
35 const DEFAULT: bool = true;
37 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
38 let builder = run.builder;
39 run.path($path).default_condition(builder.config.docs)
42 fn make_run(run: RunConfig<'_>) {
43 run.builder.ensure($name {
48 fn run(self, builder: &Builder<'_>) {
49 builder.ensure(RustbookSrc {
51 name: INTERNER.intern_str($book_name),
52 src: INTERNER.intern_path(builder.src.join($path)),
60 // NOTE: When adding a book here, make sure to ALSO build the book by
61 // adding a build step in `src/bootstrap/builder.rs`!
63 CargoBook, "src/tools/cargo/src/doc", "cargo";
64 EditionGuide, "src/doc/edition-guide", "edition-guide";
65 EmbeddedBook, "src/doc/embedded-book", "embedded-book";
66 Nomicon, "src/doc/nomicon", "nomicon";
67 Reference, "src/doc/reference", "reference";
68 RustByExample, "src/doc/rust-by-example", "rust-by-example";
69 RustdocBook, "src/doc/rustdoc", "rustdoc";
72 fn open(builder: &Builder<'_>, path: impl AsRef<Path>) {
73 if builder.config.dry_run || !builder.config.cmd.open() {
77 let path = path.as_ref();
78 builder.info(&format!("Opening doc {}", path.display()));
79 if let Err(err) = opener::open(path) {
80 builder.info(&format!("{}\n", err));
84 // "library/std" -> ["library", "std"]
86 // Used for deciding whether a particular step is one requested by the user on
87 // the `x.py doc` command line, which determines whether `--open` will open that
89 fn components_simplified(path: &PathBuf) -> Vec<&str> {
90 path.iter().map(|component| component.to_str().unwrap_or("???")).collect()
93 fn is_explicit_request(builder: &Builder<'_>, path: &str) -> bool {
97 .map(components_simplified)
98 .any(|requested| requested.iter().copied().eq(path.split('/')))
101 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
102 pub struct UnstableBook {
103 target: TargetSelection,
106 impl Step for UnstableBook {
108 const DEFAULT: bool = true;
110 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
111 let builder = run.builder;
112 run.path("src/doc/unstable-book").default_condition(builder.config.docs)
115 fn make_run(run: RunConfig<'_>) {
116 run.builder.ensure(UnstableBook { target: run.target });
119 fn run(self, builder: &Builder<'_>) {
120 builder.ensure(UnstableBookGen { target: self.target });
121 builder.ensure(RustbookSrc {
123 name: INTERNER.intern_str("unstable-book"),
124 src: INTERNER.intern_path(builder.md_doc_out(self.target).join("unstable-book")),
129 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
131 target: TargetSelection,
132 name: Interned<String>,
133 src: Interned<PathBuf>,
136 impl Step for RustbookSrc {
139 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
143 /// Invoke `rustbook` for `target` for the doc book `name` from the `src` path.
145 /// This will not actually generate any documentation if the documentation has
146 /// already been generated.
147 fn run(self, builder: &Builder<'_>) {
148 let target = self.target;
149 let name = self.name;
151 let out = builder.doc_out(target);
152 t!(fs::create_dir_all(&out));
154 let out = out.join(name);
155 let index = out.join("index.html");
156 let rustbook = builder.tool_exe(Tool::Rustbook);
157 let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook);
158 if builder.config.dry_run || up_to_date(&src, &index) && up_to_date(&rustbook, &index) {
161 builder.info(&format!("Rustbook ({}) - {}", target, name));
162 let _ = fs::remove_dir_all(&out);
164 builder.run(rustbook_cmd.arg("build").arg(&src).arg("-d").arg(out));
168 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
171 target: TargetSelection,
174 impl Step for TheBook {
176 const DEFAULT: bool = true;
178 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
179 let builder = run.builder;
180 run.path("src/doc/book").default_condition(builder.config.docs)
183 fn make_run(run: RunConfig<'_>) {
184 run.builder.ensure(TheBook {
185 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
190 /// Builds the book and associated stuff.
192 /// We need to build:
195 /// * Older edition redirects
196 /// * Version info and CSS
199 fn run(self, builder: &Builder<'_>) {
200 let compiler = self.compiler;
201 let target = self.target;
204 builder.ensure(RustbookSrc {
206 name: INTERNER.intern_str("book"),
207 src: INTERNER.intern_path(builder.src.join("src/doc/book")),
210 // building older edition redirects
211 for edition in &["first-edition", "second-edition", "2018-edition"] {
212 builder.ensure(RustbookSrc {
214 name: INTERNER.intern_string(format!("book/{}", edition)),
215 src: INTERNER.intern_path(builder.src.join("src/doc/book").join(edition)),
219 // build the version info page and CSS
220 builder.ensure(Standalone { compiler, target });
222 // build the redirect pages
223 builder.info(&format!("Documenting book redirect pages ({})", target));
224 for file in t!(fs::read_dir(builder.src.join("src/doc/book/redirects"))) {
226 let path = file.path();
227 let path = path.to_str().unwrap();
229 invoke_rustdoc(builder, compiler, target, path);
232 if is_explicit_request(builder, "src/doc/book") {
233 let out = builder.doc_out(target);
234 let index = out.join("book").join("index.html");
235 open(builder, &index);
241 builder: &Builder<'_>,
243 target: TargetSelection,
246 let out = builder.doc_out(target);
248 let path = builder.src.join("src/doc").join(markdown);
250 let header = builder.src.join("src/doc/redirect.inc");
251 let footer = builder.src.join("src/doc/footer.inc");
252 let version_info = out.join("version_info.html");
254 let mut cmd = builder.rustdoc_cmd(compiler);
256 let out = out.join("book");
258 cmd.arg("--html-after-content")
260 .arg("--html-before-content")
262 .arg("--html-in-header")
264 .arg("--markdown-no-toc")
265 .arg("--markdown-playground-url")
266 .arg("https://play.rust-lang.org/")
270 .arg("--markdown-css")
273 builder.run(&mut cmd);
276 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
277 pub struct Standalone {
279 target: TargetSelection,
282 impl Step for Standalone {
284 const DEFAULT: bool = true;
286 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
287 let builder = run.builder;
288 run.path("src/doc").default_condition(builder.config.docs)
291 fn make_run(run: RunConfig<'_>) {
292 run.builder.ensure(Standalone {
293 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
298 /// Generates all standalone documentation as compiled by the rustdoc in `stage`
299 /// for the `target` into `out`.
301 /// This will list all of `src/doc` looking for markdown files and appropriately
302 /// perform transformations like substituting `VERSION`, `SHORT_HASH`, and
303 /// `STAMP` along with providing the various header/footer HTML we've customized.
305 /// In the end, this is just a glorified wrapper around rustdoc!
306 fn run(self, builder: &Builder<'_>) {
307 let target = self.target;
308 let compiler = self.compiler;
309 builder.info(&format!("Documenting standalone ({})", target));
310 let out = builder.doc_out(target);
311 t!(fs::create_dir_all(&out));
313 let favicon = builder.src.join("src/doc/favicon.inc");
314 let footer = builder.src.join("src/doc/footer.inc");
315 let full_toc = builder.src.join("src/doc/full-toc.inc");
316 t!(fs::copy(builder.src.join("src/doc/rust.css"), out.join("rust.css")));
318 let version_input = builder.src.join("src/doc/version_info.html.template");
319 let version_info = out.join("version_info.html");
321 if !builder.config.dry_run && !up_to_date(&version_input, &version_info) {
322 let info = t!(fs::read_to_string(&version_input))
323 .replace("VERSION", &builder.rust_release())
324 .replace("SHORT_HASH", builder.rust_info.sha_short().unwrap_or(""))
325 .replace("STAMP", builder.rust_info.sha().unwrap_or(""));
326 t!(fs::write(&version_info, &info));
329 for file in t!(fs::read_dir(builder.src.join("src/doc"))) {
331 let path = file.path();
332 let filename = path.file_name().unwrap().to_str().unwrap();
333 if !filename.ends_with(".md") || filename == "README.md" {
337 let html = out.join(filename).with_extension("html");
338 let rustdoc = builder.rustdoc(compiler);
339 if up_to_date(&path, &html)
340 && up_to_date(&footer, &html)
341 && up_to_date(&favicon, &html)
342 && up_to_date(&full_toc, &html)
343 && (builder.config.dry_run || up_to_date(&version_info, &html))
344 && (builder.config.dry_run || up_to_date(&rustdoc, &html))
349 let mut cmd = builder.rustdoc_cmd(compiler);
350 // Needed for --index-page flag
351 cmd.arg("-Z").arg("unstable-options");
353 cmd.arg("--html-after-content")
355 .arg("--html-before-content")
357 .arg("--html-in-header")
359 .arg("--markdown-no-toc")
361 .arg(&builder.src.join("src/doc/index.md"))
362 .arg("--markdown-playground-url")
363 .arg("https://play.rust-lang.org/")
368 if filename == "not_found.md" {
369 cmd.arg("--markdown-css").arg("https://doc.rust-lang.org/rust.css");
371 cmd.arg("--markdown-css").arg("rust.css");
373 builder.run(&mut cmd);
376 // We open doc/index.html as the default if invoked as `x.py doc --open`
377 // with no particular explicit doc requested (e.g. library/core).
378 if builder.paths.is_empty() || is_explicit_request(builder, "src/doc") {
379 let index = out.join("index.html");
380 open(builder, &index);
385 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
388 pub target: TargetSelection,
393 const DEFAULT: bool = true;
395 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
396 let builder = run.builder;
397 run.all_krates("test").default_condition(builder.config.docs)
400 fn make_run(run: RunConfig<'_>) {
401 run.builder.ensure(Std { stage: run.builder.top_stage, target: run.target });
404 /// Compile all standard library documentation.
406 /// This will generate all documentation for the standard library and its
407 /// dependencies. This is largely just a wrapper around `cargo doc`.
408 fn run(self, builder: &Builder<'_>) {
409 let stage = self.stage;
410 let target = self.target;
411 builder.info(&format!("Documenting stage{} std ({})", stage, target));
412 let out = builder.doc_out(target);
413 t!(fs::create_dir_all(&out));
414 let compiler = builder.compiler(stage, builder.config.build);
416 builder.ensure(compile::Std { compiler, target });
417 let out_dir = builder.stage_out(compiler, Mode::Std).join(target.triple).join("doc");
419 t!(fs::copy(builder.src.join("src/doc/rust.css"), out.join("rust.css")));
421 let run_cargo_rustdoc_for = |package: &str| {
423 builder.cargo(compiler, Mode::Std, SourceType::InTree, target, "rustdoc");
424 compile::std_cargo(builder, target, compiler.stage, &mut cargo);
430 .arg("--markdown-css")
432 .arg("--markdown-no-toc")
434 .arg("unstable-options")
435 .arg("--resource-suffix")
436 .arg(&builder.version)
438 .arg(&builder.src.join("src/doc/index.md"));
440 builder.run(&mut cargo.into());
442 // Only build the following crates. While we could just iterate over the
443 // folder structure, that would also build internal crates that we do
444 // not want to show in documentation. These crates will later be visited
445 // by the rustc step, so internal documentation will show them.
447 // Note that the order here is important! The crates need to be
448 // processed starting from the leaves, otherwise rustdoc will not
449 // create correct links between crates because rustdoc depends on the
450 // existence of the output directories to know if it should be a local
452 let krates = ["core", "alloc", "std", "proc_macro", "test"];
453 for krate in &krates {
454 run_cargo_rustdoc_for(krate);
456 builder.cp_r(&out_dir, &out);
458 // Look for library/std, library/core etc in the `x.py doc` arguments and
459 // open the corresponding rendered docs.
460 for path in builder.paths.iter().map(components_simplified) {
461 if path.get(0) == Some(&"library") {
462 let requested_crate = &path[1];
463 if krates.contains(&requested_crate) {
464 let index = out.join(requested_crate).join("index.html");
465 open(builder, &index);
472 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
475 target: TargetSelection,
478 impl Step for Rustc {
480 const DEFAULT: bool = true;
481 const ONLY_HOSTS: bool = true;
483 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
484 let builder = run.builder;
485 run.krate("rustc-main").default_condition(builder.config.docs)
488 fn make_run(run: RunConfig<'_>) {
489 run.builder.ensure(Rustc { stage: run.builder.top_stage, target: run.target });
492 /// Generates compiler documentation.
494 /// This will generate all documentation for compiler and dependencies.
495 /// Compiler documentation is distributed separately, so we make sure
496 /// we do not merge it with the other documentation from std, test and
497 /// proc_macros. This is largely just a wrapper around `cargo doc`.
498 fn run(self, builder: &Builder<'_>) {
499 let stage = self.stage;
500 let target = self.target;
501 builder.info(&format!("Documenting stage{} compiler ({})", stage, target));
503 if !builder.config.compiler_docs {
504 builder.info("\tskipping - compiler/librustdoc docs disabled");
508 // This is the intended out directory for compiler documentation.
509 let out = builder.compiler_doc_out(target);
510 t!(fs::create_dir_all(&out));
513 let compiler = builder.compiler(stage, builder.config.build);
514 builder.ensure(compile::Rustc { compiler, target });
516 // This uses a shared directory so that librustdoc documentation gets
517 // correctly built and merged with the rustc documentation. This is
518 // needed because rustdoc is built in a different directory from
519 // rustc. rustdoc needs to be able to see everything, for example when
520 // merging the search index, or generating local (relative) links.
521 let out_dir = builder.stage_out(compiler, Mode::Rustc).join(target.triple).join("doc");
522 t!(symlink_dir_force(&builder.config, &out, &out_dir));
523 // Cargo puts proc macros in `target/doc` even if you pass `--target`
524 // explicitly (https://github.com/rust-lang/cargo/issues/7677).
525 let proc_macro_out_dir = builder.stage_out(compiler, Mode::Rustc).join("doc");
526 t!(symlink_dir_force(&builder.config, &out, &proc_macro_out_dir));
528 // Build cargo command.
529 let mut cargo = builder.cargo(compiler, Mode::Rustc, SourceType::InTree, target, "doc");
530 cargo.rustdocflag("--document-private-items");
531 cargo.rustdocflag("--enable-index-page");
532 cargo.rustdocflag("-Zunstable-options");
533 cargo.rustdocflag("-Znormalize-docs");
534 compile::rustc_cargo(builder, &mut cargo, target);
536 // Only include compiler crates, no dependencies of those, such as `libc`.
537 cargo.arg("--no-deps");
539 // Find dependencies for top level crates.
540 let mut compiler_crates = HashSet::new();
541 for root_crate in &["rustc_driver", "rustc_codegen_llvm", "rustc_codegen_ssa"] {
542 compiler_crates.extend(
544 .in_tree_crates(root_crate, Some(target))
546 .map(|krate| krate.name),
550 for krate in &compiler_crates {
551 // Create all crate output directories first to make sure rustdoc uses
553 // FIXME: Cargo should probably do this itself.
554 t!(fs::create_dir_all(out_dir.join(krate)));
555 cargo.arg("-p").arg(krate);
558 builder.run(&mut cargo.into());
562 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
565 target: TargetSelection,
568 impl Step for Rustdoc {
570 const DEFAULT: bool = true;
571 const ONLY_HOSTS: bool = true;
573 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
574 run.krate("rustdoc-tool")
577 fn make_run(run: RunConfig<'_>) {
578 run.builder.ensure(Rustdoc { stage: run.builder.top_stage, target: run.target });
581 /// Generates compiler documentation.
583 /// This will generate all documentation for compiler and dependencies.
584 /// Compiler documentation is distributed separately, so we make sure
585 /// we do not merge it with the other documentation from std, test and
586 /// proc_macros. This is largely just a wrapper around `cargo doc`.
587 fn run(self, builder: &Builder<'_>) {
588 let stage = self.stage;
589 let target = self.target;
590 builder.info(&format!("Documenting stage{} rustdoc ({})", stage, target));
592 // This is the intended out directory for compiler documentation.
593 let out = builder.compiler_doc_out(target);
594 t!(fs::create_dir_all(&out));
596 let compiler = builder.compiler(stage, builder.config.build);
598 if !builder.config.compiler_docs {
599 builder.info("\tskipping - compiler/librustdoc docs disabled");
603 // Build rustc docs so that we generate relative links.
604 builder.ensure(Rustc { stage, target });
607 builder.ensure(tool::Rustdoc { compiler });
609 // Symlink compiler docs to the output directory of rustdoc documentation.
610 let out_dir = builder.stage_out(compiler, Mode::ToolRustc).join(target.triple).join("doc");
611 t!(fs::create_dir_all(&out_dir));
612 t!(symlink_dir_force(&builder.config, &out, &out_dir));
614 // Build cargo command.
615 let mut cargo = prepare_tool_cargo(
626 // Only include compiler crates, no dependencies of those, such as `libc`.
627 cargo.arg("--no-deps");
628 cargo.arg("-p").arg("rustdoc");
630 cargo.rustdocflag("--document-private-items");
631 cargo.rustdocflag("--enable-index-page");
632 cargo.rustdocflag("-Zunstable-options");
633 builder.run(&mut cargo.into());
637 #[derive(Ord, PartialOrd, Debug, Copy, Clone, Hash, PartialEq, Eq)]
638 pub struct ErrorIndex {
639 pub compiler: Compiler,
640 pub target: TargetSelection,
643 impl Step for ErrorIndex {
645 const DEFAULT: bool = true;
646 const ONLY_HOSTS: bool = true;
648 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
649 let builder = run.builder;
650 run.path("src/tools/error_index_generator").default_condition(builder.config.docs)
653 fn make_run(run: RunConfig<'_>) {
654 let target = run.target;
655 // error_index_generator depends on librustdoc. Use the compiler that
656 // is normally used to build rustdoc for other documentation so that
657 // it shares the same artifacts.
659 run.builder.compiler_for(run.builder.top_stage, run.builder.config.build, target);
660 run.builder.ensure(ErrorIndex { compiler, target });
663 /// Generates the HTML rendered error-index by running the
664 /// `error_index_generator` tool.
665 fn run(self, builder: &Builder<'_>) {
666 builder.info(&format!("Documenting error index ({})", self.target));
667 let out = builder.doc_out(self.target);
668 t!(fs::create_dir_all(&out));
669 let mut index = tool::ErrorIndex::command(builder, self.compiler);
671 index.arg(out.join("error-index.html"));
672 index.arg(&builder.version);
674 builder.run(&mut index);
678 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
679 pub struct UnstableBookGen {
680 target: TargetSelection,
683 impl Step for UnstableBookGen {
685 const DEFAULT: bool = true;
686 const ONLY_HOSTS: bool = true;
688 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
689 let builder = run.builder;
690 run.path("src/tools/unstable-book-gen").default_condition(builder.config.docs)
693 fn make_run(run: RunConfig<'_>) {
694 run.builder.ensure(UnstableBookGen { target: run.target });
697 fn run(self, builder: &Builder<'_>) {
698 let target = self.target;
700 builder.info(&format!("Generating unstable book md files ({})", target));
701 let out = builder.md_doc_out(target).join("unstable-book");
702 builder.create_dir(&out);
703 builder.remove_dir(&out);
704 let mut cmd = builder.tool_cmd(Tool::UnstableBookGen);
705 cmd.arg(builder.src.join("library"));
706 cmd.arg(builder.src.join("compiler"));
707 cmd.arg(builder.src.join("src"));
710 builder.run(&mut cmd);
714 fn symlink_dir_force(config: &Config, src: &Path, dst: &Path) -> io::Result<()> {
718 if let Ok(m) = fs::symlink_metadata(dst) {
719 if m.file_type().is_dir() {
720 fs::remove_dir_all(dst)?;
722 // handle directory junctions on windows by falling back to
724 fs::remove_file(dst).or_else(|_| fs::remove_dir(dst))?;
728 symlink_dir(config, src, dst)
731 #[derive(Ord, PartialOrd, Debug, Copy, Clone, Hash, PartialEq, Eq)]
732 pub struct RustcBook {
733 pub compiler: Compiler,
734 pub target: TargetSelection,
738 impl Step for RustcBook {
740 const DEFAULT: bool = true;
741 const ONLY_HOSTS: bool = true;
743 fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
744 let builder = run.builder;
745 run.path("src/doc/rustc").default_condition(builder.config.docs)
748 fn make_run(run: RunConfig<'_>) {
749 run.builder.ensure(RustcBook {
750 compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
756 /// Builds the rustc book.
758 /// The lints are auto-generated by a tool, and then merged into the book
759 /// in the "md-doc" directory in the build output directory. Then
760 /// "rustbook" is used to convert it to HTML.
761 fn run(self, builder: &Builder<'_>) {
762 let out_base = builder.md_doc_out(self.target).join("rustc");
763 t!(fs::create_dir_all(&out_base));
764 let out_listing = out_base.join("src/lints");
765 builder.cp_r(&builder.src.join("src/doc/rustc"), &out_base);
766 builder.info(&format!("Generating lint docs ({})", self.target));
768 let rustc = builder.rustc(self.compiler);
769 // The tool runs `rustc` for extracting output examples, so it needs a
770 // functional sysroot.
771 builder.ensure(compile::Std { compiler: self.compiler, target: self.target });
772 let mut cmd = builder.tool_cmd(Tool::LintDocs);
774 cmd.arg(builder.src.join("compiler"));
776 cmd.arg(&out_listing);
779 cmd.arg("--rustc-target").arg(&self.target.rustc_target_arg());
780 if builder.config.verbose() {
781 cmd.arg("--verbose");
784 cmd.arg("--validate");
786 // If the lib directories are in an unusual location (changed in
787 // config.toml), then this needs to explicitly update the dylib search
789 builder.add_rustc_lib_path(self.compiler, &mut cmd);
790 builder.run(&mut cmd);
791 // Run rustbook/mdbook to generate the HTML pages.
792 builder.ensure(RustbookSrc {
794 name: INTERNER.intern_str("rustc"),
795 src: INTERNER.intern_path(out_base),
797 if is_explicit_request(builder, "src/doc/rustc") {
798 let out = builder.doc_out(self.target);
799 let index = out.join("rustc").join("index.html");
800 open(builder, &index);