Skip to main content

rustdoc/
lib.rs

1// tidy-alphabetical-start
2#![doc(
3    html_root_url = "https://doc.rust-lang.org/nightly/",
4    html_playground_url = "https://play.rust-lang.org/"
5)]
6#![feature(ascii_char)]
7#![feature(ascii_char_variants)]
8#![feature(default_field_values)]
9#![feature(deref_patterns)]
10#![feature(file_buffered)]
11#![feature(formatting_options)]
12#![feature(iter_intersperse)]
13#![feature(iter_order_by)]
14#![feature(iter_partition_in_place)]
15#![feature(rustc_private)]
16#![feature(test)]
17#![feature(variant_count)]
18#![recursion_limit = "256"]
19#![warn(rustc::internal)]
20#![warn(rustc::symbol_intern_string_literal)]
21// tidy-alphabetical-end
22
23// N.B. these need `extern crate` even in 2018 edition
24// because they're loaded implicitly from the sysroot.
25// The reason they're loaded from the sysroot is because
26// the rustdoc artifacts aren't stored in rustc's cargo target directory.
27// So if `rustc` was specified in Cargo.toml, this would spuriously rebuild crates.
28//
29// Dependencies listed in Cargo.toml do not need `extern crate`.
30
31extern crate rustc_abi;
32extern crate rustc_ast;
33extern crate rustc_ast_pretty;
34extern crate rustc_attr_ir;
35extern crate rustc_attr_parsing;
36extern crate rustc_data_structures;
37extern crate rustc_driver;
38extern crate rustc_errors;
39extern crate rustc_feature;
40extern crate rustc_hir;
41extern crate rustc_hir_analysis;
42extern crate rustc_hir_pretty;
43extern crate rustc_index;
44extern crate rustc_infer;
45extern crate rustc_interface;
46extern crate rustc_lexer;
47extern crate rustc_lint;
48extern crate rustc_log;
49extern crate rustc_macros;
50extern crate rustc_metadata;
51extern crate rustc_middle;
52extern crate rustc_parse;
53extern crate rustc_passes;
54extern crate rustc_resolve;
55extern crate rustc_serialize;
56extern crate rustc_session;
57extern crate rustc_span;
58extern crate rustc_structures;
59extern crate rustc_target;
60extern crate rustc_trait_selection;
61extern crate test;
62
63use std::env::{self, VarError};
64use std::io::{self, IsTerminal};
65use std::path::Path;
66use std::process::{ExitCode, Termination};
67
68use rustc_ast::ast;
69use rustc_errors::DiagCtxtHandle;
70use rustc_hir::def_id::LOCAL_CRATE;
71use rustc_interface::interface;
72use rustc_middle::ty::TyCtxt;
73use rustc_session::config::{Input, RustcOptGroup, make_crate_type_option};
74use rustc_session::output::ErrorOutputType;
75use rustc_session::{EarlyDiagCtxt, getopts};
76use rustc_span::{BytePos, Span, SyntaxContext};
77use tracing::info;
78
79use crate::clean::utils::DOC_RUST_LANG_ORG_VERSION;
80use crate::config::EmitType;
81use crate::error::Error;
82use crate::formats::cache::Cache;
83
84/// A macro to create a FxHashMap.
85///
86/// Example:
87///
88/// ```ignore(cannot-test-this-because-non-exported-macro)
89/// let letters = map!{"a" => "b", "c" => "d"};
90/// ```
91///
92/// Trailing commas are allowed.
93/// Commas between elements are required (even if the expression is a block).
94macro_rules! map {
95    ($( $key: expr => $val: expr ),* $(,)*) => {{
96        let mut map = ::rustc_data_structures::fx::FxIndexMap::default();
97        $( map.insert($key, $val); )*
98        map
99    }}
100}
101
102mod calculate_doc_coverage;
103mod clean;
104mod config;
105mod core;
106mod display;
107mod docfs;
108mod doctest;
109mod error;
110mod externalfiles;
111mod fold;
112mod formats;
113// used by the error-index generator, so it needs to be public
114pub mod html;
115mod json;
116pub(crate) mod lint;
117mod markdown;
118mod passes;
119mod scrape_examples;
120mod theme;
121mod visit;
122mod visit_ast;
123mod visit_lib;
124
125pub fn main() -> ExitCode {
126    let mut early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default());
127
128    rustc_driver::install_ice_hook(
129        "https://github.com/rust-lang/rust/issues/new\
130    ?labels=C-bug%2C+I-ICE%2C+T-rustdoc&template=ice.md",
131        |_| (),
132    );
133
134    // When using CI artifacts with `download-rustc`, tracing is unconditionally built
135    // with `--features=static_max_level_info`, which disables almost all rustdoc logging. To avoid
136    // this, compile our own version of `tracing` that logs all levels.
137    // NOTE: this compiles both versions of tracing unconditionally, because
138    // - The compile time hit is not that bad, especially compared to rustdoc's incremental times, and
139    // - Otherwise, there's no warning that logging is being ignored when `download-rustc` is enabled
140
141    crate::init_logging(&early_dcx);
142    match rustc_log::init_logger(rustc_log::LoggerConfig::from_env("RUSTDOC_LOG")) {
143        Ok(()) => {}
144        // With `download-rustc = true` there are definitely 2 distinct tracing crates in the
145        // dependency graph: one in the downloaded sysroot and one built just now as a dependency of
146        // rustdoc. So the sysroot's tracing is definitely not yet initialized here.
147        //
148        // But otherwise, depending on link style, there may or may not be 2 tracing crates in play.
149        // The one we just initialized in `crate::init_logging` above is rustdoc's direct dependency
150        // on tracing. When rustdoc is built by x.py using Cargo, rustc_driver's and rustc_log's
151        // tracing dependency is distinct from this one and also needs to be initialized (using the
152        // same RUSTDOC_LOG environment variable for both). Other build systems may use just a
153        // single tracing crate throughout the rustc and rustdoc build.
154        //
155        // The reason initializing 2 tracings does not show double logging when `download-rustc =
156        // false` and `debug_logging = true` is because all rustc logging goes only to its version
157        // of tracing (the one in the sysroot) and all of rustdoc's logging only goes to its version
158        // (the one in Cargo.toml).
159        Err(rustc_log::Error::AlreadyInit(_)) => {}
160        Err(error) => early_dcx.early_fatal(error.to_string()),
161    }
162
163    rustc_driver::catch_with_exit_code(|| {
164        let at_args = rustc_driver::args::raw_args(&early_dcx);
165        main_args(&mut early_dcx, &at_args)
166    })
167}
168
169fn init_logging(early_dcx: &EarlyDiagCtxt) {
170    let color_logs = match env::var("RUSTDOC_LOG_COLOR").as_deref() {
171        Ok("always") => true,
172        Ok("never") => false,
173        Ok("auto") | Err(VarError::NotPresent) => io::stdout().is_terminal(),
174        Ok(value) => early_dcx.early_fatal(format!(
175            "invalid log color value '{value}': expected one of always, never, or auto",
176        )),
177        Err(VarError::NotUnicode(value)) => early_dcx.early_fatal(format!(
178            "invalid log color value '{}': expected one of always, never, or auto",
179            value.to_string_lossy()
180        )),
181    };
182    let filter = tracing_subscriber::EnvFilter::from_env("RUSTDOC_LOG");
183    let layer = tracing_tree::HierarchicalLayer::default()
184        .with_writer(io::stderr)
185        .with_ansi(color_logs)
186        .with_targets(true)
187        .with_wraparound(10)
188        .with_verbose_exit(true)
189        .with_verbose_entry(true)
190        .with_indent_amount(2);
191    #[cfg(debug_assertions)]
192    let layer = layer.with_thread_ids(true).with_thread_names(true);
193
194    use tracing_subscriber::layer::SubscriberExt;
195    let subscriber = tracing_subscriber::Registry::default().with(filter).with(layer);
196    tracing::subscriber::set_global_default(subscriber).unwrap();
197}
198
199fn opts() -> Vec<RustcOptGroup> {
200    use rustc_session::config::OptionKind::{Flag, FlagMulti, Multi, Opt};
201    use rustc_session::config::OptionStability::{Stable, Unstable};
202    use rustc_session::config::make_opt as opt;
203
204    vec![
205        opt(Stable, FlagMulti, "h", "help", "show this help message", ""),
206        opt(Stable, FlagMulti, "V", "version", "print rustdoc's version", ""),
207        opt(Stable, FlagMulti, "v", "verbose", "use verbose output", ""),
208        opt(Stable, Opt, "w", "output-format", "the output type to write", "[html]"),
209        opt(
210            Stable,
211            Opt,
212            "",
213            "output",
214            "Which directory to place the output. This option is deprecated, use --out-dir instead.",
215            "PATH",
216        ),
217        opt(Stable, Opt, "o", "out-dir", "which directory to place the output", "PATH"),
218        opt(Stable, Opt, "", "crate-name", "specify the name of this crate", "NAME"),
219        make_crate_type_option(),
220        opt(Stable, Multi, "L", "library-path", "directory to add to crate search path", "DIR"),
221        opt(Stable, Multi, "", "cfg", "pass a --cfg to rustc", ""),
222        opt(Stable, Multi, "", "check-cfg", "pass a --check-cfg to rustc", ""),
223        opt(Stable, Multi, "", "extern", "pass an --extern to rustc", "NAME[=PATH]"),
224        opt(
225            Unstable,
226            Multi,
227            "",
228            "extern-html-root-url",
229            "base URL to use for dependencies; for example, \
230                \"std=/doc\" links std::vec::Vec to /doc/std/vec/struct.Vec.html",
231            "NAME=URL",
232        ),
233        opt(
234            Unstable,
235            FlagMulti,
236            "",
237            "extern-html-root-takes-precedence",
238            "give precedence to `--extern-html-root-url`, not `html_root_url`",
239            "",
240        ),
241        opt(Stable, Multi, "C", "codegen", "pass a codegen option to rustc", "OPT[=VALUE]"),
242        opt(Stable, FlagMulti, "", "document-private-items", "document private items", ""),
243        opt(
244            Unstable,
245            FlagMulti,
246            "",
247            "document-hidden-items",
248            "document items that have doc(hidden)",
249            "",
250        ),
251        opt(Stable, FlagMulti, "", "test", "run code examples as tests", ""),
252        opt(Stable, Multi, "", "test-args", "arguments to pass to the test runner", "ARGS"),
253        opt(
254            Stable,
255            Opt,
256            "",
257            "test-run-directory",
258            "The working directory in which to run tests",
259            "PATH",
260        ),
261        opt(Stable, Opt, "", "target", "target triple to document", "TRIPLE"),
262        opt(
263            Stable,
264            Multi,
265            "",
266            "markdown-css",
267            "CSS files to include via <link> in a rendered Markdown file",
268            "FILES",
269        ),
270        opt(
271            Stable,
272            Multi,
273            "",
274            "html-in-header",
275            "files to include inline in the <head> section of a rendered Markdown file \
276                or generated documentation",
277            "FILES",
278        ),
279        opt(
280            Stable,
281            Multi,
282            "",
283            "html-before-content",
284            "files to include inline between <body> and the content of a rendered \
285                Markdown file or generated documentation",
286            "FILES",
287        ),
288        opt(
289            Stable,
290            Multi,
291            "",
292            "html-after-content",
293            "files to include inline between the content and </body> of a rendered \
294                Markdown file or generated documentation",
295            "FILES",
296        ),
297        opt(
298            Unstable,
299            Multi,
300            "",
301            "markdown-before-content",
302            "files to include inline between <body> and the content of a rendered \
303                Markdown file or generated documentation",
304            "FILES",
305        ),
306        opt(
307            Unstable,
308            Multi,
309            "",
310            "markdown-after-content",
311            "files to include inline between the content and </body> of a rendered \
312                Markdown file or generated documentation",
313            "FILES",
314        ),
315        opt(Stable, Opt, "", "markdown-playground-url", "URL to send code snippets to", "URL"),
316        opt(Stable, FlagMulti, "", "markdown-no-toc", "don't include table of contents", ""),
317        opt(
318            Stable,
319            Opt,
320            "e",
321            "extend-css",
322            "To add some CSS rules with a given file to generate doc with your own theme. \
323                However, your theme might break if the rustdoc's generated HTML changes, so be careful!",
324            "PATH",
325        ),
326        opt(
327            Unstable,
328            Multi,
329            "Z",
330            "",
331            "unstable / perma-unstable options (only on nightly build)",
332            "FLAG",
333        ),
334        opt(Stable, Opt, "", "sysroot", "Override the system root", "PATH"),
335        opt(
336            Unstable,
337            Opt,
338            "",
339            "playground-url",
340            "URL to send code snippets to, may be reset by --markdown-playground-url \
341                or `#![doc(html_playground_url=...)]`",
342            "URL",
343        ),
344        opt(
345            Unstable,
346            FlagMulti,
347            "",
348            "display-doctest-warnings",
349            "show warnings that originate in doctests",
350            "",
351        ),
352        opt(
353            Stable,
354            Opt,
355            "",
356            "crate-version",
357            "crate version to print into documentation",
358            "VERSION",
359        ),
360        opt(
361            Unstable,
362            FlagMulti,
363            "",
364            "sort-modules-by-appearance",
365            "sort modules by where they appear in the program, rather than alphabetically",
366            "",
367        ),
368        opt(
369            Unstable,
370            Opt,
371            "",
372            "crate-list-heading",
373            "heading under which to list this crate in the sidebar crate list",
374            "TEXT",
375        ),
376        opt(
377            Stable,
378            Opt,
379            "",
380            "default-theme",
381            "Set the default theme. THEME should be the theme name, generally lowercase. \
382                If an unknown default theme is specified, the builtin default is used. \
383                The set of themes, and the rustdoc built-in default, are not stable.",
384            "THEME",
385        ),
386        opt(
387            Unstable,
388            Multi,
389            "",
390            "default-setting",
391            "Default value for a rustdoc setting (used when \"rustdoc-SETTING\" is absent \
392                from web browser Local Storage). If VALUE is not supplied, \"true\" is used. \
393                Supported SETTINGs and VALUEs are not documented and not stable.",
394            "SETTING[=VALUE]",
395        ),
396        opt(
397            Stable,
398            Multi,
399            "",
400            "theme",
401            "additional themes which will be added to the generated docs",
402            "FILES",
403        ),
404        opt(Stable, Multi, "", "check-theme", "check if given theme is valid", "FILES"),
405        opt(
406            Unstable,
407            Opt,
408            "",
409            "resource-suffix",
410            "suffix to add to CSS and JavaScript files, \
411                e.g., \"search-index.js\" will become \"search-index-suffix.js\"",
412            "PATH",
413        ),
414        opt(
415            Stable,
416            Opt,
417            "",
418            "edition",
419            "edition to use when compiling rust code (default: 2015)",
420            "EDITION",
421        ),
422        opt(
423            Stable,
424            Opt,
425            "",
426            "color",
427            "Configure coloring of output:
428                                          auto   = colorize, if output goes to a tty (default);
429                                          always = always colorize output;
430                                          never  = never colorize output",
431            "auto|always|never",
432        ),
433        opt(
434            Stable,
435            Opt,
436            "",
437            "error-format",
438            "How errors and other messages are produced",
439            "human|json|short",
440        ),
441        opt(
442            Stable,
443            Opt,
444            "",
445            "diagnostic-width",
446            "Provide width of the output for truncated error messages",
447            "WIDTH",
448        ),
449        opt(Stable, Opt, "", "json", "Configure the structure of JSON diagnostics", "CONFIG"),
450        opt(Stable, Multi, "A", "allow", "Set lint allowed", "LINT"),
451        opt(Stable, Multi, "W", "warn", "Set lint warnings", "LINT"),
452        opt(Stable, Multi, "", "force-warn", "Set lint force-warn", "LINT"),
453        opt(Stable, Multi, "D", "deny", "Set lint denied", "LINT"),
454        opt(Stable, Multi, "F", "forbid", "Set lint forbidden", "LINT"),
455        opt(
456            Stable,
457            Multi,
458            "",
459            "cap-lints",
460            "Set the most restrictive lint level. \
461                More restrictive lints are capped at this level. \
462                By default, it is at `forbid` level.",
463            "LEVEL",
464        ),
465        opt(
466            Stable,
467            Multi,
468            "",
469            "remap-path-prefix",
470            "Remap source names in compiler messages",
471            "FROM=TO",
472        ),
473        opt(
474            Stable,
475            Opt,
476            "",
477            "remap-path-scope",
478            "Defines which scopes of paths should be remapped by `--remap-path-prefix`",
479            "[macro,diagnostics,documentation,debuginfo,coverage,object,all]",
480        ),
481        opt(Unstable, Opt, "", "index-page", "Markdown file to be used as index page", "PATH"),
482        opt(
483            Unstable,
484            FlagMulti,
485            "",
486            "enable-index-page",
487            "To enable generation of the index page",
488            "",
489        ),
490        opt(
491            Unstable,
492            Opt,
493            "",
494            "static-root-path",
495            "Path string to force loading static files from in output pages. \
496                If not set, uses combinations of '../' to reach the documentation root.",
497            "PATH",
498        ),
499        opt(
500            Unstable,
501            Opt,
502            "",
503            "persist-doctests",
504            "Directory to persist doctest executables into",
505            "PATH",
506        ),
507        opt(
508            Unstable,
509            FlagMulti,
510            "",
511            "coverage",
512            "calculate percentage of public items with documentation",
513            "",
514        ),
515        opt(
516            Stable,
517            Opt,
518            "",
519            "test-runtool",
520            "",
521            "The tool to run tests with when building for a different target than host",
522        ),
523        opt(
524            Stable,
525            Multi,
526            "",
527            "test-runtool-arg",
528            "",
529            "One argument (of possibly many) to pass to the runtool",
530        ),
531        opt(
532            Unstable,
533            Opt,
534            "",
535            "test-builder",
536            "The rustc-like binary to use as the test builder",
537            "PATH",
538        ),
539        opt(
540            Unstable,
541            Multi,
542            "",
543            "test-builder-wrapper",
544            "Wrapper program to pass test-builder and arguments",
545            "PATH",
546        ),
547        opt(Unstable, FlagMulti, "", "check", "Run rustdoc checks", ""),
548        opt(
549            Unstable,
550            FlagMulti,
551            "",
552            "generate-redirect-map",
553            "Generate JSON file at the top level instead of generating HTML redirection files",
554            "",
555        ),
556        opt(
557            Stable,
558            Multi,
559            "",
560            "emit",
561            "Comma separated list of types of output for rustdoc to emit",
562            "[html-static-files,html-non-static-files,dep-info]",
563        ),
564        opt(
565            Unstable,
566            Multi,
567            "",
568            "print",
569            "Rustdoc information to print on stdout (or to a file)",
570            "<INFO>[=<FILE>]",
571        ),
572        opt(Unstable, FlagMulti, "", "no-run", "Compile doctests without running them", ""),
573        opt(
574            Unstable,
575            Opt,
576            "",
577            "merge-doctests",
578            "Force all doctests to be compiled as a single binary, instead of one binary per test. If merging fails, rustdoc will emit a hard error.",
579            "yes|no|auto",
580        ),
581        opt(
582            Unstable,
583            FlagMulti,
584            "",
585            "show-type-layout",
586            "Include the memory layout of types in the docs",
587            "",
588        ),
589        opt(Unstable, Flag, "", "no-capture", "Don't capture stdout and stderr of tests", ""),
590        opt(
591            Unstable,
592            Flag,
593            "",
594            "generate-link-to-definition",
595            "Make the identifiers in the HTML source code pages navigable",
596            "",
597        ),
598        opt(
599            Unstable,
600            Opt,
601            "",
602            "scrape-examples-output-path",
603            "",
604            "collect function call information and output at the given path",
605        ),
606        opt(
607            Unstable,
608            Multi,
609            "",
610            "scrape-examples-target-crate",
611            "",
612            "collect function call information for functions from the target crate",
613        ),
614        opt(Unstable, Flag, "", "scrape-tests", "Include test code when scraping examples", ""),
615        opt(
616            Unstable,
617            Multi,
618            "",
619            "with-examples",
620            "",
621            "path to function call information (for displaying examples in the documentation)",
622        ),
623        opt(
624            Unstable,
625            Opt,
626            "",
627            "write-doc-meta-dir",
628            "Writes trait implementations and other info for the current crate to provided path",
629            "path/to/doc.meta",
630        ),
631        opt(
632            Unstable,
633            Multi,
634            "",
635            "read-doc-meta-dir",
636            "Includes trait implementations and other crate info from provided path",
637            "path/to/doc.meta",
638        ),
639        opt(
640            Unstable,
641            Opt,
642            "",
643            "parts-out-dir",
644            "Deprecated synonym of write-doc-meta-dir",
645            "path/to/doc.meta",
646        ),
647        opt(
648            Unstable,
649            Multi,
650            "",
651            "include-parts-dir",
652            "Deprecated synonym of read-doc-meta-dir",
653            "path/to/doc.meta",
654        ),
655        opt(
656            Unstable,
657            Opt,
658            "",
659            "merge",
660            "Deprecated option to specify read/write-doc-meta-dir mode",
661            "none, shared, finalize",
662        ),
663        opt(Unstable, Flag, "", "html-no-source", "Disable HTML source code pages generation", ""),
664        opt(
665            Unstable,
666            Multi,
667            "",
668            "doctest-build-arg",
669            "One argument (of possibly many) to be used when compiling doctests",
670            "ARG",
671        ),
672        opt(
673            Unstable,
674            FlagMulti,
675            "",
676            "disable-minification",
677            "disable the minification of CSS/JS files (perma-unstable, do not use with cached files)",
678            "",
679        ),
680        opt(
681            Unstable,
682            Flag,
683            "",
684            "generate-macro-expansion",
685            "Add possibility to expand macros in the HTML source code pages",
686            "",
687        ),
688        // deprecated / removed options
689        opt(
690            Stable,
691            Multi,
692            "",
693            "plugin-path",
694            "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> for more information",
695            "DIR",
696        ),
697        opt(
698            Stable,
699            Multi,
700            "",
701            "passes",
702            "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> for more information",
703            "PASSES",
704        ),
705        opt(
706            Stable,
707            Multi,
708            "",
709            "plugins",
710            "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> for more information",
711            "PLUGINS",
712        ),
713        opt(
714            Stable,
715            FlagMulti,
716            "",
717            "no-defaults",
718            "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> for more information",
719            "",
720        ),
721        opt(
722            Stable,
723            Opt,
724            "r",
725            "input-format",
726            "removed, see issue #44136 <https://github.com/rust-lang/rust/issues/44136> for more information",
727            "[rust]",
728        ),
729    ]
730}
731
732fn usage(argv0: &str) {
733    let mut options = getopts::Options::new();
734    for option in opts() {
735        option.apply(&mut options);
736    }
737    println!("{}", options.usage(&format!("{argv0} [options] <input>")));
738    println!("    @path               Read newline separated options from `path`\n");
739    println!(
740        "More information available at {DOC_RUST_LANG_ORG_VERSION}/rustdoc/what-is-rustdoc.html",
741    );
742}
743
744pub(crate) fn wrap_return<T: Termination>(dcx: DiagCtxtHandle<'_>, res: Result<T, String>) -> T {
745    match res {
746        Ok(val) => {
747            dcx.abort_if_errors();
748            val
749        }
750        Err(err) => dcx.fatal(err),
751    }
752}
753
754fn run_renderer<
755    'tcx,
756    T: formats::FormatRenderer<'tcx>,
757    F: FnOnce(
758        clean::Crate,
759        config::RenderOptions,
760        Cache,
761        TyCtxt<'tcx>,
762    ) -> Result<(T, clean::Crate), Error>,
763>(
764    krate: clean::Crate,
765    renderopts: config::RenderOptions,
766    cache: formats::cache::Cache,
767    tcx: TyCtxt<'tcx>,
768    init: F,
769) {
770    match formats::run_format::<T, F>(krate, renderopts, cache, tcx, init) {
771        Ok(_) => tcx.dcx().abort_if_errors(),
772        Err(e) => {
773            let mut msg =
774                tcx.dcx().struct_fatal(format!("couldn't generate documentation: {}", e.error));
775            let file = e.file.display().to_string();
776            if !file.is_empty() {
777                msg.note(format!("failed to create or modify {e}"));
778            } else {
779                msg.note(format!("failed to create or modify file: {e}"));
780            }
781            msg.emit();
782        }
783    }
784}
785
786/// Renders and writes cross-crate info files, like the search index. This function exists so that
787/// we can run rustdoc without a crate root in the `--merge=finalize` mode. Cross-crate info files
788/// discovered via `--read-doc-meta-dir` are combined and written to the doc root.
789fn run_merge_finalize(
790    render_options: config::RenderOptions,
791    compiler: &interface::Compiler,
792) -> Result<(), error::Error> {
793    assert!(
794        render_options.should_merge.write_rendered_cci,
795        "config.rs only allows us to return InputMode::NoInputMergeFinalize if --merge=finalize"
796    );
797    assert!(
798        !render_options.should_merge.read_rendered_cci,
799        "config.rs only allows us to return InputMode::NoInputMergeFinalize if --merge=finalize"
800    );
801    let crates = html::render::CrateInfo::read_many(&render_options.include_parts_dir)?;
802    let include_sources = !render_options.html_no_source;
803
804    html::render::write_not_crate_specific(
805        &crates,
806        &render_options.output,
807        &render_options,
808        &render_options.themes,
809        render_options.extension_css.as_deref(),
810        &render_options.resource_suffix,
811        include_sources,
812        &crate::html::layout::Layout {
813            logo: String::new(),
814            favicon: String::new(),
815            external_html: render_options.external_html.clone(),
816            default_settings: render_options.default_settings.clone(),
817            krate: String::new(),
818            krate_version: String::new(),
819            css_file_extension: render_options.extension_css.clone(),
820            scrape_examples_extension: false,
821        },
822        &compiler.sess,
823    )?;
824    Ok(())
825}
826
827fn main_args(early_dcx: &mut EarlyDiagCtxt, at_args: &[String]) -> ExitCode {
828    // Throw away the first argument, the name of the binary.
829    // In case of at_args being empty, as might be the case by
830    // passing empty argument array to execve under some platforms,
831    // just use an empty slice.
832    //
833    // This situation was possible before due to arg_expand_all being
834    // called before removing the argument, enabling a crash by calling
835    // the compiler with @empty_file as argv[0] and no more arguments.
836    let at_args = at_args.get(1..).unwrap_or_default();
837
838    let args = rustc_driver::args::arg_expand_all(early_dcx, at_args);
839
840    let mut options = getopts::Options::new();
841    for option in opts() {
842        option.apply(&mut options);
843    }
844    let matches = match options.parse(&args) {
845        Ok(m) => m,
846        Err(err) => {
847            early_dcx.early_fatal(err.to_string());
848        }
849    };
850
851    // Note that we discard any distinction between different non-zero exit
852    // codes from `from_matches` here.
853    let (input, options, render_options, loaded_paths) =
854        match config::Options::from_matches(early_dcx, &matches, args) {
855            Some(opts) => opts,
856            None => return ExitCode::SUCCESS,
857        };
858
859    let dcx =
860        core::new_dcx(options.error_format, None, options.diagnostic_width, &options.unstable_opts);
861    let dcx = dcx.handle();
862
863    let input = match input {
864        config::InputMode::HasFile(input) => input,
865        config::InputMode::NoInputMergeFinalize => {
866            if !options.prints.is_empty() {
867                dcx.fatal("`--print` is not supported for the `--write-doc-meta-dir` option");
868            }
869
870            let config = core::create_config(
871                Input::Str {
872                    name: rustc_span::FileName::Custom(String::new()),
873                    input: String::new(),
874                },
875                options,
876                &render_options,
877            );
878            wrap_return(
879                dcx,
880                interface::run_compiler(config, |compiler| {
881                    run_merge_finalize(render_options, compiler)
882                        .map_err(|e| format!("could not write merged cross-crate info: {e}"))
883                }),
884            );
885            return ExitCode::SUCCESS;
886        }
887    };
888    let md_input = config::markdown_input(&input);
889
890    if options.should_test || options.output_format == config::OutputFormat::Doctest {
891        if !options.prints.is_empty() {
892            dcx.fatal(format!(
893                "`--print` is not yet supported for the `{}` option",
894                if options.should_test { "--test" } else { "--output-format=doctest" }
895            ));
896        }
897
898        return match md_input {
899            Some(_) => wrap_return(dcx, doctest::test_markdown(&input, options, dcx)),
900            None => doctest::run(dcx, input, options),
901        };
902    }
903
904    if let Some(md_input) = md_input {
905        if !options.prints.is_empty() {
906            dcx.fatal("`--print` is not yet supported for standalone Markdown files");
907        }
908
909        return {
910            let md_input = md_input.to_owned();
911            let edition = options.edition;
912            let config = core::create_config(input, options, &render_options);
913            let registered_lints = config.register_lints.is_some();
914
915            // `markdown::render` can invoke `doctest::make_test`, which
916            // requires session globals and a thread pool, so we use
917            // `run_compiler`.
918            wrap_return(
919                dcx,
920                interface::run_compiler(config, |compiler| {
921                    let sess = &compiler.sess;
922
923                    // -W help
924                    if sess.opts.describe_lints {
925                        rustc_driver::describe_lints(sess, registered_lints);
926                        return Ok(());
927                    }
928
929                    // construct a phony "crate" without actually running the parser
930                    // allows us to use other compiler infrastructure like dep-info
931                    let file = sess
932                        .source_map()
933                        .load_file(&md_input)
934                        .map_err(|e| format!("{md_input}: {e}", md_input = md_input.display()))?;
935                    let inner_span = Span::new(
936                        file.start_pos,
937                        BytePos(file.start_pos.0 + file.normalized_source_len.0),
938                        SyntaxContext::root(),
939                        None,
940                    );
941                    let krate = ast::Crate {
942                        attrs: Default::default(),
943                        items: Default::default(),
944                        spans: ast::ModSpans { inner_span, ..Default::default() },
945                        id: ast::DUMMY_NODE_ID,
946                        is_placeholder: false,
947                    };
948                    let (res, _incr_comp_session) =
949                        rustc_interface::create_and_enter_global_ctxt(compiler, krate, |tcx| {
950                            let has_dep_info = render_options.dep_info().is_some();
951                            if render_options.emit.contains(&EmitType::HtmlNonStaticFiles) {
952                                markdown::render_and_write(file, render_options, edition)?;
953                            }
954                            if has_dep_info {
955                                // Register the loaded external files in the source map so they show up in depinfo.
956                                // We can't load them via the source map because it gets created after we process the options.
957                                for external_path in &loaded_paths {
958                                    let _ =
959                                        compiler.sess.source_map().load_binary_file(external_path);
960                                }
961                                rustc_interface::passes::write_dep_info(tcx);
962                            }
963                            Ok(())
964                        });
965                    res
966                }),
967            );
968            ExitCode::SUCCESS
969        };
970    }
971
972    // need to move these items separately because we lose them by the time the closure is called,
973    // but we can't create the dcx ahead of time because it's not Send
974    let show_coverage = options.show_coverage;
975    let run_check = options.run_check;
976
977    // First, parse the crate and extract all relevant information.
978    info!("starting to run rustc");
979
980    // Interpret the input file as a rust source file, passing it through the
981    // compiler all the way through the analysis passes. The rustdoc output is
982    // then generated from the cleaned AST of the crate. This runs all the
983    // plug/cleaning passes.
984    let crate_version = options.crate_version.clone();
985
986    let scrape_examples_options = options.scrape_examples_options.clone();
987    let bin_crate = options.bin_crate;
988
989    let output_format = options.output_format;
990    let config = core::create_config(input, options, &render_options);
991    let registered_lints = config.register_lints.is_some();
992
993    interface::run_compiler(config, |compiler| {
994        let sess = &compiler.sess;
995
996        // Register the loaded external files in the source map so they show up in depinfo.
997        // We can't load them via the source map because it gets created after we process the options.
998        for external_path in &loaded_paths {
999            let _ = sess.source_map().load_binary_file(external_path);
1000        }
1001
1002        // -W help
1003        if sess.opts.describe_lints {
1004            rustc_driver::describe_lints(sess, registered_lints);
1005            return ExitCode::SUCCESS;
1006        }
1007
1008        // --print
1009        if rustc_driver::print_crate_info(&*compiler.codegen_backend, sess, true)
1010            == rustc_driver::Compilation::Stop
1011        {
1012            return ExitCode::SUCCESS;
1013        }
1014
1015        let krate = rustc_interface::passes::parse(sess);
1016        rustc_interface::create_and_enter_global_ctxt(compiler, krate, |tcx| {
1017            if sess.dcx().has_errors().is_some() {
1018                sess.dcx().fatal("Compilation failed, aborting rustdoc");
1019            }
1020
1021            let (krate, render_opts, mut cache, expanded_macros) = match sess
1022                .time("run_global_ctxt", || {
1023                    core::run_global_ctxt(tcx, show_coverage, render_options, output_format)
1024                }) {
1025                Ok(value) => value,
1026                Err(error) => return error.report(),
1027            };
1028            info!("finished with rustc");
1029
1030            if let Some(options) = scrape_examples_options {
1031                scrape_examples::run(krate, render_opts, cache, tcx, options, bin_crate);
1032                return ExitCode::SUCCESS;
1033            }
1034
1035            if show_coverage {
1036                // if we ran coverage, bail early, we don't need to also generate docs at this point
1037                // (also we didn't load in any of the useful passes)
1038                return ExitCode::SUCCESS;
1039            }
1040
1041            cache.crate_version = crate_version;
1042
1043            if render_opts.dep_info().is_some() {
1044                rustc_interface::passes::write_dep_info(tcx);
1045            }
1046
1047            if let Some(metrics_dir) = &sess.opts.unstable_opts.metrics_dir {
1048                dump_feature_usage_metrics(tcx, metrics_dir);
1049            }
1050
1051            if run_check {
1052                // Since we're in "check" mode, no need to generate anything beyond this point.
1053                return ExitCode::SUCCESS;
1054            }
1055
1056            info!("going to format");
1057            match output_format {
1058                config::OutputFormat::Html => sess.time("render_html", || {
1059                    run_renderer(
1060                        krate,
1061                        render_opts,
1062                        cache,
1063                        tcx,
1064                        |krate, render_opts, cache, tcx| {
1065                            html::render::Context::init(
1066                                krate,
1067                                render_opts,
1068                                cache,
1069                                tcx,
1070                                expanded_macros,
1071                            )
1072                        },
1073                    )
1074                }),
1075                config::OutputFormat::IrJson => sess.time("render_json", || {
1076                    run_renderer(krate, render_opts, cache, tcx, json::JsonRenderer::init)
1077                }),
1078                // Already handled above with doctest runners or coverage early return
1079                config::OutputFormat::Doctest | config::OutputFormat::CoverageJson => {
1080                    unreachable!()
1081                }
1082            }
1083            ExitCode::SUCCESS
1084        })
1085        .0
1086    })
1087}
1088
1089fn dump_feature_usage_metrics(tcx: TyCtxt<'_>, metrics_dir: &Path) {
1090    let hash = tcx.crate_hash(LOCAL_CRATE);
1091    let crate_name = tcx.crate_name(LOCAL_CRATE);
1092    let metrics_file_name = format!("unstable_feature_usage_metrics-{crate_name}-{hash}.json");
1093    let metrics_path = metrics_dir.join(metrics_file_name);
1094    if let Err(error) = tcx.features().dump_feature_usage_metrics(metrics_path) {
1095        // FIXME(yaahc): once metrics can be enabled by default we will want "failure to emit
1096        // default metrics" to only produce a warning when metrics are enabled by default and emit
1097        // an error only when the user manually enables metrics
1098        tcx.dcx().err(format!("cannot emit feature usage metrics: {error}"));
1099    }
1100}