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