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::ty;
27 /// Attempt to inline the definition of a local node id into this AST.
29 /// This function will fetch the definition of the id specified, and if it is
30 /// from another crate it will attempt to inline the documentation from the
31 /// other crate into this crate.
33 /// This is primarily used for `pub use` statements which are, in general,
34 /// implementation details. Inlining the documentation should help provide a
35 /// better experience when reading the documentation in this use case.
37 /// The returned value is `None` if the `id` could not be inlined, and `Some`
38 /// of a vector of items if it was successfully expanded.
39 pub fn try_inline(id: ast::NodeId) -> Option<Vec<clean::Item>> {
40 let cx = ::ctxtkey.get().unwrap();
41 let tcx = match cx.maybe_typed {
42 core::Typed(ref tycx) => tycx,
43 core::NotTyped(_) => return None,
45 let def = match tcx.def_map.borrow().find(&id) {
49 let did = ast_util::def_id_of_def(def);
50 if ast_util::is_local(did) { return None }
51 try_inline_def(&**cx, tcx, def)
54 fn try_inline_def(cx: &core::DocContext,
56 def: ast::Def) -> Option<Vec<clean::Item>> {
57 let mut ret = Vec::new();
58 let did = ast_util::def_id_of_def(def);
59 let inner = match def {
60 ast::DefTrait(did) => {
61 record_extern_fqn(cx, did, clean::TypeTrait);
62 clean::TraitItem(build_external_trait(tcx, did))
64 ast::DefFn(did, style) => {
65 // If this function is a tuple struct constructor, we just skip it
66 if csearch::get_tuple_struct_definition_if_ctor(&tcx.sess.cstore,
70 record_extern_fqn(cx, did, clean::TypeFunction);
71 clean::FunctionItem(build_external_function(tcx, did, style))
73 ast::DefStruct(did) => {
74 record_extern_fqn(cx, did, clean::TypeStruct);
75 ret.extend(build_impls(cx, tcx, did).move_iter());
76 clean::StructItem(build_struct(tcx, did))
79 record_extern_fqn(cx, did, clean::TypeEnum);
80 ret.extend(build_impls(cx, tcx, did).move_iter());
83 // Assume that the enum type is reexported next to the variant, and
84 // variants don't show up in documentation specially.
85 ast::DefVariant(..) => return Some(Vec::new()),
87 record_extern_fqn(cx, did, clean::TypeModule);
88 clean::ModuleItem(build_module(cx, tcx, did))
92 let fqn = csearch::get_item_path(tcx, did);
93 cx.inlined.borrow_mut().get_mut_ref().insert(did);
94 ret.push(clean::Item {
95 source: clean::Span::empty(),
96 name: Some(fqn.last().unwrap().to_str().to_string()),
97 attrs: load_attrs(tcx, did),
99 visibility: Some(ast::Public),
105 pub fn load_attrs(tcx: &ty::ctxt, did: ast::DefId) -> Vec<clean::Attribute> {
106 let mut attrs = Vec::new();
107 csearch::get_item_attrs(&tcx.sess.cstore, did, |v| {
108 attrs.extend(v.move_iter().map(|mut a| {
109 // FIXME this isn't quite always true, it's just true about 99% of
110 // the time when dealing with documentation. For example,
111 // this would treat doc comments of the form `#[doc = "foo"]`
113 if a.name().get() == "doc" && a.value_str().is_some() {
114 a.node.is_sugared_doc = true;
122 /// Record an external fully qualified name in the external_paths cache.
124 /// These names are used later on by HTML rendering to generate things like
125 /// source links back to the original item.
126 pub fn record_extern_fqn(cx: &core::DocContext,
128 kind: clean::TypeKind) {
129 match cx.maybe_typed {
130 core::Typed(ref tcx) => {
131 let fqn = csearch::get_item_path(tcx, did);
132 let fqn = fqn.move_iter().map(|i| i.to_str().to_string()).collect();
133 cx.external_paths.borrow_mut().get_mut_ref().insert(did, (fqn, kind));
135 core::NotTyped(..) => {}
139 pub fn build_external_trait(tcx: &ty::ctxt, did: ast::DefId) -> clean::Trait {
140 let def = ty::lookup_trait_def(tcx, did);
141 let methods = ty::trait_methods(tcx, did);
143 generics: def.generics.clean(),
144 methods: methods.iter().map(|i| i.clean()).collect(),
145 parents: Vec::new(), // FIXME: this is likely wrong
149 fn build_external_function(tcx: &ty::ctxt,
151 style: ast::FnStyle) -> clean::Function {
152 let t = ty::lookup_item_type(tcx, did);
154 decl: match ty::get(t.ty).sty {
155 ty::ty_bare_fn(ref f) => (did, &f.sig).clean(),
156 _ => fail!("bad function"),
158 generics: t.generics.clean(),
163 fn build_struct(tcx: &ty::ctxt, did: ast::DefId) -> clean::Struct {
164 use syntax::parse::token::special_idents::unnamed_field;
166 let t = ty::lookup_item_type(tcx, did);
167 let fields = ty::lookup_struct_fields(tcx, did);
170 struct_type: match fields.as_slice() {
172 [ref f] if f.name == unnamed_field.name => doctree::Newtype,
173 [ref f, ..] if f.name == unnamed_field.name => doctree::Tuple,
176 generics: t.generics.clean(),
177 fields: fields.iter().map(|f| f.clean()).collect(),
178 fields_stripped: false,
182 fn build_type(tcx: &ty::ctxt, did: ast::DefId) -> clean::ItemEnum {
183 let t = ty::lookup_item_type(tcx, did);
184 match ty::get(t.ty).sty {
185 ty::ty_enum(edid, _) => {
186 return clean::EnumItem(clean::Enum {
187 generics: t.generics.clean(),
188 variants_stripped: false,
189 variants: ty::enum_variants(tcx, edid).clean(),
195 clean::TypedefItem(clean::Typedef {
197 generics: t.generics.clean(),
201 fn build_impls(cx: &core::DocContext,
203 did: ast::DefId) -> Vec<clean::Item> {
204 ty::populate_implementations_for_type_if_necessary(tcx, did);
205 let mut impls = Vec::new();
207 match tcx.inherent_impls.borrow().find(&did) {
210 impls.extend(i.borrow().iter().map(|&did| { build_impl(tcx, did) }));
214 // If this is the first time we've inlined something from this crate, then
215 // we inline *all* impls from the crate into this crate. Note that there's
216 // currently no way for us to filter this based on type, and we likely need
217 // many impls for a variety of reasons.
219 // Primarily, the impls will be used to populate the documentation for this
220 // type being inlined, but impls can also be used when generating
221 // documentation for primitives (no way to find those specifically).
222 if cx.populated_crate_impls.borrow_mut().insert(did.krate) {
223 csearch::each_top_level_item_of_crate(&tcx.sess.cstore,
226 populate_impls(tcx, def, &mut impls)
229 fn populate_impls(tcx: &ty::ctxt,
230 def: decoder::DefLike,
231 impls: &mut Vec<clean::Item>) {
233 decoder::DlImpl(did) => impls.push(build_impl(tcx, did)),
234 decoder::DlDef(ast::DefMod(did)) => {
235 csearch::each_child_of_item(&tcx.sess.cstore,
238 populate_impls(tcx, def, impls)
249 fn build_impl(tcx: &ty::ctxt, did: ast::DefId) -> clean::Item {
250 let associated_trait = csearch::get_impl_trait(tcx, did);
251 let attrs = load_attrs(tcx, did);
252 let ty = ty::lookup_item_type(tcx, did);
253 let methods = csearch::get_impl_methods(&tcx.sess.cstore, did).iter().map(|did| {
254 let mut item = match ty::method(tcx, *did).clean() {
255 clean::Provided(item) => item,
256 clean::Required(item) => item,
258 item.inner = match item.inner.clone() {
259 clean::TyMethodItem(clean::TyMethod {
260 fn_style, decl, self_, generics
262 clean::MethodItem(clean::Method {
269 _ => fail!("not a tymethod"),
274 inner: clean::ImplItem(clean::Impl {
275 derived: clean::detect_derived(attrs.as_slice()),
276 trait_: associated_trait.clean().map(|bound| {
278 clean::TraitBound(ty) => ty,
279 clean::RegionBound => unreachable!(),
283 generics: ty.generics.clean(),
286 source: clean::Span::empty(),
289 visibility: Some(ast::Inherited),
294 fn build_module(cx: &core::DocContext, tcx: &ty::ctxt,
295 did: ast::DefId) -> clean::Module {
296 let mut items = Vec::new();
298 // FIXME: this doesn't handle reexports inside the module itself.
299 // Should they be handled?
300 csearch::each_child_of_item(&tcx.sess.cstore, did, |def, _, vis| {
301 if vis != ast::Public { return }
303 decoder::DlDef(def) => {
304 match try_inline_def(cx, tcx, def) {
305 Some(i) => items.extend(i.move_iter()),
309 // All impls were inlined above
310 decoder::DlImpl(..) => {}
311 decoder::DlField => fail!("unimplemented field"),