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