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