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