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