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