]> git.proxmox.com Git - rustc.git/blob - src/librustdoc/clean/inline.rs
Imported Upstream version 1.0.0~beta.3
[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::ast_util;
17 use syntax::attr::AttrMetaMethods;
18
19 use rustc::metadata::csearch;
20 use rustc::metadata::decoder;
21 use rustc::middle::def;
22 use rustc::middle::ty;
23 use rustc::middle::subst;
24 use rustc::middle::stability;
25
26 use core::DocContext;
27 use doctree;
28 use clean;
29
30 use super::Clean;
31
32 /// Attempt to inline the definition of a local node id into this AST.
33 ///
34 /// This function will fetch the definition of the id specified, and if it is
35 /// from another crate it will attempt to inline the documentation from the
36 /// other crate into this crate.
37 ///
38 /// This is primarily used for `pub use` statements which are, in general,
39 /// implementation details. Inlining the documentation should help provide a
40 /// better experience when reading the documentation in this use case.
41 ///
42 /// The returned value is `None` if the `id` could not be inlined, and `Some`
43 /// of a vector of items if it was successfully expanded.
44 pub fn try_inline(cx: &DocContext, id: ast::NodeId, into: Option<ast::Ident>)
45 -> Option<Vec<clean::Item>> {
46 let tcx = match cx.tcx_opt() {
47 Some(tcx) => tcx,
48 None => return None,
49 };
50 let def = match tcx.def_map.borrow().get(&id) {
51 Some(d) => d.full_def(),
52 None => return None,
53 };
54 let did = def.def_id();
55 if ast_util::is_local(did) { return None }
56 try_inline_def(cx, tcx, def).map(|vec| {
57 vec.into_iter().map(|mut item| {
58 match into {
59 Some(into) if item.name.is_some() => {
60 item.name = Some(into.clean(cx));
61 }
62 _ => {}
63 }
64 item
65 }).collect()
66 })
67 }
68
69 fn try_inline_def(cx: &DocContext, tcx: &ty::ctxt,
70 def: def::Def) -> Option<Vec<clean::Item>> {
71 let mut ret = Vec::new();
72 let did = def.def_id();
73 let inner = match def {
74 def::DefTrait(did) => {
75 record_extern_fqn(cx, did, clean::TypeTrait);
76 clean::TraitItem(build_external_trait(cx, tcx, did))
77 }
78 def::DefFn(did, false) => {
79 // If this function is a tuple struct constructor, we just skip it
80 record_extern_fqn(cx, did, clean::TypeFunction);
81 clean::FunctionItem(build_external_function(cx, tcx, did))
82 }
83 def::DefStruct(did) => {
84 record_extern_fqn(cx, did, clean::TypeStruct);
85 ret.extend(build_impls(cx, tcx, did).into_iter());
86 clean::StructItem(build_struct(cx, tcx, did))
87 }
88 def::DefTy(did, false) => {
89 record_extern_fqn(cx, did, clean::TypeTypedef);
90 ret.extend(build_impls(cx, tcx, did).into_iter());
91 build_type(cx, tcx, did)
92 }
93 def::DefTy(did, true) => {
94 record_extern_fqn(cx, did, clean::TypeEnum);
95 ret.extend(build_impls(cx, tcx, did).into_iter());
96 build_type(cx, tcx, did)
97 }
98 // Assume that the enum type is reexported next to the variant, and
99 // variants don't show up in documentation specially.
100 def::DefVariant(..) => return Some(Vec::new()),
101 def::DefMod(did) => {
102 record_extern_fqn(cx, did, clean::TypeModule);
103 clean::ModuleItem(build_module(cx, tcx, did))
104 }
105 def::DefStatic(did, mtbl) => {
106 record_extern_fqn(cx, did, clean::TypeStatic);
107 clean::StaticItem(build_static(cx, tcx, did, mtbl))
108 }
109 def::DefConst(did) => {
110 record_extern_fqn(cx, did, clean::TypeConst);
111 clean::ConstantItem(build_const(cx, tcx, did))
112 }
113 _ => return None,
114 };
115 let fqn = csearch::get_item_path(tcx, did);
116 cx.inlined.borrow_mut().as_mut().unwrap().insert(did);
117 ret.push(clean::Item {
118 source: clean::Span::empty(),
119 name: Some(fqn.last().unwrap().to_string()),
120 attrs: load_attrs(cx, tcx, did),
121 inner: inner,
122 visibility: Some(ast::Public),
123 stability: stability::lookup(tcx, did).clean(cx),
124 def_id: did,
125 });
126 Some(ret)
127 }
128
129 pub fn load_attrs(cx: &DocContext, tcx: &ty::ctxt,
130 did: ast::DefId) -> Vec<clean::Attribute> {
131 let attrs = csearch::get_item_attrs(&tcx.sess.cstore, did);
132 attrs.into_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: ast::DefId, kind: clean::TypeKind) {
140 match cx.tcx_opt() {
141 Some(tcx) => {
142 let fqn = csearch::get_item_path(tcx, 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: ast::DefId) -> clean::Trait {
152 let def = ty::lookup_trait_def(tcx, did);
153 let trait_items = ty::trait_items(tcx, did).clean(cx);
154 let predicates = ty::lookup_predicates(tcx, 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: ast::DefId) -> clean::Function {
167 let t = ty::lookup_item_type(tcx, did);
168 let (decl, style, abi) = match t.ty.sty {
169 ty::ty_bare_fn(_, ref f) => ((did, &f.sig).clean(cx), f.unsafety, f.abi),
170 _ => panic!("bad function"),
171 };
172 let predicates = ty::lookup_predicates(tcx, did);
173 clean::Function {
174 decl: decl,
175 generics: (&t.generics, &predicates, subst::FnSpace).clean(cx),
176 unsafety: style,
177 abi: abi,
178 }
179 }
180
181 fn build_struct(cx: &DocContext, tcx: &ty::ctxt, did: ast::DefId) -> clean::Struct {
182 use syntax::parse::token::special_idents::unnamed_field;
183
184 let t = ty::lookup_item_type(tcx, did);
185 let predicates = ty::lookup_predicates(tcx, did);
186 let fields = ty::lookup_struct_fields(tcx, did);
187
188 clean::Struct {
189 struct_type: match &*fields {
190 [] => doctree::Unit,
191 [ref f] if f.name == unnamed_field.name => doctree::Newtype,
192 [ref f, ..] if f.name == unnamed_field.name => doctree::Tuple,
193 _ => doctree::Plain,
194 },
195 generics: (&t.generics, &predicates, subst::TypeSpace).clean(cx),
196 fields: fields.clean(cx),
197 fields_stripped: false,
198 }
199 }
200
201 fn build_type(cx: &DocContext, tcx: &ty::ctxt, did: ast::DefId) -> clean::ItemEnum {
202 let t = ty::lookup_item_type(tcx, did);
203 let predicates = ty::lookup_predicates(tcx, did);
204 match t.ty.sty {
205 ty::ty_enum(edid, _) if !csearch::is_typedef(&tcx.sess.cstore, did) => {
206 return clean::EnumItem(clean::Enum {
207 generics: (&t.generics, &predicates, subst::TypeSpace).clean(cx),
208 variants_stripped: false,
209 variants: ty::enum_variants(tcx, edid).clean(cx),
210 })
211 }
212 _ => {}
213 }
214
215 clean::TypedefItem(clean::Typedef {
216 type_: t.ty.clean(cx),
217 generics: (&t.generics, &predicates, subst::TypeSpace).clean(cx),
218 })
219 }
220
221 fn build_impls(cx: &DocContext, tcx: &ty::ctxt,
222 did: ast::DefId) -> Vec<clean::Item> {
223 ty::populate_implementations_for_type_if_necessary(tcx, did);
224 let mut impls = Vec::new();
225
226 match tcx.inherent_impls.borrow().get(&did) {
227 None => {}
228 Some(i) => {
229 impls.extend(i.iter().map(|&did| { build_impl(cx, tcx, did) }));
230 }
231 }
232
233 // If this is the first time we've inlined something from this crate, then
234 // we inline *all* impls from the crate into this crate. Note that there's
235 // currently no way for us to filter this based on type, and we likely need
236 // many impls for a variety of reasons.
237 //
238 // Primarily, the impls will be used to populate the documentation for this
239 // type being inlined, but impls can also be used when generating
240 // documentation for primitives (no way to find those specifically).
241 if cx.populated_crate_impls.borrow_mut().insert(did.krate) {
242 csearch::each_top_level_item_of_crate(&tcx.sess.cstore,
243 did.krate,
244 |def, _, _| {
245 populate_impls(cx, tcx, def, &mut impls)
246 });
247
248 fn populate_impls(cx: &DocContext, tcx: &ty::ctxt,
249 def: decoder::DefLike,
250 impls: &mut Vec<Option<clean::Item>>) {
251 match def {
252 decoder::DlImpl(did) => impls.push(build_impl(cx, tcx, did)),
253 decoder::DlDef(def::DefMod(did)) => {
254 csearch::each_child_of_item(&tcx.sess.cstore,
255 did,
256 |def, _, _| {
257 populate_impls(cx, tcx, def, impls)
258 })
259 }
260 _ => {}
261 }
262 }
263 }
264
265 impls.into_iter().filter_map(|a| a).collect()
266 }
267
268 fn build_impl(cx: &DocContext,
269 tcx: &ty::ctxt,
270 did: ast::DefId) -> Option<clean::Item> {
271 if !cx.inlined.borrow_mut().as_mut().unwrap().insert(did) {
272 return None
273 }
274
275 let attrs = load_attrs(cx, tcx, did);
276 let associated_trait = csearch::get_impl_trait(tcx, did);
277 if let Some(ref t) = associated_trait {
278 // If this is an impl for a #[doc(hidden)] trait, be sure to not inline
279 let trait_attrs = load_attrs(cx, tcx, t.def_id);
280 if trait_attrs.iter().any(|a| is_doc_hidden(a)) {
281 return None
282 }
283 }
284
285 // If this is a defaulted impl, then bail out early here
286 if csearch::is_default_impl(&tcx.sess.cstore, did) {
287 return Some(clean::Item {
288 inner: clean::DefaultImplItem(clean::DefaultImpl {
289 // FIXME: this should be decoded
290 unsafety: ast::Unsafety::Normal,
291 trait_: match associated_trait.as_ref().unwrap().clean(cx) {
292 clean::TraitBound(polyt, _) => polyt.trait_,
293 clean::RegionBound(..) => unreachable!(),
294 },
295 }),
296 source: clean::Span::empty(),
297 name: None,
298 attrs: attrs,
299 visibility: Some(ast::Inherited),
300 stability: stability::lookup(tcx, did).clean(cx),
301 def_id: did,
302 });
303 }
304
305 let predicates = ty::lookup_predicates(tcx, did);
306 let trait_items = csearch::get_impl_items(&tcx.sess.cstore, did)
307 .iter()
308 .filter_map(|did| {
309 let did = did.def_id();
310 let impl_item = ty::impl_or_trait_item(tcx, did);
311 match impl_item {
312 ty::MethodTraitItem(method) => {
313 if method.vis != ast::Public && associated_trait.is_none() {
314 return None
315 }
316 if method.provided_source.is_some() {
317 return None
318 }
319 let mut item = method.clean(cx);
320 item.inner = match item.inner.clone() {
321 clean::TyMethodItem(clean::TyMethod {
322 unsafety, decl, self_, generics, abi
323 }) => {
324 clean::MethodItem(clean::Method {
325 unsafety: unsafety,
326 decl: decl,
327 self_: self_,
328 generics: generics,
329 abi: abi
330 })
331 }
332 _ => panic!("not a tymethod"),
333 };
334 Some(item)
335 }
336 ty::TypeTraitItem(ref assoc_ty) => {
337 let did = assoc_ty.def_id;
338 let type_scheme = ty::lookup_item_type(tcx, did);
339 let predicates = ty::lookup_predicates(tcx, did);
340 // Not sure the choice of ParamSpace actually matters here,
341 // because an associated type won't have generics on the LHS
342 let typedef = (type_scheme, predicates,
343 subst::ParamSpace::TypeSpace).clean(cx);
344 Some(clean::Item {
345 name: Some(assoc_ty.name.clean(cx)),
346 inner: clean::TypedefItem(typedef),
347 source: clean::Span::empty(),
348 attrs: vec![],
349 visibility: None,
350 stability: stability::lookup(tcx, did).clean(cx),
351 def_id: did
352 })
353 }
354 }
355 }).collect();
356 let polarity = csearch::get_impl_polarity(tcx, did);
357 let ty = ty::lookup_item_type(tcx, did);
358 return Some(clean::Item {
359 inner: clean::ImplItem(clean::Impl {
360 unsafety: ast::Unsafety::Normal, // FIXME: this should be decoded
361 derived: clean::detect_derived(&attrs),
362 trait_: associated_trait.clean(cx).map(|bound| {
363 match bound {
364 clean::TraitBound(polyt, _) => polyt.trait_,
365 clean::RegionBound(..) => unreachable!(),
366 }
367 }),
368 for_: ty.ty.clean(cx),
369 generics: (&ty.generics, &predicates, subst::TypeSpace).clean(cx),
370 items: trait_items,
371 polarity: polarity.map(|p| { p.clean(cx) }),
372 }),
373 source: clean::Span::empty(),
374 name: None,
375 attrs: attrs,
376 visibility: Some(ast::Inherited),
377 stability: stability::lookup(tcx, did).clean(cx),
378 def_id: did,
379 });
380
381 fn is_doc_hidden(a: &clean::Attribute) -> bool {
382 match *a {
383 clean::List(ref name, ref inner) if *name == "doc" => {
384 inner.iter().any(|a| {
385 match *a {
386 clean::Word(ref s) => *s == "hidden",
387 _ => false,
388 }
389 })
390 }
391 _ => false
392 }
393 }
394 }
395
396 fn build_module(cx: &DocContext, tcx: &ty::ctxt,
397 did: ast::DefId) -> clean::Module {
398 let mut items = Vec::new();
399 fill_in(cx, tcx, did, &mut items);
400 return clean::Module {
401 items: items,
402 is_crate: false,
403 };
404
405 fn fill_in(cx: &DocContext, tcx: &ty::ctxt, did: ast::DefId,
406 items: &mut Vec<clean::Item>) {
407 // If we're reexporting a reexport it may actually reexport something in
408 // two namespaces, so the target may be listed twice. Make sure we only
409 // visit each node at most once.
410 let mut visited = HashSet::new();
411 csearch::each_child_of_item(&tcx.sess.cstore, did, |def, _, vis| {
412 match def {
413 decoder::DlDef(def::DefForeignMod(did)) => {
414 fill_in(cx, tcx, did, items);
415 }
416 decoder::DlDef(def) if vis == ast::Public => {
417 if !visited.insert(def) { return }
418 match try_inline_def(cx, tcx, def) {
419 Some(i) => items.extend(i.into_iter()),
420 None => {}
421 }
422 }
423 decoder::DlDef(..) => {}
424 // All impls were inlined above
425 decoder::DlImpl(..) => {}
426 decoder::DlField => panic!("unimplemented field"),
427 }
428 });
429 }
430 }
431
432 fn build_const(cx: &DocContext, tcx: &ty::ctxt,
433 did: ast::DefId) -> clean::Constant {
434 use rustc::middle::const_eval;
435 use syntax::print::pprust;
436
437 let expr = const_eval::lookup_const_by_id(tcx, did).unwrap_or_else(|| {
438 panic!("expected lookup_const_by_id to succeed for {:?}", did);
439 });
440 debug!("converting constant expr {:?} to snippet", expr);
441 let sn = pprust::expr_to_string(expr);
442 debug!("got snippet {}", sn);
443
444 clean::Constant {
445 type_: ty::lookup_item_type(tcx, did).ty.clean(cx),
446 expr: sn
447 }
448 }
449
450 fn build_static(cx: &DocContext, tcx: &ty::ctxt,
451 did: ast::DefId,
452 mutable: bool) -> clean::Static {
453 clean::Static {
454 type_: ty::lookup_item_type(tcx, did).ty.clean(cx),
455 mutability: if mutable {clean::Mutable} else {clean::Immutable},
456 expr: "\n\n\n".to_string(), // trigger the "[definition]" links
457 }
458 }
459
460 /// A trait's generics clause actually contains all of the predicates for all of
461 /// its associated types as well. We specifically move these clauses to the
462 /// associated types instead when displaying, so when we're genering the
463 /// generics for the trait itself we need to be sure to remove them.
464 ///
465 /// The inverse of this filtering logic can be found in the `Clean`
466 /// implementation for `AssociatedType`
467 fn filter_non_trait_generics(trait_did: ast::DefId, mut g: clean::Generics)
468 -> clean::Generics {
469 g.where_predicates.retain(|pred| {
470 match *pred {
471 clean::WherePredicate::BoundPredicate {
472 ty: clean::QPath {
473 self_type: box clean::Generic(ref s),
474 trait_: box clean::ResolvedPath { did, .. },
475 name: ref _name,
476 }, ..
477 } => *s != "Self" || did != trait_did,
478 _ => true,
479 }
480 });
481 return g;
482 }
483
484 /// Supertrait bounds for a trait are also listed in the generics coming from
485 /// the metadata for a crate, so we want to separate those out and create a new
486 /// list of explicit supertrait bounds to render nicely.
487 fn separate_supertrait_bounds(mut g: clean::Generics)
488 -> (clean::Generics, Vec<clean::TyParamBound>) {
489 let mut ty_bounds = Vec::new();
490 g.where_predicates.retain(|pred| {
491 match *pred {
492 clean::WherePredicate::BoundPredicate {
493 ty: clean::Generic(ref s),
494 ref bounds
495 } if *s == "Self" => {
496 ty_bounds.extend(bounds.iter().cloned());
497 false
498 }
499 _ => true,
500 }
501 });
502 (g, ty_bounds)
503 }