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.
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.
11 //! Support for inlining external documentation into the current AST.
15 use syntax::attr::AttrMetaMethods;
17 use rustc::metadata::csearch;
18 use rustc::metadata::decoder;
19 use rustc::middle::def;
20 use rustc::middle::ty;
28 /// Attempt to inline the definition of a local node id into this AST.
30 /// This function will fetch the definition of the id specified, and if it is
31 /// from another crate it will attempt to inline the documentation from the
32 /// other crate into this crate.
34 /// This is primarily used for `pub use` statements which are, in general,
35 /// implementation details. Inlining the documentation should help provide a
36 /// better experience when reading the documentation in this use case.
38 /// The returned value is `None` if the `id` could not be inlined, and `Some`
39 /// of a vector of items if it was successfully expanded.
40 pub fn try_inline(id: ast::NodeId) -> Option<Vec<clean::Item>> {
41 let cx = ::ctxtkey.get().unwrap();
42 let tcx = match cx.maybe_typed {
43 core::Typed(ref tycx) => tycx,
44 core::NotTyped(_) => return None,
46 let def = match tcx.def_map.borrow().find(&id) {
50 let did = def.def_id();
51 if ast_util::is_local(did) { return None }
52 try_inline_def(&**cx, tcx, def)
55 fn try_inline_def(cx: &core::DocContext,
57 def: def::Def) -> Option<Vec<clean::Item>> {
58 let mut ret = Vec::new();
59 let did = def.def_id();
60 let inner = match def {
61 def::DefTrait(did) => {
62 record_extern_fqn(cx, did, clean::TypeTrait);
63 clean::TraitItem(build_external_trait(tcx, did))
65 def::DefFn(did, style) => {
66 // If this function is a tuple struct constructor, we just skip it
67 if csearch::get_tuple_struct_definition_if_ctor(&tcx.sess.cstore,
71 record_extern_fqn(cx, did, clean::TypeFunction);
72 clean::FunctionItem(build_external_function(tcx, did, style))
74 def::DefStruct(did) => {
75 record_extern_fqn(cx, did, clean::TypeStruct);
76 ret.extend(build_impls(cx, tcx, did).move_iter());
77 clean::StructItem(build_struct(tcx, did))
80 record_extern_fqn(cx, did, clean::TypeEnum);
81 ret.extend(build_impls(cx, tcx, did).move_iter());
84 // Assume that the enum type is reexported next to the variant, and
85 // variants don't show up in documentation specially.
86 def::DefVariant(..) => return Some(Vec::new()),
88 record_extern_fqn(cx, did, clean::TypeModule);
89 clean::ModuleItem(build_module(cx, tcx, did))
91 def::DefStatic(did, mtbl) => {
92 record_extern_fqn(cx, did, clean::TypeStatic);
93 clean::StaticItem(build_static(tcx, did, mtbl))
97 let fqn = csearch::get_item_path(tcx, did);
98 cx.inlined.borrow_mut().get_mut_ref().insert(did);
99 ret.push(clean::Item {
100 source: clean::Span::empty(),
101 name: Some(fqn.last().unwrap().to_str()),
102 attrs: load_attrs(tcx, did),
104 visibility: Some(ast::Public),
110 pub fn load_attrs(tcx: &ty::ctxt, did: ast::DefId) -> Vec<clean::Attribute> {
111 let mut attrs = Vec::new();
112 csearch::get_item_attrs(&tcx.sess.cstore, did, |v| {
113 attrs.extend(v.move_iter().map(|mut a| {
114 // FIXME this isn't quite always true, it's just true about 99% of
115 // the time when dealing with documentation. For example,
116 // this would treat doc comments of the form `#[doc = "foo"]`
118 if a.name().get() == "doc" && a.value_str().is_some() {
119 a.node.is_sugared_doc = true;
127 /// Record an external fully qualified name in the external_paths cache.
129 /// These names are used later on by HTML rendering to generate things like
130 /// source links back to the original item.
131 pub fn record_extern_fqn(cx: &core::DocContext,
133 kind: clean::TypeKind) {
134 match cx.maybe_typed {
135 core::Typed(ref tcx) => {
136 let fqn = csearch::get_item_path(tcx, did);
137 let fqn = fqn.move_iter().map(|i| i.to_str()).collect();
138 cx.external_paths.borrow_mut().get_mut_ref().insert(did, (fqn, kind));
140 core::NotTyped(..) => {}
144 pub fn build_external_trait(tcx: &ty::ctxt, did: ast::DefId) -> clean::Trait {
145 let def = ty::lookup_trait_def(tcx, did);
146 let methods = ty::trait_methods(tcx, did).clean();
147 let provided = ty::provided_trait_methods(tcx, did);
148 let mut methods = methods.move_iter().map(|meth| {
149 if provided.iter().any(|a| a.def_id == meth.def_id) {
150 clean::Provided(meth)
152 clean::Required(meth)
155 let supertraits = ty::trait_supertraits(tcx, did);
156 let mut parents = supertraits.iter().map(|i| {
158 clean::TraitBound(ty) => ty,
159 clean::RegionBound => unreachable!()
164 generics: def.generics.clean(),
165 methods: methods.collect(),
166 parents: parents.collect()
170 fn build_external_function(tcx: &ty::ctxt,
172 style: ast::FnStyle) -> clean::Function {
173 let t = ty::lookup_item_type(tcx, did);
175 decl: match ty::get(t.ty).sty {
176 ty::ty_bare_fn(ref f) => (did, &f.sig).clean(),
177 _ => fail!("bad function"),
179 generics: t.generics.clean(),
184 fn build_struct(tcx: &ty::ctxt, did: ast::DefId) -> clean::Struct {
185 use syntax::parse::token::special_idents::unnamed_field;
187 let t = ty::lookup_item_type(tcx, did);
188 let fields = ty::lookup_struct_fields(tcx, did);
191 struct_type: match fields.as_slice() {
193 [ref f] if f.name == unnamed_field.name => doctree::Newtype,
194 [ref f, ..] if f.name == unnamed_field.name => doctree::Tuple,
197 generics: t.generics.clean(),
198 fields: fields.iter().map(|f| f.clean()).collect(),
199 fields_stripped: false,
203 fn build_type(tcx: &ty::ctxt, did: ast::DefId) -> clean::ItemEnum {
204 let t = ty::lookup_item_type(tcx, did);
205 match ty::get(t.ty).sty {
206 ty::ty_enum(edid, _) if !csearch::is_typedef(&tcx.sess.cstore, did) => {
207 return clean::EnumItem(clean::Enum {
208 generics: t.generics.clean(),
209 variants_stripped: false,
210 variants: ty::enum_variants(tcx, edid).clean(),
216 clean::TypedefItem(clean::Typedef {
218 generics: t.generics.clean(),
222 fn build_impls(cx: &core::DocContext,
224 did: ast::DefId) -> Vec<clean::Item> {
225 ty::populate_implementations_for_type_if_necessary(tcx, did);
226 let mut impls = Vec::new();
228 match tcx.inherent_impls.borrow().find(&did) {
231 impls.extend(i.borrow().iter().map(|&did| { build_impl(cx, tcx, did) }));
235 // If this is the first time we've inlined something from this crate, then
236 // we inline *all* impls from the crate into this crate. Note that there's
237 // currently no way for us to filter this based on type, and we likely need
238 // many impls for a variety of reasons.
240 // Primarily, the impls will be used to populate the documentation for this
241 // type being inlined, but impls can also be used when generating
242 // documentation for primitives (no way to find those specifically).
243 if cx.populated_crate_impls.borrow_mut().insert(did.krate) {
244 csearch::each_top_level_item_of_crate(&tcx.sess.cstore,
247 populate_impls(cx, tcx, def, &mut impls)
250 fn populate_impls(cx: &core::DocContext,
252 def: decoder::DefLike,
253 impls: &mut Vec<Option<clean::Item>>) {
255 decoder::DlImpl(did) => impls.push(build_impl(cx, tcx, did)),
256 decoder::DlDef(def::DefMod(did)) => {
257 csearch::each_child_of_item(&tcx.sess.cstore,
260 populate_impls(cx, tcx, def, impls)
268 impls.move_iter().filter_map(|a| a).collect()
271 fn build_impl(cx: &core::DocContext,
273 did: ast::DefId) -> Option<clean::Item> {
274 if !cx.inlined.borrow_mut().get_mut_ref().insert(did) {
278 let associated_trait = csearch::get_impl_trait(tcx, did);
279 let attrs = load_attrs(tcx, did);
280 let ty = ty::lookup_item_type(tcx, did);
281 let methods = csearch::get_impl_methods(&tcx.sess.cstore,
282 did).iter().filter_map(|did| {
283 let method = ty::method(tcx, *did);
284 if method.vis != ast::Public && associated_trait.is_none() {
287 let mut item = ty::method(tcx, *did).clean();
288 item.inner = match item.inner.clone() {
289 clean::TyMethodItem(clean::TyMethod {
290 fn_style, decl, self_, generics
292 clean::MethodItem(clean::Method {
299 _ => fail!("not a tymethod"),
304 inner: clean::ImplItem(clean::Impl {
305 derived: clean::detect_derived(attrs.as_slice()),
306 trait_: associated_trait.clean().map(|bound| {
308 clean::TraitBound(ty) => ty,
309 clean::RegionBound => unreachable!(),
313 generics: ty.generics.clean(),
316 source: clean::Span::empty(),
319 visibility: Some(ast::Inherited),
324 fn build_module(cx: &core::DocContext, tcx: &ty::ctxt,
325 did: ast::DefId) -> clean::Module {
326 let mut items = Vec::new();
328 // FIXME: this doesn't handle reexports inside the module itself.
329 // Should they be handled?
330 csearch::each_child_of_item(&tcx.sess.cstore, did, |def, _, vis| {
331 if vis != ast::Public { return }
333 decoder::DlDef(def) => {
334 match try_inline_def(cx, tcx, def) {
335 Some(i) => items.extend(i.move_iter()),
339 // All impls were inlined above
340 decoder::DlImpl(..) => {}
341 decoder::DlField => fail!("unimplemented field"),
351 fn build_static(tcx: &ty::ctxt,
353 mutable: bool) -> clean::Static {
355 type_: ty::lookup_item_type(tcx, did).ty.clean(),
356 mutability: if mutable {clean::Mutable} else {clean::Immutable},
357 expr: "\n\n\n".to_string(), // trigger the "[definition]" links