]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/inline.rs
Switch wasm math symbols to their original names
[rust.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::iter::once;
14
15 use syntax::ast;
16 use syntax::ext::base::MacroKind;
17 use syntax_pos::Span;
18
19 use rustc::hir;
20 use rustc::hir::def::{Def, CtorKind};
21 use rustc::hir::def_id::DefId;
22 use rustc_metadata::cstore::LoadedMacro;
23 use rustc::ty;
24 use rustc::util::nodemap::FxHashSet;
25
26 use core::{DocContext, DocAccessLevels};
27 use doctree;
28 use clean::{
29     self,
30     GetDefId,
31     ToSource,
32     get_auto_traits_with_def_id,
33     get_blanket_impls_with_def_id,
34 };
35
36 use super::Clean;
37
38 /// Attempt to inline a definition into this AST.
39 ///
40 /// This function will fetch the definition specified, and if it is
41 /// from another crate it will attempt to inline the documentation
42 /// from the other crate into this crate.
43 ///
44 /// This is primarily used for `pub use` statements which are, in general,
45 /// implementation details. Inlining the documentation should help provide a
46 /// better experience when reading the documentation in this use case.
47 ///
48 /// The returned value is `None` if the definition could not be inlined,
49 /// and `Some` of a vector of items if it was successfully expanded.
50 pub fn try_inline(cx: &DocContext, def: Def, name: ast::Name, visited: &mut FxHashSet<DefId>)
51                   -> Option<Vec<clean::Item>> {
52     if def == Def::Err { return None }
53     let did = def.def_id();
54     if did.is_local() { return None }
55     let mut ret = Vec::new();
56     let inner = match def {
57         Def::Trait(did) => {
58             record_extern_fqn(cx, did, clean::TypeKind::Trait);
59             ret.extend(build_impls(cx, did, false));
60             clean::TraitItem(build_external_trait(cx, did))
61         }
62         Def::Fn(did) => {
63             record_extern_fqn(cx, did, clean::TypeKind::Function);
64             clean::FunctionItem(build_external_function(cx, did))
65         }
66         Def::Struct(did) => {
67             record_extern_fqn(cx, did, clean::TypeKind::Struct);
68             ret.extend(build_impls(cx, did, true));
69             clean::StructItem(build_struct(cx, did))
70         }
71         Def::Union(did) => {
72             record_extern_fqn(cx, did, clean::TypeKind::Union);
73             ret.extend(build_impls(cx, did, true));
74             clean::UnionItem(build_union(cx, did))
75         }
76         Def::TyAlias(did) => {
77             record_extern_fqn(cx, did, clean::TypeKind::Typedef);
78             ret.extend(build_impls(cx, did, false));
79             clean::TypedefItem(build_type_alias(cx, did), false)
80         }
81         Def::Enum(did) => {
82             record_extern_fqn(cx, did, clean::TypeKind::Enum);
83             ret.extend(build_impls(cx, did, true));
84             clean::EnumItem(build_enum(cx, did))
85         }
86         Def::ForeignTy(did) => {
87             record_extern_fqn(cx, did, clean::TypeKind::Foreign);
88             ret.extend(build_impls(cx, did, false));
89             clean::ForeignTypeItem
90         }
91         // Never inline enum variants but leave them shown as re-exports.
92         Def::Variant(..) => return None,
93         // Assume that enum variants and struct types are re-exported next to
94         // their constructors.
95         Def::VariantCtor(..) |
96         Def::StructCtor(..) => return Some(Vec::new()),
97         Def::Mod(did) => {
98             record_extern_fqn(cx, did, clean::TypeKind::Module);
99             clean::ModuleItem(build_module(cx, did, visited))
100         }
101         Def::Static(did, mtbl) => {
102             record_extern_fqn(cx, did, clean::TypeKind::Static);
103             clean::StaticItem(build_static(cx, did, mtbl))
104         }
105         Def::Const(did) => {
106             record_extern_fqn(cx, did, clean::TypeKind::Const);
107             clean::ConstantItem(build_const(cx, did))
108         }
109         // FIXME(misdreavus): if attributes/derives come down here we should probably document them
110         // separately
111         Def::Macro(did, MacroKind::Bang) => {
112             record_extern_fqn(cx, did, clean::TypeKind::Macro);
113             if let Some(mac) = build_macro(cx, did, name) {
114                 clean::MacroItem(mac)
115             } else {
116                 return None;
117             }
118         }
119         _ => return None,
120     };
121     cx.renderinfo.borrow_mut().inlined.insert(did);
122     ret.push(clean::Item {
123         source: cx.tcx.def_span(did).clean(cx),
124         name: Some(name.clean(cx)),
125         attrs: load_attrs(cx, did),
126         inner,
127         visibility: Some(clean::Public),
128         stability: cx.tcx.lookup_stability(did).clean(cx),
129         deprecation: cx.tcx.lookup_deprecation(did).clean(cx),
130         def_id: did,
131     });
132     Some(ret)
133 }
134
135 pub fn try_inline_glob(cx: &DocContext, def: Def, visited: &mut FxHashSet<DefId>)
136     -> Option<Vec<clean::Item>>
137 {
138     if def == Def::Err { return None }
139     let did = def.def_id();
140     if did.is_local() { return None }
141
142     match def {
143         Def::Mod(did) => {
144             let m = build_module(cx, did, visited);
145             Some(m.items)
146         }
147         // glob imports on things like enums aren't inlined even for local exports, so just bail
148         _ => None,
149     }
150 }
151
152 pub fn load_attrs(cx: &DocContext, did: DefId) -> clean::Attributes {
153     cx.tcx.get_attrs(did).clean(cx)
154 }
155
156 /// Record an external fully qualified name in the external_paths cache.
157 ///
158 /// These names are used later on by HTML rendering to generate things like
159 /// source links back to the original item.
160 pub fn record_extern_fqn(cx: &DocContext, did: DefId, kind: clean::TypeKind) {
161     if did.is_local() {
162         debug!("record_extern_fqn(did={:?}, kind+{:?}): def_id is local, aborting", did, kind);
163         return;
164     }
165
166     let crate_name = cx.tcx.crate_name(did.krate).to_string();
167     let relative = cx.tcx.def_path(did).data.into_iter().filter_map(|elem| {
168         // extern blocks have an empty name
169         let s = elem.data.to_string();
170         if !s.is_empty() {
171             Some(s)
172         } else {
173             None
174         }
175     });
176     let fqn = if let clean::TypeKind::Macro = kind {
177         vec![crate_name, relative.last().expect("relative was empty")]
178     } else {
179         once(crate_name).chain(relative).collect()
180     };
181     cx.renderinfo.borrow_mut().external_paths.insert(did, (fqn, kind));
182 }
183
184 pub fn build_external_trait(cx: &DocContext, did: DefId) -> clean::Trait {
185     let auto_trait = cx.tcx.trait_def(did).has_auto_impl;
186     let trait_items = cx.tcx.associated_items(did).map(|item| item.clean(cx)).collect();
187     let predicates = cx.tcx.predicates_of(did);
188     let generics = (cx.tcx.generics_of(did), &predicates).clean(cx);
189     let generics = filter_non_trait_generics(did, generics);
190     let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
191     let is_spotlight = load_attrs(cx, did).has_doc_flag("spotlight");
192     let is_auto = cx.tcx.trait_is_auto(did);
193     clean::Trait {
194         auto: auto_trait,
195         unsafety: cx.tcx.trait_def(did).unsafety,
196         generics,
197         items: trait_items,
198         bounds: supertrait_bounds,
199         is_spotlight,
200         is_auto,
201     }
202 }
203
204 fn build_external_function(cx: &DocContext, did: DefId) -> clean::Function {
205     let sig = cx.tcx.fn_sig(did);
206
207     let constness = if cx.tcx.is_const_fn(did) {
208         hir::Constness::Const
209     } else {
210         hir::Constness::NotConst
211     };
212
213     let predicates = cx.tcx.predicates_of(did);
214     clean::Function {
215         decl: (did, sig).clean(cx),
216         generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
217         header: hir::FnHeader {
218             unsafety: sig.unsafety(),
219             abi: sig.abi(),
220             constness,
221             asyncness: hir::IsAsync::NotAsync,
222         }
223     }
224 }
225
226 fn build_enum(cx: &DocContext, did: DefId) -> clean::Enum {
227     let predicates = cx.tcx.predicates_of(did);
228
229     clean::Enum {
230         generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
231         variants_stripped: false,
232         variants: cx.tcx.adt_def(did).variants.clean(cx),
233     }
234 }
235
236 fn build_struct(cx: &DocContext, did: DefId) -> clean::Struct {
237     let predicates = cx.tcx.predicates_of(did);
238     let variant = cx.tcx.adt_def(did).non_enum_variant();
239
240     clean::Struct {
241         struct_type: match variant.ctor_kind {
242             CtorKind::Fictive => doctree::Plain,
243             CtorKind::Fn => doctree::Tuple,
244             CtorKind::Const => doctree::Unit,
245         },
246         generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
247         fields: variant.fields.clean(cx),
248         fields_stripped: false,
249     }
250 }
251
252 fn build_union(cx: &DocContext, did: DefId) -> clean::Union {
253     let predicates = cx.tcx.predicates_of(did);
254     let variant = cx.tcx.adt_def(did).non_enum_variant();
255
256     clean::Union {
257         struct_type: doctree::Plain,
258         generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
259         fields: variant.fields.clean(cx),
260         fields_stripped: false,
261     }
262 }
263
264 fn build_type_alias(cx: &DocContext, did: DefId) -> clean::Typedef {
265     let predicates = cx.tcx.predicates_of(did);
266
267     clean::Typedef {
268         type_: cx.tcx.type_of(did).clean(cx),
269         generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
270     }
271 }
272
273 pub fn build_impls(cx: &DocContext, did: DefId, auto_traits: bool) -> Vec<clean::Item> {
274     let tcx = cx.tcx;
275     let mut impls = Vec::new();
276
277     for &did in tcx.inherent_impls(did).iter() {
278         build_impl(cx, did, &mut impls);
279     }
280
281     if auto_traits {
282         let auto_impls = get_auto_traits_with_def_id(cx, did);
283         {
284             let mut renderinfo = cx.renderinfo.borrow_mut();
285             let new_impls: Vec<clean::Item> = auto_impls.into_iter()
286                 .filter(|i| renderinfo.inlined.insert(i.def_id)).collect();
287
288             impls.extend(new_impls);
289         }
290         impls.extend(get_blanket_impls_with_def_id(cx, did));
291     }
292
293     // If this is the first time we've inlined something from another crate, then
294     // we inline *all* impls from all the crates into this crate. Note that there's
295     // currently no way for us to filter this based on type, and we likely need
296     // many impls for a variety of reasons.
297     //
298     // Primarily, the impls will be used to populate the documentation for this
299     // type being inlined, but impls can also be used when generating
300     // documentation for primitives (no way to find those specifically).
301     if cx.populated_all_crate_impls.get() {
302         return impls;
303     }
304
305     cx.populated_all_crate_impls.set(true);
306
307     for &cnum in tcx.crates().iter() {
308         for did in tcx.all_trait_implementations(cnum).iter() {
309             build_impl(cx, *did, &mut impls);
310         }
311     }
312
313     // Also try to inline primitive impls from other crates.
314     let lang_items = tcx.lang_items();
315     let primitive_impls = [
316         lang_items.isize_impl(),
317         lang_items.i8_impl(),
318         lang_items.i16_impl(),
319         lang_items.i32_impl(),
320         lang_items.i64_impl(),
321         lang_items.i128_impl(),
322         lang_items.usize_impl(),
323         lang_items.u8_impl(),
324         lang_items.u16_impl(),
325         lang_items.u32_impl(),
326         lang_items.u64_impl(),
327         lang_items.u128_impl(),
328         lang_items.f32_impl(),
329         lang_items.f64_impl(),
330         lang_items.f32_runtime_impl(),
331         lang_items.f64_runtime_impl(),
332         lang_items.char_impl(),
333         lang_items.str_impl(),
334         lang_items.slice_impl(),
335         lang_items.slice_u8_impl(),
336         lang_items.str_alloc_impl(),
337         lang_items.slice_alloc_impl(),
338         lang_items.slice_u8_alloc_impl(),
339         lang_items.const_ptr_impl(),
340         lang_items.mut_ptr_impl(),
341     ];
342
343     for def_id in primitive_impls.iter().filter_map(|&def_id| def_id) {
344         if !def_id.is_local() {
345             build_impl(cx, def_id, &mut impls);
346
347             let auto_impls = get_auto_traits_with_def_id(cx, def_id);
348             let blanket_impls = get_blanket_impls_with_def_id(cx, def_id);
349             let mut renderinfo = cx.renderinfo.borrow_mut();
350
351             let new_impls: Vec<clean::Item> = auto_impls.into_iter()
352                 .chain(blanket_impls.into_iter())
353                 .filter(|i| renderinfo.inlined.insert(i.def_id))
354                 .collect();
355
356             impls.extend(new_impls);
357         }
358     }
359
360     impls
361 }
362
363 pub fn build_impl(cx: &DocContext, did: DefId, ret: &mut Vec<clean::Item>) {
364     if !cx.renderinfo.borrow_mut().inlined.insert(did) {
365         return
366     }
367
368     let attrs = load_attrs(cx, did);
369     let tcx = cx.tcx;
370     let associated_trait = tcx.impl_trait_ref(did);
371
372     // Only inline impl if the implemented trait is
373     // reachable in rustdoc generated documentation
374     if let Some(traitref) = associated_trait {
375         if !cx.access_levels.borrow().is_doc_reachable(traitref.def_id) {
376             return
377         }
378     }
379
380     let for_ = tcx.type_of(did).clean(cx);
381
382     // Only inline impl if the implementing type is
383     // reachable in rustdoc generated documentation
384     if let Some(did) = for_.def_id() {
385         if !cx.access_levels.borrow().is_doc_reachable(did) {
386             return
387         }
388     }
389
390     let predicates = tcx.predicates_of(did);
391     let trait_items = tcx.associated_items(did).filter_map(|item| {
392         if associated_trait.is_some() || item.vis == ty::Visibility::Public {
393             Some(item.clean(cx))
394         } else {
395             None
396         }
397     }).collect::<Vec<_>>();
398     let polarity = tcx.impl_polarity(did);
399     let trait_ = associated_trait.clean(cx).map(|bound| {
400         match bound {
401             clean::GenericBound::TraitBound(polyt, _) => polyt.trait_,
402             clean::GenericBound::Outlives(..) => unreachable!(),
403         }
404     });
405     if trait_.def_id() == tcx.lang_items().deref_trait() {
406         super::build_deref_target_impls(cx, &trait_items, ret);
407     }
408     if let Some(trait_did) = trait_.def_id() {
409         record_extern_trait(cx, trait_did);
410     }
411
412     let provided = trait_.def_id().map(|did| {
413         tcx.provided_trait_methods(did)
414            .into_iter()
415            .map(|meth| meth.ident.to_string())
416            .collect()
417     }).unwrap_or(FxHashSet());
418
419     ret.push(clean::Item {
420         inner: clean::ImplItem(clean::Impl {
421             unsafety: hir::Unsafety::Normal,
422             generics: (tcx.generics_of(did), &predicates).clean(cx),
423             provided_trait_methods: provided,
424             trait_,
425             for_,
426             items: trait_items,
427             polarity: Some(polarity.clean(cx)),
428             synthetic: false,
429             blanket_impl: None,
430         }),
431         source: tcx.def_span(did).clean(cx),
432         name: None,
433         attrs,
434         visibility: Some(clean::Inherited),
435         stability: tcx.lookup_stability(did).clean(cx),
436         deprecation: tcx.lookup_deprecation(did).clean(cx),
437         def_id: did,
438     });
439 }
440
441 fn build_module(cx: &DocContext, did: DefId, visited: &mut FxHashSet<DefId>) -> clean::Module {
442     let mut items = Vec::new();
443     fill_in(cx, did, &mut items, visited);
444     return clean::Module {
445         items,
446         is_crate: false,
447     };
448
449     fn fill_in(cx: &DocContext, did: DefId, items: &mut Vec<clean::Item>,
450                visited: &mut FxHashSet<DefId>) {
451         // If we're re-exporting a re-export it may actually re-export something in
452         // two namespaces, so the target may be listed twice. Make sure we only
453         // visit each node at most once.
454         for &item in cx.tcx.item_children(did).iter() {
455             let def_id = item.def.def_id();
456             if item.vis == ty::Visibility::Public {
457                 if did == def_id || !visited.insert(def_id) { continue }
458                 if let Some(i) = try_inline(cx, item.def, item.ident.name, visited) {
459                     items.extend(i)
460                 }
461             }
462         }
463     }
464 }
465
466 pub fn print_inlined_const(cx: &DocContext, did: DefId) -> String {
467     cx.tcx.rendered_const(did)
468 }
469
470 fn build_const(cx: &DocContext, did: DefId) -> clean::Constant {
471     clean::Constant {
472         type_: cx.tcx.type_of(did).clean(cx),
473         expr: print_inlined_const(cx, did)
474     }
475 }
476
477 fn build_static(cx: &DocContext, did: DefId, mutable: bool) -> clean::Static {
478     clean::Static {
479         type_: cx.tcx.type_of(did).clean(cx),
480         mutability: if mutable {clean::Mutable} else {clean::Immutable},
481         expr: "\n\n\n".to_string(), // trigger the "[definition]" links
482     }
483 }
484
485 fn build_macro(cx: &DocContext, did: DefId, name: ast::Name) -> Option<clean::Macro> {
486     let imported_from = cx.tcx.original_crate_name(did.krate);
487     let def = match cx.cstore.load_macro_untracked(did, cx.sess()) {
488         LoadedMacro::MacroDef(macro_def) => macro_def,
489         // FIXME(jseyfried): document proc macro re-exports
490         LoadedMacro::ProcMacro(..) => return None,
491     };
492
493     let matchers: hir::HirVec<Span> = if let ast::ItemKind::MacroDef(ref def) = def.node {
494         let tts: Vec<_> = def.stream().into_trees().collect();
495         tts.chunks(4).map(|arm| arm[0].span()).collect()
496     } else {
497         unreachable!()
498     };
499
500     let source = format!("macro_rules! {} {{\n{}}}",
501                          name.clean(cx),
502                          matchers.iter().map(|span| {
503                              format!("    {} => {{ ... }};\n", span.to_src(cx))
504                          }).collect::<String>());
505
506     Some(clean::Macro {
507         source,
508         imported_from: Some(imported_from).clean(cx),
509     })
510 }
511
512 /// A trait's generics clause actually contains all of the predicates for all of
513 /// its associated types as well. We specifically move these clauses to the
514 /// associated types instead when displaying, so when we're generating the
515 /// generics for the trait itself we need to be sure to remove them.
516 /// We also need to remove the implied "recursive" Self: Trait bound.
517 ///
518 /// The inverse of this filtering logic can be found in the `Clean`
519 /// implementation for `AssociatedType`
520 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean::Generics {
521     for pred in &mut g.where_predicates {
522         match *pred {
523             clean::WherePredicate::BoundPredicate {
524                 ty: clean::Generic(ref s),
525                 ref mut bounds
526             } if *s == "Self" => {
527                 bounds.retain(|bound| {
528                     match *bound {
529                         clean::GenericBound::TraitBound(clean::PolyTrait {
530                             trait_: clean::ResolvedPath { did, .. },
531                             ..
532                         }, _) => did != trait_did,
533                         _ => true
534                     }
535                 });
536             }
537             _ => {}
538         }
539     }
540
541     g.where_predicates.retain(|pred| {
542         match *pred {
543             clean::WherePredicate::BoundPredicate {
544                 ty: clean::QPath {
545                     self_type: box clean::Generic(ref s),
546                     trait_: box clean::ResolvedPath { did, .. },
547                     name: ref _name,
548                 }, ref bounds
549             } => !(*s == "Self" && did == trait_did) && !bounds.is_empty(),
550             _ => true,
551         }
552     });
553     g
554 }
555
556 /// Supertrait bounds for a trait are also listed in the generics coming from
557 /// the metadata for a crate, so we want to separate those out and create a new
558 /// list of explicit supertrait bounds to render nicely.
559 fn separate_supertrait_bounds(mut g: clean::Generics)
560                               -> (clean::Generics, Vec<clean::GenericBound>) {
561     let mut ty_bounds = Vec::new();
562     g.where_predicates.retain(|pred| {
563         match *pred {
564             clean::WherePredicate::BoundPredicate {
565                 ty: clean::Generic(ref s),
566                 ref bounds
567             } if *s == "Self" => {
568                 ty_bounds.extend(bounds.iter().cloned());
569                 false
570             }
571             _ => true,
572         }
573     });
574     (g, ty_bounds)
575 }
576
577 pub fn record_extern_trait(cx: &DocContext, did: DefId) {
578     if cx.external_traits.borrow().contains_key(&did) ||
579         cx.active_extern_traits.borrow().contains(&did)
580     {
581         return;
582     }
583
584     cx.active_extern_traits.borrow_mut().push(did);
585
586     let trait_ = build_external_trait(cx, did);
587
588     cx.external_traits.borrow_mut().insert(did, trait_);
589     cx.active_extern_traits.borrow_mut().remove_item(&did);
590 }