]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/inline.rs
Linkify extern crates on rustdoc pages
[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 syntax::attr::AttrMetaMethods;
18 use rustc::hir;
19
20 use rustc::middle::cstore::{self, CrateStore};
21 use rustc::hir::def::Def;
22 use rustc::hir::def_id::DefId;
23 use rustc::ty::{self, TyCtxt};
24 use rustc::ty::subst;
25 use rustc::middle::stability;
26
27 use rustc_const_eval::lookup_const_by_id;
28
29 use core::{DocContext, DocAccessLevels};
30 use doctree;
31 use clean::{self, GetDefId};
32
33 use super::{Clean, ToSource};
34
35 /// Attempt to inline the definition of a local node id into this AST.
36 ///
37 /// This function will fetch the definition of the id specified, and if it is
38 /// from another crate it will attempt to inline the documentation from the
39 /// other crate into this crate.
40 ///
41 /// This is primarily used for `pub use` statements which are, in general,
42 /// implementation details. Inlining the documentation should help provide a
43 /// better experience when reading the documentation in this use case.
44 ///
45 /// The returned value is `None` if the `id` could not be inlined, and `Some`
46 /// of a vector of items if it was successfully expanded.
47 pub fn try_inline(cx: &DocContext, id: ast::NodeId, into: Option<ast::Name>)
48                   -> Option<Vec<clean::Item>> {
49     let tcx = match cx.tcx_opt() {
50         Some(tcx) => tcx,
51         None => return None,
52     };
53     let def = match tcx.def_map.borrow().get(&id) {
54         Some(d) => d.full_def(),
55         None => return None,
56     };
57     let did = def.def_id();
58     if did.is_local() { return None }
59     try_inline_def(cx, tcx, def).map(|vec| {
60         vec.into_iter().map(|mut item| {
61             match into {
62                 Some(into) if item.name.is_some() => {
63                     item.name = Some(into.clean(cx));
64                 }
65                 _ => {}
66             }
67             item
68         }).collect()
69     })
70 }
71
72 fn try_inline_def(cx: &DocContext, tcx: &TyCtxt,
73                   def: Def) -> Option<Vec<clean::Item>> {
74     let mut ret = Vec::new();
75     let did = def.def_id();
76     let inner = match def {
77         Def::Trait(did) => {
78             record_extern_fqn(cx, did, clean::TypeTrait);
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: stability::lookup_stability(tcx, did).clean(cx),
127         deprecation: stability::lookup_deprecation(tcx, did).clean(cx),
128         def_id: did,
129     });
130     Some(ret)
131 }
132
133 pub fn load_attrs(cx: &DocContext, tcx: &TyCtxt,
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(cx: &DocContext, tcx: &TyCtxt,
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(cx: &DocContext, tcx: &TyCtxt, did: DefId) -> clean::Function {
170     let t = tcx.lookup_item_type(did);
171     let (decl, style, abi) = match t.ty.sty {
172         ty::TyFnDef(_, _, ref f) => ((did, &f.sig).clean(cx), f.unsafety, f.abi),
173         _ => panic!("bad function"),
174     };
175
176     let constness = if tcx.sess.cstore.is_const_fn(did) {
177         hir::Constness::Const
178     } else {
179         hir::Constness::NotConst
180     };
181
182     let predicates = tcx.lookup_predicates(did);
183     clean::Function {
184         decl: decl,
185         generics: (&t.generics, &predicates, subst::FnSpace).clean(cx),
186         unsafety: style,
187         constness: constness,
188         abi: abi,
189     }
190 }
191
192 fn build_struct(cx: &DocContext, tcx: &TyCtxt, did: DefId) -> clean::Struct {
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             [_] if variant.kind == ty::VariantKind::Tuple => doctree::Newtype,
201             [..] if variant.kind == ty::VariantKind::Tuple => 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: &TyCtxt, 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,
231                    tcx: &TyCtxt,
232                    did: DefId) -> Vec<clean::Item> {
233     tcx.populate_inherent_implementations_for_type_if_necessary(did);
234     let mut impls = Vec::new();
235
236     if let Some(i) = tcx.inherent_impls.borrow().get(&did) {
237         for &did in i.iter() {
238             build_impl(cx, tcx, did, &mut impls);
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.all_crate_impls.borrow_mut().contains_key(&did.krate) {
251         let mut impls = Vec::new();
252         for item in tcx.sess.cstore.crate_top_level_items(did.krate) {
253             populate_impls(cx, tcx, item.def, &mut impls);
254         }
255         cx.all_crate_impls.borrow_mut().insert(did.krate, impls);
256
257         fn populate_impls(cx: &DocContext, tcx: &TyCtxt,
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     let mut candidates = cx.all_crate_impls.borrow_mut();
273     let candidates = candidates.get_mut(&did.krate).unwrap();
274     for i in (0..candidates.len()).rev() {
275         let remove = match candidates[i].inner {
276             clean::ImplItem(ref i) => {
277                 i.for_.def_id() == Some(did) || i.for_.primitive_type().is_some()
278             }
279             _ => continue,
280         };
281         if remove {
282             impls.push(candidates.swap_remove(i));
283         }
284     }
285
286     return impls;
287 }
288
289 pub fn build_impl(cx: &DocContext,
290                   tcx: &TyCtxt,
291                   did: DefId,
292                   ret: &mut Vec<clean::Item>) {
293     if !cx.renderinfo.borrow_mut().inlined.insert(did) {
294         return
295     }
296
297     let attrs = load_attrs(cx, tcx, did);
298     let associated_trait = tcx.impl_trait_ref(did);
299
300     // Only inline impl if the implemented trait is
301     // reachable in rustdoc generated documentation
302     if let Some(traitref) = associated_trait {
303         if !cx.access_levels.borrow().is_doc_reachable(traitref.def_id) {
304             return
305         }
306     }
307
308     // If this is a defaulted impl, then bail out early here
309     if tcx.sess.cstore.is_default_impl(did) {
310         return ret.push(clean::Item {
311             inner: clean::DefaultImplItem(clean::DefaultImpl {
312                 // FIXME: this should be decoded
313                 unsafety: hir::Unsafety::Normal,
314                 trait_: match associated_trait.as_ref().unwrap().clean(cx) {
315                     clean::TraitBound(polyt, _) => polyt.trait_,
316                     clean::RegionBound(..) => unreachable!(),
317                 },
318             }),
319             source: clean::Span::empty(),
320             name: None,
321             attrs: attrs,
322             visibility: Some(clean::Inherited),
323             stability: stability::lookup_stability(tcx, did).clean(cx),
324             deprecation: stability::lookup_deprecation(tcx, did).clean(cx),
325             def_id: did,
326         });
327     }
328
329     let ty = tcx.lookup_item_type(did);
330     let for_ = ty.ty.clean(cx);
331
332     // Only inline impl if the implementing type is
333     // reachable in rustdoc generated documentation
334     if let Some(did) = for_.def_id() {
335         if !cx.access_levels.borrow().is_doc_reachable(did) {
336             return
337         }
338     }
339
340     let predicates = tcx.lookup_predicates(did);
341     let trait_items = tcx.sess.cstore.impl_items(did)
342             .iter()
343             .filter_map(|did| {
344         let did = did.def_id();
345         let impl_item = tcx.impl_or_trait_item(did);
346         match impl_item {
347             ty::ConstTraitItem(ref assoc_const) => {
348                 let did = assoc_const.def_id;
349                 let type_scheme = tcx.lookup_item_type(did);
350                 let default = if assoc_const.has_value {
351                     Some(lookup_const_by_id(tcx, did, None)
352                          .unwrap().0.span.to_src(cx))
353                 } else {
354                     None
355                 };
356                 Some(clean::Item {
357                     name: Some(assoc_const.name.clean(cx)),
358                     inner: clean::AssociatedConstItem(
359                         type_scheme.ty.clean(cx),
360                         default,
361                     ),
362                     source: clean::Span::empty(),
363                     attrs: vec![],
364                     visibility: None,
365                     stability: stability::lookup_stability(tcx, did).clean(cx),
366                     deprecation: stability::lookup_deprecation(tcx, did).clean(cx),
367                     def_id: did
368                 })
369             }
370             ty::MethodTraitItem(method) => {
371                 if method.vis != ty::Visibility::Public && associated_trait.is_none() {
372                     return None
373                 }
374                 let mut item = method.clean(cx);
375                 item.inner = match item.inner.clone() {
376                     clean::TyMethodItem(clean::TyMethod {
377                         unsafety, decl, self_, generics, abi
378                     }) => {
379                         let constness = if tcx.sess.cstore.is_const_fn(did) {
380                             hir::Constness::Const
381                         } else {
382                             hir::Constness::NotConst
383                         };
384
385                         clean::MethodItem(clean::Method {
386                             unsafety: unsafety,
387                             constness: constness,
388                             decl: decl,
389                             self_: self_,
390                             generics: generics,
391                             abi: abi
392                         })
393                     }
394                     _ => panic!("not a tymethod"),
395                 };
396                 Some(item)
397             }
398             ty::TypeTraitItem(ref assoc_ty) => {
399                 let did = assoc_ty.def_id;
400                 let type_scheme = ty::TypeScheme {
401                     ty: assoc_ty.ty.unwrap(),
402                     generics: ty::Generics::empty()
403                 };
404                 // Not sure the choice of ParamSpace actually matters here,
405                 // because an associated type won't have generics on the LHS
406                 let typedef = (type_scheme, ty::GenericPredicates::empty(),
407                                subst::ParamSpace::TypeSpace).clean(cx);
408                 Some(clean::Item {
409                     name: Some(assoc_ty.name.clean(cx)),
410                     inner: clean::TypedefItem(typedef, true),
411                     source: clean::Span::empty(),
412                     attrs: vec![],
413                     visibility: None,
414                     stability: stability::lookup_stability(tcx, did).clean(cx),
415                     deprecation: stability::lookup_deprecation(tcx, did).clean(cx),
416                     def_id: did
417                 })
418             }
419         }
420     }).collect::<Vec<_>>();
421     let polarity = tcx.trait_impl_polarity(did);
422     let trait_ = associated_trait.clean(cx).map(|bound| {
423         match bound {
424             clean::TraitBound(polyt, _) => polyt.trait_,
425             clean::RegionBound(..) => unreachable!(),
426         }
427     });
428     if trait_.def_id() == cx.deref_trait_did.get() {
429         super::build_deref_target_impls(cx, &trait_items, ret);
430     }
431
432     let provided = trait_.def_id().map(|did| {
433         cx.tcx().provided_trait_methods(did)
434                 .into_iter()
435                 .map(|meth| meth.name.to_string())
436                 .collect()
437     }).unwrap_or(HashSet::new());
438
439     ret.push(clean::Item {
440         inner: clean::ImplItem(clean::Impl {
441             unsafety: hir::Unsafety::Normal, // FIXME: this should be decoded
442             derived: clean::detect_derived(&attrs),
443             provided_trait_methods: provided,
444             trait_: trait_,
445             for_: for_,
446             generics: (&ty.generics, &predicates, subst::TypeSpace).clean(cx),
447             items: trait_items,
448             polarity: polarity.map(|p| { p.clean(cx) }),
449         }),
450         source: clean::Span::empty(),
451         name: None,
452         attrs: attrs,
453         visibility: Some(clean::Inherited),
454         stability: stability::lookup_stability(tcx, did).clean(cx),
455         deprecation: stability::lookup_deprecation(tcx, did).clean(cx),
456         def_id: did,
457     });
458 }
459
460 fn build_module(cx: &DocContext, tcx: &TyCtxt,
461                 did: DefId) -> clean::Module {
462     let mut items = Vec::new();
463     fill_in(cx, tcx, did, &mut items);
464     return clean::Module {
465         items: items,
466         is_crate: false,
467     };
468
469     fn fill_in(cx: &DocContext, tcx: &TyCtxt, did: DefId,
470                items: &mut Vec<clean::Item>) {
471         // If we're reexporting a reexport it may actually reexport something in
472         // two namespaces, so the target may be listed twice. Make sure we only
473         // visit each node at most once.
474         let mut visited = HashSet::new();
475         for item in tcx.sess.cstore.item_children(did) {
476             match item.def {
477                 cstore::DlDef(Def::ForeignMod(did)) => {
478                     fill_in(cx, tcx, did, items);
479                 }
480                 cstore::DlDef(def) if item.vis == ty::Visibility::Public => {
481                     if !visited.insert(def) { continue }
482                     if let Some(i) = try_inline_def(cx, tcx, def) {
483                         items.extend(i)
484                     }
485                 }
486                 cstore::DlDef(..) => {}
487                 // All impls were inlined above
488                 cstore::DlImpl(..) => {}
489                 cstore::DlField => panic!("unimplemented field"),
490             }
491         }
492     }
493 }
494
495 fn build_const(cx: &DocContext, tcx: &TyCtxt,
496                did: DefId) -> clean::Constant {
497     use rustc::hir::print as pprust;
498
499     let (expr, ty) = lookup_const_by_id(tcx, did, None).unwrap_or_else(|| {
500         panic!("expected lookup_const_by_id to succeed for {:?}", did);
501     });
502     debug!("converting constant expr {:?} to snippet", expr);
503     let sn = pprust::expr_to_string(expr);
504     debug!("got snippet {}", sn);
505
506     clean::Constant {
507         type_: ty.map(|t| t.clean(cx)).unwrap_or_else(|| tcx.lookup_item_type(did).ty.clean(cx)),
508         expr: sn
509     }
510 }
511
512 fn build_static(cx: &DocContext, tcx: &TyCtxt,
513                 did: DefId,
514                 mutable: bool) -> clean::Static {
515     clean::Static {
516         type_: tcx.lookup_item_type(did).ty.clean(cx),
517         mutability: if mutable {clean::Mutable} else {clean::Immutable},
518         expr: "\n\n\n".to_string(), // trigger the "[definition]" links
519     }
520 }
521
522 /// A trait's generics clause actually contains all of the predicates for all of
523 /// its associated types as well. We specifically move these clauses to the
524 /// associated types instead when displaying, so when we're genering the
525 /// generics for the trait itself we need to be sure to remove them.
526 ///
527 /// The inverse of this filtering logic can be found in the `Clean`
528 /// implementation for `AssociatedType`
529 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics)
530                              -> clean::Generics {
531     g.where_predicates.retain(|pred| {
532         match *pred {
533             clean::WherePredicate::BoundPredicate {
534                 ty: clean::QPath {
535                     self_type: box clean::Generic(ref s),
536                     trait_: box clean::ResolvedPath { did, .. },
537                     name: ref _name,
538                 }, ..
539             } => *s != "Self" || did != trait_did,
540             _ => true,
541         }
542     });
543     return g;
544 }
545
546 /// Supertrait bounds for a trait are also listed in the generics coming from
547 /// the metadata for a crate, so we want to separate those out and create a new
548 /// list of explicit supertrait bounds to render nicely.
549 fn separate_supertrait_bounds(mut g: clean::Generics)
550                               -> (clean::Generics, Vec<clean::TyParamBound>) {
551     let mut ty_bounds = Vec::new();
552     g.where_predicates.retain(|pred| {
553         match *pred {
554             clean::WherePredicate::BoundPredicate {
555                 ty: clean::Generic(ref s),
556                 ref bounds
557             } if *s == "Self" => {
558                 ty_bounds.extend(bounds.iter().cloned());
559                 false
560             }
561             _ => true,
562         }
563     });
564     (g, ty_bounds)
565 }