bootstrap/core/build_steps/
doc.rs

1//! Documentation generation for bootstrap.
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
10use std::io::{self, Write};
11use std::path::{Path, PathBuf};
12use std::{env, fs, mem};
13
14use crate::Mode;
15use crate::core::build_steps::compile;
16use crate::core::build_steps::tool::{self, SourceType, Tool, prepare_tool_cargo};
17use crate::core::builder::{
18    self, Alias, Builder, Compiler, Kind, RunConfig, ShouldRun, Step, crate_description,
19};
20use crate::core::config::{Config, TargetSelection};
21use crate::helpers::{submodule_path_of, symlink_dir, t, up_to_date};
22
23macro_rules! book {
24    ($($name:ident, $path:expr, $book_name:expr, $lang:expr ;)+) => {
25        $(
26            #[derive(Debug, Clone, Hash, PartialEq, Eq)]
27        pub struct $name {
28            target: TargetSelection,
29        }
30
31        impl Step for $name {
32            type Output = ();
33            const DEFAULT: bool = true;
34
35            fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
36                let builder = run.builder;
37                run.path($path).default_condition(builder.config.docs)
38            }
39
40            fn make_run(run: RunConfig<'_>) {
41                run.builder.ensure($name {
42                    target: run.target,
43                });
44            }
45
46            fn run(self, builder: &Builder<'_>) {
47                if let Some(submodule_path) = submodule_path_of(&builder, $path) {
48                    builder.require_submodule(&submodule_path, None)
49                }
50
51                builder.ensure(RustbookSrc {
52                    target: self.target,
53                    name: $book_name.to_owned(),
54                    src: builder.src.join($path),
55                    parent: Some(self),
56                    languages: $lang.into(),
57                    rustdoc_compiler: None,
58                })
59            }
60        }
61        )+
62    }
63}
64
65// NOTE: When adding a book here, make sure to ALSO build the book by
66// adding a build step in `src/bootstrap/code/builder/mod.rs`!
67// NOTE: Make sure to add the corresponding submodule when adding a new book.
68book!(
69    CargoBook, "src/tools/cargo/src/doc", "cargo", &[];
70    ClippyBook, "src/tools/clippy/book", "clippy", &[];
71    EditionGuide, "src/doc/edition-guide", "edition-guide", &[];
72    EmbeddedBook, "src/doc/embedded-book", "embedded-book", &[];
73    Nomicon, "src/doc/nomicon", "nomicon", &[];
74    RustByExample, "src/doc/rust-by-example", "rust-by-example", &["ja", "zh"];
75    RustdocBook, "src/doc/rustdoc", "rustdoc", &[];
76    StyleGuide, "src/doc/style-guide", "style-guide", &[];
77);
78
79#[derive(Debug, Clone, Hash, PartialEq, Eq)]
80pub struct UnstableBook {
81    target: TargetSelection,
82}
83
84impl Step for UnstableBook {
85    type Output = ();
86    const DEFAULT: bool = true;
87
88    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
89        let builder = run.builder;
90        run.path("src/doc/unstable-book").default_condition(builder.config.docs)
91    }
92
93    fn make_run(run: RunConfig<'_>) {
94        run.builder.ensure(UnstableBook { target: run.target });
95    }
96
97    fn run(self, builder: &Builder<'_>) {
98        builder.ensure(UnstableBookGen { target: self.target });
99        builder.ensure(RustbookSrc {
100            target: self.target,
101            name: "unstable-book".to_owned(),
102            src: builder.md_doc_out(self.target).join("unstable-book"),
103            parent: Some(self),
104            languages: vec![],
105            rustdoc_compiler: None,
106        })
107    }
108}
109
110#[derive(Debug, Clone, Hash, PartialEq, Eq)]
111struct RustbookSrc<P: Step> {
112    target: TargetSelection,
113    name: String,
114    src: PathBuf,
115    parent: Option<P>,
116    languages: Vec<&'static str>,
117    rustdoc_compiler: Option<Compiler>,
118}
119
120impl<P: Step> Step for RustbookSrc<P> {
121    type Output = ();
122
123    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
124        run.never()
125    }
126
127    /// Invoke `rustbook` for `target` for the doc book `name` from the `src` path.
128    ///
129    /// This will not actually generate any documentation if the documentation has
130    /// already been generated.
131    fn run(self, builder: &Builder<'_>) {
132        let target = self.target;
133        let name = self.name;
134        let src = self.src;
135        let out = builder.doc_out(target);
136        t!(fs::create_dir_all(&out));
137
138        let out = out.join(&name);
139        let index = out.join("index.html");
140        let rustbook = builder.tool_exe(Tool::Rustbook);
141
142        if !builder.config.dry_run()
143            && (!up_to_date(&src, &index) || !up_to_date(&rustbook, &index))
144        {
145            builder.info(&format!("Rustbook ({target}) - {name}"));
146            let _ = fs::remove_dir_all(&out);
147
148            let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook);
149
150            if let Some(compiler) = self.rustdoc_compiler {
151                let mut rustdoc = builder.rustdoc(compiler);
152                rustdoc.pop();
153                let old_path = env::var_os("PATH").unwrap_or_default();
154                let new_path =
155                    env::join_paths(std::iter::once(rustdoc).chain(env::split_paths(&old_path)))
156                        .expect("could not add rustdoc to PATH");
157
158                rustbook_cmd.env("PATH", new_path);
159                builder.add_rustc_lib_path(compiler, &mut rustbook_cmd);
160            }
161
162            rustbook_cmd
163                .arg("build")
164                .arg(&src)
165                .arg("-d")
166                .arg(&out)
167                .arg("--rust-root")
168                .arg(&builder.src)
169                .run(builder);
170
171            for lang in &self.languages {
172                let out = out.join(lang);
173
174                builder.info(&format!("Rustbook ({target}) - {name} - {lang}"));
175                let _ = fs::remove_dir_all(&out);
176
177                builder
178                    .tool_cmd(Tool::Rustbook)
179                    .arg("build")
180                    .arg(&src)
181                    .arg("-d")
182                    .arg(&out)
183                    .arg("-l")
184                    .arg(lang)
185                    .run(builder);
186            }
187        }
188
189        if self.parent.is_some() {
190            builder.maybe_open_in_browser::<P>(index)
191        }
192    }
193}
194
195#[derive(Debug, Clone, Hash, PartialEq, Eq)]
196pub struct TheBook {
197    compiler: Compiler,
198    target: TargetSelection,
199}
200
201impl Step for TheBook {
202    type Output = ();
203    const DEFAULT: bool = true;
204
205    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
206        let builder = run.builder;
207        run.path("src/doc/book").default_condition(builder.config.docs)
208    }
209
210    fn make_run(run: RunConfig<'_>) {
211        run.builder.ensure(TheBook {
212            compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
213            target: run.target,
214        });
215    }
216
217    /// Builds the book and associated stuff.
218    ///
219    /// We need to build:
220    ///
221    /// * Book
222    /// * Older edition redirects
223    /// * Version info and CSS
224    /// * Index page
225    /// * Redirect pages
226    fn run(self, builder: &Builder<'_>) {
227        builder.require_submodule("src/doc/book", None);
228
229        let compiler = self.compiler;
230        let target = self.target;
231
232        let absolute_path = builder.src.join("src/doc/book");
233        let redirect_path = absolute_path.join("redirects");
234
235        // build book
236        builder.ensure(RustbookSrc {
237            target,
238            name: "book".to_owned(),
239            src: absolute_path.clone(),
240            parent: Some(self),
241            languages: vec![],
242            rustdoc_compiler: None,
243        });
244
245        // building older edition redirects
246        for edition in &["first-edition", "second-edition", "2018-edition"] {
247            builder.ensure(RustbookSrc {
248                target,
249                name: format!("book/{edition}"),
250                src: absolute_path.join(edition),
251                // There should only be one book that is marked as the parent for each target, so
252                // treat the other editions as not having a parent.
253                parent: Option::<Self>::None,
254                languages: vec![],
255                rustdoc_compiler: None,
256            });
257        }
258
259        // build the version info page and CSS
260        let shared_assets = builder.ensure(SharedAssets { target });
261
262        // build the redirect pages
263        let _guard = builder.msg_doc(compiler, "book redirect pages", target);
264        for file in t!(fs::read_dir(redirect_path)) {
265            let file = t!(file);
266            let path = file.path();
267            let path = path.to_str().unwrap();
268
269            invoke_rustdoc(builder, compiler, &shared_assets, target, path);
270        }
271    }
272}
273
274fn invoke_rustdoc(
275    builder: &Builder<'_>,
276    compiler: Compiler,
277    shared_assets: &SharedAssetsPaths,
278    target: TargetSelection,
279    markdown: &str,
280) {
281    let out = builder.doc_out(target);
282
283    let path = builder.src.join("src/doc").join(markdown);
284
285    let header = builder.src.join("src/doc/redirect.inc");
286    let footer = builder.src.join("src/doc/footer.inc");
287
288    let mut cmd = builder.rustdoc_cmd(compiler);
289
290    let out = out.join("book");
291
292    cmd.arg("--html-after-content")
293        .arg(&footer)
294        .arg("--html-before-content")
295        .arg(&shared_assets.version_info)
296        .arg("--html-in-header")
297        .arg(&header)
298        .arg("--markdown-no-toc")
299        .arg("--markdown-playground-url")
300        .arg("https://play.rust-lang.org/")
301        .arg("-o")
302        .arg(&out)
303        .arg(&path)
304        .arg("--markdown-css")
305        .arg("../rust.css")
306        .arg("-Zunstable-options");
307
308    if !builder.config.docs_minification {
309        cmd.arg("--disable-minification");
310    }
311
312    cmd.run(builder);
313}
314
315#[derive(Debug, Clone, Hash, PartialEq, Eq)]
316pub struct Standalone {
317    compiler: Compiler,
318    target: TargetSelection,
319}
320
321impl Step for Standalone {
322    type Output = ();
323    const DEFAULT: bool = true;
324
325    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
326        let builder = run.builder;
327        run.path("src/doc").alias("standalone").default_condition(builder.config.docs)
328    }
329
330    fn make_run(run: RunConfig<'_>) {
331        run.builder.ensure(Standalone {
332            compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
333            target: run.target,
334        });
335    }
336
337    /// Generates all standalone documentation as compiled by the rustdoc in `stage`
338    /// for the `target` into `out`.
339    ///
340    /// This will list all of `src/doc` looking for markdown files and appropriately
341    /// perform transformations like substituting `VERSION`, `SHORT_HASH`, and
342    /// `STAMP` along with providing the various header/footer HTML we've customized.
343    ///
344    /// In the end, this is just a glorified wrapper around rustdoc!
345    fn run(self, builder: &Builder<'_>) {
346        let target = self.target;
347        let compiler = self.compiler;
348        let _guard = builder.msg_doc(compiler, "standalone", target);
349        let out = builder.doc_out(target);
350        t!(fs::create_dir_all(&out));
351
352        let version_info = builder.ensure(SharedAssets { target: self.target }).version_info;
353
354        let favicon = builder.src.join("src/doc/favicon.inc");
355        let footer = builder.src.join("src/doc/footer.inc");
356        let full_toc = builder.src.join("src/doc/full-toc.inc");
357
358        for file in t!(fs::read_dir(builder.src.join("src/doc"))) {
359            let file = t!(file);
360            let path = file.path();
361            let filename = path.file_name().unwrap().to_str().unwrap();
362            if !filename.ends_with(".md") || filename == "README.md" {
363                continue;
364            }
365
366            let html = out.join(filename).with_extension("html");
367            let rustdoc = builder.rustdoc(compiler);
368            if up_to_date(&path, &html)
369                && up_to_date(&footer, &html)
370                && up_to_date(&favicon, &html)
371                && up_to_date(&full_toc, &html)
372                && (builder.config.dry_run() || up_to_date(&version_info, &html))
373                && (builder.config.dry_run() || up_to_date(&rustdoc, &html))
374            {
375                continue;
376            }
377
378            let mut cmd = builder.rustdoc_cmd(compiler);
379
380            cmd.arg("--html-after-content")
381                .arg(&footer)
382                .arg("--html-before-content")
383                .arg(&version_info)
384                .arg("--html-in-header")
385                .arg(&favicon)
386                .arg("--markdown-no-toc")
387                .arg("-Zunstable-options")
388                .arg("--index-page")
389                .arg(builder.src.join("src/doc/index.md"))
390                .arg("--markdown-playground-url")
391                .arg("https://play.rust-lang.org/")
392                .arg("-o")
393                .arg(&out)
394                .arg(&path);
395
396            if !builder.config.docs_minification {
397                cmd.arg("--disable-minification");
398            }
399
400            if filename == "not_found.md" {
401                cmd.arg("--markdown-css").arg("https://doc.rust-lang.org/rust.css");
402            } else {
403                cmd.arg("--markdown-css").arg("rust.css");
404            }
405            cmd.run(builder);
406        }
407
408        // We open doc/index.html as the default if invoked as `x.py doc --open`
409        // with no particular explicit doc requested (e.g. library/core).
410        if builder.paths.is_empty() || builder.was_invoked_explicitly::<Self>(Kind::Doc) {
411            let index = out.join("index.html");
412            builder.open_in_browser(index);
413        }
414    }
415}
416
417#[derive(Debug, Clone, Hash, PartialEq, Eq)]
418pub struct Releases {
419    compiler: Compiler,
420    target: TargetSelection,
421}
422
423impl Step for Releases {
424    type Output = ();
425    const DEFAULT: bool = true;
426
427    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
428        let builder = run.builder;
429        run.path("RELEASES.md").alias("releases").default_condition(builder.config.docs)
430    }
431
432    fn make_run(run: RunConfig<'_>) {
433        run.builder.ensure(Releases {
434            compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
435            target: run.target,
436        });
437    }
438
439    /// Generates HTML release notes to include in the final docs bundle.
440    ///
441    /// This uses the same stylesheet and other tools as Standalone, but the
442    /// RELEASES.md file is included at the root of the repository and gets
443    /// the headline added. In the end, the conversion is done by Rustdoc.
444    fn run(self, builder: &Builder<'_>) {
445        let target = self.target;
446        let compiler = self.compiler;
447        let _guard = builder.msg_doc(compiler, "releases", target);
448        let out = builder.doc_out(target);
449        t!(fs::create_dir_all(&out));
450
451        builder.ensure(Standalone {
452            compiler: builder.compiler(builder.top_stage, builder.config.build),
453            target,
454        });
455
456        let version_info = builder.ensure(SharedAssets { target: self.target }).version_info;
457
458        let favicon = builder.src.join("src/doc/favicon.inc");
459        let footer = builder.src.join("src/doc/footer.inc");
460        let full_toc = builder.src.join("src/doc/full-toc.inc");
461
462        let html = out.join("releases.html");
463        let tmppath = out.join("releases.md");
464        let inpath = builder.src.join("RELEASES.md");
465        let rustdoc = builder.rustdoc(compiler);
466        if !up_to_date(&inpath, &html)
467            || !up_to_date(&footer, &html)
468            || !up_to_date(&favicon, &html)
469            || !up_to_date(&full_toc, &html)
470            || !(builder.config.dry_run()
471                || up_to_date(&version_info, &html)
472                || up_to_date(&rustdoc, &html))
473        {
474            let mut tmpfile = t!(fs::File::create(&tmppath));
475            t!(tmpfile.write_all(b"% Rust Release Notes\n\n"));
476            t!(io::copy(&mut t!(fs::File::open(&inpath)), &mut tmpfile));
477            mem::drop(tmpfile);
478            let mut cmd = builder.rustdoc_cmd(compiler);
479
480            cmd.arg("--html-after-content")
481                .arg(&footer)
482                .arg("--html-before-content")
483                .arg(&version_info)
484                .arg("--html-in-header")
485                .arg(&favicon)
486                .arg("--markdown-no-toc")
487                .arg("--markdown-css")
488                .arg("rust.css")
489                .arg("-Zunstable-options")
490                .arg("--index-page")
491                .arg(builder.src.join("src/doc/index.md"))
492                .arg("--markdown-playground-url")
493                .arg("https://play.rust-lang.org/")
494                .arg("-o")
495                .arg(&out)
496                .arg(&tmppath);
497
498            if !builder.config.docs_minification {
499                cmd.arg("--disable-minification");
500            }
501
502            cmd.run(builder);
503        }
504
505        // We open doc/RELEASES.html as the default if invoked as `x.py doc --open RELEASES.md`
506        // with no particular explicit doc requested (e.g. library/core).
507        if builder.was_invoked_explicitly::<Self>(Kind::Doc) {
508            builder.open_in_browser(&html);
509        }
510    }
511}
512
513#[derive(Debug, Clone)]
514pub struct SharedAssetsPaths {
515    pub version_info: PathBuf,
516}
517
518#[derive(Debug, Clone, Hash, PartialEq, Eq)]
519pub struct SharedAssets {
520    target: TargetSelection,
521}
522
523impl Step for SharedAssets {
524    type Output = SharedAssetsPaths;
525    const DEFAULT: bool = false;
526
527    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
528        // Other tasks depend on this, no need to execute it on its own
529        run.never()
530    }
531
532    /// Generate shared resources used by other pieces of documentation.
533    fn run(self, builder: &Builder<'_>) -> Self::Output {
534        let out = builder.doc_out(self.target);
535
536        let version_input = builder.src.join("src").join("doc").join("version_info.html.template");
537        let version_info = out.join("version_info.html");
538        if !builder.config.dry_run() && !up_to_date(&version_input, &version_info) {
539            let info = t!(fs::read_to_string(&version_input))
540                .replace("VERSION", &builder.rust_release())
541                .replace("SHORT_HASH", builder.rust_info().sha_short().unwrap_or(""))
542                .replace("STAMP", builder.rust_info().sha().unwrap_or(""));
543            t!(fs::write(&version_info, info));
544        }
545
546        builder.copy_link(
547            &builder.src.join("src").join("doc").join("rust.css"),
548            &out.join("rust.css"),
549        );
550
551        SharedAssetsPaths { version_info }
552    }
553}
554
555#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
556pub struct Std {
557    pub stage: u32,
558    pub target: TargetSelection,
559    pub format: DocumentationFormat,
560    crates: Vec<String>,
561}
562
563impl Std {
564    pub(crate) fn new(stage: u32, target: TargetSelection, format: DocumentationFormat) -> Self {
565        Std { stage, target, format, crates: vec![] }
566    }
567}
568
569impl Step for Std {
570    type Output = ();
571    const DEFAULT: bool = true;
572
573    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
574        let builder = run.builder;
575        run.crate_or_deps("sysroot").path("library").default_condition(builder.config.docs)
576    }
577
578    fn make_run(run: RunConfig<'_>) {
579        let crates = compile::std_crates_for_run_make(&run);
580        let target_is_no_std = run.builder.no_std(run.target).unwrap_or(false);
581        if crates.is_empty() && target_is_no_std {
582            return;
583        }
584        run.builder.ensure(Std {
585            stage: run.builder.top_stage,
586            target: run.target,
587            format: if run.builder.config.cmd.json() {
588                DocumentationFormat::Json
589            } else {
590                DocumentationFormat::Html
591            },
592            crates,
593        });
594    }
595
596    /// Compile all standard library documentation.
597    ///
598    /// This will generate all documentation for the standard library and its
599    /// dependencies. This is largely just a wrapper around `cargo doc`.
600    fn run(self, builder: &Builder<'_>) {
601        let stage = self.stage;
602        let target = self.target;
603        let crates = if self.crates.is_empty() {
604            builder
605                .in_tree_crates("sysroot", Some(target))
606                .iter()
607                .map(|c| c.name.to_string())
608                .collect()
609        } else {
610            self.crates
611        };
612
613        let out = match self.format {
614            DocumentationFormat::Html => builder.doc_out(target),
615            DocumentationFormat::Json => builder.json_doc_out(target),
616        };
617
618        t!(fs::create_dir_all(&out));
619
620        if self.format == DocumentationFormat::Html {
621            builder.ensure(SharedAssets { target: self.target });
622        }
623
624        let index_page = builder
625            .src
626            .join("src/doc/index.md")
627            .into_os_string()
628            .into_string()
629            .expect("non-utf8 paths are unsupported");
630        let mut extra_args = match self.format {
631            DocumentationFormat::Html => {
632                vec!["--markdown-css", "rust.css", "--markdown-no-toc", "--index-page", &index_page]
633            }
634            DocumentationFormat::Json => vec!["--output-format", "json"],
635        };
636
637        if !builder.config.docs_minification {
638            extra_args.push("--disable-minification");
639        }
640        // For `--index-page` and `--output-format=json`.
641        extra_args.push("-Zunstable-options");
642
643        doc_std(builder, self.format, stage, target, &out, &extra_args, &crates);
644
645        // Don't open if the format is json
646        if let DocumentationFormat::Json = self.format {
647            return;
648        }
649
650        if builder.paths.iter().any(|path| path.ends_with("library")) {
651            // For `x.py doc library --open`, open `std` by default.
652            let index = out.join("std").join("index.html");
653            builder.open_in_browser(index);
654        } else {
655            for requested_crate in crates {
656                if STD_PUBLIC_CRATES.iter().any(|&k| k == requested_crate) {
657                    let index = out.join(requested_crate).join("index.html");
658                    builder.open_in_browser(index);
659                    break;
660                }
661            }
662        }
663    }
664}
665
666/// Name of the crates that are visible to consumers of the standard library.
667/// Documentation for internal crates is handled by the rustc step, so internal crates will show
668/// up there.
669///
670/// Order here is important!
671/// Crates need to be processed starting from the leaves, otherwise rustdoc will not
672/// create correct links between crates because rustdoc depends on the
673/// existence of the output directories to know if it should be a local
674/// or remote link.
675const STD_PUBLIC_CRATES: [&str; 5] = ["core", "alloc", "std", "proc_macro", "test"];
676
677#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
678pub enum DocumentationFormat {
679    Html,
680    Json,
681}
682
683impl DocumentationFormat {
684    fn as_str(&self) -> &str {
685        match self {
686            DocumentationFormat::Html => "HTML",
687            DocumentationFormat::Json => "JSON",
688        }
689    }
690}
691
692/// Build the documentation for public standard library crates.
693fn doc_std(
694    builder: &Builder<'_>,
695    format: DocumentationFormat,
696    stage: u32,
697    target: TargetSelection,
698    out: &Path,
699    extra_args: &[&str],
700    requested_crates: &[String],
701) {
702    let compiler = builder.compiler(stage, builder.config.build);
703
704    let target_doc_dir_name = if format == DocumentationFormat::Json { "json-doc" } else { "doc" };
705    let target_dir = builder.stage_out(compiler, Mode::Std).join(target).join(target_doc_dir_name);
706
707    // This is directory where the compiler will place the output of the command.
708    // We will then copy the files from this directory into the final `out` directory, the specified
709    // as a function parameter.
710    let out_dir = target_dir.join(target).join("doc");
711
712    let mut cargo =
713        builder::Cargo::new(builder, compiler, Mode::Std, SourceType::InTree, target, Kind::Doc);
714
715    compile::std_cargo(builder, target, compiler.stage, &mut cargo);
716    cargo
717        .arg("--no-deps")
718        .arg("--target-dir")
719        .arg(&*target_dir.to_string_lossy())
720        .arg("-Zskip-rustdoc-fingerprint")
721        .arg("-Zrustdoc-map")
722        .rustdocflag("--extern-html-root-url")
723        .rustdocflag("std_detect=https://docs.rs/std_detect/latest/")
724        .rustdocflag("--extern-html-root-takes-precedence")
725        .rustdocflag("--resource-suffix")
726        .rustdocflag(&builder.version);
727    for arg in extra_args {
728        cargo.rustdocflag(arg);
729    }
730
731    if builder.config.library_docs_private_items {
732        cargo.rustdocflag("--document-private-items").rustdocflag("--document-hidden-items");
733    }
734
735    for krate in requested_crates {
736        if krate == "sysroot" {
737            // The sysroot crate is an implementation detail, don't include it in public docs.
738            continue;
739        }
740        cargo.arg("-p").arg(krate);
741    }
742
743    let description =
744        format!("library{} in {} format", crate_description(requested_crates), format.as_str());
745    let _guard = builder.msg_doc(compiler, description, target);
746
747    cargo.into_cmd().run(builder);
748    builder.cp_link_r(&out_dir, out);
749}
750
751#[derive(Debug, Clone, Hash, PartialEq, Eq)]
752pub struct Rustc {
753    pub stage: u32,
754    pub target: TargetSelection,
755    crates: Vec<String>,
756}
757
758impl Rustc {
759    pub(crate) fn new(stage: u32, target: TargetSelection, builder: &Builder<'_>) -> Self {
760        let crates = builder
761            .in_tree_crates("rustc-main", Some(target))
762            .into_iter()
763            .map(|krate| krate.name.to_string())
764            .collect();
765        Self { stage, target, crates }
766    }
767}
768
769impl Step for Rustc {
770    type Output = ();
771    const DEFAULT: bool = true;
772    const ONLY_HOSTS: bool = true;
773
774    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
775        let builder = run.builder;
776        run.crate_or_deps("rustc-main")
777            .path("compiler")
778            .default_condition(builder.config.compiler_docs)
779    }
780
781    fn make_run(run: RunConfig<'_>) {
782        run.builder.ensure(Rustc {
783            stage: run.builder.top_stage,
784            target: run.target,
785            crates: run.make_run_crates(Alias::Compiler),
786        });
787    }
788
789    /// Generates compiler documentation.
790    ///
791    /// This will generate all documentation for compiler and dependencies.
792    /// Compiler documentation is distributed separately, so we make sure
793    /// we do not merge it with the other documentation from std, test and
794    /// proc_macros. This is largely just a wrapper around `cargo doc`.
795    fn run(self, builder: &Builder<'_>) {
796        let stage = self.stage;
797        let target = self.target;
798
799        // This is the intended out directory for compiler documentation.
800        let out = builder.compiler_doc_out(target);
801        t!(fs::create_dir_all(&out));
802
803        // Build the standard library, so that proc-macros can use it.
804        // (Normally, only the metadata would be necessary, but proc-macros are special since they run at compile-time.)
805        let compiler = builder.compiler(stage, builder.config.build);
806        builder.ensure(compile::Std::new(compiler, builder.config.build));
807
808        let _guard = builder.msg_sysroot_tool(
809            Kind::Doc,
810            stage,
811            format!("compiler{}", crate_description(&self.crates)),
812            compiler.host,
813            target,
814        );
815
816        // Build cargo command.
817        let mut cargo = builder::Cargo::new(
818            builder,
819            compiler,
820            Mode::Rustc,
821            SourceType::InTree,
822            target,
823            Kind::Doc,
824        );
825
826        cargo.rustdocflag("--document-private-items");
827        // Since we always pass --document-private-items, there's no need to warn about linking to private items.
828        cargo.rustdocflag("-Arustdoc::private-intra-doc-links");
829        cargo.rustdocflag("--enable-index-page");
830        cargo.rustdocflag("-Znormalize-docs");
831        cargo.rustdocflag("--show-type-layout");
832        // FIXME: `--generate-link-to-definition` tries to resolve cfged out code
833        // see https://github.com/rust-lang/rust/pull/122066#issuecomment-1983049222
834        // If there is any bug, please comment out the next line.
835        cargo.rustdocflag("--generate-link-to-definition");
836
837        compile::rustc_cargo(builder, &mut cargo, target, &compiler, &self.crates);
838        cargo.arg("-Zskip-rustdoc-fingerprint");
839
840        // Only include compiler crates, no dependencies of those, such as `libc`.
841        // Do link to dependencies on `docs.rs` however using `rustdoc-map`.
842        cargo.arg("--no-deps");
843        cargo.arg("-Zrustdoc-map");
844
845        // FIXME: `-Zrustdoc-map` does not yet correctly work for transitive dependencies,
846        // once this is no longer an issue the special case for `ena` can be removed.
847        cargo.rustdocflag("--extern-html-root-url");
848        cargo.rustdocflag("ena=https://docs.rs/ena/latest/");
849
850        let mut to_open = None;
851
852        let out_dir = builder.stage_out(compiler, Mode::Rustc).join(target).join("doc");
853        for krate in &*self.crates {
854            // Create all crate output directories first to make sure rustdoc uses
855            // relative links.
856            // FIXME: Cargo should probably do this itself.
857            let dir_name = krate.replace('-', "_");
858            t!(fs::create_dir_all(out_dir.join(&*dir_name)));
859            cargo.arg("-p").arg(krate);
860            if to_open.is_none() {
861                to_open = Some(dir_name);
862            }
863        }
864
865        // This uses a shared directory so that librustdoc documentation gets
866        // correctly built and merged with the rustc documentation.
867        //
868        // This is needed because rustdoc is built in a different directory from
869        // rustc. rustdoc needs to be able to see everything, for example when
870        // merging the search index, or generating local (relative) links.
871        symlink_dir_force(&builder.config, &out, &out_dir);
872        // Cargo puts proc macros in `target/doc` even if you pass `--target`
873        // explicitly (https://github.com/rust-lang/cargo/issues/7677).
874        let proc_macro_out_dir = builder.stage_out(compiler, Mode::Rustc).join("doc");
875        symlink_dir_force(&builder.config, &out, &proc_macro_out_dir);
876
877        cargo.into_cmd().run(builder);
878
879        if !builder.config.dry_run() {
880            // Sanity check on linked compiler crates
881            for krate in &*self.crates {
882                let dir_name = krate.replace('-', "_");
883                // Making sure the directory exists and is not empty.
884                assert!(out.join(&*dir_name).read_dir().unwrap().next().is_some());
885            }
886        }
887
888        if builder.paths.iter().any(|path| path.ends_with("compiler")) {
889            // For `x.py doc compiler --open`, open `rustc_middle` by default.
890            let index = out.join("rustc_middle").join("index.html");
891            builder.open_in_browser(index);
892        } else if let Some(krate) = to_open {
893            // Let's open the first crate documentation page:
894            let index = out.join(krate).join("index.html");
895            builder.open_in_browser(index);
896        }
897    }
898}
899
900macro_rules! tool_doc {
901    (
902        $tool: ident,
903        $path: literal,
904        $(rustc_tool = $rustc_tool:literal, )?
905        $(is_library = $is_library:expr,)?
906        $(crates = $crates:expr)?
907       ) => {
908        #[derive(Debug, Clone, Hash, PartialEq, Eq)]
909        pub struct $tool {
910            target: TargetSelection,
911        }
912
913        impl Step for $tool {
914            type Output = ();
915            const DEFAULT: bool = true;
916            const ONLY_HOSTS: bool = true;
917
918            fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
919                let builder = run.builder;
920                run.path($path).default_condition(builder.config.compiler_docs)
921            }
922
923            fn make_run(run: RunConfig<'_>) {
924                run.builder.ensure($tool { target: run.target });
925            }
926
927            /// Generates compiler documentation.
928            ///
929            /// This will generate all documentation for compiler and dependencies.
930            /// Compiler documentation is distributed separately, so we make sure
931            /// we do not merge it with the other documentation from std, test and
932            /// proc_macros. This is largely just a wrapper around `cargo doc`.
933            fn run(self, builder: &Builder<'_>) {
934                let mut source_type = SourceType::InTree;
935
936                if let Some(submodule_path) = submodule_path_of(&builder, $path) {
937                    source_type = SourceType::Submodule;
938                    builder.require_submodule(&submodule_path, None);
939                }
940
941                let stage = builder.top_stage;
942                let target = self.target;
943
944                // This is the intended out directory for compiler documentation.
945                let out = builder.compiler_doc_out(target);
946                t!(fs::create_dir_all(&out));
947
948                let compiler = builder.compiler(stage, builder.config.build);
949                builder.ensure(compile::Std::new(compiler, target));
950
951                if true $(&& $rustc_tool)? {
952                    // Build rustc docs so that we generate relative links.
953                    builder.ensure(Rustc::new(stage, target, builder));
954
955                    // Rustdoc needs the rustc sysroot available to build.
956                    // FIXME: is there a way to only ensure `check::Rustc` here? Last time I tried it failed
957                    // with strange errors, but only on a full bors test ...
958                    builder.ensure(compile::Rustc::new(compiler, target));
959                }
960
961                // Build cargo command.
962                let mut cargo = prepare_tool_cargo(
963                    builder,
964                    compiler,
965                    Mode::ToolRustc,
966                    target,
967                    Kind::Doc,
968                    $path,
969                    source_type,
970                    &[],
971                );
972
973                cargo.arg("-Zskip-rustdoc-fingerprint");
974                // Only include compiler crates, no dependencies of those, such as `libc`.
975                cargo.arg("--no-deps");
976
977                if false $(|| $is_library)? {
978                    cargo.arg("--lib");
979                }
980
981                $(for krate in $crates {
982                    cargo.arg("-p").arg(krate);
983                })?
984
985                cargo.rustdocflag("--document-private-items");
986                // Since we always pass --document-private-items, there's no need to warn about linking to private items.
987                cargo.rustdocflag("-Arustdoc::private-intra-doc-links");
988                cargo.rustdocflag("--enable-index-page");
989                cargo.rustdocflag("--show-type-layout");
990                cargo.rustdocflag("--generate-link-to-definition");
991
992                let out_dir = builder.stage_out(compiler, Mode::ToolRustc).join(target).join("doc");
993                $(for krate in $crates {
994                    let dir_name = krate.replace("-", "_");
995                    t!(fs::create_dir_all(out_dir.join(&*dir_name)));
996                })?
997
998                // Symlink compiler docs to the output directory of rustdoc documentation.
999                symlink_dir_force(&builder.config, &out, &out_dir);
1000                let proc_macro_out_dir = builder.stage_out(compiler, Mode::ToolRustc).join("doc");
1001                symlink_dir_force(&builder.config, &out, &proc_macro_out_dir);
1002
1003                let _guard = builder.msg_doc(compiler, stringify!($tool).to_lowercase(), target);
1004                cargo.into_cmd().run(builder);
1005
1006                if !builder.config.dry_run() {
1007                    // Sanity check on linked doc directories
1008                    $(for krate in $crates {
1009                        let dir_name = krate.replace("-", "_");
1010                        // Making sure the directory exists and is not empty.
1011                        assert!(out.join(&*dir_name).read_dir().unwrap().next().is_some());
1012                    })?
1013                }
1014            }
1015        }
1016    }
1017}
1018
1019// NOTE: make sure to register these in `Builder::get_step_description`.
1020tool_doc!(
1021    BuildHelper,
1022    "src/build_helper",
1023    rustc_tool = false,
1024    is_library = true,
1025    crates = ["build_helper"]
1026);
1027tool_doc!(Rustdoc, "src/tools/rustdoc", crates = ["rustdoc", "rustdoc-json-types"]);
1028tool_doc!(Rustfmt, "src/tools/rustfmt", crates = ["rustfmt-nightly", "rustfmt-config_proc_macro"]);
1029tool_doc!(Clippy, "src/tools/clippy", crates = ["clippy_config", "clippy_utils"]);
1030tool_doc!(Miri, "src/tools/miri", crates = ["miri"]);
1031tool_doc!(
1032    Cargo,
1033    "src/tools/cargo",
1034    rustc_tool = false,
1035    crates = [
1036        "cargo",
1037        "cargo-credential",
1038        "cargo-platform",
1039        "cargo-test-macro",
1040        "cargo-test-support",
1041        "cargo-util",
1042        "cargo-util-schemas",
1043        "crates-io",
1044        "mdman",
1045        "rustfix",
1046    ]
1047);
1048tool_doc!(Tidy, "src/tools/tidy", rustc_tool = false, crates = ["tidy"]);
1049tool_doc!(
1050    Bootstrap,
1051    "src/bootstrap",
1052    rustc_tool = false,
1053    is_library = true,
1054    crates = ["bootstrap"]
1055);
1056tool_doc!(
1057    RunMakeSupport,
1058    "src/tools/run-make-support",
1059    rustc_tool = false,
1060    is_library = true,
1061    crates = ["run_make_support"]
1062);
1063tool_doc!(
1064    Compiletest,
1065    "src/tools/compiletest",
1066    rustc_tool = false,
1067    is_library = true,
1068    crates = ["compiletest"]
1069);
1070
1071#[derive(Ord, PartialOrd, Debug, Clone, Hash, PartialEq, Eq)]
1072pub struct ErrorIndex {
1073    pub target: TargetSelection,
1074}
1075
1076impl Step for ErrorIndex {
1077    type Output = ();
1078    const DEFAULT: bool = true;
1079    const ONLY_HOSTS: bool = true;
1080
1081    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1082        let builder = run.builder;
1083        run.path("src/tools/error_index_generator").default_condition(builder.config.docs)
1084    }
1085
1086    fn make_run(run: RunConfig<'_>) {
1087        let target = run.target;
1088        run.builder.ensure(ErrorIndex { target });
1089    }
1090
1091    /// Generates the HTML rendered error-index by running the
1092    /// `error_index_generator` tool.
1093    fn run(self, builder: &Builder<'_>) {
1094        builder.info(&format!("Documenting error index ({})", self.target));
1095        let out = builder.doc_out(self.target);
1096        t!(fs::create_dir_all(&out));
1097        tool::ErrorIndex::command(builder).arg("html").arg(out).arg(&builder.version).run(builder);
1098    }
1099}
1100
1101#[derive(Debug, Clone, Hash, PartialEq, Eq)]
1102pub struct UnstableBookGen {
1103    target: TargetSelection,
1104}
1105
1106impl Step for UnstableBookGen {
1107    type Output = ();
1108    const DEFAULT: bool = true;
1109    const ONLY_HOSTS: bool = true;
1110
1111    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1112        let builder = run.builder;
1113        run.path("src/tools/unstable-book-gen").default_condition(builder.config.docs)
1114    }
1115
1116    fn make_run(run: RunConfig<'_>) {
1117        run.builder.ensure(UnstableBookGen { target: run.target });
1118    }
1119
1120    fn run(self, builder: &Builder<'_>) {
1121        let target = self.target;
1122
1123        builder.info(&format!("Generating unstable book md files ({target})"));
1124        let out = builder.md_doc_out(target).join("unstable-book");
1125        builder.create_dir(&out);
1126        builder.remove_dir(&out);
1127        let mut cmd = builder.tool_cmd(Tool::UnstableBookGen);
1128        cmd.arg(builder.src.join("library"));
1129        cmd.arg(builder.src.join("compiler"));
1130        cmd.arg(builder.src.join("src"));
1131        cmd.arg(out);
1132
1133        cmd.run(builder);
1134    }
1135}
1136
1137fn symlink_dir_force(config: &Config, original: &Path, link: &Path) {
1138    if config.dry_run() {
1139        return;
1140    }
1141    if let Ok(m) = fs::symlink_metadata(link) {
1142        if m.file_type().is_dir() {
1143            t!(fs::remove_dir_all(link));
1144        } else {
1145            // handle directory junctions on windows by falling back to
1146            // `remove_dir`.
1147            t!(fs::remove_file(link).or_else(|_| fs::remove_dir(link)));
1148        }
1149    }
1150
1151    t!(
1152        symlink_dir(config, original, link),
1153        format!("failed to create link from {} -> {}", link.display(), original.display())
1154    );
1155}
1156
1157#[derive(Ord, PartialOrd, Debug, Clone, Hash, PartialEq, Eq)]
1158pub struct RustcBook {
1159    pub compiler: Compiler,
1160    pub target: TargetSelection,
1161    pub validate: bool,
1162}
1163
1164impl Step for RustcBook {
1165    type Output = ();
1166    const DEFAULT: bool = true;
1167    const ONLY_HOSTS: bool = true;
1168
1169    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1170        let builder = run.builder;
1171        run.path("src/doc/rustc").default_condition(builder.config.docs)
1172    }
1173
1174    fn make_run(run: RunConfig<'_>) {
1175        run.builder.ensure(RustcBook {
1176            compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
1177            target: run.target,
1178            validate: false,
1179        });
1180    }
1181
1182    /// Builds the rustc book.
1183    ///
1184    /// The lints are auto-generated by a tool, and then merged into the book
1185    /// in the "md-doc" directory in the build output directory. Then
1186    /// "rustbook" is used to convert it to HTML.
1187    fn run(self, builder: &Builder<'_>) {
1188        let out_base = builder.md_doc_out(self.target).join("rustc");
1189        t!(fs::create_dir_all(&out_base));
1190        let out_listing = out_base.join("src/lints");
1191        builder.cp_link_r(&builder.src.join("src/doc/rustc"), &out_base);
1192        builder.info(&format!("Generating lint docs ({})", self.target));
1193
1194        let rustc = builder.rustc(self.compiler);
1195        // The tool runs `rustc` for extracting output examples, so it needs a
1196        // functional sysroot.
1197        builder.ensure(compile::Std::new(self.compiler, self.target));
1198        let mut cmd = builder.tool_cmd(Tool::LintDocs);
1199        cmd.arg("--src");
1200        cmd.arg(builder.src.join("compiler"));
1201        cmd.arg("--out");
1202        cmd.arg(&out_listing);
1203        cmd.arg("--rustc");
1204        cmd.arg(&rustc);
1205        cmd.arg("--rustc-target").arg(self.target.rustc_target_arg());
1206        if let Some(target_linker) = builder.linker(self.target) {
1207            cmd.arg("--rustc-linker").arg(target_linker);
1208        }
1209        if builder.is_verbose() {
1210            cmd.arg("--verbose");
1211        }
1212        if self.validate {
1213            cmd.arg("--validate");
1214        }
1215        // We need to validate nightly features, even on the stable channel.
1216        // Set this unconditionally as the stage0 compiler may be being used to
1217        // document.
1218        cmd.env("RUSTC_BOOTSTRAP", "1");
1219
1220        // If the lib directories are in an unusual location (changed in
1221        // config.toml), then this needs to explicitly update the dylib search
1222        // path.
1223        builder.add_rustc_lib_path(self.compiler, &mut cmd);
1224        let doc_generator_guard = builder.msg(
1225            Kind::Run,
1226            self.compiler.stage,
1227            "lint-docs",
1228            self.compiler.host,
1229            self.target,
1230        );
1231        cmd.run(builder);
1232        drop(doc_generator_guard);
1233
1234        // Run rustbook/mdbook to generate the HTML pages.
1235        builder.ensure(RustbookSrc {
1236            target: self.target,
1237            name: "rustc".to_owned(),
1238            src: out_base,
1239            parent: Some(self),
1240            languages: vec![],
1241            rustdoc_compiler: None,
1242        });
1243    }
1244}
1245
1246#[derive(Ord, PartialOrd, Debug, Clone, Hash, PartialEq, Eq)]
1247pub struct Reference {
1248    pub compiler: Compiler,
1249    pub target: TargetSelection,
1250}
1251
1252impl Step for Reference {
1253    type Output = ();
1254    const DEFAULT: bool = true;
1255
1256    fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> {
1257        let builder = run.builder;
1258        run.path("src/doc/reference").default_condition(builder.config.docs)
1259    }
1260
1261    fn make_run(run: RunConfig<'_>) {
1262        run.builder.ensure(Reference {
1263            compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.build),
1264            target: run.target,
1265        });
1266    }
1267
1268    /// Builds the reference book.
1269    fn run(self, builder: &Builder<'_>) {
1270        builder.require_submodule("src/doc/reference", None);
1271
1272        // This is needed for generating links to the standard library using
1273        // the mdbook-spec plugin.
1274        builder.ensure(compile::Std::new(self.compiler, builder.config.build));
1275
1276        // Run rustbook/mdbook to generate the HTML pages.
1277        builder.ensure(RustbookSrc {
1278            target: self.target,
1279            name: "reference".to_owned(),
1280            src: builder.src.join("src/doc/reference"),
1281            rustdoc_compiler: Some(self.compiler),
1282            parent: Some(self),
1283            languages: vec![],
1284        });
1285    }
1286}