Skip to main content

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