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