]> git.proxmox.com Git - rustc.git/blob - src/librustdoc/clean/inline.rs
Imported Upstream version 1.9.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 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;
30 use doctree;
31 use clean::{self, Attributes, 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.inlined.borrow_mut().as_mut().unwrap().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(hir::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.external_paths.borrow_mut().as_mut().unwrap().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 // Don't recurse if this is a #[doc(hidden)] module
264 if load_attrs(cx, tcx, did).list("doc").has_word("hidden") {
265 return;
266 }
267
268 for item in tcx.sess.cstore.item_children(did) {
269 populate_impls(cx, tcx, item.def, impls)
270 }
271 }
272 _ => {}
273 }
274 }
275 }
276
277 let mut candidates = cx.all_crate_impls.borrow_mut();
278 let candidates = candidates.get_mut(&did.krate).unwrap();
279 for i in (0..candidates.len()).rev() {
280 let remove = match candidates[i].inner {
281 clean::ImplItem(ref i) => {
282 i.for_.def_id() == Some(did) || i.for_.primitive_type().is_some()
283 }
284 _ => continue,
285 };
286 if remove {
287 impls.push(candidates.swap_remove(i));
288 }
289 }
290
291 return impls;
292 }
293
294 pub fn build_impl(cx: &DocContext,
295 tcx: &TyCtxt,
296 did: DefId,
297 ret: &mut Vec<clean::Item>) {
298 if !cx.inlined.borrow_mut().as_mut().unwrap().insert(did) {
299 return
300 }
301
302 let attrs = load_attrs(cx, tcx, did);
303 let associated_trait = tcx.impl_trait_ref(did);
304 if let Some(ref t) = associated_trait {
305 // If this is an impl for a #[doc(hidden)] trait, be sure to not inline
306 let trait_attrs = load_attrs(cx, tcx, t.def_id);
307 if trait_attrs.list("doc").has_word("hidden") {
308 return
309 }
310 }
311
312 // If this is a defaulted impl, then bail out early here
313 if tcx.sess.cstore.is_default_impl(did) {
314 return ret.push(clean::Item {
315 inner: clean::DefaultImplItem(clean::DefaultImpl {
316 // FIXME: this should be decoded
317 unsafety: hir::Unsafety::Normal,
318 trait_: match associated_trait.as_ref().unwrap().clean(cx) {
319 clean::TraitBound(polyt, _) => polyt.trait_,
320 clean::RegionBound(..) => unreachable!(),
321 },
322 }),
323 source: clean::Span::empty(),
324 name: None,
325 attrs: attrs,
326 visibility: Some(hir::Inherited),
327 stability: stability::lookup_stability(tcx, did).clean(cx),
328 deprecation: stability::lookup_deprecation(tcx, did).clean(cx),
329 def_id: did,
330 });
331 }
332
333 let predicates = tcx.lookup_predicates(did);
334 let trait_items = tcx.sess.cstore.impl_items(did)
335 .iter()
336 .filter_map(|did| {
337 let did = did.def_id();
338 let impl_item = tcx.impl_or_trait_item(did);
339 match impl_item {
340 ty::ConstTraitItem(ref assoc_const) => {
341 let did = assoc_const.def_id;
342 let type_scheme = tcx.lookup_item_type(did);
343 let default = if assoc_const.has_value {
344 Some(lookup_const_by_id(tcx, did, None)
345 .unwrap().0.span.to_src(cx))
346 } else {
347 None
348 };
349 Some(clean::Item {
350 name: Some(assoc_const.name.clean(cx)),
351 inner: clean::AssociatedConstItem(
352 type_scheme.ty.clean(cx),
353 default,
354 ),
355 source: clean::Span::empty(),
356 attrs: vec![],
357 visibility: None,
358 stability: stability::lookup_stability(tcx, did).clean(cx),
359 deprecation: stability::lookup_deprecation(tcx, did).clean(cx),
360 def_id: did
361 })
362 }
363 ty::MethodTraitItem(method) => {
364 if method.vis != ty::Visibility::Public && associated_trait.is_none() {
365 return None
366 }
367 let mut item = method.clean(cx);
368 item.inner = match item.inner.clone() {
369 clean::TyMethodItem(clean::TyMethod {
370 unsafety, decl, self_, generics, abi
371 }) => {
372 let constness = if tcx.sess.cstore.is_const_fn(did) {
373 hir::Constness::Const
374 } else {
375 hir::Constness::NotConst
376 };
377
378 clean::MethodItem(clean::Method {
379 unsafety: unsafety,
380 constness: constness,
381 decl: decl,
382 self_: self_,
383 generics: generics,
384 abi: abi
385 })
386 }
387 _ => panic!("not a tymethod"),
388 };
389 Some(item)
390 }
391 ty::TypeTraitItem(ref assoc_ty) => {
392 let did = assoc_ty.def_id;
393 let type_scheme = ty::TypeScheme {
394 ty: assoc_ty.ty.unwrap(),
395 generics: ty::Generics::empty()
396 };
397 // Not sure the choice of ParamSpace actually matters here,
398 // because an associated type won't have generics on the LHS
399 let typedef = (type_scheme, ty::GenericPredicates::empty(),
400 subst::ParamSpace::TypeSpace).clean(cx);
401 Some(clean::Item {
402 name: Some(assoc_ty.name.clean(cx)),
403 inner: clean::TypedefItem(typedef, true),
404 source: clean::Span::empty(),
405 attrs: vec![],
406 visibility: None,
407 stability: stability::lookup_stability(tcx, did).clean(cx),
408 deprecation: stability::lookup_deprecation(tcx, did).clean(cx),
409 def_id: did
410 })
411 }
412 }
413 }).collect::<Vec<_>>();
414 let polarity = tcx.trait_impl_polarity(did);
415 let ty = tcx.lookup_item_type(did);
416 let trait_ = associated_trait.clean(cx).map(|bound| {
417 match bound {
418 clean::TraitBound(polyt, _) => polyt.trait_,
419 clean::RegionBound(..) => unreachable!(),
420 }
421 });
422 if trait_.def_id() == cx.deref_trait_did.get() {
423 super::build_deref_target_impls(cx, &trait_items, ret);
424 }
425
426 let provided = trait_.def_id().map(|did| {
427 cx.tcx().provided_trait_methods(did)
428 .into_iter()
429 .map(|meth| meth.name.to_string())
430 .collect()
431 }).unwrap_or(HashSet::new());
432
433 ret.push(clean::Item {
434 inner: clean::ImplItem(clean::Impl {
435 unsafety: hir::Unsafety::Normal, // FIXME: this should be decoded
436 derived: clean::detect_derived(&attrs),
437 provided_trait_methods: provided,
438 trait_: trait_,
439 for_: ty.ty.clean(cx),
440 generics: (&ty.generics, &predicates, subst::TypeSpace).clean(cx),
441 items: trait_items,
442 polarity: polarity.map(|p| { p.clean(cx) }),
443 }),
444 source: clean::Span::empty(),
445 name: None,
446 attrs: attrs,
447 visibility: Some(hir::Inherited),
448 stability: stability::lookup_stability(tcx, did).clean(cx),
449 deprecation: stability::lookup_deprecation(tcx, did).clean(cx),
450 def_id: did,
451 });
452 }
453
454 fn build_module(cx: &DocContext, tcx: &TyCtxt,
455 did: DefId) -> clean::Module {
456 let mut items = Vec::new();
457 fill_in(cx, tcx, did, &mut items);
458 return clean::Module {
459 items: items,
460 is_crate: false,
461 };
462
463 fn fill_in(cx: &DocContext, tcx: &TyCtxt, did: DefId,
464 items: &mut Vec<clean::Item>) {
465 // If we're reexporting a reexport it may actually reexport something in
466 // two namespaces, so the target may be listed twice. Make sure we only
467 // visit each node at most once.
468 let mut visited = HashSet::new();
469 for item in tcx.sess.cstore.item_children(did) {
470 match item.def {
471 cstore::DlDef(Def::ForeignMod(did)) => {
472 fill_in(cx, tcx, did, items);
473 }
474 cstore::DlDef(def) if item.vis == ty::Visibility::Public => {
475 if !visited.insert(def) { continue }
476 if let Some(i) = try_inline_def(cx, tcx, def) {
477 items.extend(i)
478 }
479 }
480 cstore::DlDef(..) => {}
481 // All impls were inlined above
482 cstore::DlImpl(..) => {}
483 cstore::DlField => panic!("unimplemented field"),
484 }
485 }
486 }
487 }
488
489 fn build_const(cx: &DocContext, tcx: &TyCtxt,
490 did: DefId) -> clean::Constant {
491 use rustc::hir::print as pprust;
492
493 let (expr, ty) = lookup_const_by_id(tcx, did, None).unwrap_or_else(|| {
494 panic!("expected lookup_const_by_id to succeed for {:?}", did);
495 });
496 debug!("converting constant expr {:?} to snippet", expr);
497 let sn = pprust::expr_to_string(expr);
498 debug!("got snippet {}", sn);
499
500 clean::Constant {
501 type_: ty.map(|t| t.clean(cx)).unwrap_or_else(|| tcx.lookup_item_type(did).ty.clean(cx)),
502 expr: sn
503 }
504 }
505
506 fn build_static(cx: &DocContext, tcx: &TyCtxt,
507 did: DefId,
508 mutable: bool) -> clean::Static {
509 clean::Static {
510 type_: tcx.lookup_item_type(did).ty.clean(cx),
511 mutability: if mutable {clean::Mutable} else {clean::Immutable},
512 expr: "\n\n\n".to_string(), // trigger the "[definition]" links
513 }
514 }
515
516 /// A trait's generics clause actually contains all of the predicates for all of
517 /// its associated types as well. We specifically move these clauses to the
518 /// associated types instead when displaying, so when we're genering the
519 /// generics for the trait itself we need to be sure to remove them.
520 ///
521 /// The inverse of this filtering logic can be found in the `Clean`
522 /// implementation for `AssociatedType`
523 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics)
524 -> clean::Generics {
525 g.where_predicates.retain(|pred| {
526 match *pred {
527 clean::WherePredicate::BoundPredicate {
528 ty: clean::QPath {
529 self_type: box clean::Generic(ref s),
530 trait_: box clean::ResolvedPath { did, .. },
531 name: ref _name,
532 }, ..
533 } => *s != "Self" || did != trait_did,
534 _ => true,
535 }
536 });
537 return g;
538 }
539
540 /// Supertrait bounds for a trait are also listed in the generics coming from
541 /// the metadata for a crate, so we want to separate those out and create a new
542 /// list of explicit supertrait bounds to render nicely.
543 fn separate_supertrait_bounds(mut g: clean::Generics)
544 -> (clean::Generics, Vec<clean::TyParamBound>) {
545 let mut ty_bounds = Vec::new();
546 g.where_predicates.retain(|pred| {
547 match *pred {
548 clean::WherePredicate::BoundPredicate {
549 ty: clean::Generic(ref s),
550 ref bounds
551 } if *s == "Self" => {
552 ty_bounds.extend(bounds.iter().cloned());
553 false
554 }
555 _ => true,
556 }
557 });
558 (g, ty_bounds)
559 }