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