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