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