]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/inline.rs
Changed issue number to 36105
[rust.git] / src / librustdoc / clean / inline.rs
1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Support for inlining external documentation into the current AST.
12
13 use std::collections::HashSet;
14 use std::iter::once;
15
16 use syntax::ast;
17 use rustc::hir;
18
19 use rustc::middle::cstore;
20 use rustc::hir::def::Def;
21 use rustc::hir::def_id::DefId;
22 use rustc::hir::print as pprust;
23 use rustc::ty::{self, TyCtxt};
24
25 use rustc_const_eval::lookup_const_by_id;
26
27 use core::{DocContext, DocAccessLevels};
28 use doctree;
29 use clean::{self, GetDefId};
30
31 use super::Clean;
32
33 /// Attempt to inline the definition of a local node id into this AST.
34 ///
35 /// This function will fetch the definition of the id specified, and if it is
36 /// from another crate it will attempt to inline the documentation from the
37 /// other crate into this crate.
38 ///
39 /// This is primarily used for `pub use` statements which are, in general,
40 /// implementation details. Inlining the documentation should help provide a
41 /// better experience when reading the documentation in this use case.
42 ///
43 /// The returned value is `None` if the `id` could not be inlined, and `Some`
44 /// of a vector of items if it was successfully expanded.
45 pub fn try_inline(cx: &DocContext, id: ast::NodeId, into: Option<ast::Name>)
46                   -> Option<Vec<clean::Item>> {
47     let tcx = match cx.tcx_opt() {
48         Some(tcx) => tcx,
49         None => return None,
50     };
51     let def = match tcx.expect_def_or_none(id) {
52         Some(def) => def,
53         None => return None,
54     };
55     let did = def.def_id();
56     if did.is_local() { return None }
57     try_inline_def(cx, tcx, def).map(|vec| {
58         vec.into_iter().map(|mut item| {
59             match into {
60                 Some(into) if item.name.is_some() => {
61                     item.name = Some(into.clean(cx));
62                 }
63                 _ => {}
64             }
65             item
66         }).collect()
67     })
68 }
69
70 fn try_inline_def<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
71                             def: Def) -> Option<Vec<clean::Item>> {
72     let mut ret = Vec::new();
73     let did = def.def_id();
74     let inner = match def {
75         Def::Trait(did) => {
76             record_extern_fqn(cx, did, clean::TypeTrait);
77             ret.extend(build_impls(cx, tcx, did));
78             clean::TraitItem(build_external_trait(cx, tcx, did))
79         }
80         Def::Fn(did) => {
81             record_extern_fqn(cx, did, clean::TypeFunction);
82             clean::FunctionItem(build_external_function(cx, tcx, did))
83         }
84         Def::Struct(did)
85                 // If this is a struct constructor, we skip it
86                 if tcx.sess.cstore.tuple_struct_definition_if_ctor(did).is_none() => {
87             record_extern_fqn(cx, did, clean::TypeStruct);
88             ret.extend(build_impls(cx, tcx, did));
89             clean::StructItem(build_struct(cx, tcx, did))
90         }
91         Def::TyAlias(did) => {
92             record_extern_fqn(cx, did, clean::TypeTypedef);
93             ret.extend(build_impls(cx, tcx, did));
94             build_type(cx, tcx, did)
95         }
96         Def::Enum(did) => {
97             record_extern_fqn(cx, did, clean::TypeEnum);
98             ret.extend(build_impls(cx, tcx, did));
99             build_type(cx, tcx, did)
100         }
101         // Assume that the enum type is reexported next to the variant, and
102         // variants don't show up in documentation specially.
103         Def::Variant(..) => return Some(Vec::new()),
104         Def::Mod(did) => {
105             record_extern_fqn(cx, did, clean::TypeModule);
106             clean::ModuleItem(build_module(cx, tcx, did))
107         }
108         Def::Static(did, mtbl) => {
109             record_extern_fqn(cx, did, clean::TypeStatic);
110             clean::StaticItem(build_static(cx, tcx, did, mtbl))
111         }
112         Def::Const(did) | Def::AssociatedConst(did) => {
113             record_extern_fqn(cx, did, clean::TypeConst);
114             clean::ConstantItem(build_const(cx, tcx, did))
115         }
116         _ => return None,
117     };
118     cx.renderinfo.borrow_mut().inlined.insert(did);
119     ret.push(clean::Item {
120         source: clean::Span::empty(),
121         name: Some(tcx.item_name(did).to_string()),
122         attrs: load_attrs(cx, tcx, did),
123         inner: inner,
124         visibility: Some(clean::Public),
125         stability: tcx.lookup_stability(did).clean(cx),
126         deprecation: tcx.lookup_deprecation(did).clean(cx),
127         def_id: did,
128     });
129     Some(ret)
130 }
131
132 pub fn load_attrs<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
133                             did: DefId) -> Vec<clean::Attribute> {
134     tcx.get_attrs(did).iter().map(|a| a.clean(cx)).collect()
135 }
136
137 /// Record an external fully qualified name in the external_paths cache.
138 ///
139 /// These names are used later on by HTML rendering to generate things like
140 /// source links back to the original item.
141 pub fn record_extern_fqn(cx: &DocContext, did: DefId, kind: clean::TypeKind) {
142     if let Some(tcx) = cx.tcx_opt() {
143         let crate_name = tcx.sess.cstore.crate_name(did.krate).to_string();
144         let relative = tcx.def_path(did).data.into_iter().filter_map(|elem| {
145             // extern blocks have an empty name
146             let s = elem.data.to_string();
147             if !s.is_empty() {
148                 Some(s)
149             } else {
150                 None
151             }
152         });
153         let fqn = once(crate_name).chain(relative).collect();
154         cx.renderinfo.borrow_mut().external_paths.insert(did, (fqn, kind));
155     }
156 }
157
158 pub fn build_external_trait<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
159                                       did: DefId) -> clean::Trait {
160     let def = tcx.lookup_trait_def(did);
161     let trait_items = tcx.trait_items(did).clean(cx);
162     let predicates = tcx.lookup_predicates(did);
163     let generics = (def.generics, &predicates).clean(cx);
164     let generics = filter_non_trait_generics(did, generics);
165     let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
166     clean::Trait {
167         unsafety: def.unsafety,
168         generics: generics,
169         items: trait_items,
170         bounds: supertrait_bounds,
171     }
172 }
173
174 fn build_external_function<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
175                                      did: DefId) -> clean::Function {
176     let t = tcx.lookup_item_type(did);
177     let (decl, style, abi) = match t.ty.sty {
178         ty::TyFnDef(_, _, ref f) => ((did, &f.sig).clean(cx), f.unsafety, f.abi),
179         _ => panic!("bad function"),
180     };
181
182     let constness = if tcx.sess.cstore.is_const_fn(did) {
183         hir::Constness::Const
184     } else {
185         hir::Constness::NotConst
186     };
187
188     let predicates = tcx.lookup_predicates(did);
189     clean::Function {
190         decl: decl,
191         generics: (t.generics, &predicates).clean(cx),
192         unsafety: style,
193         constness: constness,
194         abi: abi,
195     }
196 }
197
198 fn build_struct<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
199                           did: DefId) -> clean::Struct {
200     let t = tcx.lookup_item_type(did);
201     let predicates = tcx.lookup_predicates(did);
202     let variant = tcx.lookup_adt_def(did).struct_variant();
203
204     clean::Struct {
205         struct_type: match &variant.fields[..] {
206             &[] => doctree::Unit,
207             &[_] if variant.kind == ty::VariantKind::Tuple => doctree::Newtype,
208             &[..] if variant.kind == ty::VariantKind::Tuple => doctree::Tuple,
209             _ => doctree::Plain,
210         },
211         generics: (t.generics, &predicates).clean(cx),
212         fields: variant.fields.clean(cx),
213         fields_stripped: false,
214     }
215 }
216
217 fn build_type<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
218                         did: DefId) -> clean::ItemEnum {
219     let t = tcx.lookup_item_type(did);
220     let predicates = tcx.lookup_predicates(did);
221     match t.ty.sty {
222         ty::TyEnum(edef, _) if !tcx.sess.cstore.is_typedef(did) => {
223             return clean::EnumItem(clean::Enum {
224                 generics: (t.generics, &predicates).clean(cx),
225                 variants_stripped: false,
226                 variants: edef.variants.clean(cx),
227             })
228         }
229         _ => {}
230     }
231
232     clean::TypedefItem(clean::Typedef {
233         type_: t.ty.clean(cx),
234         generics: (t.generics, &predicates).clean(cx),
235     }, false)
236 }
237
238 pub fn build_impls<'a, 'tcx>(cx: &DocContext,
239                              tcx: TyCtxt<'a, 'tcx, 'tcx>,
240                              did: DefId) -> Vec<clean::Item> {
241     tcx.populate_inherent_implementations_for_type_if_necessary(did);
242     let mut impls = Vec::new();
243
244     if let Some(i) = tcx.inherent_impls.borrow().get(&did) {
245         for &did in i.iter() {
246             build_impl(cx, tcx, did, &mut impls);
247         }
248     }
249
250     // If this is the first time we've inlined something from this crate, then
251     // we inline *all* impls from the crate into this crate. Note that there's
252     // currently no way for us to filter this based on type, and we likely need
253     // many impls for a variety of reasons.
254     //
255     // Primarily, the impls will be used to populate the documentation for this
256     // type being inlined, but impls can also be used when generating
257     // documentation for primitives (no way to find those specifically).
258     if cx.populated_crate_impls.borrow_mut().insert(did.krate) {
259         for item in tcx.sess.cstore.crate_top_level_items(did.krate) {
260             populate_impls(cx, tcx, item.def, &mut impls);
261         }
262
263         fn populate_impls<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
264                                     def: cstore::DefLike,
265                                     impls: &mut Vec<clean::Item>) {
266             match def {
267                 cstore::DlImpl(did) => build_impl(cx, tcx, did, impls),
268                 cstore::DlDef(Def::Mod(did)) => {
269                     for item in tcx.sess.cstore.item_children(did) {
270                         populate_impls(cx, tcx, item.def, impls)
271                     }
272                 }
273                 _ => {}
274             }
275         }
276     }
277
278     impls
279 }
280
281 pub fn build_impl<'a, 'tcx>(cx: &DocContext,
282                             tcx: TyCtxt<'a, 'tcx, 'tcx>,
283                             did: DefId,
284                             ret: &mut Vec<clean::Item>) {
285     if !cx.renderinfo.borrow_mut().inlined.insert(did) {
286         return
287     }
288
289     let attrs = load_attrs(cx, tcx, did);
290     let associated_trait = tcx.impl_trait_ref(did);
291
292     // Only inline impl if the implemented trait is
293     // reachable in rustdoc generated documentation
294     if let Some(traitref) = associated_trait {
295         if !cx.access_levels.borrow().is_doc_reachable(traitref.def_id) {
296             return
297         }
298     }
299
300     // If this is a defaulted impl, then bail out early here
301     if tcx.sess.cstore.is_default_impl(did) {
302         return ret.push(clean::Item {
303             inner: clean::DefaultImplItem(clean::DefaultImpl {
304                 // FIXME: this should be decoded
305                 unsafety: hir::Unsafety::Normal,
306                 trait_: match associated_trait.as_ref().unwrap().clean(cx) {
307                     clean::TraitBound(polyt, _) => polyt.trait_,
308                     clean::RegionBound(..) => unreachable!(),
309                 },
310             }),
311             source: clean::Span::empty(),
312             name: None,
313             attrs: attrs,
314             visibility: Some(clean::Inherited),
315             stability: tcx.lookup_stability(did).clean(cx),
316             deprecation: tcx.lookup_deprecation(did).clean(cx),
317             def_id: did,
318         });
319     }
320
321     let ty = tcx.lookup_item_type(did);
322     let for_ = ty.ty.clean(cx);
323
324     // Only inline impl if the implementing type is
325     // reachable in rustdoc generated documentation
326     if let Some(did) = for_.def_id() {
327         if !cx.access_levels.borrow().is_doc_reachable(did) {
328             return
329         }
330     }
331
332     let predicates = tcx.lookup_predicates(did);
333     let trait_items = tcx.sess.cstore.impl_items(did)
334             .iter()
335             .filter_map(|did| {
336         let did = did.def_id();
337         let impl_item = tcx.impl_or_trait_item(did);
338         match impl_item {
339             ty::ConstTraitItem(ref assoc_const) => {
340                 let did = assoc_const.def_id;
341                 let type_scheme = tcx.lookup_item_type(did);
342                 let default = if assoc_const.has_value {
343                     Some(pprust::expr_to_string(
344                         lookup_const_by_id(tcx, did, None).unwrap().0))
345                 } else {
346                     None
347                 };
348                 Some(clean::Item {
349                     name: Some(assoc_const.name.clean(cx)),
350                     inner: clean::AssociatedConstItem(
351                         type_scheme.ty.clean(cx),
352                         default,
353                     ),
354                     source: clean::Span::empty(),
355                     attrs: vec![],
356                     visibility: None,
357                     stability: tcx.lookup_stability(did).clean(cx),
358                     deprecation: tcx.lookup_deprecation(did).clean(cx),
359                     def_id: did
360                 })
361             }
362             ty::MethodTraitItem(method) => {
363                 if method.vis != ty::Visibility::Public && associated_trait.is_none() {
364                     return None
365                 }
366                 let mut item = method.clean(cx);
367                 item.inner = match item.inner.clone() {
368                     clean::TyMethodItem(clean::TyMethod {
369                         unsafety, decl, generics, abi
370                     }) => {
371                         let constness = if tcx.sess.cstore.is_const_fn(did) {
372                             hir::Constness::Const
373                         } else {
374                             hir::Constness::NotConst
375                         };
376
377                         clean::MethodItem(clean::Method {
378                             unsafety: unsafety,
379                             constness: constness,
380                             decl: decl,
381                             generics: generics,
382                             abi: abi
383                         })
384                     }
385                     _ => panic!("not a tymethod"),
386                 };
387                 Some(item)
388             }
389             ty::TypeTraitItem(ref assoc_ty) => {
390                 let did = assoc_ty.def_id;
391                 let typedef = clean::Typedef {
392                     type_: assoc_ty.ty.unwrap().clean(cx),
393                     generics: clean::Generics {
394                         lifetimes: vec![],
395                         type_params: vec![],
396                         where_predicates: vec![]
397                     }
398                 };
399                 Some(clean::Item {
400                     name: Some(assoc_ty.name.clean(cx)),
401                     inner: clean::TypedefItem(typedef, true),
402                     source: clean::Span::empty(),
403                     attrs: vec![],
404                     visibility: None,
405                     stability: tcx.lookup_stability(did).clean(cx),
406                     deprecation: tcx.lookup_deprecation(did).clean(cx),
407                     def_id: did
408                 })
409             }
410         }
411     }).collect::<Vec<_>>();
412     let polarity = tcx.trait_impl_polarity(did);
413     let trait_ = associated_trait.clean(cx).map(|bound| {
414         match bound {
415             clean::TraitBound(polyt, _) => polyt.trait_,
416             clean::RegionBound(..) => unreachable!(),
417         }
418     });
419     if trait_.def_id() == cx.deref_trait_did.get() {
420         super::build_deref_target_impls(cx, &trait_items, ret);
421     }
422
423     let provided = trait_.def_id().map(|did| {
424         cx.tcx().provided_trait_methods(did)
425                 .into_iter()
426                 .map(|meth| meth.name.to_string())
427                 .collect()
428     }).unwrap_or(HashSet::new());
429
430     ret.push(clean::Item {
431         inner: clean::ImplItem(clean::Impl {
432             unsafety: hir::Unsafety::Normal, // FIXME: this should be decoded
433             provided_trait_methods: provided,
434             trait_: trait_,
435             for_: for_,
436             generics: (ty.generics, &predicates).clean(cx),
437             items: trait_items,
438             polarity: polarity.map(|p| { p.clean(cx) }),
439         }),
440         source: clean::Span::empty(),
441         name: None,
442         attrs: attrs,
443         visibility: Some(clean::Inherited),
444         stability: tcx.lookup_stability(did).clean(cx),
445         deprecation: tcx.lookup_deprecation(did).clean(cx),
446         def_id: did,
447     });
448 }
449
450 fn build_module<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
451                           did: DefId) -> clean::Module {
452     let mut items = Vec::new();
453     fill_in(cx, tcx, did, &mut items);
454     return clean::Module {
455         items: items,
456         is_crate: false,
457     };
458
459     fn fill_in<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
460                          did: DefId, items: &mut Vec<clean::Item>) {
461         // If we're reexporting a reexport it may actually reexport something in
462         // two namespaces, so the target may be listed twice. Make sure we only
463         // visit each node at most once.
464         let mut visited = HashSet::new();
465         for item in tcx.sess.cstore.item_children(did) {
466             match item.def {
467                 cstore::DlDef(Def::ForeignMod(did)) => {
468                     fill_in(cx, tcx, did, items);
469                 }
470                 cstore::DlDef(def) if item.vis == ty::Visibility::Public => {
471                     if !visited.insert(def) { continue }
472                     if let Some(i) = try_inline_def(cx, tcx, def) {
473                         items.extend(i)
474                     }
475                 }
476                 cstore::DlDef(..) => {}
477                 // All impls were inlined above
478                 cstore::DlImpl(..) => {}
479                 cstore::DlField => panic!("unimplemented field"),
480             }
481         }
482     }
483 }
484
485 fn build_const<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
486                          did: DefId) -> clean::Constant {
487     let (expr, ty) = lookup_const_by_id(tcx, did, None).unwrap_or_else(|| {
488         panic!("expected lookup_const_by_id to succeed for {:?}", did);
489     });
490     debug!("converting constant expr {:?} to snippet", expr);
491     let sn = pprust::expr_to_string(expr);
492     debug!("got snippet {}", sn);
493
494     clean::Constant {
495         type_: ty.map(|t| t.clean(cx)).unwrap_or_else(|| tcx.lookup_item_type(did).ty.clean(cx)),
496         expr: sn
497     }
498 }
499
500 fn build_static<'a, 'tcx>(cx: &DocContext, tcx: TyCtxt<'a, 'tcx, 'tcx>,
501                           did: DefId,
502                           mutable: bool) -> clean::Static {
503     clean::Static {
504         type_: tcx.lookup_item_type(did).ty.clean(cx),
505         mutability: if mutable {clean::Mutable} else {clean::Immutable},
506         expr: "\n\n\n".to_string(), // trigger the "[definition]" links
507     }
508 }
509
510 /// A trait's generics clause actually contains all of the predicates for all of
511 /// its associated types as well. We specifically move these clauses to the
512 /// associated types instead when displaying, so when we're genering the
513 /// generics for the trait itself we need to be sure to remove them.
514 /// We also need to remove the implied "recursive" Self: Trait bound.
515 ///
516 /// The inverse of this filtering logic can be found in the `Clean`
517 /// implementation for `AssociatedType`
518 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics)
519                              -> clean::Generics {
520     for pred in &mut g.where_predicates {
521         match *pred {
522             clean::WherePredicate::BoundPredicate {
523                 ty: clean::Generic(ref s),
524                 ref mut bounds
525             } if *s == "Self" => {
526                 bounds.retain(|bound| {
527                     match *bound {
528                         clean::TyParamBound::TraitBound(clean::PolyTrait {
529                             trait_: clean::ResolvedPath { did, .. },
530                             ..
531                         }, _) => did != trait_did,
532                         _ => true
533                     }
534                 });
535             }
536             _ => {}
537         }
538     }
539
540     g.where_predicates.retain(|pred| {
541         match *pred {
542             clean::WherePredicate::BoundPredicate {
543                 ty: clean::QPath {
544                     self_type: box clean::Generic(ref s),
545                     trait_: box clean::ResolvedPath { did, .. },
546                     name: ref _name,
547                 }, ref bounds
548             } => !(*s == "Self" && did == trait_did) && !bounds.is_empty(),
549             _ => true,
550         }
551     });
552     return g;
553 }
554
555 /// Supertrait bounds for a trait are also listed in the generics coming from
556 /// the metadata for a crate, so we want to separate those out and create a new
557 /// list of explicit supertrait bounds to render nicely.
558 fn separate_supertrait_bounds(mut g: clean::Generics)
559                               -> (clean::Generics, Vec<clean::TyParamBound>) {
560     let mut ty_bounds = Vec::new();
561     g.where_predicates.retain(|pred| {
562         match *pred {
563             clean::WherePredicate::BoundPredicate {
564                 ty: clean::Generic(ref s),
565                 ref bounds
566             } if *s == "Self" => {
567                 ty_bounds.extend(bounds.iter().cloned());
568                 false
569             }
570             _ => true,
571         }
572     });
573     (g, ty_bounds)
574 }