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