]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/utils.rs
Rename ItemEnum -> ItemKind, inner -> kind
[rust.git] / src / librustdoc / clean / utils.rs
1 use crate::clean::auto_trait::AutoTraitFinder;
2 use crate::clean::blanket_impl::BlanketImplFinder;
3 use crate::clean::{
4     inline, Clean, Crate, Deprecation, ExternalCrate, FnDecl, FnRetTy, Generic, GenericArg,
5     GenericArgs, GenericBound, Generics, GetDefId, ImportSource, Item, ItemKind, Lifetime,
6     MacroKind, Path, PathSegment, Primitive, PrimitiveType, ResolvedPath, Span, Type, TypeBinding,
7     TypeKind, Visibility, WherePredicate,
8 };
9 use crate::core::DocContext;
10
11 use itertools::Itertools;
12 use rustc_attr::Stability;
13 use rustc_data_structures::fx::FxHashSet;
14 use rustc_hir as hir;
15 use rustc_hir::def::{DefKind, Res};
16 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
17 use rustc_middle::mir::interpret::ConstValue;
18 use rustc_middle::ty::subst::{GenericArgKind, SubstsRef};
19 use rustc_middle::ty::{self, DefIdTree, Ty};
20 use rustc_span::symbol::{kw, sym, Symbol};
21 use std::mem;
22
23 pub fn krate(mut cx: &mut DocContext<'_>) -> Crate {
24     use crate::visit_lib::LibEmbargoVisitor;
25
26     let krate = cx.tcx.hir().krate();
27     let module = crate::visit_ast::RustdocVisitor::new(&mut cx).visit(krate);
28
29     let mut r = cx.renderinfo.get_mut();
30     r.deref_trait_did = cx.tcx.lang_items().deref_trait();
31     r.deref_mut_trait_did = cx.tcx.lang_items().deref_mut_trait();
32     r.owned_box_did = cx.tcx.lang_items().owned_box();
33
34     let mut externs = Vec::new();
35     for &cnum in cx.tcx.crates().iter() {
36         externs.push((cnum, cnum.clean(cx)));
37         // Analyze doc-reachability for extern items
38         LibEmbargoVisitor::new(&mut cx).visit_lib(cnum);
39     }
40     externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
41
42     // Clean the crate, translating the entire librustc_ast AST to one that is
43     // understood by rustdoc.
44     let mut module = module.clean(cx);
45     let mut masked_crates = FxHashSet::default();
46
47     match module.kind {
48         ItemKind::ModuleItem(ref module) => {
49             for it in &module.items {
50                 // `compiler_builtins` should be masked too, but we can't apply
51                 // `#[doc(masked)]` to the injected `extern crate` because it's unstable.
52                 if it.is_extern_crate()
53                     && (it.attrs.has_doc_flag(sym::masked)
54                         || cx.tcx.is_compiler_builtins(it.def_id.krate))
55                 {
56                     masked_crates.insert(it.def_id.krate);
57                 }
58             }
59         }
60         _ => unreachable!(),
61     }
62
63     let ExternalCrate { name, src, primitives, keywords, .. } = LOCAL_CRATE.clean(cx);
64     {
65         let m = match module.kind {
66             ItemKind::ModuleItem(ref mut m) => m,
67             _ => unreachable!(),
68         };
69         m.items.extend(primitives.iter().map(|&(def_id, prim, ref attrs)| Item {
70             source: Span::empty(),
71             name: Some(prim.to_url_str().to_string()),
72             attrs: attrs.clone(),
73             visibility: Visibility::Public,
74             stability: get_stability(cx, def_id),
75             deprecation: get_deprecation(cx, def_id),
76             def_id,
77             kind: ItemKind::PrimitiveItem(prim),
78         }));
79         m.items.extend(keywords.into_iter().map(|(def_id, kw, attrs)| Item {
80             source: Span::empty(),
81             name: Some(kw.clone()),
82             attrs,
83             visibility: Visibility::Public,
84             stability: get_stability(cx, def_id),
85             deprecation: get_deprecation(cx, def_id),
86             def_id,
87             kind: ItemKind::KeywordItem(kw),
88         }));
89     }
90
91     Crate {
92         name,
93         version: None,
94         src,
95         module: Some(module),
96         externs,
97         primitives,
98         external_traits: cx.external_traits.clone(),
99         masked_crates,
100         collapsed: false,
101     }
102 }
103
104 // extract the stability index for a node from tcx, if possible
105 pub fn get_stability(cx: &DocContext<'_>, def_id: DefId) -> Option<Stability> {
106     cx.tcx.lookup_stability(def_id).cloned()
107 }
108
109 pub fn get_deprecation(cx: &DocContext<'_>, def_id: DefId) -> Option<Deprecation> {
110     cx.tcx.lookup_deprecation(def_id).clean(cx)
111 }
112
113 fn external_generic_args(
114     cx: &DocContext<'_>,
115     trait_did: Option<DefId>,
116     has_self: bool,
117     bindings: Vec<TypeBinding>,
118     substs: SubstsRef<'_>,
119 ) -> GenericArgs {
120     let mut skip_self = has_self;
121     let mut ty_kind = None;
122     let args: Vec<_> = substs
123         .iter()
124         .filter_map(|kind| match kind.unpack() {
125             GenericArgKind::Lifetime(lt) => match lt {
126                 ty::ReLateBound(_, ty::BrAnon(_)) => Some(GenericArg::Lifetime(Lifetime::elided())),
127                 _ => lt.clean(cx).map(GenericArg::Lifetime),
128             },
129             GenericArgKind::Type(_) if skip_self => {
130                 skip_self = false;
131                 None
132             }
133             GenericArgKind::Type(ty) => {
134                 ty_kind = Some(ty.kind());
135                 Some(GenericArg::Type(ty.clean(cx)))
136             }
137             GenericArgKind::Const(ct) => Some(GenericArg::Const(ct.clean(cx))),
138         })
139         .collect();
140
141     match trait_did {
142         // Attempt to sugar an external path like Fn<(A, B,), C> to Fn(A, B) -> C
143         Some(did) if cx.tcx.fn_trait_kind_from_lang_item(did).is_some() => {
144             assert!(ty_kind.is_some());
145             let inputs = match ty_kind {
146                 Some(ty::Tuple(ref tys)) => tys.iter().map(|t| t.expect_ty().clean(cx)).collect(),
147                 _ => return GenericArgs::AngleBracketed { args, bindings },
148             };
149             let output = None;
150             // FIXME(#20299) return type comes from a projection now
151             // match types[1].kind {
152             //     ty::Tuple(ref v) if v.is_empty() => None, // -> ()
153             //     _ => Some(types[1].clean(cx))
154             // };
155             GenericArgs::Parenthesized { inputs, output }
156         }
157         _ => GenericArgs::AngleBracketed { args, bindings },
158     }
159 }
160
161 // trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
162 // from Fn<(A, B,), C> to Fn(A, B) -> C
163 pub(super) fn external_path(
164     cx: &DocContext<'_>,
165     name: Symbol,
166     trait_did: Option<DefId>,
167     has_self: bool,
168     bindings: Vec<TypeBinding>,
169     substs: SubstsRef<'_>,
170 ) -> Path {
171     Path {
172         global: false,
173         res: Res::Err,
174         segments: vec![PathSegment {
175             name: name.to_string(),
176             args: external_generic_args(cx, trait_did, has_self, bindings, substs),
177         }],
178     }
179 }
180
181 /// The point of this function is to replace bounds with types.
182 ///
183 /// i.e. `[T, U]` when you have the following bounds: `T: Display, U: Option<T>` will return
184 /// `[Display, Option]` (we just returns the list of the types, we don't care about the
185 /// wrapped types in here).
186 pub fn get_real_types(
187     generics: &Generics,
188     arg: &Type,
189     cx: &DocContext<'_>,
190     recurse: i32,
191 ) -> FxHashSet<(Type, TypeKind)> {
192     let arg_s = arg.print().to_string();
193     let mut res = FxHashSet::default();
194     if recurse >= 10 {
195         // FIXME: remove this whole recurse thing when the recursion bug is fixed
196         return res;
197     }
198     if arg.is_full_generic() {
199         if let Some(where_pred) = generics.where_predicates.iter().find(|g| match g {
200             &WherePredicate::BoundPredicate { ref ty, .. } => ty.def_id() == arg.def_id(),
201             _ => false,
202         }) {
203             let bounds = where_pred.get_bounds().unwrap_or_else(|| &[]);
204             for bound in bounds.iter() {
205                 if let GenericBound::TraitBound(ref poly_trait, _) = *bound {
206                     for x in poly_trait.generic_params.iter() {
207                         if !x.is_type() {
208                             continue;
209                         }
210                         if let Some(ty) = x.get_type() {
211                             let adds = get_real_types(generics, &ty, cx, recurse + 1);
212                             if !adds.is_empty() {
213                                 res.extend(adds);
214                             } else if !ty.is_full_generic() {
215                                 if let Some(kind) =
216                                     ty.def_id().map(|did| cx.tcx.def_kind(did).clean(cx))
217                                 {
218                                     res.insert((ty, kind));
219                                 }
220                             }
221                         }
222                     }
223                 }
224             }
225         }
226         if let Some(bound) = generics.params.iter().find(|g| g.is_type() && g.name == arg_s) {
227             for bound in bound.get_bounds().unwrap_or_else(|| &[]) {
228                 if let Some(ty) = bound.get_trait_type() {
229                     let adds = get_real_types(generics, &ty, cx, recurse + 1);
230                     if !adds.is_empty() {
231                         res.extend(adds);
232                     } else if !ty.is_full_generic() {
233                         if let Some(kind) = ty.def_id().map(|did| cx.tcx.def_kind(did).clean(cx)) {
234                             res.insert((ty.clone(), kind));
235                         }
236                     }
237                 }
238             }
239         }
240     } else {
241         if let Some(kind) = arg.def_id().map(|did| cx.tcx.def_kind(did).clean(cx)) {
242             res.insert((arg.clone(), kind));
243         }
244         if let Some(gens) = arg.generics() {
245             for gen in gens.iter() {
246                 if gen.is_full_generic() {
247                     let adds = get_real_types(generics, gen, cx, recurse + 1);
248                     if !adds.is_empty() {
249                         res.extend(adds);
250                     }
251                 } else if let Some(kind) = gen.def_id().map(|did| cx.tcx.def_kind(did).clean(cx)) {
252                     res.insert((gen.clone(), kind));
253                 }
254             }
255         }
256     }
257     res
258 }
259
260 /// Return the full list of types when bounds have been resolved.
261 ///
262 /// i.e. `fn foo<A: Display, B: Option<A>>(x: u32, y: B)` will return
263 /// `[u32, Display, Option]`.
264 pub fn get_all_types(
265     generics: &Generics,
266     decl: &FnDecl,
267     cx: &DocContext<'_>,
268 ) -> (Vec<(Type, TypeKind)>, Vec<(Type, TypeKind)>) {
269     let mut all_types = FxHashSet::default();
270     for arg in decl.inputs.values.iter() {
271         if arg.type_.is_self_type() {
272             continue;
273         }
274         let args = get_real_types(generics, &arg.type_, cx, 0);
275         if !args.is_empty() {
276             all_types.extend(args);
277         } else {
278             if let Some(kind) = arg.type_.def_id().map(|did| cx.tcx.def_kind(did).clean(cx)) {
279                 all_types.insert((arg.type_.clone(), kind));
280             }
281         }
282     }
283
284     let ret_types = match decl.output {
285         FnRetTy::Return(ref return_type) => {
286             let mut ret = get_real_types(generics, &return_type, cx, 0);
287             if ret.is_empty() {
288                 if let Some(kind) = return_type.def_id().map(|did| cx.tcx.def_kind(did).clean(cx)) {
289                     ret.insert((return_type.clone(), kind));
290                 }
291             }
292             ret.into_iter().collect()
293         }
294         _ => Vec::new(),
295     };
296     (all_types.into_iter().collect(), ret_types)
297 }
298
299 pub fn strip_type(ty: Type) -> Type {
300     match ty {
301         Type::ResolvedPath { path, param_names, did, is_generic } => {
302             Type::ResolvedPath { path: strip_path(&path), param_names, did, is_generic }
303         }
304         Type::Tuple(inner_tys) => {
305             Type::Tuple(inner_tys.iter().map(|t| strip_type(t.clone())).collect())
306         }
307         Type::Slice(inner_ty) => Type::Slice(Box::new(strip_type(*inner_ty))),
308         Type::Array(inner_ty, s) => Type::Array(Box::new(strip_type(*inner_ty)), s),
309         Type::RawPointer(m, inner_ty) => Type::RawPointer(m, Box::new(strip_type(*inner_ty))),
310         Type::BorrowedRef { lifetime, mutability, type_ } => {
311             Type::BorrowedRef { lifetime, mutability, type_: Box::new(strip_type(*type_)) }
312         }
313         Type::QPath { name, self_type, trait_ } => Type::QPath {
314             name,
315             self_type: Box::new(strip_type(*self_type)),
316             trait_: Box::new(strip_type(*trait_)),
317         },
318         _ => ty,
319     }
320 }
321
322 pub fn strip_path(path: &Path) -> Path {
323     let segments = path
324         .segments
325         .iter()
326         .map(|s| PathSegment {
327             name: s.name.clone(),
328             args: GenericArgs::AngleBracketed { args: vec![], bindings: vec![] },
329         })
330         .collect();
331
332     Path { global: path.global, res: path.res, segments }
333 }
334
335 pub fn qpath_to_string(p: &hir::QPath<'_>) -> String {
336     let segments = match *p {
337         hir::QPath::Resolved(_, ref path) => &path.segments,
338         hir::QPath::TypeRelative(_, ref segment) => return segment.ident.to_string(),
339         hir::QPath::LangItem(lang_item, ..) => return lang_item.name().to_string(),
340     };
341
342     let mut s = String::new();
343     for (i, seg) in segments.iter().enumerate() {
344         if i > 0 {
345             s.push_str("::");
346         }
347         if seg.ident.name != kw::PathRoot {
348             s.push_str(&seg.ident.as_str());
349         }
350     }
351     s
352 }
353
354 pub fn build_deref_target_impls(cx: &DocContext<'_>, items: &[Item], ret: &mut Vec<Item>) {
355     let tcx = cx.tcx;
356
357     for item in items {
358         let target = match item.kind {
359             ItemKind::TypedefItem(ref t, true) => &t.type_,
360             _ => continue,
361         };
362         let primitive = match *target {
363             ResolvedPath { did, .. } if did.is_local() => continue,
364             ResolvedPath { did, .. } => {
365                 ret.extend(inline::build_impls(cx, None, did, None));
366                 continue;
367             }
368             _ => match target.primitive_type() {
369                 Some(prim) => prim,
370                 None => continue,
371             },
372         };
373         for &did in primitive.impls(tcx) {
374             if !did.is_local() {
375                 inline::build_impl(cx, None, did, None, ret);
376             }
377         }
378     }
379 }
380
381 pub trait ToSource {
382     fn to_src(&self, cx: &DocContext<'_>) -> String;
383 }
384
385 impl ToSource for rustc_span::Span {
386     fn to_src(&self, cx: &DocContext<'_>) -> String {
387         debug!("converting span {:?} to snippet", self.clean(cx));
388         let sn = match cx.sess().source_map().span_to_snippet(*self) {
389             Ok(x) => x,
390             Err(_) => String::new(),
391         };
392         debug!("got snippet {}", sn);
393         sn
394     }
395 }
396
397 pub fn name_from_pat(p: &hir::Pat<'_>) -> String {
398     use rustc_hir::*;
399     debug!("trying to get a name from pattern: {:?}", p);
400
401     match p.kind {
402         PatKind::Wild => "_".to_string(),
403         PatKind::Binding(_, _, ident, _) => ident.to_string(),
404         PatKind::TupleStruct(ref p, ..) | PatKind::Path(ref p) => qpath_to_string(p),
405         PatKind::Struct(ref name, ref fields, etc) => format!(
406             "{} {{ {}{} }}",
407             qpath_to_string(name),
408             fields
409                 .iter()
410                 .map(|fp| format!("{}: {}", fp.ident, name_from_pat(&fp.pat)))
411                 .collect::<Vec<String>>()
412                 .join(", "),
413             if etc { ", .." } else { "" }
414         ),
415         PatKind::Or(ref pats) => {
416             pats.iter().map(|p| name_from_pat(&**p)).collect::<Vec<String>>().join(" | ")
417         }
418         PatKind::Tuple(ref elts, _) => format!(
419             "({})",
420             elts.iter().map(|p| name_from_pat(&**p)).collect::<Vec<String>>().join(", ")
421         ),
422         PatKind::Box(ref p) => name_from_pat(&**p),
423         PatKind::Ref(ref p, _) => name_from_pat(&**p),
424         PatKind::Lit(..) => {
425             warn!(
426                 "tried to get argument name from PatKind::Lit, which is silly in function arguments"
427             );
428             "()".to_string()
429         }
430         PatKind::Range(..) => panic!(
431             "tried to get argument name from PatKind::Range, \
432              which is not allowed in function arguments"
433         ),
434         PatKind::Slice(ref begin, ref mid, ref end) => {
435             let begin = begin.iter().map(|p| name_from_pat(&**p));
436             let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
437             let end = end.iter().map(|p| name_from_pat(&**p));
438             format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
439         }
440     }
441 }
442
443 pub fn print_const(cx: &DocContext<'_>, n: &'tcx ty::Const<'_>) -> String {
444     match n.val {
445         ty::ConstKind::Unevaluated(def, _, promoted) => {
446             let mut s = if let Some(def) = def.as_local() {
447                 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def.did);
448                 print_const_expr(cx, cx.tcx.hir().body_owned_by(hir_id))
449             } else {
450                 inline::print_inlined_const(cx, def.did)
451             };
452             if let Some(promoted) = promoted {
453                 s.push_str(&format!("::{:?}", promoted))
454             }
455             s
456         }
457         _ => {
458             let mut s = n.to_string();
459             // array lengths are obviously usize
460             if s.ends_with("_usize") {
461                 let n = s.len() - "_usize".len();
462                 s.truncate(n);
463                 if s.ends_with(": ") {
464                     let n = s.len() - ": ".len();
465                     s.truncate(n);
466                 }
467             }
468             s
469         }
470     }
471 }
472
473 pub fn print_evaluated_const(cx: &DocContext<'_>, def_id: DefId) -> Option<String> {
474     cx.tcx.const_eval_poly(def_id).ok().and_then(|val| {
475         let ty = cx.tcx.type_of(def_id);
476         match (val, ty.kind()) {
477             (_, &ty::Ref(..)) => None,
478             (ConstValue::Scalar(_), &ty::Adt(_, _)) => None,
479             (ConstValue::Scalar(_), _) => {
480                 let const_ = ty::Const::from_value(cx.tcx, val, ty);
481                 Some(print_const_with_custom_print_scalar(cx, const_))
482             }
483             _ => None,
484         }
485     })
486 }
487
488 fn format_integer_with_underscore_sep(num: &str) -> String {
489     let num_chars: Vec<_> = num.chars().collect();
490     let num_start_index = if num_chars.get(0) == Some(&'-') { 1 } else { 0 };
491
492     num_chars[..num_start_index]
493         .iter()
494         .chain(num_chars[num_start_index..].rchunks(3).rev().intersperse(&['_']).flatten())
495         .collect()
496 }
497
498 fn print_const_with_custom_print_scalar(cx: &DocContext<'_>, ct: &'tcx ty::Const<'tcx>) -> String {
499     // Use a slightly different format for integer types which always shows the actual value.
500     // For all other types, fallback to the original `pretty_print_const`.
501     match (ct.val, ct.ty.kind()) {
502         (ty::ConstKind::Value(ConstValue::Scalar(int)), ty::Uint(ui)) => {
503             format!("{}{}", format_integer_with_underscore_sep(&int.to_string()), ui.name_str())
504         }
505         (ty::ConstKind::Value(ConstValue::Scalar(int)), ty::Int(i)) => {
506             let ty = cx.tcx.lift(ct.ty).unwrap();
507             let size = cx.tcx.layout_of(ty::ParamEnv::empty().and(ty)).unwrap().size;
508             let data = int.assert_bits(size);
509             let sign_extended_data = size.sign_extend(data) as i128;
510
511             format!(
512                 "{}{}",
513                 format_integer_with_underscore_sep(&sign_extended_data.to_string()),
514                 i.name_str()
515             )
516         }
517         _ => ct.to_string(),
518     }
519 }
520
521 pub fn is_literal_expr(cx: &DocContext<'_>, hir_id: hir::HirId) -> bool {
522     if let hir::Node::Expr(expr) = cx.tcx.hir().get(hir_id) {
523         if let hir::ExprKind::Lit(_) = &expr.kind {
524             return true;
525         }
526
527         if let hir::ExprKind::Unary(hir::UnOp::UnNeg, expr) = &expr.kind {
528             if let hir::ExprKind::Lit(_) = &expr.kind {
529                 return true;
530             }
531         }
532     }
533
534     false
535 }
536
537 pub fn print_const_expr(cx: &DocContext<'_>, body: hir::BodyId) -> String {
538     let value = &cx.tcx.hir().body(body).value;
539
540     let snippet = if !value.span.from_expansion() {
541         cx.sess().source_map().span_to_snippet(value.span).ok()
542     } else {
543         None
544     };
545
546     snippet.unwrap_or_else(|| rustc_hir_pretty::id_to_string(&cx.tcx.hir(), body.hir_id))
547 }
548
549 /// Given a type Path, resolve it to a Type using the TyCtxt
550 pub fn resolve_type(cx: &DocContext<'_>, path: Path, id: hir::HirId) -> Type {
551     debug!("resolve_type({:?},{:?})", path, id);
552
553     let is_generic = match path.res {
554         Res::PrimTy(p) => return Primitive(PrimitiveType::from(p)),
555         Res::SelfTy(..) if path.segments.len() == 1 => {
556             return Generic(kw::SelfUpper.to_string());
557         }
558         Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => {
559             return Generic(format!("{:#}", path.print()));
560         }
561         Res::SelfTy(..) | Res::Def(DefKind::TyParam | DefKind::AssocTy, _) => true,
562         _ => false,
563     };
564     let did = register_res(&*cx, path.res);
565     ResolvedPath { path, param_names: None, did, is_generic }
566 }
567
568 pub fn get_auto_trait_and_blanket_impls(
569     cx: &DocContext<'tcx>,
570     ty: Ty<'tcx>,
571     param_env_def_id: DefId,
572 ) -> impl Iterator<Item = Item> {
573     AutoTraitFinder::new(cx)
574         .get_auto_trait_impls(ty, param_env_def_id)
575         .into_iter()
576         .chain(BlanketImplFinder::new(cx).get_blanket_impls(ty, param_env_def_id))
577 }
578
579 pub fn register_res(cx: &DocContext<'_>, res: Res) -> DefId {
580     debug!("register_res({:?})", res);
581
582     let (did, kind) = match res {
583         Res::Def(DefKind::Fn, i) => (i, TypeKind::Function),
584         Res::Def(DefKind::TyAlias, i) => (i, TypeKind::Typedef),
585         Res::Def(DefKind::Enum, i) => (i, TypeKind::Enum),
586         Res::Def(DefKind::Trait, i) => (i, TypeKind::Trait),
587         Res::Def(DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst, i) => {
588             (cx.tcx.parent(i).unwrap(), TypeKind::Trait)
589         }
590         Res::Def(DefKind::Struct, i) => (i, TypeKind::Struct),
591         Res::Def(DefKind::Union, i) => (i, TypeKind::Union),
592         Res::Def(DefKind::Mod, i) => (i, TypeKind::Module),
593         Res::Def(DefKind::ForeignTy, i) => (i, TypeKind::Foreign),
594         Res::Def(DefKind::Const, i) => (i, TypeKind::Const),
595         Res::Def(DefKind::Static, i) => (i, TypeKind::Static),
596         Res::Def(DefKind::Variant, i) => {
597             (cx.tcx.parent(i).expect("cannot get parent def id"), TypeKind::Enum)
598         }
599         Res::Def(DefKind::Macro(mac_kind), i) => match mac_kind {
600             MacroKind::Bang => (i, TypeKind::Macro),
601             MacroKind::Attr => (i, TypeKind::Attr),
602             MacroKind::Derive => (i, TypeKind::Derive),
603         },
604         Res::Def(DefKind::TraitAlias, i) => (i, TypeKind::TraitAlias),
605         Res::SelfTy(Some(def_id), _) => (def_id, TypeKind::Trait),
606         Res::SelfTy(_, Some((impl_def_id, _))) => return impl_def_id,
607         _ => return res.def_id(),
608     };
609     if did.is_local() {
610         return did;
611     }
612     inline::record_extern_fqn(cx, did, kind);
613     if let TypeKind::Trait = kind {
614         inline::record_extern_trait(cx, did);
615     }
616     did
617 }
618
619 pub fn resolve_use_source(cx: &DocContext<'_>, path: Path) -> ImportSource {
620     ImportSource {
621         did: if path.res.opt_def_id().is_none() { None } else { Some(register_res(cx, path.res)) },
622         path,
623     }
624 }
625
626 pub fn enter_impl_trait<F, R>(cx: &DocContext<'_>, f: F) -> R
627 where
628     F: FnOnce() -> R,
629 {
630     let old_bounds = mem::take(&mut *cx.impl_trait_bounds.borrow_mut());
631     let r = f();
632     assert!(cx.impl_trait_bounds.borrow().is_empty());
633     *cx.impl_trait_bounds.borrow_mut() = old_bounds;
634     r
635 }