Skip to main content

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::{DynEmitter, HumanReadableErrorType, OutputTheme, stderr_destination};
11use rustc_errors::json::JsonEmitter;
12use rustc_feature::UnstableFeatures;
13use rustc_hir::def::Res;
14use rustc_hir::def_id::{DefId, DefIdMap, DefIdSet, LocalDefId};
15use rustc_hir::intravisit::{self, Visitor};
16use rustc_hir::{HirId, Path};
17use rustc_lint::{MissingDoc, late_lint_mod};
18use rustc_middle::hir::nested_filter;
19use rustc_middle::ty::{self, ParamEnv, Ty, TyCtxt};
20use rustc_session::config::{
21    self, CrateType, ErrorOutputType, Input, OutputType, OutputTypes, ResolveDocLinks,
22};
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_trait;
30use crate::clean::{self, ItemId};
31use crate::config::{Options as RustdocOptions, OutputFormat, RenderOptions};
32use crate::formats::cache::Cache;
33use crate::html::macro_expansion::{ExpandedCode, source_macro_expansion};
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    /// This same cache is used throughout rustdoc, including in [`crate::html::render`].
64    pub(crate) cache: Cache,
65    /// Used by [`clean::inline`] to tell if an item has already been inlined.
66    pub(crate) inlined: FxHashSet<ItemId>,
67    /// Used by `calculate_doc_coverage`.
68    pub(crate) output_format: OutputFormat,
69    /// Used by `strip_private`.
70    pub(crate) show_coverage: bool,
71}
72
73impl<'tcx> DocContext<'tcx> {
74    pub(crate) fn sess(&self) -> &'tcx Session {
75        self.tcx.sess
76    }
77
78    pub(crate) fn with_param_env<T, F: FnOnce(&mut Self) -> T>(
79        &mut self,
80        def_id: DefId,
81        f: F,
82    ) -> T {
83        let old_param_env = mem::replace(&mut self.param_env, self.tcx.param_env(def_id));
84        let ret = f(self);
85        self.param_env = old_param_env;
86        ret
87    }
88
89    pub(crate) fn typing_env(&self) -> ty::TypingEnv<'tcx> {
90        ty::TypingEnv {
91            typing_mode: ty::TypingMode::non_body_analysis(),
92            param_env: self.param_env,
93        }
94    }
95
96    /// Call the closure with the given parameters set as
97    /// the generic parameters for a type alias' RHS.
98    pub(crate) fn enter_alias<F, R>(
99        &mut self,
100        args: DefIdMap<clean::GenericArg>,
101        def_id: DefId,
102        f: F,
103    ) -> R
104    where
105        F: FnOnce(&mut Self) -> R,
106    {
107        let old_args = mem::replace(&mut self.args, args);
108        *self.current_type_aliases.entry(def_id).or_insert(0) += 1;
109        let r = f(self);
110        self.args = old_args;
111        if let Some(count) = self.current_type_aliases.get_mut(&def_id) {
112            *count -= 1;
113            if *count == 0 {
114                self.current_type_aliases.remove(&def_id);
115            }
116        }
117        r
118    }
119
120    /// Like `tcx.local_def_id_to_hir_id()`, but skips calling it on fake DefIds.
121    /// (This avoids a slice-index-out-of-bounds panic.)
122    pub(crate) fn as_local_hir_id(tcx: TyCtxt<'_>, item_id: ItemId) -> Option<HirId> {
123        match item_id {
124            ItemId::DefId(real_id) => {
125                real_id.as_local().map(|def_id| tcx.local_def_id_to_hir_id(def_id))
126            }
127            // FIXME: Can this be `Some` for `Auto` or `Blanket`?
128            _ => None,
129        }
130    }
131
132    /// Returns `true` if the JSON output format is enabled for generating the crate content.
133    ///
134    /// If another option like `--show-coverage` is enabled, it will return `false`.
135    pub(crate) fn is_json_output(&self) -> bool {
136        self.output_format.is_json() && !self.show_coverage
137    }
138
139    /// If `--document-private-items` was passed to rustdoc.
140    pub(crate) fn document_private(&self) -> bool {
141        self.cache.document_private
142    }
143
144    /// If `--document-hidden-items` was passed to rustdoc.
145    pub(crate) fn document_hidden(&self) -> bool {
146        self.cache.document_hidden
147    }
148}
149
150/// Creates a new `DiagCtxt` that can be used to emit warnings and errors.
151///
152/// If the given `error_format` is `ErrorOutputType::Json` and no `SourceMap` is given, a new one
153/// will be created for the `DiagCtxt`.
154pub(crate) fn new_dcx(
155    error_format: ErrorOutputType,
156    source_map: Option<Arc<source_map::SourceMap>>,
157    diagnostic_width: Option<usize>,
158    unstable_opts: &UnstableOptions,
159) -> rustc_errors::DiagCtxt {
160    let emitter: Box<DynEmitter> = match error_format {
161        ErrorOutputType::HumanReadable { kind, color_config } => match kind {
162            HumanReadableErrorType { short, unicode } => Box::new(
163                AnnotateSnippetEmitter::new(stderr_destination(color_config))
164                    .sm(source_map.map(|sm| sm as _))
165                    .short_message(short)
166                    .diagnostic_width(diagnostic_width)
167                    .track_diagnostics(unstable_opts.track_diagnostics)
168                    .theme(if unicode { OutputTheme::Unicode } else { OutputTheme::Ascii })
169                    .ui_testing(unstable_opts.ui_testing),
170            ),
171        },
172        ErrorOutputType::Json { pretty, json_rendered, color_config } => {
173            let source_map = source_map.unwrap_or_else(|| {
174                Arc::new(source_map::SourceMap::new(source_map::FilePathMapping::empty()))
175            });
176            Box::new(
177                JsonEmitter::new(
178                    Box::new(io::BufWriter::new(io::stderr())),
179                    Some(source_map),
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        lint_caps,
291        psess_created: None,
292        hash_untracked_state: None,
293        register_lints: Some(Box::new(crate::lint::register_lints)),
294        override_queries: Some(|_sess, providers| {
295            // We do not register late module lints, so this only runs `MissingDoc`.
296            // Most lints will require typechecking, so just don't run them.
297            providers.queries.lint_mod =
298                |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.queries.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.queries.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.queries.typeck)(tcx, def_id)
318            };
319        }),
320        extra_symbols: Vec::new(),
321        make_codegen_backend: None,
322        ice_file: None,
323        using_internal_features: &USING_INTERNAL_FEATURES,
324    }
325}
326
327pub(crate) fn run_global_ctxt(
328    tcx: TyCtxt<'_>,
329    show_coverage: bool,
330    render_options: RenderOptions,
331    output_format: OutputFormat,
332) -> (clean::Crate, RenderOptions, Cache, FxHashMap<rustc_span::BytePos, Vec<ExpandedCode>>) {
333    // Certain queries assume that some checks were run elsewhere
334    // (see https://github.com/rust-lang/rust/pull/73566#issuecomment-656954425),
335    // so type-check everything other than function bodies in this crate before running lints.
336
337    let expanded_macros = {
338        // We need for these variables to be removed to ensure that the `Crate` won't be "stolen"
339        // anymore.
340        let (_resolver, krate) = &*tcx.resolver_for_lowering().borrow();
341
342        source_macro_expansion(&krate, &render_options, output_format, tcx.sess.source_map())
343    };
344
345    // NOTE: this does not call `tcx.analysis()` so that we won't
346    // typeck function bodies or run the default rustc lints.
347    // (see `override_queries` in the `config`)
348
349    // NOTE: These are copy/pasted from typeck/lib.rs and should be kept in sync with those changes.
350    let _ = tcx.sess.time("wf_checking", || tcx.ensure_ok().check_type_wf(()));
351
352    tcx.dcx().abort_if_errors();
353
354    tcx.sess.time("missing_docs", || rustc_lint::check_crate(tcx));
355    tcx.sess.time("check_mod_attrs", || {
356        tcx.hir_for_each_module(|module| tcx.ensure_ok().check_mod_attrs(module))
357    });
358    rustc_passes::stability::check_unused_or_stable_features(tcx);
359
360    let auto_traits =
361        tcx.visible_traits().filter(|&trait_def_id| tcx.trait_is_auto(trait_def_id)).collect();
362
363    let mut ctxt = DocContext {
364        tcx,
365        param_env: ParamEnv::empty(),
366        external_traits: Default::default(),
367        active_extern_traits: Default::default(),
368        args: Default::default(),
369        current_type_aliases: Default::default(),
370        impl_trait_bounds: Default::default(),
371        generated_synthetics: Default::default(),
372        auto_traits,
373        cache: Cache::new(render_options.document_private, render_options.document_hidden),
374        inlined: FxHashSet::default(),
375        output_format,
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_trait(&mut ctxt, sized_trait_did);
388        ctxt.external_traits.insert(sized_trait_did, sized_trait);
389    }
390
391    let mut krate = tcx.sess.time("clean_crate", || clean::krate(&mut ctxt));
392
393    if krate.module.doc_value().is_empty() {
394        let help = format!(
395            "The following guide may be of use:\n\
396            {}/rustdoc/how-to-write-documentation.html",
397            crate::DOC_RUST_LANG_ORG_VERSION
398        );
399        tcx.node_lint(
400            crate::lint::MISSING_CRATE_LEVEL_DOCS,
401            DocContext::as_local_hir_id(tcx, krate.module.item_id).unwrap(),
402            |lint| {
403                if let Some(local_def_id) = krate.module.item_id.as_local_def_id() {
404                    lint.span(tcx.def_span(local_def_id));
405                }
406                lint.primary_message("no documentation found for this crate's top-level module");
407                lint.help(help);
408            },
409        );
410    }
411
412    info!("Executing passes");
413
414    let mut visited = FxHashMap::default();
415    let mut ambiguous = FxIndexMap::default();
416
417    for p in passes::defaults(show_coverage) {
418        let run = match p.condition {
419            Always => true,
420            WhenDocumentPrivate => ctxt.document_private(),
421            WhenNotDocumentPrivate => !ctxt.document_private(),
422            WhenNotDocumentHidden => !ctxt.document_hidden(),
423        };
424        if run {
425            debug!("running pass {}", p.pass.name);
426            if let Some(run_fn) = p.pass.run {
427                krate = tcx.sess.time(p.pass.name, || run_fn(krate, &mut ctxt));
428            } else {
429                let (k, LinkCollector { visited_links, ambiguous_links, .. }) =
430                    passes::collect_intra_doc_links::collect_intra_doc_links(krate, &mut ctxt);
431                krate = k;
432                visited = visited_links;
433                ambiguous = ambiguous_links;
434            }
435        }
436    }
437
438    tcx.sess.time("check_lint_expectations", || tcx.check_expectations(Some(sym::rustdoc)));
439
440    krate =
441        tcx.sess.time("create_format_cache", || Cache::populate(&mut ctxt, krate, &render_options));
442
443    let mut collector =
444        LinkCollector { cx: &mut ctxt, visited_links: visited, ambiguous_links: ambiguous };
445    collector.resolve_ambiguities();
446
447    tcx.dcx().abort_if_errors();
448
449    (krate, render_options, ctxt.cache, expanded_macros)
450}
451
452/// Due to <https://github.com/rust-lang/rust/pull/73566>,
453/// the name resolution pass may find errors that are never emitted.
454/// If typeck is called after this happens, then we'll get an ICE:
455/// 'Res::Error found but not reported'. To avoid this, emit the errors now.
456struct EmitIgnoredResolutionErrors<'tcx> {
457    tcx: TyCtxt<'tcx>,
458}
459
460impl<'tcx> EmitIgnoredResolutionErrors<'tcx> {
461    fn new(tcx: TyCtxt<'tcx>) -> Self {
462        Self { tcx }
463    }
464}
465
466impl<'tcx> Visitor<'tcx> for EmitIgnoredResolutionErrors<'tcx> {
467    type NestedFilter = nested_filter::OnlyBodies;
468
469    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
470        // We need to recurse into nested closures,
471        // since those will fallback to the parent for type checking.
472        self.tcx
473    }
474
475    fn visit_path(&mut self, path: &Path<'tcx>, _id: HirId) {
476        debug!("visiting path {path:?}");
477        if path.res == Res::Err {
478            // We have less context here than in rustc_resolve,
479            // so we can only emit the name and span.
480            // However we can give a hint that rustc_resolve will have more info.
481            let label = format!(
482                "could not resolve path `{}`",
483                path.segments
484                    .iter()
485                    .map(|segment| segment.ident.as_str())
486                    .intersperse("::")
487                    .collect::<String>()
488            );
489            rustc_errors::struct_span_code_err!(
490                self.tcx.dcx(),
491                path.span,
492                E0433,
493                "failed to resolve: {label}",
494            )
495            .with_span_label(path.span, label)
496            .with_note("this error was originally ignored because you are running `rustdoc`")
497            .with_note("try running again with `rustc` or `cargo check` and you may get a more detailed error")
498            .emit();
499        }
500        // We could have an outer resolution that succeeded,
501        // but with generic parameters that failed.
502        // Recurse into the segments so we catch those too.
503        intravisit::walk_path(self, path);
504    }
505}
506
507/// `DefId` or parameter index (`ty::ParamTy.index`) of a synthetic type parameter
508/// for `impl Trait` in argument position.
509#[derive(Clone, Copy, PartialEq, Eq, Hash)]
510pub(crate) enum ImplTraitParam {
511    DefId(DefId),
512    ParamIndex(u32),
513}
514
515impl From<DefId> for ImplTraitParam {
516    fn from(did: DefId) -> Self {
517        ImplTraitParam::DefId(did)
518    }
519}
520
521impl From<u32> for ImplTraitParam {
522    fn from(idx: u32) -> Self {
523        ImplTraitParam::ParamIndex(idx)
524    }
525}