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 dst: &std::path::Path,
173 ) -> ExternalLocation {
174 use ExternalLocation::*;
176 fn to_remote(url: impl ToString) -> ExternalLocation {
177 let mut url = url.to_string();
178 if !url.ends_with('/') {
184 // See if there's documentation generated into the local directory
185 // WARNING: since rustdoc creates these directories as it generates documentation, this check is only accurate before rendering starts.
186 // Make sure to call `location()` by that time.
187 let local_location = dst.join(&*self.name(tcx).as_str());
188 if local_location.is_dir() {
192 if let Some(url) = extern_url {
193 return to_remote(url);
196 // Failing that, see if there's an attribute specifying where to find this
198 let did = DefId { krate: self.crate_num, index: CRATE_DEF_INDEX };
201 .filter(|a| a.has_name(sym::html_root_url))
202 .filter_map(|a| a.value_str())
205 .unwrap_or(Unknown) // Well, at least we tried.
208 crate fn keywords(&self, tcx: TyCtxt<'_>) -> ThinVec<(DefId, Symbol)> {
209 let root = self.def_id();
211 let as_keyword = |res: Res| {
212 if let Res::Def(DefKind::Mod, def_id) = res {
213 let attrs = tcx.get_attrs(def_id);
214 let mut keyword = None;
215 for attr in attrs.lists(sym::doc) {
216 if attr.has_name(sym::keyword) {
217 if let Some(v) = attr.value_str() {
223 return keyword.map(|p| (def_id, p));
234 let item = tcx.hir().item(id);
236 hir::ItemKind::Mod(_) => {
237 as_keyword(Res::Def(DefKind::Mod, id.def_id.to_def_id()))
239 hir::ItemKind::Use(ref path, hir::UseKind::Single)
240 if item.vis.node.is_pub() =>
242 as_keyword(path.res).map(|(_, prim)| (id.def_id.to_def_id(), prim))
249 tcx.item_children(root).iter().map(|item| item.res).filter_map(as_keyword).collect()
253 crate fn primitives(&self, tcx: TyCtxt<'_>) -> ThinVec<(DefId, PrimitiveType)> {
254 let root = self.def_id();
256 // Collect all inner modules which are tagged as implementations of
259 // Note that this loop only searches the top-level items of the crate,
260 // and this is intentional. If we were to search the entire crate for an
261 // item tagged with `#[doc(primitive)]` then we would also have to
262 // search the entirety of external modules for items tagged
263 // `#[doc(primitive)]`, which is a pretty inefficient process (decoding
264 // all that metadata unconditionally).
266 // In order to keep the metadata load under control, the
267 // `#[doc(primitive)]` feature is explicitly designed to only allow the
268 // primitive tags to show up as the top level items in a crate.
270 // Also note that this does not attempt to deal with modules tagged
271 // duplicately for the same primitive. This is handled later on when
272 // rendering by delegating everything to a hash map.
273 let as_primitive = |res: Res| {
274 if let Res::Def(DefKind::Mod, def_id) = res {
275 let attrs = tcx.get_attrs(def_id);
277 for attr in attrs.lists(sym::doc) {
278 if let Some(v) = attr.value_str() {
279 if attr.has_name(sym::primitive) {
280 prim = PrimitiveType::from_symbol(v);
284 // FIXME: should warn on unknown primitives?
288 return prim.map(|p| (def_id, p));
300 let item = tcx.hir().item(id);
302 hir::ItemKind::Mod(_) => {
303 as_primitive(Res::Def(DefKind::Mod, id.def_id.to_def_id()))
305 hir::ItemKind::Use(ref path, hir::UseKind::Single)
306 if item.vis.node.is_pub() =>
308 as_primitive(path.res).map(|(_, prim)| {
309 // Pretend the primitive is local.
310 (id.def_id.to_def_id(), prim)
318 tcx.item_children(root).iter().map(|item| item.res).filter_map(as_primitive).collect()
323 /// Anything with a source location and set of attributes and, optionally, a
324 /// name. That is, anything that can be documented. This doesn't correspond
325 /// directly to the AST's concept of an item; it's a strict superset.
326 #[derive(Clone, Debug)]
328 /// The name of this item.
329 /// Optional because not every item has a name, e.g. impls.
330 crate name: Option<Symbol>,
331 crate attrs: Box<Attributes>,
332 crate visibility: Visibility,
333 /// Information about this item that is specific to what kind of item it is.
334 /// E.g., struct vs enum vs function.
335 crate kind: Box<ItemKind>,
336 crate def_id: ItemId,
338 crate cfg: Option<Arc<Cfg>>,
341 // `Item` is used a lot. Make sure it doesn't unintentionally get bigger.
342 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
343 rustc_data_structures::static_assert_size!(Item, 56);
345 crate fn rustc_span(def_id: DefId, tcx: TyCtxt<'_>) -> Span {
346 Span::from_rustc_span(def_id.as_local().map_or_else(
347 || tcx.def_span(def_id),
350 hir.span_with_body(hir.local_def_id_to_hir_id(local))
356 crate fn stability<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Option<&'tcx Stability> {
357 self.def_id.as_def_id().and_then(|did| tcx.lookup_stability(did))
360 crate fn const_stability<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Option<&'tcx ConstStability> {
361 self.def_id.as_def_id().and_then(|did| tcx.lookup_const_stability(did))
364 crate fn deprecation(&self, tcx: TyCtxt<'_>) -> Option<Deprecation> {
365 self.def_id.as_def_id().and_then(|did| tcx.lookup_deprecation(did))
368 crate fn inner_docs(&self, tcx: TyCtxt<'_>) -> bool {
369 self.def_id.as_def_id().map(|did| tcx.get_attrs(did).inner_docs()).unwrap_or(false)
372 crate fn span(&self, tcx: TyCtxt<'_>) -> Span {
373 let kind = match &*self.kind {
374 ItemKind::StrippedItem(k) => k,
377 if let ItemKind::ModuleItem(Module { span, .. }) | ItemKind::ImplItem(Impl { span, .. }) =
382 self.def_id.as_def_id().map(|did| rustc_span(did, tcx)).unwrap_or_else(|| Span::dummy())
386 crate fn attr_span(&self, tcx: TyCtxt<'_>) -> rustc_span::Span {
387 crate::passes::span_of_attrs(&self.attrs).unwrap_or_else(|| self.span(tcx).inner())
390 /// Finds the `doc` attribute as a NameValue and returns the corresponding
392 crate fn doc_value(&self) -> Option<String> {
393 self.attrs.doc_value()
396 /// Convenience wrapper around [`Self::from_def_id_and_parts`] which converts
397 /// `hir_id` to a [`DefId`]
398 pub fn from_hir_id_and_parts(
400 name: Option<Symbol>,
402 cx: &mut DocContext<'_>,
404 Item::from_def_id_and_parts(cx.tcx.hir().local_def_id(hir_id).to_def_id(), name, kind, cx)
407 pub fn from_def_id_and_parts(
409 name: Option<Symbol>,
411 cx: &mut DocContext<'_>,
413 let ast_attrs = cx.tcx.get_attrs(def_id);
415 Self::from_def_id_and_attrs_and_parts(
419 box ast_attrs.clean(cx),
421 ast_attrs.cfg(cx.sess()),
425 pub fn from_def_id_and_attrs_and_parts(
427 name: Option<Symbol>,
429 attrs: Box<Attributes>,
430 cx: &mut DocContext<'_>,
431 cfg: Option<Arc<Cfg>>,
433 trace!("name={:?}, def_id={:?}", name, def_id);
436 def_id: def_id.into(),
440 visibility: cx.tcx.visibility(def_id).clean(cx),
445 /// Finds all `doc` attributes as NameValues and returns their corresponding values, joined
447 crate fn collapsed_doc_value(&self) -> Option<String> {
448 self.attrs.collapsed_doc_value()
451 crate fn links(&self, cx: &Context<'_>) -> Vec<RenderedLink> {
452 use crate::html::format::href;
457 .map_or(&[][..], |v| v.as_slice())
459 .filter_map(|ItemLink { link: s, link_text, did, ref fragment }| {
462 if let Ok((mut href, ..)) = href(did.clone(), cx) {
463 if let Some(ref fragment) = *fragment {
465 href.push_str(fragment);
468 original_text: s.clone(),
469 new_text: link_text.clone(),
476 // FIXME(83083): using fragments as a side-channel for
477 // primitive names is very unfortunate
479 let relative_to = &cx.current;
480 if let Some(ref fragment) = *fragment {
481 let url = match cx.cache().extern_locations.get(&self.def_id.krate()) {
482 Some(&ExternalLocation::Local) => {
483 if relative_to[0] == "std" {
484 let depth = relative_to.len() - 1;
487 let depth = relative_to.len();
488 format!("{}std/", "../".repeat(depth))
491 Some(ExternalLocation::Remote(ref s)) => {
492 format!("{}/std/", s.trim_end_matches('/'))
494 Some(ExternalLocation::Unknown) | None => {
495 format!("{}/std/", crate::DOC_RUST_LANG_ORG_CHANNEL)
498 // This is a primitive so the url is done "by hand".
499 let tail = fragment.find('#').unwrap_or_else(|| fragment.len());
501 original_text: s.clone(),
502 new_text: link_text.clone(),
504 "{}primitive.{}.html{}",
511 panic!("This isn't a primitive?!");
519 /// Find a list of all link names, without finding their href.
521 /// This is used for generating summary text, which does not include
522 /// the link text, but does need to know which `[]`-bracketed names
523 /// are actually links.
524 crate fn link_names(&self, cache: &Cache) -> Vec<RenderedLink> {
528 .map_or(&[][..], |v| v.as_slice())
530 .filter_map(|ItemLink { link: s, link_text, did, fragment }| {
531 // FIXME(83083): using fragments as a side-channel for
532 // primitive names is very unfortunate
533 if did.is_some() || fragment.is_some() {
535 original_text: s.clone(),
536 new_text: link_text.clone(),
546 crate fn is_crate(&self) -> bool {
547 self.is_mod() && self.def_id.as_def_id().map_or(false, |did| did.index == CRATE_DEF_INDEX)
549 crate fn is_mod(&self) -> bool {
550 self.type_() == ItemType::Module
552 crate fn is_trait(&self) -> bool {
553 self.type_() == ItemType::Trait
555 crate fn is_struct(&self) -> bool {
556 self.type_() == ItemType::Struct
558 crate fn is_enum(&self) -> bool {
559 self.type_() == ItemType::Enum
561 crate fn is_variant(&self) -> bool {
562 self.type_() == ItemType::Variant
564 crate fn is_associated_type(&self) -> bool {
565 self.type_() == ItemType::AssocType
567 crate fn is_associated_const(&self) -> bool {
568 self.type_() == ItemType::AssocConst
570 crate fn is_method(&self) -> bool {
571 self.type_() == ItemType::Method
573 crate fn is_ty_method(&self) -> bool {
574 self.type_() == ItemType::TyMethod
576 crate fn is_typedef(&self) -> bool {
577 self.type_() == ItemType::Typedef
579 crate fn is_primitive(&self) -> bool {
580 self.type_() == ItemType::Primitive
582 crate fn is_union(&self) -> bool {
583 self.type_() == ItemType::Union
585 crate fn is_import(&self) -> bool {
586 self.type_() == ItemType::Import
588 crate fn is_extern_crate(&self) -> bool {
589 self.type_() == ItemType::ExternCrate
591 crate fn is_keyword(&self) -> bool {
592 self.type_() == ItemType::Keyword
594 crate fn is_stripped(&self) -> bool {
596 StrippedItem(..) => true,
597 ImportItem(ref i) => !i.should_be_displayed,
601 crate fn has_stripped_fields(&self) -> Option<bool> {
603 StructItem(ref _struct) => Some(_struct.fields_stripped),
604 UnionItem(ref union) => Some(union.fields_stripped),
605 VariantItem(Variant::Struct(ref vstruct)) => Some(vstruct.fields_stripped),
610 crate fn stability_class(&self, tcx: TyCtxt<'_>) -> Option<String> {
611 self.stability(tcx).as_ref().and_then(|ref s| {
612 let mut classes = Vec::with_capacity(2);
614 if s.level.is_unstable() {
615 classes.push("unstable");
618 // FIXME: what about non-staged API items that are deprecated?
619 if self.deprecation(tcx).is_some() {
620 classes.push("deprecated");
623 if !classes.is_empty() { Some(classes.join(" ")) } else { None }
627 crate fn stable_since(&self, tcx: TyCtxt<'_>) -> Option<SymbolStr> {
628 match self.stability(tcx)?.level {
629 StabilityLevel::Stable { since, .. } => Some(since.as_str()),
630 StabilityLevel::Unstable { .. } => None,
634 crate fn const_stable_since(&self, tcx: TyCtxt<'_>) -> Option<SymbolStr> {
635 match self.const_stability(tcx)?.level {
636 StabilityLevel::Stable { since, .. } => Some(since.as_str()),
637 StabilityLevel::Unstable { .. } => None,
641 crate fn is_non_exhaustive(&self) -> bool {
642 self.attrs.other_attrs.iter().any(|a| a.has_name(sym::non_exhaustive))
645 /// Returns a documentation-level item type from the item.
646 crate fn type_(&self) -> ItemType {
650 crate fn is_default(&self) -> bool {
652 ItemKind::MethodItem(_, Some(defaultness)) => {
653 defaultness.has_value() && !defaultness.is_final()
660 #[derive(Clone, Debug)]
661 crate enum ItemKind {
663 /// The crate's name, *not* the name it's imported as.
670 FunctionItem(Function),
672 TypedefItem(Typedef, bool /* is associated type */),
673 OpaqueTyItem(OpaqueTy),
675 ConstantItem(Constant),
677 TraitAliasItem(TraitAlias),
679 /// A method signature only. Used for required methods in traits (ie,
680 /// non-default-methods).
681 TyMethodItem(Function),
682 /// A method with a body.
683 MethodItem(Function, Option<hir::Defaultness>),
684 StructFieldItem(Type),
685 VariantItem(Variant),
686 /// `fn`s from an extern block
687 ForeignFunctionItem(Function),
688 /// `static`s from an extern block
689 ForeignStaticItem(Static),
690 /// `type`s from an extern block
693 ProcMacroItem(ProcMacro),
694 PrimitiveItem(PrimitiveType),
695 AssocConstItem(Type, Option<String>),
696 /// An associated item in a trait or trait impl.
698 /// The bounds may be non-empty if there is a `where` clause.
699 /// The `Option<Type>` is the default concrete type (e.g. `trait Trait { type Target = usize; }`)
700 AssocTypeItem(Vec<GenericBound>, Option<Type>),
701 /// An item that has been stripped by a rustdoc pass
702 StrippedItem(Box<ItemKind>),
707 /// Some items contain others such as structs (for their fields) and Enums
708 /// (for their variants). This method returns those contained items.
709 crate fn inner_items(&self) -> impl Iterator<Item = &Item> {
711 StructItem(s) => s.fields.iter(),
712 UnionItem(u) => u.fields.iter(),
713 VariantItem(Variant::Struct(v)) => v.fields.iter(),
714 EnumItem(e) => e.variants.iter(),
715 TraitItem(t) => t.items.iter(),
716 ImplItem(i) => i.items.iter(),
717 ModuleItem(m) => m.items.iter(),
718 ExternCrateItem { .. }
730 | ForeignFunctionItem(_)
731 | ForeignStaticItem(_)
736 | AssocConstItem(_, _)
737 | AssocTypeItem(_, _)
739 | KeywordItem(_) => [].iter(),
744 #[derive(Clone, Debug)]
745 crate struct Module {
746 crate items: Vec<Item>,
750 crate struct ListAttributesIter<'a> {
751 attrs: slice::Iter<'a, ast::Attribute>,
752 current_list: vec::IntoIter<ast::NestedMetaItem>,
756 impl<'a> Iterator for ListAttributesIter<'a> {
757 type Item = ast::NestedMetaItem;
759 fn next(&mut self) -> Option<Self::Item> {
760 if let Some(nested) = self.current_list.next() {
764 for attr in &mut self.attrs {
765 if let Some(list) = attr.meta_item_list() {
766 if attr.has_name(self.name) {
767 self.current_list = list.into_iter();
768 if let Some(nested) = self.current_list.next() {
778 fn size_hint(&self) -> (usize, Option<usize>) {
779 let lower = self.current_list.len();
784 crate trait AttributesExt {
785 /// Finds an attribute as List and returns the list of attributes nested inside.
786 fn lists(&self, name: Symbol) -> ListAttributesIter<'_>;
788 fn span(&self) -> Option<rustc_span::Span>;
790 fn inner_docs(&self) -> bool;
792 fn other_attrs(&self) -> Vec<ast::Attribute>;
794 fn cfg(&self, sess: &Session) -> Option<Arc<Cfg>>;
797 impl AttributesExt for [ast::Attribute] {
798 fn lists(&self, name: Symbol) -> ListAttributesIter<'_> {
799 ListAttributesIter { attrs: self.iter(), current_list: Vec::new().into_iter(), name }
802 /// Return the span of the first doc-comment, if it exists.
803 fn span(&self) -> Option<rustc_span::Span> {
804 self.iter().find(|attr| attr.doc_str().is_some()).map(|attr| attr.span)
807 /// Returns whether the first doc-comment is an inner attribute.
809 //// If there are no doc-comments, return true.
810 /// FIXME(#78591): Support both inner and outer attributes on the same item.
811 fn inner_docs(&self) -> bool {
812 self.iter().find(|a| a.doc_str().is_some()).map_or(true, |a| a.style == AttrStyle::Inner)
815 fn other_attrs(&self) -> Vec<ast::Attribute> {
816 self.iter().filter(|attr| attr.doc_str().is_none()).cloned().collect()
819 fn cfg(&self, sess: &Session) -> Option<Arc<Cfg>> {
820 let mut cfg = Cfg::True;
822 for attr in self.iter() {
824 if attr.doc_str().is_none() && attr.has_name(sym::doc) {
826 if let Some(list) = attr.meta().as_ref().and_then(|mi| mi.meta_item_list()) {
829 if !item.has_name(sym::cfg) {
833 if let Some(cfg_mi) = item
835 .and_then(|item| rustc_expand::config::parse_cfg(&item, sess))
837 match Cfg::parse(&cfg_mi) {
838 Ok(new_cfg) => cfg &= new_cfg,
839 Err(e) => sess.span_err(e.span, e.msg),
847 for attr in self.lists(sym::target_feature) {
848 if attr.has_name(sym::enable) {
849 if let Some(feat) = attr.value_str() {
850 let meta = attr::mk_name_value_item_str(
851 Ident::with_dummy_span(sym::target_feature),
855 if let Ok(feat_cfg) = Cfg::parse(&meta) {
862 if cfg == Cfg::True { None } else { Some(Arc::new(cfg)) }
866 crate trait NestedAttributesExt {
867 /// Returns `true` if the attribute list contains a specific `Word`
868 fn has_word(self, word: Symbol) -> bool;
869 fn get_word_attr(self, word: Symbol) -> Option<ast::NestedMetaItem>;
872 impl<I: Iterator<Item = ast::NestedMetaItem> + IntoIterator<Item = ast::NestedMetaItem>>
873 NestedAttributesExt for I
875 fn has_word(self, word: Symbol) -> bool {
876 self.into_iter().any(|attr| attr.is_word() && attr.has_name(word))
879 fn get_word_attr(mut self, word: Symbol) -> Option<ast::NestedMetaItem> {
880 self.find(|attr| attr.is_word() && attr.has_name(word))
884 /// A portion of documentation, extracted from a `#[doc]` attribute.
886 /// Each variant contains the line number within the complete doc-comment where the fragment
887 /// starts, as well as the Span where the corresponding doc comment or attribute is located.
889 /// Included files are kept separate from inline doc comments so that proper line-number
890 /// information can be given when a doctest fails. Sugared doc comments and "raw" doc comments are
891 /// kept separate because of issue #42760.
892 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
893 crate struct DocFragment {
895 crate span: rustc_span::Span,
896 /// The module this doc-comment came from.
898 /// This allows distinguishing between the original documentation and a pub re-export.
899 /// If it is `None`, the item was not re-exported.
900 crate parent_module: Option<DefId>,
902 crate kind: DocFragmentKind,
903 crate need_backline: bool,
907 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
908 crate enum DocFragmentKind {
909 /// A doc fragment created from a `///` or `//!` doc comment.
911 /// A doc fragment created from a "raw" `#[doc=""]` attribute.
915 // The goal of this function is to apply the `DocFragment` transformations that are required when
916 // transforming into the final markdown. So the transformations in here are:
918 // * Applying the computed indent to each lines in each doc fragment (a `DocFragment` can contain
919 // multiple lines in case of `#[doc = ""]`).
920 // * Adding backlines between `DocFragment`s and adding an extra one if required (stored in the
921 // `need_backline` field).
922 fn add_doc_fragment(out: &mut String, frag: &DocFragment) {
923 let s = frag.doc.as_str();
924 let mut iter = s.lines().peekable();
925 while let Some(line) = iter.next() {
926 if line.chars().any(|c| !c.is_whitespace()) {
927 assert!(line.len() >= frag.indent);
928 out.push_str(&line[frag.indent..]);
932 if iter.peek().is_some() {
936 if frag.need_backline {
941 impl<'a> FromIterator<&'a DocFragment> for String {
942 fn from_iter<T>(iter: T) -> Self
944 T: IntoIterator<Item = &'a DocFragment>,
946 iter.into_iter().fold(String::new(), |mut acc, frag| {
947 add_doc_fragment(&mut acc, &frag);
953 /// The attributes on an [`Item`], including attributes like `#[derive(...)]` and `#[inline]`,
954 /// as well as doc comments.
955 #[derive(Clone, Debug, Default)]
956 crate struct Attributes {
957 crate doc_strings: Vec<DocFragment>,
958 crate other_attrs: Vec<ast::Attribute>,
961 #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
962 /// A link that has not yet been rendered.
964 /// This link will be turned into a rendered link by [`Item::links`].
965 crate struct ItemLink {
966 /// The original link written in the markdown
967 pub(crate) link: String,
968 /// The link text displayed in the HTML.
970 /// This may not be the same as `link` if there was a disambiguator
971 /// in an intra-doc link (e.g. \[`fn@f`\])
972 pub(crate) link_text: String,
973 pub(crate) did: Option<DefId>,
974 /// The url fragment to append to the link
975 pub(crate) fragment: Option<String>,
978 pub struct RenderedLink {
979 /// The text the link was original written as.
981 /// This could potentially include disambiguators and backticks.
982 pub(crate) original_text: String,
983 /// The text to display in the HTML
984 pub(crate) new_text: String,
985 /// The URL to put in the `href`
986 pub(crate) href: String,
990 crate fn lists(&self, name: Symbol) -> ListAttributesIter<'_> {
991 self.other_attrs.lists(name)
994 crate fn has_doc_flag(&self, flag: Symbol) -> bool {
995 for attr in &self.other_attrs {
996 if !attr.has_name(sym::doc) {
1000 if let Some(items) = attr.meta_item_list() {
1001 if items.iter().filter_map(|i| i.meta_item()).any(|it| it.has_name(flag)) {
1011 attrs: &[ast::Attribute],
1012 additional_attrs: Option<(&[ast::Attribute], DefId)>,
1014 let mut doc_strings: Vec<DocFragment> = vec![];
1015 let mut doc_line = 0;
1017 fn update_need_backline(doc_strings: &mut Vec<DocFragment>) {
1018 if let Some(prev) = doc_strings.last_mut() {
1019 prev.need_backline = true;
1023 let clean_attr = |(attr, parent_module): (&ast::Attribute, Option<DefId>)| {
1024 if let Some(value) = attr.doc_str() {
1025 trace!("got doc_str={:?}", value);
1026 let value = beautify_doc_string(value);
1027 let kind = if attr.is_doc_comment() {
1028 DocFragmentKind::SugaredDoc
1030 DocFragmentKind::RawDoc
1033 let line = doc_line;
1034 doc_line += value.as_str().lines().count();
1035 let frag = DocFragment {
1041 need_backline: false,
1045 update_need_backline(&mut doc_strings);
1047 doc_strings.push(frag);
1055 // Additional documentation should be shown before the original documentation
1056 let other_attrs = additional_attrs
1058 .map(|(attrs, id)| attrs.iter().map(move |attr| (attr, Some(id))))
1060 .chain(attrs.iter().map(|attr| (attr, None)))
1061 .filter_map(clean_attr)
1064 Attributes { doc_strings, other_attrs }
1067 /// Finds the `doc` attribute as a NameValue and returns the corresponding
1069 crate fn doc_value(&self) -> Option<String> {
1070 let mut iter = self.doc_strings.iter();
1072 let ori = iter.next()?;
1073 let mut out = String::new();
1074 add_doc_fragment(&mut out, &ori);
1075 while let Some(new_frag) = iter.next() {
1076 if new_frag.kind != ori.kind || new_frag.parent_module != ori.parent_module {
1079 add_doc_fragment(&mut out, &new_frag);
1081 if out.is_empty() { None } else { Some(out) }
1084 /// Return the doc-comments on this item, grouped by the module they came from.
1086 /// The module can be different if this is a re-export with added documentation.
1087 crate fn collapsed_doc_value_by_module_level(&self) -> FxHashMap<Option<DefId>, String> {
1088 let mut ret = FxHashMap::default();
1090 for new_frag in self.doc_strings.iter() {
1091 let out = ret.entry(new_frag.parent_module).or_default();
1092 add_doc_fragment(out, &new_frag);
1097 /// Finds all `doc` attributes as NameValues and returns their corresponding values, joined
1099 crate fn collapsed_doc_value(&self) -> Option<String> {
1100 if self.doc_strings.is_empty() { None } else { Some(self.doc_strings.iter().collect()) }
1103 crate fn get_doc_aliases(&self) -> Box<[String]> {
1104 let mut aliases = FxHashSet::default();
1106 for attr in self.other_attrs.lists(sym::doc).filter(|a| a.has_name(sym::alias)) {
1107 if let Some(values) = attr.meta_item_list() {
1109 match l.literal().unwrap().kind {
1110 ast::LitKind::Str(s, _) => {
1111 aliases.insert(s.as_str().to_string());
1113 _ => unreachable!(),
1117 aliases.insert(attr.value_str().map(|s| s.to_string()).unwrap());
1120 aliases.into_iter().collect::<Vec<String>>().into()
1124 impl PartialEq for Attributes {
1125 fn eq(&self, rhs: &Self) -> bool {
1126 self.doc_strings == rhs.doc_strings
1130 .map(|attr| attr.id)
1131 .eq(rhs.other_attrs.iter().map(|attr| attr.id))
1135 impl Eq for Attributes {}
1137 impl Hash for Attributes {
1138 fn hash<H: Hasher>(&self, hasher: &mut H) {
1139 self.doc_strings.hash(hasher);
1140 for attr in &self.other_attrs {
1141 attr.id.hash(hasher);
1146 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
1147 crate enum GenericBound {
1148 TraitBound(PolyTrait, hir::TraitBoundModifier),
1153 crate fn maybe_sized(cx: &mut DocContext<'_>) -> GenericBound {
1154 let did = cx.tcx.require_lang_item(LangItem::Sized, None);
1155 let empty = cx.tcx.intern_substs(&[]);
1156 let path = external_path(cx, cx.tcx.item_name(did), Some(did), false, vec![], empty);
1157 inline::record_extern_fqn(cx, did, ItemType::Trait);
1158 GenericBound::TraitBound(
1160 trait_: ResolvedPath { path, did, is_generic: false },
1161 generic_params: Vec::new(),
1163 hir::TraitBoundModifier::Maybe,
1167 crate fn is_sized_bound(&self, cx: &DocContext<'_>) -> bool {
1168 use rustc_hir::TraitBoundModifier as TBM;
1169 if let GenericBound::TraitBound(PolyTrait { ref trait_, .. }, TBM::None) = *self {
1170 if trait_.def_id() == cx.tcx.lang_items().sized_trait() {
1177 crate fn get_poly_trait(&self) -> Option<PolyTrait> {
1178 if let GenericBound::TraitBound(ref p, _) = *self {
1179 return Some(p.clone());
1184 crate fn get_trait_type(&self) -> Option<Type> {
1185 if let GenericBound::TraitBound(PolyTrait { ref trait_, .. }, _) = *self {
1186 Some(trait_.clone())
1193 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
1194 crate struct Lifetime(pub Symbol);
1197 crate fn get_ref(&self) -> SymbolStr {
1201 crate fn statik() -> Lifetime {
1202 Lifetime(kw::StaticLifetime)
1205 crate fn elided() -> Lifetime {
1206 Lifetime(kw::UnderscoreLifetime)
1210 #[derive(Clone, Debug)]
1211 crate enum WherePredicate {
1212 BoundPredicate { ty: Type, bounds: Vec<GenericBound>, bound_params: Vec<Lifetime> },
1213 RegionPredicate { lifetime: Lifetime, bounds: Vec<GenericBound> },
1214 EqPredicate { lhs: Type, rhs: Type },
1217 impl WherePredicate {
1218 crate fn get_bounds(&self) -> Option<&[GenericBound]> {
1220 WherePredicate::BoundPredicate { ref bounds, .. } => Some(bounds),
1221 WherePredicate::RegionPredicate { ref bounds, .. } => Some(bounds),
1227 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
1228 crate enum GenericParamDefKind {
1232 bounds: Vec<GenericBound>,
1233 default: Option<Type>,
1234 synthetic: Option<hir::SyntheticTyParamKind>,
1239 default: Option<String>,
1243 impl GenericParamDefKind {
1244 crate fn is_type(&self) -> bool {
1245 matches!(self, GenericParamDefKind::Type { .. })
1248 // FIXME(eddyb) this either returns the default of a type parameter, or the
1249 // type of a `const` parameter. It seems that the intention is to *visit*
1250 // any embedded types, but `get_type` seems to be the wrong name for that.
1251 crate fn get_type(&self) -> Option<Type> {
1253 GenericParamDefKind::Type { default, .. } => default.clone(),
1254 GenericParamDefKind::Const { ty, .. } => Some(ty.clone()),
1255 GenericParamDefKind::Lifetime => None,
1260 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
1261 crate struct GenericParamDef {
1263 crate kind: GenericParamDefKind,
1266 impl GenericParamDef {
1267 crate fn is_synthetic_type_param(&self) -> bool {
1269 GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => false,
1270 GenericParamDefKind::Type { ref synthetic, .. } => synthetic.is_some(),
1274 crate fn is_type(&self) -> bool {
1278 crate fn get_type(&self) -> Option<Type> {
1279 self.kind.get_type()
1282 crate fn get_bounds(&self) -> Option<&[GenericBound]> {
1284 GenericParamDefKind::Type { ref bounds, .. } => Some(bounds),
1290 // maybe use a Generic enum and use Vec<Generic>?
1291 #[derive(Clone, Debug, Default)]
1292 crate struct Generics {
1293 crate params: Vec<GenericParamDef>,
1294 crate where_predicates: Vec<WherePredicate>,
1297 #[derive(Clone, Debug)]
1298 crate struct Function {
1300 crate generics: Generics,
1301 crate header: hir::FnHeader,
1304 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
1305 crate struct FnDecl {
1306 crate inputs: Arguments,
1307 crate output: FnRetTy,
1308 crate c_variadic: bool,
1312 crate fn self_type(&self) -> Option<SelfTy> {
1313 self.inputs.values.get(0).and_then(|v| v.to_self())
1316 /// Returns the sugared return type for an async function.
1318 /// For example, if the return type is `impl std::future::Future<Output = i32>`, this function
1319 /// will return `i32`.
1323 /// This function will panic if the return type does not match the expected sugaring for async
1325 crate fn sugared_async_return_type(&self) -> FnRetTy {
1326 match &self.output {
1327 FnRetTy::Return(Type::ImplTrait(bounds)) => match &bounds[0] {
1328 GenericBound::TraitBound(PolyTrait { trait_, .. }, ..) => {
1329 let bindings = trait_.bindings().unwrap();
1330 FnRetTy::Return(bindings[0].ty().clone())
1332 _ => panic!("unexpected desugaring of async function"),
1334 _ => panic!("unexpected desugaring of async function"),
1339 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
1340 crate struct Arguments {
1341 crate values: Vec<Argument>,
1344 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
1345 crate struct Argument {
1350 #[derive(Clone, PartialEq, Debug)]
1353 SelfBorrowed(Option<Lifetime>, Mutability),
1358 crate fn to_self(&self) -> Option<SelfTy> {
1359 if self.name != kw::SelfLower {
1362 if self.type_.is_self_type() {
1363 return Some(SelfValue);
1366 BorrowedRef { ref lifetime, mutability, ref type_ } if type_.is_self_type() => {
1367 Some(SelfBorrowed(lifetime.clone(), mutability))
1369 _ => Some(SelfExplicit(self.type_.clone())),
1374 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
1375 crate enum FnRetTy {
1380 impl GetDefId for FnRetTy {
1381 fn def_id(&self) -> Option<DefId> {
1383 Return(ref ty) => ty.def_id(),
1384 DefaultReturn => None,
1388 fn def_id_full(&self, cache: &Cache) -> Option<DefId> {
1390 Return(ref ty) => ty.def_id_full(cache),
1391 DefaultReturn => None,
1396 #[derive(Clone, Debug)]
1397 crate struct Trait {
1398 crate unsafety: hir::Unsafety,
1399 crate items: Vec<Item>,
1400 crate generics: Generics,
1401 crate bounds: Vec<GenericBound>,
1402 crate is_auto: bool,
1405 #[derive(Clone, Debug)]
1406 crate struct TraitAlias {
1407 crate generics: Generics,
1408 crate bounds: Vec<GenericBound>,
1411 /// A trait reference, which may have higher ranked lifetimes.
1412 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
1413 crate struct PolyTrait {
1415 crate generic_params: Vec<GenericParamDef>,
1418 /// A representation of a type suitable for hyperlinking purposes. Ideally, one can get the original
1419 /// type out of the AST/`TyCtxt` given one of these, if more information is needed. Most
1420 /// importantly, it does not preserve mutability or boxes.
1421 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
1423 /// Structs/enums/traits (most that would be an `hir::TyKind::Path`).
1427 /// `true` if is a `T::Name` path for associated types.
1430 /// `dyn for<'a> Trait<'a> + Send + 'static`
1431 DynTrait(Vec<PolyTrait>, Option<Lifetime>),
1432 /// For parameterized types, so the consumer of the JSON don't go
1433 /// looking for types which don't exist anywhere.
1435 /// Primitives are the fixed-size numeric types (plus int/usize/float), char,
1436 /// arrays, slices, and tuples.
1437 Primitive(PrimitiveType),
1438 /// `extern "ABI" fn`
1439 BareFunction(Box<BareFunctionDecl>),
1442 /// The `String` field is about the size or the constant representing the array's length.
1443 Array(Box<Type>, String),
1445 RawPointer(Mutability, Box<Type>),
1447 lifetime: Option<Lifetime>,
1448 mutability: Mutability,
1452 // `<Type as Trait>::Name`
1455 self_type: Box<Type>,
1456 self_def_id: Option<DefId>,
1463 // `impl TraitA + TraitB + ...`
1464 ImplTrait(Vec<GenericBound>),
1467 #[derive(Clone, PartialEq, Eq, Hash, Copy, Debug)]
1468 /// N.B. this has to be different from `hir::PrimTy` because it also includes types that aren't
1469 /// paths, like `Unit`.
1470 crate enum PrimitiveType {
1498 crate trait GetDefId {
1499 /// Use this method to get the [`DefId`] of a [`clean`] AST node.
1500 /// This will return [`None`] when called on a primitive [`clean::Type`].
1501 /// Use [`Self::def_id_full`] if you want to include primitives.
1503 /// [`clean`]: crate::clean
1504 /// [`clean::Type`]: crate::clean::Type
1505 // FIXME: get rid of this function and always use `def_id_full`
1506 fn def_id(&self) -> Option<DefId>;
1508 /// Use this method to get the [DefId] of a [clean] AST node, including [PrimitiveType]s.
1510 /// See [`Self::def_id`] for more.
1512 /// [clean]: crate::clean
1513 fn def_id_full(&self, cache: &Cache) -> Option<DefId>;
1516 impl<T: GetDefId> GetDefId for Option<T> {
1517 fn def_id(&self) -> Option<DefId> {
1518 self.as_ref().and_then(|d| d.def_id())
1521 fn def_id_full(&self, cache: &Cache) -> Option<DefId> {
1522 self.as_ref().and_then(|d| d.def_id_full(cache))
1527 crate fn primitive_type(&self) -> Option<PrimitiveType> {
1529 Primitive(p) | BorrowedRef { type_: box Primitive(p), .. } => Some(p),
1530 Slice(..) | BorrowedRef { type_: box Slice(..), .. } => Some(PrimitiveType::Slice),
1531 Array(..) | BorrowedRef { type_: box Array(..), .. } => Some(PrimitiveType::Array),
1534 Some(PrimitiveType::Unit)
1536 Some(PrimitiveType::Tuple)
1539 RawPointer(..) => Some(PrimitiveType::RawPointer),
1540 BareFunction(..) => Some(PrimitiveType::Fn),
1541 Never => Some(PrimitiveType::Never),
1546 crate fn is_generic(&self) -> bool {
1548 ResolvedPath { is_generic, .. } => is_generic,
1553 crate fn is_self_type(&self) -> bool {
1555 Generic(name) => name == kw::SelfUpper,
1560 crate fn generics(&self) -> Option<Vec<&Type>> {
1562 ResolvedPath { ref path, .. } => path.segments.last().and_then(|seg| {
1563 if let GenericArgs::AngleBracketed { ref args, .. } = seg.args {
1566 .filter_map(|arg| match arg {
1567 GenericArg::Type(ty) => Some(ty),
1580 crate fn bindings(&self) -> Option<&[TypeBinding]> {
1582 ResolvedPath { ref path, .. } => path.segments.last().and_then(|seg| {
1583 if let GenericArgs::AngleBracketed { ref bindings, .. } = seg.args {
1593 crate fn is_full_generic(&self) -> bool {
1594 matches!(self, Type::Generic(_))
1597 crate fn is_primitive(&self) -> bool {
1598 self.primitive_type().is_some()
1601 crate fn projection(&self) -> Option<(&Type, DefId, Symbol)> {
1602 let (self_, trait_, name) = match self {
1603 QPath { self_type, trait_, name, .. } => (self_type, trait_, name),
1606 let trait_did = match **trait_ {
1607 ResolvedPath { did, .. } => did,
1610 Some((&self_, trait_did, *name))
1615 fn inner_def_id(&self, cache: Option<&Cache>) -> Option<DefId> {
1616 let t: PrimitiveType = match *self {
1617 ResolvedPath { did, .. } => return Some(did.into()),
1618 DynTrait(ref bounds, _) => return bounds[0].trait_.inner_def_id(cache),
1619 Primitive(p) => return cache.and_then(|c| c.primitive_locations.get(&p).cloned()),
1620 BorrowedRef { type_: box Generic(..), .. } => PrimitiveType::Reference,
1621 BorrowedRef { ref type_, .. } => return type_.inner_def_id(cache),
1626 PrimitiveType::Tuple
1629 BareFunction(..) => PrimitiveType::Fn,
1630 Never => PrimitiveType::Never,
1631 Slice(..) => PrimitiveType::Slice,
1632 Array(..) => PrimitiveType::Array,
1633 RawPointer(..) => PrimitiveType::RawPointer,
1634 QPath { ref self_type, .. } => return self_type.inner_def_id(cache),
1635 Generic(_) | Infer | ImplTrait(_) => return None,
1637 cache.and_then(|c| Primitive(t).def_id_full(c))
1641 impl GetDefId for Type {
1642 fn def_id(&self) -> Option<DefId> {
1643 self.inner_def_id(None)
1646 fn def_id_full(&self, cache: &Cache) -> Option<DefId> {
1647 self.inner_def_id(Some(cache))
1651 impl PrimitiveType {
1652 crate fn from_hir(prim: hir::PrimTy) -> PrimitiveType {
1653 use ast::{FloatTy, IntTy, UintTy};
1655 hir::PrimTy::Int(IntTy::Isize) => PrimitiveType::Isize,
1656 hir::PrimTy::Int(IntTy::I8) => PrimitiveType::I8,
1657 hir::PrimTy::Int(IntTy::I16) => PrimitiveType::I16,
1658 hir::PrimTy::Int(IntTy::I32) => PrimitiveType::I32,
1659 hir::PrimTy::Int(IntTy::I64) => PrimitiveType::I64,
1660 hir::PrimTy::Int(IntTy::I128) => PrimitiveType::I128,
1661 hir::PrimTy::Uint(UintTy::Usize) => PrimitiveType::Usize,
1662 hir::PrimTy::Uint(UintTy::U8) => PrimitiveType::U8,
1663 hir::PrimTy::Uint(UintTy::U16) => PrimitiveType::U16,
1664 hir::PrimTy::Uint(UintTy::U32) => PrimitiveType::U32,
1665 hir::PrimTy::Uint(UintTy::U64) => PrimitiveType::U64,
1666 hir::PrimTy::Uint(UintTy::U128) => PrimitiveType::U128,
1667 hir::PrimTy::Float(FloatTy::F32) => PrimitiveType::F32,
1668 hir::PrimTy::Float(FloatTy::F64) => PrimitiveType::F64,
1669 hir::PrimTy::Str => PrimitiveType::Str,
1670 hir::PrimTy::Bool => PrimitiveType::Bool,
1671 hir::PrimTy::Char => PrimitiveType::Char,
1675 crate fn from_symbol(s: Symbol) -> Option<PrimitiveType> {
1677 sym::isize => Some(PrimitiveType::Isize),
1678 sym::i8 => Some(PrimitiveType::I8),
1679 sym::i16 => Some(PrimitiveType::I16),
1680 sym::i32 => Some(PrimitiveType::I32),
1681 sym::i64 => Some(PrimitiveType::I64),
1682 sym::i128 => Some(PrimitiveType::I128),
1683 sym::usize => Some(PrimitiveType::Usize),
1684 sym::u8 => Some(PrimitiveType::U8),
1685 sym::u16 => Some(PrimitiveType::U16),
1686 sym::u32 => Some(PrimitiveType::U32),
1687 sym::u64 => Some(PrimitiveType::U64),
1688 sym::u128 => Some(PrimitiveType::U128),
1689 sym::bool => Some(PrimitiveType::Bool),
1690 sym::char => Some(PrimitiveType::Char),
1691 sym::str => Some(PrimitiveType::Str),
1692 sym::f32 => Some(PrimitiveType::F32),
1693 sym::f64 => Some(PrimitiveType::F64),
1694 sym::array => Some(PrimitiveType::Array),
1695 sym::slice => Some(PrimitiveType::Slice),
1696 sym::tuple => Some(PrimitiveType::Tuple),
1697 sym::unit => Some(PrimitiveType::Unit),
1698 sym::pointer => Some(PrimitiveType::RawPointer),
1699 sym::reference => Some(PrimitiveType::Reference),
1700 kw::Fn => Some(PrimitiveType::Fn),
1701 sym::never => Some(PrimitiveType::Never),
1706 crate fn impls(&self, tcx: TyCtxt<'_>) -> &'static ArrayVec<DefId, 4> {
1707 Self::all_impls(tcx).get(self).expect("missing impl for primitive type")
1710 crate fn all_impls(tcx: TyCtxt<'_>) -> &'static FxHashMap<PrimitiveType, ArrayVec<DefId, 4>> {
1711 static CELL: OnceCell<FxHashMap<PrimitiveType, ArrayVec<DefId, 4>>> = OnceCell::new();
1713 CELL.get_or_init(move || {
1714 use self::PrimitiveType::*;
1716 let single = |a: Option<DefId>| a.into_iter().collect();
1717 let both = |a: Option<DefId>, b: Option<DefId>| -> ArrayVec<_, 4> {
1718 a.into_iter().chain(b).collect()
1721 let lang_items = tcx.lang_items();
1723 Isize => single(lang_items.isize_impl()),
1724 I8 => single(lang_items.i8_impl()),
1725 I16 => single(lang_items.i16_impl()),
1726 I32 => single(lang_items.i32_impl()),
1727 I64 => single(lang_items.i64_impl()),
1728 I128 => single(lang_items.i128_impl()),
1729 Usize => single(lang_items.usize_impl()),
1730 U8 => single(lang_items.u8_impl()),
1731 U16 => single(lang_items.u16_impl()),
1732 U32 => single(lang_items.u32_impl()),
1733 U64 => single(lang_items.u64_impl()),
1734 U128 => single(lang_items.u128_impl()),
1735 F32 => both(lang_items.f32_impl(), lang_items.f32_runtime_impl()),
1736 F64 => both(lang_items.f64_impl(), lang_items.f64_runtime_impl()),
1737 Char => single(lang_items.char_impl()),
1738 Bool => single(lang_items.bool_impl()),
1739 Str => both(lang_items.str_impl(), lang_items.str_alloc_impl()),
1744 .chain(lang_items.slice_u8_impl())
1745 .chain(lang_items.slice_alloc_impl())
1746 .chain(lang_items.slice_u8_alloc_impl())
1749 Array => single(lang_items.array_impl()),
1750 Tuple => ArrayVec::new(),
1751 Unit => ArrayVec::new(),
1756 .chain(lang_items.mut_ptr_impl())
1757 .chain(lang_items.const_slice_ptr_impl())
1758 .chain(lang_items.mut_slice_ptr_impl())
1761 Reference => ArrayVec::new(),
1762 Fn => ArrayVec::new(),
1763 Never => ArrayVec::new(),
1768 crate fn as_sym(&self) -> Symbol {
1769 use PrimitiveType::*;
1771 Isize => sym::isize,
1777 Usize => sym::usize,
1788 Array => sym::array,
1789 Slice => sym::slice,
1790 Tuple => sym::tuple,
1792 RawPointer => sym::pointer,
1793 Reference => sym::reference,
1795 Never => sym::never,
1800 impl From<ast::IntTy> for PrimitiveType {
1801 fn from(int_ty: ast::IntTy) -> PrimitiveType {
1803 ast::IntTy::Isize => PrimitiveType::Isize,
1804 ast::IntTy::I8 => PrimitiveType::I8,
1805 ast::IntTy::I16 => PrimitiveType::I16,
1806 ast::IntTy::I32 => PrimitiveType::I32,
1807 ast::IntTy::I64 => PrimitiveType::I64,
1808 ast::IntTy::I128 => PrimitiveType::I128,
1813 impl From<ast::UintTy> for PrimitiveType {
1814 fn from(uint_ty: ast::UintTy) -> PrimitiveType {
1816 ast::UintTy::Usize => PrimitiveType::Usize,
1817 ast::UintTy::U8 => PrimitiveType::U8,
1818 ast::UintTy::U16 => PrimitiveType::U16,
1819 ast::UintTy::U32 => PrimitiveType::U32,
1820 ast::UintTy::U64 => PrimitiveType::U64,
1821 ast::UintTy::U128 => PrimitiveType::U128,
1826 impl From<ast::FloatTy> for PrimitiveType {
1827 fn from(float_ty: ast::FloatTy) -> PrimitiveType {
1829 ast::FloatTy::F32 => PrimitiveType::F32,
1830 ast::FloatTy::F64 => PrimitiveType::F64,
1835 impl From<ty::IntTy> for PrimitiveType {
1836 fn from(int_ty: ty::IntTy) -> PrimitiveType {
1838 ty::IntTy::Isize => PrimitiveType::Isize,
1839 ty::IntTy::I8 => PrimitiveType::I8,
1840 ty::IntTy::I16 => PrimitiveType::I16,
1841 ty::IntTy::I32 => PrimitiveType::I32,
1842 ty::IntTy::I64 => PrimitiveType::I64,
1843 ty::IntTy::I128 => PrimitiveType::I128,
1848 impl From<ty::UintTy> for PrimitiveType {
1849 fn from(uint_ty: ty::UintTy) -> PrimitiveType {
1851 ty::UintTy::Usize => PrimitiveType::Usize,
1852 ty::UintTy::U8 => PrimitiveType::U8,
1853 ty::UintTy::U16 => PrimitiveType::U16,
1854 ty::UintTy::U32 => PrimitiveType::U32,
1855 ty::UintTy::U64 => PrimitiveType::U64,
1856 ty::UintTy::U128 => PrimitiveType::U128,
1861 impl From<ty::FloatTy> for PrimitiveType {
1862 fn from(float_ty: ty::FloatTy) -> PrimitiveType {
1864 ty::FloatTy::F32 => PrimitiveType::F32,
1865 ty::FloatTy::F64 => PrimitiveType::F64,
1870 impl From<hir::PrimTy> for PrimitiveType {
1871 fn from(prim_ty: hir::PrimTy) -> PrimitiveType {
1873 hir::PrimTy::Int(int_ty) => int_ty.into(),
1874 hir::PrimTy::Uint(uint_ty) => uint_ty.into(),
1875 hir::PrimTy::Float(float_ty) => float_ty.into(),
1876 hir::PrimTy::Str => PrimitiveType::Str,
1877 hir::PrimTy::Bool => PrimitiveType::Bool,
1878 hir::PrimTy::Char => PrimitiveType::Char,
1883 #[derive(Copy, Clone, Debug)]
1884 crate enum Visibility {
1887 /// Visibility inherited from parent.
1889 /// For example, this is the visibility of private items and of enum variants.
1891 /// `pub(crate)`, `pub(super)`, or `pub(in path::to::somewhere)`
1896 crate fn is_public(&self) -> bool {
1897 matches!(self, Visibility::Public)
1901 #[derive(Clone, Debug)]
1902 crate struct Struct {
1903 crate struct_type: CtorKind,
1904 crate generics: Generics,
1905 crate fields: Vec<Item>,
1906 crate fields_stripped: bool,
1909 #[derive(Clone, Debug)]
1910 crate struct Union {
1911 crate generics: Generics,
1912 crate fields: Vec<Item>,
1913 crate fields_stripped: bool,
1916 /// This is a more limited form of the standard Struct, different in that
1917 /// it lacks the things most items have (name, id, parameterization). Found
1918 /// only as a variant in an enum.
1919 #[derive(Clone, Debug)]
1920 crate struct VariantStruct {
1921 crate struct_type: CtorKind,
1922 crate fields: Vec<Item>,
1923 crate fields_stripped: bool,
1926 #[derive(Clone, Debug)]
1928 crate variants: IndexVec<VariantIdx, Item>,
1929 crate generics: Generics,
1930 crate variants_stripped: bool,
1933 #[derive(Clone, Debug)]
1934 crate enum Variant {
1937 Struct(VariantStruct),
1940 /// Small wrapper around [`rustc_span::Span]` that adds helper methods
1941 /// and enforces calling [`rustc_span::Span::source_callsite()`].
1942 #[derive(Copy, Clone, Debug)]
1943 crate struct Span(rustc_span::Span);
1946 crate fn from_rustc_span(sp: rustc_span::Span) -> Self {
1947 // Get the macro invocation instead of the definition,
1948 // in case the span is result of a macro expansion.
1949 // (See rust-lang/rust#39726)
1950 Self(sp.source_callsite())
1953 crate fn inner(&self) -> rustc_span::Span {
1957 crate fn dummy() -> Self {
1958 Self(rustc_span::DUMMY_SP)
1961 crate fn is_dummy(&self) -> bool {
1965 crate fn filename(&self, sess: &Session) -> FileName {
1966 sess.source_map().span_to_filename(self.0)
1969 crate fn lo(&self, sess: &Session) -> Loc {
1970 sess.source_map().lookup_char_pos(self.0.lo())
1973 crate fn hi(&self, sess: &Session) -> Loc {
1974 sess.source_map().lookup_char_pos(self.0.hi())
1977 crate fn cnum(&self, sess: &Session) -> CrateNum {
1978 // FIXME: is there a time when the lo and hi crate would be different?
1979 self.lo(sess).file.cnum
1983 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
1987 crate segments: Vec<PathSegment>,
1991 crate fn last(&self) -> Symbol {
1992 self.segments.last().expect("segments were empty").name
1995 crate fn last_name(&self) -> SymbolStr {
1996 self.segments.last().expect("segments were empty").name.as_str()
1999 crate fn whole_name(&self) -> String {
2000 String::from(if self.global { "::" } else { "" })
2001 + &self.segments.iter().map(|s| s.name.to_string()).collect::<Vec<_>>().join("::")
2005 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
2006 crate enum GenericArg {
2013 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
2014 crate enum GenericArgs {
2015 AngleBracketed { args: Vec<GenericArg>, bindings: Vec<TypeBinding> },
2016 Parenthesized { inputs: Vec<Type>, output: Option<Type> },
2019 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
2020 crate struct PathSegment {
2022 crate args: GenericArgs,
2025 #[derive(Clone, Debug)]
2026 crate struct Typedef {
2028 crate generics: Generics,
2029 /// `type_` can come from either the HIR or from metadata. If it comes from HIR, it may be a type
2030 /// alias instead of the final type. This will always have the final type, regardless of whether
2031 /// `type_` came from HIR or from metadata.
2033 /// If `item_type.is_none()`, `type_` is guarenteed to come from metadata (and therefore hold the
2035 crate item_type: Option<Type>,
2038 impl GetDefId for Typedef {
2039 fn def_id(&self) -> Option<DefId> {
2043 fn def_id_full(&self, cache: &Cache) -> Option<DefId> {
2044 self.type_.def_id_full(cache)
2048 #[derive(Clone, Debug)]
2049 crate struct OpaqueTy {
2050 crate bounds: Vec<GenericBound>,
2051 crate generics: Generics,
2054 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
2055 crate struct BareFunctionDecl {
2056 crate unsafety: hir::Unsafety,
2057 crate generic_params: Vec<GenericParamDef>,
2062 #[derive(Clone, Debug)]
2063 crate struct Static {
2065 crate mutability: Mutability,
2066 crate expr: Option<BodyId>,
2069 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
2070 crate struct Constant {
2072 crate kind: ConstantKind,
2075 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
2076 crate enum ConstantKind {
2077 /// This is the wrapper around `ty::Const` for a non-local constant. Because it doesn't have a
2078 /// `BodyId`, we need to handle it on its own.
2080 /// Note that `ty::Const` includes generic parameters, and may not always be uniquely identified
2081 /// by a DefId. So this field must be different from `Extern`.
2082 TyConst { expr: String },
2083 /// A constant (expression) that's not an item or associated item. These are usually found
2084 /// nested inside types (e.g., array lengths) or expressions (e.g., repeat counts), and also
2085 /// used to define explicit discriminant values for enum variants.
2086 Anonymous { body: BodyId },
2087 /// A constant from a different crate.
2088 Extern { def_id: DefId },
2089 /// `const FOO: u32 = ...;`
2090 Local { def_id: DefId, body: BodyId },
2094 crate fn expr(&self, tcx: TyCtxt<'_>) -> String {
2096 ConstantKind::TyConst { ref expr } => expr.clone(),
2097 ConstantKind::Extern { def_id } => print_inlined_const(tcx, def_id),
2098 ConstantKind::Local { body, .. } | ConstantKind::Anonymous { body } => {
2099 print_const_expr(tcx, body)
2104 crate fn value(&self, tcx: TyCtxt<'_>) -> Option<String> {
2106 ConstantKind::TyConst { .. } | ConstantKind::Anonymous { .. } => None,
2107 ConstantKind::Extern { def_id } | ConstantKind::Local { def_id, .. } => {
2108 print_evaluated_const(tcx, def_id)
2113 crate fn is_literal(&self, tcx: TyCtxt<'_>) -> bool {
2115 ConstantKind::TyConst { .. } => false,
2116 ConstantKind::Extern { def_id } => def_id.as_local().map_or(false, |def_id| {
2117 is_literal_expr(tcx, tcx.hir().local_def_id_to_hir_id(def_id))
2119 ConstantKind::Local { body, .. } | ConstantKind::Anonymous { body } => {
2120 is_literal_expr(tcx, body.hir_id)
2126 #[derive(Clone, Debug)]
2129 crate unsafety: hir::Unsafety,
2130 crate generics: Generics,
2131 crate trait_: Option<Type>,
2133 crate items: Vec<Item>,
2134 crate negative_polarity: bool,
2135 crate synthetic: bool,
2136 crate blanket_impl: Option<Box<Type>>,
2140 crate fn provided_trait_methods(&self, tcx: TyCtxt<'_>) -> FxHashSet<Symbol> {
2143 .map(|did| tcx.provided_trait_methods(did).map(|meth| meth.ident.name).collect())
2144 .unwrap_or_default()
2148 #[derive(Clone, Debug)]
2149 crate struct Import {
2150 crate kind: ImportKind,
2151 crate source: ImportSource,
2152 crate should_be_displayed: bool,
2156 crate fn new_simple(name: Symbol, source: ImportSource, should_be_displayed: bool) -> Self {
2157 Self { kind: ImportKind::Simple(name), source, should_be_displayed }
2160 crate fn new_glob(source: ImportSource, should_be_displayed: bool) -> Self {
2161 Self { kind: ImportKind::Glob, source, should_be_displayed }
2165 #[derive(Clone, Debug)]
2166 crate enum ImportKind {
2167 // use source as str;
2173 #[derive(Clone, Debug)]
2174 crate struct ImportSource {
2176 crate did: Option<DefId>,
2179 #[derive(Clone, Debug)]
2180 crate struct Macro {
2181 crate source: String,
2182 crate imported_from: Option<Symbol>,
2185 #[derive(Clone, Debug)]
2186 crate struct ProcMacro {
2187 crate kind: MacroKind,
2188 crate helpers: Vec<Symbol>,
2191 /// An type binding on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or
2192 /// `A: Send + Sync` in `Foo<A: Send + Sync>`).
2193 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
2194 crate struct TypeBinding {
2196 crate kind: TypeBindingKind,
2199 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
2200 crate enum TypeBindingKind {
2201 Equality { ty: Type },
2202 Constraint { bounds: Vec<GenericBound> },
2206 crate fn ty(&self) -> &Type {
2208 TypeBindingKind::Equality { ref ty } => ty,
2209 _ => panic!("expected equality type binding for parenthesized generic args"),