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