[go: up one dir, main page]

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::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    /// The options given to rustdoc that could be relevant to a pass.
64    pub(crate) render_options: RenderOptions,
65    /// This same cache is used throughout rustdoc, including in [`crate::html::render`].
66    pub(crate) cache: Cache,
67    /// Used by [`clean::inline`] to tell if an item has already been inlined.
68    pub(crate) inlined: FxHashSet<ItemId>,
69    /// Used by `calculate_doc_coverage`.
70    pub(crate) output_format: OutputFormat,
71    /// Used by `strip_private`.
72    pub(crate) show_coverage: bool,
73}
74
75impl<'tcx> DocContext<'tcx> {
76    pub(crate) fn sess(&self) -> &'tcx Session {
77        self.tcx.sess
78    }
79
80    pub(crate) fn with_param_env<T, F: FnOnce(&mut Self) -> T>(
81        &mut self,
82        def_id: DefId,
83        f: F,
84    ) -> T {
85        let old_param_env = mem::replace(&mut self.param_env, self.tcx.param_env(def_id));
86        let ret = f(self);
87        self.param_env = old_param_env;
88        ret
89    }
90
91    pub(crate) fn typing_env(&self) -> ty::TypingEnv<'tcx> {
92        ty::TypingEnv {
93            typing_mode: ty::TypingMode::non_body_analysis(),
94            param_env: self.param_env,
95        }
96    }
97
98    /// Call the closure with the given parameters set as
99    /// the generic parameters for a type alias' RHS.
100    pub(crate) fn enter_alias<F, R>(
101        &mut self,
102        args: DefIdMap<clean::GenericArg>,
103        def_id: DefId,
104        f: F,
105    ) -> R
106    where
107        F: FnOnce(&mut Self) -> R,
108    {
109        let old_args = mem::replace(&mut self.args, args);
110        *self.current_type_aliases.entry(def_id).or_insert(0) += 1;
111        let r = f(self);
112        self.args = old_args;
113        if let Some(count) = self.current_type_aliases.get_mut(&def_id) {
114            *count -= 1;
115            if *count == 0 {
116                self.current_type_aliases.remove(&def_id);
117            }
118        }
119        r
120    }
121
122    /// Like `tcx.local_def_id_to_hir_id()`, but skips calling it on fake DefIds.
123    /// (This avoids a slice-index-out-of-bounds panic.)
124    pub(crate) fn as_local_hir_id(tcx: TyCtxt<'_>, item_id: ItemId) -> Option<HirId> {
125        match item_id {
126            ItemId::DefId(real_id) => {
127                real_id.as_local().map(|def_id| tcx.local_def_id_to_hir_id(def_id))
128            }
129            // FIXME: Can this be `Some` for `Auto` or `Blanket`?
130            _ => None,
131        }
132    }
133
134    /// Returns `true` if the JSON output format is enabled for generating the crate content.
135    ///
136    /// If another option like `--show-coverage` is enabled, it will return `false`.
137    pub(crate) fn is_json_output(&self) -> bool {
138        self.output_format.is_json() && !self.show_coverage
139    }
140}
141
142/// Creates a new `DiagCtxt` that can be used to emit warnings and errors.
143///
144/// If the given `error_format` is `ErrorOutputType::Json` and no `SourceMap` is given, a new one
145/// will be created for the `DiagCtxt`.
146pub(crate) fn new_dcx(
147    error_format: ErrorOutputType,
148    source_map: Option<Arc<source_map::SourceMap>>,
149    diagnostic_width: Option<usize>,
150    unstable_opts: &UnstableOptions,
151) -> rustc_errors::DiagCtxt {
152    let translator = rustc_driver::default_translator();
153    let emitter: Box<DynEmitter> = match error_format {
154        ErrorOutputType::HumanReadable { kind, color_config } => {
155            let short = kind.short();
156            Box::new(
157                HumanEmitter::new(stderr_destination(color_config), translator)
158                    .sm(source_map.map(|sm| sm as _))
159                    .short_message(short)
160                    .diagnostic_width(diagnostic_width)
161                    .track_diagnostics(unstable_opts.track_diagnostics)
162                    .theme(if let HumanReadableErrorType::Unicode = kind {
163                        OutputTheme::Unicode
164                    } else {
165                        OutputTheme::Ascii
166                    })
167                    .ui_testing(unstable_opts.ui_testing),
168            )
169        }
170        ErrorOutputType::Json { pretty, json_rendered, color_config } => {
171            let source_map = source_map.unwrap_or_else(|| {
172                Arc::new(source_map::SourceMap::new(source_map::FilePathMapping::empty()))
173            });
174            Box::new(
175                JsonEmitter::new(
176                    Box::new(io::BufWriter::new(io::stderr())),
177                    Some(source_map),
178                    translator,
179                    pretty,
180                    json_rendered,
181                    color_config,
182                )
183                .ui_testing(unstable_opts.ui_testing)
184                .diagnostic_width(diagnostic_width)
185                .track_diagnostics(unstable_opts.track_diagnostics)
186                .terminal_url(TerminalUrl::No),
187            )
188        }
189    };
190
191    rustc_errors::DiagCtxt::new(emitter).with_flags(unstable_opts.dcx_flags(true))
192}
193
194/// Parse, resolve, and typecheck the given crate.
195pub(crate) fn create_config(
196    input: Input,
197    RustdocOptions {
198        crate_name,
199        proc_macro_crate,
200        error_format,
201        diagnostic_width,
202        libs,
203        externs,
204        mut cfgs,
205        check_cfgs,
206        codegen_options,
207        unstable_opts,
208        target,
209        edition,
210        sysroot,
211        lint_opts,
212        describe_lints,
213        lint_cap,
214        scrape_examples_options,
215        expanded_args,
216        remap_path_prefix,
217        ..
218    }: RustdocOptions,
219    render_options: &RenderOptions,
220) -> rustc_interface::Config {
221    // Add the doc cfg into the doc build.
222    cfgs.push("doc".to_string());
223
224    // By default, rustdoc ignores all lints.
225    // Specifically unblock lints relevant to documentation or the lint machinery itself.
226    let mut lints_to_show = vec![
227        // it's unclear whether these should be part of rustdoc directly (#77364)
228        rustc_lint::builtin::MISSING_DOCS.name.to_string(),
229        rustc_lint::builtin::INVALID_DOC_ATTRIBUTES.name.to_string(),
230        // these are definitely not part of rustdoc, but we want to warn on them anyway.
231        rustc_lint::builtin::RENAMED_AND_REMOVED_LINTS.name.to_string(),
232        rustc_lint::builtin::UNKNOWN_LINTS.name.to_string(),
233        rustc_lint::builtin::UNEXPECTED_CFGS.name.to_string(),
234        // this lint is needed to support `#[expect]` attributes
235        rustc_lint::builtin::UNFULFILLED_LINT_EXPECTATIONS.name.to_string(),
236    ];
237    lints_to_show.extend(crate::lint::RUSTDOC_LINTS.iter().map(|lint| lint.name.to_string()));
238
239    let (lint_opts, lint_caps) = crate::lint::init_lints(lints_to_show, lint_opts, |lint| {
240        Some((lint.name_lower(), lint::Allow))
241    });
242
243    let crate_types =
244        if proc_macro_crate { vec![CrateType::ProcMacro] } else { vec![CrateType::Rlib] };
245    let resolve_doc_links = if render_options.document_private {
246        ResolveDocLinks::All
247    } else {
248        ResolveDocLinks::Exported
249    };
250    let test = scrape_examples_options.map(|opts| opts.scrape_tests).unwrap_or(false);
251    // plays with error output here!
252    let sessopts = config::Options {
253        sysroot,
254        search_paths: libs,
255        crate_types,
256        lint_opts,
257        lint_cap,
258        cg: codegen_options,
259        externs,
260        target_triple: target,
261        unstable_features: UnstableFeatures::from_environment(crate_name.as_deref()),
262        actually_rustdoc: true,
263        resolve_doc_links,
264        unstable_opts,
265        error_format,
266        diagnostic_width,
267        edition,
268        describe_lints,
269        crate_name,
270        test,
271        remap_path_prefix,
272        output_types: if let Some(file) = render_options.dep_info() {
273            OutputTypes::new(&[(
274                OutputType::DepInfo,
275                file.map(|f| OutFileName::Real(f.to_path_buf())),
276            )])
277        } else {
278            OutputTypes::new(&[])
279        },
280        ..Options::default()
281    };
282
283    rustc_interface::Config {
284        opts: sessopts,
285        crate_cfg: cfgs,
286        crate_check_cfg: check_cfgs,
287        input,
288        output_file: None,
289        output_dir: None,
290        file_loader: None,
291        locale_resources: rustc_driver::DEFAULT_LOCALE_RESOURCES.to_vec(),
292        lint_caps,
293        psess_created: None,
294        hash_untracked_state: None,
295        register_lints: Some(Box::new(crate::lint::register_lints)),
296        override_queries: Some(|_sess, providers| {
297            // We do not register late module lints, so this only runs `MissingDoc`.
298            // Most lints will require typechecking, so just don't run them.
299            providers.lint_mod = |tcx, module_def_id| late_lint_mod(tcx, module_def_id, MissingDoc);
300            // hack so that `used_trait_imports` won't try to call typeck
301            providers.used_trait_imports = |_, _| {
302                static EMPTY_SET: LazyLock<UnordSet<LocalDefId>> = LazyLock::new(UnordSet::default);
303                &EMPTY_SET
304            };
305            // In case typeck does end up being called, don't ICE in case there were name resolution errors
306            providers.typeck = move |tcx, def_id| {
307                // Closures' tables come from their outermost function,
308                // as they are part of the same "inference environment".
309                // This avoids emitting errors for the parent twice (see similar code in `typeck_with_fallback`)
310                let typeck_root_def_id = tcx.typeck_root_def_id(def_id.to_def_id()).expect_local();
311                if typeck_root_def_id != def_id {
312                    return tcx.typeck(typeck_root_def_id);
313                }
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.typeck)(tcx, def_id)
319            };
320        }),
321        extra_symbols: Vec::new(),
322        make_codegen_backend: None,
323        registry: rustc_driver::diagnostics_registry(),
324        ice_file: None,
325        using_internal_features: &USING_INTERNAL_FEATURES,
326        expanded_args,
327    }
328}
329
330pub(crate) fn run_global_ctxt(
331    tcx: TyCtxt<'_>,
332    show_coverage: bool,
333    render_options: RenderOptions,
334    output_format: OutputFormat,
335) -> (clean::Crate, RenderOptions, Cache) {
336    // Certain queries assume that some checks were run elsewhere
337    // (see https://github.com/rust-lang/rust/pull/73566#issuecomment-656954425),
338    // so type-check everything other than function bodies in this crate before running lints.
339
340    // NOTE: this does not call `tcx.analysis()` so that we won't
341    // typeck function bodies or run the default rustc lints.
342    // (see `override_queries` in the `config`)
343
344    // NOTE: These are copy/pasted from typeck/lib.rs and should be kept in sync with those changes.
345    let _ = tcx.sess.time("wf_checking", || tcx.ensure_ok().check_type_wf(()));
346
347    tcx.dcx().abort_if_errors();
348
349    tcx.sess.time("missing_docs", || rustc_lint::check_crate(tcx));
350    tcx.sess.time("check_mod_attrs", || {
351        tcx.hir_for_each_module(|module| tcx.ensure_ok().check_mod_attrs(module))
352    });
353    rustc_passes::stability::check_unused_or_stable_features(tcx);
354
355    let auto_traits =
356        tcx.all_traits().filter(|&trait_def_id| tcx.trait_is_auto(trait_def_id)).collect();
357
358    let mut ctxt = DocContext {
359        tcx,
360        param_env: ParamEnv::empty(),
361        external_traits: Default::default(),
362        active_extern_traits: Default::default(),
363        args: Default::default(),
364        current_type_aliases: Default::default(),
365        impl_trait_bounds: Default::default(),
366        generated_synthetics: Default::default(),
367        auto_traits,
368        cache: Cache::new(render_options.document_private, render_options.document_hidden),
369        inlined: FxHashSet::default(),
370        output_format,
371        render_options,
372        show_coverage,
373    };
374
375    for cnum in tcx.crates(()) {
376        crate::visit_lib::lib_embargo_visit_item(&mut ctxt, cnum.as_def_id());
377    }
378
379    // Small hack to force the Sized trait to be present.
380    //
381    // Note that in case of `#![no_core]`, the trait is not available.
382    if let Some(sized_trait_did) = ctxt.tcx.lang_items().sized_trait() {
383        let sized_trait = build_trait(&mut ctxt, sized_trait_did);
384        ctxt.external_traits.insert(sized_trait_did, sized_trait);
385    }
386
387    let mut krate = tcx.sess.time("clean_crate", || clean::krate(&mut ctxt));
388
389    if krate.module.doc_value().is_empty() {
390        let help = format!(
391            "The following guide may be of use:\n\
392            {}/rustdoc/how-to-write-documentation.html",
393            crate::DOC_RUST_LANG_ORG_VERSION
394        );
395        tcx.node_lint(
396            crate::lint::MISSING_CRATE_LEVEL_DOCS,
397            DocContext::as_local_hir_id(tcx, krate.module.item_id).unwrap(),
398            |lint| {
399                lint.primary_message("no documentation found for this crate's top-level module");
400                lint.help(help);
401            },
402        );
403    }
404
405    // Process all of the crate attributes, extracting plugin metadata along
406    // with the passes which we are supposed to run.
407    for attr in krate.module.attrs.lists(sym::doc) {
408        if attr.is_word() && attr.has_name(sym::document_private_items) {
409            ctxt.render_options.document_private = true;
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.render_options.document_private,
422            WhenNotDocumentPrivate => !ctxt.render_options.document_private,
423            WhenNotDocumentHidden => !ctxt.render_options.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 = tcx.sess.time("create_format_cache", || Cache::populate(&mut ctxt, krate));
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, ctxt.render_options, ctxt.cache)
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}