rustdoc/
core.rs

1use std::sync::{Arc, LazyLock};
2use std::{io, mem};
3
4use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
5use rustc_data_structures::unord::UnordSet;
6use rustc_driver::USING_INTERNAL_FEATURES;
7use rustc_errors::TerminalUrl;
8use rustc_errors::codes::*;
9use rustc_errors::emitter::{
10    DynEmitter, HumanEmitter, HumanReadableErrorType, OutputTheme, stderr_destination,
11};
12use rustc_errors::json::JsonEmitter;
13use rustc_feature::UnstableFeatures;
14use rustc_hir::def::Res;
15use rustc_hir::def_id::{DefId, DefIdMap, DefIdSet, LocalDefId};
16use rustc_hir::intravisit::{self, Visitor};
17use rustc_hir::{HirId, Path};
18use rustc_lint::{MissingDoc, late_lint_mod};
19use rustc_middle::hir::nested_filter;
20use rustc_middle::ty::{self, ParamEnv, Ty, TyCtxt};
21use rustc_session::config::{
22    self, CrateType, ErrorOutputType, Input, OutputType, OutputTypes, ResolveDocLinks,
23};
24pub(crate) use rustc_session::config::{Options, UnstableOptions};
25use rustc_session::{Session, lint};
26use rustc_span::source_map;
27use rustc_span::symbol::sym;
28use tracing::{debug, info};
29
30use crate::clean::inline::build_trait;
31use crate::clean::{self, ItemId};
32use crate::config::{Options as RustdocOptions, OutputFormat, RenderOptions};
33use crate::formats::cache::Cache;
34use crate::html::macro_expansion::{ExpandedCode, source_macro_expansion};
35use crate::passes;
36use crate::passes::Condition::*;
37use crate::passes::collect_intra_doc_links::LinkCollector;
38
39pub(crate) struct DocContext<'tcx> {
40    pub(crate) tcx: TyCtxt<'tcx>,
41    /// Used for normalization.
42    ///
43    /// Most of this logic is copied from rustc_lint::late.
44    pub(crate) param_env: ParamEnv<'tcx>,
45    /// Later on moved through `clean::Crate` into `cache`
46    pub(crate) external_traits: FxIndexMap<DefId, clean::Trait>,
47    /// Used while populating `external_traits` to ensure we don't process the same trait twice at
48    /// the same time.
49    pub(crate) active_extern_traits: DefIdSet,
50    /// The current set of parameter instantiations for expanding type aliases at the HIR level.
51    ///
52    /// Maps from the `DefId` of a lifetime or type parameter to the
53    /// generic argument it's currently instantiated to in this context.
54    // FIXME(#82852): We don't record const params since we don't visit const exprs at all and
55    // therefore wouldn't use the corresp. generic arg anyway. Add support for them.
56    pub(crate) args: DefIdMap<clean::GenericArg>,
57    pub(crate) current_type_aliases: DefIdMap<usize>,
58    /// Table synthetic type parameter for `impl Trait` in argument position -> bounds
59    pub(crate) impl_trait_bounds: FxHashMap<ImplTraitParam, Vec<clean::GenericBound>>,
60    /// Auto-trait or blanket impls processed so far, as `(self_ty, trait_def_id)`.
61    // FIXME(eddyb) make this a `ty::TraitRef<'tcx>` set.
62    pub(crate) generated_synthetics: FxHashSet<(Ty<'tcx>, DefId)>,
63    pub(crate) auto_traits: Vec<DefId>,
64    /// The options given to rustdoc that could be relevant to a pass.
65    pub(crate) render_options: RenderOptions,
66    /// This same cache is used throughout rustdoc, including in [`crate::html::render`].
67    pub(crate) cache: Cache,
68    /// Used by [`clean::inline`] to tell if an item has already been inlined.
69    pub(crate) inlined: FxHashSet<ItemId>,
70    /// Used by `calculate_doc_coverage`.
71    pub(crate) output_format: OutputFormat,
72    /// Used by `strip_private`.
73    pub(crate) show_coverage: bool,
74}
75
76impl<'tcx> DocContext<'tcx> {
77    pub(crate) fn sess(&self) -> &'tcx Session {
78        self.tcx.sess
79    }
80
81    pub(crate) fn with_param_env<T, F: FnOnce(&mut Self) -> T>(
82        &mut self,
83        def_id: DefId,
84        f: F,
85    ) -> T {
86        let old_param_env = mem::replace(&mut self.param_env, self.tcx.param_env(def_id));
87        let ret = f(self);
88        self.param_env = old_param_env;
89        ret
90    }
91
92    pub(crate) fn typing_env(&self) -> ty::TypingEnv<'tcx> {
93        ty::TypingEnv {
94            typing_mode: ty::TypingMode::non_body_analysis(),
95            param_env: self.param_env,
96        }
97    }
98
99    /// Call the closure with the given parameters set as
100    /// the generic parameters for a type alias' RHS.
101    pub(crate) fn enter_alias<F, R>(
102        &mut self,
103        args: DefIdMap<clean::GenericArg>,
104        def_id: DefId,
105        f: F,
106    ) -> R
107    where
108        F: FnOnce(&mut Self) -> R,
109    {
110        let old_args = mem::replace(&mut self.args, args);
111        *self.current_type_aliases.entry(def_id).or_insert(0) += 1;
112        let r = f(self);
113        self.args = old_args;
114        if let Some(count) = self.current_type_aliases.get_mut(&def_id) {
115            *count -= 1;
116            if *count == 0 {
117                self.current_type_aliases.remove(&def_id);
118            }
119        }
120        r
121    }
122
123    /// Like `tcx.local_def_id_to_hir_id()`, but skips calling it on fake DefIds.
124    /// (This avoids a slice-index-out-of-bounds panic.)
125    pub(crate) fn as_local_hir_id(tcx: TyCtxt<'_>, item_id: ItemId) -> Option<HirId> {
126        match item_id {
127            ItemId::DefId(real_id) => {
128                real_id.as_local().map(|def_id| tcx.local_def_id_to_hir_id(def_id))
129            }
130            // FIXME: Can this be `Some` for `Auto` or `Blanket`?
131            _ => None,
132        }
133    }
134
135    /// Returns `true` if the JSON output format is enabled for generating the crate content.
136    ///
137    /// If another option like `--show-coverage` is enabled, it will return `false`.
138    pub(crate) fn is_json_output(&self) -> bool {
139        self.output_format.is_json() && !self.show_coverage
140    }
141}
142
143/// Creates a new `DiagCtxt` that can be used to emit warnings and errors.
144///
145/// If the given `error_format` is `ErrorOutputType::Json` and no `SourceMap` is given, a new one
146/// will be created for the `DiagCtxt`.
147pub(crate) fn new_dcx(
148    error_format: ErrorOutputType,
149    source_map: Option<Arc<source_map::SourceMap>>,
150    diagnostic_width: Option<usize>,
151    unstable_opts: &UnstableOptions,
152) -> rustc_errors::DiagCtxt {
153    let translator = rustc_driver::default_translator();
154    let emitter: Box<DynEmitter> = match error_format {
155        ErrorOutputType::HumanReadable { kind, color_config } => {
156            let short = kind.short();
157            Box::new(
158                HumanEmitter::new(stderr_destination(color_config), translator)
159                    .sm(source_map.map(|sm| sm as _))
160                    .short_message(short)
161                    .diagnostic_width(diagnostic_width)
162                    .track_diagnostics(unstable_opts.track_diagnostics)
163                    .theme(if let HumanReadableErrorType::Unicode = kind {
164                        OutputTheme::Unicode
165                    } else {
166                        OutputTheme::Ascii
167                    })
168                    .ui_testing(unstable_opts.ui_testing),
169            )
170        }
171        ErrorOutputType::Json { pretty, json_rendered, color_config } => {
172            let source_map = source_map.unwrap_or_else(|| {
173                Arc::new(source_map::SourceMap::new(source_map::FilePathMapping::empty()))
174            });
175            Box::new(
176                JsonEmitter::new(
177                    Box::new(io::BufWriter::new(io::stderr())),
178                    Some(source_map),
179                    translator,
180                    pretty,
181                    json_rendered,
182                    color_config,
183                )
184                .ui_testing(unstable_opts.ui_testing)
185                .diagnostic_width(diagnostic_width)
186                .track_diagnostics(unstable_opts.track_diagnostics)
187                .terminal_url(TerminalUrl::No),
188            )
189        }
190    };
191
192    rustc_errors::DiagCtxt::new(emitter).with_flags(unstable_opts.dcx_flags(true))
193}
194
195/// Parse, resolve, and typecheck the given crate.
196pub(crate) fn create_config(
197    input: Input,
198    RustdocOptions {
199        crate_name,
200        proc_macro_crate,
201        error_format,
202        diagnostic_width,
203        libs,
204        externs,
205        mut cfgs,
206        check_cfgs,
207        codegen_options,
208        unstable_opts,
209        target,
210        edition,
211        sysroot,
212        lint_opts,
213        describe_lints,
214        lint_cap,
215        scrape_examples_options,
216        remap_path_prefix,
217        target_modifiers,
218        ..
219    }: RustdocOptions,
220    render_options: &RenderOptions,
221) -> rustc_interface::Config {
222    // Add the doc cfg into the doc build.
223    cfgs.push("doc".to_string());
224
225    // By default, rustdoc ignores all lints.
226    // Specifically unblock lints relevant to documentation or the lint machinery itself.
227    let mut lints_to_show = vec![
228        // it's unclear whether these should be part of rustdoc directly (#77364)
229        rustc_lint::builtin::MISSING_DOCS.name.to_string(),
230        rustc_lint::builtin::INVALID_DOC_ATTRIBUTES.name.to_string(),
231        // these are definitely not part of rustdoc, but we want to warn on them anyway.
232        rustc_lint::builtin::RENAMED_AND_REMOVED_LINTS.name.to_string(),
233        rustc_lint::builtin::UNKNOWN_LINTS.name.to_string(),
234        rustc_lint::builtin::UNEXPECTED_CFGS.name.to_string(),
235        // this lint is needed to support `#[expect]` attributes
236        rustc_lint::builtin::UNFULFILLED_LINT_EXPECTATIONS.name.to_string(),
237    ];
238    lints_to_show.extend(crate::lint::RUSTDOC_LINTS.iter().map(|lint| lint.name.to_string()));
239
240    let (lint_opts, lint_caps) = crate::lint::init_lints(lints_to_show, lint_opts, |lint| {
241        Some((lint.name_lower(), lint::Allow))
242    });
243
244    let crate_types =
245        if proc_macro_crate { vec![CrateType::ProcMacro] } else { vec![CrateType::Rlib] };
246    let resolve_doc_links = if render_options.document_private {
247        ResolveDocLinks::All
248    } else {
249        ResolveDocLinks::Exported
250    };
251    let test = scrape_examples_options.map(|opts| opts.scrape_tests).unwrap_or(false);
252    // plays with error output here!
253    let sessopts = config::Options {
254        sysroot,
255        search_paths: libs,
256        crate_types,
257        lint_opts,
258        lint_cap,
259        cg: codegen_options,
260        externs,
261        target_triple: target,
262        unstable_features: UnstableFeatures::from_environment(crate_name.as_deref()),
263        actually_rustdoc: true,
264        resolve_doc_links,
265        unstable_opts,
266        error_format,
267        diagnostic_width,
268        edition,
269        describe_lints,
270        crate_name,
271        test,
272        remap_path_prefix,
273        output_types: if let Some(file) = render_options.dep_info() {
274            OutputTypes::new(&[(OutputType::DepInfo, file.cloned())])
275        } else {
276            OutputTypes::new(&[])
277        },
278        target_modifiers,
279        ..Options::default()
280    };
281
282    rustc_interface::Config {
283        opts: sessopts,
284        crate_cfg: cfgs,
285        crate_check_cfg: check_cfgs,
286        input,
287        output_file: None,
288        output_dir: None,
289        file_loader: None,
290        locale_resources: rustc_driver::DEFAULT_LOCALE_RESOURCES.to_vec(),
291        lint_caps,
292        psess_created: None,
293        hash_untracked_state: None,
294        register_lints: Some(Box::new(crate::lint::register_lints)),
295        override_queries: Some(|_sess, providers| {
296            // We do not register late module lints, so this only runs `MissingDoc`.
297            // Most lints will require typechecking, so just don't run them.
298            providers.lint_mod = |tcx, module_def_id| late_lint_mod(tcx, module_def_id, MissingDoc);
299            // hack so that `used_trait_imports` won't try to call typeck
300            providers.used_trait_imports = |_, _| {
301                static EMPTY_SET: LazyLock<UnordSet<LocalDefId>> = LazyLock::new(UnordSet::default);
302                &EMPTY_SET
303            };
304            // In case typeck does end up being called, don't ICE in case there were name resolution errors
305            providers.typeck = move |tcx, def_id| {
306                // Closures' tables come from their outermost function,
307                // as they are part of the same "inference environment".
308                // This avoids emitting errors for the parent twice (see similar code in `typeck_with_fallback`)
309                let typeck_root_def_id = tcx.typeck_root_def_id(def_id.to_def_id()).expect_local();
310                if typeck_root_def_id != def_id {
311                    return tcx.typeck(typeck_root_def_id);
312                }
313
314                let body = tcx.hir_body_owned_by(def_id);
315                debug!("visiting body for {def_id:?}");
316                EmitIgnoredResolutionErrors::new(tcx).visit_body(body);
317                (rustc_interface::DEFAULT_QUERY_PROVIDERS.typeck)(tcx, def_id)
318            };
319        }),
320        extra_symbols: Vec::new(),
321        make_codegen_backend: None,
322        registry: rustc_driver::diagnostics_registry(),
323        ice_file: None,
324        using_internal_features: &USING_INTERNAL_FEATURES,
325    }
326}
327
328pub(crate) fn run_global_ctxt(
329    tcx: TyCtxt<'_>,
330    show_coverage: bool,
331    render_options: RenderOptions,
332    output_format: OutputFormat,
333) -> (clean::Crate, RenderOptions, Cache, FxHashMap<rustc_span::BytePos, Vec<ExpandedCode>>) {
334    // Certain queries assume that some checks were run elsewhere
335    // (see https://github.com/rust-lang/rust/pull/73566#issuecomment-656954425),
336    // so type-check everything other than function bodies in this crate before running lints.
337
338    let expanded_macros = {
339        // We need for these variables to be removed to ensure that the `Crate` won't be "stolen"
340        // anymore.
341        let (_resolver, krate) = &*tcx.resolver_for_lowering().borrow();
342
343        source_macro_expansion(&krate, &render_options, output_format, tcx.sess.source_map())
344    };
345
346    // NOTE: this does not call `tcx.analysis()` so that we won't
347    // typeck function bodies or run the default rustc lints.
348    // (see `override_queries` in the `config`)
349
350    // NOTE: These are copy/pasted from typeck/lib.rs and should be kept in sync with those changes.
351    let _ = tcx.sess.time("wf_checking", || tcx.ensure_ok().check_type_wf(()));
352
353    tcx.dcx().abort_if_errors();
354
355    tcx.sess.time("missing_docs", || rustc_lint::check_crate(tcx));
356    tcx.sess.time("check_mod_attrs", || {
357        tcx.hir_for_each_module(|module| tcx.ensure_ok().check_mod_attrs(module))
358    });
359    rustc_passes::stability::check_unused_or_stable_features(tcx);
360
361    let auto_traits =
362        tcx.visible_traits().filter(|&trait_def_id| tcx.trait_is_auto(trait_def_id)).collect();
363
364    let mut ctxt = DocContext {
365        tcx,
366        param_env: ParamEnv::empty(),
367        external_traits: Default::default(),
368        active_extern_traits: Default::default(),
369        args: Default::default(),
370        current_type_aliases: Default::default(),
371        impl_trait_bounds: Default::default(),
372        generated_synthetics: Default::default(),
373        auto_traits,
374        cache: Cache::new(render_options.document_private, render_options.document_hidden),
375        inlined: FxHashSet::default(),
376        output_format,
377        render_options,
378        show_coverage,
379    };
380
381    for cnum in tcx.crates(()) {
382        crate::visit_lib::lib_embargo_visit_item(&mut ctxt, cnum.as_def_id());
383    }
384
385    // Small hack to force the Sized trait to be present.
386    //
387    // Note that in case of `#![no_core]`, the trait is not available.
388    if let Some(sized_trait_did) = ctxt.tcx.lang_items().sized_trait() {
389        let sized_trait = build_trait(&mut ctxt, sized_trait_did);
390        ctxt.external_traits.insert(sized_trait_did, sized_trait);
391    }
392
393    let mut krate = tcx.sess.time("clean_crate", || clean::krate(&mut ctxt));
394
395    if krate.module.doc_value().is_empty() {
396        let help = format!(
397            "The following guide may be of use:\n\
398            {}/rustdoc/how-to-write-documentation.html",
399            crate::DOC_RUST_LANG_ORG_VERSION
400        );
401        tcx.node_lint(
402            crate::lint::MISSING_CRATE_LEVEL_DOCS,
403            DocContext::as_local_hir_id(tcx, krate.module.item_id).unwrap(),
404            |lint| {
405                if let Some(local_def_id) = krate.module.item_id.as_local_def_id() {
406                    lint.span(tcx.def_span(local_def_id));
407                }
408                lint.primary_message("no documentation found for this crate's top-level module");
409                lint.help(help);
410            },
411        );
412    }
413
414    // Process all of the crate attributes, extracting plugin metadata along
415    // with the passes which we are supposed to run.
416    for attr in krate.module.attrs.lists(sym::doc) {
417        if attr.is_word() && attr.has_name(sym::document_private_items) {
418            ctxt.render_options.document_private = true;
419        }
420    }
421
422    info!("Executing passes");
423
424    let mut visited = FxHashMap::default();
425    let mut ambiguous = FxIndexMap::default();
426
427    for p in passes::defaults(show_coverage) {
428        let run = match p.condition {
429            Always => true,
430            WhenDocumentPrivate => ctxt.render_options.document_private,
431            WhenNotDocumentPrivate => !ctxt.render_options.document_private,
432            WhenNotDocumentHidden => !ctxt.render_options.document_hidden,
433        };
434        if run {
435            debug!("running pass {}", p.pass.name);
436            if let Some(run_fn) = p.pass.run {
437                krate = tcx.sess.time(p.pass.name, || run_fn(krate, &mut ctxt));
438            } else {
439                let (k, LinkCollector { visited_links, ambiguous_links, .. }) =
440                    passes::collect_intra_doc_links::collect_intra_doc_links(krate, &mut ctxt);
441                krate = k;
442                visited = visited_links;
443                ambiguous = ambiguous_links;
444            }
445        }
446    }
447
448    tcx.sess.time("check_lint_expectations", || tcx.check_expectations(Some(sym::rustdoc)));
449
450    krate = tcx.sess.time("create_format_cache", || Cache::populate(&mut ctxt, krate));
451
452    let mut collector =
453        LinkCollector { cx: &mut ctxt, visited_links: visited, ambiguous_links: ambiguous };
454    collector.resolve_ambiguities();
455
456    tcx.dcx().abort_if_errors();
457
458    (krate, ctxt.render_options, ctxt.cache, expanded_macros)
459}
460
461/// Due to <https://github.com/rust-lang/rust/pull/73566>,
462/// the name resolution pass may find errors that are never emitted.
463/// If typeck is called after this happens, then we'll get an ICE:
464/// 'Res::Error found but not reported'. To avoid this, emit the errors now.
465struct EmitIgnoredResolutionErrors<'tcx> {
466    tcx: TyCtxt<'tcx>,
467}
468
469impl<'tcx> EmitIgnoredResolutionErrors<'tcx> {
470    fn new(tcx: TyCtxt<'tcx>) -> Self {
471        Self { tcx }
472    }
473}
474
475impl<'tcx> Visitor<'tcx> for EmitIgnoredResolutionErrors<'tcx> {
476    type NestedFilter = nested_filter::OnlyBodies;
477
478    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
479        // We need to recurse into nested closures,
480        // since those will fallback to the parent for type checking.
481        self.tcx
482    }
483
484    fn visit_path(&mut self, path: &Path<'tcx>, _id: HirId) {
485        debug!("visiting path {path:?}");
486        if path.res == Res::Err {
487            // We have less context here than in rustc_resolve,
488            // so we can only emit the name and span.
489            // However we can give a hint that rustc_resolve will have more info.
490            let label = format!(
491                "could not resolve path `{}`",
492                path.segments
493                    .iter()
494                    .map(|segment| segment.ident.as_str())
495                    .intersperse("::")
496                    .collect::<String>()
497            );
498            rustc_errors::struct_span_code_err!(
499                self.tcx.dcx(),
500                path.span,
501                E0433,
502                "failed to resolve: {label}",
503            )
504            .with_span_label(path.span, label)
505            .with_note("this error was originally ignored because you are running `rustdoc`")
506            .with_note("try running again with `rustc` or `cargo check` and you may get a more detailed error")
507            .emit();
508        }
509        // We could have an outer resolution that succeeded,
510        // but with generic parameters that failed.
511        // Recurse into the segments so we catch those too.
512        intravisit::walk_path(self, path);
513    }
514}
515
516/// `DefId` or parameter index (`ty::ParamTy.index`) of a synthetic type parameter
517/// for `impl Trait` in argument position.
518#[derive(Clone, Copy, PartialEq, Eq, Hash)]
519pub(crate) enum ImplTraitParam {
520    DefId(DefId),
521    ParamIndex(u32),
522}
523
524impl From<DefId> for ImplTraitParam {
525    fn from(did: DefId) -> Self {
526        ImplTraitParam::DefId(did)
527    }
528}
529
530impl From<u32> for ImplTraitParam {
531    fn from(idx: u32) -> Self {
532        ImplTraitParam::ParamIndex(idx)
533    }
534}