]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/assoc.rs
Rollup merge of #106441 - mllken:abstract-socket-noref, r=joshtriplett
[rust.git] / compiler / rustc_middle / src / ty / assoc.rs
1 pub use self::AssocItemContainer::*;
2
3 use crate::ty::{self, DefIdTree};
4 use rustc_data_structures::sorted_map::SortedIndexMultiMap;
5 use rustc_hir as hir;
6 use rustc_hir::def::{DefKind, Namespace};
7 use rustc_hir::def_id::DefId;
8 use rustc_span::symbol::{Ident, Symbol};
9
10 use super::{TyCtxt, Visibility};
11
12 #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable, Hash, Encodable, Decodable)]
13 pub enum AssocItemContainer {
14     TraitContainer,
15     ImplContainer,
16 }
17
18 /// Information about an associated item
19 #[derive(Copy, Clone, Debug, PartialEq, HashStable, Eq, Hash, Encodable, Decodable)]
20 pub struct AssocItem {
21     pub def_id: DefId,
22     pub name: Symbol,
23     pub kind: AssocKind,
24     pub container: AssocItemContainer,
25
26     /// If this is an item in an impl of a trait then this is the `DefId` of
27     /// the associated item on the trait that this implements.
28     pub trait_item_def_id: Option<DefId>,
29
30     /// Whether this is a method with an explicit self
31     /// as its first parameter, allowing method calls.
32     pub fn_has_self_parameter: bool,
33 }
34
35 impl AssocItem {
36     pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident {
37         Ident::new(self.name, tcx.def_ident_span(self.def_id).unwrap())
38     }
39
40     pub fn defaultness(&self, tcx: TyCtxt<'_>) -> hir::Defaultness {
41         tcx.impl_defaultness(self.def_id)
42     }
43
44     #[inline]
45     pub fn visibility(&self, tcx: TyCtxt<'_>) -> Visibility<DefId> {
46         tcx.visibility(self.def_id)
47     }
48
49     #[inline]
50     pub fn container_id(&self, tcx: TyCtxt<'_>) -> DefId {
51         tcx.parent(self.def_id)
52     }
53
54     #[inline]
55     pub fn trait_container(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
56         match self.container {
57             AssocItemContainer::ImplContainer => None,
58             AssocItemContainer::TraitContainer => Some(tcx.parent(self.def_id)),
59         }
60     }
61
62     #[inline]
63     pub fn impl_container(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
64         match self.container {
65             AssocItemContainer::ImplContainer => Some(tcx.parent(self.def_id)),
66             AssocItemContainer::TraitContainer => None,
67         }
68     }
69
70     pub fn signature(&self, tcx: TyCtxt<'_>) -> String {
71         match self.kind {
72             ty::AssocKind::Fn => {
73                 // We skip the binder here because the binder would deanonymize all
74                 // late-bound regions, and we don't want method signatures to show up
75                 // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound
76                 // regions just fine, showing `fn(&MyType)`.
77                 tcx.fn_sig(self.def_id).skip_binder().to_string()
78             }
79             ty::AssocKind::Type => format!("type {};", self.name),
80             ty::AssocKind::Const => {
81                 format!("const {}: {:?};", self.name, tcx.type_of(self.def_id))
82             }
83         }
84     }
85 }
86
87 #[derive(Copy, Clone, PartialEq, Debug, HashStable, Eq, Hash, Encodable, Decodable)]
88 pub enum AssocKind {
89     Const,
90     Fn,
91     Type,
92 }
93
94 impl AssocKind {
95     pub fn namespace(&self) -> Namespace {
96         match *self {
97             ty::AssocKind::Type => Namespace::TypeNS,
98             ty::AssocKind::Const | ty::AssocKind::Fn => Namespace::ValueNS,
99         }
100     }
101
102     pub fn as_def_kind(&self) -> DefKind {
103         match self {
104             AssocKind::Const => DefKind::AssocConst,
105             AssocKind::Fn => DefKind::AssocFn,
106             AssocKind::Type => DefKind::AssocTy,
107         }
108     }
109 }
110
111 impl std::fmt::Display for AssocKind {
112     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
113         match self {
114             AssocKind::Fn => write!(f, "method"),
115             AssocKind::Const => write!(f, "associated const"),
116             AssocKind::Type => write!(f, "associated type"),
117         }
118     }
119 }
120
121 /// A list of `ty::AssocItem`s in definition order that allows for efficient lookup by name.
122 ///
123 /// When doing lookup by name, we try to postpone hygienic comparison for as long as possible since
124 /// it is relatively expensive. Instead, items are indexed by `Symbol` and hygienic comparison is
125 /// done only on items with the same name.
126 #[derive(Debug, Clone, PartialEq, HashStable)]
127 pub struct AssocItems<'tcx> {
128     pub(super) items: SortedIndexMultiMap<u32, Symbol, &'tcx ty::AssocItem>,
129 }
130
131 impl<'tcx> AssocItems<'tcx> {
132     /// Constructs an `AssociatedItems` map from a series of `ty::AssocItem`s in definition order.
133     pub fn new(items_in_def_order: impl IntoIterator<Item = &'tcx ty::AssocItem>) -> Self {
134         let items = items_in_def_order.into_iter().map(|item| (item.name, item)).collect();
135         AssocItems { items }
136     }
137
138     /// Returns a slice of associated items in the order they were defined.
139     ///
140     /// New code should avoid relying on definition order. If you need a particular associated item
141     /// for a known trait, make that trait a lang item instead of indexing this array.
142     pub fn in_definition_order(&self) -> impl '_ + Iterator<Item = &ty::AssocItem> {
143         self.items.iter().map(|(_, v)| *v)
144     }
145
146     pub fn len(&self) -> usize {
147         self.items.len()
148     }
149
150     /// Returns an iterator over all associated items with the given name, ignoring hygiene.
151     pub fn filter_by_name_unhygienic(
152         &self,
153         name: Symbol,
154     ) -> impl '_ + Iterator<Item = &ty::AssocItem> {
155         self.items.get_by_key(name).copied()
156     }
157
158     /// Returns the associated item with the given name and `AssocKind`, if one exists.
159     pub fn find_by_name_and_kind(
160         &self,
161         tcx: TyCtxt<'_>,
162         ident: Ident,
163         kind: AssocKind,
164         parent_def_id: DefId,
165     ) -> Option<&ty::AssocItem> {
166         self.filter_by_name_unhygienic(ident.name)
167             .filter(|item| item.kind == kind)
168             .find(|item| tcx.hygienic_eq(ident, item.ident(tcx), parent_def_id))
169     }
170
171     /// Returns the associated item with the given name and any of `AssocKind`, if one exists.
172     pub fn find_by_name_and_kinds(
173         &self,
174         tcx: TyCtxt<'_>,
175         ident: Ident,
176         // Sorted in order of what kinds to look at
177         kinds: &[AssocKind],
178         parent_def_id: DefId,
179     ) -> Option<&ty::AssocItem> {
180         kinds.iter().find_map(|kind| self.find_by_name_and_kind(tcx, ident, *kind, parent_def_id))
181     }
182
183     /// Returns the associated item with the given name in the given `Namespace`, if one exists.
184     pub fn find_by_name_and_namespace(
185         &self,
186         tcx: TyCtxt<'_>,
187         ident: Ident,
188         ns: Namespace,
189         parent_def_id: DefId,
190     ) -> Option<&ty::AssocItem> {
191         self.filter_by_name_unhygienic(ident.name)
192             .filter(|item| item.kind.namespace() == ns)
193             .find(|item| tcx.hygienic_eq(ident, item.ident(tcx), parent_def_id))
194     }
195 }