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 //! This module contains the "cleaned" pieces of the AST, and the functions
14 pub use self::Type::*;
15 pub use self::Mutability::*;
16 pub use self::ItemEnum::*;
17 pub use self::TyParamBound::*;
18 pub use self::SelfTy::*;
19 pub use self::FunctionRetTy::*;
20 pub use self::Visibility::*;
23 use syntax::ast::{self, AttrStyle};
25 use syntax::codemap::Spanned;
26 use syntax::feature_gate::UnstableFeatures;
28 use syntax::symbol::keywords;
29 use syntax::symbol::Symbol;
30 use syntax_pos::{self, DUMMY_SP, Pos, FileName};
32 use rustc::middle::const_val::ConstVal;
33 use rustc::middle::privacy::AccessLevels;
34 use rustc::middle::resolve_lifetime as rl;
35 use rustc::ty::fold::TypeFolder;
36 use rustc::middle::lang_items;
37 use rustc::hir::{self, HirVec};
38 use rustc::hir::def::{self, Def, CtorKind};
39 use rustc::hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE};
40 use rustc::hir::def_id::DefIndexAddressSpace;
42 use rustc::ty::subst::Substs;
43 use rustc::ty::{self, TyCtxt, Region, RegionVid, Ty, AdtKind};
44 use rustc::middle::stability;
45 use rustc::util::nodemap::{FxHashMap, FxHashSet};
46 use rustc_typeck::hir_ty_to_ty;
47 use rustc::infer::{InferCtxt, RegionObligation};
48 use rustc::infer::region_constraints::{RegionConstraintData, Constraint};
50 use std::collections::hash_map::Entry;
51 use std::collections::VecDeque;
54 use rustc_const_math::ConstInt;
55 use std::default::Default;
56 use std::{mem, slice, vec};
57 use std::iter::{FromIterator, once};
59 use std::cell::RefCell;
63 use core::{self, DocContext};
66 use html::item_type::ItemType;
67 use html::markdown::markdown_links;
75 use self::auto_trait::AutoTraitFinder;
77 thread_local!(static MAX_DEF_ID: RefCell<FxHashMap<CrateNum, DefId>> = RefCell::new(FxHashMap()));
79 const FN_OUTPUT_NAME: &'static str = "Output";
81 // extract the stability index for a node from tcx, if possible
82 fn get_stability(cx: &DocContext, def_id: DefId) -> Option<Stability> {
83 cx.tcx.lookup_stability(def_id).clean(cx)
86 fn get_deprecation(cx: &DocContext, def_id: DefId) -> Option<Deprecation> {
87 cx.tcx.lookup_deprecation(def_id).clean(cx)
91 fn clean(&self, cx: &DocContext) -> T;
94 impl<T: Clean<U>, U> Clean<Vec<U>> for [T] {
95 fn clean(&self, cx: &DocContext) -> Vec<U> {
96 self.iter().map(|x| x.clean(cx)).collect()
100 impl<T: Clean<U>, U> Clean<U> for P<T> {
101 fn clean(&self, cx: &DocContext) -> U {
106 impl<T: Clean<U>, U> Clean<U> for Rc<T> {
107 fn clean(&self, cx: &DocContext) -> U {
112 impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
113 fn clean(&self, cx: &DocContext) -> Option<U> {
114 self.as_ref().map(|v| v.clean(cx))
118 impl<T, U> Clean<U> for ty::Binder<T> where T: Clean<U> {
119 fn clean(&self, cx: &DocContext) -> U {
124 impl<T: Clean<U>, U> Clean<Vec<U>> for P<[T]> {
125 fn clean(&self, cx: &DocContext) -> Vec<U> {
126 self.iter().map(|x| x.clean(cx)).collect()
130 #[derive(Clone, Debug)]
133 pub version: Option<String>,
135 pub module: Option<Item>,
136 pub externs: Vec<(CrateNum, ExternalCrate)>,
137 pub primitives: Vec<(DefId, PrimitiveType, Attributes)>,
138 pub access_levels: Arc<AccessLevels<DefId>>,
139 // These are later on moved into `CACHEKEY`, leaving the map empty.
140 // Only here so that they can be filtered through the rustdoc passes.
141 pub external_traits: FxHashMap<DefId, Trait>,
142 pub masked_crates: FxHashSet<CrateNum>,
145 impl<'a, 'tcx, 'rcx> Clean<Crate> for visit_ast::RustdocVisitor<'a, 'tcx, 'rcx> {
146 fn clean(&self, cx: &DocContext) -> Crate {
147 use ::visit_lib::LibEmbargoVisitor;
150 let mut r = cx.renderinfo.borrow_mut();
151 r.deref_trait_did = cx.tcx.lang_items().deref_trait();
152 r.deref_mut_trait_did = cx.tcx.lang_items().deref_mut_trait();
153 r.owned_box_did = cx.tcx.lang_items().owned_box();
156 let mut externs = Vec::new();
157 for &cnum in cx.tcx.crates().iter() {
158 externs.push((cnum, cnum.clean(cx)));
159 // Analyze doc-reachability for extern items
160 LibEmbargoVisitor::new(cx).visit_lib(cnum);
162 externs.sort_by(|&(a, _), &(b, _)| a.cmp(&b));
164 // Clean the crate, translating the entire libsyntax AST to one that is
165 // understood by rustdoc.
166 let mut module = self.module.clean(cx);
167 let mut masked_crates = FxHashSet();
170 ModuleItem(ref module) => {
171 for it in &module.items {
172 if it.is_extern_crate() && it.attrs.has_doc_flag("masked") {
173 masked_crates.insert(it.def_id.krate);
180 let ExternalCrate { name, src, primitives, .. } = LOCAL_CRATE.clean(cx);
182 let m = match module.inner {
183 ModuleItem(ref mut m) => m,
186 m.items.extend(primitives.iter().map(|&(def_id, prim, ref attrs)| {
188 source: Span::empty(),
189 name: Some(prim.to_url_str().to_string()),
190 attrs: attrs.clone(),
191 visibility: Some(Public),
192 stability: get_stability(cx, def_id),
193 deprecation: get_deprecation(cx, def_id),
195 inner: PrimitiveItem(prim),
200 let mut access_levels = cx.access_levels.borrow_mut();
201 let mut external_traits = cx.external_traits.borrow_mut();
207 module: Some(module),
210 access_levels: Arc::new(mem::replace(&mut access_levels, Default::default())),
211 external_traits: mem::replace(&mut external_traits, Default::default()),
217 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
218 pub struct ExternalCrate {
221 pub attrs: Attributes,
222 pub primitives: Vec<(DefId, PrimitiveType, Attributes)>,
225 impl Clean<ExternalCrate> for CrateNum {
226 fn clean(&self, cx: &DocContext) -> ExternalCrate {
227 let root = DefId { krate: *self, index: CRATE_DEF_INDEX };
228 let krate_span = cx.tcx.def_span(root);
229 let krate_src = cx.sess().codemap().span_to_filename(krate_span);
231 // Collect all inner modules which are tagged as implementations of
234 // Note that this loop only searches the top-level items of the crate,
235 // and this is intentional. If we were to search the entire crate for an
236 // item tagged with `#[doc(primitive)]` then we would also have to
237 // search the entirety of external modules for items tagged
238 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
239 // all that metadata unconditionally).
241 // In order to keep the metadata load under control, the
242 // `#[doc(primitive)]` feature is explicitly designed to only allow the
243 // primitive tags to show up as the top level items in a crate.
245 // Also note that this does not attempt to deal with modules tagged
246 // duplicately for the same primitive. This is handled later on when
247 // rendering by delegating everything to a hash map.
248 let as_primitive = |def: Def| {
249 if let Def::Mod(def_id) = def {
250 let attrs = cx.tcx.get_attrs(def_id).clean(cx);
252 for attr in attrs.lists("doc") {
253 if let Some(v) = attr.value_str() {
254 if attr.check_name("primitive") {
255 prim = PrimitiveType::from_str(&v.as_str());
259 // FIXME: should warn on unknown primitives?
263 return prim.map(|p| (def_id, p, attrs));
267 let primitives = if root.is_local() {
268 cx.tcx.hir.krate().module.item_ids.iter().filter_map(|&id| {
269 let item = cx.tcx.hir.expect_item(id.id);
272 as_primitive(Def::Mod(cx.tcx.hir.local_def_id(id.id)))
274 hir::ItemUse(ref path, hir::UseKind::Single)
275 if item.vis == hir::Visibility::Public => {
276 as_primitive(path.def).map(|(_, prim, attrs)| {
277 // Pretend the primitive is local.
278 (cx.tcx.hir.local_def_id(id.id), prim, attrs)
285 cx.tcx.item_children(root).iter().map(|item| item.def)
286 .filter_map(as_primitive).collect()
290 name: cx.tcx.crate_name(*self).to_string(),
292 attrs: cx.tcx.get_attrs(root).clean(cx),
298 /// Anything with a source location and set of attributes and, optionally, a
299 /// name. That is, anything that can be documented. This doesn't correspond
300 /// directly to the AST's concept of an item; it's a strict superset.
301 #[derive(Clone, RustcEncodable, RustcDecodable)]
305 /// Not everything has a name. E.g., impls
306 pub name: Option<String>,
307 pub attrs: Attributes,
309 pub visibility: Option<Visibility>,
311 pub stability: Option<Stability>,
312 pub deprecation: Option<Deprecation>,
315 impl fmt::Debug for Item {
316 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
318 let fake = MAX_DEF_ID.with(|m| m.borrow().get(&self.def_id.krate)
319 .map(|id| self.def_id >= *id).unwrap_or(false));
320 let def_id: &fmt::Debug = if fake { &"**FAKE**" } else { &self.def_id };
322 fmt.debug_struct("Item")
323 .field("source", &self.source)
324 .field("name", &self.name)
325 .field("attrs", &self.attrs)
326 .field("inner", &self.inner)
327 .field("visibility", &self.visibility)
328 .field("def_id", def_id)
329 .field("stability", &self.stability)
330 .field("deprecation", &self.deprecation)
336 /// Finds the `doc` attribute as a NameValue and returns the corresponding
338 pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
339 self.attrs.doc_value()
341 /// Finds all `doc` attributes as NameValues and returns their corresponding values, joined
343 pub fn collapsed_doc_value(&self) -> Option<String> {
344 self.attrs.collapsed_doc_value()
347 pub fn links(&self) -> Vec<(String, String)> {
351 pub fn is_crate(&self) -> bool {
353 StrippedItem(box ModuleItem(Module { is_crate: true, ..})) |
354 ModuleItem(Module { is_crate: true, ..}) => true,
358 pub fn is_mod(&self) -> bool {
359 self.type_() == ItemType::Module
361 pub fn is_trait(&self) -> bool {
362 self.type_() == ItemType::Trait
364 pub fn is_struct(&self) -> bool {
365 self.type_() == ItemType::Struct
367 pub fn is_enum(&self) -> bool {
368 self.type_() == ItemType::Enum
370 pub fn is_fn(&self) -> bool {
371 self.type_() == ItemType::Function
373 pub fn is_associated_type(&self) -> bool {
374 self.type_() == ItemType::AssociatedType
376 pub fn is_associated_const(&self) -> bool {
377 self.type_() == ItemType::AssociatedConst
379 pub fn is_method(&self) -> bool {
380 self.type_() == ItemType::Method
382 pub fn is_ty_method(&self) -> bool {
383 self.type_() == ItemType::TyMethod
385 pub fn is_typedef(&self) -> bool {
386 self.type_() == ItemType::Typedef
388 pub fn is_primitive(&self) -> bool {
389 self.type_() == ItemType::Primitive
391 pub fn is_union(&self) -> bool {
392 self.type_() == ItemType::Union
394 pub fn is_import(&self) -> bool {
395 self.type_() == ItemType::Import
397 pub fn is_extern_crate(&self) -> bool {
398 self.type_() == ItemType::ExternCrate
401 pub fn is_stripped(&self) -> bool {
402 match self.inner { StrippedItem(..) => true, _ => false }
404 pub fn has_stripped_fields(&self) -> Option<bool> {
406 StructItem(ref _struct) => Some(_struct.fields_stripped),
407 UnionItem(ref union) => Some(union.fields_stripped),
408 VariantItem(Variant { kind: VariantKind::Struct(ref vstruct)} ) => {
409 Some(vstruct.fields_stripped)
415 pub fn stability_class(&self) -> Option<String> {
416 self.stability.as_ref().and_then(|ref s| {
417 let mut classes = Vec::with_capacity(2);
419 if s.level == stability::Unstable {
420 classes.push("unstable");
423 if !s.deprecated_since.is_empty() {
424 classes.push("deprecated");
427 if classes.len() != 0 {
428 Some(classes.join(" "))
435 pub fn stable_since(&self) -> Option<&str> {
436 self.stability.as_ref().map(|s| &s.since[..])
439 /// Returns a documentation-level item type from the item.
440 pub fn type_(&self) -> ItemType {
445 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
447 ExternCrateItem(String, Option<String>),
452 FunctionItem(Function),
454 TypedefItem(Typedef, bool /* is associated type */),
456 ConstantItem(Constant),
459 /// A method signature only. Used for required methods in traits (ie,
460 /// non-default-methods).
461 TyMethodItem(TyMethod),
462 /// A method with a body.
464 StructFieldItem(Type),
465 VariantItem(Variant),
466 /// `fn`s from an extern block
467 ForeignFunctionItem(Function),
468 /// `static`s from an extern block
469 ForeignStaticItem(Static),
470 /// `type`s from an extern block
473 PrimitiveItem(PrimitiveType),
474 AssociatedConstItem(Type, Option<String>),
475 AssociatedTypeItem(Vec<TyParamBound>, Option<Type>),
476 /// An item that has been stripped by a rustdoc pass
477 StrippedItem(Box<ItemEnum>),
481 pub fn generics(&self) -> Option<&Generics> {
483 ItemEnum::StructItem(ref s) => &s.generics,
484 ItemEnum::EnumItem(ref e) => &e.generics,
485 ItemEnum::FunctionItem(ref f) => &f.generics,
486 ItemEnum::TypedefItem(ref t, _) => &t.generics,
487 ItemEnum::TraitItem(ref t) => &t.generics,
488 ItemEnum::ImplItem(ref i) => &i.generics,
489 ItemEnum::TyMethodItem(ref i) => &i.generics,
490 ItemEnum::MethodItem(ref i) => &i.generics,
491 ItemEnum::ForeignFunctionItem(ref f) => &f.generics,
497 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
499 pub items: Vec<Item>,
503 impl Clean<Item> for doctree::Module {
504 fn clean(&self, cx: &DocContext) -> Item {
505 let name = if self.name.is_some() {
506 self.name.unwrap().clean(cx)
511 // maintain a stack of mod ids, for doc comment path resolution
512 // but we also need to resolve the module's own docs based on whether its docs were written
513 // inside or outside the module, so check for that
514 let attrs = if self.attrs.iter()
515 .filter(|a| a.check_name("doc"))
517 .map_or(true, |a| a.style == AttrStyle::Inner) {
518 // inner doc comment, use the module's own scope for resolution
519 cx.mod_ids.borrow_mut().push(self.id);
522 // outer doc comment, use its parent's scope
523 let attrs = self.attrs.clean(cx);
524 cx.mod_ids.borrow_mut().push(self.id);
528 let mut items: Vec<Item> = vec![];
529 items.extend(self.extern_crates.iter().map(|x| x.clean(cx)));
530 items.extend(self.imports.iter().flat_map(|x| x.clean(cx)));
531 items.extend(self.structs.iter().flat_map(|x| x.clean(cx)));
532 items.extend(self.unions.iter().flat_map(|x| x.clean(cx)));
533 items.extend(self.enums.iter().flat_map(|x| x.clean(cx)));
534 items.extend(self.fns.iter().map(|x| x.clean(cx)));
535 items.extend(self.foreigns.iter().flat_map(|x| x.clean(cx)));
536 items.extend(self.mods.iter().map(|x| x.clean(cx)));
537 items.extend(self.typedefs.iter().map(|x| x.clean(cx)));
538 items.extend(self.statics.iter().map(|x| x.clean(cx)));
539 items.extend(self.constants.iter().map(|x| x.clean(cx)));
540 items.extend(self.traits.iter().map(|x| x.clean(cx)));
541 items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
542 items.extend(self.macros.iter().map(|x| x.clean(cx)));
544 cx.mod_ids.borrow_mut().pop();
546 // determine if we should display the inner contents or
547 // the outer `mod` item for the source code.
549 let cm = cx.sess().codemap();
550 let outer = cm.lookup_char_pos(self.where_outer.lo());
551 let inner = cm.lookup_char_pos(self.where_inner.lo());
552 if outer.file.start_pos == inner.file.start_pos {
556 // mod foo; (and a separate FileMap for the contents)
564 source: whence.clean(cx),
565 visibility: self.vis.clean(cx),
566 stability: self.stab.clean(cx),
567 deprecation: self.depr.clean(cx),
568 def_id: cx.tcx.hir.local_def_id(self.id),
569 inner: ModuleItem(Module {
570 is_crate: self.is_crate,
577 pub struct ListAttributesIter<'a> {
578 attrs: slice::Iter<'a, ast::Attribute>,
579 current_list: vec::IntoIter<ast::NestedMetaItem>,
583 impl<'a> Iterator for ListAttributesIter<'a> {
584 type Item = ast::NestedMetaItem;
586 fn next(&mut self) -> Option<Self::Item> {
587 if let Some(nested) = self.current_list.next() {
591 for attr in &mut self.attrs {
592 if let Some(list) = attr.meta_item_list() {
593 if attr.check_name(self.name) {
594 self.current_list = list.into_iter();
595 if let Some(nested) = self.current_list.next() {
606 pub trait AttributesExt {
607 /// Finds an attribute as List and returns the list of attributes nested inside.
608 fn lists<'a>(&'a self, name: &'a str) -> ListAttributesIter<'a>;
611 impl AttributesExt for [ast::Attribute] {
612 fn lists<'a>(&'a self, name: &'a str) -> ListAttributesIter<'a> {
615 current_list: Vec::new().into_iter(),
621 pub trait NestedAttributesExt {
622 /// Returns whether the attribute list contains a specific `Word`
623 fn has_word(self, word: &str) -> bool;
626 impl<I: IntoIterator<Item=ast::NestedMetaItem>> NestedAttributesExt for I {
627 fn has_word(self, word: &str) -> bool {
628 self.into_iter().any(|attr| attr.is_word() && attr.check_name(word))
632 /// A portion of documentation, extracted from a `#[doc]` attribute.
634 /// Each variant contains the line number within the complete doc-comment where the fragment
635 /// starts, as well as the Span where the corresponding doc comment or attribute is located.
637 /// Included files are kept separate from inline doc comments so that proper line-number
638 /// information can be given when a doctest fails. Sugared doc comments and "raw" doc comments are
639 /// kept separate because of issue #42760.
640 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
641 pub enum DocFragment {
642 // FIXME #44229 (misdreavus): sugared and raw doc comments can be brought back together once
643 // hoedown is completely removed from rustdoc.
644 /// A doc fragment created from a `///` or `//!` doc comment.
645 SugaredDoc(usize, syntax_pos::Span, String),
646 /// A doc fragment created from a "raw" `#[doc=""]` attribute.
647 RawDoc(usize, syntax_pos::Span, String),
648 /// A doc fragment created from a `#[doc(include="filename")]` attribute. Contains both the
649 /// given filename and the file contents.
650 Include(usize, syntax_pos::Span, String, String),
654 pub fn as_str(&self) -> &str {
656 DocFragment::SugaredDoc(_, _, ref s) => &s[..],
657 DocFragment::RawDoc(_, _, ref s) => &s[..],
658 DocFragment::Include(_, _, _, ref s) => &s[..],
662 pub fn span(&self) -> syntax_pos::Span {
664 DocFragment::SugaredDoc(_, span, _) |
665 DocFragment::RawDoc(_, span, _) |
666 DocFragment::Include(_, span, _, _) => span,
671 impl<'a> FromIterator<&'a DocFragment> for String {
672 fn from_iter<T>(iter: T) -> Self
674 T: IntoIterator<Item = &'a DocFragment>
676 iter.into_iter().fold(String::new(), |mut acc, frag| {
681 DocFragment::SugaredDoc(_, _, ref docs)
682 | DocFragment::RawDoc(_, _, ref docs)
683 | DocFragment::Include(_, _, _, ref docs) =>
692 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Default, Hash)]
693 pub struct Attributes {
694 pub doc_strings: Vec<DocFragment>,
695 pub other_attrs: Vec<ast::Attribute>,
696 pub cfg: Option<Rc<Cfg>>,
697 pub span: Option<syntax_pos::Span>,
698 /// map from Rust paths to resolved defs and potential URL fragments
699 pub links: Vec<(String, DefId, Option<String>)>,
703 /// Extracts the content from an attribute `#[doc(cfg(content))]`.
704 fn extract_cfg(mi: &ast::MetaItem) -> Option<&ast::MetaItem> {
705 use syntax::ast::NestedMetaItemKind::MetaItem;
707 if let ast::MetaItemKind::List(ref nmis) = mi.node {
709 if let MetaItem(ref cfg_mi) = nmis[0].node {
710 if cfg_mi.check_name("cfg") {
711 if let ast::MetaItemKind::List(ref cfg_nmis) = cfg_mi.node {
712 if cfg_nmis.len() == 1 {
713 if let MetaItem(ref content_mi) = cfg_nmis[0].node {
714 return Some(content_mi);
726 /// Reads a `MetaItem` from within an attribute, looks for whether it is a
727 /// `#[doc(include="file")]`, and returns the filename and contents of the file as loaded from
729 fn extract_include(mi: &ast::MetaItem)
730 -> Option<(String, String)>
732 mi.meta_item_list().and_then(|list| {
734 if meta.check_name("include") {
735 // the actual compiled `#[doc(include="filename")]` gets expanded to
736 // `#[doc(include(file="filename", contents="file contents")]` so we need to
737 // look for that instead
738 return meta.meta_item_list().and_then(|list| {
739 let mut filename: Option<String> = None;
740 let mut contents: Option<String> = None;
743 if it.check_name("file") {
744 if let Some(name) = it.value_str() {
745 filename = Some(name.to_string());
747 } else if it.check_name("contents") {
748 if let Some(docs) = it.value_str() {
749 contents = Some(docs.to_string());
754 if let (Some(filename), Some(contents)) = (filename, contents) {
755 Some((filename, contents))
767 pub fn has_doc_flag(&self, flag: &str) -> bool {
768 for attr in &self.other_attrs {
769 if !attr.check_name("doc") { continue; }
771 if let Some(items) = attr.meta_item_list() {
772 if items.iter().filter_map(|i| i.meta_item()).any(|it| it.check_name(flag)) {
781 pub fn from_ast(diagnostic: &::errors::Handler,
782 attrs: &[ast::Attribute]) -> Attributes {
783 let mut doc_strings = vec![];
785 let mut cfg = Cfg::True;
786 let mut doc_line = 0;
788 let other_attrs = attrs.iter().filter_map(|attr| {
789 attr.with_desugared_doc(|attr| {
790 if attr.check_name("doc") {
791 if let Some(mi) = attr.meta() {
792 if let Some(value) = mi.value_str() {
793 // Extracted #[doc = "..."]
794 let value = value.to_string();
796 doc_line += value.lines().count();
798 if attr.is_sugared_doc {
799 doc_strings.push(DocFragment::SugaredDoc(line, attr.span, value));
801 doc_strings.push(DocFragment::RawDoc(line, attr.span, value));
805 sp = Some(attr.span);
808 } else if let Some(cfg_mi) = Attributes::extract_cfg(&mi) {
809 // Extracted #[doc(cfg(...))]
810 match Cfg::parse(cfg_mi) {
811 Ok(new_cfg) => cfg &= new_cfg,
812 Err(e) => diagnostic.span_err(e.span, e.msg),
815 } else if let Some((filename, contents)) = Attributes::extract_include(&mi)
818 doc_line += contents.lines().count();
819 doc_strings.push(DocFragment::Include(line,
833 cfg: if cfg == Cfg::True { None } else { Some(Rc::new(cfg)) },
839 /// Finds the `doc` attribute as a NameValue and returns the corresponding
841 pub fn doc_value<'a>(&'a self) -> Option<&'a str> {
842 self.doc_strings.first().map(|s| s.as_str())
845 /// Finds all `doc` attributes as NameValues and returns their corresponding values, joined
847 pub fn collapsed_doc_value(&self) -> Option<String> {
848 if !self.doc_strings.is_empty() {
849 Some(self.doc_strings.iter().collect())
855 /// Get links as a vector
857 /// Cache must be populated before call
858 pub fn links(&self) -> Vec<(String, String)> {
859 use html::format::href;
860 self.links.iter().filter_map(|&(ref s, did, ref fragment)| {
861 if let Some((mut href, ..)) = href(did) {
862 if let Some(ref fragment) = *fragment {
864 href.push_str(fragment);
866 Some((s.clone(), href))
874 impl AttributesExt for Attributes {
875 fn lists<'a>(&'a self, name: &'a str) -> ListAttributesIter<'a> {
876 self.other_attrs.lists(name)
880 /// Given a def, returns its name and disambiguator
881 /// for a value namespace
883 /// Returns None for things which cannot be ambiguous since
884 /// they exist in both namespaces (structs and modules)
885 fn value_ns_kind(def: Def, path_str: &str) -> Option<(&'static str, String)> {
887 // structs, variants, and mods exist in both namespaces. skip them
888 Def::StructCtor(..) | Def::Mod(..) | Def::Variant(..) | Def::VariantCtor(..) => None,
890 => Some(("function", format!("{}()", path_str))),
892 => Some(("method", format!("{}()", path_str))),
894 => Some(("const", format!("const@{}", path_str))),
896 => Some(("static", format!("static@{}", path_str))),
897 _ => Some(("value", format!("value@{}", path_str))),
901 /// Given a def, returns its name, the article to be used, and a disambiguator
902 /// for the type namespace
903 fn type_ns_kind(def: Def, path_str: &str) -> (&'static str, &'static str, String) {
904 let (kind, article) = match def {
905 // we can still have non-tuple structs
906 Def::Struct(..) => ("struct", "a"),
907 Def::Enum(..) => ("enum", "an"),
908 Def::Trait(..) => ("trait", "a"),
909 Def::Union(..) => ("union", "a"),
912 (kind, article, format!("{}@{}", kind, path_str))
915 fn ambiguity_error(cx: &DocContext, attrs: &Attributes,
917 article1: &str, kind1: &str, disambig1: &str,
918 article2: &str, kind2: &str, disambig2: &str) {
919 let sp = attrs.doc_strings.first()
920 .map_or(DUMMY_SP, |a| a.span());
922 .struct_span_warn(sp,
923 &format!("`{}` is both {} {} and {} {}",
924 path_str, article1, kind1,
926 .help(&format!("try `{}` if you want to select the {}, \
927 or `{}` if you want to \
929 disambig1, kind1, disambig2,
934 /// Given an enum variant's def, return the def of its enum and the associated fragment
935 fn handle_variant(cx: &DocContext, def: Def) -> Result<(Def, Option<String>), ()> {
936 use rustc::ty::DefIdTree;
938 let parent = if let Some(parent) = cx.tcx.parent(def.def_id()) {
943 let parent_def = Def::Enum(parent);
944 let variant = cx.tcx.expect_variant_def(def);
945 Ok((parent_def, Some(format!("{}.v", variant.name))))
948 /// Resolve a given string as a path, along with whether or not it is
949 /// in the value namespace. Also returns an optional URL fragment in the case
950 /// of variants and methods
951 fn resolve(cx: &DocContext, path_str: &str, is_val: bool) -> Result<(Def, Option<String>), ()> {
952 // In case we're in a module, try to resolve the relative
954 if let Some(id) = cx.mod_ids.borrow().last() {
955 let result = cx.resolver.borrow_mut()
958 resolver.resolve_str_path_error(DUMMY_SP,
962 if let Ok(result) = result {
963 // In case this is a trait item, skip the
964 // early return and try looking for the trait
965 let value = match result.def {
966 Def::Method(_) | Def::AssociatedConst(_) => true,
967 Def::AssociatedTy(_) => false,
968 Def::Variant(_) => return handle_variant(cx, result.def),
969 // not a trait item, just return what we found
970 _ => return Ok((result.def, None))
977 // If resolution failed, it may still be a method
978 // because methods are not handled by the resolver
979 // If so, bail when we're not looking for a value
985 // Try looking for methods and associated items
986 let mut split = path_str.rsplitn(2, "::");
987 let mut item_name = if let Some(first) = split.next() {
993 let mut path = if let Some(second) = split.next() {
999 let ty = cx.resolver.borrow_mut()
1002 resolver.resolve_str_path_error(DUMMY_SP,
1006 Def::Struct(did) | Def::Union(did) | Def::Enum(did) | Def::TyAlias(did) => {
1007 let item = cx.tcx.inherent_impls(did).iter()
1008 .flat_map(|imp| cx.tcx.associated_items(*imp))
1009 .find(|item| item.name == item_name);
1010 if let Some(item) = item {
1011 if item.kind == ty::AssociatedKind::Method && is_val {
1012 Ok((ty.def, Some(format!("method.{}", item_name))))
1020 Def::Trait(did) => {
1021 let item = cx.tcx.associated_item_def_ids(did).iter()
1022 .map(|item| cx.tcx.associated_item(*item))
1023 .find(|item| item.name == item_name);
1024 if let Some(item) = item {
1025 let kind = match item.kind {
1026 ty::AssociatedKind::Const if is_val => "associatedconstant",
1027 ty::AssociatedKind::Type if !is_val => "associatedtype",
1028 ty::AssociatedKind::Method if is_val => "tymethod",
1032 Ok((ty.def, Some(format!("{}.{}", kind, item_name))))
1045 /// Resolve a string as a macro
1046 fn macro_resolve(cx: &DocContext, path_str: &str) -> Option<Def> {
1047 use syntax::ext::base::{MacroKind, SyntaxExtension};
1048 use syntax::ext::hygiene::Mark;
1049 let segment = ast::PathSegment {
1050 identifier: ast::Ident::from_str(path_str),
1054 let path = ast::Path {
1056 segments: vec![segment],
1059 let mut resolver = cx.resolver.borrow_mut();
1060 let mark = Mark::root();
1062 .resolve_macro_to_def_inner(mark, &path, MacroKind::Bang, false);
1063 if let Ok(def) = res {
1064 if let SyntaxExtension::DeclMacro(..) = *resolver.get_macro(def) {
1069 } else if let Some(def) = resolver.all_macros.get(&path_str.into()) {
1077 /// can be either value or type, not a macro
1081 /// values, functions, consts, statics, everything in the value namespace
1083 /// types, traits, everything in the type namespace
1087 impl Clean<Attributes> for [ast::Attribute] {
1088 fn clean(&self, cx: &DocContext) -> Attributes {
1089 let mut attrs = Attributes::from_ast(cx.sess().diagnostic(), self);
1091 if UnstableFeatures::from_environment().is_nightly_build() {
1092 let dox = attrs.collapsed_doc_value().unwrap_or_else(String::new);
1093 for link in markdown_links(&dox) {
1094 // bail early for real links
1095 if link.contains('/') {
1098 let (def, fragment) = {
1099 let mut kind = PathKind::Unknown;
1100 let path_str = if let Some(prefix) =
1101 ["struct@", "enum@", "type@",
1102 "trait@", "union@"].iter()
1103 .find(|p| link.starts_with(**p)) {
1104 kind = PathKind::Type;
1105 link.trim_left_matches(prefix)
1106 } else if let Some(prefix) =
1107 ["const@", "static@",
1108 "value@", "function@", "mod@",
1109 "fn@", "module@", "method@"]
1110 .iter().find(|p| link.starts_with(**p)) {
1111 kind = PathKind::Value;
1112 link.trim_left_matches(prefix)
1113 } else if link.ends_with("()") {
1114 kind = PathKind::Value;
1115 link.trim_right_matches("()")
1116 } else if link.starts_with("macro@") {
1117 kind = PathKind::Macro;
1118 link.trim_left_matches("macro@")
1119 } else if link.ends_with('!') {
1120 kind = PathKind::Macro;
1121 link.trim_right_matches('!')
1126 // avoid resolving things (i.e. regular links) which aren't like paths
1127 // FIXME(Manishearth) given that most links have slashes in them might be worth
1128 // doing a check for slashes first
1129 if path_str.contains(|ch: char| !(ch.is_alphanumeric() ||
1130 ch == ':' || ch == '_')) {
1136 PathKind::Value => {
1137 if let Ok(def) = resolve(cx, path_str, true) {
1140 // this could just be a normal link or a broken link
1141 // we could potentially check if something is
1142 // "intra-doc-link-like" and warn in that case
1147 if let Ok(def) = resolve(cx, path_str, false) {
1150 // this could just be a normal link
1154 PathKind::Unknown => {
1156 if let Some(macro_def) = macro_resolve(cx, path_str) {
1157 if let Ok(type_def) = resolve(cx, path_str, false) {
1158 let (type_kind, article, type_disambig)
1159 = type_ns_kind(type_def.0, path_str);
1160 ambiguity_error(cx, &attrs, path_str,
1161 article, type_kind, &type_disambig,
1162 "a", "macro", &format!("macro@{}", path_str));
1164 } else if let Ok(value_def) = resolve(cx, path_str, true) {
1165 let (value_kind, value_disambig)
1166 = value_ns_kind(value_def.0, path_str)
1167 .expect("struct and mod cases should have been \
1168 caught in previous branch");
1169 ambiguity_error(cx, &attrs, path_str,
1170 "a", value_kind, &value_disambig,
1171 "a", "macro", &format!("macro@{}", path_str));
1174 } else if let Ok(type_def) = resolve(cx, path_str, false) {
1175 // It is imperative we search for not-a-value first
1176 // Otherwise we will find struct ctors for when we are looking
1177 // for structs, and the link won't work.
1178 // if there is something in both namespaces
1179 if let Ok(value_def) = resolve(cx, path_str, true) {
1180 let kind = value_ns_kind(value_def.0, path_str);
1181 if let Some((value_kind, value_disambig)) = kind {
1182 let (type_kind, article, type_disambig)
1183 = type_ns_kind(type_def.0, path_str);
1184 ambiguity_error(cx, &attrs, path_str,
1185 article, type_kind, &type_disambig,
1186 "a", value_kind, &value_disambig);
1191 } else if let Ok(value_def) = resolve(cx, path_str, true) {
1194 // this could just be a normal link
1198 PathKind::Macro => {
1199 if let Some(def) = macro_resolve(cx, path_str) {
1209 let id = register_def(cx, def);
1210 attrs.links.push((link, id, fragment));
1213 cx.sess().abort_if_errors();
1220 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
1221 pub struct TyParam {
1224 pub bounds: Vec<TyParamBound>,
1225 pub default: Option<Type>,
1228 impl Clean<TyParam> for hir::TyParam {
1229 fn clean(&self, cx: &DocContext) -> TyParam {
1231 name: self.name.clean(cx),
1232 did: cx.tcx.hir.local_def_id(self.id),
1233 bounds: self.bounds.clean(cx),
1234 default: self.default.clean(cx),
1239 impl<'tcx> Clean<TyParam> for ty::TypeParameterDef {
1240 fn clean(&self, cx: &DocContext) -> TyParam {
1241 cx.renderinfo.borrow_mut().external_typarams.insert(self.def_id, self.name.clean(cx));
1243 name: self.name.clean(cx),
1245 bounds: vec![], // these are filled in from the where-clauses
1246 default: if self.has_default {
1247 Some(cx.tcx.type_of(self.def_id).clean(cx))
1255 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
1256 pub enum TyParamBound {
1257 RegionBound(Lifetime),
1258 TraitBound(PolyTrait, hir::TraitBoundModifier)
1262 fn maybe_sized(cx: &DocContext) -> TyParamBound {
1263 let did = cx.tcx.require_lang_item(lang_items::SizedTraitLangItem);
1264 let empty = cx.tcx.intern_substs(&[]);
1265 let path = external_path(cx, &cx.tcx.item_name(did),
1266 Some(did), false, vec![], empty);
1267 inline::record_extern_fqn(cx, did, TypeKind::Trait);
1268 TraitBound(PolyTrait {
1269 trait_: ResolvedPath {
1275 generic_params: Vec::new(),
1276 }, hir::TraitBoundModifier::Maybe)
1279 fn is_sized_bound(&self, cx: &DocContext) -> bool {
1280 use rustc::hir::TraitBoundModifier as TBM;
1281 if let TyParamBound::TraitBound(PolyTrait { ref trait_, .. }, TBM::None) = *self {
1282 if trait_.def_id() == cx.tcx.lang_items().sized_trait() {
1289 fn get_poly_trait(&self) -> Option<PolyTrait> {
1290 if let TyParamBound::TraitBound(ref p, _) = *self {
1291 return Some(p.clone())
1296 fn get_trait_type(&self) -> Option<Type> {
1298 if let TyParamBound::TraitBound(PolyTrait { ref trait_, .. }, _) = *self {
1299 return Some(trait_.clone());
1305 impl Clean<TyParamBound> for hir::TyParamBound {
1306 fn clean(&self, cx: &DocContext) -> TyParamBound {
1308 hir::RegionTyParamBound(lt) => RegionBound(lt.clean(cx)),
1309 hir::TraitTyParamBound(ref t, modifier) => TraitBound(t.clean(cx), modifier),
1314 fn external_path_params(cx: &DocContext, trait_did: Option<DefId>, has_self: bool,
1315 bindings: Vec<TypeBinding>, substs: &Substs) -> PathParameters {
1316 let lifetimes = substs.regions().filter_map(|v| v.clean(cx)).collect();
1317 let types = substs.types().skip(has_self as usize).collect::<Vec<_>>();
1320 // Attempt to sugar an external path like Fn<(A, B,), C> to Fn(A, B) -> C
1321 Some(did) if cx.tcx.lang_items().fn_trait_kind(did).is_some() => {
1322 assert_eq!(types.len(), 1);
1323 let inputs = match types[0].sty {
1324 ty::TyTuple(ref tys, _) => tys.iter().map(|t| t.clean(cx)).collect(),
1326 return PathParameters::AngleBracketed {
1328 types: types.clean(cx),
1334 // FIXME(#20299) return type comes from a projection now
1335 // match types[1].sty {
1336 // ty::TyTuple(ref v, _) if v.is_empty() => None, // -> ()
1337 // _ => Some(types[1].clean(cx))
1339 PathParameters::Parenthesized {
1345 PathParameters::AngleBracketed {
1347 types: types.clean(cx),
1354 // trait_did should be set to a trait's DefId if called on a TraitRef, in order to sugar
1355 // from Fn<(A, B,), C> to Fn(A, B) -> C
1356 fn external_path(cx: &DocContext, name: &str, trait_did: Option<DefId>, has_self: bool,
1357 bindings: Vec<TypeBinding>, substs: &Substs) -> Path {
1361 segments: vec![PathSegment {
1362 name: name.to_string(),
1363 params: external_path_params(cx, trait_did, has_self, bindings, substs)
1368 impl<'tcx> Clean<TyParamBound> for ty::TraitRef<'tcx> {
1369 fn clean(&self, cx: &DocContext) -> TyParamBound {
1370 inline::record_extern_fqn(cx, self.def_id, TypeKind::Trait);
1371 let path = external_path(cx, &cx.tcx.item_name(self.def_id),
1372 Some(self.def_id), true, vec![], self.substs);
1374 debug!("ty::TraitRef\n subst: {:?}\n", self.substs);
1376 // collect any late bound regions
1377 let mut late_bounds = vec![];
1378 for ty_s in self.input_types().skip(1) {
1379 if let ty::TyTuple(ts, _) = ty_s.sty {
1381 if let ty::TyRef(ref reg, _) = ty_s.sty {
1382 if let &ty::RegionKind::ReLateBound(..) = *reg {
1383 debug!(" hit an ReLateBound {:?}", reg);
1384 if let Some(lt) = reg.clean(cx) {
1385 late_bounds.push(GenericParam::Lifetime(lt));
1395 trait_: ResolvedPath {
1401 generic_params: late_bounds,
1403 hir::TraitBoundModifier::None
1408 impl<'tcx> Clean<Option<Vec<TyParamBound>>> for Substs<'tcx> {
1409 fn clean(&self, cx: &DocContext) -> Option<Vec<TyParamBound>> {
1410 let mut v = Vec::new();
1411 v.extend(self.regions().filter_map(|r| r.clean(cx))
1413 v.extend(self.types().map(|t| TraitBound(PolyTrait {
1414 trait_: t.clean(cx),
1415 generic_params: Vec::new(),
1416 }, hir::TraitBoundModifier::None)));
1417 if !v.is_empty() {Some(v)} else {None}
1421 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
1422 pub struct Lifetime(String);
1425 pub fn get_ref<'a>(&'a self) -> &'a str {
1426 let Lifetime(ref s) = *self;
1431 pub fn statik() -> Lifetime {
1432 Lifetime("'static".to_string())
1436 impl Clean<Lifetime> for hir::Lifetime {
1437 fn clean(&self, cx: &DocContext) -> Lifetime {
1438 if self.id != ast::DUMMY_NODE_ID {
1439 let hir_id = cx.tcx.hir.node_to_hir_id(self.id);
1440 let def = cx.tcx.named_region(hir_id);
1442 Some(rl::Region::EarlyBound(_, node_id, _)) |
1443 Some(rl::Region::LateBound(_, node_id, _)) |
1444 Some(rl::Region::Free(_, node_id)) => {
1445 if let Some(lt) = cx.lt_substs.borrow().get(&node_id).cloned() {
1452 Lifetime(self.name.name().to_string())
1456 impl Clean<Lifetime> for hir::LifetimeDef {
1457 fn clean(&self, _: &DocContext) -> Lifetime {
1458 if self.bounds.len() > 0 {
1459 let mut s = format!("{}: {}",
1460 self.lifetime.name.name(),
1461 self.bounds[0].name.name());
1462 for bound in self.bounds.iter().skip(1) {
1463 s.push_str(&format!(" + {}", bound.name.name()));
1467 Lifetime(self.lifetime.name.name().to_string())
1472 impl Clean<Lifetime> for ty::RegionParameterDef {
1473 fn clean(&self, _: &DocContext) -> Lifetime {
1474 Lifetime(self.name.to_string())
1478 impl Clean<Option<Lifetime>> for ty::RegionKind {
1479 fn clean(&self, cx: &DocContext) -> Option<Lifetime> {
1481 ty::ReStatic => Some(Lifetime::statik()),
1482 ty::ReLateBound(_, ty::BrNamed(_, name)) => Some(Lifetime(name.to_string())),
1483 ty::ReEarlyBound(ref data) => Some(Lifetime(data.name.clean(cx))),
1485 ty::ReLateBound(..) |
1489 ty::ReSkolemized(..) |
1491 ty::ReClosureBound(_) |
1492 ty::ReErased => None
1497 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
1498 pub enum WherePredicate {
1499 BoundPredicate { ty: Type, bounds: Vec<TyParamBound> },
1500 RegionPredicate { lifetime: Lifetime, bounds: Vec<Lifetime>},
1501 EqPredicate { lhs: Type, rhs: Type },
1504 impl Clean<WherePredicate> for hir::WherePredicate {
1505 fn clean(&self, cx: &DocContext) -> WherePredicate {
1507 hir::WherePredicate::BoundPredicate(ref wbp) => {
1508 WherePredicate::BoundPredicate {
1509 ty: wbp.bounded_ty.clean(cx),
1510 bounds: wbp.bounds.clean(cx)
1514 hir::WherePredicate::RegionPredicate(ref wrp) => {
1515 WherePredicate::RegionPredicate {
1516 lifetime: wrp.lifetime.clean(cx),
1517 bounds: wrp.bounds.clean(cx)
1521 hir::WherePredicate::EqPredicate(ref wrp) => {
1522 WherePredicate::EqPredicate {
1523 lhs: wrp.lhs_ty.clean(cx),
1524 rhs: wrp.rhs_ty.clean(cx)
1531 impl<'a> Clean<WherePredicate> for ty::Predicate<'a> {
1532 fn clean(&self, cx: &DocContext) -> WherePredicate {
1533 use rustc::ty::Predicate;
1536 Predicate::Trait(ref pred) => pred.clean(cx),
1537 Predicate::Equate(ref pred) => pred.clean(cx),
1538 Predicate::Subtype(ref pred) => pred.clean(cx),
1539 Predicate::RegionOutlives(ref pred) => pred.clean(cx),
1540 Predicate::TypeOutlives(ref pred) => pred.clean(cx),
1541 Predicate::Projection(ref pred) => pred.clean(cx),
1542 Predicate::WellFormed(_) => panic!("not user writable"),
1543 Predicate::ObjectSafe(_) => panic!("not user writable"),
1544 Predicate::ClosureKind(..) => panic!("not user writable"),
1545 Predicate::ConstEvaluatable(..) => panic!("not user writable"),
1550 impl<'a> Clean<WherePredicate> for ty::TraitPredicate<'a> {
1551 fn clean(&self, cx: &DocContext) -> WherePredicate {
1552 WherePredicate::BoundPredicate {
1553 ty: self.trait_ref.self_ty().clean(cx),
1554 bounds: vec![self.trait_ref.clean(cx)]
1559 impl<'tcx> Clean<WherePredicate> for ty::EquatePredicate<'tcx> {
1560 fn clean(&self, cx: &DocContext) -> WherePredicate {
1561 let ty::EquatePredicate(ref lhs, ref rhs) = *self;
1562 WherePredicate::EqPredicate {
1569 impl<'tcx> Clean<WherePredicate> for ty::SubtypePredicate<'tcx> {
1570 fn clean(&self, _cx: &DocContext) -> WherePredicate {
1571 panic!("subtype predicates are an internal rustc artifact \
1572 and should not be seen by rustdoc")
1576 impl<'tcx> Clean<WherePredicate> for ty::OutlivesPredicate<ty::Region<'tcx>, ty::Region<'tcx>> {
1577 fn clean(&self, cx: &DocContext) -> WherePredicate {
1578 let ty::OutlivesPredicate(ref a, ref b) = *self;
1579 WherePredicate::RegionPredicate {
1580 lifetime: a.clean(cx).unwrap(),
1581 bounds: vec![b.clean(cx).unwrap()]
1586 impl<'tcx> Clean<WherePredicate> for ty::OutlivesPredicate<Ty<'tcx>, ty::Region<'tcx>> {
1587 fn clean(&self, cx: &DocContext) -> WherePredicate {
1588 let ty::OutlivesPredicate(ref ty, ref lt) = *self;
1590 WherePredicate::BoundPredicate {
1592 bounds: vec![TyParamBound::RegionBound(lt.clean(cx).unwrap())]
1597 impl<'tcx> Clean<WherePredicate> for ty::ProjectionPredicate<'tcx> {
1598 fn clean(&self, cx: &DocContext) -> WherePredicate {
1599 WherePredicate::EqPredicate {
1600 lhs: self.projection_ty.clean(cx),
1601 rhs: self.ty.clean(cx)
1606 impl<'tcx> Clean<Type> for ty::ProjectionTy<'tcx> {
1607 fn clean(&self, cx: &DocContext) -> Type {
1608 let trait_ = match self.trait_ref(cx.tcx).clean(cx) {
1609 TyParamBound::TraitBound(t, _) => t.trait_,
1610 TyParamBound::RegionBound(_) => {
1611 panic!("cleaning a trait got a region")
1615 name: cx.tcx.associated_item(self.item_def_id).name.clean(cx),
1616 self_type: box self.self_ty().clean(cx),
1622 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
1623 pub enum GenericParam {
1628 impl Clean<GenericParam> for hir::GenericParam {
1629 fn clean(&self, cx: &DocContext) -> GenericParam {
1631 hir::GenericParam::Lifetime(ref l) => GenericParam::Lifetime(l.clean(cx)),
1632 hir::GenericParam::Type(ref t) => GenericParam::Type(t.clean(cx)),
1637 // maybe use a Generic enum and use Vec<Generic>?
1638 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Default, Hash)]
1639 pub struct Generics {
1640 pub params: Vec<GenericParam>,
1641 pub where_predicates: Vec<WherePredicate>,
1644 impl Clean<Generics> for hir::Generics {
1645 fn clean(&self, cx: &DocContext) -> Generics {
1646 let mut g = Generics {
1647 params: self.params.clean(cx),
1648 where_predicates: self.where_clause.predicates.clean(cx)
1651 // Some duplicates are generated for ?Sized bounds between type params and where
1652 // predicates. The point in here is to move the bounds definitions from type params
1653 // to where predicates when such cases occur.
1654 for where_pred in &mut g.where_predicates {
1656 WherePredicate::BoundPredicate { ty: Generic(ref name), ref mut bounds } => {
1657 if bounds.is_empty() {
1658 for param in &mut g.params {
1659 if let GenericParam::Type(ref mut type_param) = *param {
1660 if &type_param.name == name {
1661 mem::swap(bounds, &mut type_param.bounds);
1675 impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics,
1676 &'a ty::GenericPredicates<'tcx>) {
1677 fn clean(&self, cx: &DocContext) -> Generics {
1678 use self::WherePredicate as WP;
1680 let (gens, preds) = *self;
1682 // Bounds in the type_params and lifetimes fields are repeated in the
1683 // predicates field (see rustc_typeck::collect::ty_generics), so remove
1685 let stripped_typarams = gens.types.iter().filter_map(|tp| {
1686 if tp.name == keywords::SelfType.name() {
1687 assert_eq!(tp.index, 0);
1692 }).collect::<Vec<_>>();
1694 let mut where_predicates = preds.predicates.to_vec().clean(cx);
1696 // Type parameters and have a Sized bound by default unless removed with
1697 // ?Sized. Scan through the predicates and mark any type parameter with
1698 // a Sized bound, removing the bounds as we find them.
1700 // Note that associated types also have a sized bound by default, but we
1701 // don't actually know the set of associated types right here so that's
1702 // handled in cleaning associated types
1703 let mut sized_params = FxHashSet();
1704 where_predicates.retain(|pred| {
1706 WP::BoundPredicate { ty: Generic(ref g), ref bounds } => {
1707 if bounds.iter().any(|b| b.is_sized_bound(cx)) {
1708 sized_params.insert(g.clone());
1718 // Run through the type parameters again and insert a ?Sized
1719 // unbound for any we didn't find to be Sized.
1720 for tp in &stripped_typarams {
1721 if !sized_params.contains(&tp.name) {
1722 where_predicates.push(WP::BoundPredicate {
1723 ty: Type::Generic(tp.name.clone()),
1724 bounds: vec![TyParamBound::maybe_sized(cx)],
1729 // It would be nice to collect all of the bounds on a type and recombine
1730 // them if possible, to avoid e.g. `where T: Foo, T: Bar, T: Sized, T: 'a`
1731 // and instead see `where T: Foo + Bar + Sized + 'a`
1734 params: gens.regions
1737 .map(|lp| GenericParam::Lifetime(lp))
1739 simplify::ty_params(stripped_typarams)
1741 .map(|tp| GenericParam::Type(tp))
1744 where_predicates: simplify::where_clauses(cx, where_predicates),
1749 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1751 pub generics: Generics,
1752 pub unsafety: hir::Unsafety,
1753 pub constness: hir::Constness,
1758 impl<'a> Clean<Method> for (&'a hir::MethodSig, &'a hir::Generics, hir::BodyId) {
1759 fn clean(&self, cx: &DocContext) -> Method {
1761 generics: self.1.clean(cx),
1762 unsafety: self.0.unsafety,
1763 constness: self.0.constness,
1764 decl: (&*self.0.decl, self.2).clean(cx),
1770 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1771 pub struct TyMethod {
1772 pub unsafety: hir::Unsafety,
1774 pub generics: Generics,
1778 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1779 pub struct Function {
1781 pub generics: Generics,
1782 pub unsafety: hir::Unsafety,
1783 pub constness: hir::Constness,
1787 impl Clean<Item> for doctree::Function {
1788 fn clean(&self, cx: &DocContext) -> Item {
1790 name: Some(self.name.clean(cx)),
1791 attrs: self.attrs.clean(cx),
1792 source: self.whence.clean(cx),
1793 visibility: self.vis.clean(cx),
1794 stability: self.stab.clean(cx),
1795 deprecation: self.depr.clean(cx),
1796 def_id: cx.tcx.hir.local_def_id(self.id),
1797 inner: FunctionItem(Function {
1798 decl: (&self.decl, self.body).clean(cx),
1799 generics: self.generics.clean(cx),
1800 unsafety: self.unsafety,
1801 constness: self.constness,
1808 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
1810 pub inputs: Arguments,
1811 pub output: FunctionRetTy,
1813 pub attrs: Attributes,
1817 pub fn has_self(&self) -> bool {
1818 self.inputs.values.len() > 0 && self.inputs.values[0].name == "self"
1821 pub fn self_type(&self) -> Option<SelfTy> {
1822 self.inputs.values.get(0).and_then(|v| v.to_self())
1826 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
1827 pub struct Arguments {
1828 pub values: Vec<Argument>,
1831 impl<'a> Clean<Arguments> for (&'a [P<hir::Ty>], &'a [Spanned<ast::Name>]) {
1832 fn clean(&self, cx: &DocContext) -> Arguments {
1834 values: self.0.iter().enumerate().map(|(i, ty)| {
1835 let mut name = self.1.get(i).map(|n| n.node.to_string())
1836 .unwrap_or(String::new());
1837 if name.is_empty() {
1838 name = "_".to_string();
1842 type_: ty.clean(cx),
1849 impl<'a> Clean<Arguments> for (&'a [P<hir::Ty>], hir::BodyId) {
1850 fn clean(&self, cx: &DocContext) -> Arguments {
1851 let body = cx.tcx.hir.body(self.1);
1854 values: self.0.iter().enumerate().map(|(i, ty)| {
1856 name: name_from_pat(&body.arguments[i].pat),
1857 type_: ty.clean(cx),
1864 impl<'a, A: Copy> Clean<FnDecl> for (&'a hir::FnDecl, A)
1865 where (&'a [P<hir::Ty>], A): Clean<Arguments>
1867 fn clean(&self, cx: &DocContext) -> FnDecl {
1869 inputs: (&self.0.inputs[..], self.1).clean(cx),
1870 output: self.0.output.clean(cx),
1871 variadic: self.0.variadic,
1872 attrs: Attributes::default()
1877 impl<'a, 'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
1878 fn clean(&self, cx: &DocContext) -> FnDecl {
1879 let (did, sig) = *self;
1880 let mut names = if cx.tcx.hir.as_local_node_id(did).is_some() {
1883 cx.tcx.fn_arg_names(did).into_iter()
1886 output: Return(sig.skip_binder().output().clean(cx)),
1887 attrs: Attributes::default(),
1888 variadic: sig.skip_binder().variadic,
1890 values: sig.skip_binder().inputs().iter().map(|t| {
1893 name: names.next().map_or("".to_string(), |name| name.to_string()),
1901 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
1902 pub struct Argument {
1907 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Debug)]
1910 SelfBorrowed(Option<Lifetime>, Mutability),
1915 pub fn to_self(&self) -> Option<SelfTy> {
1916 if self.name != "self" {
1919 if self.type_.is_self_type() {
1920 return Some(SelfValue);
1923 BorrowedRef{ref lifetime, mutability, ref type_} if type_.is_self_type() => {
1924 Some(SelfBorrowed(lifetime.clone(), mutability))
1926 _ => Some(SelfExplicit(self.type_.clone()))
1931 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
1932 pub enum FunctionRetTy {
1937 impl Clean<FunctionRetTy> for hir::FunctionRetTy {
1938 fn clean(&self, cx: &DocContext) -> FunctionRetTy {
1940 hir::Return(ref typ) => Return(typ.clean(cx)),
1941 hir::DefaultReturn(..) => DefaultReturn,
1946 impl GetDefId for FunctionRetTy {
1947 fn def_id(&self) -> Option<DefId> {
1949 Return(ref ty) => ty.def_id(),
1950 DefaultReturn => None,
1955 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
1958 pub unsafety: hir::Unsafety,
1959 pub items: Vec<Item>,
1960 pub generics: Generics,
1961 pub bounds: Vec<TyParamBound>,
1962 pub is_spotlight: bool,
1966 impl Clean<Item> for doctree::Trait {
1967 fn clean(&self, cx: &DocContext) -> Item {
1968 let attrs = self.attrs.clean(cx);
1969 let is_spotlight = attrs.has_doc_flag("spotlight");
1971 name: Some(self.name.clean(cx)),
1973 source: self.whence.clean(cx),
1974 def_id: cx.tcx.hir.local_def_id(self.id),
1975 visibility: self.vis.clean(cx),
1976 stability: self.stab.clean(cx),
1977 deprecation: self.depr.clean(cx),
1978 inner: TraitItem(Trait {
1979 auto: self.is_auto.clean(cx),
1980 unsafety: self.unsafety,
1981 items: self.items.clean(cx),
1982 generics: self.generics.clean(cx),
1983 bounds: self.bounds.clean(cx),
1984 is_spotlight: is_spotlight,
1985 is_auto: self.is_auto.clean(cx),
1991 impl Clean<bool> for hir::IsAuto {
1992 fn clean(&self, _: &DocContext) -> bool {
1994 hir::IsAuto::Yes => true,
1995 hir::IsAuto::No => false,
2000 impl Clean<Type> for hir::TraitRef {
2001 fn clean(&self, cx: &DocContext) -> Type {
2002 resolve_type(cx, self.path.clean(cx), self.ref_id)
2006 impl Clean<PolyTrait> for hir::PolyTraitRef {
2007 fn clean(&self, cx: &DocContext) -> PolyTrait {
2009 trait_: self.trait_ref.clean(cx),
2010 generic_params: self.bound_generic_params.clean(cx)
2015 impl Clean<Item> for hir::TraitItem {
2016 fn clean(&self, cx: &DocContext) -> Item {
2017 let inner = match self.node {
2018 hir::TraitItemKind::Const(ref ty, default) => {
2019 AssociatedConstItem(ty.clean(cx),
2020 default.map(|e| print_const_expr(cx, e)))
2022 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
2023 MethodItem((sig, &self.generics, body).clean(cx))
2025 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref names)) => {
2026 TyMethodItem(TyMethod {
2027 unsafety: sig.unsafety.clone(),
2028 decl: (&*sig.decl, &names[..]).clean(cx),
2029 generics: self.generics.clean(cx),
2033 hir::TraitItemKind::Type(ref bounds, ref default) => {
2034 AssociatedTypeItem(bounds.clean(cx), default.clean(cx))
2038 name: Some(self.name.clean(cx)),
2039 attrs: self.attrs.clean(cx),
2040 source: self.span.clean(cx),
2041 def_id: cx.tcx.hir.local_def_id(self.id),
2043 stability: get_stability(cx, cx.tcx.hir.local_def_id(self.id)),
2044 deprecation: get_deprecation(cx, cx.tcx.hir.local_def_id(self.id)),
2050 impl Clean<Item> for hir::ImplItem {
2051 fn clean(&self, cx: &DocContext) -> Item {
2052 let inner = match self.node {
2053 hir::ImplItemKind::Const(ref ty, expr) => {
2054 AssociatedConstItem(ty.clean(cx),
2055 Some(print_const_expr(cx, expr)))
2057 hir::ImplItemKind::Method(ref sig, body) => {
2058 MethodItem((sig, &self.generics, body).clean(cx))
2060 hir::ImplItemKind::Type(ref ty) => TypedefItem(Typedef {
2061 type_: ty.clean(cx),
2062 generics: Generics::default(),
2066 name: Some(self.name.clean(cx)),
2067 source: self.span.clean(cx),
2068 attrs: self.attrs.clean(cx),
2069 def_id: cx.tcx.hir.local_def_id(self.id),
2070 visibility: self.vis.clean(cx),
2071 stability: get_stability(cx, cx.tcx.hir.local_def_id(self.id)),
2072 deprecation: get_deprecation(cx, cx.tcx.hir.local_def_id(self.id)),
2078 impl<'tcx> Clean<Item> for ty::AssociatedItem {
2079 fn clean(&self, cx: &DocContext) -> Item {
2080 let inner = match self.kind {
2081 ty::AssociatedKind::Const => {
2082 let ty = cx.tcx.type_of(self.def_id);
2083 let default = if self.defaultness.has_value() {
2084 Some(inline::print_inlined_const(cx, self.def_id))
2088 AssociatedConstItem(ty.clean(cx), default)
2090 ty::AssociatedKind::Method => {
2091 let generics = (cx.tcx.generics_of(self.def_id),
2092 &cx.tcx.predicates_of(self.def_id)).clean(cx);
2093 let sig = cx.tcx.fn_sig(self.def_id);
2094 let mut decl = (self.def_id, sig).clean(cx);
2096 if self.method_has_self_argument {
2097 let self_ty = match self.container {
2098 ty::ImplContainer(def_id) => {
2099 cx.tcx.type_of(def_id)
2101 ty::TraitContainer(_) => cx.tcx.mk_self_type()
2103 let self_arg_ty = *sig.input(0).skip_binder();
2104 if self_arg_ty == self_ty {
2105 decl.inputs.values[0].type_ = Generic(String::from("Self"));
2106 } else if let ty::TyRef(_, mt) = self_arg_ty.sty {
2107 if mt.ty == self_ty {
2108 match decl.inputs.values[0].type_ {
2109 BorrowedRef{ref mut type_, ..} => {
2110 **type_ = Generic(String::from("Self"))
2112 _ => unreachable!(),
2118 let provided = match self.container {
2119 ty::ImplContainer(_) => true,
2120 ty::TraitContainer(_) => self.defaultness.has_value()
2123 let constness = if cx.tcx.is_const_fn(self.def_id) {
2124 hir::Constness::Const
2126 hir::Constness::NotConst
2129 unsafety: sig.unsafety(),
2136 TyMethodItem(TyMethod {
2137 unsafety: sig.unsafety(),
2144 ty::AssociatedKind::Type => {
2145 let my_name = self.name.clean(cx);
2147 if let ty::TraitContainer(did) = self.container {
2148 // When loading a cross-crate associated type, the bounds for this type
2149 // are actually located on the trait/impl itself, so we need to load
2150 // all of the generics from there and then look for bounds that are
2151 // applied to this associated type in question.
2152 let predicates = cx.tcx.predicates_of(did);
2153 let generics = (cx.tcx.generics_of(did), &predicates).clean(cx);
2154 let mut bounds = generics.where_predicates.iter().filter_map(|pred| {
2155 let (name, self_type, trait_, bounds) = match *pred {
2156 WherePredicate::BoundPredicate {
2157 ty: QPath { ref name, ref self_type, ref trait_ },
2159 } => (name, self_type, trait_, bounds),
2162 if *name != my_name { return None }
2164 ResolvedPath { did, .. } if did == self.container.id() => {}
2168 Generic(ref s) if *s == "Self" => {}
2172 }).flat_map(|i| i.iter().cloned()).collect::<Vec<_>>();
2173 // Our Sized/?Sized bound didn't get handled when creating the generics
2174 // because we didn't actually get our whole set of bounds until just now
2175 // (some of them may have come from the trait). If we do have a sized
2176 // bound, we remove it, and if we don't then we add the `?Sized` bound
2178 match bounds.iter().position(|b| b.is_sized_bound(cx)) {
2179 Some(i) => { bounds.remove(i); }
2180 None => bounds.push(TyParamBound::maybe_sized(cx)),
2183 let ty = if self.defaultness.has_value() {
2184 Some(cx.tcx.type_of(self.def_id))
2189 AssociatedTypeItem(bounds, ty.clean(cx))
2191 TypedefItem(Typedef {
2192 type_: cx.tcx.type_of(self.def_id).clean(cx),
2193 generics: Generics {
2195 where_predicates: Vec::new(),
2202 let visibility = match self.container {
2203 ty::ImplContainer(_) => self.vis.clean(cx),
2204 ty::TraitContainer(_) => None,
2208 name: Some(self.name.clean(cx)),
2210 stability: get_stability(cx, self.def_id),
2211 deprecation: get_deprecation(cx, self.def_id),
2212 def_id: self.def_id,
2213 attrs: inline::load_attrs(cx, self.def_id),
2214 source: cx.tcx.def_span(self.def_id).clean(cx),
2220 /// A trait reference, which may have higher ranked lifetimes.
2221 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
2222 pub struct PolyTrait {
2224 pub generic_params: Vec<GenericParam>,
2227 /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original
2228 /// type out of the AST/TyCtxt given one of these, if more information is needed. Most importantly
2229 /// it does not preserve mutability or boxes.
2230 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
2232 /// structs/enums/traits (most that'd be an hir::TyPath)
2235 typarams: Option<Vec<TyParamBound>>,
2237 /// true if is a `T::Name` path for associated types
2240 /// For parameterized types, so the consumer of the JSON don't go
2241 /// looking for types which don't exist anywhere.
2243 /// Primitives are the fixed-size numeric types (plus int/usize/float), char,
2244 /// arrays, slices, and tuples.
2245 Primitive(PrimitiveType),
2247 BareFunction(Box<BareFunctionDecl>),
2250 Array(Box<Type>, String),
2253 RawPointer(Mutability, Box<Type>),
2255 lifetime: Option<Lifetime>,
2256 mutability: Mutability,
2260 // <Type as Trait>::Name
2263 self_type: Box<Type>,
2270 // impl TraitA+TraitB
2271 ImplTrait(Vec<TyParamBound>),
2274 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy, Debug)]
2275 pub enum PrimitiveType {
2276 Isize, I8, I16, I32, I64, I128,
2277 Usize, U8, U16, U32, U64, U128,
2292 #[derive(Clone, RustcEncodable, RustcDecodable, Copy, Debug)]
2308 pub trait GetDefId {
2309 fn def_id(&self) -> Option<DefId>;
2312 impl<T: GetDefId> GetDefId for Option<T> {
2313 fn def_id(&self) -> Option<DefId> {
2314 self.as_ref().and_then(|d| d.def_id())
2319 pub fn primitive_type(&self) -> Option<PrimitiveType> {
2321 Primitive(p) | BorrowedRef { type_: box Primitive(p), ..} => Some(p),
2322 Slice(..) | BorrowedRef { type_: box Slice(..), .. } => Some(PrimitiveType::Slice),
2323 Array(..) | BorrowedRef { type_: box Array(..), .. } => Some(PrimitiveType::Array),
2324 Tuple(ref tys) => if tys.is_empty() {
2325 Some(PrimitiveType::Unit)
2327 Some(PrimitiveType::Tuple)
2329 RawPointer(..) => Some(PrimitiveType::RawPointer),
2330 BorrowedRef { type_: box Generic(..), .. } => Some(PrimitiveType::Reference),
2331 BareFunction(..) => Some(PrimitiveType::Fn),
2332 Never => Some(PrimitiveType::Never),
2337 pub fn is_generic(&self) -> bool {
2339 ResolvedPath { is_generic, .. } => is_generic,
2344 pub fn is_self_type(&self) -> bool {
2346 Generic(ref name) => name == "Self",
2351 pub fn generics(&self) -> Option<&[Type]> {
2353 ResolvedPath { ref path, .. } => {
2354 path.segments.last().and_then(|seg| {
2355 if let PathParameters::AngleBracketed { ref types, .. } = seg.params {
2367 impl GetDefId for Type {
2368 fn def_id(&self) -> Option<DefId> {
2370 ResolvedPath { did, .. } => Some(did),
2371 Primitive(p) => ::html::render::cache().primitive_locations.get(&p).cloned(),
2372 BorrowedRef { type_: box Generic(..), .. } =>
2373 Primitive(PrimitiveType::Reference).def_id(),
2374 BorrowedRef { ref type_, .. } => type_.def_id(),
2375 Tuple(ref tys) => if tys.is_empty() {
2376 Primitive(PrimitiveType::Unit).def_id()
2378 Primitive(PrimitiveType::Tuple).def_id()
2380 BareFunction(..) => Primitive(PrimitiveType::Fn).def_id(),
2381 Never => Primitive(PrimitiveType::Never).def_id(),
2382 Slice(..) => Primitive(PrimitiveType::Slice).def_id(),
2383 Array(..) => Primitive(PrimitiveType::Array).def_id(),
2384 RawPointer(..) => Primitive(PrimitiveType::RawPointer).def_id(),
2385 QPath { ref self_type, .. } => self_type.def_id(),
2391 impl PrimitiveType {
2392 fn from_str(s: &str) -> Option<PrimitiveType> {
2394 "isize" => Some(PrimitiveType::Isize),
2395 "i8" => Some(PrimitiveType::I8),
2396 "i16" => Some(PrimitiveType::I16),
2397 "i32" => Some(PrimitiveType::I32),
2398 "i64" => Some(PrimitiveType::I64),
2399 "i128" => Some(PrimitiveType::I128),
2400 "usize" => Some(PrimitiveType::Usize),
2401 "u8" => Some(PrimitiveType::U8),
2402 "u16" => Some(PrimitiveType::U16),
2403 "u32" => Some(PrimitiveType::U32),
2404 "u64" => Some(PrimitiveType::U64),
2405 "u128" => Some(PrimitiveType::U128),
2406 "bool" => Some(PrimitiveType::Bool),
2407 "char" => Some(PrimitiveType::Char),
2408 "str" => Some(PrimitiveType::Str),
2409 "f32" => Some(PrimitiveType::F32),
2410 "f64" => Some(PrimitiveType::F64),
2411 "array" => Some(PrimitiveType::Array),
2412 "slice" => Some(PrimitiveType::Slice),
2413 "tuple" => Some(PrimitiveType::Tuple),
2414 "unit" => Some(PrimitiveType::Unit),
2415 "pointer" => Some(PrimitiveType::RawPointer),
2416 "reference" => Some(PrimitiveType::Reference),
2417 "fn" => Some(PrimitiveType::Fn),
2418 "never" => Some(PrimitiveType::Never),
2423 pub fn as_str(&self) -> &'static str {
2424 use self::PrimitiveType::*;
2447 RawPointer => "pointer",
2448 Reference => "reference",
2454 pub fn to_url_str(&self) -> &'static str {
2459 impl From<ast::IntTy> for PrimitiveType {
2460 fn from(int_ty: ast::IntTy) -> PrimitiveType {
2462 ast::IntTy::Isize => PrimitiveType::Isize,
2463 ast::IntTy::I8 => PrimitiveType::I8,
2464 ast::IntTy::I16 => PrimitiveType::I16,
2465 ast::IntTy::I32 => PrimitiveType::I32,
2466 ast::IntTy::I64 => PrimitiveType::I64,
2467 ast::IntTy::I128 => PrimitiveType::I128,
2472 impl From<ast::UintTy> for PrimitiveType {
2473 fn from(uint_ty: ast::UintTy) -> PrimitiveType {
2475 ast::UintTy::Usize => PrimitiveType::Usize,
2476 ast::UintTy::U8 => PrimitiveType::U8,
2477 ast::UintTy::U16 => PrimitiveType::U16,
2478 ast::UintTy::U32 => PrimitiveType::U32,
2479 ast::UintTy::U64 => PrimitiveType::U64,
2480 ast::UintTy::U128 => PrimitiveType::U128,
2485 impl From<ast::FloatTy> for PrimitiveType {
2486 fn from(float_ty: ast::FloatTy) -> PrimitiveType {
2488 ast::FloatTy::F32 => PrimitiveType::F32,
2489 ast::FloatTy::F64 => PrimitiveType::F64,
2494 impl Clean<Type> for hir::Ty {
2495 fn clean(&self, cx: &DocContext) -> Type {
2499 TyPtr(ref m) => RawPointer(m.mutbl.clean(cx), box m.ty.clean(cx)),
2500 TyRptr(ref l, ref m) => {
2501 let lifetime = if l.is_elided() {
2506 BorrowedRef {lifetime: lifetime, mutability: m.mutbl.clean(cx),
2507 type_: box m.ty.clean(cx)}
2509 TySlice(ref ty) => Slice(box ty.clean(cx)),
2510 TyArray(ref ty, n) => {
2511 let def_id = cx.tcx.hir.body_owner_def_id(n);
2512 let param_env = cx.tcx.param_env(def_id);
2513 let substs = Substs::identity_for_item(cx.tcx, def_id);
2514 let n = cx.tcx.const_eval(param_env.and((def_id, substs))).unwrap_or_else(|_| {
2515 cx.tcx.mk_const(ty::Const {
2516 val: ConstVal::Unevaluated(def_id, substs),
2517 ty: cx.tcx.types.usize
2520 let n = if let ConstVal::Integral(ConstInt::Usize(n)) = n.val {
2522 } else if let ConstVal::Unevaluated(def_id, _) = n.val {
2523 if let Some(node_id) = cx.tcx.hir.as_local_node_id(def_id) {
2524 print_const_expr(cx, cx.tcx.hir.body_owned_by(node_id))
2526 inline::print_inlined_const(cx, def_id)
2531 Array(box ty.clean(cx), n)
2533 TyTup(ref tys) => Tuple(tys.clean(cx)),
2534 TyPath(hir::QPath::Resolved(None, ref path)) => {
2535 if let Some(new_ty) = cx.ty_substs.borrow().get(&path.def).cloned() {
2539 let mut alias = None;
2540 if let Def::TyAlias(def_id) = path.def {
2541 // Substitute private type aliases
2542 if let Some(node_id) = cx.tcx.hir.as_local_node_id(def_id) {
2543 if !cx.access_levels.borrow().is_exported(def_id) {
2544 alias = Some(&cx.tcx.hir.expect_item(node_id).node);
2549 if let Some(&hir::ItemTy(ref ty, ref generics)) = alias {
2550 let provided_params = &path.segments.last().unwrap();
2551 let mut ty_substs = FxHashMap();
2552 let mut lt_substs = FxHashMap();
2553 provided_params.with_parameters(|provided_params| {
2554 for (i, ty_param) in generics.ty_params().enumerate() {
2555 let ty_param_def = Def::TyParam(cx.tcx.hir.local_def_id(ty_param.id));
2556 if let Some(ty) = provided_params.types.get(i).cloned() {
2557 ty_substs.insert(ty_param_def, ty.into_inner().clean(cx));
2558 } else if let Some(default) = ty_param.default.clone() {
2559 ty_substs.insert(ty_param_def, default.into_inner().clean(cx));
2563 for (i, lt_param) in generics.lifetimes().enumerate() {
2564 if let Some(lt) = provided_params.lifetimes.get(i).cloned() {
2565 if !lt.is_elided() {
2566 let lt_def_id = cx.tcx.hir.local_def_id(lt_param.lifetime.id);
2567 lt_substs.insert(lt_def_id, lt.clean(cx));
2572 return cx.enter_alias(ty_substs, lt_substs, || ty.clean(cx));
2574 resolve_type(cx, path.clean(cx), self.id)
2576 TyPath(hir::QPath::Resolved(Some(ref qself), ref p)) => {
2577 let mut segments: Vec<_> = p.segments.clone().into();
2579 let trait_path = hir::Path {
2581 def: Def::Trait(cx.tcx.associated_item(p.def.def_id()).container.id()),
2582 segments: segments.into(),
2585 name: p.segments.last().unwrap().name.clean(cx),
2586 self_type: box qself.clean(cx),
2587 trait_: box resolve_type(cx, trait_path.clean(cx), self.id)
2590 TyPath(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2591 let mut def = Def::Err;
2592 let ty = hir_ty_to_ty(cx.tcx, self);
2593 if let ty::TyProjection(proj) = ty.sty {
2594 def = Def::Trait(proj.trait_ref(cx.tcx).def_id);
2596 let trait_path = hir::Path {
2599 segments: vec![].into(),
2602 name: segment.name.clean(cx),
2603 self_type: box qself.clean(cx),
2604 trait_: box resolve_type(cx, trait_path.clean(cx), self.id)
2607 TyTraitObject(ref bounds, ref lifetime) => {
2608 match bounds[0].clean(cx).trait_ {
2609 ResolvedPath { path, typarams: None, did, is_generic } => {
2610 let mut bounds: Vec<_> = bounds[1..].iter().map(|bound| {
2611 TraitBound(bound.clean(cx), hir::TraitBoundModifier::None)
2613 if !lifetime.is_elided() {
2614 bounds.push(RegionBound(lifetime.clean(cx)));
2618 typarams: Some(bounds),
2623 _ => Infer // shouldn't happen
2626 TyBareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
2627 TyImplTraitExistential(ref exist_ty, ref _lts) => ImplTrait(exist_ty.bounds.clean(cx)),
2628 TyInfer | TyErr => Infer,
2629 TyTypeof(..) => panic!("Unimplemented type {:?}", self.node),
2634 impl<'tcx> Clean<Type> for Ty<'tcx> {
2635 fn clean(&self, cx: &DocContext) -> Type {
2637 ty::TyNever => Never,
2638 ty::TyBool => Primitive(PrimitiveType::Bool),
2639 ty::TyChar => Primitive(PrimitiveType::Char),
2640 ty::TyInt(int_ty) => Primitive(int_ty.into()),
2641 ty::TyUint(uint_ty) => Primitive(uint_ty.into()),
2642 ty::TyFloat(float_ty) => Primitive(float_ty.into()),
2643 ty::TyStr => Primitive(PrimitiveType::Str),
2644 ty::TySlice(ty) => Slice(box ty.clean(cx)),
2645 ty::TyArray(ty, n) => {
2646 let mut n = cx.tcx.lift(&n).unwrap();
2647 if let ConstVal::Unevaluated(def_id, substs) = n.val {
2648 let param_env = cx.tcx.param_env(def_id);
2649 if let Ok(new_n) = cx.tcx.const_eval(param_env.and((def_id, substs))) {
2653 let n = if let ConstVal::Integral(ConstInt::Usize(n)) = n.val {
2655 } else if let ConstVal::Unevaluated(def_id, _) = n.val {
2656 if let Some(node_id) = cx.tcx.hir.as_local_node_id(def_id) {
2657 print_const_expr(cx, cx.tcx.hir.body_owned_by(node_id))
2659 inline::print_inlined_const(cx, def_id)
2664 Array(box ty.clean(cx), n)
2666 ty::TyRawPtr(mt) => RawPointer(mt.mutbl.clean(cx), box mt.ty.clean(cx)),
2667 ty::TyRef(r, mt) => BorrowedRef {
2668 lifetime: r.clean(cx),
2669 mutability: mt.mutbl.clean(cx),
2670 type_: box mt.ty.clean(cx),
2674 let ty = cx.tcx.lift(self).unwrap();
2675 let sig = ty.fn_sig(cx.tcx);
2676 BareFunction(box BareFunctionDecl {
2677 unsafety: sig.unsafety(),
2678 generic_params: Vec::new(),
2679 decl: (cx.tcx.hir.local_def_id(ast::CRATE_NODE_ID), sig).clean(cx),
2683 ty::TyAdt(def, substs) => {
2685 let kind = match def.adt_kind() {
2686 AdtKind::Struct => TypeKind::Struct,
2687 AdtKind::Union => TypeKind::Union,
2688 AdtKind::Enum => TypeKind::Enum,
2690 inline::record_extern_fqn(cx, did, kind);
2691 let path = external_path(cx, &cx.tcx.item_name(did),
2692 None, false, vec![], substs);
2700 ty::TyForeign(did) => {
2701 inline::record_extern_fqn(cx, did, TypeKind::Foreign);
2702 let path = external_path(cx, &cx.tcx.item_name(did),
2703 None, false, vec![], Substs::empty());
2711 ty::TyDynamic(ref obj, ref reg) => {
2712 if let Some(principal) = obj.principal() {
2713 let did = principal.def_id();
2714 inline::record_extern_fqn(cx, did, TypeKind::Trait);
2716 let mut typarams = vec![];
2717 reg.clean(cx).map(|b| typarams.push(RegionBound(b)));
2718 for did in obj.auto_traits() {
2719 let empty = cx.tcx.intern_substs(&[]);
2720 let path = external_path(cx, &cx.tcx.item_name(did),
2721 Some(did), false, vec![], empty);
2722 inline::record_extern_fqn(cx, did, TypeKind::Trait);
2723 let bound = TraitBound(PolyTrait {
2724 trait_: ResolvedPath {
2730 generic_params: Vec::new(),
2731 }, hir::TraitBoundModifier::None);
2732 typarams.push(bound);
2735 let mut bindings = vec![];
2736 for ty::Binder(ref pb) in obj.projection_bounds() {
2737 bindings.push(TypeBinding {
2738 name: cx.tcx.associated_item(pb.item_def_id).name.clean(cx),
2743 let path = external_path(cx, &cx.tcx.item_name(did), Some(did),
2744 false, bindings, principal.0.substs);
2747 typarams: Some(typarams),
2755 ty::TyTuple(ref t, _) => Tuple(t.clean(cx)),
2757 ty::TyProjection(ref data) => data.clean(cx),
2759 ty::TyParam(ref p) => Generic(p.name.to_string()),
2761 ty::TyAnon(def_id, substs) => {
2762 // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
2763 // by looking up the projections associated with the def_id.
2764 let predicates_of = cx.tcx.predicates_of(def_id);
2765 let substs = cx.tcx.lift(&substs).unwrap();
2766 let bounds = predicates_of.instantiate(cx.tcx, substs);
2767 ImplTrait(bounds.predicates.into_iter().filter_map(|predicate| {
2768 predicate.to_opt_poly_trait_ref().clean(cx)
2772 ty::TyClosure(..) | ty::TyGenerator(..) => Tuple(vec![]), // FIXME(pcwalton)
2774 ty::TyGeneratorWitness(..) => panic!("TyGeneratorWitness"),
2775 ty::TyInfer(..) => panic!("TyInfer"),
2776 ty::TyError => panic!("TyError"),
2781 impl Clean<Item> for hir::StructField {
2782 fn clean(&self, cx: &DocContext) -> Item {
2784 name: Some(self.name).clean(cx),
2785 attrs: self.attrs.clean(cx),
2786 source: self.span.clean(cx),
2787 visibility: self.vis.clean(cx),
2788 stability: get_stability(cx, cx.tcx.hir.local_def_id(self.id)),
2789 deprecation: get_deprecation(cx, cx.tcx.hir.local_def_id(self.id)),
2790 def_id: cx.tcx.hir.local_def_id(self.id),
2791 inner: StructFieldItem(self.ty.clean(cx)),
2796 impl<'tcx> Clean<Item> for ty::FieldDef {
2797 fn clean(&self, cx: &DocContext) -> Item {
2799 name: Some(self.name).clean(cx),
2800 attrs: cx.tcx.get_attrs(self.did).clean(cx),
2801 source: cx.tcx.def_span(self.did).clean(cx),
2802 visibility: self.vis.clean(cx),
2803 stability: get_stability(cx, self.did),
2804 deprecation: get_deprecation(cx, self.did),
2806 inner: StructFieldItem(cx.tcx.type_of(self.did).clean(cx)),
2811 #[derive(Clone, PartialEq, Eq, RustcDecodable, RustcEncodable, Debug)]
2812 pub enum Visibility {
2817 impl Clean<Option<Visibility>> for hir::Visibility {
2818 fn clean(&self, _: &DocContext) -> Option<Visibility> {
2819 Some(if *self == hir::Visibility::Public { Public } else { Inherited })
2823 impl Clean<Option<Visibility>> for ty::Visibility {
2824 fn clean(&self, _: &DocContext) -> Option<Visibility> {
2825 Some(if *self == ty::Visibility::Public { Public } else { Inherited })
2829 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2831 pub struct_type: doctree::StructType,
2832 pub generics: Generics,
2833 pub fields: Vec<Item>,
2834 pub fields_stripped: bool,
2837 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2839 pub struct_type: doctree::StructType,
2840 pub generics: Generics,
2841 pub fields: Vec<Item>,
2842 pub fields_stripped: bool,
2845 impl Clean<Vec<Item>> for doctree::Struct {
2846 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2847 let name = self.name.clean(cx);
2848 let mut ret = get_auto_traits_with_node_id(cx, self.id, name.clone());
2852 attrs: self.attrs.clean(cx),
2853 source: self.whence.clean(cx),
2854 def_id: cx.tcx.hir.local_def_id(self.id),
2855 visibility: self.vis.clean(cx),
2856 stability: self.stab.clean(cx),
2857 deprecation: self.depr.clean(cx),
2858 inner: StructItem(Struct {
2859 struct_type: self.struct_type,
2860 generics: self.generics.clean(cx),
2861 fields: self.fields.clean(cx),
2862 fields_stripped: false,
2870 impl Clean<Vec<Item>> for doctree::Union {
2871 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2872 let name = self.name.clean(cx);
2873 let mut ret = get_auto_traits_with_node_id(cx, self.id, name.clone());
2877 attrs: self.attrs.clean(cx),
2878 source: self.whence.clean(cx),
2879 def_id: cx.tcx.hir.local_def_id(self.id),
2880 visibility: self.vis.clean(cx),
2881 stability: self.stab.clean(cx),
2882 deprecation: self.depr.clean(cx),
2883 inner: UnionItem(Union {
2884 struct_type: self.struct_type,
2885 generics: self.generics.clean(cx),
2886 fields: self.fields.clean(cx),
2887 fields_stripped: false,
2895 /// This is a more limited form of the standard Struct, different in that
2896 /// it lacks the things most items have (name, id, parameterization). Found
2897 /// only as a variant in an enum.
2898 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2899 pub struct VariantStruct {
2900 pub struct_type: doctree::StructType,
2901 pub fields: Vec<Item>,
2902 pub fields_stripped: bool,
2905 impl Clean<VariantStruct> for ::rustc::hir::VariantData {
2906 fn clean(&self, cx: &DocContext) -> VariantStruct {
2908 struct_type: doctree::struct_type_from_def(self),
2909 fields: self.fields().iter().map(|x| x.clean(cx)).collect(),
2910 fields_stripped: false,
2915 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2917 pub variants: Vec<Item>,
2918 pub generics: Generics,
2919 pub variants_stripped: bool,
2922 impl Clean<Vec<Item>> for doctree::Enum {
2923 fn clean(&self, cx: &DocContext) -> Vec<Item> {
2924 let name = self.name.clean(cx);
2925 let mut ret = get_auto_traits_with_node_id(cx, self.id, name.clone());
2929 attrs: self.attrs.clean(cx),
2930 source: self.whence.clean(cx),
2931 def_id: cx.tcx.hir.local_def_id(self.id),
2932 visibility: self.vis.clean(cx),
2933 stability: self.stab.clean(cx),
2934 deprecation: self.depr.clean(cx),
2935 inner: EnumItem(Enum {
2936 variants: self.variants.clean(cx),
2937 generics: self.generics.clean(cx),
2938 variants_stripped: false,
2946 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
2947 pub struct Variant {
2948 pub kind: VariantKind,
2951 impl Clean<Item> for doctree::Variant {
2952 fn clean(&self, cx: &DocContext) -> Item {
2954 name: Some(self.name.clean(cx)),
2955 attrs: self.attrs.clean(cx),
2956 source: self.whence.clean(cx),
2958 stability: self.stab.clean(cx),
2959 deprecation: self.depr.clean(cx),
2960 def_id: cx.tcx.hir.local_def_id(self.def.id()),
2961 inner: VariantItem(Variant {
2962 kind: self.def.clean(cx),
2968 impl<'tcx> Clean<Item> for ty::VariantDef {
2969 fn clean(&self, cx: &DocContext) -> Item {
2970 let kind = match self.ctor_kind {
2971 CtorKind::Const => VariantKind::CLike,
2974 self.fields.iter().map(|f| cx.tcx.type_of(f.did).clean(cx)).collect()
2977 CtorKind::Fictive => {
2978 VariantKind::Struct(VariantStruct {
2979 struct_type: doctree::Plain,
2980 fields_stripped: false,
2981 fields: self.fields.iter().map(|field| {
2983 source: cx.tcx.def_span(field.did).clean(cx),
2984 name: Some(field.name.clean(cx)),
2985 attrs: cx.tcx.get_attrs(field.did).clean(cx),
2986 visibility: field.vis.clean(cx),
2988 stability: get_stability(cx, field.did),
2989 deprecation: get_deprecation(cx, field.did),
2990 inner: StructFieldItem(cx.tcx.type_of(field.did).clean(cx))
2997 name: Some(self.name.clean(cx)),
2998 attrs: inline::load_attrs(cx, self.did),
2999 source: cx.tcx.def_span(self.did).clean(cx),
3000 visibility: Some(Inherited),
3002 inner: VariantItem(Variant { kind: kind }),
3003 stability: get_stability(cx, self.did),
3004 deprecation: get_deprecation(cx, self.did),
3009 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
3010 pub enum VariantKind {
3013 Struct(VariantStruct),
3016 impl Clean<VariantKind> for hir::VariantData {
3017 fn clean(&self, cx: &DocContext) -> VariantKind {
3018 if self.is_struct() {
3019 VariantKind::Struct(self.clean(cx))
3020 } else if self.is_unit() {
3023 VariantKind::Tuple(self.fields().iter().map(|x| x.ty.clean(cx)).collect())
3028 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
3030 pub filename: FileName,
3038 pub fn empty() -> Span {
3040 filename: FileName::Anon,
3041 loline: 0, locol: 0,
3042 hiline: 0, hicol: 0,
3047 impl Clean<Span> for syntax_pos::Span {
3048 fn clean(&self, cx: &DocContext) -> Span {
3049 if *self == DUMMY_SP {
3050 return Span::empty();
3053 let cm = cx.sess().codemap();
3054 let filename = cm.span_to_filename(*self);
3055 let lo = cm.lookup_char_pos(self.lo());
3056 let hi = cm.lookup_char_pos(self.hi());
3060 locol: lo.col.to_usize(),
3062 hicol: hi.col.to_usize(),
3067 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
3071 pub segments: Vec<PathSegment>,
3075 pub fn singleton(name: String) -> Path {
3079 segments: vec![PathSegment {
3081 params: PathParameters::AngleBracketed {
3082 lifetimes: Vec::new(),
3084 bindings: Vec::new(),
3090 pub fn last_name(&self) -> &str {
3091 self.segments.last().unwrap().name.as_str()
3095 impl Clean<Path> for hir::Path {
3096 fn clean(&self, cx: &DocContext) -> Path {
3098 global: self.is_global(),
3100 segments: if self.is_global() { &self.segments[1..] } else { &self.segments }.clean(cx),
3105 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
3106 pub enum PathParameters {
3108 lifetimes: Vec<Lifetime>,
3110 bindings: Vec<TypeBinding>,
3114 output: Option<Type>,
3118 impl Clean<PathParameters> for hir::PathParameters {
3119 fn clean(&self, cx: &DocContext) -> PathParameters {
3120 if self.parenthesized {
3121 let output = self.bindings[0].ty.clean(cx);
3122 PathParameters::Parenthesized {
3123 inputs: self.inputs().clean(cx),
3124 output: if output != Type::Tuple(Vec::new()) { Some(output) } else { None }
3127 PathParameters::AngleBracketed {
3128 lifetimes: if self.lifetimes.iter().all(|lt| lt.is_elided()) {
3131 self.lifetimes.clean(cx)
3133 types: self.types.clean(cx),
3134 bindings: self.bindings.clean(cx),
3140 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
3141 pub struct PathSegment {
3143 pub params: PathParameters,
3146 impl Clean<PathSegment> for hir::PathSegment {
3147 fn clean(&self, cx: &DocContext) -> PathSegment {
3149 name: self.name.clean(cx),
3150 params: self.with_parameters(|parameters| parameters.clean(cx))
3155 fn strip_type(ty: Type) -> Type {
3157 Type::ResolvedPath { path, typarams, did, is_generic } => {
3158 Type::ResolvedPath { path: strip_path(&path), typarams, did, is_generic }
3160 Type::Tuple(inner_tys) => {
3161 Type::Tuple(inner_tys.iter().map(|t| strip_type(t.clone())).collect())
3163 Type::Slice(inner_ty) => Type::Slice(Box::new(strip_type(*inner_ty))),
3164 Type::Array(inner_ty, s) => Type::Array(Box::new(strip_type(*inner_ty)), s),
3165 Type::Unique(inner_ty) => Type::Unique(Box::new(strip_type(*inner_ty))),
3166 Type::RawPointer(m, inner_ty) => Type::RawPointer(m, Box::new(strip_type(*inner_ty))),
3167 Type::BorrowedRef { lifetime, mutability, type_ } => {
3168 Type::BorrowedRef { lifetime, mutability, type_: Box::new(strip_type(*type_)) }
3170 Type::QPath { name, self_type, trait_ } => {
3173 self_type: Box::new(strip_type(*self_type)), trait_: Box::new(strip_type(*trait_))
3180 fn strip_path(path: &Path) -> Path {
3181 let segments = path.segments.iter().map(|s| {
3183 name: s.name.clone(),
3184 params: PathParameters::AngleBracketed {
3185 lifetimes: Vec::new(),
3187 bindings: Vec::new(),
3193 global: path.global,
3194 def: path.def.clone(),
3199 fn qpath_to_string(p: &hir::QPath) -> String {
3200 let segments = match *p {
3201 hir::QPath::Resolved(_, ref path) => &path.segments,
3202 hir::QPath::TypeRelative(_, ref segment) => return segment.name.to_string(),
3205 let mut s = String::new();
3206 for (i, seg) in segments.iter().enumerate() {
3210 if seg.name != keywords::CrateRoot.name() {
3211 s.push_str(&*seg.name.as_str());
3217 impl Clean<String> for ast::Name {
3218 fn clean(&self, _: &DocContext) -> String {
3223 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
3224 pub struct Typedef {
3226 pub generics: Generics,
3229 impl Clean<Item> for doctree::Typedef {
3230 fn clean(&self, cx: &DocContext) -> Item {
3232 name: Some(self.name.clean(cx)),
3233 attrs: self.attrs.clean(cx),
3234 source: self.whence.clean(cx),
3235 def_id: cx.tcx.hir.local_def_id(self.id.clone()),
3236 visibility: self.vis.clean(cx),
3237 stability: self.stab.clean(cx),
3238 deprecation: self.depr.clean(cx),
3239 inner: TypedefItem(Typedef {
3240 type_: self.ty.clean(cx),
3241 generics: self.gen.clean(cx),
3247 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
3248 pub struct BareFunctionDecl {
3249 pub unsafety: hir::Unsafety,
3250 pub generic_params: Vec<GenericParam>,
3255 impl Clean<BareFunctionDecl> for hir::BareFnTy {
3256 fn clean(&self, cx: &DocContext) -> BareFunctionDecl {
3258 unsafety: self.unsafety,
3259 generic_params: self.generic_params.clean(cx),
3260 decl: (&*self.decl, &self.arg_names[..]).clean(cx),
3266 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
3269 pub mutability: Mutability,
3270 /// It's useful to have the value of a static documented, but I have no
3271 /// desire to represent expressions (that'd basically be all of the AST,
3272 /// which is huge!). So, have a string.
3276 impl Clean<Item> for doctree::Static {
3277 fn clean(&self, cx: &DocContext) -> Item {
3278 debug!("cleaning static {}: {:?}", self.name.clean(cx), self);
3280 name: Some(self.name.clean(cx)),
3281 attrs: self.attrs.clean(cx),
3282 source: self.whence.clean(cx),
3283 def_id: cx.tcx.hir.local_def_id(self.id),
3284 visibility: self.vis.clean(cx),
3285 stability: self.stab.clean(cx),
3286 deprecation: self.depr.clean(cx),
3287 inner: StaticItem(Static {
3288 type_: self.type_.clean(cx),
3289 mutability: self.mutability.clean(cx),
3290 expr: print_const_expr(cx, self.expr),
3296 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
3297 pub struct Constant {
3302 impl Clean<Item> for doctree::Constant {
3303 fn clean(&self, cx: &DocContext) -> Item {
3305 name: Some(self.name.clean(cx)),
3306 attrs: self.attrs.clean(cx),
3307 source: self.whence.clean(cx),
3308 def_id: cx.tcx.hir.local_def_id(self.id),
3309 visibility: self.vis.clean(cx),
3310 stability: self.stab.clean(cx),
3311 deprecation: self.depr.clean(cx),
3312 inner: ConstantItem(Constant {
3313 type_: self.type_.clean(cx),
3314 expr: print_const_expr(cx, self.expr),
3320 #[derive(Debug, Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Copy, Hash)]
3321 pub enum Mutability {
3326 impl Clean<Mutability> for hir::Mutability {
3327 fn clean(&self, _: &DocContext) -> Mutability {
3329 &hir::MutMutable => Mutable,
3330 &hir::MutImmutable => Immutable,
3335 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Copy, Debug, Hash)]
3336 pub enum ImplPolarity {
3341 impl Clean<ImplPolarity> for hir::ImplPolarity {
3342 fn clean(&self, _: &DocContext) -> ImplPolarity {
3344 &hir::ImplPolarity::Positive => ImplPolarity::Positive,
3345 &hir::ImplPolarity::Negative => ImplPolarity::Negative,
3350 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
3352 pub unsafety: hir::Unsafety,
3353 pub generics: Generics,
3354 pub provided_trait_methods: FxHashSet<String>,
3355 pub trait_: Option<Type>,
3357 pub items: Vec<Item>,
3358 pub polarity: Option<ImplPolarity>,
3359 pub synthetic: bool,
3362 pub fn get_auto_traits_with_node_id(cx: &DocContext, id: ast::NodeId, name: String) -> Vec<Item> {
3363 let finder = AutoTraitFinder { cx };
3364 finder.get_with_node_id(id, name)
3367 pub fn get_auto_traits_with_def_id(cx: &DocContext, id: DefId) -> Vec<Item> {
3368 let finder = AutoTraitFinder {
3372 finder.get_with_def_id(id)
3375 impl Clean<Vec<Item>> for doctree::Impl {
3376 fn clean(&self, cx: &DocContext) -> Vec<Item> {
3377 let mut ret = Vec::new();
3378 let trait_ = self.trait_.clean(cx);
3379 let items = self.items.clean(cx);
3381 // If this impl block is an implementation of the Deref trait, then we
3382 // need to try inlining the target's inherent impl blocks as well.
3383 if trait_.def_id() == cx.tcx.lang_items().deref_trait() {
3384 build_deref_target_impls(cx, &items, &mut ret);
3387 let provided = trait_.def_id().map(|did| {
3388 cx.tcx.provided_trait_methods(did)
3390 .map(|meth| meth.name.to_string())
3392 }).unwrap_or(FxHashSet());
3396 attrs: self.attrs.clean(cx),
3397 source: self.whence.clean(cx),
3398 def_id: cx.tcx.hir.local_def_id(self.id),
3399 visibility: self.vis.clean(cx),
3400 stability: self.stab.clean(cx),
3401 deprecation: self.depr.clean(cx),
3402 inner: ImplItem(Impl {
3403 unsafety: self.unsafety,
3404 generics: self.generics.clean(cx),
3405 provided_trait_methods: provided,
3407 for_: self.for_.clean(cx),
3409 polarity: Some(self.polarity.clean(cx)),
3417 fn build_deref_target_impls(cx: &DocContext,
3419 ret: &mut Vec<Item>) {
3420 use self::PrimitiveType::*;
3424 let target = match item.inner {
3425 TypedefItem(ref t, true) => &t.type_,
3428 let primitive = match *target {
3429 ResolvedPath { did, .. } if did.is_local() => continue,
3430 ResolvedPath { did, .. } => {
3431 // We set the last parameter to false to avoid looking for auto-impls for traits
3432 // and therefore avoid an ICE.
3433 // The reason behind this is that auto-traits don't propagate through Deref so
3434 // we're not supposed to synthesise impls for them.
3435 ret.extend(inline::build_impls(cx, did, false));
3438 _ => match target.primitive_type() {
3443 let did = match primitive {
3444 Isize => tcx.lang_items().isize_impl(),
3445 I8 => tcx.lang_items().i8_impl(),
3446 I16 => tcx.lang_items().i16_impl(),
3447 I32 => tcx.lang_items().i32_impl(),
3448 I64 => tcx.lang_items().i64_impl(),
3449 I128 => tcx.lang_items().i128_impl(),
3450 Usize => tcx.lang_items().usize_impl(),
3451 U8 => tcx.lang_items().u8_impl(),
3452 U16 => tcx.lang_items().u16_impl(),
3453 U32 => tcx.lang_items().u32_impl(),
3454 U64 => tcx.lang_items().u64_impl(),
3455 U128 => tcx.lang_items().u128_impl(),
3456 F32 => tcx.lang_items().f32_impl(),
3457 F64 => tcx.lang_items().f64_impl(),
3458 Char => tcx.lang_items().char_impl(),
3460 Str => tcx.lang_items().str_impl(),
3461 Slice => tcx.lang_items().slice_impl(),
3462 Array => tcx.lang_items().slice_impl(),
3465 RawPointer => tcx.lang_items().const_ptr_impl(),
3470 if let Some(did) = did {
3471 if !did.is_local() {
3472 inline::build_impl(cx, did, ret);
3478 impl Clean<Item> for doctree::ExternCrate {
3479 fn clean(&self, cx: &DocContext) -> Item {
3482 attrs: self.attrs.clean(cx),
3483 source: self.whence.clean(cx),
3484 def_id: DefId { krate: self.cnum, index: CRATE_DEF_INDEX },
3485 visibility: self.vis.clean(cx),
3488 inner: ExternCrateItem(self.name.clean(cx), self.path.clone())
3493 impl Clean<Vec<Item>> for doctree::Import {
3494 fn clean(&self, cx: &DocContext) -> Vec<Item> {
3495 // We consider inlining the documentation of `pub use` statements, but we
3496 // forcefully don't inline if this is not public or if the
3497 // #[doc(no_inline)] attribute is present.
3498 // Don't inline doc(hidden) imports so they can be stripped at a later stage.
3499 let denied = self.vis != hir::Public || self.attrs.iter().any(|a| {
3500 a.name().unwrap() == "doc" && match a.meta_item_list() {
3501 Some(l) => attr::list_contains_name(&l, "no_inline") ||
3502 attr::list_contains_name(&l, "hidden"),
3506 let path = self.path.clean(cx);
3507 let inner = if self.glob {
3508 Import::Glob(resolve_use_source(cx, path))
3510 let name = self.name;
3512 if let Some(items) = inline::try_inline(cx, path.def, name) {
3516 Import::Simple(name.clean(cx), resolve_use_source(cx, path))
3520 attrs: self.attrs.clean(cx),
3521 source: self.whence.clean(cx),
3522 def_id: cx.tcx.hir.local_def_id(ast::CRATE_NODE_ID),
3523 visibility: self.vis.clean(cx),
3526 inner: ImportItem(inner)
3531 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
3533 // use source as str;
3534 Simple(String, ImportSource),
3539 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
3540 pub struct ImportSource {
3542 pub did: Option<DefId>,
3545 impl Clean<Vec<Item>> for hir::ForeignMod {
3546 fn clean(&self, cx: &DocContext) -> Vec<Item> {
3547 let mut items = self.items.clean(cx);
3548 for item in &mut items {
3549 if let ForeignFunctionItem(ref mut f) = item.inner {
3557 impl Clean<Item> for hir::ForeignItem {
3558 fn clean(&self, cx: &DocContext) -> Item {
3559 let inner = match self.node {
3560 hir::ForeignItemFn(ref decl, ref names, ref generics) => {
3561 ForeignFunctionItem(Function {
3562 decl: (&**decl, &names[..]).clean(cx),
3563 generics: generics.clean(cx),
3564 unsafety: hir::Unsafety::Unsafe,
3566 constness: hir::Constness::NotConst,
3569 hir::ForeignItemStatic(ref ty, mutbl) => {
3570 ForeignStaticItem(Static {
3571 type_: ty.clean(cx),
3572 mutability: if mutbl {Mutable} else {Immutable},
3573 expr: "".to_string(),
3576 hir::ForeignItemType => {
3581 name: Some(self.name.clean(cx)),
3582 attrs: self.attrs.clean(cx),
3583 source: self.span.clean(cx),
3584 def_id: cx.tcx.hir.local_def_id(self.id),
3585 visibility: self.vis.clean(cx),
3586 stability: get_stability(cx, cx.tcx.hir.local_def_id(self.id)),
3587 deprecation: get_deprecation(cx, cx.tcx.hir.local_def_id(self.id)),
3596 fn to_src(&self, cx: &DocContext) -> String;
3599 impl ToSource for syntax_pos::Span {
3600 fn to_src(&self, cx: &DocContext) -> String {
3601 debug!("converting span {:?} to snippet", self.clean(cx));
3602 let sn = match cx.sess().codemap().span_to_snippet(*self) {
3603 Ok(x) => x.to_string(),
3604 Err(_) => "".to_string()
3606 debug!("got snippet {}", sn);
3611 fn name_from_pat(p: &hir::Pat) -> String {
3613 debug!("Trying to get a name from pattern: {:?}", p);
3616 PatKind::Wild => "_".to_string(),
3617 PatKind::Binding(_, _, ref p, _) => p.node.to_string(),
3618 PatKind::TupleStruct(ref p, ..) | PatKind::Path(ref p) => qpath_to_string(p),
3619 PatKind::Struct(ref name, ref fields, etc) => {
3620 format!("{} {{ {}{} }}", qpath_to_string(name),
3621 fields.iter().map(|&Spanned { node: ref fp, .. }|
3622 format!("{}: {}", fp.name, name_from_pat(&*fp.pat)))
3623 .collect::<Vec<String>>().join(", "),
3624 if etc { ", ..." } else { "" }
3627 PatKind::Tuple(ref elts, _) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
3628 .collect::<Vec<String>>().join(", ")),
3629 PatKind::Box(ref p) => name_from_pat(&**p),
3630 PatKind::Ref(ref p, _) => name_from_pat(&**p),
3631 PatKind::Lit(..) => {
3632 warn!("tried to get argument name from PatKind::Lit, \
3633 which is silly in function arguments");
3636 PatKind::Range(..) => panic!("tried to get argument name from PatKind::Range, \
3637 which is not allowed in function arguments"),
3638 PatKind::Slice(ref begin, ref mid, ref end) => {
3639 let begin = begin.iter().map(|p| name_from_pat(&**p));
3640 let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter();
3641 let end = end.iter().map(|p| name_from_pat(&**p));
3642 format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", "))
3647 fn print_const_expr(cx: &DocContext, body: hir::BodyId) -> String {
3648 cx.tcx.hir.node_to_pretty_string(body.node_id)
3651 /// Given a type Path, resolve it to a Type using the TyCtxt
3652 fn resolve_type(cx: &DocContext,
3654 id: ast::NodeId) -> Type {
3655 if id == ast::DUMMY_NODE_ID {
3656 debug!("resolve_type({:?})", path);
3658 debug!("resolve_type({:?},{:?})", path, id);
3661 let is_generic = match path.def {
3662 Def::PrimTy(p) => match p {
3663 hir::TyStr => return Primitive(PrimitiveType::Str),
3664 hir::TyBool => return Primitive(PrimitiveType::Bool),
3665 hir::TyChar => return Primitive(PrimitiveType::Char),
3666 hir::TyInt(int_ty) => return Primitive(int_ty.into()),
3667 hir::TyUint(uint_ty) => return Primitive(uint_ty.into()),
3668 hir::TyFloat(float_ty) => return Primitive(float_ty.into()),
3670 Def::SelfTy(..) if path.segments.len() == 1 => {
3671 return Generic(keywords::SelfType.name().to_string());
3673 Def::TyParam(..) if path.segments.len() == 1 => {
3674 return Generic(format!("{:#}", path));
3676 Def::SelfTy(..) | Def::TyParam(..) | Def::AssociatedTy(..) => true,
3679 let did = register_def(&*cx, path.def);
3680 ResolvedPath { path: path, typarams: None, did: did, is_generic: is_generic }
3683 fn register_def(cx: &DocContext, def: Def) -> DefId {
3684 debug!("register_def({:?})", def);
3686 let (did, kind) = match def {
3687 Def::Fn(i) => (i, TypeKind::Function),
3688 Def::TyAlias(i) => (i, TypeKind::Typedef),
3689 Def::Enum(i) => (i, TypeKind::Enum),
3690 Def::Trait(i) => (i, TypeKind::Trait),
3691 Def::Struct(i) => (i, TypeKind::Struct),
3692 Def::Union(i) => (i, TypeKind::Union),
3693 Def::Mod(i) => (i, TypeKind::Module),
3694 Def::TyForeign(i) => (i, TypeKind::Foreign),
3695 Def::Static(i, _) => (i, TypeKind::Static),
3696 Def::Variant(i) => (cx.tcx.parent_def_id(i).unwrap(), TypeKind::Enum),
3697 Def::Macro(i, _) => (i, TypeKind::Macro),
3698 Def::SelfTy(Some(def_id), _) => (def_id, TypeKind::Trait),
3699 Def::SelfTy(_, Some(impl_def_id)) => {
3702 _ => return def.def_id()
3704 if did.is_local() { return did }
3705 inline::record_extern_fqn(cx, did, kind);
3706 if let TypeKind::Trait = kind {
3707 inline::record_extern_trait(cx, did);
3712 fn resolve_use_source(cx: &DocContext, path: Path) -> ImportSource {
3714 did: if path.def == Def::Err {
3717 Some(register_def(cx, path.def))
3723 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
3726 pub imported_from: Option<String>,
3729 impl Clean<Item> for doctree::Macro {
3730 fn clean(&self, cx: &DocContext) -> Item {
3731 let name = self.name.clean(cx);
3733 name: Some(name.clone()),
3734 attrs: self.attrs.clean(cx),
3735 source: self.whence.clean(cx),
3736 visibility: Some(Public),
3737 stability: self.stab.clean(cx),
3738 deprecation: self.depr.clean(cx),
3739 def_id: self.def_id,
3740 inner: MacroItem(Macro {
3741 source: format!("macro_rules! {} {{\n{}}}",
3743 self.matchers.iter().map(|span| {
3744 format!(" {} => {{ ... }};\n", span.to_src(cx))
3745 }).collect::<String>()),
3746 imported_from: self.imported_from.clean(cx),
3752 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
3753 pub struct Stability {
3754 pub level: stability::StabilityLevel,
3755 pub feature: String,
3757 pub deprecated_since: String,
3758 pub deprecated_reason: String,
3759 pub unstable_reason: String,
3760 pub issue: Option<u32>
3763 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
3764 pub struct Deprecation {
3769 impl Clean<Stability> for attr::Stability {
3770 fn clean(&self, _: &DocContext) -> Stability {
3772 level: stability::StabilityLevel::from_attr_level(&self.level),
3773 feature: self.feature.to_string(),
3774 since: match self.level {
3775 attr::Stable {ref since} => since.to_string(),
3776 _ => "".to_string(),
3778 deprecated_since: match self.rustc_depr {
3779 Some(attr::RustcDeprecation {ref since, ..}) => since.to_string(),
3782 deprecated_reason: match self.rustc_depr {
3783 Some(ref depr) => depr.reason.to_string(),
3784 _ => "".to_string(),
3786 unstable_reason: match self.level {
3787 attr::Unstable { reason: Some(ref reason), .. } => reason.to_string(),
3788 _ => "".to_string(),
3790 issue: match self.level {
3791 attr::Unstable {issue, ..} => Some(issue),
3798 impl<'a> Clean<Stability> for &'a attr::Stability {
3799 fn clean(&self, dc: &DocContext) -> Stability {
3804 impl Clean<Deprecation> for attr::Deprecation {
3805 fn clean(&self, _: &DocContext) -> Deprecation {
3807 since: self.since.as_ref().map_or("".to_string(), |s| s.to_string()),
3808 note: self.note.as_ref().map_or("".to_string(), |s| s.to_string()),
3813 /// An equality constraint on an associated type, e.g. `A=Bar` in `Foo<A=Bar>`
3814 #[derive(Clone, PartialEq, Eq, RustcDecodable, RustcEncodable, Debug, Hash)]
3815 pub struct TypeBinding {
3820 impl Clean<TypeBinding> for hir::TypeBinding {
3821 fn clean(&self, cx: &DocContext) -> TypeBinding {
3823 name: self.name.clean(cx),
3824 ty: self.ty.clean(cx)
3829 pub fn def_id_to_path(cx: &DocContext, did: DefId, name: Option<String>) -> Vec<String> {
3830 let crate_name = name.unwrap_or_else(|| cx.tcx.crate_name(did.krate).to_string());
3831 let relative = cx.tcx.def_path(did).data.into_iter().filter_map(|elem| {
3832 // extern blocks have an empty name
3833 let s = elem.data.to_string();
3840 once(crate_name).chain(relative).collect()
3843 // Start of code copied from rust-clippy
3845 pub fn get_trait_def_id(tcx: &TyCtxt, path: &[&str], use_local: bool) -> Option<DefId> {
3847 path_to_def_local(tcx, path)
3849 path_to_def(tcx, path)
3853 pub fn path_to_def_local(tcx: &TyCtxt, path: &[&str]) -> Option<DefId> {
3854 let krate = tcx.hir.krate();
3855 let mut items = krate.module.item_ids.clone();
3856 let mut path_it = path.iter().peekable();
3859 let segment = match path_it.next() {
3860 Some(segment) => segment,
3861 None => return None,
3864 for item_id in mem::replace(&mut items, HirVec::new()).iter() {
3865 let item = tcx.hir.expect_item(item_id.id);
3866 if item.name == *segment {
3867 if path_it.peek().is_none() {
3868 return Some(tcx.hir.local_def_id(item_id.id))
3871 items = match &item.node {
3872 &hir::ItemMod(ref m) => m.item_ids.clone(),
3873 _ => panic!("Unexpected item {:?} in path {:?} path")
3881 pub fn path_to_def(tcx: &TyCtxt, path: &[&str]) -> Option<DefId> {
3882 let crates = tcx.crates();
3886 .find(|&&krate| tcx.crate_name(krate) == path[0]);
3888 if let Some(krate) = krate {
3891 index: CRATE_DEF_INDEX,
3893 let mut items = tcx.item_children(krate);
3894 let mut path_it = path.iter().skip(1).peekable();
3897 let segment = match path_it.next() {
3898 Some(segment) => segment,
3899 None => return None,
3902 for item in mem::replace(&mut items, Rc::new(vec![])).iter() {
3903 if item.ident.name == *segment {
3904 if path_it.peek().is_none() {
3905 return match item.def {
3906 def::Def::Trait(did) => Some(did),
3911 items = tcx.item_children(item.def.def_id());
3921 fn get_path_for_type(tcx: TyCtxt, def_id: DefId, def_ctor: fn(DefId) -> Def) -> hir::Path {
3922 struct AbsolutePathBuffer {
3926 impl ty::item_path::ItemPathBuffer for AbsolutePathBuffer {
3927 fn root_mode(&self) -> &ty::item_path::RootMode {
3928 const ABSOLUTE: &'static ty::item_path::RootMode = &ty::item_path::RootMode::Absolute;
3932 fn push(&mut self, text: &str) {
3933 self.names.push(text.to_owned());
3937 let mut apb = AbsolutePathBuffer { names: vec![] };
3939 tcx.push_item_path(&mut apb, def_id);
3943 def: def_ctor(def_id),
3944 segments: hir::HirVec::from_vec(apb.names.iter().map(|s| hir::PathSegment {
3945 name: ast::Name::intern(&s),
3952 // End of code copied from rust-clippy
3955 #[derive(Eq, PartialEq, Hash, Copy, Clone, Debug)]
3956 enum RegionTarget<'tcx> {
3957 Region(Region<'tcx>),
3958 RegionVid(RegionVid)
3961 #[derive(Default, Debug, Clone)]
3962 struct RegionDeps<'tcx> {
3963 larger: FxHashSet<RegionTarget<'tcx>>,
3964 smaller: FxHashSet<RegionTarget<'tcx>>
3967 #[derive(Eq, PartialEq, Hash, Debug)]
3969 RegionBound(Lifetime),
3970 TraitBound(Vec<PathSegment>, Vec<SimpleBound>, Vec<GenericParam>, hir::TraitBoundModifier)
3973 enum AutoTraitResult {
3975 PositiveImpl(Generics),
3979 impl AutoTraitResult {
3980 fn is_auto(&self) -> bool {
3982 AutoTraitResult::PositiveImpl(_) | AutoTraitResult::NegativeImpl => true,
3988 impl From<TyParamBound> for SimpleBound {
3989 fn from(bound: TyParamBound) -> Self {
3990 match bound.clone() {
3991 TyParamBound::RegionBound(l) => SimpleBound::RegionBound(l),
3992 TyParamBound::TraitBound(t, mod_) => match t.trait_ {
3993 Type::ResolvedPath { path, typarams, .. } => {
3994 SimpleBound::TraitBound(path.segments,
3996 .map_or_else(|| Vec::new(), |v| v.iter()
3997 .map(|p| SimpleBound::from(p.clone()))
4002 _ => panic!("Unexpected bound {:?}", bound),