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