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