1 use std::cell::RefCell;
2 use std::default::Default;
3 use std::hash::{Hash, Hasher};
4 use std::iter::FromIterator;
5 use std::lazy::SyncOnceCell as OnceCell;
6 use std::path::PathBuf;
11 use arrayvec::ArrayVec;
14 use rustc_ast::util::comments::beautify_doc_string;
15 use rustc_ast::{self as ast, AttrStyle};
16 use rustc_attr::{ConstStability, Deprecation, Stability, StabilityLevel};
17 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
18 use rustc_data_structures::thin_vec::ThinVec;
20 use rustc_hir::def::{CtorKind, DefKind, Res};
21 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE};
22 use rustc_hir::lang_items::LangItem;
23 use rustc_hir::{BodyId, Mutability};
24 use rustc_index::vec::IndexVec;
25 use rustc_middle::ty::{self, TyCtxt};
26 use rustc_session::Session;
27 use rustc_span::hygiene::MacroKind;
28 use rustc_span::source_map::DUMMY_SP;
29 use rustc_span::symbol::{kw, sym, Ident, Symbol, SymbolStr};
30 use rustc_span::{self, FileName, Loc};
31 use rustc_target::abi::VariantIdx;
32 use rustc_target::spec::abi::Abi;
34 use crate::clean::cfg::Cfg;
35 use crate::clean::external_path;
36 use crate::clean::inline::{self, print_inlined_const};
37 use crate::clean::types::Type::{QPath, ResolvedPath};
38 use crate::clean::utils::{is_literal_expr, print_const_expr, print_evaluated_const};
39 use crate::clean::Clean;
40 use crate::core::DocContext;
41 use crate::formats::cache::Cache;
42 use crate::formats::item_type::ItemType;
43 use crate::html::render::cache::ExternalLocation;
44 use crate::html::render::Context;
47 use self::ItemKind::*;
51 crate type ItemIdSet = FxHashSet<ItemId>;
53 #[derive(Debug, Clone, PartialEq, Eq, Hash, Copy)]
55 /// A "normal" item that uses a [`DefId`] for identification.
57 /// Identifier that is used for auto traits.
58 Auto { trait_: DefId, for_: DefId },
59 /// Identifier that is used for blanket implementations.
60 Blanket { impl_id: DefId, for_: DefId },
61 /// Identifier for primitive types.
62 Primitive(PrimitiveType, CrateNum),
67 crate fn is_local(self) -> bool {
69 ItemId::Auto { for_: id, .. }
70 | ItemId::Blanket { for_: id, .. }
71 | ItemId::DefId(id) => id.is_local(),
72 ItemId::Primitive(_, krate) => krate == LOCAL_CRATE,
78 crate fn expect_def_id(self) -> DefId {
80 .unwrap_or_else(|| panic!("ItemId::expect_def_id: `{:?}` isn't a DefId", self))
84 crate fn as_def_id(self) -> Option<DefId> {
86 ItemId::DefId(id) => Some(id),
92 crate fn krate(self) -> CrateNum {
94 ItemId::Auto { for_: id, .. }
95 | ItemId::Blanket { for_: id, .. }
96 | ItemId::DefId(id) => id.krate,
97 ItemId::Primitive(_, krate) => krate,
102 crate fn index(self) -> Option<DefIndex> {
104 ItemId::DefId(id) => Some(id.index),
110 impl From<DefId> for ItemId {
111 fn from(id: DefId) -> Self {
116 #[derive(Clone, Debug)]
121 crate externs: Vec<ExternalCrate>,
122 crate primitives: ThinVec<(DefId, PrimitiveType)>,
123 // These are later on moved into `CACHEKEY`, leaving the map empty.
124 // Only here so that they can be filtered through the rustdoc passes.
125 crate external_traits: Rc<RefCell<FxHashMap<DefId, TraitWithExtraInfo>>>,
126 crate collapsed: bool,
129 /// This struct is used to wrap additional information added by rustdoc on a `trait` item.
130 #[derive(Clone, Debug)]
131 crate struct TraitWithExtraInfo {
133 crate is_notable: bool,
136 #[derive(Copy, Clone, Debug)]
137 crate struct ExternalCrate {
138 crate crate_num: CrateNum,
143 crate fn def_id(&self) -> DefId {
144 DefId { krate: self.crate_num, index: CRATE_DEF_INDEX }
147 crate fn src(&self, tcx: TyCtxt<'_>) -> FileName {
148 let krate_span = tcx.def_span(self.def_id());
149 tcx.sess.source_map().span_to_filename(krate_span)
152 crate fn name(&self, tcx: TyCtxt<'_>) -> Symbol {
153 tcx.crate_name(self.crate_num)
156 crate fn src_root(&self, tcx: TyCtxt<'_>) -> PathBuf {
157 match self.src(tcx) {
158 FileName::Real(ref p) => match p.local_path_if_available().parent() {
159 Some(p) => p.to_path_buf(),
160 None => PathBuf::new(),
166 /// Attempts to find where an external crate is located, given that we're
167 /// rendering in to the specified source destination.
170 extern_url: Option<&str>,
171 extern_url_takes_precedence: bool,
172 dst: &std::path::Path,
174 ) -> ExternalLocation {
175 use ExternalLocation::*;
177 fn to_remote(url: impl ToString) -> ExternalLocation {
178 let mut url = url.to_string();
179 if !url.ends_with('/') {
185 // See if there's documentation generated into the local directory
186 // WARNING: since rustdoc creates these directories as it generates documentation, this check is only accurate before rendering starts.
187 // Make sure to call `location()` by that time.
188 let local_location = dst.join(&*self.name(tcx).as_str());
189 if local_location.is_dir() {
193 if extern_url_takes_precedence {
194 if let Some(url) = extern_url {
195 return to_remote(url);
199 // Failing that, see if there's an attribute specifying where to find this
201 let did = DefId { krate: self.crate_num, index: CRATE_DEF_INDEX };
204 .filter(|a| a.has_name(sym::html_root_url))
205 .filter_map(|a| a.value_str())
208 .or(extern_url.map(to_remote)) // NOTE: only matters if `extern_url_takes_precedence` is false
209 .unwrap_or(Unknown) // Well, at least we tried.
212 crate fn keywords(&self, tcx: TyCtxt<'_>) -> ThinVec<(DefId, Symbol)> {
213 let root = self.def_id();
215 let as_keyword = |res: Res<!>| {
216 if let Res::Def(DefKind::Mod, def_id) = res {
217 let attrs = tcx.get_attrs(def_id);
218 let mut keyword = None;
219 for attr in attrs.lists(sym::doc) {
220 if attr.has_name(sym::keyword) {
221 if let Some(v) = attr.value_str() {
227 return keyword.map(|p| (def_id, p));
238 let item = tcx.hir().item(id);
240 hir::ItemKind::Mod(_) => {
241 as_keyword(Res::Def(DefKind::Mod, id.def_id.to_def_id()))
243 hir::ItemKind::Use(ref path, hir::UseKind::Single)
244 if item.vis.node.is_pub() =>
246 as_keyword(path.res.expect_non_local())
247 .map(|(_, prim)| (id.def_id.to_def_id(), prim))
254 tcx.item_children(root).iter().map(|item| item.res).filter_map(as_keyword).collect()
258 crate fn primitives(&self, tcx: TyCtxt<'_>) -> ThinVec<(DefId, PrimitiveType)> {
259 let root = self.def_id();
261 // Collect all inner modules which are tagged as implementations of
264 // Note that this loop only searches the top-level items of the crate,
265 // and this is intentional. If we were to search the entire crate for an
266 // item tagged with `#[doc(primitive)]` then we would also have to
267 // search the entirety of external modules for items tagged
268 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
269 // all that metadata unconditionally).
271 // In order to keep the metadata load under control, the
272 // `#[doc(primitive)]` feature is explicitly designed to only allow the
273 // primitive tags to show up as the top level items in a crate.
275 // Also note that this does not attempt to deal with modules tagged
276 // duplicately for the same primitive. This is handled later on when
277 // rendering by delegating everything to a hash map.
278 let as_primitive = |res: Res<!>| {
279 if let Res::Def(DefKind::Mod, def_id) = res {
280 let attrs = tcx.get_attrs(def_id);
282 for attr in attrs.lists(sym::doc) {
283 if let Some(v) = attr.value_str() {
284 if attr.has_name(sym::primitive) {
285 prim = PrimitiveType::from_symbol(v);
289 // FIXME: should warn on unknown primitives?
293 return prim.map(|p| (def_id, p));
305 let item = tcx.hir().item(id);
307 hir::ItemKind::Mod(_) => {
308 as_primitive(Res::Def(DefKind::Mod, id.def_id.to_def_id()))
310 hir::ItemKind::Use(ref path, hir::UseKind::Single)
311 if item.vis.node.is_pub() =>
313 as_primitive(path.res.expect_non_local()).map(|(_, prim)| {
314 // Pretend the primitive is local.
315 (id.def_id.to_def_id(), prim)
323 tcx.item_children(root).iter().map(|item| item.res).filter_map(as_primitive).collect()
328 /// Anything with a source location and set of attributes and, optionally, a
329 /// name. That is, anything that can be documented. This doesn't correspond
330 /// directly to the AST's concept of an item; it's a strict superset.
331 #[derive(Clone, Debug)]
333 /// The name of this item.
334 /// Optional because not every item has a name, e.g. impls.
335 crate name: Option<Symbol>,
336 crate attrs: Box<Attributes>,
337 crate visibility: Visibility,
338 /// Information about this item that is specific to what kind of item it is.
339 /// E.g., struct vs enum vs function.
340 crate kind: Box<ItemKind>,
341 crate def_id: ItemId,
343 crate cfg: Option<Arc<Cfg>>,
346 // `Item` is used a lot. Make sure it doesn't unintentionally get bigger.
347 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
348 rustc_data_structures::static_assert_size!(Item, 56);
350 crate fn rustc_span(def_id: DefId, tcx: TyCtxt<'_>) -> Span {
351 Span::new(def_id.as_local().map_or_else(
352 || tcx.def_span(def_id),
355 hir.span_with_body(hir.local_def_id_to_hir_id(local))
361 crate fn stability<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Option<&'tcx Stability> {
362 self.def_id.as_def_id().and_then(|did| tcx.lookup_stability(did))
365 crate fn const_stability<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Option<&'tcx ConstStability> {
366 self.def_id.as_def_id().and_then(|did| tcx.lookup_const_stability(did))
369 crate fn deprecation(&self, tcx: TyCtxt<'_>) -> Option<Deprecation> {
370 self.def_id.as_def_id().and_then(|did| tcx.lookup_deprecation(did))
373 crate fn inner_docs(&self, tcx: TyCtxt<'_>) -> bool {
374 self.def_id.as_def_id().map(|did| tcx.get_attrs(did).inner_docs()).unwrap_or(false)
377 crate fn span(&self, tcx: TyCtxt<'_>) -> Span {
378 let kind = match &*self.kind {
379 ItemKind::StrippedItem(k) => k,
382 if let ItemKind::ModuleItem(Module { span, .. }) | ItemKind::ImplItem(Impl { span, .. }) =
387 self.def_id.as_def_id().map(|did| rustc_span(did, tcx)).unwrap_or_else(|| Span::dummy())
391 crate fn attr_span(&self, tcx: TyCtxt<'_>) -> rustc_span::Span {
392 crate::passes::span_of_attrs(&self.attrs).unwrap_or_else(|| self.span(tcx).inner())
395 /// Finds the `doc` attribute as a NameValue and returns the corresponding
397 crate fn doc_value(&self) -> Option<String> {
398 self.attrs.doc_value()
401 /// Convenience wrapper around [`Self::from_def_id_and_parts`] which converts
402 /// `hir_id` to a [`DefId`]
403 pub fn from_hir_id_and_parts(
405 name: Option<Symbol>,
407 cx: &mut DocContext<'_>,
409 Item::from_def_id_and_parts(cx.tcx.hir().local_def_id(hir_id).to_def_id(), name, kind, cx)
412 pub fn from_def_id_and_parts(
414 name: Option<Symbol>,
416 cx: &mut DocContext<'_>,
418 let ast_attrs = cx.tcx.get_attrs(def_id);
420 Self::from_def_id_and_attrs_and_parts(
424 Box::new(ast_attrs.clean(cx)),
426 ast_attrs.cfg(cx.sess()),
430 pub fn from_def_id_and_attrs_and_parts(
432 name: Option<Symbol>,
434 attrs: Box<Attributes>,
435 cx: &mut DocContext<'_>,
436 cfg: Option<Arc<Cfg>>,
438 trace!("name={:?}, def_id={:?}", name, def_id);
441 def_id: def_id.into(),
442 kind: Box::new(kind),
445 visibility: cx.tcx.visibility(def_id).clean(cx),
450 /// Finds all `doc` attributes as NameValues and returns their corresponding values, joined
452 crate fn collapsed_doc_value(&self) -> Option<String> {
453 self.attrs.collapsed_doc_value()
456 crate fn links(&self, cx: &Context<'_>) -> Vec<RenderedLink> {
457 use crate::html::format::href;
462 .map_or(&[][..], |v| v.as_slice())
464 .filter_map(|ItemLink { link: s, link_text, did, ref fragment }| {
466 if let Ok((mut href, ..)) = href(*did, cx) {
468 if let Some(ref fragment) = *fragment {
470 href.push_str(fragment);
473 original_text: s.clone(),
474 new_text: link_text.clone(),
484 /// Find a list of all link names, without finding their href.
486 /// This is used for generating summary text, which does not include
487 /// the link text, but does need to know which `[]`-bracketed names
488 /// are actually links.
489 crate fn link_names(&self, cache: &Cache) -> Vec<RenderedLink> {
493 .map_or(&[][..], |v| v.as_slice())
495 .map(|ItemLink { link: s, link_text, .. }| RenderedLink {
496 original_text: s.clone(),
497 new_text: link_text.clone(),
503 crate fn is_crate(&self) -> bool {
504 self.is_mod() && self.def_id.as_def_id().map_or(false, |did| did.index == CRATE_DEF_INDEX)
506 crate fn is_mod(&self) -> bool {
507 self.type_() == ItemType::Module
509 crate fn is_trait(&self) -> bool {
510 self.type_() == ItemType::Trait
512 crate fn is_struct(&self) -> bool {
513 self.type_() == ItemType::Struct
515 crate fn is_enum(&self) -> bool {
516 self.type_() == ItemType::Enum
518 crate fn is_variant(&self) -> bool {
519 self.type_() == ItemType::Variant
521 crate fn is_associated_type(&self) -> bool {
522 self.type_() == ItemType::AssocType
524 crate fn is_associated_const(&self) -> bool {
525 self.type_() == ItemType::AssocConst
527 crate fn is_method(&self) -> bool {
528 self.type_() == ItemType::Method
530 crate fn is_ty_method(&self) -> bool {
531 self.type_() == ItemType::TyMethod
533 crate fn is_typedef(&self) -> bool {
534 self.type_() == ItemType::Typedef
536 crate fn is_primitive(&self) -> bool {
537 self.type_() == ItemType::Primitive
539 crate fn is_union(&self) -> bool {
540 self.type_() == ItemType::Union
542 crate fn is_import(&self) -> bool {
543 self.type_() == ItemType::Import
545 crate fn is_extern_crate(&self) -> bool {
546 self.type_() == ItemType::ExternCrate
548 crate fn is_keyword(&self) -> bool {
549 self.type_() == ItemType::Keyword
551 crate fn is_stripped(&self) -> bool {
553 StrippedItem(..) => true,
554 ImportItem(ref i) => !i.should_be_displayed,
558 crate fn has_stripped_fields(&self) -> Option<bool> {
560 StructItem(ref _struct) => Some(_struct.fields_stripped),
561 UnionItem(ref union) => Some(union.fields_stripped),
562 VariantItem(Variant::Struct(ref vstruct)) => Some(vstruct.fields_stripped),
567 crate fn stability_class(&self, tcx: TyCtxt<'_>) -> Option<String> {
568 self.stability(tcx).as_ref().and_then(|ref s| {
569 let mut classes = Vec::with_capacity(2);
571 if s.level.is_unstable() {
572 classes.push("unstable");
575 // FIXME: what about non-staged API items that are deprecated?
576 if self.deprecation(tcx).is_some() {
577 classes.push("deprecated");
580 if !classes.is_empty() { Some(classes.join(" ")) } else { None }
584 crate fn stable_since(&self, tcx: TyCtxt<'_>) -> Option<SymbolStr> {
585 match self.stability(tcx)?.level {
586 StabilityLevel::Stable { since, .. } => Some(since.as_str()),
587 StabilityLevel::Unstable { .. } => None,
591 crate fn const_stable_since(&self, tcx: TyCtxt<'_>) -> Option<SymbolStr> {
592 match self.const_stability(tcx)?.level {
593 StabilityLevel::Stable { since, .. } => Some(since.as_str()),
594 StabilityLevel::Unstable { .. } => None,
598 crate fn is_non_exhaustive(&self) -> bool {
599 self.attrs.other_attrs.iter().any(|a| a.has_name(sym::non_exhaustive))
602 /// Returns a documentation-level item type from the item.
603 crate fn type_(&self) -> ItemType {
607 crate fn is_default(&self) -> bool {
609 ItemKind::MethodItem(_, Some(defaultness)) => {
610 defaultness.has_value() && !defaultness.is_final()
617 #[derive(Clone, Debug)]
618 crate enum ItemKind {
620 /// The crate's name, *not* the name it's imported as.
627 FunctionItem(Function),
629 TypedefItem(Typedef, bool /* is associated type */),
630 OpaqueTyItem(OpaqueTy),
632 ConstantItem(Constant),
634 TraitAliasItem(TraitAlias),
636 /// A method signature only. Used for required methods in traits (ie,
637 /// non-default-methods).
638 TyMethodItem(Function),
639 /// A method with a body.
640 MethodItem(Function, Option<hir::Defaultness>),
641 StructFieldItem(Type),
642 VariantItem(Variant),
643 /// `fn`s from an extern block
644 ForeignFunctionItem(Function),
645 /// `static`s from an extern block
646 ForeignStaticItem(Static),
647 /// `type`s from an extern block
650 ProcMacroItem(ProcMacro),
651 PrimitiveItem(PrimitiveType),
652 AssocConstItem(Type, Option<String>),
653 /// An associated item in a trait or trait impl.
655 /// The bounds may be non-empty if there is a `where` clause.
656 /// The `Option<Type>` is the default concrete type (e.g. `trait Trait { type Target = usize; }`)
657 AssocTypeItem(Vec<GenericBound>, Option<Type>),
658 /// An item that has been stripped by a rustdoc pass
659 StrippedItem(Box<ItemKind>),
664 /// Some items contain others such as structs (for their fields) and Enums
665 /// (for their variants). This method returns those contained items.
666 crate fn inner_items(&self) -> impl Iterator<Item = &Item> {
668 StructItem(s) => s.fields.iter(),
669 UnionItem(u) => u.fields.iter(),
670 VariantItem(Variant::Struct(v)) => v.fields.iter(),
671 VariantItem(Variant::Tuple(v)) => v.iter(),
672 EnumItem(e) => e.variants.iter(),
673 TraitItem(t) => t.items.iter(),
674 ImplItem(i) => i.items.iter(),
675 ModuleItem(m) => m.items.iter(),
676 ExternCrateItem { .. }
688 | ForeignFunctionItem(_)
689 | ForeignStaticItem(_)
694 | AssocConstItem(_, _)
695 | AssocTypeItem(_, _)
697 | KeywordItem(_) => [].iter(),
702 #[derive(Clone, Debug)]
703 crate struct Module {
704 crate items: Vec<Item>,
708 crate struct ListAttributesIter<'a> {
709 attrs: slice::Iter<'a, ast::Attribute>,
710 current_list: vec::IntoIter<ast::NestedMetaItem>,
714 impl<'a> Iterator for ListAttributesIter<'a> {
715 type Item = ast::NestedMetaItem;
717 fn next(&mut self) -> Option<Self::Item> {
718 if let Some(nested) = self.current_list.next() {
722 for attr in &mut self.attrs {
723 if let Some(list) = attr.meta_item_list() {
724 if attr.has_name(self.name) {
725 self.current_list = list.into_iter();
726 if let Some(nested) = self.current_list.next() {
736 fn size_hint(&self) -> (usize, Option<usize>) {
737 let lower = self.current_list.len();
742 crate trait AttributesExt {
743 /// Finds an attribute as List and returns the list of attributes nested inside.
744 fn lists(&self, name: Symbol) -> ListAttributesIter<'_>;
746 fn span(&self) -> Option<rustc_span::Span>;
748 fn inner_docs(&self) -> bool;
750 fn other_attrs(&self) -> Vec<ast::Attribute>;
752 fn cfg(&self, sess: &Session) -> Option<Arc<Cfg>>;
755 impl AttributesExt for [ast::Attribute] {
756 fn lists(&self, name: Symbol) -> ListAttributesIter<'_> {
757 ListAttributesIter { attrs: self.iter(), current_list: Vec::new().into_iter(), name }
760 /// Return the span of the first doc-comment, if it exists.
761 fn span(&self) -> Option<rustc_span::Span> {
762 self.iter().find(|attr| attr.doc_str().is_some()).map(|attr| attr.span)
765 /// Returns whether the first doc-comment is an inner attribute.
767 //// If there are no doc-comments, return true.
768 /// FIXME(#78591): Support both inner and outer attributes on the same item.
769 fn inner_docs(&self) -> bool {
770 self.iter().find(|a| a.doc_str().is_some()).map_or(true, |a| a.style == AttrStyle::Inner)
773 fn other_attrs(&self) -> Vec<ast::Attribute> {
774 self.iter().filter(|attr| attr.doc_str().is_none()).cloned().collect()
777 fn cfg(&self, sess: &Session) -> Option<Arc<Cfg>> {
778 let mut cfg = Cfg::True;
780 for attr in self.iter() {
782 if attr.doc_str().is_none() && attr.has_name(sym::doc) {
784 if let Some(list) = attr.meta().as_ref().and_then(|mi| mi.meta_item_list()) {
787 if !item.has_name(sym::cfg) {
791 if let Some(cfg_mi) = item
793 .and_then(|item| rustc_expand::config::parse_cfg(&item, sess))
795 match Cfg::parse(&cfg_mi) {
796 Ok(new_cfg) => cfg &= new_cfg,
797 Err(e) => sess.span_err(e.span, e.msg),
805 for attr in self.lists(sym::target_feature) {
806 if attr.has_name(sym::enable) {
807 if let Some(feat) = attr.value_str() {
808 let meta = attr::mk_name_value_item_str(
809 Ident::with_dummy_span(sym::target_feature),
813 if let Ok(feat_cfg) = Cfg::parse(&meta) {
820 if cfg == Cfg::True { None } else { Some(Arc::new(cfg)) }
824 crate trait NestedAttributesExt {
825 /// Returns `true` if the attribute list contains a specific `Word`
826 fn has_word(self, word: Symbol) -> bool;
827 fn get_word_attr(self, word: Symbol) -> Option<ast::NestedMetaItem>;
830 impl<I: Iterator<Item = ast::NestedMetaItem> + IntoIterator<Item = ast::NestedMetaItem>>
831 NestedAttributesExt for I
833 fn has_word(self, word: Symbol) -> bool {
834 self.into_iter().any(|attr| attr.is_word() && attr.has_name(word))
837 fn get_word_attr(mut self, word: Symbol) -> Option<ast::NestedMetaItem> {
838 self.find(|attr| attr.is_word() && attr.has_name(word))
842 /// A portion of documentation, extracted from a `#[doc]` attribute.
844 /// Each variant contains the line number within the complete doc-comment where the fragment
845 /// starts, as well as the Span where the corresponding doc comment or attribute is located.
847 /// Included files are kept separate from inline doc comments so that proper line-number
848 /// information can be given when a doctest fails. Sugared doc comments and "raw" doc comments are
849 /// kept separate because of issue #42760.
850 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
851 crate struct DocFragment {
853 crate span: rustc_span::Span,
854 /// The module this doc-comment came from.
856 /// This allows distinguishing between the original documentation and a pub re-export.
857 /// If it is `None`, the item was not re-exported.
858 crate parent_module: Option<DefId>,
860 crate kind: DocFragmentKind,
861 crate need_backline: bool,
865 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
866 crate enum DocFragmentKind {
867 /// A doc fragment created from a `///` or `//!` doc comment.
869 /// A doc fragment created from a "raw" `#[doc=""]` attribute.
873 // The goal of this function is to apply the `DocFragment` transformations that are required when
874 // transforming into the final markdown. So the transformations in here are:
876 // * Applying the computed indent to each lines in each doc fragment (a `DocFragment` can contain
877 // multiple lines in case of `#[doc = ""]`).
878 // * Adding backlines between `DocFragment`s and adding an extra one if required (stored in the
879 // `need_backline` field).
880 fn add_doc_fragment(out: &mut String, frag: &DocFragment) {
881 let s = frag.doc.as_str();
882 let mut iter = s.lines().peekable();
883 while let Some(line) = iter.next() {
884 if line.chars().any(|c| !c.is_whitespace()) {
885 assert!(line.len() >= frag.indent);
886 out.push_str(&line[frag.indent..]);
890 if iter.peek().is_some() {
894 if frag.need_backline {
899 impl<'a> FromIterator<&'a DocFragment> for String {
900 fn from_iter<T>(iter: T) -> Self
902 T: IntoIterator<Item = &'a DocFragment>,
904 iter.into_iter().fold(String::new(), |mut acc, frag| {
905 add_doc_fragment(&mut acc, &frag);
911 /// The attributes on an [`Item`], including attributes like `#[derive(...)]` and `#[inline]`,
912 /// as well as doc comments.
913 #[derive(Clone, Debug, Default)]
914 crate struct Attributes {
915 crate doc_strings: Vec<DocFragment>,
916 crate other_attrs: Vec<ast::Attribute>,
919 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
920 /// A link that has not yet been rendered.
922 /// This link will be turned into a rendered link by [`Item::links`].
923 crate struct ItemLink {
924 /// The original link written in the markdown
925 pub(crate) link: String,
926 /// The link text displayed in the HTML.
928 /// This may not be the same as `link` if there was a disambiguator
929 /// in an intra-doc link (e.g. \[`fn@f`\])
930 pub(crate) link_text: String,
931 pub(crate) did: DefId,
932 /// The url fragment to append to the link
933 pub(crate) fragment: Option<String>,
936 pub struct RenderedLink {
937 /// The text the link was original written as.
939 /// This could potentially include disambiguators and backticks.
940 pub(crate) original_text: String,
941 /// The text to display in the HTML
942 pub(crate) new_text: String,
943 /// The URL to put in the `href`
944 pub(crate) href: String,
948 crate fn lists(&self, name: Symbol) -> ListAttributesIter<'_> {
949 self.other_attrs.lists(name)
952 crate fn has_doc_flag(&self, flag: Symbol) -> bool {
953 for attr in &self.other_attrs {
954 if !attr.has_name(sym::doc) {
958 if let Some(items) = attr.meta_item_list() {
959 if items.iter().filter_map(|i| i.meta_item()).any(|it| it.has_name(flag)) {
969 attrs: &[ast::Attribute],
970 additional_attrs: Option<(&[ast::Attribute], DefId)>,
972 let mut doc_strings: Vec<DocFragment> = vec![];
973 let mut doc_line = 0;
975 fn update_need_backline(doc_strings: &mut Vec<DocFragment>) {
976 if let Some(prev) = doc_strings.last_mut() {
977 prev.need_backline = true;
981 let clean_attr = |(attr, parent_module): (&ast::Attribute, Option<DefId>)| {
982 if let Some(value) = attr.doc_str() {
983 trace!("got doc_str={:?}", value);
984 let value = beautify_doc_string(value);
985 let kind = if attr.is_doc_comment() {
986 DocFragmentKind::SugaredDoc
988 DocFragmentKind::RawDoc
992 doc_line += value.as_str().lines().count();
993 let frag = DocFragment {
999 need_backline: false,
1003 update_need_backline(&mut doc_strings);
1005 doc_strings.push(frag);
1013 // Additional documentation should be shown before the original documentation
1014 let other_attrs = additional_attrs
1016 .map(|(attrs, id)| attrs.iter().map(move |attr| (attr, Some(id))))
1018 .chain(attrs.iter().map(|attr| (attr, None)))
1019 .filter_map(clean_attr)
1022 Attributes { doc_strings, other_attrs }
1025 /// Finds the `doc` attribute as a NameValue and returns the corresponding
1027 crate fn doc_value(&self) -> Option<String> {
1028 let mut iter = self.doc_strings.iter();
1030 let ori = iter.next()?;
1031 let mut out = String::new();
1032 add_doc_fragment(&mut out, &ori);
1033 while let Some(new_frag) = iter.next() {
1034 if new_frag.kind != ori.kind || new_frag.parent_module != ori.parent_module {
1037 add_doc_fragment(&mut out, &new_frag);
1039 if out.is_empty() { None } else { Some(out) }
1042 /// Return the doc-comments on this item, grouped by the module they came from.
1044 /// The module can be different if this is a re-export with added documentation.
1045 crate fn collapsed_doc_value_by_module_level(&self) -> FxHashMap<Option<DefId>, String> {
1046 let mut ret = FxHashMap::default();
1048 for new_frag in self.doc_strings.iter() {
1049 let out = ret.entry(new_frag.parent_module).or_default();
1050 add_doc_fragment(out, &new_frag);
1055 /// Finds all `doc` attributes as NameValues and returns their corresponding values, joined
1057 crate fn collapsed_doc_value(&self) -> Option<String> {
1058 if self.doc_strings.is_empty() { None } else { Some(self.doc_strings.iter().collect()) }
1061 crate fn get_doc_aliases(&self) -> Box<[String]> {
1062 let mut aliases = FxHashSet::default();
1064 for attr in self.other_attrs.lists(sym::doc).filter(|a| a.has_name(sym::alias)) {
1065 if let Some(values) = attr.meta_item_list() {
1067 match l.literal().unwrap().kind {
1068 ast::LitKind::Str(s, _) => {
1069 aliases.insert(s.as_str().to_string());
1071 _ => unreachable!(),
1075 aliases.insert(attr.value_str().map(|s| s.to_string()).unwrap());
1078 aliases.into_iter().collect::<Vec<String>>().into()
1082 impl PartialEq for Attributes {
1083 fn eq(&self, rhs: &Self) -> bool {
1084 self.doc_strings == rhs.doc_strings
1088 .map(|attr| attr.id)
1089 .eq(rhs.other_attrs.iter().map(|attr| attr.id))
1093 impl Eq for Attributes {}
1095 impl Hash for Attributes {
1096 fn hash<H: Hasher>(&self, hasher: &mut H) {
1097 self.doc_strings.hash(hasher);
1098 for attr in &self.other_attrs {
1099 attr.id.hash(hasher);
1104 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
1105 crate enum GenericBound {
1106 TraitBound(PolyTrait, hir::TraitBoundModifier),
1111 crate fn maybe_sized(cx: &mut DocContext<'_>) -> GenericBound {
1112 let did = cx.tcx.require_lang_item(LangItem::Sized, None);
1113 let empty = cx.tcx.intern_substs(&[]);
1114 let path = external_path(cx, did, false, vec![], empty);
1115 inline::record_extern_fqn(cx, did, ItemType::Trait);
1116 GenericBound::TraitBound(
1118 trait_: ResolvedPath { path, did, is_generic: false },
1119 generic_params: Vec::new(),
1121 hir::TraitBoundModifier::Maybe,
1125 crate fn is_sized_bound(&self, cx: &DocContext<'_>) -> bool {
1126 use rustc_hir::TraitBoundModifier as TBM;
1127 if let GenericBound::TraitBound(PolyTrait { ref trait_, .. }, TBM::None) = *self {
1128 if trait_.def_id() == cx.tcx.lang_items().sized_trait() {
1135 crate fn get_poly_trait(&self) -> Option<PolyTrait> {
1136 if let GenericBound::TraitBound(ref p, _) = *self {
1137 return Some(p.clone());
1142 crate fn get_trait_type(&self) -> Option<Type> {
1143 if let GenericBound::TraitBound(PolyTrait { ref trait_, .. }, _) = *self {
1144 Some(trait_.clone())
1151 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
1152 crate struct Lifetime(pub Symbol);
1155 crate fn get_ref(&self) -> SymbolStr {
1159 crate fn statik() -> Lifetime {
1160 Lifetime(kw::StaticLifetime)
1163 crate fn elided() -> Lifetime {
1164 Lifetime(kw::UnderscoreLifetime)
1168 #[derive(Clone, Debug)]
1169 crate enum WherePredicate {
1170 BoundPredicate { ty: Type, bounds: Vec<GenericBound>, bound_params: Vec<Lifetime> },
1171 RegionPredicate { lifetime: Lifetime, bounds: Vec<GenericBound> },
1172 EqPredicate { lhs: Type, rhs: Type },
1175 impl WherePredicate {
1176 crate fn get_bounds(&self) -> Option<&[GenericBound]> {
1178 WherePredicate::BoundPredicate { ref bounds, .. } => Some(bounds),
1179 WherePredicate::RegionPredicate { ref bounds, .. } => Some(bounds),
1185 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
1186 crate enum GenericParamDefKind {
1188 outlives: Vec<Lifetime>,
1192 bounds: Vec<GenericBound>,
1193 default: Option<Type>,
1194 synthetic: Option<hir::SyntheticTyParamKind>,
1199 default: Option<String>,
1203 impl GenericParamDefKind {
1204 crate fn is_type(&self) -> bool {
1205 matches!(self, GenericParamDefKind::Type { .. })
1208 // FIXME(eddyb) this either returns the default of a type parameter, or the
1209 // type of a `const` parameter. It seems that the intention is to *visit*
1210 // any embedded types, but `get_type` seems to be the wrong name for that.
1211 crate fn get_type(&self) -> Option<Type> {
1213 GenericParamDefKind::Type { default, .. } => default.clone(),
1214 GenericParamDefKind::Const { ty, .. } => Some(ty.clone()),
1215 GenericParamDefKind::Lifetime { .. } => None,
1220 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
1221 crate struct GenericParamDef {
1223 crate kind: GenericParamDefKind,
1226 impl GenericParamDef {
1227 crate fn is_synthetic_type_param(&self) -> bool {
1229 GenericParamDefKind::Lifetime { .. } | GenericParamDefKind::Const { .. } => false,
1230 GenericParamDefKind::Type { ref synthetic, .. } => synthetic.is_some(),
1234 crate fn is_type(&self) -> bool {
1238 crate fn get_type(&self) -> Option<Type> {
1239 self.kind.get_type()
1242 crate fn get_bounds(&self) -> Option<&[GenericBound]> {
1244 GenericParamDefKind::Type { ref bounds, .. } => Some(bounds),
1250 // maybe use a Generic enum and use Vec<Generic>?
1251 #[derive(Clone, Debug, Default)]
1252 crate struct Generics {
1253 crate params: Vec<GenericParamDef>,
1254 crate where_predicates: Vec<WherePredicate>,
1257 #[derive(Clone, Debug)]
1258 crate struct Function {
1260 crate generics: Generics,
1261 crate header: hir::FnHeader,
1264 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
1265 crate struct FnDecl {
1266 crate inputs: Arguments,
1267 crate output: FnRetTy,
1268 crate c_variadic: bool,
1272 crate fn self_type(&self) -> Option<SelfTy> {
1273 self.inputs.values.get(0).and_then(|v| v.to_self())
1276 /// Returns the sugared return type for an async function.
1278 /// For example, if the return type is `impl std::future::Future<Output = i32>`, this function
1279 /// will return `i32`.
1283 /// This function will panic if the return type does not match the expected sugaring for async
1285 crate fn sugared_async_return_type(&self) -> FnRetTy {
1286 match &self.output {
1287 FnRetTy::Return(Type::ImplTrait(bounds)) => match &bounds[0] {
1288 GenericBound::TraitBound(PolyTrait { trait_, .. }, ..) => {
1289 let bindings = trait_.bindings().unwrap();
1290 FnRetTy::Return(bindings[0].ty().clone())
1292 _ => panic!("unexpected desugaring of async function"),
1294 _ => panic!("unexpected desugaring of async function"),
1299 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
1300 crate struct Arguments {
1301 crate values: Vec<Argument>,
1304 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
1305 crate struct Argument {
1310 #[derive(Clone, PartialEq, Debug)]
1313 SelfBorrowed(Option<Lifetime>, Mutability),
1318 crate fn to_self(&self) -> Option<SelfTy> {
1319 if self.name != kw::SelfLower {
1322 if self.type_.is_self_type() {
1323 return Some(SelfValue);
1326 BorrowedRef { ref lifetime, mutability, ref type_ } if type_.is_self_type() => {
1327 Some(SelfBorrowed(lifetime.clone(), mutability))
1329 _ => Some(SelfExplicit(self.type_.clone())),
1334 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
1335 crate enum FnRetTy {
1340 impl GetDefId for FnRetTy {
1341 fn def_id(&self) -> Option<DefId> {
1343 Return(ref ty) => ty.def_id(),
1344 DefaultReturn => None,
1348 fn def_id_full(&self, cache: &Cache) -> Option<DefId> {
1350 Return(ref ty) => ty.def_id_full(cache),
1351 DefaultReturn => None,
1356 #[derive(Clone, Debug)]
1357 crate struct Trait {
1358 crate unsafety: hir::Unsafety,
1359 crate items: Vec<Item>,
1360 crate generics: Generics,
1361 crate bounds: Vec<GenericBound>,
1362 crate is_auto: bool,
1365 #[derive(Clone, Debug)]
1366 crate struct TraitAlias {
1367 crate generics: Generics,
1368 crate bounds: Vec<GenericBound>,
1371 /// A trait reference, which may have higher ranked lifetimes.
1372 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
1373 crate struct PolyTrait {
1375 crate generic_params: Vec<GenericParamDef>,
1378 /// A representation of a type suitable for hyperlinking purposes. Ideally, one can get the original
1379 /// type out of the AST/`TyCtxt` given one of these, if more information is needed. Most
1380 /// importantly, it does not preserve mutability or boxes.
1381 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
1383 /// Structs/enums/traits (most that would be an `hir::TyKind::Path`).
1387 /// `true` if is a `T::Name` path for associated types.
1390 /// `dyn for<'a> Trait<'a> + Send + 'static`
1391 DynTrait(Vec<PolyTrait>, Option<Lifetime>),
1392 /// For parameterized types, so the consumer of the JSON don't go
1393 /// looking for types which don't exist anywhere.
1395 /// Primitives are the fixed-size numeric types (plus int/usize/float), char,
1396 /// arrays, slices, and tuples.
1397 Primitive(PrimitiveType),
1398 /// `extern "ABI" fn`
1399 BareFunction(Box<BareFunctionDecl>),
1402 /// The `String` field is about the size or the constant representing the array's length.
1403 Array(Box<Type>, String),
1405 RawPointer(Mutability, Box<Type>),
1407 lifetime: Option<Lifetime>,
1408 mutability: Mutability,
1412 // `<Type as Trait>::Name`
1415 self_type: Box<Type>,
1416 self_def_id: Option<DefId>,
1423 // `impl TraitA + TraitB + ...`
1424 ImplTrait(Vec<GenericBound>),
1427 #[derive(Clone, PartialEq, Eq, Hash, Copy, Debug)]
1428 /// N.B. this has to be different from `hir::PrimTy` because it also includes types that aren't
1429 /// paths, like `Unit`.
1430 crate enum PrimitiveType {
1458 crate trait GetDefId {
1459 /// Use this method to get the [`DefId`] of a [`clean`] AST node.
1460 /// This will return [`None`] when called on a primitive [`clean::Type`].
1461 /// Use [`Self::def_id_full`] if you want to include primitives.
1463 /// [`clean`]: crate::clean
1464 /// [`clean::Type`]: crate::clean::Type
1465 // FIXME: get rid of this function and always use `def_id_full`
1466 fn def_id(&self) -> Option<DefId>;
1468 /// Use this method to get the [DefId] of a [clean] AST node, including [PrimitiveType]s.
1470 /// See [`Self::def_id`] for more.
1472 /// [clean]: crate::clean
1473 fn def_id_full(&self, cache: &Cache) -> Option<DefId>;
1476 impl<T: GetDefId> GetDefId for Option<T> {
1477 fn def_id(&self) -> Option<DefId> {
1478 self.as_ref().and_then(|d| d.def_id())
1481 fn def_id_full(&self, cache: &Cache) -> Option<DefId> {
1482 self.as_ref().and_then(|d| d.def_id_full(cache))
1487 crate fn primitive_type(&self) -> Option<PrimitiveType> {
1489 Primitive(p) | BorrowedRef { type_: box Primitive(p), .. } => Some(p),
1490 Slice(..) | BorrowedRef { type_: box Slice(..), .. } => Some(PrimitiveType::Slice),
1491 Array(..) | BorrowedRef { type_: box Array(..), .. } => Some(PrimitiveType::Array),
1494 Some(PrimitiveType::Unit)
1496 Some(PrimitiveType::Tuple)
1499 RawPointer(..) => Some(PrimitiveType::RawPointer),
1500 BareFunction(..) => Some(PrimitiveType::Fn),
1501 Never => Some(PrimitiveType::Never),
1506 crate fn is_generic(&self) -> bool {
1508 ResolvedPath { is_generic, .. } => is_generic,
1513 crate fn is_self_type(&self) -> bool {
1515 Generic(name) => name == kw::SelfUpper,
1520 crate fn generics(&self) -> Option<Vec<&Type>> {
1522 ResolvedPath { ref path, .. } => path.segments.last().and_then(|seg| {
1523 if let GenericArgs::AngleBracketed { ref args, .. } = seg.args {
1526 .filter_map(|arg| match arg {
1527 GenericArg::Type(ty) => Some(ty),
1540 crate fn bindings(&self) -> Option<&[TypeBinding]> {
1542 ResolvedPath { ref path, .. } => path.segments.last().and_then(|seg| {
1543 if let GenericArgs::AngleBracketed { ref bindings, .. } = seg.args {
1553 crate fn is_full_generic(&self) -> bool {
1554 matches!(self, Type::Generic(_))
1557 crate fn is_primitive(&self) -> bool {
1558 self.primitive_type().is_some()
1561 crate fn projection(&self) -> Option<(&Type, DefId, Symbol)> {
1562 let (self_, trait_, name) = match self {
1563 QPath { self_type, trait_, name, .. } => (self_type, trait_, name),
1566 let trait_did = match **trait_ {
1567 ResolvedPath { did, .. } => did,
1570 Some((&self_, trait_did, *name))
1575 fn inner_def_id(&self, cache: Option<&Cache>) -> Option<DefId> {
1576 let t: PrimitiveType = match *self {
1577 ResolvedPath { did, .. } => return Some(did),
1578 DynTrait(ref bounds, _) => return bounds[0].trait_.inner_def_id(cache),
1579 Primitive(p) => return cache.and_then(|c| c.primitive_locations.get(&p).cloned()),
1580 BorrowedRef { type_: box Generic(..), .. } => PrimitiveType::Reference,
1581 BorrowedRef { ref type_, .. } => return type_.inner_def_id(cache),
1586 PrimitiveType::Tuple
1589 BareFunction(..) => PrimitiveType::Fn,
1590 Never => PrimitiveType::Never,
1591 Slice(..) => PrimitiveType::Slice,
1592 Array(..) => PrimitiveType::Array,
1593 RawPointer(..) => PrimitiveType::RawPointer,
1594 QPath { ref self_type, .. } => return self_type.inner_def_id(cache),
1595 Generic(_) | Infer | ImplTrait(_) => return None,
1597 cache.and_then(|c| Primitive(t).def_id_full(c))
1601 impl GetDefId for Type {
1602 fn def_id(&self) -> Option<DefId> {
1603 self.inner_def_id(None)
1606 fn def_id_full(&self, cache: &Cache) -> Option<DefId> {
1607 self.inner_def_id(Some(cache))
1611 impl PrimitiveType {
1612 crate fn from_hir(prim: hir::PrimTy) -> PrimitiveType {
1613 use ast::{FloatTy, IntTy, UintTy};
1615 hir::PrimTy::Int(IntTy::Isize) => PrimitiveType::Isize,
1616 hir::PrimTy::Int(IntTy::I8) => PrimitiveType::I8,
1617 hir::PrimTy::Int(IntTy::I16) => PrimitiveType::I16,
1618 hir::PrimTy::Int(IntTy::I32) => PrimitiveType::I32,
1619 hir::PrimTy::Int(IntTy::I64) => PrimitiveType::I64,
1620 hir::PrimTy::Int(IntTy::I128) => PrimitiveType::I128,
1621 hir::PrimTy::Uint(UintTy::Usize) => PrimitiveType::Usize,
1622 hir::PrimTy::Uint(UintTy::U8) => PrimitiveType::U8,
1623 hir::PrimTy::Uint(UintTy::U16) => PrimitiveType::U16,
1624 hir::PrimTy::Uint(UintTy::U32) => PrimitiveType::U32,
1625 hir::PrimTy::Uint(UintTy::U64) => PrimitiveType::U64,
1626 hir::PrimTy::Uint(UintTy::U128) => PrimitiveType::U128,
1627 hir::PrimTy::Float(FloatTy::F32) => PrimitiveType::F32,
1628 hir::PrimTy::Float(FloatTy::F64) => PrimitiveType::F64,
1629 hir::PrimTy::Str => PrimitiveType::Str,
1630 hir::PrimTy::Bool => PrimitiveType::Bool,
1631 hir::PrimTy::Char => PrimitiveType::Char,
1635 crate fn from_symbol(s: Symbol) -> Option<PrimitiveType> {
1637 sym::isize => Some(PrimitiveType::Isize),
1638 sym::i8 => Some(PrimitiveType::I8),
1639 sym::i16 => Some(PrimitiveType::I16),
1640 sym::i32 => Some(PrimitiveType::I32),
1641 sym::i64 => Some(PrimitiveType::I64),
1642 sym::i128 => Some(PrimitiveType::I128),
1643 sym::usize => Some(PrimitiveType::Usize),
1644 sym::u8 => Some(PrimitiveType::U8),
1645 sym::u16 => Some(PrimitiveType::U16),
1646 sym::u32 => Some(PrimitiveType::U32),
1647 sym::u64 => Some(PrimitiveType::U64),
1648 sym::u128 => Some(PrimitiveType::U128),
1649 sym::bool => Some(PrimitiveType::Bool),
1650 sym::char => Some(PrimitiveType::Char),
1651 sym::str => Some(PrimitiveType::Str),
1652 sym::f32 => Some(PrimitiveType::F32),
1653 sym::f64 => Some(PrimitiveType::F64),
1654 sym::array => Some(PrimitiveType::Array),
1655 sym::slice => Some(PrimitiveType::Slice),
1656 sym::tuple => Some(PrimitiveType::Tuple),
1657 sym::unit => Some(PrimitiveType::Unit),
1658 sym::pointer => Some(PrimitiveType::RawPointer),
1659 sym::reference => Some(PrimitiveType::Reference),
1660 kw::Fn => Some(PrimitiveType::Fn),
1661 sym::never => Some(PrimitiveType::Never),
1666 crate fn impls(&self, tcx: TyCtxt<'_>) -> &'static ArrayVec<DefId, 4> {
1667 Self::all_impls(tcx).get(self).expect("missing impl for primitive type")
1670 crate fn all_impls(tcx: TyCtxt<'_>) -> &'static FxHashMap<PrimitiveType, ArrayVec<DefId, 4>> {
1671 static CELL: OnceCell<FxHashMap<PrimitiveType, ArrayVec<DefId, 4>>> = OnceCell::new();
1673 CELL.get_or_init(move || {
1674 use self::PrimitiveType::*;
1676 let single = |a: Option<DefId>| a.into_iter().collect();
1677 let both = |a: Option<DefId>, b: Option<DefId>| -> ArrayVec<_, 4> {
1678 a.into_iter().chain(b).collect()
1681 let lang_items = tcx.lang_items();
1683 Isize => single(lang_items.isize_impl()),
1684 I8 => single(lang_items.i8_impl()),
1685 I16 => single(lang_items.i16_impl()),
1686 I32 => single(lang_items.i32_impl()),
1687 I64 => single(lang_items.i64_impl()),
1688 I128 => single(lang_items.i128_impl()),
1689 Usize => single(lang_items.usize_impl()),
1690 U8 => single(lang_items.u8_impl()),
1691 U16 => single(lang_items.u16_impl()),
1692 U32 => single(lang_items.u32_impl()),
1693 U64 => single(lang_items.u64_impl()),
1694 U128 => single(lang_items.u128_impl()),
1695 F32 => both(lang_items.f32_impl(), lang_items.f32_runtime_impl()),
1696 F64 => both(lang_items.f64_impl(), lang_items.f64_runtime_impl()),
1697 Char => single(lang_items.char_impl()),
1698 Bool => single(lang_items.bool_impl()),
1699 Str => both(lang_items.str_impl(), lang_items.str_alloc_impl()),
1704 .chain(lang_items.slice_u8_impl())
1705 .chain(lang_items.slice_alloc_impl())
1706 .chain(lang_items.slice_u8_alloc_impl())
1709 Array => single(lang_items.array_impl()),
1710 Tuple => ArrayVec::new(),
1711 Unit => ArrayVec::new(),
1716 .chain(lang_items.mut_ptr_impl())
1717 .chain(lang_items.const_slice_ptr_impl())
1718 .chain(lang_items.mut_slice_ptr_impl())
1721 Reference => ArrayVec::new(),
1722 Fn => ArrayVec::new(),
1723 Never => ArrayVec::new(),
1728 crate fn as_sym(&self) -> Symbol {
1729 use PrimitiveType::*;
1731 Isize => sym::isize,
1737 Usize => sym::usize,
1748 Array => sym::array,
1749 Slice => sym::slice,
1750 Tuple => sym::tuple,
1752 RawPointer => sym::pointer,
1753 Reference => sym::reference,
1755 Never => sym::never,
1759 /// Returns the DefId of the module with `doc(primitive)` for this primitive type.
1760 /// Panics if there is no such module.
1762 /// This gives precedence to primitives defined in the current crate, and deprioritizes primitives defined in `core`,
1763 /// but otherwise, if multiple crates define the same primitive, there is no guarantee of which will be picked.
1764 /// In particular, if a crate depends on both `std` and another crate that also defines `doc(primitive)`, then
1765 /// it's entirely random whether `std` or the other crate is picked. (no_std crates are usually fine unless multiple dependencies define a primitive.)
1766 crate fn primitive_locations(tcx: TyCtxt<'_>) -> &FxHashMap<PrimitiveType, DefId> {
1767 static PRIMITIVE_LOCATIONS: OnceCell<FxHashMap<PrimitiveType, DefId>> = OnceCell::new();
1768 PRIMITIVE_LOCATIONS.get_or_init(|| {
1769 let mut primitive_locations = FxHashMap::default();
1770 // NOTE: technically this misses crates that are only passed with `--extern` and not loaded when checking the crate.
1771 // This is a degenerate case that I don't plan to support.
1772 for &crate_num in tcx.crates(()) {
1773 let e = ExternalCrate { crate_num };
1774 let crate_name = e.name(tcx);
1775 debug!(?crate_num, ?crate_name);
1776 for &(def_id, prim) in &e.primitives(tcx) {
1777 // HACK: try to link to std instead where possible
1778 if crate_name == sym::core && primitive_locations.contains_key(&prim) {
1781 primitive_locations.insert(prim, def_id);
1784 let local_primitives = ExternalCrate { crate_num: LOCAL_CRATE }.primitives(tcx);
1785 for (def_id, prim) in local_primitives {
1786 primitive_locations.insert(prim, def_id);
1793 impl From<ast::IntTy> for PrimitiveType {
1794 fn from(int_ty: ast::IntTy) -> PrimitiveType {
1796 ast::IntTy::Isize => PrimitiveType::Isize,
1797 ast::IntTy::I8 => PrimitiveType::I8,
1798 ast::IntTy::I16 => PrimitiveType::I16,
1799 ast::IntTy::I32 => PrimitiveType::I32,
1800 ast::IntTy::I64 => PrimitiveType::I64,
1801 ast::IntTy::I128 => PrimitiveType::I128,
1806 impl From<ast::UintTy> for PrimitiveType {
1807 fn from(uint_ty: ast::UintTy) -> PrimitiveType {
1809 ast::UintTy::Usize => PrimitiveType::Usize,
1810 ast::UintTy::U8 => PrimitiveType::U8,
1811 ast::UintTy::U16 => PrimitiveType::U16,
1812 ast::UintTy::U32 => PrimitiveType::U32,
1813 ast::UintTy::U64 => PrimitiveType::U64,
1814 ast::UintTy::U128 => PrimitiveType::U128,
1819 impl From<ast::FloatTy> for PrimitiveType {
1820 fn from(float_ty: ast::FloatTy) -> PrimitiveType {
1822 ast::FloatTy::F32 => PrimitiveType::F32,
1823 ast::FloatTy::F64 => PrimitiveType::F64,
1828 impl From<ty::IntTy> for PrimitiveType {
1829 fn from(int_ty: ty::IntTy) -> PrimitiveType {
1831 ty::IntTy::Isize => PrimitiveType::Isize,
1832 ty::IntTy::I8 => PrimitiveType::I8,
1833 ty::IntTy::I16 => PrimitiveType::I16,
1834 ty::IntTy::I32 => PrimitiveType::I32,
1835 ty::IntTy::I64 => PrimitiveType::I64,
1836 ty::IntTy::I128 => PrimitiveType::I128,
1841 impl From<ty::UintTy> for PrimitiveType {
1842 fn from(uint_ty: ty::UintTy) -> PrimitiveType {
1844 ty::UintTy::Usize => PrimitiveType::Usize,
1845 ty::UintTy::U8 => PrimitiveType::U8,
1846 ty::UintTy::U16 => PrimitiveType::U16,
1847 ty::UintTy::U32 => PrimitiveType::U32,
1848 ty::UintTy::U64 => PrimitiveType::U64,
1849 ty::UintTy::U128 => PrimitiveType::U128,
1854 impl From<ty::FloatTy> for PrimitiveType {
1855 fn from(float_ty: ty::FloatTy) -> PrimitiveType {
1857 ty::FloatTy::F32 => PrimitiveType::F32,
1858 ty::FloatTy::F64 => PrimitiveType::F64,
1863 impl From<hir::PrimTy> for PrimitiveType {
1864 fn from(prim_ty: hir::PrimTy) -> PrimitiveType {
1866 hir::PrimTy::Int(int_ty) => int_ty.into(),
1867 hir::PrimTy::Uint(uint_ty) => uint_ty.into(),
1868 hir::PrimTy::Float(float_ty) => float_ty.into(),
1869 hir::PrimTy::Str => PrimitiveType::Str,
1870 hir::PrimTy::Bool => PrimitiveType::Bool,
1871 hir::PrimTy::Char => PrimitiveType::Char,
1876 #[derive(Copy, Clone, Debug)]
1877 crate enum Visibility {
1880 /// Visibility inherited from parent.
1882 /// For example, this is the visibility of private items and of enum variants.
1884 /// `pub(crate)`, `pub(super)`, or `pub(in path::to::somewhere)`
1889 crate fn is_public(&self) -> bool {
1890 matches!(self, Visibility::Public)
1894 #[derive(Clone, Debug)]
1895 crate struct Struct {
1896 crate struct_type: CtorKind,
1897 crate generics: Generics,
1898 crate fields: Vec<Item>,
1899 crate fields_stripped: bool,
1902 #[derive(Clone, Debug)]
1903 crate struct Union {
1904 crate generics: Generics,
1905 crate fields: Vec<Item>,
1906 crate fields_stripped: bool,
1909 /// This is a more limited form of the standard Struct, different in that
1910 /// it lacks the things most items have (name, id, parameterization). Found
1911 /// only as a variant in an enum.
1912 #[derive(Clone, Debug)]
1913 crate struct VariantStruct {
1914 crate struct_type: CtorKind,
1915 crate fields: Vec<Item>,
1916 crate fields_stripped: bool,
1919 #[derive(Clone, Debug)]
1921 crate variants: IndexVec<VariantIdx, Item>,
1922 crate generics: Generics,
1923 crate variants_stripped: bool,
1926 #[derive(Clone, Debug)]
1927 crate enum Variant {
1930 Struct(VariantStruct),
1933 /// Small wrapper around [`rustc_span::Span`] that adds helper methods
1934 /// and enforces calling [`rustc_span::Span::source_callsite()`].
1935 #[derive(Copy, Clone, Debug)]
1936 crate struct Span(rustc_span::Span);
1939 /// Wraps a [`rustc_span::Span`]. In case this span is the result of a macro expansion, the
1940 /// span will be updated to point to the macro invocation instead of the macro definition.
1942 /// (See rust-lang/rust#39726)
1943 crate fn new(sp: rustc_span::Span) -> Self {
1944 Self(sp.source_callsite())
1947 crate fn inner(&self) -> rustc_span::Span {
1951 crate fn dummy() -> Self {
1952 Self(rustc_span::DUMMY_SP)
1955 crate fn is_dummy(&self) -> bool {
1959 crate fn filename(&self, sess: &Session) -> FileName {
1960 sess.source_map().span_to_filename(self.0)
1963 crate fn lo(&self, sess: &Session) -> Loc {
1964 sess.source_map().lookup_char_pos(self.0.lo())
1967 crate fn hi(&self, sess: &Session) -> Loc {
1968 sess.source_map().lookup_char_pos(self.0.hi())
1971 crate fn cnum(&self, sess: &Session) -> CrateNum {
1972 // FIXME: is there a time when the lo and hi crate would be different?
1973 self.lo(sess).file.cnum
1977 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
1981 crate segments: Vec<PathSegment>,
1985 crate fn last(&self) -> Symbol {
1986 self.segments.last().expect("segments were empty").name
1989 crate fn last_name(&self) -> SymbolStr {
1990 self.segments.last().expect("segments were empty").name.as_str()
1993 crate fn whole_name(&self) -> String {
1994 String::from(if self.global { "::" } else { "" })
1995 + &self.segments.iter().map(|s| s.name.to_string()).collect::<Vec<_>>().join("::")
1999 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
2000 crate enum GenericArg {
2003 Const(Box<Constant>),
2007 // `GenericArg` can occur many times in a single `Path`, so make sure it
2008 // doesn't increase in size unexpectedly.
2009 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2010 rustc_data_structures::static_assert_size!(GenericArg, 80);
2012 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
2013 crate enum GenericArgs {
2014 AngleBracketed { args: Vec<GenericArg>, bindings: Vec<TypeBinding> },
2015 Parenthesized { inputs: Vec<Type>, output: Option<Box<Type>> },
2018 // `GenericArgs` is in every `PathSegment`, so its size can significantly
2019 // affect rustdoc's memory usage.
2020 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2021 rustc_data_structures::static_assert_size!(GenericArgs, 56);
2023 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
2024 crate struct PathSegment {
2026 crate args: GenericArgs,
2029 // `PathSegment` usually occurs multiple times in every `Path`, so its size can
2030 // significantly affect rustdoc's memory usage.
2031 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
2032 rustc_data_structures::static_assert_size!(PathSegment, 64);
2034 #[derive(Clone, Debug)]
2035 crate struct Typedef {
2037 crate generics: Generics,
2038 /// `type_` can come from either the HIR or from metadata. If it comes from HIR, it may be a type
2039 /// alias instead of the final type. This will always have the final type, regardless of whether
2040 /// `type_` came from HIR or from metadata.
2042 /// If `item_type.is_none()`, `type_` is guarenteed to come from metadata (and therefore hold the
2044 crate item_type: Option<Type>,
2047 impl GetDefId for Typedef {
2048 fn def_id(&self) -> Option<DefId> {
2052 fn def_id_full(&self, cache: &Cache) -> Option<DefId> {
2053 self.type_.def_id_full(cache)
2057 #[derive(Clone, Debug)]
2058 crate struct OpaqueTy {
2059 crate bounds: Vec<GenericBound>,
2060 crate generics: Generics,
2063 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
2064 crate struct BareFunctionDecl {
2065 crate unsafety: hir::Unsafety,
2066 crate generic_params: Vec<GenericParamDef>,
2071 #[derive(Clone, Debug)]
2072 crate struct Static {
2074 crate mutability: Mutability,
2075 crate expr: Option<BodyId>,
2078 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
2079 crate struct Constant {
2081 crate kind: ConstantKind,
2084 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
2085 crate enum ConstantKind {
2086 /// This is the wrapper around `ty::Const` for a non-local constant. Because it doesn't have a
2087 /// `BodyId`, we need to handle it on its own.
2089 /// Note that `ty::Const` includes generic parameters, and may not always be uniquely identified
2090 /// by a DefId. So this field must be different from `Extern`.
2091 TyConst { expr: String },
2092 /// A constant (expression) that's not an item or associated item. These are usually found
2093 /// nested inside types (e.g., array lengths) or expressions (e.g., repeat counts), and also
2094 /// used to define explicit discriminant values for enum variants.
2095 Anonymous { body: BodyId },
2096 /// A constant from a different crate.
2097 Extern { def_id: DefId },
2098 /// `const FOO: u32 = ...;`
2099 Local { def_id: DefId, body: BodyId },
2103 crate fn expr(&self, tcx: TyCtxt<'_>) -> String {
2105 ConstantKind::TyConst { ref expr } => expr.clone(),
2106 ConstantKind::Extern { def_id } => print_inlined_const(tcx, def_id),
2107 ConstantKind::Local { body, .. } | ConstantKind::Anonymous { body } => {
2108 print_const_expr(tcx, body)
2113 crate fn value(&self, tcx: TyCtxt<'_>) -> Option<String> {
2115 ConstantKind::TyConst { .. } | ConstantKind::Anonymous { .. } => None,
2116 ConstantKind::Extern { def_id } | ConstantKind::Local { def_id, .. } => {
2117 print_evaluated_const(tcx, def_id)
2122 crate fn is_literal(&self, tcx: TyCtxt<'_>) -> bool {
2124 ConstantKind::TyConst { .. } => false,
2125 ConstantKind::Extern { def_id } => def_id.as_local().map_or(false, |def_id| {
2126 is_literal_expr(tcx, tcx.hir().local_def_id_to_hir_id(def_id))
2128 ConstantKind::Local { body, .. } | ConstantKind::Anonymous { body } => {
2129 is_literal_expr(tcx, body.hir_id)
2135 #[derive(Clone, Debug)]
2138 crate unsafety: hir::Unsafety,
2139 crate generics: Generics,
2140 crate trait_: Option<Type>,
2142 crate items: Vec<Item>,
2143 crate negative_polarity: bool,
2144 crate synthetic: bool,
2145 crate blanket_impl: Option<Box<Type>>,
2149 crate fn provided_trait_methods(&self, tcx: TyCtxt<'_>) -> FxHashSet<Symbol> {
2152 .map(|did| tcx.provided_trait_methods(did).map(|meth| meth.ident.name).collect())
2153 .unwrap_or_default()
2157 #[derive(Clone, Debug)]
2158 crate struct Import {
2159 crate kind: ImportKind,
2160 crate source: ImportSource,
2161 crate should_be_displayed: bool,
2165 crate fn new_simple(name: Symbol, source: ImportSource, should_be_displayed: bool) -> Self {
2166 Self { kind: ImportKind::Simple(name), source, should_be_displayed }
2169 crate fn new_glob(source: ImportSource, should_be_displayed: bool) -> Self {
2170 Self { kind: ImportKind::Glob, source, should_be_displayed }
2174 #[derive(Clone, Debug)]
2175 crate enum ImportKind {
2176 // use source as str;
2182 #[derive(Clone, Debug)]
2183 crate struct ImportSource {
2185 crate did: Option<DefId>,
2188 #[derive(Clone, Debug)]
2189 crate struct Macro {
2190 crate source: String,
2193 #[derive(Clone, Debug)]
2194 crate struct ProcMacro {
2195 crate kind: MacroKind,
2196 crate helpers: Vec<Symbol>,
2199 /// An type binding on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
2200 /// `A: Send + Sync` in `Foo<A: Send + Sync>`).
2201 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
2202 crate struct TypeBinding {
2204 crate kind: TypeBindingKind,
2207 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
2208 crate enum TypeBindingKind {
2209 Equality { ty: Type },
2210 Constraint { bounds: Vec<GenericBound> },
2214 crate fn ty(&self) -> &Type {
2216 TypeBindingKind::Equality { ref ty } => ty,
2217 _ => panic!("expected equality type binding for parenthesized generic args"),