]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/utils.rs
Make utils module public
[rust.git] / src / librustdoc / clean / utils.rs
1 use crate::core::DocContext;
2 use crate::clean::{
3     Clean, Crate, Deprecation, ExternalCrate, FnDecl, FunctionRetTy, Generic, GenericArg,
4     GenericArgs, Generics, GenericBound, GenericParamDef, GetDefId, ImportSource, Item, ItemEnum,
5     Lifetime, MacroKind, Path, PathSegment, Primitive, PrimitiveType, Region, RegionVid,
6     ResolvedPath, Span, Stability, Type, TypeBinding, TypeKind, Visibility, WherePredicate, inline,
7 };
8 use crate::clean::blanket_impl::BlanketImplFinder;
9 use crate::clean::auto_trait::AutoTraitFinder;
10
11 use rustc::hir;
12 use rustc::hir::def::{DefKind, Res};
13 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
14 use rustc::ty::{self, DefIdTree, Ty};
15 use rustc::ty::subst::{SubstsRef, GenericArgKind};
16 use rustc::util::nodemap::FxHashSet;
17 use syntax_pos;
18 use syntax_pos::symbol::{Symbol, kw, sym};
19
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 libsyntax 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         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             ModuleItem(ref mut m) => m,
66             _ => unreachable!(),
67         };
68         m.items.extend(primitives.iter().map(|&(def_id, prim, ref attrs)| {
69             Item {
70                 source: Span::empty(),
71                 name: Some(prim.to_url_str().to_string()),
72                 attrs: attrs.clone(),
73                 visibility: Public,
74                 stability: get_stability(cx, def_id),
75                 deprecation: get_deprecation(cx, def_id),
76                 def_id,
77                 inner: PrimitiveItem(prim),
78             }
79         }));
80         m.items.extend(keywords.into_iter().map(|(def_id, kw, attrs)| {
81             Item {
82                 source: Span::empty(),
83                 name: Some(kw.clone()),
84                 attrs,
85                 visibility: Public,
86                 stability: get_stability(cx, def_id),
87                 deprecation: get_deprecation(cx, def_id),
88                 def_id,
89                 inner: KeywordItem(kw),
90             }
91         }));
92     }
93
94     Crate {
95         name,
96         version: None,
97         src,
98         module: Some(module),
99         externs,
100         primitives,
101         external_traits: cx.external_traits.clone(),
102         masked_crates,
103         collapsed: false,
104     }
105 }
106
107 // extract the stability index for a node from tcx, if possible
108 pub fn get_stability(cx: &DocContext<'_>, def_id: DefId) -> Option<Stability> {
109     cx.tcx.lookup_stability(def_id).clean(cx)
110 }
111
112 pub fn get_deprecation(cx: &DocContext<'_>, def_id: DefId) -> Option<Deprecation> {
113     cx.tcx.lookup_deprecation(def_id).clean(cx)
114 }
115
116 pub fn external_generic_args(
117     cx: &DocContext<'_>,
118     trait_did: Option<DefId>,
119     has_self: bool,
120     bindings: Vec<TypeBinding>,
121     substs: SubstsRef<'_>,
122 ) -> GenericArgs {
123     let mut skip_self = has_self;
124     let mut ty_kind = None;
125     let args: Vec<_> = substs.iter().filter_map(|kind| match kind.unpack() {
126         GenericArgKind::Lifetime(lt) => {
127             lt.clean(cx).and_then(|lt| Some(GenericArg::Lifetime(lt)))
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     }).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         _ => {
157             GenericArgs::AngleBracketed { args, bindings }
158         }
159     }
160 }
161
162 // trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
163 // from Fn<(A, B,), C> to Fn(A, B) -> C
164 pub fn external_path(cx: &DocContext<'_>, name: Symbol, trait_did: Option<DefId>, has_self: bool,
165                      bindings: Vec<TypeBinding>, substs: SubstsRef<'_>) -> Path {
166     Path {
167         global: false,
168         res: Res::Err,
169         segments: vec![PathSegment {
170             name: name.to_string(),
171             args: external_generic_args(cx, trait_did, has_self, bindings, substs)
172         }],
173     }
174 }
175
176 /// The point of this function is to replace bounds with types.
177 ///
178 /// i.e. `[T, U]` when you have the following bounds: `T: Display, U: Option<T>` will return
179 /// `[Display, Option]` (we just returns the list of the types, we don't care about the
180 /// wrapped types in here).
181 pub fn get_real_types(
182     generics: &Generics,
183     arg: &Type,
184     cx: &DocContext<'_>,
185     recurse: i32,
186 ) -> FxHashSet<Type> {
187     let arg_s = arg.print().to_string();
188     let mut res = FxHashSet::default();
189     if recurse >= 10 { // FIXME: remove this whole recurse thing when the recursion bug is fixed
190         return res;
191     }
192     if arg.is_full_generic() {
193         if let Some(where_pred) = generics.where_predicates.iter().find(|g| {
194             match g {
195                 &WherePredicate::BoundPredicate { ref ty, .. } => ty.def_id() == arg.def_id(),
196                 _ => false,
197             }
198         }) {
199             let bounds = where_pred.get_bounds().unwrap_or_else(|| &[]);
200             for bound in bounds.iter() {
201                 match *bound {
202                     GenericBound::TraitBound(ref poly_trait, _) => {
203                         for x in poly_trait.generic_params.iter() {
204                             if !x.is_type() {
205                                 continue
206                             }
207                             if let Some(ty) = x.get_type() {
208                                 let adds = get_real_types(generics, &ty, cx, recurse + 1);
209                                 if !adds.is_empty() {
210                                     res.extend(adds);
211                                 } else if !ty.is_full_generic() {
212                                     res.insert(ty);
213                                 }
214                             }
215                         }
216                     }
217                     _ => {}
218                 }
219             }
220         }
221         if let Some(bound) = generics.params.iter().find(|g| {
222             g.is_type() && g.name == arg_s
223         }) {
224             for bound in bound.get_bounds().unwrap_or_else(|| &[]) {
225                 if let Some(ty) = bound.get_trait_type() {
226                     let adds = get_real_types(generics, &ty, cx, recurse + 1);
227                     if !adds.is_empty() {
228                         res.extend(adds);
229                     } else if !ty.is_full_generic() {
230                         res.insert(ty.clone());
231                     }
232                 }
233             }
234         }
235     } else {
236         res.insert(arg.clone());
237         if let Some(gens) = arg.generics() {
238             for gen in gens.iter() {
239                 if gen.is_full_generic() {
240                     let adds = get_real_types(generics, gen, cx, recurse + 1);
241                     if !adds.is_empty() {
242                         res.extend(adds);
243                     }
244                 } else {
245                     res.insert(gen.clone());
246                 }
247             }
248         }
249     }
250     res
251 }
252
253 /// Return the full list of types when bounds have been resolved.
254 ///
255 /// i.e. `fn foo<A: Display, B: Option<A>>(x: u32, y: B)` will return
256 /// `[u32, Display, Option]`.
257 pub fn get_all_types(
258     generics: &Generics,
259     decl: &FnDecl,
260     cx: &DocContext<'_>,
261 ) -> (Vec<Type>, Vec<Type>) {
262     let mut all_types = FxHashSet::default();
263     for arg in decl.inputs.values.iter() {
264         if arg.type_.is_self_type() {
265             continue;
266         }
267         let args = get_real_types(generics, &arg.type_, cx, 0);
268         if !args.is_empty() {
269             all_types.extend(args);
270         } else {
271             all_types.insert(arg.type_.clone());
272         }
273     }
274
275     let ret_types = match decl.output {
276         FunctionRetTy::Return(ref return_type) => {
277             let mut ret = get_real_types(generics, &return_type, cx, 0);
278             if ret.is_empty() {
279                 ret.insert(return_type.clone());
280             }
281             ret.into_iter().collect()
282         }
283         _ => Vec::new(),
284     };
285     (all_types.into_iter().collect(), ret_types)
286 }
287
288 pub fn strip_type(ty: Type) -> Type {
289     match ty {
290         Type::ResolvedPath { path, param_names, did, is_generic } => {
291             Type::ResolvedPath { path: strip_path(&path), param_names, did, is_generic }
292         }
293         Type::Tuple(inner_tys) => {
294             Type::Tuple(inner_tys.iter().map(|t| strip_type(t.clone())).collect())
295         }
296         Type::Slice(inner_ty) => Type::Slice(Box::new(strip_type(*inner_ty))),
297         Type::Array(inner_ty, s) => Type::Array(Box::new(strip_type(*inner_ty)), s),
298         Type::RawPointer(m, inner_ty) => Type::RawPointer(m, Box::new(strip_type(*inner_ty))),
299         Type::BorrowedRef { lifetime, mutability, type_ } => {
300             Type::BorrowedRef { lifetime, mutability, type_: Box::new(strip_type(*type_)) }
301         }
302         Type::QPath { name, self_type, trait_ } => {
303             Type::QPath {
304                 name,
305                 self_type: Box::new(strip_type(*self_type)), trait_: Box::new(strip_type(*trait_))
306             }
307         }
308         _ => ty
309     }
310 }
311
312 pub fn strip_path(path: &Path) -> Path {
313     let segments = path.segments.iter().map(|s| {
314         PathSegment {
315             name: s.name.clone(),
316             args: GenericArgs::AngleBracketed {
317                 args: vec![],
318                 bindings: vec![],
319             }
320         }
321     }).collect();
322
323     Path {
324         global: path.global,
325         res: path.res.clone(),
326         segments,
327     }
328 }
329
330 pub fn qpath_to_string(p: &hir::QPath) -> String {
331     let segments = match *p {
332         hir::QPath::Resolved(_, ref path) => &path.segments,
333         hir::QPath::TypeRelative(_, ref segment) => return segment.ident.to_string(),
334     };
335
336     let mut s = String::new();
337     for (i, seg) in segments.iter().enumerate() {
338         if i > 0 {
339             s.push_str("::");
340         }
341         if seg.ident.name != kw::PathRoot {
342             s.push_str(&seg.ident.as_str());
343         }
344     }
345     s
346 }
347
348 pub fn build_deref_target_impls(cx: &DocContext<'_>,
349                                 items: &[Item],
350                                 ret: &mut Vec<Item>) {
351     use self::PrimitiveType::*;
352     let tcx = cx.tcx;
353
354     for item in items {
355         let target = match item.inner {
356             TypedefItem(ref t, true) => &t.type_,
357             _ => continue,
358         };
359         let primitive = match *target {
360             ResolvedPath { did, .. } if did.is_local() => continue,
361             ResolvedPath { did, .. } => {
362                 ret.extend(inline::build_impls(cx, did, None));
363                 continue
364             }
365             _ => match target.primitive_type() {
366                 Some(prim) => prim,
367                 None => continue,
368             }
369         };
370         let did = match primitive {
371             Isize => tcx.lang_items().isize_impl(),
372             I8 => tcx.lang_items().i8_impl(),
373             I16 => tcx.lang_items().i16_impl(),
374             I32 => tcx.lang_items().i32_impl(),
375             I64 => tcx.lang_items().i64_impl(),
376             I128 => tcx.lang_items().i128_impl(),
377             Usize => tcx.lang_items().usize_impl(),
378             U8 => tcx.lang_items().u8_impl(),
379             U16 => tcx.lang_items().u16_impl(),
380             U32 => tcx.lang_items().u32_impl(),
381             U64 => tcx.lang_items().u64_impl(),
382             U128 => tcx.lang_items().u128_impl(),
383             F32 => tcx.lang_items().f32_impl(),
384             F64 => tcx.lang_items().f64_impl(),
385             Char => tcx.lang_items().char_impl(),
386             Bool => tcx.lang_items().bool_impl(),
387             Str => tcx.lang_items().str_impl(),
388             Slice => tcx.lang_items().slice_impl(),
389             Array => tcx.lang_items().slice_impl(),
390             Tuple => None,
391             Unit => None,
392             RawPointer => tcx.lang_items().const_ptr_impl(),
393             Reference => None,
394             Fn => None,
395             Never => None,
396         };
397         if let Some(did) = did {
398             if !did.is_local() {
399                 inline::build_impl(cx, did, None, ret);
400             }
401         }
402     }
403 }
404
405 // Utilities
406
407 pub trait ToSource {
408     fn to_src(&self, cx: &DocContext<'_>) -> String;
409 }
410
411 impl ToSource for syntax_pos::Span {
412     fn to_src(&self, cx: &DocContext<'_>) -> String {
413         debug!("converting span {:?} to snippet", self.clean(cx));
414         let sn = match cx.sess().source_map().span_to_snippet(*self) {
415             Ok(x) => x,
416             Err(_) => String::new()
417         };
418         debug!("got snippet {}", sn);
419         sn
420     }
421 }
422
423 pub fn name_from_pat(p: &hir::Pat) -> String {
424     use rustc::hir::*;
425     debug!("trying to get a name from pattern: {:?}", p);
426
427     match p.kind {
428         PatKind::Wild => "_".to_string(),
429         PatKind::Binding(_, _, ident, _) => ident.to_string(),
430         PatKind::TupleStruct(ref p, ..) | PatKind::Path(ref p) => qpath_to_string(p),
431         PatKind::Struct(ref name, ref fields, etc) => {
432             format!("{} {{ {}{} }}", qpath_to_string(name),
433                 fields.iter().map(|fp| format!("{}: {}", fp.ident, name_from_pat(&fp.pat)))
434                              .collect::<Vec<String>>().join(", "),
435                 if etc { ", .." } else { "" }
436             )
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!("({})", elts.iter().map(|p| name_from_pat(&**p))
442                                             .collect::<Vec<String>>().join(", ")),
443         PatKind::Box(ref p) => name_from_pat(&**p),
444         PatKind::Ref(ref p, _) => name_from_pat(&**p),
445         PatKind::Lit(..) => {
446             warn!("tried to get argument name from PatKind::Lit, \
447                   which is silly in function arguments");
448             "()".to_string()
449         },
450         PatKind::Range(..) => panic!("tried to get argument name from PatKind::Range, \
451                               which is not allowed in function arguments"),
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, _) => {
464             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         },
470         _ => {
471             let mut s = n.to_string();
472             // array lengths are obviously usize
473             if s.ends_with("usize") {
474                 let n = s.len() - "usize".len();
475                 s.truncate(n);
476                 if s.ends_with(": ") {
477                     let n = s.len() - ": ".len();
478                     s.truncate(n);
479                 }
480             }
481             s
482         },
483     }
484 }
485
486 pub fn print_const_expr(cx: &DocContext<'_>, body: hir::BodyId) -> String {
487     cx.tcx.hir().hir_to_pretty_string(body.hir_id)
488 }
489
490 /// Given a type Path, resolve it to a Type using the TyCtxt
491 pub fn resolve_type(cx: &DocContext<'_>,
492                     path: Path,
493                     id: hir::HirId) -> Type {
494     if id == hir::DUMMY_HIR_ID {
495         debug!("resolve_type({:?})", path);
496     } else {
497         debug!("resolve_type({:?},{:?})", path, id);
498     }
499
500     let is_generic = match path.res {
501         Res::PrimTy(p) => match p {
502             hir::Str => return Primitive(PrimitiveType::Str),
503             hir::Bool => return Primitive(PrimitiveType::Bool),
504             hir::Char => return Primitive(PrimitiveType::Char),
505             hir::Int(int_ty) => return Primitive(int_ty.into()),
506             hir::Uint(uint_ty) => return Primitive(uint_ty.into()),
507             hir::Float(float_ty) => return Primitive(float_ty.into()),
508         },
509         Res::SelfTy(..) if path.segments.len() == 1 => {
510             return Generic(kw::SelfUpper.to_string());
511         }
512         Res::Def(DefKind::TyParam, _) if path.segments.len() == 1 => {
513             return Generic(format!("{:#}", path.print()));
514         }
515         Res::SelfTy(..)
516         | Res::Def(DefKind::TyParam, _)
517         | Res::Def(DefKind::AssocTy, _) => true,
518         _ => false,
519     };
520     let did = register_res(&*cx, path.res);
521     ResolvedPath { path, param_names: None, did, is_generic }
522 }
523
524 pub fn get_auto_trait_and_blanket_impls(
525     cx: &DocContext<'tcx>,
526     ty: Ty<'tcx>,
527     param_env_def_id: DefId,
528 ) -> impl Iterator<Item = Item> {
529     AutoTraitFinder::new(cx).get_auto_trait_impls(ty, param_env_def_id).into_iter()
530         .chain(BlanketImplFinder::new(cx).get_blanket_impls(ty, param_env_def_id))
531 }
532
533 pub fn register_res(cx: &DocContext<'_>, res: Res) -> DefId {
534     debug!("register_res({:?})", res);
535
536     let (did, kind) = match res {
537         Res::Def(DefKind::Fn, i) => (i, TypeKind::Function),
538         Res::Def(DefKind::TyAlias, i) => (i, TypeKind::Typedef),
539         Res::Def(DefKind::Enum, i) => (i, TypeKind::Enum),
540         Res::Def(DefKind::Trait, i) => (i, TypeKind::Trait),
541         Res::Def(DefKind::Struct, i) => (i, TypeKind::Struct),
542         Res::Def(DefKind::Union, i) => (i, TypeKind::Union),
543         Res::Def(DefKind::Mod, i) => (i, TypeKind::Module),
544         Res::Def(DefKind::ForeignTy, i) => (i, TypeKind::Foreign),
545         Res::Def(DefKind::Const, i) => (i, TypeKind::Const),
546         Res::Def(DefKind::Static, i) => (i, TypeKind::Static),
547         Res::Def(DefKind::Variant, i) => (cx.tcx.parent(i).expect("cannot get parent def id"),
548                             TypeKind::Enum),
549         Res::Def(DefKind::Macro(mac_kind), i) => match mac_kind {
550             MacroKind::Bang => (i, TypeKind::Macro),
551             MacroKind::Attr => (i, TypeKind::Attr),
552             MacroKind::Derive => (i, TypeKind::Derive),
553         },
554         Res::Def(DefKind::TraitAlias, i) => (i, TypeKind::TraitAlias),
555         Res::SelfTy(Some(def_id), _) => (def_id, TypeKind::Trait),
556         Res::SelfTy(_, Some(impl_def_id)) => return impl_def_id,
557         _ => return res.def_id()
558     };
559     if did.is_local() { return did }
560     inline::record_extern_fqn(cx, did, kind);
561     if let TypeKind::Trait = kind {
562         inline::record_extern_trait(cx, did);
563     }
564     did
565 }
566
567 pub fn resolve_use_source(cx: &DocContext<'_>, path: Path) -> ImportSource {
568     ImportSource {
569         did: if path.res.opt_def_id().is_none() {
570             None
571         } else {
572             Some(register_res(cx, path.res))
573         },
574         path,
575     }
576 }
577
578 pub fn enter_impl_trait<F, R>(cx: &DocContext<'_>, f: F) -> R
579 where
580     F: FnOnce() -> R,
581 {
582     let old_bounds = mem::take(&mut *cx.impl_trait_bounds.borrow_mut());
583     let r = f();
584     assert!(cx.impl_trait_bounds.borrow().is_empty());
585     *cx.impl_trait_bounds.borrow_mut() = old_bounds;
586     r
587 }