]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/utils.rs
Rollup merge of #68462 - matthiaskrgr:novec, r=varkor
[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, FunctionRetTy, 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::mir::interpret::{sign_extend, ConstValue, Scalar};
13 use rustc::ty::subst::{GenericArgKind, SubstsRef};
14 use rustc::ty::{self, DefIdTree, Ty};
15 use rustc_data_structures::fx::FxHashSet;
16 use rustc_hir as hir;
17 use rustc_hir::def::{DefKind, Res};
18 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
19 use rustc_span;
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 libsyntax 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.inner {
48         ItemEnum::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.inner {
66             ItemEnum::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             inner: ItemEnum::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             inner: ItemEnum::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).clean(cx)
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 pub 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) => {
126                 lt.clean(cx).and_then(|lt| Some(GenericArg::Lifetime(lt)))
127             }
128             GenericArgKind::Type(_) if skip_self => {
129                 skip_self = false;
130                 None
131             }
132             GenericArgKind::Type(ty) => {
133                 ty_kind = Some(&ty.kind);
134                 Some(GenericArg::Type(ty.clean(cx)))
135             }
136             GenericArgKind::Const(ct) => Some(GenericArg::Const(ct.clean(cx))),
137         })
138         .collect();
139
140     match trait_did {
141         // Attempt to sugar an external path like Fn<(A, B,), C> to Fn(A, B) -> C
142         Some(did) if cx.tcx.lang_items().fn_trait_kind(did).is_some() => {
143             assert!(ty_kind.is_some());
144             let inputs = match ty_kind {
145                 Some(ty::Tuple(ref tys)) => tys.iter().map(|t| t.expect_ty().clean(cx)).collect(),
146                 _ => return GenericArgs::AngleBracketed { args, bindings },
147             };
148             let output = None;
149             // FIXME(#20299) return type comes from a projection now
150             // match types[1].kind {
151             //     ty::Tuple(ref v) if v.is_empty() => None, // -> ()
152             //     _ => Some(types[1].clean(cx))
153             // };
154             GenericArgs::Parenthesized { inputs, output }
155         }
156         _ => GenericArgs::AngleBracketed { args, bindings },
157     }
158 }
159
160 // trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
161 // from Fn<(A, B,), C> to Fn(A, B) -> C
162 pub fn external_path(
163     cx: &DocContext<'_>,
164     name: Symbol,
165     trait_did: Option<DefId>,
166     has_self: bool,
167     bindings: Vec<TypeBinding>,
168     substs: SubstsRef<'_>,
169 ) -> Path {
170     Path {
171         global: false,
172         res: Res::Err,
173         segments: vec![PathSegment {
174             name: name.to_string(),
175             args: external_generic_args(cx, trait_did, has_self, bindings, substs),
176         }],
177     }
178 }
179
180 /// The point of this function is to replace bounds with types.
181 ///
182 /// i.e. `[T, U]` when you have the following bounds: `T: Display, U: Option<T>` will return
183 /// `[Display, Option]` (we just returns the list of the types, we don't care about the
184 /// wrapped types in here).
185 pub fn get_real_types(
186     generics: &Generics,
187     arg: &Type,
188     cx: &DocContext<'_>,
189     recurse: i32,
190 ) -> FxHashSet<Type> {
191     let arg_s = arg.print().to_string();
192     let mut res = FxHashSet::default();
193     if recurse >= 10 {
194         // FIXME: remove this whole recurse thing when the recursion bug is fixed
195         return res;
196     }
197     if arg.is_full_generic() {
198         if let Some(where_pred) = generics.where_predicates.iter().find(|g| match g {
199             &WherePredicate::BoundPredicate { ref ty, .. } => ty.def_id() == arg.def_id(),
200             _ => false,
201         }) {
202             let bounds = where_pred.get_bounds().unwrap_or_else(|| &[]);
203             for bound in bounds.iter() {
204                 match *bound {
205                     GenericBound::TraitBound(ref poly_trait, _) => {
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                                     res.insert(ty);
216                                 }
217                             }
218                         }
219                     }
220                     _ => {}
221                 }
222             }
223         }
224         if let Some(bound) = generics.params.iter().find(|g| g.is_type() && g.name == arg_s) {
225             for bound in bound.get_bounds().unwrap_or_else(|| &[]) {
226                 if let Some(ty) = bound.get_trait_type() {
227                     let adds = get_real_types(generics, &ty, cx, recurse + 1);
228                     if !adds.is_empty() {
229                         res.extend(adds);
230                     } else if !ty.is_full_generic() {
231                         res.insert(ty.clone());
232                     }
233                 }
234             }
235         }
236     } else {
237         res.insert(arg.clone());
238         if let Some(gens) = arg.generics() {
239             for gen in gens.iter() {
240                 if gen.is_full_generic() {
241                     let adds = get_real_types(generics, gen, cx, recurse + 1);
242                     if !adds.is_empty() {
243                         res.extend(adds);
244                     }
245                 } else {
246                     res.insert(gen.clone());
247                 }
248             }
249         }
250     }
251     res
252 }
253
254 /// Return the full list of types when bounds have been resolved.
255 ///
256 /// i.e. `fn foo<A: Display, B: Option<A>>(x: u32, y: B)` will return
257 /// `[u32, Display, Option]`.
258 pub fn get_all_types(
259     generics: &Generics,
260     decl: &FnDecl,
261     cx: &DocContext<'_>,
262 ) -> (Vec<Type>, Vec<Type>) {
263     let mut all_types = FxHashSet::default();
264     for arg in decl.inputs.values.iter() {
265         if arg.type_.is_self_type() {
266             continue;
267         }
268         let args = get_real_types(generics, &arg.type_, cx, 0);
269         if !args.is_empty() {
270             all_types.extend(args);
271         } else {
272             all_types.insert(arg.type_.clone());
273         }
274     }
275
276     let ret_types = match decl.output {
277         FunctionRetTy::Return(ref return_type) => {
278             let mut ret = get_real_types(generics, &return_type, cx, 0);
279             if ret.is_empty() {
280                 ret.insert(return_type.clone());
281             }
282             ret.into_iter().collect()
283         }
284         _ => Vec::new(),
285     };
286     (all_types.into_iter().collect(), ret_types)
287 }
288
289 pub fn strip_type(ty: Type) -> Type {
290     match ty {
291         Type::ResolvedPath { path, param_names, did, is_generic } => {
292             Type::ResolvedPath { path: strip_path(&path), param_names, did, is_generic }
293         }
294         Type::Tuple(inner_tys) => {
295             Type::Tuple(inner_tys.iter().map(|t| strip_type(t.clone())).collect())
296         }
297         Type::Slice(inner_ty) => Type::Slice(Box::new(strip_type(*inner_ty))),
298         Type::Array(inner_ty, s) => Type::Array(Box::new(strip_type(*inner_ty)), s),
299         Type::RawPointer(m, inner_ty) => Type::RawPointer(m, Box::new(strip_type(*inner_ty))),
300         Type::BorrowedRef { lifetime, mutability, type_ } => {
301             Type::BorrowedRef { lifetime, mutability, type_: Box::new(strip_type(*type_)) }
302         }
303         Type::QPath { name, self_type, trait_ } => Type::QPath {
304             name,
305             self_type: Box::new(strip_type(*self_type)),
306             trait_: Box::new(strip_type(*trait_)),
307         },
308         _ => ty,
309     }
310 }
311
312 pub fn strip_path(path: &Path) -> Path {
313     let segments = path
314         .segments
315         .iter()
316         .map(|s| PathSegment {
317             name: s.name.clone(),
318             args: GenericArgs::AngleBracketed { args: vec![], bindings: vec![] },
319         })
320         .collect();
321
322     Path { global: path.global, res: path.res.clone(), segments }
323 }
324
325 pub fn qpath_to_string(p: &hir::QPath) -> String {
326     let segments = match *p {
327         hir::QPath::Resolved(_, ref path) => &path.segments,
328         hir::QPath::TypeRelative(_, ref segment) => return segment.ident.to_string(),
329     };
330
331     let mut s = String::new();
332     for (i, seg) in segments.iter().enumerate() {
333         if i > 0 {
334             s.push_str("::");
335         }
336         if seg.ident.name != kw::PathRoot {
337             s.push_str(&seg.ident.as_str());
338         }
339     }
340     s
341 }
342
343 pub fn build_deref_target_impls(cx: &DocContext<'_>, items: &[Item], ret: &mut Vec<Item>) {
344     use self::PrimitiveType::*;
345     let tcx = cx.tcx;
346
347     for item in items {
348         let target = match item.inner {
349             ItemEnum::TypedefItem(ref t, true) => &t.type_,
350             _ => continue,
351         };
352         let primitive = match *target {
353             ResolvedPath { did, .. } if did.is_local() => continue,
354             ResolvedPath { did, .. } => {
355                 ret.extend(inline::build_impls(cx, did, None));
356                 continue;
357             }
358             _ => match target.primitive_type() {
359                 Some(prim) => prim,
360                 None => continue,
361             },
362         };
363         let did = match primitive {
364             Isize => tcx.lang_items().isize_impl(),
365             I8 => tcx.lang_items().i8_impl(),
366             I16 => tcx.lang_items().i16_impl(),
367             I32 => tcx.lang_items().i32_impl(),
368             I64 => tcx.lang_items().i64_impl(),
369             I128 => tcx.lang_items().i128_impl(),
370             Usize => tcx.lang_items().usize_impl(),
371             U8 => tcx.lang_items().u8_impl(),
372             U16 => tcx.lang_items().u16_impl(),
373             U32 => tcx.lang_items().u32_impl(),
374             U64 => tcx.lang_items().u64_impl(),
375             U128 => tcx.lang_items().u128_impl(),
376             F32 => tcx.lang_items().f32_impl(),
377             F64 => tcx.lang_items().f64_impl(),
378             Char => tcx.lang_items().char_impl(),
379             Bool => tcx.lang_items().bool_impl(),
380             Str => tcx.lang_items().str_impl(),
381             Slice => tcx.lang_items().slice_impl(),
382             Array => tcx.lang_items().slice_impl(),
383             Tuple => None,
384             Unit => None,
385             RawPointer => tcx.lang_items().const_ptr_impl(),
386             Reference => None,
387             Fn => None,
388             Never => None,
389         };
390         if let Some(did) = did {
391             if !did.is_local() {
392                 inline::build_impl(cx, did, None, ret);
393             }
394         }
395     }
396 }
397
398 pub trait ToSource {
399     fn to_src(&self, cx: &DocContext<'_>) -> String;
400 }
401
402 impl ToSource for rustc_span::Span {
403     fn to_src(&self, cx: &DocContext<'_>) -> String {
404         debug!("converting span {:?} to snippet", self.clean(cx));
405         let sn = match cx.sess().source_map().span_to_snippet(*self) {
406             Ok(x) => x,
407             Err(_) => String::new(),
408         };
409         debug!("got snippet {}", sn);
410         sn
411     }
412 }
413
414 pub fn name_from_pat(p: &hir::Pat) -> String {
415     use rustc_hir::*;
416     debug!("trying to get a name from pattern: {:?}", p);
417
418     match p.kind {
419         PatKind::Wild => "_".to_string(),
420         PatKind::Binding(_, _, ident, _) => ident.to_string(),
421         PatKind::TupleStruct(ref p, ..) | PatKind::Path(ref p) => qpath_to_string(p),
422         PatKind::Struct(ref name, ref fields, etc) => format!(
423             "{} {{ {}{} }}",
424             qpath_to_string(name),
425             fields
426                 .iter()
427                 .map(|fp| format!("{}: {}", fp.ident, name_from_pat(&fp.pat)))
428                 .collect::<Vec<String>>()
429                 .join(", "),
430             if etc { ", .." } else { "" }
431         ),
432         PatKind::Or(ref pats) => {
433             pats.iter().map(|p| name_from_pat(&**p)).collect::<Vec<String>>().join(" | ")
434         }
435         PatKind::Tuple(ref elts, _) => format!(
436             "({})",
437             elts.iter().map(|p| name_from_pat(&**p)).collect::<Vec<String>>().join(", ")
438         ),
439         PatKind::Box(ref p) => name_from_pat(&**p),
440         PatKind::Ref(ref p, _) => name_from_pat(&**p),
441         PatKind::Lit(..) => {
442             warn!(
443                 "tried to get argument name from PatKind::Lit, \
444                   which is silly in function arguments"
445             );
446             "()".to_string()
447         }
448         PatKind::Range(..) => panic!(
449             "tried to get argument name from PatKind::Range, \
450                               which is not allowed in function arguments"
451         ),
452         PatKind::Slice(ref begin, ref mid, ref end) => {
453             let begin = begin.iter().map(|p| name_from_pat(&**p));
454             let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
455             let end = end.iter().map(|p| name_from_pat(&**p));
456             format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
457         }
458     }
459 }
460
461 pub fn print_const(cx: &DocContext<'_>, n: &ty::Const<'_>) -> String {
462     match n.val {
463         ty::ConstKind::Unevaluated(def_id, _, promoted) => {
464             let mut s = if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(def_id) {
465                 print_const_expr(cx, cx.tcx.hir().body_owned_by(hir_id))
466             } else {
467                 inline::print_inlined_const(cx, def_id)
468             };
469             if let Some(promoted) = promoted {
470                 s.push_str(&format!("::{:?}", promoted))
471             }
472             s
473         }
474         _ => {
475             let mut s = n.to_string();
476             // array lengths are obviously usize
477             if s.ends_with("usize") {
478                 let n = s.len() - "usize".len();
479                 s.truncate(n);
480                 if s.ends_with(": ") {
481                     let n = s.len() - ": ".len();
482                     s.truncate(n);
483                 }
484             }
485             s
486         }
487     }
488 }
489
490 pub fn print_evaluated_const(cx: &DocContext<'_>, def_id: DefId) -> Option<String> {
491     let value =
492         cx.tcx.const_eval_poly(def_id).ok().and_then(|value| match (value.val, &value.ty.kind) {
493             (_, ty::Ref(..)) => None,
494             (ty::ConstKind::Value(ConstValue::Scalar(_)), ty::Adt(_, _)) => None,
495             (ty::ConstKind::Value(ConstValue::Scalar(_)), _) => {
496                 Some(print_const_with_custom_print_scalar(cx, value))
497             }
498             _ => None,
499         });
500
501     value
502 }
503
504 fn format_integer_with_underscore_sep(num: &str) -> String {
505     let num_chars: Vec<_> = num.chars().collect();
506     let num_start_index = if num_chars.get(0) == Some(&'-') { 1 } else { 0 };
507
508     num_chars[..num_start_index]
509         .iter()
510         .chain(num_chars[num_start_index..].rchunks(3).rev().intersperse(&['_']).flatten())
511         .collect()
512 }
513
514 fn print_const_with_custom_print_scalar(cx: &DocContext<'_>, ct: &'tcx ty::Const<'tcx>) -> String {
515     // Use a slightly different format for integer types which always shows the actual value.
516     // For all other types, fallback to the original `pretty_print_const`.
517     match (ct.val, &ct.ty.kind) {
518         (ty::ConstKind::Value(ConstValue::Scalar(Scalar::Raw { data, .. })), ty::Uint(ui)) => {
519             format!("{}{}", format_integer_with_underscore_sep(&data.to_string()), ui.name_str())
520         }
521         (ty::ConstKind::Value(ConstValue::Scalar(Scalar::Raw { data, .. })), ty::Int(i)) => {
522             let ty = cx.tcx.lift(&ct.ty).unwrap();
523             let size = cx.tcx.layout_of(ty::ParamEnv::empty().and(ty)).unwrap().size;
524             let sign_extended_data = sign_extend(data, size) as i128;
525
526             format!(
527                 "{}{}",
528                 format_integer_with_underscore_sep(&sign_extended_data.to_string()),
529                 i.name_str()
530             )
531         }
532         _ => ct.to_string(),
533     }
534 }
535
536 pub fn is_literal_expr(cx: &DocContext<'_>, hir_id: hir::HirId) -> bool {
537     if let hir::Node::Expr(expr) = cx.tcx.hir().get(hir_id) {
538         if let hir::ExprKind::Lit(_) = &expr.kind {
539             return true;
540         }
541
542         if let hir::ExprKind::Unary(hir::UnOp::UnNeg, expr) = &expr.kind {
543             if let hir::ExprKind::Lit(_) = &expr.kind {
544                 return true;
545             }
546         }
547     }
548
549     false
550 }
551
552 pub fn print_const_expr(cx: &DocContext<'_>, body: hir::BodyId) -> String {
553     let value = &cx.tcx.hir().body(body).value;
554
555     let snippet = if !value.span.from_expansion() {
556         cx.sess().source_map().span_to_snippet(value.span).ok()
557     } else {
558         None
559     };
560
561     snippet.unwrap_or_else(|| cx.tcx.hir().hir_to_pretty_string(body.hir_id))
562 }
563
564 /// Given a type Path, resolve it to a Type using the TyCtxt
565 pub fn resolve_type(cx: &DocContext<'_>, path: Path, id: hir::HirId) -> Type {
566     if id == hir::DUMMY_HIR_ID {
567         debug!("resolve_type({:?})", path);
568     } else {
569         debug!("resolve_type({:?},{:?})", path, id);
570     }
571
572     let is_generic = match path.res {
573         Res::PrimTy(p) => match p {
574             hir::PrimTy::Str => return Primitive(PrimitiveType::Str),
575             hir::PrimTy::Bool => return Primitive(PrimitiveType::Bool),
576             hir::PrimTy::Char => return Primitive(PrimitiveType::Char),
577             hir::PrimTy::Int(int_ty) => return Primitive(int_ty.into()),
578             hir::PrimTy::Uint(uint_ty) => return Primitive(uint_ty.into()),
579             hir::PrimTy::Float(float_ty) => return Primitive(float_ty.into()),
580         },
581         Res::SelfTy(..) if path.segments.len() == 1 => {
582             return Generic(kw::SelfUpper.to_string());
583         }
584         Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => {
585             return Generic(format!("{:#}", path.print()));
586         }
587         Res::SelfTy(..) | Res::Def(DefKind::TyParam, _) | Res::Def(DefKind::AssocTy, _) => true,
588         _ => false,
589     };
590     let did = register_res(&*cx, path.res);
591     ResolvedPath { path, param_names: None, did, is_generic }
592 }
593
594 pub fn get_auto_trait_and_blanket_impls(
595     cx: &DocContext<'tcx>,
596     ty: Ty<'tcx>,
597     param_env_def_id: DefId,
598 ) -> impl Iterator<Item = Item> {
599     AutoTraitFinder::new(cx)
600         .get_auto_trait_impls(ty, param_env_def_id)
601         .into_iter()
602         .chain(BlanketImplFinder::new(cx).get_blanket_impls(ty, param_env_def_id))
603 }
604
605 pub fn register_res(cx: &DocContext<'_>, res: Res) -> DefId {
606     debug!("register_res({:?})", res);
607
608     let (did, kind) = match res {
609         Res::Def(DefKind::Fn, i) => (i, TypeKind::Function),
610         Res::Def(DefKind::TyAlias, i) => (i, TypeKind::Typedef),
611         Res::Def(DefKind::Enum, i) => (i, TypeKind::Enum),
612         Res::Def(DefKind::Trait, i) => (i, TypeKind::Trait),
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 }