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