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