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