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 record_extern_fqn(cx, did, clean::TypeFunction);
66 clean::FunctionItem(build_external_function(tcx, did, style))
68 ast::DefStruct(did) => {
69 record_extern_fqn(cx, did, clean::TypeStruct);
70 ret.extend(build_impls(cx, tcx, did).move_iter());
71 clean::StructItem(build_struct(tcx, did))
74 record_extern_fqn(cx, did, clean::TypeEnum);
75 ret.extend(build_impls(cx, tcx, did).move_iter());
78 // Assume that the enum type is reexported next to the variant, and
79 // variants don't show up in documentation specially.
80 ast::DefVariant(..) => return Some(Vec::new()),
82 record_extern_fqn(cx, did, clean::TypeModule);
83 clean::ModuleItem(build_module(cx, tcx, did))
87 let fqn = csearch::get_item_path(tcx, did);
88 cx.inlined.borrow_mut().get_mut_ref().insert(did);
89 ret.push(clean::Item {
90 source: clean::Span::empty(),
91 name: Some(fqn.last().unwrap().to_str().to_string()),
92 attrs: load_attrs(tcx, did),
94 visibility: Some(ast::Public),
100 pub fn load_attrs(tcx: &ty::ctxt, did: ast::DefId) -> Vec<clean::Attribute> {
101 let mut attrs = Vec::new();
102 csearch::get_item_attrs(&tcx.sess.cstore, did, |v| {
103 attrs.extend(v.move_iter().map(|mut a| {
104 // FIXME this isn't quite always true, it's just true about 99% of
105 // the time when dealing with documentation. For example,
106 // this would treat doc comments of the form `#[doc = "foo"]`
108 if a.name().get() == "doc" && a.value_str().is_some() {
109 a.node.is_sugared_doc = true;
117 /// Record an external fully qualified name in the external_paths cache.
119 /// These names are used later on by HTML rendering to generate things like
120 /// source links back to the original item.
121 pub fn record_extern_fqn(cx: &core::DocContext,
123 kind: clean::TypeKind) {
124 match cx.maybe_typed {
125 core::Typed(ref tcx) => {
126 let fqn = csearch::get_item_path(tcx, did);
127 let fqn = fqn.move_iter().map(|i| i.to_str().to_string()).collect();
128 cx.external_paths.borrow_mut().get_mut_ref().insert(did, (fqn, kind));
130 core::NotTyped(..) => {}
134 pub fn build_external_trait(tcx: &ty::ctxt, did: ast::DefId) -> clean::Trait {
135 let def = ty::lookup_trait_def(tcx, did);
136 let methods = ty::trait_methods(tcx, did);
138 generics: def.generics.clean(),
139 methods: methods.iter().map(|i| i.clean()).collect(),
140 parents: Vec::new(), // FIXME: this is likely wrong
144 fn build_external_function(tcx: &ty::ctxt,
146 style: ast::FnStyle) -> clean::Function {
147 let t = ty::lookup_item_type(tcx, did);
149 decl: match ty::get(t.ty).sty {
150 ty::ty_bare_fn(ref f) => (did, &f.sig).clean(),
151 _ => fail!("bad function"),
153 generics: t.generics.clean(),
158 fn build_struct(tcx: &ty::ctxt, did: ast::DefId) -> clean::Struct {
159 use syntax::parse::token::special_idents::unnamed_field;
161 let t = ty::lookup_item_type(tcx, did);
162 let fields = ty::lookup_struct_fields(tcx, did);
165 struct_type: match fields.as_slice() {
167 [ref f] if f.name == unnamed_field.name => doctree::Newtype,
168 [ref f, ..] if f.name == unnamed_field.name => doctree::Tuple,
171 generics: t.generics.clean(),
172 fields: fields.iter().map(|f| f.clean()).collect(),
173 fields_stripped: false,
177 fn build_type(tcx: &ty::ctxt, did: ast::DefId) -> clean::ItemEnum {
178 let t = ty::lookup_item_type(tcx, did);
179 match ty::get(t.ty).sty {
180 ty::ty_enum(edid, _) => {
181 return clean::EnumItem(clean::Enum {
182 generics: t.generics.clean(),
183 variants_stripped: false,
184 variants: ty::enum_variants(tcx, edid).clean(),
190 clean::TypedefItem(clean::Typedef {
192 generics: t.generics.clean(),
196 fn build_impls(cx: &core::DocContext,
198 did: ast::DefId) -> Vec<clean::Item> {
199 ty::populate_implementations_for_type_if_necessary(tcx, did);
200 let mut impls = Vec::new();
202 match tcx.inherent_impls.borrow().find(&did) {
205 impls.extend(i.borrow().iter().map(|&did| { build_impl(tcx, did) }));
209 // If this is the first time we've inlined something from this crate, then
210 // we inline *all* impls from the crate into this crate. Note that there's
211 // currently no way for us to filter this based on type, and we likely need
212 // many impls for a variety of reasons.
214 // Primarily, the impls will be used to populate the documentation for this
215 // type being inlined, but impls can also be used when generating
216 // documentation for primitives (no way to find those specifically).
217 if cx.populated_crate_impls.borrow_mut().insert(did.krate) {
218 csearch::each_top_level_item_of_crate(&tcx.sess.cstore,
221 populate_impls(tcx, def, &mut impls)
224 fn populate_impls(tcx: &ty::ctxt,
225 def: decoder::DefLike,
226 impls: &mut Vec<clean::Item>) {
228 decoder::DlImpl(did) => impls.push(build_impl(tcx, did)),
229 decoder::DlDef(ast::DefMod(did)) => {
230 csearch::each_child_of_item(&tcx.sess.cstore,
233 populate_impls(tcx, def, impls)
244 fn build_impl(tcx: &ty::ctxt, did: ast::DefId) -> clean::Item {
245 let associated_trait = csearch::get_impl_trait(tcx, did);
246 let attrs = load_attrs(tcx, did);
247 let ty = ty::lookup_item_type(tcx, did);
248 let methods = csearch::get_impl_methods(&tcx.sess.cstore, did).iter().map(|did| {
249 let mut item = match ty::method(tcx, *did).clean() {
250 clean::Provided(item) => item,
251 clean::Required(item) => item,
253 item.inner = match item.inner.clone() {
254 clean::TyMethodItem(clean::TyMethod {
255 fn_style, decl, self_, generics
257 clean::MethodItem(clean::Method {
264 _ => fail!("not a tymethod"),
269 inner: clean::ImplItem(clean::Impl {
270 derived: clean::detect_derived(attrs.as_slice()),
271 trait_: associated_trait.clean().map(|bound| {
273 clean::TraitBound(ty) => ty,
274 clean::RegionBound => unreachable!(),
278 generics: ty.generics.clean(),
281 source: clean::Span::empty(),
284 visibility: Some(ast::Inherited),
289 fn build_module(cx: &core::DocContext, tcx: &ty::ctxt,
290 did: ast::DefId) -> clean::Module {
291 let mut items = Vec::new();
293 // FIXME: this doesn't handle reexports inside the module itself.
294 // Should they be handled?
295 csearch::each_child_of_item(&tcx.sess.cstore, did, |def, _, vis| {
296 if vis != ast::Public { return }
298 decoder::DlDef(def) => {
299 match try_inline_def(cx, tcx, def) {
300 Some(i) => items.extend(i.move_iter()),
304 // All impls were inlined above
305 decoder::DlImpl(..) => {}
306 decoder::DlField => fail!("unimplemented field"),