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