]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/core.rs
Auto merge of #84725 - sebpop:arm64-isb, r=joshtriplett
[rust.git] / src / librustdoc / core.rs
1 use rustc_ast as ast;
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::Res;
9 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, LOCAL_CRATE};
10 use rustc_hir::HirId;
11 use rustc_hir::{
12     intravisit::{self, NestedVisitorMap, Visitor},
13     Path,
14 };
15 use rustc_interface::{interface, Queries};
16 use rustc_middle::hir::map::Map;
17 use rustc_middle::middle::privacy::AccessLevels;
18 use rustc_middle::ty::{ParamEnv, Ty, TyCtxt};
19 use rustc_resolve as resolve;
20 use rustc_session::config::{self, CrateType, ErrorOutputType};
21 use rustc_session::lint;
22 use rustc_session::DiagnosticOutput;
23 use rustc_session::Session;
24 use rustc_span::source_map;
25 use rustc_span::symbol::sym;
26 use rustc_span::Span;
27
28 use std::cell::RefCell;
29 use std::collections::hash_map::Entry;
30 use std::mem;
31 use std::rc::Rc;
32
33 use crate::clean;
34 use crate::clean::inline::build_external_trait;
35 use crate::clean::{TraitWithExtraInfo, MAX_DEF_IDX};
36 use crate::config::{Options as RustdocOptions, OutputFormat, RenderOptions};
37 use crate::formats::cache::Cache;
38 use crate::passes::{self, Condition::*, ConditionalPass};
39
40 crate use rustc_session::config::{DebuggingOptions, Input, Options};
41
42 crate struct DocContext<'tcx> {
43     crate tcx: TyCtxt<'tcx>,
44     /// Name resolver. Used for intra-doc links.
45     ///
46     /// The `Rc<RefCell<...>>` wrapping is needed because that is what's returned by
47     /// [`Queries::expansion()`].
48     // FIXME: see if we can get rid of this RefCell somehow
49     crate resolver: Rc<RefCell<interface::BoxedResolver>>,
50     /// Used for normalization.
51     ///
52     /// Most of this logic is copied from rustc_lint::late.
53     crate param_env: ParamEnv<'tcx>,
54     /// Later on moved through `clean::Crate` into `cache`
55     crate external_traits: Rc<RefCell<FxHashMap<DefId, clean::TraitWithExtraInfo>>>,
56     /// Used while populating `external_traits` to ensure we don't process the same trait twice at
57     /// the same time.
58     crate active_extern_traits: FxHashSet<DefId>,
59     // The current set of type and lifetime substitutions,
60     // for expanding type aliases at the HIR level:
61     /// Table `DefId` of type parameter -> substituted type
62     crate ty_substs: FxHashMap<DefId, clean::Type>,
63     /// Table `DefId` of lifetime parameter -> substituted lifetime
64     crate lt_substs: FxHashMap<DefId, clean::Lifetime>,
65     /// Table `DefId` of const parameter -> substituted const
66     crate ct_substs: FxHashMap<DefId, clean::Constant>,
67     /// Table synthetic type parameter for `impl Trait` in argument position -> bounds
68     crate impl_trait_bounds: FxHashMap<ImplTraitParam, Vec<clean::GenericBound>>,
69     crate fake_def_ids: FxHashMap<CrateNum, DefIndex>,
70     /// Auto-trait or blanket impls processed so far, as `(self_ty, trait_def_id)`.
71     // FIXME(eddyb) make this a `ty::TraitRef<'tcx>` set.
72     crate generated_synthetics: FxHashSet<(Ty<'tcx>, DefId)>,
73     crate auto_traits: Vec<DefId>,
74     /// The options given to rustdoc that could be relevant to a pass.
75     crate render_options: RenderOptions,
76     /// The traits in scope for a given module.
77     ///
78     /// See `collect_intra_doc_links::traits_implemented_by` for more details.
79     /// `map<module, set<trait>>`
80     crate module_trait_cache: FxHashMap<DefId, FxHashSet<DefId>>,
81     /// This same cache is used throughout rustdoc, including in [`crate::html::render`].
82     crate cache: Cache,
83     /// Used by [`clean::inline`] to tell if an item has already been inlined.
84     crate inlined: FxHashSet<DefId>,
85     /// Used by `calculate_doc_coverage`.
86     crate output_format: OutputFormat,
87 }
88
89 impl<'tcx> DocContext<'tcx> {
90     crate fn sess(&self) -> &'tcx Session {
91         &self.tcx.sess
92     }
93
94     crate fn with_param_env<T, F: FnOnce(&mut Self) -> T>(&mut self, def_id: DefId, f: F) -> T {
95         let old_param_env = mem::replace(&mut self.param_env, self.tcx.param_env(def_id));
96         let ret = f(self);
97         self.param_env = old_param_env;
98         ret
99     }
100
101     crate fn enter_resolver<F, R>(&self, f: F) -> R
102     where
103         F: FnOnce(&mut resolve::Resolver<'_>) -> R,
104     {
105         self.resolver.borrow_mut().access(f)
106     }
107
108     /// Call the closure with the given parameters set as
109     /// the substitutions for a type alias' RHS.
110     crate fn enter_alias<F, R>(
111         &mut self,
112         ty_substs: FxHashMap<DefId, clean::Type>,
113         lt_substs: FxHashMap<DefId, clean::Lifetime>,
114         ct_substs: FxHashMap<DefId, clean::Constant>,
115         f: F,
116     ) -> R
117     where
118         F: FnOnce(&mut Self) -> R,
119     {
120         let (old_tys, old_lts, old_cts) = (
121             mem::replace(&mut self.ty_substs, ty_substs),
122             mem::replace(&mut self.lt_substs, lt_substs),
123             mem::replace(&mut self.ct_substs, ct_substs),
124         );
125         let r = f(self);
126         self.ty_substs = old_tys;
127         self.lt_substs = old_lts;
128         self.ct_substs = old_cts;
129         r
130     }
131
132     /// Create a new "fake" [`DefId`].
133     ///
134     /// This is an ugly hack, but it's the simplest way to handle synthetic impls without greatly
135     /// refactoring either rustdoc or [`rustc_middle`]. In particular, allowing new [`DefId`]s
136     /// to be registered after the AST is constructed would require storing the [`DefId`] mapping
137     /// in a [`RefCell`], decreasing the performance for normal compilation for very little gain.
138     ///
139     /// Instead, we construct "fake" [`DefId`]s, which start immediately after the last `DefId`.
140     /// In the [`Debug`] impl for [`clean::Item`], we explicitly check for fake `DefId`s,
141     /// as we'll end up with a panic if we use the `DefId` `Debug` impl for fake `DefId`s.
142     ///
143     /// [`RefCell`]: std::cell::RefCell
144     /// [`Debug`]: std::fmt::Debug
145     /// [`clean::Item`]: crate::clean::types::Item
146     crate fn next_def_id(&mut self, crate_num: CrateNum) -> DefId {
147         let def_index = match self.fake_def_ids.entry(crate_num) {
148             Entry::Vacant(e) => {
149                 let num_def_idx = {
150                     let num_def_idx = if crate_num == LOCAL_CRATE {
151                         self.tcx.hir().definitions().def_path_table().num_def_ids()
152                     } else {
153                         self.resolver.borrow_mut().access(|r| r.cstore().num_def_ids(crate_num))
154                     };
155
156                     DefIndex::from_usize(num_def_idx)
157                 };
158
159                 MAX_DEF_IDX.with(|m| {
160                     m.borrow_mut().insert(crate_num, num_def_idx);
161                 });
162                 e.insert(num_def_idx)
163             }
164             Entry::Occupied(e) => e.into_mut(),
165         };
166         *def_index = *def_index + 1;
167
168         DefId { krate: crate_num, index: *def_index }
169     }
170
171     /// Like `hir().local_def_id_to_hir_id()`, but skips calling it on fake DefIds.
172     /// (This avoids a slice-index-out-of-bounds panic.)
173     crate fn as_local_hir_id(tcx: TyCtxt<'_>, def_id: DefId) -> Option<HirId> {
174         if MAX_DEF_IDX.with(|m| {
175             m.borrow().get(&def_id.krate).map(|&idx| idx <= def_id.index).unwrap_or(false)
176         }) {
177             None
178         } else {
179             def_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
180         }
181     }
182 }
183
184 /// Creates a new diagnostic `Handler` that can be used to emit warnings and errors.
185 ///
186 /// If the given `error_format` is `ErrorOutputType::Json` and no `SourceMap` is given, a new one
187 /// will be created for the handler.
188 crate fn new_handler(
189     error_format: ErrorOutputType,
190     source_map: Option<Lrc<source_map::SourceMap>>,
191     debugging_opts: &DebuggingOptions,
192 ) -> rustc_errors::Handler {
193     let emitter: Box<dyn Emitter + sync::Send> = match error_format {
194         ErrorOutputType::HumanReadable(kind) => {
195             let (short, color_config) = kind.unzip();
196             Box::new(
197                 EmitterWriter::stderr(
198                     color_config,
199                     source_map.map(|sm| sm as _),
200                     short,
201                     debugging_opts.teach,
202                     debugging_opts.terminal_width,
203                     false,
204                 )
205                 .ui_testing(debugging_opts.ui_testing),
206             )
207         }
208         ErrorOutputType::Json { pretty, json_rendered } => {
209             let source_map = source_map.unwrap_or_else(|| {
210                 Lrc::new(source_map::SourceMap::new(source_map::FilePathMapping::empty()))
211             });
212             Box::new(
213                 JsonEmitter::stderr(
214                     None,
215                     source_map,
216                     pretty,
217                     json_rendered,
218                     debugging_opts.terminal_width,
219                     false,
220                 )
221                 .ui_testing(debugging_opts.ui_testing),
222             )
223         }
224     };
225
226     rustc_errors::Handler::with_emitter_and_flags(
227         emitter,
228         debugging_opts.diagnostic_handler_flags(true),
229     )
230 }
231
232 /// Parse, resolve, and typecheck the given crate.
233 crate fn create_config(
234     RustdocOptions {
235         input,
236         crate_name,
237         proc_macro_crate,
238         error_format,
239         libs,
240         externs,
241         mut cfgs,
242         codegen_options,
243         debugging_opts,
244         target,
245         edition,
246         maybe_sysroot,
247         lint_opts,
248         describe_lints,
249         lint_cap,
250         display_warnings,
251         ..
252     }: RustdocOptions,
253 ) -> rustc_interface::Config {
254     // Add the doc cfg into the doc build.
255     cfgs.push("doc".to_string());
256
257     let cpath = Some(input.clone());
258     let input = Input::File(input);
259
260     // By default, rustdoc ignores all lints.
261     // Specifically unblock lints relevant to documentation or the lint machinery itself.
262     let mut lints_to_show = vec![
263         // it's unclear whether this should be part of rustdoc directly (#77364)
264         rustc_lint::builtin::MISSING_DOCS.name.to_string(),
265         // these are definitely not part of rustdoc, but we want to warn on them anyway.
266         rustc_lint::builtin::RENAMED_AND_REMOVED_LINTS.name.to_string(),
267         rustc_lint::builtin::UNKNOWN_LINTS.name.to_string(),
268     ];
269     lints_to_show.extend(crate::lint::RUSTDOC_LINTS.iter().map(|lint| lint.name.to_string()));
270
271     let (lint_opts, lint_caps) = crate::lint::init_lints(lints_to_show, lint_opts, |lint| {
272         // FIXME: why is this necessary?
273         if lint.name == crate::lint::BROKEN_INTRA_DOC_LINKS.name
274             || lint.name == crate::lint::INVALID_CODEBLOCK_ATTRIBUTES.name
275         {
276             None
277         } else {
278             Some((lint.name_lower(), lint::Allow))
279         }
280     });
281
282     let crate_types =
283         if proc_macro_crate { vec![CrateType::ProcMacro] } else { vec![CrateType::Rlib] };
284     // plays with error output here!
285     let sessopts = config::Options {
286         maybe_sysroot,
287         search_paths: libs,
288         crate_types,
289         lint_opts: if !display_warnings { lint_opts } else { vec![] },
290         lint_cap,
291         cg: codegen_options,
292         externs,
293         target_triple: target,
294         unstable_features: UnstableFeatures::from_environment(crate_name.as_deref()),
295         actually_rustdoc: true,
296         debugging_opts,
297         error_format,
298         edition,
299         describe_lints,
300         crate_name,
301         ..Options::default()
302     };
303
304     interface::Config {
305         opts: sessopts,
306         crate_cfg: interface::parse_cfgspecs(cfgs),
307         input,
308         input_path: cpath,
309         output_file: None,
310         output_dir: None,
311         file_loader: None,
312         diagnostic_output: DiagnosticOutput::Default,
313         stderr: None,
314         lint_caps,
315         parse_sess_created: None,
316         register_lints: Some(box crate::lint::register_lints),
317         override_queries: Some(|_sess, providers, _external_providers| {
318             // Most lints will require typechecking, so just don't run them.
319             providers.lint_mod = |_, _| {};
320             // Prevent `rustc_typeck::check_crate` from calling `typeck` on all bodies.
321             providers.typeck_item_bodies = |_, _| {};
322             // hack so that `used_trait_imports` won't try to call typeck
323             providers.used_trait_imports = |_, _| {
324                 lazy_static! {
325                     static ref EMPTY_SET: FxHashSet<LocalDefId> = FxHashSet::default();
326                 }
327                 &EMPTY_SET
328             };
329             // In case typeck does end up being called, don't ICE in case there were name resolution errors
330             providers.typeck = move |tcx, def_id| {
331                 // Closures' tables come from their outermost function,
332                 // as they are part of the same "inference environment".
333                 // This avoids emitting errors for the parent twice (see similar code in `typeck_with_fallback`)
334                 let outer_def_id = tcx.closure_base_def_id(def_id.to_def_id()).expect_local();
335                 if outer_def_id != def_id {
336                     return tcx.typeck(outer_def_id);
337                 }
338
339                 let hir = tcx.hir();
340                 let body = hir.body(hir.body_owned_by(hir.local_def_id_to_hir_id(def_id)));
341                 debug!("visiting body for {:?}", def_id);
342                 EmitIgnoredResolutionErrors::new(tcx).visit_body(body);
343                 (rustc_interface::DEFAULT_QUERY_PROVIDERS.typeck)(tcx, def_id)
344             };
345         }),
346         make_codegen_backend: None,
347         registry: rustc_driver::diagnostics_registry(),
348     }
349 }
350
351 crate fn create_resolver<'a>(
352     queries: &Queries<'a>,
353     sess: &Session,
354 ) -> Rc<RefCell<interface::BoxedResolver>> {
355     let parts = abort_on_err(queries.expansion(), sess).peek();
356     let (krate, resolver, _) = &*parts;
357     let resolver = resolver.borrow().clone();
358
359     let mut loader = crate::passes::collect_intra_doc_links::IntraLinkCrateLoader::new(resolver);
360     ast::visit::walk_crate(&mut loader, krate);
361
362     loader.resolver
363 }
364
365 crate fn run_global_ctxt(
366     tcx: TyCtxt<'_>,
367     resolver: Rc<RefCell<interface::BoxedResolver>>,
368     mut default_passes: passes::DefaultPassOption,
369     manual_passes: Vec<String>,
370     render_options: RenderOptions,
371     output_format: OutputFormat,
372 ) -> (clean::Crate, RenderOptions, Cache) {
373     // Certain queries assume that some checks were run elsewhere
374     // (see https://github.com/rust-lang/rust/pull/73566#issuecomment-656954425),
375     // so type-check everything other than function bodies in this crate before running lints.
376
377     // NOTE: this does not call `tcx.analysis()` so that we won't
378     // typeck function bodies or run the default rustc lints.
379     // (see `override_queries` in the `config`)
380
381     // HACK(jynelson) this calls an _extremely_ limited subset of `typeck`
382     // and might break if queries change their assumptions in the future.
383
384     // NOTE: This is copy/pasted from typeck/lib.rs and should be kept in sync with those changes.
385     tcx.sess.time("item_types_checking", || {
386         for &module in tcx.hir().krate().modules.keys() {
387             tcx.ensure().check_mod_item_types(module);
388         }
389     });
390     tcx.sess.abort_if_errors();
391     tcx.sess.time("missing_docs", || {
392         rustc_lint::check_crate(tcx, rustc_lint::builtin::MissingDoc::new);
393     });
394     tcx.sess.time("check_mod_attrs", || {
395         for &module in tcx.hir().krate().modules.keys() {
396             tcx.ensure().check_mod_attrs(module);
397         }
398     });
399     rustc_passes::stability::check_unused_or_stable_features(tcx);
400
401     let access_levels = tcx.privacy_access_levels(LOCAL_CRATE);
402     // Convert from a HirId set to a DefId set since we don't always have easy access
403     // to the map from defid -> hirid
404     let access_levels = AccessLevels {
405         map: access_levels
406             .map
407             .iter()
408             .map(|(&k, &v)| (tcx.hir().local_def_id(k).to_def_id(), v))
409             .collect(),
410     };
411
412     let mut ctxt = DocContext {
413         tcx,
414         resolver,
415         param_env: ParamEnv::empty(),
416         external_traits: Default::default(),
417         active_extern_traits: Default::default(),
418         ty_substs: Default::default(),
419         lt_substs: Default::default(),
420         ct_substs: Default::default(),
421         impl_trait_bounds: Default::default(),
422         fake_def_ids: Default::default(),
423         generated_synthetics: Default::default(),
424         auto_traits: tcx
425             .all_traits(LOCAL_CRATE)
426             .iter()
427             .cloned()
428             .filter(|trait_def_id| tcx.trait_is_auto(*trait_def_id))
429             .collect(),
430         module_trait_cache: FxHashMap::default(),
431         cache: Cache::new(access_levels, render_options.document_private),
432         inlined: FxHashSet::default(),
433         output_format,
434         render_options,
435     };
436
437     // Small hack to force the Sized trait to be present.
438     //
439     // Note that in case of `#![no_core]`, the trait is not available.
440     if let Some(sized_trait_did) = ctxt.tcx.lang_items().sized_trait() {
441         let mut sized_trait = build_external_trait(&mut ctxt, sized_trait_did);
442         sized_trait.is_auto = true;
443         ctxt.external_traits
444             .borrow_mut()
445             .insert(sized_trait_did, TraitWithExtraInfo { trait_: sized_trait, is_notable: false });
446     }
447
448     debug!("crate: {:?}", tcx.hir().krate());
449
450     let mut krate = tcx.sess.time("clean_crate", || clean::krate(&mut ctxt));
451
452     if krate.module.doc_value().map(|d| d.is_empty()).unwrap_or(true) {
453         let help = format!(
454             "The following guide may be of use:\n\
455             https://doc.rust-lang.org/{}/rustdoc/how-to-write-documentation.html",
456             crate::doc_rust_lang_org_channel(),
457         );
458         tcx.struct_lint_node(
459             crate::lint::MISSING_CRATE_LEVEL_DOCS,
460             DocContext::as_local_hir_id(tcx, krate.module.def_id).unwrap(),
461             |lint| {
462                 let mut diag =
463                     lint.build("no documentation found for this crate's top-level module");
464                 diag.help(&help);
465                 diag.emit();
466             },
467         );
468     }
469
470     fn report_deprecated_attr(name: &str, diag: &rustc_errors::Handler, sp: Span) {
471         let mut msg =
472             diag.struct_span_warn(sp, &format!("the `#![doc({})]` attribute is deprecated", name));
473         msg.note(
474             "see issue #44136 <https://github.com/rust-lang/rust/issues/44136> \
475              for more information",
476         );
477
478         if name == "no_default_passes" {
479             msg.help("you may want to use `#![doc(document_private_items)]`");
480         } else if name.starts_with("plugins") {
481             msg.warn("`#![doc(plugins = \"...\")]` no longer functions; see CVE-2018-1000622 <https://nvd.nist.gov/vuln/detail/CVE-2018-1000622>");
482         }
483
484         msg.emit();
485     }
486
487     let parse_pass = |name: &str, sp: Option<Span>| {
488         if let Some(pass) = passes::find_pass(name) {
489             Some(ConditionalPass::always(pass))
490         } else {
491             let msg = &format!("ignoring unknown pass `{}`", name);
492             let mut warning = if let Some(sp) = sp {
493                 tcx.sess.struct_span_warn(sp, msg)
494             } else {
495                 tcx.sess.struct_warn(msg)
496             };
497             if name == "collapse-docs" {
498                 warning.note("the `collapse-docs` pass was removed in #80261 <https://github.com/rust-lang/rust/pull/80261>");
499             }
500             warning.emit();
501             None
502         }
503     };
504
505     let mut manual_passes: Vec<_> =
506         manual_passes.into_iter().flat_map(|name| parse_pass(&name, None)).collect();
507
508     // Process all of the crate attributes, extracting plugin metadata along
509     // with the passes which we are supposed to run.
510     for attr in krate.module.attrs.lists(sym::doc) {
511         let diag = ctxt.sess().diagnostic();
512
513         let name = attr.name_or_empty();
514         if attr.is_word() {
515             if name == sym::no_default_passes {
516                 report_deprecated_attr("no_default_passes", diag, attr.span());
517                 if default_passes == passes::DefaultPassOption::Default {
518                     default_passes = passes::DefaultPassOption::None;
519                 }
520             }
521         } else if let Some(value) = attr.value_str() {
522             match name {
523                 sym::passes => {
524                     report_deprecated_attr("passes = \"...\"", diag, attr.span());
525                 }
526                 sym::plugins => {
527                     report_deprecated_attr("plugins = \"...\"", diag, attr.span());
528                     continue;
529                 }
530                 _ => continue,
531             };
532             for name in value.as_str().split_whitespace() {
533                 let span = attr.name_value_literal_span().unwrap_or(attr.span());
534                 manual_passes.extend(parse_pass(name, Some(span)));
535             }
536         }
537
538         if attr.is_word() && name == sym::document_private_items {
539             ctxt.render_options.document_private = true;
540         }
541     }
542
543     let passes = passes::defaults(default_passes).iter().copied().chain(manual_passes);
544     info!("Executing passes");
545
546     for p in passes {
547         let run = match p.condition {
548             Always => true,
549             WhenDocumentPrivate => ctxt.render_options.document_private,
550             WhenNotDocumentPrivate => !ctxt.render_options.document_private,
551             WhenNotDocumentHidden => !ctxt.render_options.document_hidden,
552         };
553         if run {
554             debug!("running pass {}", p.pass.name);
555             krate = ctxt.tcx.sess.time(p.pass.name, || (p.pass.run)(krate, &mut ctxt));
556         }
557     }
558
559     ctxt.sess().abort_if_errors();
560
561     let render_options = ctxt.render_options;
562     let mut cache = ctxt.cache;
563     krate = tcx.sess.time("create_format_cache", || {
564         cache.populate(krate, tcx, &render_options.extern_html_root_urls, &render_options.output)
565     });
566
567     // The main crate doc comments are always collapsed.
568     krate.collapsed = true;
569
570     (krate, render_options, cache)
571 }
572
573 /// Due to <https://github.com/rust-lang/rust/pull/73566>,
574 /// the name resolution pass may find errors that are never emitted.
575 /// If typeck is called after this happens, then we'll get an ICE:
576 /// 'Res::Error found but not reported'. To avoid this, emit the errors now.
577 struct EmitIgnoredResolutionErrors<'tcx> {
578     tcx: TyCtxt<'tcx>,
579 }
580
581 impl<'tcx> EmitIgnoredResolutionErrors<'tcx> {
582     fn new(tcx: TyCtxt<'tcx>) -> Self {
583         Self { tcx }
584     }
585 }
586
587 impl<'tcx> Visitor<'tcx> for EmitIgnoredResolutionErrors<'tcx> {
588     type Map = Map<'tcx>;
589
590     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
591         // We need to recurse into nested closures,
592         // since those will fallback to the parent for type checking.
593         NestedVisitorMap::OnlyBodies(self.tcx.hir())
594     }
595
596     fn visit_path(&mut self, path: &'tcx Path<'_>, _id: HirId) {
597         debug!("visiting path {:?}", path);
598         if path.res == Res::Err {
599             // We have less context here than in rustc_resolve,
600             // so we can only emit the name and span.
601             // However we can give a hint that rustc_resolve will have more info.
602             let label = format!(
603                 "could not resolve path `{}`",
604                 path.segments
605                     .iter()
606                     .map(|segment| segment.ident.as_str().to_string())
607                     .collect::<Vec<_>>()
608                     .join("::")
609             );
610             let mut err = rustc_errors::struct_span_err!(
611                 self.tcx.sess,
612                 path.span,
613                 E0433,
614                 "failed to resolve: {}",
615                 label
616             );
617             err.span_label(path.span, label);
618             err.note("this error was originally ignored because you are running `rustdoc`");
619             err.note("try running again with `rustc` or `cargo check` and you may get a more detailed error");
620             err.emit();
621         }
622         // We could have an outer resolution that succeeded,
623         // but with generic parameters that failed.
624         // Recurse into the segments so we catch those too.
625         intravisit::walk_path(self, path);
626     }
627 }
628
629 /// `DefId` or parameter index (`ty::ParamTy.index`) of a synthetic type parameter
630 /// for `impl Trait` in argument position.
631 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
632 crate enum ImplTraitParam {
633     DefId(DefId),
634     ParamIndex(u32),
635 }
636
637 impl From<DefId> for ImplTraitParam {
638     fn from(did: DefId) -> Self {
639         ImplTraitParam::DefId(did)
640     }
641 }
642
643 impl From<u32> for ImplTraitParam {
644     fn from(idx: u32) -> Self {
645         ImplTraitParam::ParamIndex(idx)
646     }
647 }