]> git.lizzy.rs Git - rust.git/blob - src/bootstrap/doc.rs
Rollup merge of #68279 - GuillaumeGomez:clean-up-e0198, r=Dylan-DPC
[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, RunConfig, ShouldRun, Step};
19 use crate::cache::{Interned, INTERNER};
20 use crate::compile;
21 use crate::config::Config;
22 use crate::tool::{self, prepare_tool_cargo, SourceType, Tool};
23 use crate::util::symlink_dir;
24
25 macro_rules! book {
26     ($($name:ident, $path:expr, $book_name:expr;)+) => {
27         $(
28             #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
29         pub struct $name {
30             target: Interned<String>,
31         }
32
33         impl Step for $name {
34             type Output = ();
35             const DEFAULT: bool = true;
36
37             fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
38                 let builder = run.builder;
39                 run.path($path).default_condition(builder.config.docs)
40             }
41
42             fn make_run(run: RunConfig<'_>) {
43                 run.builder.ensure($name {
44                     target: run.target,
45                 });
46             }
47
48             fn run(self, builder: &Builder<'_>) {
49                 builder.ensure(RustbookSrc {
50                     target: self.target,
51                     name: INTERNER.intern_str($book_name),
52                     src: INTERNER.intern_path(builder.src.join($path)),
53                 })
54             }
55         }
56         )+
57     }
58 }
59
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`!
62 book!(
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     RustcBook, "src/doc/rustc", "rustc";
70     RustdocBook, "src/doc/rustdoc", "rustdoc";
71 );
72
73 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
74 pub struct UnstableBook {
75     target: Interned<String>,
76 }
77
78 impl Step for UnstableBook {
79     type Output = ();
80     const DEFAULT: bool = true;
81
82     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
83         let builder = run.builder;
84         run.path("src/doc/unstable-book").default_condition(builder.config.docs)
85     }
86
87     fn make_run(run: RunConfig<'_>) {
88         run.builder.ensure(UnstableBook { target: run.target });
89     }
90
91     fn run(self, builder: &Builder<'_>) {
92         builder.ensure(UnstableBookGen { target: self.target });
93         builder.ensure(RustbookSrc {
94             target: self.target,
95             name: INTERNER.intern_str("unstable-book"),
96             src: INTERNER.intern_path(builder.md_doc_out(self.target).join("unstable-book")),
97         })
98     }
99 }
100
101 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
102 struct RustbookSrc {
103     target: Interned<String>,
104     name: Interned<String>,
105     src: Interned<PathBuf>,
106 }
107
108 impl Step for RustbookSrc {
109     type Output = ();
110
111     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
112         run.never()
113     }
114
115     /// Invoke `rustbook` for `target` for the doc book `name` from the `src` path.
116     ///
117     /// This will not actually generate any documentation if the documentation has
118     /// already been generated.
119     fn run(self, builder: &Builder<'_>) {
120         let target = self.target;
121         let name = self.name;
122         let src = self.src;
123         let out = builder.doc_out(target);
124         t!(fs::create_dir_all(&out));
125
126         let out = out.join(name);
127         let index = out.join("index.html");
128         let rustbook = builder.tool_exe(Tool::Rustbook);
129         let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook);
130         if up_to_date(&src, &index) && up_to_date(&rustbook, &index) {
131             return;
132         }
133         builder.info(&format!("Rustbook ({}) - {}", target, name));
134         let _ = fs::remove_dir_all(&out);
135
136         builder.run(rustbook_cmd.arg("build").arg(&src).arg("-d").arg(out));
137     }
138 }
139
140 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
141 pub struct TheBook {
142     compiler: Compiler,
143     target: Interned<String>,
144 }
145
146 impl Step for TheBook {
147     type Output = ();
148     const DEFAULT: bool = true;
149
150     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
151         let builder = run.builder;
152         run.path("src/doc/book").default_condition(builder.config.docs)
153     }
154
155     fn make_run(run: RunConfig<'_>) {
156         run.builder.ensure(TheBook {
157             compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
158             target: run.target,
159         });
160     }
161
162     /// Builds the book and associated stuff.
163     ///
164     /// We need to build:
165     ///
166     /// * Book
167     /// * Older edition redirects
168     /// * Version info and CSS
169     /// * Index page
170     /// * Redirect pages
171     fn run(self, builder: &Builder<'_>) {
172         let compiler = self.compiler;
173         let target = self.target;
174
175         // build book
176         builder.ensure(RustbookSrc {
177             target,
178             name: INTERNER.intern_str("book"),
179             src: INTERNER.intern_path(builder.src.join("src/doc/book")),
180         });
181
182         // building older edition redirects
183         for edition in &["first-edition", "second-edition", "2018-edition"] {
184             builder.ensure(RustbookSrc {
185                 target,
186                 name: INTERNER.intern_string(format!("book/{}", edition)),
187                 src: INTERNER.intern_path(builder.src.join("src/doc/book").join(edition)),
188             });
189         }
190
191         // build the version info page and CSS
192         builder.ensure(Standalone { compiler, target });
193
194         // build the redirect pages
195         builder.info(&format!("Documenting book redirect pages ({})", target));
196         for file in t!(fs::read_dir(builder.src.join("src/doc/book/redirects"))) {
197             let file = t!(file);
198             let path = file.path();
199             let path = path.to_str().unwrap();
200
201             invoke_rustdoc(builder, compiler, target, path);
202         }
203     }
204 }
205
206 fn invoke_rustdoc(
207     builder: &Builder<'_>,
208     compiler: Compiler,
209     target: Interned<String>,
210     markdown: &str,
211 ) {
212     let out = builder.doc_out(target);
213
214     let path = builder.src.join("src/doc").join(markdown);
215
216     let header = builder.src.join("src/doc/redirect.inc");
217     let footer = builder.src.join("src/doc/footer.inc");
218     let version_info = out.join("version_info.html");
219
220     let mut cmd = builder.rustdoc_cmd(compiler);
221
222     let out = out.join("book");
223
224     cmd.arg("--html-after-content")
225         .arg(&footer)
226         .arg("--html-before-content")
227         .arg(&version_info)
228         .arg("--html-in-header")
229         .arg(&header)
230         .arg("--markdown-no-toc")
231         .arg("--markdown-playground-url")
232         .arg("https://play.rust-lang.org/")
233         .arg("-o")
234         .arg(&out)
235         .arg(&path)
236         .arg("--markdown-css")
237         .arg("../rust.css");
238
239     builder.run(&mut cmd);
240 }
241
242 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
243 pub struct Standalone {
244     compiler: Compiler,
245     target: Interned<String>,
246 }
247
248 impl Step for Standalone {
249     type Output = ();
250     const DEFAULT: bool = true;
251
252     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
253         let builder = run.builder;
254         run.path("src/doc").default_condition(builder.config.docs)
255     }
256
257     fn make_run(run: RunConfig<'_>) {
258         run.builder.ensure(Standalone {
259             compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
260             target: run.target,
261         });
262     }
263
264     /// Generates all standalone documentation as compiled by the rustdoc in `stage`
265     /// for the `target` into `out`.
266     ///
267     /// This will list all of `src/doc` looking for markdown files and appropriately
268     /// perform transformations like substituting `VERSION`, `SHORT_HASH`, and
269     /// `STAMP` along with providing the various header/footer HTML we've customized.
270     ///
271     /// In the end, this is just a glorified wrapper around rustdoc!
272     fn run(self, builder: &Builder<'_>) {
273         let target = self.target;
274         let compiler = self.compiler;
275         builder.info(&format!("Documenting standalone ({})", target));
276         let out = builder.doc_out(target);
277         t!(fs::create_dir_all(&out));
278
279         let favicon = builder.src.join("src/doc/favicon.inc");
280         let footer = builder.src.join("src/doc/footer.inc");
281         let full_toc = builder.src.join("src/doc/full-toc.inc");
282         t!(fs::copy(builder.src.join("src/doc/rust.css"), out.join("rust.css")));
283
284         let version_input = builder.src.join("src/doc/version_info.html.template");
285         let version_info = out.join("version_info.html");
286
287         if !builder.config.dry_run && !up_to_date(&version_input, &version_info) {
288             let info = t!(fs::read_to_string(&version_input))
289                 .replace("VERSION", &builder.rust_release())
290                 .replace("SHORT_HASH", builder.rust_info.sha_short().unwrap_or(""))
291                 .replace("STAMP", builder.rust_info.sha().unwrap_or(""));
292             t!(fs::write(&version_info, &info));
293         }
294
295         for file in t!(fs::read_dir(builder.src.join("src/doc"))) {
296             let file = t!(file);
297             let path = file.path();
298             let filename = path.file_name().unwrap().to_str().unwrap();
299             if !filename.ends_with(".md") || filename == "README.md" {
300                 continue;
301             }
302
303             let html = out.join(filename).with_extension("html");
304             let rustdoc = builder.rustdoc(compiler);
305             if up_to_date(&path, &html)
306                 && up_to_date(&footer, &html)
307                 && up_to_date(&favicon, &html)
308                 && up_to_date(&full_toc, &html)
309                 && (builder.config.dry_run || up_to_date(&version_info, &html))
310                 && (builder.config.dry_run || up_to_date(&rustdoc, &html))
311             {
312                 continue;
313             }
314
315             let mut cmd = builder.rustdoc_cmd(compiler);
316             cmd.arg("--html-after-content")
317                 .arg(&footer)
318                 .arg("--html-before-content")
319                 .arg(&version_info)
320                 .arg("--html-in-header")
321                 .arg(&favicon)
322                 .arg("--markdown-no-toc")
323                 .arg("--index-page")
324                 .arg(&builder.src.join("src/doc/index.md"))
325                 .arg("--markdown-playground-url")
326                 .arg("https://play.rust-lang.org/")
327                 .arg("-o")
328                 .arg(&out)
329                 .arg(&path);
330
331             if filename == "not_found.md" {
332                 cmd.arg("--markdown-css").arg("https://doc.rust-lang.org/rust.css");
333             } else {
334                 cmd.arg("--markdown-css").arg("rust.css");
335             }
336             builder.run(&mut cmd);
337         }
338     }
339 }
340
341 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
342 pub struct Std {
343     pub stage: u32,
344     pub target: Interned<String>,
345 }
346
347 impl Step for Std {
348     type Output = ();
349     const DEFAULT: bool = true;
350
351     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
352         let builder = run.builder;
353         run.all_krates("test").default_condition(builder.config.docs)
354     }
355
356     fn make_run(run: RunConfig<'_>) {
357         run.builder.ensure(Std { stage: run.builder.top_stage, target: run.target });
358     }
359
360     /// Compile all standard library documentation.
361     ///
362     /// This will generate all documentation for the standard library and its
363     /// dependencies. This is largely just a wrapper around `cargo doc`.
364     fn run(self, builder: &Builder<'_>) {
365         let stage = self.stage;
366         let target = self.target;
367         builder.info(&format!("Documenting stage{} std ({})", stage, target));
368         let out = builder.doc_out(target);
369         t!(fs::create_dir_all(&out));
370         let compiler = builder.compiler(stage, builder.config.build);
371
372         builder.ensure(compile::Std { compiler, target });
373         let out_dir = builder.stage_out(compiler, Mode::Std).join(target).join("doc");
374
375         // Here what we're doing is creating a *symlink* (directory junction on
376         // Windows) to the final output location. This is not done as an
377         // optimization but rather for correctness. We've got three trees of
378         // documentation, one for std, one for test, and one for rustc. It's then
379         // our job to merge them all together.
380         //
381         // Unfortunately rustbuild doesn't know nearly as well how to merge doc
382         // trees as rustdoc does itself, so instead of actually having three
383         // separate trees we just have rustdoc output to the same location across
384         // all of them.
385         //
386         // This way rustdoc generates output directly into the output, and rustdoc
387         // will also directly handle merging.
388         let my_out = builder.crate_doc_out(target);
389         t!(symlink_dir_force(&builder.config, &my_out, &out_dir));
390         t!(fs::copy(builder.src.join("src/doc/rust.css"), out.join("rust.css")));
391
392         let run_cargo_rustdoc_for = |package: &str| {
393             let mut cargo = builder.cargo(compiler, Mode::Std, target, "rustdoc");
394             compile::std_cargo(builder, target, &mut cargo);
395
396             // Keep a whitelist so we do not build internal stdlib crates, these will be
397             // build by the rustc step later if enabled.
398             cargo.arg("-Z").arg("unstable-options").arg("-p").arg(package);
399             // Create all crate output directories first to make sure rustdoc uses
400             // relative links.
401             // FIXME: Cargo should probably do this itself.
402             t!(fs::create_dir_all(out_dir.join(package)));
403             cargo
404                 .arg("--")
405                 .arg("--markdown-css")
406                 .arg("rust.css")
407                 .arg("--markdown-no-toc")
408                 .arg("--generate-redirect-pages")
409                 .arg("--resource-suffix")
410                 .arg(crate::channel::CFG_RELEASE_NUM)
411                 .arg("--index-page")
412                 .arg(&builder.src.join("src/doc/index.md"));
413
414             builder.run(&mut cargo.into());
415         };
416         for krate in &["alloc", "core", "std", "proc_macro", "test"] {
417             run_cargo_rustdoc_for(krate);
418         }
419         builder.cp_r(&my_out, &out);
420     }
421 }
422
423 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
424 pub struct Rustc {
425     stage: u32,
426     target: Interned<String>,
427 }
428
429 impl Step for Rustc {
430     type Output = ();
431     const DEFAULT: bool = true;
432     const ONLY_HOSTS: bool = true;
433
434     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
435         let builder = run.builder;
436         run.krate("rustc-main").default_condition(builder.config.docs)
437     }
438
439     fn make_run(run: RunConfig<'_>) {
440         run.builder.ensure(Rustc { stage: run.builder.top_stage, target: run.target });
441     }
442
443     /// Generates compiler documentation.
444     ///
445     /// This will generate all documentation for compiler and dependencies.
446     /// Compiler documentation is distributed separately, so we make sure
447     /// we do not merge it with the other documentation from std, test and
448     /// proc_macros. This is largely just a wrapper around `cargo doc`.
449     fn run(self, builder: &Builder<'_>) {
450         let stage = self.stage;
451         let target = self.target;
452         builder.info(&format!("Documenting stage{} compiler ({})", stage, target));
453
454         // This is the intended out directory for compiler documentation.
455         let out = builder.compiler_doc_out(target);
456         t!(fs::create_dir_all(&out));
457
458         // Get the correct compiler for this stage.
459         let compiler = builder.compiler_for(stage, builder.config.build, target);
460
461         if !builder.config.compiler_docs {
462             builder.info("\tskipping - compiler/librustdoc docs disabled");
463             return;
464         }
465
466         // Build rustc.
467         builder.ensure(compile::Rustc { compiler, target });
468
469         // We do not symlink to the same shared folder that already contains std library
470         // documentation from previous steps as we do not want to include that.
471         let out_dir = builder.stage_out(compiler, Mode::Rustc).join(target).join("doc");
472         t!(symlink_dir_force(&builder.config, &out, &out_dir));
473
474         // Build cargo command.
475         let mut cargo = builder.cargo(compiler, Mode::Rustc, target, "doc");
476         cargo.env("RUSTDOCFLAGS", "--document-private-items");
477         compile::rustc_cargo(builder, &mut cargo, target);
478
479         // Only include compiler crates, no dependencies of those, such as `libc`.
480         cargo.arg("--no-deps");
481
482         // Find dependencies for top level crates.
483         let mut compiler_crates = HashSet::new();
484         for root_crate in &["rustc_driver", "rustc_codegen_llvm", "rustc_codegen_ssa"] {
485             let interned_root_crate = INTERNER.intern_str(root_crate);
486             find_compiler_crates(builder, &interned_root_crate, &mut compiler_crates);
487         }
488
489         for krate in &compiler_crates {
490             // Create all crate output directories first to make sure rustdoc uses
491             // relative links.
492             // FIXME: Cargo should probably do this itself.
493             t!(fs::create_dir_all(out_dir.join(krate)));
494             cargo.arg("-p").arg(krate);
495         }
496
497         builder.run(&mut cargo.into());
498     }
499 }
500
501 fn find_compiler_crates(
502     builder: &Builder<'_>,
503     name: &Interned<String>,
504     crates: &mut HashSet<Interned<String>>,
505 ) {
506     // Add current crate.
507     crates.insert(*name);
508
509     // Look for dependencies.
510     for dep in builder.crates.get(name).unwrap().deps.iter() {
511         if builder.crates.get(dep).unwrap().is_local(builder) {
512             find_compiler_crates(builder, dep, crates);
513         }
514     }
515 }
516
517 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
518 pub struct Rustdoc {
519     stage: u32,
520     target: Interned<String>,
521 }
522
523 impl Step for Rustdoc {
524     type Output = ();
525     const DEFAULT: bool = true;
526     const ONLY_HOSTS: bool = true;
527
528     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
529         run.krate("rustdoc-tool")
530     }
531
532     fn make_run(run: RunConfig<'_>) {
533         run.builder.ensure(Rustdoc { stage: run.builder.top_stage, target: run.target });
534     }
535
536     /// Generates compiler documentation.
537     ///
538     /// This will generate all documentation for compiler and dependencies.
539     /// Compiler documentation is distributed separately, so we make sure
540     /// we do not merge it with the other documentation from std, test and
541     /// proc_macros. This is largely just a wrapper around `cargo doc`.
542     fn run(self, builder: &Builder<'_>) {
543         let stage = self.stage;
544         let target = self.target;
545         builder.info(&format!("Documenting stage{} rustdoc ({})", stage, target));
546
547         // This is the intended out directory for compiler documentation.
548         let out = builder.compiler_doc_out(target);
549         t!(fs::create_dir_all(&out));
550
551         // Get the correct compiler for this stage.
552         let compiler = builder.compiler_for(stage, builder.config.build, target);
553
554         if !builder.config.compiler_docs {
555             builder.info("\tskipping - compiler/librustdoc docs disabled");
556             return;
557         }
558
559         // Build rustc docs so that we generate relative links.
560         builder.ensure(Rustc { stage, target });
561
562         // Build rustdoc.
563         builder.ensure(tool::Rustdoc { compiler: compiler });
564
565         // Symlink compiler docs to the output directory of rustdoc documentation.
566         let out_dir = builder.stage_out(compiler, Mode::ToolRustc).join(target).join("doc");
567         t!(fs::create_dir_all(&out_dir));
568         t!(symlink_dir_force(&builder.config, &out, &out_dir));
569
570         // Build cargo command.
571         let mut cargo = prepare_tool_cargo(
572             builder,
573             compiler,
574             Mode::ToolRustc,
575             target,
576             "doc",
577             "src/tools/rustdoc",
578             SourceType::InTree,
579             &[],
580         );
581
582         // Only include compiler crates, no dependencies of those, such as `libc`.
583         cargo.arg("--no-deps");
584         cargo.arg("-p").arg("rustdoc");
585
586         cargo.env("RUSTDOCFLAGS", "--document-private-items");
587         builder.run(&mut cargo.into());
588     }
589 }
590
591 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
592 pub struct ErrorIndex {
593     target: Interned<String>,
594 }
595
596 impl Step for ErrorIndex {
597     type Output = ();
598     const DEFAULT: bool = true;
599     const ONLY_HOSTS: bool = true;
600
601     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
602         let builder = run.builder;
603         run.path("src/tools/error_index_generator").default_condition(builder.config.docs)
604     }
605
606     fn make_run(run: RunConfig<'_>) {
607         run.builder.ensure(ErrorIndex { target: run.target });
608     }
609
610     /// Generates the HTML rendered error-index by running the
611     /// `error_index_generator` tool.
612     fn run(self, builder: &Builder<'_>) {
613         let target = self.target;
614
615         builder.info(&format!("Documenting error index ({})", target));
616         let out = builder.doc_out(target);
617         t!(fs::create_dir_all(&out));
618         let compiler = builder.compiler(2, builder.config.build);
619         let mut index = tool::ErrorIndex::command(builder, compiler);
620         index.arg("html");
621         index.arg(out.join("error-index.html"));
622         index.arg(crate::channel::CFG_RELEASE_NUM);
623
624         // FIXME: shouldn't have to pass this env var
625         index.env("CFG_BUILD", &builder.config.build);
626
627         builder.run(&mut index);
628     }
629 }
630
631 #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
632 pub struct UnstableBookGen {
633     target: Interned<String>,
634 }
635
636 impl Step for UnstableBookGen {
637     type Output = ();
638     const DEFAULT: bool = true;
639     const ONLY_HOSTS: bool = true;
640
641     fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
642         let builder = run.builder;
643         run.path("src/tools/unstable-book-gen").default_condition(builder.config.docs)
644     }
645
646     fn make_run(run: RunConfig<'_>) {
647         run.builder.ensure(UnstableBookGen { target: run.target });
648     }
649
650     fn run(self, builder: &Builder<'_>) {
651         let target = self.target;
652
653         builder.info(&format!("Generating unstable book md files ({})", target));
654         let out = builder.md_doc_out(target).join("unstable-book");
655         builder.create_dir(&out);
656         builder.remove_dir(&out);
657         let mut cmd = builder.tool_cmd(Tool::UnstableBookGen);
658         cmd.arg(builder.src.join("src"));
659         cmd.arg(out);
660
661         builder.run(&mut cmd);
662     }
663 }
664
665 fn symlink_dir_force(config: &Config, src: &Path, dst: &Path) -> io::Result<()> {
666     if config.dry_run {
667         return Ok(());
668     }
669     if let Ok(m) = fs::symlink_metadata(dst) {
670         if m.file_type().is_dir() {
671             fs::remove_dir_all(dst)?;
672         } else {
673             // handle directory junctions on windows by falling back to
674             // `remove_dir`.
675             fs::remove_file(dst).or_else(|_| fs::remove_dir(dst))?;
676         }
677     }
678
679     symlink_dir(config, src, dst)
680 }