]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/core.rs
152094684adf42d169d04b0fb440bcc07033f958
[rust.git] / src / librustdoc / core.rs
1 use rustc_ast as ast;
2 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
3 use rustc_data_structures::sync::{self, Lrc};
4 use rustc_driver::abort_on_err;
5 use rustc_errors::emitter::{Emitter, EmitterWriter};
6 use rustc_errors::json::JsonEmitter;
7 use rustc_feature::UnstableFeatures;
8 use rustc_hir::def::{Namespace::TypeNS, Res};
9 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
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;
27
28 use std::cell::RefCell;
29 use std::collections::hash_map::Entry;
30 use std::mem;
31 use std::rc::Rc;
32
33 use crate::clean;
34 use crate::clean::inline::build_external_trait;
35 use crate::clean::{AttributesExt, TraitWithExtraInfo, MAX_DEF_IDX};
36 use crate::config::{Options as RustdocOptions, OutputFormat, RenderOptions};
37 use crate::formats::cache::Cache;
38 use crate::passes::{self, Condition::*, ConditionalPass};
39
40 crate use rustc_session::config::{DebuggingOptions, Input, Options};
41
42 crate struct DocContext<'tcx> {
43     crate tcx: TyCtxt<'tcx>,
44     /// Name resolver. Used for intra-doc links.
45     ///
46     /// The `Rc<RefCell<...>>` wrapping is needed because that is what's returned by
47     /// [`Queries::expansion()`].
48     // FIXME: see if we can get rid of this RefCell somehow
49     crate resolver: Rc<RefCell<interface::BoxedResolver>>,
50     /// Used for normalization.
51     ///
52     /// Most of this logic is copied from rustc_lint::late.
53     crate param_env: ParamEnv<'tcx>,
54     /// Later on moved through `clean::Crate` into `cache`
55     crate external_traits: Rc<RefCell<FxHashMap<DefId, clean::TraitWithExtraInfo>>>,
56     /// Used while populating `external_traits` to ensure we don't process the same trait twice at
57     /// the same time.
58     crate active_extern_traits: FxHashSet<DefId>,
59     // The current set of type and lifetime substitutions,
60     // for expanding type aliases at the HIR level:
61     /// Table `DefId` of type parameter -> substituted type
62     crate ty_substs: FxHashMap<DefId, clean::Type>,
63     /// Table `DefId` of lifetime parameter -> substituted lifetime
64     crate lt_substs: FxHashMap<DefId, clean::Lifetime>,
65     /// Table `DefId` of const parameter -> substituted const
66     crate ct_substs: FxHashMap<DefId, clean::Constant>,
67     /// Table synthetic type parameter for `impl Trait` in argument position -> bounds
68     crate impl_trait_bounds: FxHashMap<ImplTraitParam, Vec<clean::GenericBound>>,
69     crate fake_def_ids: FxHashMap<CrateNum, DefIndex>,
70     /// Auto-trait or blanket impls processed so far, as `(self_ty, trait_def_id)`.
71     // FIXME(eddyb) make this a `ty::TraitRef<'tcx>` set.
72     crate generated_synthetics: FxHashSet<(Ty<'tcx>, DefId)>,
73     crate auto_traits: Vec<DefId>,
74     /// The options given to rustdoc that could be relevant to a pass.
75     crate render_options: RenderOptions,
76     /// The traits in scope for a given module.
77     ///
78     /// See `collect_intra_doc_links::traits_implemented_by` for more details.
79     /// `map<module, set<trait>>`
80     crate module_trait_cache: FxHashMap<DefId, FxHashSet<DefId>>,
81     /// This same cache is used throughout rustdoc, including in [`crate::html::render`].
82     crate cache: Cache,
83     /// Used by [`clean::inline`] to tell if an item has already been inlined.
84     crate inlined: FxHashSet<DefId>,
85     /// Used by `calculate_doc_coverage`.
86     crate output_format: OutputFormat,
87 }
88
89 impl<'tcx> DocContext<'tcx> {
90     crate fn sess(&self) -> &'tcx Session {
91         &self.tcx.sess
92     }
93
94     crate fn with_param_env<T, F: FnOnce(&mut Self) -> T>(&mut self, def_id: DefId, f: F) -> T {
95         let old_param_env = mem::replace(&mut self.param_env, self.tcx.param_env(def_id));
96         let ret = f(self);
97         self.param_env = old_param_env;
98         ret
99     }
100
101     crate fn enter_resolver<F, R>(&self, f: F) -> R
102     where
103         F: FnOnce(&mut resolve::Resolver<'_>) -> R,
104     {
105         self.resolver.borrow_mut().access(f)
106     }
107
108     /// Call the closure with the given parameters set as
109     /// the substitutions for a type alias' RHS.
110     crate fn enter_alias<F, R>(
111         &mut self,
112         ty_substs: FxHashMap<DefId, clean::Type>,
113         lt_substs: FxHashMap<DefId, clean::Lifetime>,
114         ct_substs: FxHashMap<DefId, clean::Constant>,
115         f: F,
116     ) -> R
117     where
118         F: FnOnce(&mut Self) -> R,
119     {
120         let (old_tys, old_lts, old_cts) = (
121             mem::replace(&mut self.ty_substs, ty_substs),
122             mem::replace(&mut self.lt_substs, lt_substs),
123             mem::replace(&mut self.ct_substs, ct_substs),
124         );
125         let r = f(self);
126         self.ty_substs = old_tys;
127         self.lt_substs = old_lts;
128         self.ct_substs = old_cts;
129         r
130     }
131
132     /// Create a new "fake" [`DefId`].
133     ///
134     /// This is an ugly hack, but it's the simplest way to handle synthetic impls without greatly
135     /// refactoring either rustdoc or [`rustc_middle`]. In particular, allowing new [`DefId`]s
136     /// to be registered after the AST is constructed would require storing the [`DefId`] mapping
137     /// in a [`RefCell`], decreasing the performance for normal compilation for very little gain.
138     ///
139     /// Instead, we construct "fake" [`DefId`]s, which start immediately after the last `DefId`.
140     /// In the [`Debug`] impl for [`clean::Item`], we explicitly check for fake `DefId`s,
141     /// as we'll end up with a panic if we use the `DefId` `Debug` impl for fake `DefId`s.
142     ///
143     /// [`RefCell`]: std::cell::RefCell
144     /// [`Debug`]: std::fmt::Debug
145     /// [`clean::Item`]: crate::clean::types::Item
146     crate fn next_def_id(&mut self, crate_num: CrateNum) -> DefId {
147         let def_index = match self.fake_def_ids.entry(crate_num) {
148             Entry::Vacant(e) => {
149                 let num_def_idx = {
150                     let num_def_idx = if crate_num == LOCAL_CRATE {
151                         self.tcx.hir().definitions().def_path_table().num_def_ids()
152                     } else {
153                         self.resolver.borrow_mut().access(|r| r.cstore().num_def_ids(crate_num))
154                     };
155
156                     DefIndex::from_usize(num_def_idx)
157                 };
158
159                 MAX_DEF_IDX.with(|m| {
160                     m.borrow_mut().insert(crate_num, num_def_idx);
161                 });
162                 e.insert(num_def_idx)
163             }
164             Entry::Occupied(e) => e.into_mut(),
165         };
166         *def_index = *def_index + 1;
167
168         DefId { krate: crate_num, index: *def_index }
169     }
170
171     /// Like `hir().local_def_id_to_hir_id()`, but skips calling it on fake DefIds.
172     /// (This avoids a slice-index-out-of-bounds panic.)
173     crate fn as_local_hir_id(tcx: TyCtxt<'_>, def_id: DefId) -> Option<HirId> {
174         if MAX_DEF_IDX.with(|m| {
175             m.borrow().get(&def_id.krate).map(|&idx| idx <= def_id.index).unwrap_or(false)
176         }) {
177             None
178         } else {
179             def_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
180         }
181     }
182 }
183
184 /// Creates a new diagnostic `Handler` that can be used to emit warnings and errors.
185 ///
186 /// If the given `error_format` is `ErrorOutputType::Json` and no `SourceMap` is given, a new one
187 /// will be created for the handler.
188 crate fn new_handler(
189     error_format: ErrorOutputType,
190     source_map: Option<Lrc<source_map::SourceMap>>,
191     debugging_opts: &DebuggingOptions,
192 ) -> rustc_errors::Handler {
193     let emitter: Box<dyn Emitter + sync::Send> = match error_format {
194         ErrorOutputType::HumanReadable(kind) => {
195             let (short, color_config) = kind.unzip();
196             Box::new(
197                 EmitterWriter::stderr(
198                     color_config,
199                     source_map.map(|sm| sm as _),
200                     short,
201                     debugging_opts.teach,
202                     debugging_opts.terminal_width,
203                     false,
204                 )
205                 .ui_testing(debugging_opts.ui_testing),
206             )
207         }
208         ErrorOutputType::Json { pretty, json_rendered } => {
209             let source_map = source_map.unwrap_or_else(|| {
210                 Lrc::new(source_map::SourceMap::new(source_map::FilePathMapping::empty()))
211             });
212             Box::new(
213                 JsonEmitter::stderr(
214                     None,
215                     source_map,
216                     pretty,
217                     json_rendered,
218                     debugging_opts.terminal_width,
219                     false,
220                 )
221                 .ui_testing(debugging_opts.ui_testing),
222             )
223         }
224     };
225
226     rustc_errors::Handler::with_emitter_and_flags(
227         emitter,
228         debugging_opts.diagnostic_handler_flags(true),
229     )
230 }
231
232 /// Parse, resolve, and typecheck the given crate.
233 crate fn create_config(
234     RustdocOptions {
235         input,
236         crate_name,
237         proc_macro_crate,
238         error_format,
239         libs,
240         externs,
241         mut cfgs,
242         codegen_options,
243         debugging_opts,
244         target,
245         edition,
246         maybe_sysroot,
247         lint_opts,
248         describe_lints,
249         lint_cap,
250         display_warnings,
251         ..
252     }: RustdocOptions,
253 ) -> rustc_interface::Config {
254     // Add the doc cfg into the doc build.
255     cfgs.push("doc".to_string());
256
257     let cpath = Some(input.clone());
258     let input = Input::File(input);
259
260     // By default, rustdoc ignores all lints.
261     // Specifically unblock lints relevant to documentation or the lint machinery itself.
262     let mut lints_to_show = vec![
263         // it's unclear whether this should be part of rustdoc directly (#77364)
264         rustc_lint::builtin::MISSING_DOCS.name.to_string(),
265         // these are definitely not part of rustdoc, but we want to warn on them anyway.
266         rustc_lint::builtin::RENAMED_AND_REMOVED_LINTS.name.to_string(),
267         rustc_lint::builtin::UNKNOWN_LINTS.name.to_string(),
268     ];
269     lints_to_show.extend(crate::lint::RUSTDOC_LINTS.iter().map(|lint| lint.name.to_string()));
270
271     let (lint_opts, lint_caps) = crate::lint::init_lints(lints_to_show, lint_opts, |lint| {
272         // FIXME: why is this necessary?
273         if lint.name == crate::lint::BROKEN_INTRA_DOC_LINKS.name
274             || lint.name == crate::lint::INVALID_CODEBLOCK_ATTRIBUTES.name
275         {
276             None
277         } else {
278             Some((lint.name_lower(), lint::Allow))
279         }
280     });
281
282     let crate_types =
283         if proc_macro_crate { vec![CrateType::ProcMacro] } else { vec![CrateType::Rlib] };
284     // plays with error output here!
285     let sessopts = config::Options {
286         maybe_sysroot,
287         search_paths: libs,
288         crate_types,
289         lint_opts: if !display_warnings { lint_opts } else { vec![] },
290         lint_cap,
291         cg: codegen_options,
292         externs,
293         target_triple: target,
294         unstable_features: UnstableFeatures::from_environment(crate_name.as_deref()),
295         actually_rustdoc: true,
296         debugging_opts,
297         error_format,
298         edition,
299         describe_lints,
300         crate_name,
301         ..Options::default()
302     };
303
304     interface::Config {
305         opts: sessopts,
306         crate_cfg: interface::parse_cfgspecs(cfgs),
307         input,
308         input_path: cpath,
309         output_file: None,
310         output_dir: None,
311         file_loader: None,
312         diagnostic_output: DiagnosticOutput::Default,
313         stderr: None,
314         lint_caps,
315         parse_sess_created: None,
316         register_lints: Some(box crate::lint::register_lints),
317         override_queries: Some(|_sess, providers, _external_providers| {
318             // Most lints will require typechecking, so just don't run them.
319             providers.lint_mod = |_, _| {};
320             // Prevent `rustc_typeck::check_crate` from calling `typeck` on all bodies.
321             providers.typeck_item_bodies = |_, _| {};
322             // hack so that `used_trait_imports` won't try to call typeck
323             providers.used_trait_imports = |_, _| {
324                 lazy_static! {
325                     static ref EMPTY_SET: FxHashSet<LocalDefId> = FxHashSet::default();
326                 }
327                 &EMPTY_SET
328             };
329             // In case typeck does end up being called, don't ICE in case there were name resolution errors
330             providers.typeck = move |tcx, def_id| {
331                 // Closures' tables come from their outermost function,
332                 // as they are part of the same "inference environment".
333                 // This avoids emitting errors for the parent twice (see similar code in `typeck_with_fallback`)
334                 let outer_def_id = tcx.closure_base_def_id(def_id.to_def_id()).expect_local();
335                 if outer_def_id != def_id {
336                     return tcx.typeck(outer_def_id);
337                 }
338
339                 let hir = tcx.hir();
340                 let body = hir.body(hir.body_owned_by(hir.local_def_id_to_hir_id(def_id)));
341                 debug!("visiting body for {:?}", def_id);
342                 EmitIgnoredResolutionErrors::new(tcx).visit_body(body);
343                 (rustc_interface::DEFAULT_QUERY_PROVIDERS.typeck)(tcx, def_id)
344             };
345         }),
346         make_codegen_backend: None,
347         registry: rustc_driver::diagnostics_registry(),
348     }
349 }
350
351 crate fn create_resolver<'a>(
352     queries: &Queries<'a>,
353     sess: &Session,
354 ) -> Rc<RefCell<interface::BoxedResolver>> {
355     let parts = abort_on_err(queries.expansion(), sess).peek();
356     let (krate, resolver, _) = &*parts;
357     let resolver = resolver.borrow().clone();
358
359     // Letting the resolver escape at the end of the function leads to inconsistencies between the
360     // crates the TyCtxt sees and the resolver sees (because the resolver could load more crates
361     // after escaping). Hopefully `IntraLinkCrateLoader` gets all the crates we need ...
362     struct IntraLinkCrateLoader {
363         current_mod: DefId,
364         resolver: Rc<RefCell<interface::BoxedResolver>>,
365     }
366     impl ast::visit::Visitor<'_> for IntraLinkCrateLoader {
367         fn visit_attribute(&mut self, attr: &ast::Attribute) {
368             use crate::html::markdown::{markdown_links, MarkdownLink};
369             use crate::passes::collect_intra_doc_links::Disambiguator;
370
371             if let Some(doc) = attr.doc_str() {
372                 for MarkdownLink { link, .. } in markdown_links(&doc.as_str()) {
373                     // FIXME: this misses a *lot* of the preprocessing done in collect_intra_doc_links
374                     // I think most of it shouldn't be necessary since we only need the crate prefix?
375                     let path_str = match Disambiguator::from_str(&link) {
376                         Ok(x) => x.map_or(link.as_str(), |(_, p)| p),
377                         Err(_) => continue,
378                     };
379                     self.resolver.borrow_mut().access(|resolver| {
380                         let _ = resolver.resolve_str_path_error(
381                             attr.span,
382                             path_str,
383                             TypeNS,
384                             self.current_mod,
385                         );
386                     });
387                 }
388             }
389             ast::visit::walk_attribute(self, attr);
390         }
391
392         fn visit_item(&mut self, item: &ast::Item) {
393             use rustc_ast_lowering::ResolverAstLowering;
394
395             if let ast::ItemKind::Mod(..) = item.kind {
396                 let new_mod =
397                     self.resolver.borrow_mut().access(|resolver| resolver.local_def_id(item.id));
398                 let old_mod = mem::replace(&mut self.current_mod, new_mod.to_def_id());
399                 ast::visit::walk_item(self, item);
400                 self.current_mod = old_mod;
401             } else {
402                 ast::visit::walk_item(self, item);
403             }
404         }
405     }
406     let crate_id = LocalDefId { local_def_index: CRATE_DEF_INDEX }.to_def_id();
407     let mut loader = IntraLinkCrateLoader { current_mod: crate_id, resolver };
408     ast::visit::walk_crate(&mut loader, krate);
409
410     loader.resolver
411 }
412
413 crate fn run_global_ctxt(
414     tcx: TyCtxt<'_>,
415     resolver: Rc<RefCell<interface::BoxedResolver>>,
416     mut default_passes: passes::DefaultPassOption,
417     manual_passes: Vec<String>,
418     render_options: RenderOptions,
419     output_format: OutputFormat,
420 ) -> (clean::Crate, RenderOptions, Cache) {
421     // Certain queries assume that some checks were run elsewhere
422     // (see https://github.com/rust-lang/rust/pull/73566#issuecomment-656954425),
423     // so type-check everything other than function bodies in this crate before running lints.
424
425     // NOTE: this does not call `tcx.analysis()` so that we won't
426     // typeck function bodies or run the default rustc lints.
427     // (see `override_queries` in the `config`)
428
429     // HACK(jynelson) this calls an _extremely_ limited subset of `typeck`
430     // and might break if queries change their assumptions in the future.
431
432     // NOTE: This is copy/pasted from typeck/lib.rs and should be kept in sync with those changes.
433     tcx.sess.time("item_types_checking", || {
434         for &module in tcx.hir().krate().modules.keys() {
435             tcx.ensure().check_mod_item_types(module);
436         }
437     });
438     tcx.sess.abort_if_errors();
439     tcx.sess.time("missing_docs", || {
440         rustc_lint::check_crate(tcx, rustc_lint::builtin::MissingDoc::new);
441     });
442     tcx.sess.time("check_mod_attrs", || {
443         for &module in tcx.hir().krate().modules.keys() {
444             tcx.ensure().check_mod_attrs(module);
445         }
446     });
447     rustc_passes::stability::check_unused_or_stable_features(tcx);
448
449     let access_levels = tcx.privacy_access_levels(LOCAL_CRATE);
450     // Convert from a HirId set to a DefId set since we don't always have easy access
451     // to the map from defid -> hirid
452     let access_levels = AccessLevels {
453         map: access_levels
454             .map
455             .iter()
456             .map(|(&k, &v)| (tcx.hir().local_def_id(k).to_def_id(), v))
457             .collect(),
458     };
459
460     let mut ctxt = DocContext {
461         tcx,
462         resolver,
463         param_env: ParamEnv::empty(),
464         external_traits: Default::default(),
465         active_extern_traits: Default::default(),
466         ty_substs: Default::default(),
467         lt_substs: Default::default(),
468         ct_substs: Default::default(),
469         impl_trait_bounds: Default::default(),
470         fake_def_ids: Default::default(),
471         generated_synthetics: Default::default(),
472         auto_traits: tcx
473             .all_traits(LOCAL_CRATE)
474             .iter()
475             .cloned()
476             .filter(|trait_def_id| tcx.trait_is_auto(*trait_def_id))
477             .collect(),
478         module_trait_cache: FxHashMap::default(),
479         cache: Cache::new(access_levels, render_options.document_private),
480         inlined: FxHashSet::default(),
481         output_format,
482         render_options,
483     };
484
485     // Small hack to force the Sized trait to be present.
486     //
487     // Note that in case of `#![no_core]`, the trait is not available.
488     if let Some(sized_trait_did) = ctxt.tcx.lang_items().sized_trait() {
489         let mut sized_trait = build_external_trait(&mut ctxt, sized_trait_did);
490         sized_trait.is_auto = true;
491         ctxt.external_traits
492             .borrow_mut()
493             .insert(sized_trait_did, TraitWithExtraInfo { trait_: sized_trait, is_notable: false });
494     }
495
496     debug!("crate: {:?}", tcx.hir().krate());
497
498     let mut krate = tcx.sess.time("clean_crate", || clean::krate(&mut ctxt));
499
500     if krate.module.doc_value().map(|d| d.is_empty()).unwrap_or(true) {
501         let help = "The following guide may be of use:\n\
502                 https://doc.rust-lang.org/nightly/rustdoc/how-to-write-documentation.html";
503         tcx.struct_lint_node(
504             crate::lint::MISSING_CRATE_LEVEL_DOCS,
505             DocContext::as_local_hir_id(tcx, krate.module.def_id).unwrap(),
506             |lint| {
507                 let mut diag =
508                     lint.build("no documentation found for this crate's top-level module");
509                 diag.help(help);
510                 diag.emit();
511             },
512         );
513     }
514
515     fn report_deprecated_attr(name: &str, diag: &rustc_errors::Handler, sp: Span) {
516         let mut msg =
517             diag.struct_span_warn(sp, &format!("the `#![doc({})]` attribute is deprecated", name));
518         msg.note(
519             "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
520              for more information",
521         );
522
523         if name == "no_default_passes" {
524             msg.help("you may want to use `#![doc(document_private_items)]`");
525         } else if name.starts_with("plugins") {
526             msg.warn("`#![doc(plugins = \"...\")]` no longer functions; see CVE-2018-1000622 <https://nvd.nist.gov/vuln/detail/CVE-2018-1000622>");
527         }
528
529         msg.emit();
530     }
531
532     let parse_pass = |name: &str, sp: Option<Span>| {
533         if let Some(pass) = passes::find_pass(name) {
534             Some(ConditionalPass::always(pass))
535         } else {
536             let msg = &format!("ignoring unknown pass `{}`", name);
537             let mut warning = if let Some(sp) = sp {
538                 tcx.sess.struct_span_warn(sp, msg)
539             } else {
540                 tcx.sess.struct_warn(msg)
541             };
542             if name == "collapse-docs" {
543                 warning.note("the `collapse-docs` pass was removed in #80261 <https://github.com/rust-lang/rust/pull/80261>");
544             }
545             warning.emit();
546             None
547         }
548     };
549
550     let mut manual_passes: Vec<_> =
551         manual_passes.into_iter().flat_map(|name| parse_pass(&name, None)).collect();
552
553     // Process all of the crate attributes, extracting plugin metadata along
554     // with the passes which we are supposed to run.
555     for attr in krate.module.attrs.lists(sym::doc) {
556         let diag = ctxt.sess().diagnostic();
557
558         let name = attr.name_or_empty();
559         if attr.is_word() {
560             if name == sym::no_default_passes {
561                 report_deprecated_attr("no_default_passes", diag, attr.span());
562                 if default_passes == passes::DefaultPassOption::Default {
563                     default_passes = passes::DefaultPassOption::None;
564                 }
565             }
566         } else if let Some(value) = attr.value_str() {
567             match name {
568                 sym::passes => {
569                     report_deprecated_attr("passes = \"...\"", diag, attr.span());
570                 }
571                 sym::plugins => {
572                     report_deprecated_attr("plugins = \"...\"", diag, attr.span());
573                     continue;
574                 }
575                 _ => continue,
576             };
577             for name in value.as_str().split_whitespace() {
578                 let span = attr.name_value_literal_span().unwrap_or(attr.span());
579                 manual_passes.extend(parse_pass(name, Some(span)));
580             }
581         }
582
583         if attr.is_word() && name == sym::document_private_items {
584             ctxt.render_options.document_private = true;
585         }
586     }
587
588     let passes = passes::defaults(default_passes).iter().copied().chain(manual_passes);
589     info!("Executing passes");
590
591     for p in passes {
592         let run = match p.condition {
593             Always => true,
594             WhenDocumentPrivate => ctxt.render_options.document_private,
595             WhenNotDocumentPrivate => !ctxt.render_options.document_private,
596             WhenNotDocumentHidden => !ctxt.render_options.document_hidden,
597         };
598         if run {
599             debug!("running pass {}", p.pass.name);
600             krate = ctxt.tcx.sess.time(p.pass.name, || (p.pass.run)(krate, &mut ctxt));
601         }
602     }
603
604     ctxt.sess().abort_if_errors();
605
606     let render_options = ctxt.render_options;
607     let mut cache = ctxt.cache;
608     krate = tcx.sess.time("create_format_cache", || {
609         cache.populate(krate, tcx, &render_options.extern_html_root_urls, &render_options.output)
610     });
611
612     // The main crate doc comments are always collapsed.
613     krate.collapsed = true;
614
615     (krate, render_options, cache)
616 }
617
618 /// Due to <https://github.com/rust-lang/rust/pull/73566>,
619 /// the name resolution pass may find errors that are never emitted.
620 /// If typeck is called after this happens, then we'll get an ICE:
621 /// 'Res::Error found but not reported'. To avoid this, emit the errors now.
622 struct EmitIgnoredResolutionErrors<'tcx> {
623     tcx: TyCtxt<'tcx>,
624 }
625
626 impl<'tcx> EmitIgnoredResolutionErrors<'tcx> {
627     fn new(tcx: TyCtxt<'tcx>) -> Self {
628         Self { tcx }
629     }
630 }
631
632 impl<'tcx> Visitor<'tcx> for EmitIgnoredResolutionErrors<'tcx> {
633     type Map = Map<'tcx>;
634
635     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
636         // We need to recurse into nested closures,
637         // since those will fallback to the parent for type checking.
638         NestedVisitorMap::OnlyBodies(self.tcx.hir())
639     }
640
641     fn visit_path(&mut self, path: &'tcx Path<'_>, _id: HirId) {
642         debug!("visiting path {:?}", path);
643         if path.res == Res::Err {
644             // We have less context here than in rustc_resolve,
645             // so we can only emit the name and span.
646             // However we can give a hint that rustc_resolve will have more info.
647             let label = format!(
648                 "could not resolve path `{}`",
649                 path.segments
650                     .iter()
651                     .map(|segment| segment.ident.as_str().to_string())
652                     .collect::<Vec<_>>()
653                     .join("::")
654             );
655             let mut err = rustc_errors::struct_span_err!(
656                 self.tcx.sess,
657                 path.span,
658                 E0433,
659                 "failed to resolve: {}",
660                 label
661             );
662             err.span_label(path.span, label);
663             err.note("this error was originally ignored because you are running `rustdoc`");
664             err.note("try running again with `rustc` or `cargo check` and you may get a more detailed error");
665             err.emit();
666         }
667         // We could have an outer resolution that succeeded,
668         // but with generic parameters that failed.
669         // Recurse into the segments so we catch those too.
670         intravisit::walk_path(self, path);
671     }
672 }
673
674 /// `DefId` or parameter index (`ty::ParamTy.index`) of a synthetic type parameter
675 /// for `impl Trait` in argument position.
676 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
677 crate enum ImplTraitParam {
678     DefId(DefId),
679     ParamIndex(u32),
680 }
681
682 impl From<DefId> for ImplTraitParam {
683     fn from(did: DefId) -> Self {
684         ImplTraitParam::DefId(did)
685     }
686 }
687
688 impl From<u32> for ImplTraitParam {
689     fn from(idx: u32) -> Self {
690         ImplTraitParam::ParamIndex(idx)
691     }
692 }