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, OutFileName, 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_external_trait;
31use crate::clean::{self, ItemId};
32use crate::config::{Options as RustdocOptions, OutputFormat, RenderOptions};
33use crate::formats::cache::Cache;
34use crate::passes;
35use crate::passes::Condition::*;
36use crate::passes::collect_intra_doc_links::LinkCollector;
37
38pub(crate) struct DocContext<'tcx> {
39    pub(crate) tcx: TyCtxt<'tcx>,
40    /// Used for normalization.
41    ///
42    /// Most of this logic is copied from rustc_lint::late.
43    pub(crate) param_env: ParamEnv<'tcx>,
44    /// Later on moved through `clean::Crate` into `cache`
45    pub(crate) external_traits: FxIndexMap<DefId, clean::Trait>,
46    /// Used while populating `external_traits` to ensure we don't process the same trait twice at
47    /// the same time.
48    pub(crate) active_extern_traits: DefIdSet,
49    /// The current set of parameter instantiations for expanding type aliases at the HIR level.
50    ///
51    /// Maps from the `DefId` of a lifetime or type parameter to the
52    /// generic argument it's currently instantiated to in this context.
53    // FIXME(#82852): We don't record const params since we don't visit const exprs at all and
54    // therefore wouldn't use the corresp. generic arg anyway. Add support for them.
55    pub(crate) args: DefIdMap<clean::GenericArg>,
56    pub(crate) current_type_aliases: DefIdMap<usize>,
57    /// Table synthetic type parameter for `impl Trait` in argument position -> bounds
58    pub(crate) impl_trait_bounds: FxHashMap<ImplTraitParam, Vec<clean::GenericBound>>,
59    /// Auto-trait or blanket impls processed so far, as `(self_ty, trait_def_id)`.
60    // FIXME(eddyb) make this a `ty::TraitRef<'tcx>` set.
61    pub(crate) generated_synthetics: FxHashSet<(Ty<'tcx>, DefId)>,
62    pub(crate) auto_traits: Vec<DefId>,
63    /// The options given to rustdoc that could be relevant to a pass.
64    pub(crate) render_options: RenderOptions,
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
142/// Creates a new `DiagCtxt` that can be used to emit warnings and errors.
143///
144/// If the given `error_format` is `ErrorOutputType::Json` and no `SourceMap` is given, a new one
145/// will be created for the `DiagCtxt`.
146pub(crate) fn new_dcx(
147    error_format: ErrorOutputType,
148    source_map: Option<Arc<source_map::SourceMap>>,
149    diagnostic_width: Option<usize>,
150    unstable_opts: &UnstableOptions,
151) -> rustc_errors::DiagCtxt {
152    let fallback_bundle = rustc_errors::fallback_fluent_bundle(
153        rustc_driver::DEFAULT_LOCALE_RESOURCES.to_vec(),
154        false,
155    );
156    let emitter: Box<DynEmitter> = match error_format {
157        ErrorOutputType::HumanReadable { kind, color_config } => {
158            let short = kind.short();
159            Box::new(
160                HumanEmitter::new(stderr_destination(color_config), fallback_bundle)
161                    .sm(source_map.map(|sm| sm as _))
162                    .short_message(short)
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        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    render_options: &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 = if render_options.document_private {
249        ResolveDocLinks::All
250    } else {
251        ResolveDocLinks::Exported
252    };
253    let test = scrape_examples_options.map(|opts| opts.scrape_tests).unwrap_or(false);
254    // plays with error output here!
255    let sessopts = config::Options {
256        sysroot,
257        search_paths: libs,
258        crate_types,
259        lint_opts,
260        lint_cap,
261        cg: codegen_options,
262        externs,
263        target_triple: target,
264        unstable_features: UnstableFeatures::from_environment(crate_name.as_deref()),
265        actually_rustdoc: true,
266        resolve_doc_links,
267        unstable_opts,
268        error_format,
269        diagnostic_width,
270        edition,
271        describe_lints,
272        crate_name,
273        test,
274        remap_path_prefix,
275        output_types: if let Some(file) = render_options.dep_info() {
276            OutputTypes::new(&[(
277                OutputType::DepInfo,
278                file.map(|f| OutFileName::Real(f.to_path_buf())),
279            )])
280        } else {
281            OutputTypes::new(&[])
282        },
283        ..Options::default()
284    };
285
286    rustc_interface::Config {
287        opts: sessopts,
288        crate_cfg: cfgs,
289        crate_check_cfg: check_cfgs,
290        input,
291        output_file: None,
292        output_dir: None,
293        file_loader: None,
294        locale_resources: rustc_driver::DEFAULT_LOCALE_RESOURCES.to_vec(),
295        lint_caps,
296        psess_created: None,
297        hash_untracked_state: None,
298        register_lints: Some(Box::new(crate::lint::register_lints)),
299        override_queries: Some(|_sess, providers| {
300            // We do not register late module lints, so this only runs `MissingDoc`.
301            // Most lints will require typechecking, so just don't run them.
302            providers.lint_mod = |tcx, module_def_id| late_lint_mod(tcx, module_def_id, MissingDoc);
303            // hack so that `used_trait_imports` won't try to call typeck
304            providers.used_trait_imports = |_, _| {
305                static EMPTY_SET: LazyLock<UnordSet<LocalDefId>> = LazyLock::new(UnordSet::default);
306                &EMPTY_SET
307            };
308            // In case typeck does end up being called, don't ICE in case there were name resolution errors
309            providers.typeck = move |tcx, def_id| {
310                // Closures' tables come from their outermost function,
311                // as they are part of the same "inference environment".
312                // This avoids emitting errors for the parent twice (see similar code in `typeck_with_fallback`)
313                let typeck_root_def_id = tcx.typeck_root_def_id(def_id.to_def_id()).expect_local();
314                if typeck_root_def_id != def_id {
315                    return tcx.typeck(typeck_root_def_id);
316                }
317
318                let body = tcx.hir_body_owned_by(def_id);
319                debug!("visiting body for {def_id:?}");
320                EmitIgnoredResolutionErrors::new(tcx).visit_body(body);
321                (rustc_interface::DEFAULT_QUERY_PROVIDERS.typeck)(tcx, def_id)
322            };
323        }),
324        make_codegen_backend: None,
325        registry: rustc_driver::diagnostics_registry(),
326        ice_file: None,
327        using_internal_features: &USING_INTERNAL_FEATURES,
328        expanded_args,
329    }
330}
331
332pub(crate) fn run_global_ctxt(
333    tcx: TyCtxt<'_>,
334    show_coverage: bool,
335    render_options: RenderOptions,
336    output_format: OutputFormat,
337) -> (clean::Crate, RenderOptions, Cache) {
338    // Certain queries assume that some checks were run elsewhere
339    // (see https://github.com/rust-lang/rust/pull/73566#issuecomment-656954425),
340    // so type-check everything other than function bodies in this crate before running lints.
341
342    // NOTE: this does not call `tcx.analysis()` so that we won't
343    // typeck function bodies or run the default rustc lints.
344    // (see `override_queries` in the `config`)
345
346    // NOTE: These are copy/pasted from typeck/lib.rs and should be kept in sync with those changes.
347    let _ = tcx.sess.time("wf_checking", || {
348        tcx.try_par_hir_for_each_module(|module| tcx.ensure_ok().check_mod_type_wf(module))
349    });
350
351    tcx.dcx().abort_if_errors();
352
353    tcx.sess.time("missing_docs", || rustc_lint::check_crate(tcx));
354    tcx.sess.time("check_mod_attrs", || {
355        tcx.hir_for_each_module(|module| tcx.ensure_ok().check_mod_attrs(module))
356    });
357    rustc_passes::stability::check_unused_or_stable_features(tcx);
358
359    let auto_traits =
360        tcx.all_traits().filter(|&trait_def_id| tcx.trait_is_auto(trait_def_id)).collect();
361
362    let mut ctxt = DocContext {
363        tcx,
364        param_env: ParamEnv::empty(),
365        external_traits: Default::default(),
366        active_extern_traits: Default::default(),
367        args: Default::default(),
368        current_type_aliases: Default::default(),
369        impl_trait_bounds: Default::default(),
370        generated_synthetics: Default::default(),
371        auto_traits,
372        cache: Cache::new(render_options.document_private, render_options.document_hidden),
373        inlined: FxHashSet::default(),
374        output_format,
375        render_options,
376        show_coverage,
377    };
378
379    for cnum in tcx.crates(()) {
380        crate::visit_lib::lib_embargo_visit_item(&mut ctxt, cnum.as_def_id());
381    }
382
383    // Small hack to force the Sized trait to be present.
384    //
385    // Note that in case of `#![no_core]`, the trait is not available.
386    if let Some(sized_trait_did) = ctxt.tcx.lang_items().sized_trait() {
387        let sized_trait = build_external_trait(&mut ctxt, sized_trait_did);
388        ctxt.external_traits.insert(sized_trait_did, sized_trait);
389    }
390
391    debug!("crate: {:?}", tcx.hir_crate(()));
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                lint.primary_message("no documentation found for this crate's top-level module");
406                lint.help(help);
407            },
408        );
409    }
410
411    // Process all of the crate attributes, extracting plugin metadata along
412    // with the passes which we are supposed to run.
413    for attr in krate.module.attrs.lists(sym::doc) {
414        let name = attr.name_or_empty();
415
416        if attr.is_word() && name == sym::document_private_items {
417            ctxt.render_options.document_private = true;
418        }
419    }
420
421    info!("Executing passes");
422
423    let mut visited = FxHashMap::default();
424    let mut ambiguous = FxIndexMap::default();
425
426    for p in passes::defaults(show_coverage) {
427        let run = match p.condition {
428            Always => true,
429            WhenDocumentPrivate => ctxt.render_options.document_private,
430            WhenNotDocumentPrivate => !ctxt.render_options.document_private,
431            WhenNotDocumentHidden => !ctxt.render_options.document_hidden,
432        };
433        if run {
434            debug!("running pass {}", p.pass.name);
435            if let Some(run_fn) = p.pass.run {
436                krate = tcx.sess.time(p.pass.name, || run_fn(krate, &mut ctxt));
437            } else {
438                let (k, LinkCollector { visited_links, ambiguous_links, .. }) =
439                    passes::collect_intra_doc_links::collect_intra_doc_links(krate, &mut ctxt);
440                krate = k;
441                visited = visited_links;
442                ambiguous = ambiguous_links;
443            }
444        }
445    }
446
447    tcx.sess.time("check_lint_expectations", || tcx.check_expectations(Some(sym::rustdoc)));
448
449    krate = tcx.sess.time("create_format_cache", || Cache::populate(&mut ctxt, krate));
450
451    let mut collector =
452        LinkCollector { cx: &mut ctxt, visited_links: visited, ambiguous_links: ambiguous };
453    collector.resolve_ambiguities();
454
455    tcx.dcx().abort_if_errors();
456
457    (krate, ctxt.render_options, ctxt.cache)
458}
459
460/// Due to <https://github.com/rust-lang/rust/pull/73566>,
461/// the name resolution pass may find errors that are never emitted.
462/// If typeck is called after this happens, then we'll get an ICE:
463/// 'Res::Error found but not reported'. To avoid this, emit the errors now.
464struct EmitIgnoredResolutionErrors<'tcx> {
465    tcx: TyCtxt<'tcx>,
466}
467
468impl<'tcx> EmitIgnoredResolutionErrors<'tcx> {
469    fn new(tcx: TyCtxt<'tcx>) -> Self {
470        Self { tcx }
471    }
472}
473
474impl<'tcx> Visitor<'tcx> for EmitIgnoredResolutionErrors<'tcx> {
475    type NestedFilter = nested_filter::OnlyBodies;
476
477    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
478        // We need to recurse into nested closures,
479        // since those will fallback to the parent for type checking.
480        self.tcx
481    }
482
483    fn visit_path(&mut self, path: &Path<'tcx>, _id: HirId) {
484        debug!("visiting path {path:?}");
485        if path.res == Res::Err {
486            // We have less context here than in rustc_resolve,
487            // so we can only emit the name and span.
488            // However we can give a hint that rustc_resolve will have more info.
489            let label = format!(
490                "could not resolve path `{}`",
491                path.segments
492                    .iter()
493                    .map(|segment| segment.ident.as_str())
494                    .intersperse("::")
495                    .collect::<String>()
496            );
497            rustc_errors::struct_span_code_err!(
498                self.tcx.dcx(),
499                path.span,
500                E0433,
501                "failed to resolve: {label}",
502            )
503            .with_span_label(path.span, label)
504            .with_note("this error was originally ignored because you are running `rustdoc`")
505            .with_note("try running again with `rustc` or `cargo check` and you may get a more detailed error")
506            .emit();
507        }
508        // We could have an outer resolution that succeeded,
509        // but with generic parameters that failed.
510        // Recurse into the segments so we catch those too.
511        intravisit::walk_path(self, path);
512    }
513}
514
515/// `DefId` or parameter index (`ty::ParamTy.index`) of a synthetic type parameter
516/// for `impl Trait` in argument position.
517#[derive(Clone, Copy, PartialEq, Eq, Hash)]
518pub(crate) enum ImplTraitParam {
519    DefId(DefId),
520    ParamIndex(u32),
521}
522
523impl From<DefId> for ImplTraitParam {
524    fn from(did: DefId) -> Self {
525        ImplTraitParam::DefId(did)
526    }
527}
528
529impl From<u32> for ImplTraitParam {
530    fn from(idx: u32) -> Self {
531        ImplTraitParam::ParamIndex(idx)
532    }
533}