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