]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/core.rs
Rollup merge of #100609 - chenyukang:fix-100527, r=davidtwco
[rust.git] / src / librustdoc / core.rs
1 use rustc_ast::NodeId;
2 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
3 use rustc_data_structures::sync::{self, Lrc};
4 use rustc_errors::emitter::{Emitter, EmitterWriter};
5 use rustc_errors::json::JsonEmitter;
6 use rustc_feature::UnstableFeatures;
7 use rustc_hir::def::{Namespace, Res};
8 use rustc_hir::def_id::{DefId, DefIdMap, LocalDefId};
9 use rustc_hir::intravisit::{self, Visitor};
10 use rustc_hir::{HirId, Path, TraitCandidate};
11 use rustc_interface::interface;
12 use rustc_middle::hir::nested_filter;
13 use rustc_middle::middle::privacy::AccessLevels;
14 use rustc_middle::ty::{ParamEnv, Ty, TyCtxt};
15 use rustc_resolve as resolve;
16 use rustc_session::config::{self, CrateType, ErrorOutputType};
17 use rustc_session::lint;
18 use rustc_session::DiagnosticOutput;
19 use rustc_session::Session;
20 use rustc_span::symbol::sym;
21 use rustc_span::{source_map, Span, Symbol};
22
23 use std::cell::RefCell;
24 use std::mem;
25 use std::rc::Rc;
26 use std::sync::LazyLock;
27
28 use crate::clean::inline::build_external_trait;
29 use crate::clean::{self, ItemId, TraitWithExtraInfo};
30 use crate::config::{Options as RustdocOptions, OutputFormat, RenderOptions};
31 use crate::formats::cache::Cache;
32 use crate::passes::collect_intra_doc_links::PreprocessedMarkdownLink;
33 use crate::passes::{self, Condition::*};
34
35 pub(crate) use rustc_session::config::{Input, Options, UnstableOptions};
36
37 pub(crate) struct ResolverCaches {
38     pub(crate) markdown_links: Option<FxHashMap<String, Vec<PreprocessedMarkdownLink>>>,
39     pub(crate) doc_link_resolutions: FxHashMap<(Symbol, Namespace, DefId), Option<Res<NodeId>>>,
40     /// Traits in scope for a given module.
41     /// See `collect_intra_doc_links::traits_implemented_by` for more details.
42     pub(crate) traits_in_scope: DefIdMap<Vec<TraitCandidate>>,
43     pub(crate) all_traits: Option<Vec<DefId>>,
44     pub(crate) all_trait_impls: Option<Vec<DefId>>,
45     pub(crate) all_macro_rules: FxHashMap<Symbol, Res<NodeId>>,
46 }
47
48 pub(crate) struct DocContext<'tcx> {
49     pub(crate) tcx: TyCtxt<'tcx>,
50     /// Name resolver. Used for intra-doc links.
51     ///
52     /// The `Rc<RefCell<...>>` wrapping is needed because that is what's returned by
53     /// [`rustc_interface::Queries::expansion()`].
54     // FIXME: see if we can get rid of this RefCell somehow
55     pub(crate) resolver: Rc<RefCell<interface::BoxedResolver>>,
56     pub(crate) resolver_caches: ResolverCaches,
57     /// Used for normalization.
58     ///
59     /// Most of this logic is copied from rustc_lint::late.
60     pub(crate) param_env: ParamEnv<'tcx>,
61     /// Later on moved through `clean::Crate` into `cache`
62     pub(crate) external_traits: Rc<RefCell<FxHashMap<DefId, clean::TraitWithExtraInfo>>>,
63     /// Used while populating `external_traits` to ensure we don't process the same trait twice at
64     /// the same time.
65     pub(crate) active_extern_traits: FxHashSet<DefId>,
66     // The current set of parameter substitutions,
67     // for expanding type aliases at the HIR level:
68     /// Table `DefId` of type, lifetime, or const parameter -> substituted type, lifetime, or const
69     pub(crate) substs: FxHashMap<DefId, clean::SubstParam>,
70     /// Table synthetic type parameter for `impl Trait` in argument position -> bounds
71     pub(crate) impl_trait_bounds: FxHashMap<ImplTraitParam, Vec<clean::GenericBound>>,
72     /// Auto-trait or blanket impls processed so far, as `(self_ty, trait_def_id)`.
73     // FIXME(eddyb) make this a `ty::TraitRef<'tcx>` set.
74     pub(crate) generated_synthetics: FxHashSet<(Ty<'tcx>, DefId)>,
75     pub(crate) auto_traits: Vec<DefId>,
76     /// The options given to rustdoc that could be relevant to a pass.
77     pub(crate) render_options: RenderOptions,
78     /// This same cache is used throughout rustdoc, including in [`crate::html::render`].
79     pub(crate) cache: Cache,
80     /// Used by [`clean::inline`] to tell if an item has already been inlined.
81     pub(crate) inlined: FxHashSet<ItemId>,
82     /// Used by `calculate_doc_coverage`.
83     pub(crate) output_format: OutputFormat,
84     /// Used by `strip_private`.
85     pub(crate) show_coverage: bool,
86 }
87
88 impl<'tcx> DocContext<'tcx> {
89     pub(crate) fn sess(&self) -> &'tcx Session {
90         self.tcx.sess
91     }
92
93     pub(crate) fn with_param_env<T, F: FnOnce(&mut Self) -> T>(
94         &mut self,
95         def_id: DefId,
96         f: F,
97     ) -> T {
98         let old_param_env = mem::replace(&mut self.param_env, self.tcx.param_env(def_id));
99         let ret = f(self);
100         self.param_env = old_param_env;
101         ret
102     }
103
104     pub(crate) fn enter_resolver<F, R>(&self, f: F) -> R
105     where
106         F: FnOnce(&mut resolve::Resolver<'_>) -> R,
107     {
108         self.resolver.borrow_mut().access(f)
109     }
110
111     /// Call the closure with the given parameters set as
112     /// the substitutions for a type alias' RHS.
113     pub(crate) fn enter_alias<F, R>(
114         &mut self,
115         substs: FxHashMap<DefId, clean::SubstParam>,
116         f: F,
117     ) -> R
118     where
119         F: FnOnce(&mut Self) -> R,
120     {
121         let old_substs = mem::replace(&mut self.substs, substs);
122         let r = f(self);
123         self.substs = old_substs;
124         r
125     }
126
127     /// Like `hir().local_def_id_to_hir_id()`, but skips calling it on fake DefIds.
128     /// (This avoids a slice-index-out-of-bounds panic.)
129     pub(crate) fn as_local_hir_id(tcx: TyCtxt<'_>, item_id: ItemId) -> Option<HirId> {
130         match item_id {
131             ItemId::DefId(real_id) => {
132                 real_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
133             }
134             // FIXME: Can this be `Some` for `Auto` or `Blanket`?
135             _ => None,
136         }
137     }
138
139     pub(crate) fn with_all_traits(&mut self, f: impl FnOnce(&mut Self, &[DefId])) {
140         let all_traits = self.resolver_caches.all_traits.take();
141         f(self, all_traits.as_ref().expect("`all_traits` are already borrowed"));
142         self.resolver_caches.all_traits = all_traits;
143     }
144
145     pub(crate) fn with_all_trait_impls(&mut self, f: impl FnOnce(&mut Self, &[DefId])) {
146         let all_trait_impls = self.resolver_caches.all_trait_impls.take();
147         f(self, all_trait_impls.as_ref().expect("`all_trait_impls` are already borrowed"));
148         self.resolver_caches.all_trait_impls = all_trait_impls;
149     }
150 }
151
152 /// Creates a new diagnostic `Handler` that can be used to emit warnings and errors.
153 ///
154 /// If the given `error_format` is `ErrorOutputType::Json` and no `SourceMap` is given, a new one
155 /// will be created for the handler.
156 pub(crate) fn new_handler(
157     error_format: ErrorOutputType,
158     source_map: Option<Lrc<source_map::SourceMap>>,
159     diagnostic_width: Option<usize>,
160     unstable_opts: &UnstableOptions,
161 ) -> rustc_errors::Handler {
162     let fallback_bundle =
163         rustc_errors::fallback_fluent_bundle(rustc_errors::DEFAULT_LOCALE_RESOURCES, false);
164     let emitter: Box<dyn Emitter + sync::Send> = match error_format {
165         ErrorOutputType::HumanReadable(kind) => {
166             let (short, color_config) = kind.unzip();
167             Box::new(
168                 EmitterWriter::stderr(
169                     color_config,
170                     source_map.map(|sm| sm as _),
171                     None,
172                     fallback_bundle,
173                     short,
174                     unstable_opts.teach,
175                     diagnostic_width,
176                     false,
177                 )
178                 .ui_testing(unstable_opts.ui_testing),
179             )
180         }
181         ErrorOutputType::Json { pretty, json_rendered } => {
182             let source_map = source_map.unwrap_or_else(|| {
183                 Lrc::new(source_map::SourceMap::new(source_map::FilePathMapping::empty()))
184             });
185             Box::new(
186                 JsonEmitter::stderr(
187                     None,
188                     source_map,
189                     None,
190                     fallback_bundle,
191                     pretty,
192                     json_rendered,
193                     diagnostic_width,
194                     false,
195                 )
196                 .ui_testing(unstable_opts.ui_testing),
197             )
198         }
199     };
200
201     rustc_errors::Handler::with_emitter_and_flags(
202         emitter,
203         unstable_opts.diagnostic_handler_flags(true),
204     )
205 }
206
207 /// Parse, resolve, and typecheck the given crate.
208 pub(crate) fn create_config(
209     RustdocOptions {
210         input,
211         crate_name,
212         proc_macro_crate,
213         error_format,
214         diagnostic_width,
215         libs,
216         externs,
217         mut cfgs,
218         check_cfgs,
219         codegen_options,
220         unstable_opts,
221         target,
222         edition,
223         maybe_sysroot,
224         lint_opts,
225         describe_lints,
226         lint_cap,
227         scrape_examples_options,
228         ..
229     }: RustdocOptions,
230 ) -> rustc_interface::Config {
231     // Add the doc cfg into the doc build.
232     cfgs.push("doc".to_string());
233
234     let cpath = Some(input.clone());
235     let input = Input::File(input);
236
237     // By default, rustdoc ignores all lints.
238     // Specifically unblock lints relevant to documentation or the lint machinery itself.
239     let mut lints_to_show = vec![
240         // it's unclear whether these should be part of rustdoc directly (#77364)
241         rustc_lint::builtin::MISSING_DOCS.name.to_string(),
242         rustc_lint::builtin::INVALID_DOC_ATTRIBUTES.name.to_string(),
243         // these are definitely not part of rustdoc, but we want to warn on them anyway.
244         rustc_lint::builtin::RENAMED_AND_REMOVED_LINTS.name.to_string(),
245         rustc_lint::builtin::UNKNOWN_LINTS.name.to_string(),
246         rustc_lint::builtin::UNEXPECTED_CFGS.name.to_string(),
247         // this lint is needed to support `#[expect]` attributes
248         rustc_lint::builtin::UNFULFILLED_LINT_EXPECTATIONS.name.to_string(),
249     ];
250     lints_to_show.extend(crate::lint::RUSTDOC_LINTS.iter().map(|lint| lint.name.to_string()));
251
252     let (lint_opts, lint_caps) = crate::lint::init_lints(lints_to_show, lint_opts, |lint| {
253         Some((lint.name_lower(), lint::Allow))
254     });
255
256     let crate_types =
257         if proc_macro_crate { vec![CrateType::ProcMacro] } else { vec![CrateType::Rlib] };
258     let test = scrape_examples_options.map(|opts| opts.scrape_tests).unwrap_or(false);
259     // plays with error output here!
260     let sessopts = config::Options {
261         maybe_sysroot,
262         search_paths: libs,
263         crate_types,
264         lint_opts,
265         lint_cap,
266         cg: codegen_options,
267         externs,
268         target_triple: target,
269         unstable_features: UnstableFeatures::from_environment(crate_name.as_deref()),
270         actually_rustdoc: true,
271         unstable_opts,
272         error_format,
273         diagnostic_width,
274         edition,
275         describe_lints,
276         crate_name,
277         test,
278         ..Options::default()
279     };
280
281     interface::Config {
282         opts: sessopts,
283         crate_cfg: interface::parse_cfgspecs(cfgs),
284         crate_check_cfg: interface::parse_check_cfg(check_cfgs),
285         input,
286         input_path: cpath,
287         output_file: None,
288         output_dir: None,
289         file_loader: None,
290         diagnostic_output: DiagnosticOutput::Default,
291         lint_caps,
292         parse_sess_created: None,
293         register_lints: Some(Box::new(crate::lint::register_lints)),
294         override_queries: Some(|_sess, providers, _external_providers| {
295             // Most lints will require typechecking, so just don't run them.
296             providers.lint_mod = |_, _| {};
297             // Prevent `rustc_typeck::check_crate` from calling `typeck` on all bodies.
298             providers.typeck_item_bodies = |_, _| {};
299             // hack so that `used_trait_imports` won't try to call typeck
300             providers.used_trait_imports = |_, _| {
301                 static EMPTY_SET: LazyLock<FxHashSet<LocalDefId>> =
302                     LazyLock::new(FxHashSet::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 hir = tcx.hir();
316                 let body = hir.body(hir.body_owned_by(def_id));
317                 debug!("visiting body for {:?}", def_id);
318                 EmitIgnoredResolutionErrors::new(tcx).visit_body(body);
319                 (rustc_interface::DEFAULT_QUERY_PROVIDERS.typeck)(tcx, def_id)
320             };
321         }),
322         make_codegen_backend: None,
323         registry: rustc_driver::diagnostics_registry(),
324     }
325 }
326
327 pub(crate) fn run_global_ctxt(
328     tcx: TyCtxt<'_>,
329     resolver: Rc<RefCell<interface::BoxedResolver>>,
330     resolver_caches: ResolverCaches,
331     show_coverage: bool,
332     render_options: RenderOptions,
333     output_format: OutputFormat,
334 ) -> (clean::Crate, RenderOptions, Cache) {
335     // Certain queries assume that some checks were run elsewhere
336     // (see https://github.com/rust-lang/rust/pull/73566#issuecomment-656954425),
337     // so type-check everything other than function bodies in this crate before running lints.
338
339     // NOTE: this does not call `tcx.analysis()` so that we won't
340     // typeck function bodies or run the default rustc lints.
341     // (see `override_queries` in the `config`)
342
343     // HACK(jynelson) this calls an _extremely_ limited subset of `typeck`
344     // and might break if queries change their assumptions in the future.
345
346     // NOTE: This is copy/pasted from typeck/lib.rs and should be kept in sync with those changes.
347     tcx.sess.time("item_types_checking", || {
348         tcx.hir().for_each_module(|module| tcx.ensure().check_mod_item_types(module))
349     });
350     tcx.sess.abort_if_errors();
351     tcx.sess.time("missing_docs", || {
352         rustc_lint::check_crate(tcx, rustc_lint::builtin::MissingDoc::new);
353     });
354     tcx.sess.time("check_mod_attrs", || {
355         tcx.hir().for_each_module(|module| tcx.ensure().check_mod_attrs(module))
356     });
357     rustc_passes::stability::check_unused_or_stable_features(tcx);
358
359     let auto_traits = resolver_caches
360         .all_traits
361         .as_ref()
362         .expect("`all_traits` are already borrowed")
363         .iter()
364         .copied()
365         .filter(|&trait_def_id| tcx.trait_is_auto(trait_def_id))
366         .collect();
367     let access_levels = AccessLevels {
368         map: tcx.privacy_access_levels(()).map.iter().map(|(k, v)| (k.to_def_id(), *v)).collect(),
369     };
370
371     let mut ctxt = DocContext {
372         tcx,
373         resolver,
374         resolver_caches,
375         param_env: ParamEnv::empty(),
376         external_traits: Default::default(),
377         active_extern_traits: Default::default(),
378         substs: Default::default(),
379         impl_trait_bounds: Default::default(),
380         generated_synthetics: Default::default(),
381         auto_traits,
382         cache: Cache::new(access_levels, render_options.document_private),
383         inlined: FxHashSet::default(),
384         output_format,
385         render_options,
386         show_coverage,
387     };
388
389     // Small hack to force the Sized trait to be present.
390     //
391     // Note that in case of `#![no_core]`, the trait is not available.
392     if let Some(sized_trait_did) = ctxt.tcx.lang_items().sized_trait() {
393         let sized_trait = build_external_trait(&mut ctxt, sized_trait_did);
394         ctxt.external_traits
395             .borrow_mut()
396             .insert(sized_trait_did, TraitWithExtraInfo { trait_: sized_trait, is_notable: false });
397     }
398
399     debug!("crate: {:?}", tcx.hir().krate());
400
401     let mut krate = tcx.sess.time("clean_crate", || clean::krate(&mut ctxt));
402
403     if krate.module.doc_value().map(|d| d.is_empty()).unwrap_or(true) {
404         let help = format!(
405             "The following guide may be of use:\n\
406             {}/rustdoc/how-to-write-documentation.html",
407             crate::DOC_RUST_LANG_ORG_CHANNEL
408         );
409         tcx.struct_lint_node(
410             crate::lint::MISSING_CRATE_LEVEL_DOCS,
411             DocContext::as_local_hir_id(tcx, krate.module.item_id).unwrap(),
412             |lint| {
413                 let mut diag =
414                     lint.build("no documentation found for this crate's top-level module");
415                 diag.help(&help);
416                 diag.emit();
417             },
418         );
419     }
420
421     fn report_deprecated_attr(name: &str, diag: &rustc_errors::Handler, sp: Span) {
422         let mut msg =
423             diag.struct_span_warn(sp, &format!("the `#![doc({})]` attribute is deprecated", name));
424         msg.note(
425             "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
426             for more information",
427         );
428
429         if name == "no_default_passes" {
430             msg.help("`#![doc(no_default_passes)]` no longer functions; you may want to use `#![doc(document_private_items)]`");
431         } else if name.starts_with("passes") {
432             msg.help("`#![doc(passes = \"...\")]` no longer functions; you may want to use `#![doc(document_private_items)]`");
433         } else if name.starts_with("plugins") {
434             msg.warn("`#![doc(plugins = \"...\")]` no longer functions; see CVE-2018-1000622 <https://nvd.nist.gov/vuln/detail/CVE-2018-1000622>");
435         }
436
437         msg.emit();
438     }
439
440     // Process all of the crate attributes, extracting plugin metadata along
441     // with the passes which we are supposed to run.
442     for attr in krate.module.attrs.lists(sym::doc) {
443         let diag = ctxt.sess().diagnostic();
444
445         let name = attr.name_or_empty();
446         // `plugins = "..."`, `no_default_passes`, and `passes = "..."` have no effect
447         if attr.is_word() && name == sym::no_default_passes {
448             report_deprecated_attr("no_default_passes", diag, attr.span());
449         } else if attr.value_str().is_some() {
450             match name {
451                 sym::passes => {
452                     report_deprecated_attr("passes = \"...\"", diag, attr.span());
453                 }
454                 sym::plugins => {
455                     report_deprecated_attr("plugins = \"...\"", diag, attr.span());
456                 }
457                 _ => (),
458             }
459         }
460
461         if attr.is_word() && name == sym::document_private_items {
462             ctxt.render_options.document_private = true;
463         }
464     }
465
466     info!("Executing passes");
467
468     for p in passes::defaults(show_coverage) {
469         let run = match p.condition {
470             Always => true,
471             WhenDocumentPrivate => ctxt.render_options.document_private,
472             WhenNotDocumentPrivate => !ctxt.render_options.document_private,
473             WhenNotDocumentHidden => !ctxt.render_options.document_hidden,
474         };
475         if run {
476             debug!("running pass {}", p.pass.name);
477             krate = tcx.sess.time(p.pass.name, || (p.pass.run)(krate, &mut ctxt));
478         }
479     }
480
481     tcx.sess.time("check_lint_expectations", || tcx.check_expectations(Some(sym::rustdoc)));
482
483     if tcx.sess.diagnostic().has_errors_or_lint_errors().is_some() {
484         rustc_errors::FatalError.raise();
485     }
486
487     krate = tcx.sess.time("create_format_cache", || Cache::populate(&mut ctxt, krate));
488
489     (krate, ctxt.render_options, ctxt.cache)
490 }
491
492 /// Due to <https://github.com/rust-lang/rust/pull/73566>,
493 /// the name resolution pass may find errors that are never emitted.
494 /// If typeck is called after this happens, then we'll get an ICE:
495 /// 'Res::Error found but not reported'. To avoid this, emit the errors now.
496 struct EmitIgnoredResolutionErrors<'tcx> {
497     tcx: TyCtxt<'tcx>,
498 }
499
500 impl<'tcx> EmitIgnoredResolutionErrors<'tcx> {
501     fn new(tcx: TyCtxt<'tcx>) -> Self {
502         Self { tcx }
503     }
504 }
505
506 impl<'tcx> Visitor<'tcx> for EmitIgnoredResolutionErrors<'tcx> {
507     type NestedFilter = nested_filter::OnlyBodies;
508
509     fn nested_visit_map(&mut self) -> Self::Map {
510         // We need to recurse into nested closures,
511         // since those will fallback to the parent for type checking.
512         self.tcx.hir()
513     }
514
515     fn visit_path(&mut self, path: &'tcx Path<'_>, _id: HirId) {
516         debug!("visiting path {:?}", path);
517         if path.res == Res::Err {
518             // We have less context here than in rustc_resolve,
519             // so we can only emit the name and span.
520             // However we can give a hint that rustc_resolve will have more info.
521             let label = format!(
522                 "could not resolve path `{}`",
523                 path.segments
524                     .iter()
525                     .map(|segment| segment.ident.as_str())
526                     .intersperse("::")
527                     .collect::<String>()
528             );
529             let mut err = rustc_errors::struct_span_err!(
530                 self.tcx.sess,
531                 path.span,
532                 E0433,
533                 "failed to resolve: {}",
534                 label
535             );
536             err.span_label(path.span, label);
537             err.note("this error was originally ignored because you are running `rustdoc`");
538             err.note("try running again with `rustc` or `cargo check` and you may get a more detailed error");
539             err.emit();
540         }
541         // We could have an outer resolution that succeeded,
542         // but with generic parameters that failed.
543         // Recurse into the segments so we catch those too.
544         intravisit::walk_path(self, path);
545     }
546 }
547
548 /// `DefId` or parameter index (`ty::ParamTy.index`) of a synthetic type parameter
549 /// for `impl Trait` in argument position.
550 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
551 pub(crate) enum ImplTraitParam {
552     DefId(DefId),
553     ParamIndex(u32),
554 }
555
556 impl From<DefId> for ImplTraitParam {
557     fn from(did: DefId) -> Self {
558         ImplTraitParam::DefId(did)
559     }
560 }
561
562 impl From<u32> for ImplTraitParam {
563     fn from(idx: u32) -> Self {
564         ImplTraitParam::ParamIndex(idx)
565     }
566 }