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