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