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