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