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