]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/data.rs
Merge #8042
[rust.git] / crates / hir_def / src / data.rs
1 //! Contains basic data about various HIR declarations.
2
3 use std::sync::Arc;
4
5 use hir_expand::{name::Name, InFile};
6 use syntax::ast;
7
8 use crate::{
9     attr::Attrs,
10     body::Expander,
11     db::DefDatabase,
12     item_tree::{AssocItem, FunctionQualifier, ItemTreeId, ModItem},
13     type_ref::{TypeBound, TypeRef},
14     visibility::RawVisibility,
15     AssocContainerId, AssocItemId, ConstId, ConstLoc, FunctionId, FunctionLoc, HasModule, ImplId,
16     Intern, Lookup, ModuleId, StaticId, TraitId, TypeAliasId, TypeAliasLoc,
17 };
18
19 #[derive(Debug, Clone, PartialEq, Eq)]
20 pub struct FunctionData {
21     pub name: Name,
22     pub params: Vec<TypeRef>,
23     pub ret_type: TypeRef,
24     pub attrs: Attrs,
25     /// True if the first param is `self`. This is relevant to decide whether this
26     /// can be called as a method.
27     pub has_self_param: bool,
28     pub has_body: bool,
29     pub qualifier: FunctionQualifier,
30     pub is_in_extern_block: bool,
31     pub is_varargs: bool,
32     pub visibility: RawVisibility,
33 }
34
35 impl FunctionData {
36     pub(crate) fn fn_data_query(db: &dyn DefDatabase, func: FunctionId) -> Arc<FunctionData> {
37         let loc = func.lookup(db);
38         let krate = loc.container.module(db).krate;
39         let item_tree = db.item_tree(loc.id.file_id);
40         let func = &item_tree[loc.id.value];
41
42         Arc::new(FunctionData {
43             name: func.name.clone(),
44             params: func.params.iter().map(|id| item_tree[*id].clone()).collect(),
45             ret_type: item_tree[func.ret_type].clone(),
46             attrs: item_tree.attrs(db, krate, ModItem::from(loc.id.value).into()),
47             has_self_param: func.has_self_param,
48             has_body: func.has_body,
49             qualifier: func.qualifier.clone(),
50             is_in_extern_block: func.is_in_extern_block,
51             is_varargs: func.is_varargs,
52             visibility: item_tree[func.visibility].clone(),
53         })
54     }
55 }
56
57 #[derive(Debug, Clone, PartialEq, Eq)]
58 pub struct TypeAliasData {
59     pub name: Name,
60     pub type_ref: Option<TypeRef>,
61     pub visibility: RawVisibility,
62     pub is_extern: bool,
63     /// Bounds restricting the type alias itself (eg. `type Ty: Bound;` in a trait or impl).
64     pub bounds: Vec<TypeBound>,
65 }
66
67 impl TypeAliasData {
68     pub(crate) fn type_alias_data_query(
69         db: &dyn DefDatabase,
70         typ: TypeAliasId,
71     ) -> Arc<TypeAliasData> {
72         let loc = typ.lookup(db);
73         let item_tree = db.item_tree(loc.id.file_id);
74         let typ = &item_tree[loc.id.value];
75
76         Arc::new(TypeAliasData {
77             name: typ.name.clone(),
78             type_ref: typ.type_ref.map(|id| item_tree[id].clone()),
79             visibility: item_tree[typ.visibility].clone(),
80             is_extern: typ.is_extern,
81             bounds: typ.bounds.to_vec(),
82         })
83     }
84 }
85
86 #[derive(Debug, Clone, PartialEq, Eq)]
87 pub struct TraitData {
88     pub name: Name,
89     pub items: Vec<(Name, AssocItemId)>,
90     pub is_auto: bool,
91     pub is_unsafe: bool,
92     pub visibility: RawVisibility,
93     pub bounds: Box<[TypeBound]>,
94 }
95
96 impl TraitData {
97     pub(crate) fn trait_data_query(db: &dyn DefDatabase, tr: TraitId) -> Arc<TraitData> {
98         let tr_loc = tr.lookup(db);
99         let item_tree = db.item_tree(tr_loc.id.file_id);
100         let tr_def = &item_tree[tr_loc.id.value];
101         let name = tr_def.name.clone();
102         let is_auto = tr_def.is_auto;
103         let is_unsafe = tr_def.is_unsafe;
104         let module_id = tr_loc.container;
105         let container = AssocContainerId::TraitId(tr);
106         let mut expander = Expander::new(db, tr_loc.id.file_id, module_id);
107         let visibility = item_tree[tr_def.visibility].clone();
108         let bounds = tr_def.bounds.clone();
109
110         let items = collect_items(
111             db,
112             module_id,
113             &mut expander,
114             tr_def.items.iter().copied(),
115             tr_loc.id.file_id,
116             container,
117             100,
118         );
119
120         Arc::new(TraitData { name, items, is_auto, is_unsafe, visibility, bounds })
121     }
122
123     pub fn associated_types(&self) -> impl Iterator<Item = TypeAliasId> + '_ {
124         self.items.iter().filter_map(|(_name, item)| match item {
125             AssocItemId::TypeAliasId(t) => Some(*t),
126             _ => None,
127         })
128     }
129
130     pub fn associated_type_by_name(&self, name: &Name) -> Option<TypeAliasId> {
131         self.items.iter().find_map(|(item_name, item)| match item {
132             AssocItemId::TypeAliasId(t) if item_name == name => Some(*t),
133             _ => None,
134         })
135     }
136 }
137
138 #[derive(Debug, Clone, PartialEq, Eq)]
139 pub struct ImplData {
140     pub target_trait: Option<TypeRef>,
141     pub target_type: TypeRef,
142     pub items: Vec<AssocItemId>,
143     pub is_negative: bool,
144 }
145
146 impl ImplData {
147     pub(crate) fn impl_data_query(db: &dyn DefDatabase, id: ImplId) -> Arc<ImplData> {
148         let _p = profile::span("impl_data_query");
149         let impl_loc = id.lookup(db);
150
151         let item_tree = db.item_tree(impl_loc.id.file_id);
152         let impl_def = &item_tree[impl_loc.id.value];
153         let target_trait = impl_def.target_trait.map(|id| item_tree[id].clone());
154         let target_type = item_tree[impl_def.target_type].clone();
155         let is_negative = impl_def.is_negative;
156         let module_id = impl_loc.container;
157         let container = AssocContainerId::ImplId(id);
158         let mut expander = Expander::new(db, impl_loc.id.file_id, module_id);
159
160         let items = collect_items(
161             db,
162             module_id,
163             &mut expander,
164             impl_def.items.iter().copied(),
165             impl_loc.id.file_id,
166             container,
167             100,
168         );
169         let items = items.into_iter().map(|(_, item)| item).collect();
170
171         Arc::new(ImplData { target_trait, target_type, items, is_negative })
172     }
173 }
174
175 #[derive(Debug, Clone, PartialEq, Eq)]
176 pub struct ConstData {
177     /// const _: () = ();
178     pub name: Option<Name>,
179     pub type_ref: TypeRef,
180     pub visibility: RawVisibility,
181 }
182
183 impl ConstData {
184     pub(crate) fn const_data_query(db: &dyn DefDatabase, konst: ConstId) -> Arc<ConstData> {
185         let loc = konst.lookup(db);
186         let item_tree = db.item_tree(loc.id.file_id);
187         let konst = &item_tree[loc.id.value];
188
189         Arc::new(ConstData {
190             name: konst.name.clone(),
191             type_ref: item_tree[konst.type_ref].clone(),
192             visibility: item_tree[konst.visibility].clone(),
193         })
194     }
195 }
196
197 #[derive(Debug, Clone, PartialEq, Eq)]
198 pub struct StaticData {
199     pub name: Option<Name>,
200     pub type_ref: TypeRef,
201     pub visibility: RawVisibility,
202     pub mutable: bool,
203     pub is_extern: bool,
204 }
205
206 impl StaticData {
207     pub(crate) fn static_data_query(db: &dyn DefDatabase, konst: StaticId) -> Arc<StaticData> {
208         let node = konst.lookup(db);
209         let item_tree = db.item_tree(node.id.file_id);
210         let statik = &item_tree[node.id.value];
211
212         Arc::new(StaticData {
213             name: Some(statik.name.clone()),
214             type_ref: item_tree[statik.type_ref].clone(),
215             visibility: item_tree[statik.visibility].clone(),
216             mutable: statik.mutable,
217             is_extern: statik.is_extern,
218         })
219     }
220 }
221
222 fn collect_items(
223     db: &dyn DefDatabase,
224     module: ModuleId,
225     expander: &mut Expander,
226     assoc_items: impl Iterator<Item = AssocItem>,
227     file_id: crate::HirFileId,
228     container: AssocContainerId,
229     limit: usize,
230 ) -> Vec<(Name, AssocItemId)> {
231     if limit == 0 {
232         return Vec::new();
233     }
234
235     let item_tree = db.item_tree(file_id);
236     let cfg_options = db.crate_graph()[module.krate].cfg_options.clone();
237
238     let mut items = Vec::new();
239     for item in assoc_items {
240         match item {
241             AssocItem::Function(id) => {
242                 let item = &item_tree[id];
243                 let attrs = item_tree.attrs(db, module.krate, ModItem::from(id).into());
244                 if !attrs.is_cfg_enabled(&cfg_options) {
245                     continue;
246                 }
247                 let def = FunctionLoc { container, id: ItemTreeId::new(file_id, id) }.intern(db);
248                 items.push((item.name.clone(), def.into()));
249             }
250             // FIXME: cfg?
251             AssocItem::Const(id) => {
252                 let item = &item_tree[id];
253                 let name = match item.name.clone() {
254                     Some(name) => name,
255                     None => continue,
256                 };
257                 let def = ConstLoc { container, id: ItemTreeId::new(file_id, id) }.intern(db);
258                 items.push((name, def.into()));
259             }
260             AssocItem::TypeAlias(id) => {
261                 let item = &item_tree[id];
262                 let def = TypeAliasLoc { container, id: ItemTreeId::new(file_id, id) }.intern(db);
263                 items.push((item.name.clone(), def.into()));
264             }
265             AssocItem::MacroCall(call) => {
266                 let call = &item_tree[call];
267                 let ast_id_map = db.ast_id_map(file_id);
268                 let root = db.parse_or_expand(file_id).unwrap();
269                 let call = ast_id_map.get(call.ast_id).to_node(&root);
270
271                 if let Some((mark, mac)) = expander.enter_expand(db, call).value {
272                     let src: InFile<ast::MacroItems> = expander.to_source(mac);
273                     let item_tree = db.item_tree(src.file_id);
274                     let iter =
275                         item_tree.top_level_items().iter().filter_map(ModItem::as_assoc_item);
276                     items.extend(collect_items(
277                         db,
278                         module,
279                         expander,
280                         iter,
281                         src.file_id,
282                         container,
283                         limit - 1,
284                     ));
285
286                     expander.exit(db, mark);
287                 }
288             }
289         }
290     }
291
292     items
293 }