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