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