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