]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/inline.rs
Auto merge of #31010 - petrochenkov:def, r=arielb1
[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::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) -> 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             clean::TraitItem(build_external_trait(cx, tcx, did))
78         }
79         Def::Fn(did) => {
80             record_extern_fqn(cx, did, clean::TypeFunction);
81             clean::FunctionItem(build_external_function(cx, tcx, did))
82         }
83         Def::Struct(did)
84                 // If this is a struct constructor, we skip it
85                 if tcx.sess.cstore.tuple_struct_definition_if_ctor(did).is_none() => {
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::TyAlias(did) => {
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::Enum(did) => {
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::Variant(..) => return Some(Vec::new()),
103         Def::Mod(did) => {
104             record_extern_fqn(cx, did, clean::TypeModule);
105             clean::ModuleItem(build_module(cx, tcx, did))
106         }
107         Def::Static(did, mtbl) => {
108             record_extern_fqn(cx, did, clean::TypeStatic);
109             clean::StaticItem(build_static(cx, tcx, did, mtbl))
110         }
111         Def::Const(did) | Def::AssociatedConst(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_stability(tcx, did).clean(cx),
125         deprecation: stability::lookup_deprecation(tcx, did).clean(cx),
126         def_id: did,
127     });
128     Some(ret)
129 }
130
131 pub fn load_attrs(cx: &DocContext, tcx: &ty::ctxt,
132                   did: DefId) -> Vec<clean::Attribute> {
133     tcx.get_attrs(did).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 = tcx.sess.cstore.extern_item_path(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
174     let constness = if tcx.sess.cstore.is_const_fn(did) {
175         hir::Constness::Const
176     } else {
177         hir::Constness::NotConst
178     };
179
180     let predicates = tcx.lookup_predicates(did);
181     clean::Function {
182         decl: decl,
183         generics: (&t.generics, &predicates, subst::FnSpace).clean(cx),
184         unsafety: style,
185         constness: constness,
186         abi: abi,
187     }
188 }
189
190 fn build_struct(cx: &DocContext, tcx: &ty::ctxt, did: DefId) -> clean::Struct {
191     use syntax::parse::token::special_idents::unnamed_field;
192
193     let t = tcx.lookup_item_type(did);
194     let predicates = tcx.lookup_predicates(did);
195     let variant = tcx.lookup_adt_def(did).struct_variant();
196
197     clean::Struct {
198         struct_type: match &*variant.fields {
199             [] => doctree::Unit,
200             [ref f] if f.name == unnamed_field.name => doctree::Newtype,
201             [ref f, ..] if f.name == unnamed_field.name => doctree::Tuple,
202             _ => doctree::Plain,
203         },
204         generics: (&t.generics, &predicates, subst::TypeSpace).clean(cx),
205         fields: variant.fields.clean(cx),
206         fields_stripped: false,
207     }
208 }
209
210 fn build_type(cx: &DocContext, tcx: &ty::ctxt, did: DefId) -> clean::ItemEnum {
211     let t = tcx.lookup_item_type(did);
212     let predicates = tcx.lookup_predicates(did);
213     match t.ty.sty {
214         ty::TyEnum(edef, _) if !tcx.sess.cstore.is_typedef(did) => {
215             return clean::EnumItem(clean::Enum {
216                 generics: (&t.generics, &predicates, subst::TypeSpace).clean(cx),
217                 variants_stripped: false,
218                 variants: edef.variants.clean(cx),
219             })
220         }
221         _ => {}
222     }
223
224     clean::TypedefItem(clean::Typedef {
225         type_: t.ty.clean(cx),
226         generics: (&t.generics, &predicates, subst::TypeSpace).clean(cx),
227     }, false)
228 }
229
230 pub fn build_impls(cx: &DocContext, tcx: &ty::ctxt,
231                    did: DefId) -> Vec<clean::Item> {
232     tcx.populate_inherent_implementations_for_type_if_necessary(did);
233     let mut impls = Vec::new();
234
235     match tcx.inherent_impls.borrow().get(&did) {
236         None => {}
237         Some(i) => {
238             for &did in i.iter() {
239                 build_impl(cx, tcx, did, &mut impls);
240             }
241         }
242     }
243
244     // If this is the first time we've inlined something from this crate, then
245     // we inline *all* impls from the crate into this crate. Note that there's
246     // currently no way for us to filter this based on type, and we likely need
247     // many impls for a variety of reasons.
248     //
249     // Primarily, the impls will be used to populate the documentation for this
250     // type being inlined, but impls can also be used when generating
251     // documentation for primitives (no way to find those specifically).
252     if cx.populated_crate_impls.borrow_mut().insert(did.krate) {
253         for item in tcx.sess.cstore.crate_top_level_items(did.krate) {
254             populate_impls(cx, tcx, item.def, &mut impls);
255         }
256
257         fn populate_impls(cx: &DocContext, tcx: &ty::ctxt,
258                           def: cstore::DefLike,
259                           impls: &mut Vec<clean::Item>) {
260             match def {
261                 cstore::DlImpl(did) => build_impl(cx, tcx, did, impls),
262                 cstore::DlDef(Def::Mod(did)) => {
263                     for item in tcx.sess.cstore.item_children(did) {
264                         populate_impls(cx, tcx, item.def, impls)
265                     }
266                 }
267                 _ => {}
268             }
269         }
270     }
271
272     return impls;
273 }
274
275 pub fn build_impl(cx: &DocContext,
276                   tcx: &ty::ctxt,
277                   did: DefId,
278                   ret: &mut Vec<clean::Item>) {
279     if !cx.inlined.borrow_mut().as_mut().unwrap().insert(did) {
280         return
281     }
282
283     let attrs = load_attrs(cx, tcx, did);
284     let associated_trait = tcx.impl_trait_ref(did);
285     if let Some(ref t) = associated_trait {
286         // If this is an impl for a #[doc(hidden)] trait, be sure to not inline
287         let trait_attrs = load_attrs(cx, tcx, t.def_id);
288         if trait_attrs.iter().any(|a| is_doc_hidden(a)) {
289             return
290         }
291     }
292
293     // If this is a defaulted impl, then bail out early here
294     if tcx.sess.cstore.is_default_impl(did) {
295         return ret.push(clean::Item {
296             inner: clean::DefaultImplItem(clean::DefaultImpl {
297                 // FIXME: this should be decoded
298                 unsafety: hir::Unsafety::Normal,
299                 trait_: match associated_trait.as_ref().unwrap().clean(cx) {
300                     clean::TraitBound(polyt, _) => polyt.trait_,
301                     clean::RegionBound(..) => unreachable!(),
302                 },
303             }),
304             source: clean::Span::empty(),
305             name: None,
306             attrs: attrs,
307             visibility: Some(hir::Inherited),
308             stability: stability::lookup_stability(tcx, did).clean(cx),
309             deprecation: stability::lookup_deprecation(tcx, did).clean(cx),
310             def_id: did,
311         });
312     }
313
314     let predicates = tcx.lookup_predicates(did);
315     let trait_items = tcx.sess.cstore.impl_items(did)
316             .iter()
317             .filter_map(|did| {
318         let did = did.def_id();
319         let impl_item = tcx.impl_or_trait_item(did);
320         match impl_item {
321             ty::ConstTraitItem(ref assoc_const) => {
322                 let did = assoc_const.def_id;
323                 let type_scheme = tcx.lookup_item_type(did);
324                 let default = if assoc_const.has_value {
325                     Some(const_eval::lookup_const_by_id(tcx, did, None, None)
326                          .unwrap().span.to_src(cx))
327                 } else {
328                     None
329                 };
330                 Some(clean::Item {
331                     name: Some(assoc_const.name.clean(cx)),
332                     inner: clean::AssociatedConstItem(
333                         type_scheme.ty.clean(cx),
334                         default,
335                     ),
336                     source: clean::Span::empty(),
337                     attrs: vec![],
338                     visibility: None,
339                     stability: stability::lookup_stability(tcx, did).clean(cx),
340                     deprecation: stability::lookup_deprecation(tcx, did).clean(cx),
341                     def_id: did
342                 })
343             }
344             ty::MethodTraitItem(method) => {
345                 if method.vis != hir::Public && associated_trait.is_none() {
346                     return None
347                 }
348                 let mut item = method.clean(cx);
349                 item.inner = match item.inner.clone() {
350                     clean::TyMethodItem(clean::TyMethod {
351                         unsafety, decl, self_, generics, abi
352                     }) => {
353                         let constness = if tcx.sess.cstore.is_const_fn(did) {
354                             hir::Constness::Const
355                         } else {
356                             hir::Constness::NotConst
357                         };
358
359                         clean::MethodItem(clean::Method {
360                             unsafety: unsafety,
361                             constness: constness,
362                             decl: decl,
363                             self_: self_,
364                             generics: generics,
365                             abi: abi
366                         })
367                     }
368                     _ => panic!("not a tymethod"),
369                 };
370                 Some(item)
371             }
372             ty::TypeTraitItem(ref assoc_ty) => {
373                 let did = assoc_ty.def_id;
374                 let type_scheme = ty::TypeScheme {
375                     ty: assoc_ty.ty.unwrap(),
376                     generics: ty::Generics::empty()
377                 };
378                 // Not sure the choice of ParamSpace actually matters here,
379                 // because an associated type won't have generics on the LHS
380                 let typedef = (type_scheme, ty::GenericPredicates::empty(),
381                                subst::ParamSpace::TypeSpace).clean(cx);
382                 Some(clean::Item {
383                     name: Some(assoc_ty.name.clean(cx)),
384                     inner: clean::TypedefItem(typedef, true),
385                     source: clean::Span::empty(),
386                     attrs: vec![],
387                     visibility: None,
388                     stability: stability::lookup_stability(tcx, did).clean(cx),
389                     deprecation: stability::lookup_deprecation(tcx, did).clean(cx),
390                     def_id: did
391                 })
392             }
393         }
394     }).collect::<Vec<_>>();
395     let polarity = tcx.trait_impl_polarity(did);
396     let ty = tcx.lookup_item_type(did);
397     let trait_ = associated_trait.clean(cx).map(|bound| {
398         match bound {
399             clean::TraitBound(polyt, _) => polyt.trait_,
400             clean::RegionBound(..) => unreachable!(),
401         }
402     });
403     if let Some(clean::ResolvedPath { did, .. }) = trait_ {
404         if Some(did) == cx.deref_trait_did.get() {
405             super::build_deref_target_impls(cx, &trait_items, ret);
406         }
407     }
408     ret.push(clean::Item {
409         inner: clean::ImplItem(clean::Impl {
410             unsafety: hir::Unsafety::Normal, // FIXME: this should be decoded
411             derived: clean::detect_derived(&attrs),
412             trait_: trait_,
413             for_: ty.ty.clean(cx),
414             generics: (&ty.generics, &predicates, subst::TypeSpace).clean(cx),
415             items: trait_items,
416             polarity: polarity.map(|p| { p.clean(cx) }),
417         }),
418         source: clean::Span::empty(),
419         name: None,
420         attrs: attrs,
421         visibility: Some(hir::Inherited),
422         stability: stability::lookup_stability(tcx, did).clean(cx),
423         deprecation: stability::lookup_deprecation(tcx, did).clean(cx),
424         def_id: did,
425     });
426
427     fn is_doc_hidden(a: &clean::Attribute) -> bool {
428         match *a {
429             clean::List(ref name, ref inner) if *name == "doc" => {
430                 inner.iter().any(|a| {
431                     match *a {
432                         clean::Word(ref s) => *s == "hidden",
433                         _ => false,
434                     }
435                 })
436             }
437             _ => false
438         }
439     }
440 }
441
442 fn build_module(cx: &DocContext, tcx: &ty::ctxt,
443                 did: DefId) -> clean::Module {
444     let mut items = Vec::new();
445     fill_in(cx, tcx, did, &mut items);
446     return clean::Module {
447         items: items,
448         is_crate: false,
449     };
450
451     fn fill_in(cx: &DocContext, tcx: &ty::ctxt, did: DefId,
452                items: &mut Vec<clean::Item>) {
453         // If we're reexporting a reexport it may actually reexport something in
454         // two namespaces, so the target may be listed twice. Make sure we only
455         // visit each node at most once.
456         let mut visited = HashSet::new();
457         for item in tcx.sess.cstore.item_children(did) {
458             match item.def {
459                 cstore::DlDef(Def::ForeignMod(did)) => {
460                     fill_in(cx, tcx, did, items);
461                 }
462                 cstore::DlDef(def) if item.vis == hir::Public => {
463                     if !visited.insert(def) { continue }
464                     match try_inline_def(cx, tcx, def) {
465                         Some(i) => items.extend(i),
466                         None => {}
467                     }
468                 }
469                 cstore::DlDef(..) => {}
470                 // All impls were inlined above
471                 cstore::DlImpl(..) => {}
472                 cstore::DlField => panic!("unimplemented field"),
473             }
474         }
475     }
476 }
477
478 fn build_const(cx: &DocContext, tcx: &ty::ctxt,
479                did: DefId) -> clean::Constant {
480     use rustc::middle::const_eval;
481     use rustc_front::print::pprust;
482
483     let expr = const_eval::lookup_const_by_id(tcx, did, None, 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_: tcx.lookup_item_type(did).ty.clean(cx),
492         expr: sn
493     }
494 }
495
496 fn build_static(cx: &DocContext, tcx: &ty::ctxt,
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 }