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