]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/data.rs
Record attribute calls on assoc items in TraitData and ImplData
[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, AstId, ExpandResult, InFile, MacroCallId};
6 use syntax::ast;
7
8 use crate::{
9     attr::Attrs,
10     body::{Expander, Mark},
11     db::DefDatabase,
12     intern::Interned,
13     item_tree::{self, AssocItem, FnFlags, ItemTreeId, ModItem, Param},
14     nameres::attr_resolution::ResolvedAttr,
15     type_ref::{TraitRef, TypeBound, TypeRef},
16     visibility::RawVisibility,
17     AssocItemId, AstIdWithPath, ConstId, ConstLoc, FunctionId, FunctionLoc, HasModule, ImplId,
18     Intern, ItemContainerId, Lookup, ModuleId, StaticId, TraitId, TypeAliasId, TypeAliasLoc,
19 };
20
21 #[derive(Debug, Clone, PartialEq, Eq)]
22 pub struct FunctionData {
23     pub name: Name,
24     pub params: Vec<(Option<Name>, Interned<TypeRef>)>,
25     pub ret_type: Interned<TypeRef>,
26     pub async_ret_type: Option<Interned<TypeRef>>,
27     pub attrs: Attrs,
28     pub visibility: RawVisibility,
29     pub abi: Option<Interned<str>>,
30     pub legacy_const_generics_indices: Vec<u32>,
31     flags: FnFlags,
32 }
33
34 impl FunctionData {
35     pub(crate) fn fn_data_query(db: &dyn DefDatabase, func: FunctionId) -> Arc<FunctionData> {
36         let loc = func.lookup(db);
37         let krate = loc.container.module(db).krate;
38         let crate_graph = db.crate_graph();
39         let cfg_options = &crate_graph[krate].cfg_options;
40         let item_tree = loc.id.item_tree(db);
41         let func = &item_tree[loc.id.value];
42
43         let enabled_params = func
44             .params
45             .clone()
46             .filter(|&param| item_tree.attrs(db, krate, param.into()).is_cfg_enabled(cfg_options));
47
48         // If last cfg-enabled param is a `...` param, it's a varargs function.
49         let is_varargs = enabled_params
50             .clone()
51             .next_back()
52             .map_or(false, |param| matches!(item_tree[param], Param::Varargs));
53
54         let mut flags = func.flags;
55         if is_varargs {
56             flags.bits |= FnFlags::IS_VARARGS;
57         }
58
59         if matches!(loc.container, ItemContainerId::ExternBlockId(_)) {
60             flags.bits |= FnFlags::IS_IN_EXTERN_BLOCK;
61         }
62
63         let legacy_const_generics_indices = item_tree
64             .attrs(db, krate, ModItem::from(loc.id.value).into())
65             .by_key("rustc_legacy_const_generics")
66             .tt_values()
67             .next()
68             .map(|arg| parse_rustc_legacy_const_generics(arg))
69             .unwrap_or_default();
70
71         Arc::new(FunctionData {
72             name: func.name.clone(),
73             params: enabled_params
74                 .clone()
75                 .filter_map(|id| match &item_tree[id] {
76                     Param::Normal(name, ty) => Some((name.clone(), ty.clone())),
77                     Param::Varargs => None,
78                 })
79                 .collect(),
80             ret_type: func.ret_type.clone(),
81             async_ret_type: func.async_ret_type.clone(),
82             attrs: item_tree.attrs(db, krate, ModItem::from(loc.id.value).into()),
83             visibility: item_tree[func.visibility].clone(),
84             abi: func.abi.clone(),
85             legacy_const_generics_indices,
86             flags,
87         })
88     }
89
90     pub fn has_body(&self) -> bool {
91         self.flags.bits & FnFlags::HAS_BODY != 0
92     }
93
94     /// True if the first param is `self`. This is relevant to decide whether this
95     /// can be called as a method.
96     pub fn has_self_param(&self) -> bool {
97         self.flags.bits & FnFlags::HAS_SELF_PARAM != 0
98     }
99
100     pub fn is_default(&self) -> bool {
101         self.flags.bits & FnFlags::IS_DEFAULT != 0
102     }
103
104     pub fn is_const(&self) -> bool {
105         self.flags.bits & FnFlags::IS_CONST != 0
106     }
107
108     pub fn is_async(&self) -> bool {
109         self.flags.bits & FnFlags::IS_ASYNC != 0
110     }
111
112     pub fn is_unsafe(&self) -> bool {
113         self.flags.bits & FnFlags::IS_UNSAFE != 0
114     }
115
116     pub fn is_in_extern_block(&self) -> bool {
117         self.flags.bits & FnFlags::IS_IN_EXTERN_BLOCK != 0
118     }
119
120     pub fn is_varargs(&self) -> bool {
121         self.flags.bits & FnFlags::IS_VARARGS != 0
122     }
123 }
124
125 fn parse_rustc_legacy_const_generics(tt: &tt::Subtree) -> Vec<u32> {
126     let mut indices = Vec::new();
127     for args in tt.token_trees.chunks(2) {
128         match &args[0] {
129             tt::TokenTree::Leaf(tt::Leaf::Literal(lit)) => match lit.text.parse() {
130                 Ok(index) => indices.push(index),
131                 Err(_) => break,
132             },
133             _ => break,
134         }
135
136         if let Some(comma) = args.get(1) {
137             match comma {
138                 tt::TokenTree::Leaf(tt::Leaf::Punct(punct)) if punct.char == ',' => {}
139                 _ => break,
140             }
141         }
142     }
143
144     indices
145 }
146
147 #[derive(Debug, Clone, PartialEq, Eq)]
148 pub struct TypeAliasData {
149     pub name: Name,
150     pub type_ref: Option<Interned<TypeRef>>,
151     pub visibility: RawVisibility,
152     pub is_extern: bool,
153     /// Bounds restricting the type alias itself (eg. `type Ty: Bound;` in a trait or impl).
154     pub bounds: Vec<Interned<TypeBound>>,
155 }
156
157 impl TypeAliasData {
158     pub(crate) fn type_alias_data_query(
159         db: &dyn DefDatabase,
160         typ: TypeAliasId,
161     ) -> Arc<TypeAliasData> {
162         let loc = typ.lookup(db);
163         let item_tree = loc.id.item_tree(db);
164         let typ = &item_tree[loc.id.value];
165
166         Arc::new(TypeAliasData {
167             name: typ.name.clone(),
168             type_ref: typ.type_ref.clone(),
169             visibility: item_tree[typ.visibility].clone(),
170             is_extern: matches!(loc.container, ItemContainerId::ExternBlockId(_)),
171             bounds: typ.bounds.to_vec(),
172         })
173     }
174 }
175
176 #[derive(Debug, Clone, PartialEq, Eq)]
177 pub struct TraitData {
178     pub name: Name,
179     pub items: Vec<(Name, AssocItemId)>,
180     pub is_auto: bool,
181     pub is_unsafe: bool,
182     pub visibility: RawVisibility,
183     /// Whether the trait has `#[rust_skip_array_during_method_dispatch]`. `hir_ty` will ignore
184     /// method calls to this trait's methods when the receiver is an array and the crate edition is
185     /// 2015 or 2018.
186     pub skip_array_during_method_dispatch: bool,
187     pub attribute_calls: Option<Box<Vec<(AstId<ast::Item>, MacroCallId)>>>,
188 }
189
190 impl TraitData {
191     pub(crate) fn trait_data_query(db: &dyn DefDatabase, tr: TraitId) -> Arc<TraitData> {
192         let tr_loc = tr.lookup(db);
193         let item_tree = tr_loc.id.item_tree(db);
194         let tr_def = &item_tree[tr_loc.id.value];
195         let _cx = stdx::panic_context::enter(format!(
196             "trait_data_query({:?} -> {:?} -> {:?})",
197             tr, tr_loc, tr_def
198         ));
199         let name = tr_def.name.clone();
200         let is_auto = tr_def.is_auto;
201         let is_unsafe = tr_def.is_unsafe;
202         let module_id = tr_loc.container;
203         let container = ItemContainerId::TraitId(tr);
204         let visibility = item_tree[tr_def.visibility].clone();
205         let mut expander = Expander::new(db, tr_loc.id.file_id(), module_id);
206         let skip_array_during_method_dispatch = item_tree
207             .attrs(db, tr_loc.container.krate(), ModItem::from(tr_loc.id.value).into())
208             .by_key("rustc_skip_array_during_method_dispatch")
209             .exists();
210
211         let (attribute_calls, items) = collect_items(
212             db,
213             module_id,
214             &mut expander,
215             tr_def.items.iter().copied(),
216             tr_loc.id.tree_id(),
217             container,
218             100,
219         );
220         let attribute_calls =
221             if attribute_calls.is_empty() { None } else { Some(Box::new(attribute_calls)) };
222
223         Arc::new(TraitData {
224             name,
225             items,
226             is_auto,
227             is_unsafe,
228             visibility,
229             skip_array_during_method_dispatch,
230             attribute_calls,
231         })
232     }
233
234     pub fn associated_types(&self) -> impl Iterator<Item = TypeAliasId> + '_ {
235         self.items.iter().filter_map(|(_name, item)| match item {
236             AssocItemId::TypeAliasId(t) => Some(*t),
237             _ => None,
238         })
239     }
240
241     pub fn associated_type_by_name(&self, name: &Name) -> Option<TypeAliasId> {
242         self.items.iter().find_map(|(item_name, item)| match item {
243             AssocItemId::TypeAliasId(t) if item_name == name => Some(*t),
244             _ => None,
245         })
246     }
247
248     pub fn method_by_name(&self, name: &Name) -> Option<FunctionId> {
249         self.items.iter().find_map(|(item_name, item)| match item {
250             AssocItemId::FunctionId(t) if item_name == name => Some(*t),
251             _ => None,
252         })
253     }
254
255     pub fn attribute_calls(&self) -> impl Iterator<Item = (AstId<ast::Item>, MacroCallId)> + '_ {
256         self.attribute_calls.iter().flat_map(|it| it.iter()).copied()
257     }
258 }
259
260 #[derive(Debug, Clone, PartialEq, Eq)]
261 pub struct ImplData {
262     pub target_trait: Option<Interned<TraitRef>>,
263     pub self_ty: Interned<TypeRef>,
264     pub items: Vec<AssocItemId>,
265     pub is_negative: bool,
266     pub attribute_calls: Option<Box<Vec<(AstId<ast::Item>, MacroCallId)>>>,
267 }
268
269 impl ImplData {
270     pub(crate) fn impl_data_query(db: &dyn DefDatabase, id: ImplId) -> Arc<ImplData> {
271         let _p = profile::span("impl_data_query");
272         let impl_loc = id.lookup(db);
273
274         let item_tree = impl_loc.id.item_tree(db);
275         let impl_def = &item_tree[impl_loc.id.value];
276         let target_trait = impl_def.target_trait.clone();
277         let self_ty = impl_def.self_ty.clone();
278         let is_negative = impl_def.is_negative;
279         let module_id = impl_loc.container;
280         let container = ItemContainerId::ImplId(id);
281         let mut expander = Expander::new(db, impl_loc.id.file_id(), module_id);
282
283         let (attribute_calls, items) = collect_items(
284             db,
285             module_id,
286             &mut expander,
287             impl_def.items.iter().copied(),
288             impl_loc.id.tree_id(),
289             container,
290             100,
291         );
292         let items = items.into_iter().map(|(_, item)| item).collect();
293         let attribute_calls =
294             if attribute_calls.is_empty() { None } else { Some(Box::new(attribute_calls)) };
295
296         Arc::new(ImplData { target_trait, self_ty, items, is_negative, attribute_calls })
297     }
298
299     pub fn attribute_calls(&self) -> impl Iterator<Item = (AstId<ast::Item>, MacroCallId)> + '_ {
300         self.attribute_calls.iter().flat_map(|it| it.iter()).copied()
301     }
302 }
303
304 #[derive(Debug, Clone, PartialEq, Eq)]
305 pub struct ConstData {
306     /// `None` for `const _: () = ();`
307     pub name: Option<Name>,
308     pub type_ref: Interned<TypeRef>,
309     pub visibility: RawVisibility,
310 }
311
312 impl ConstData {
313     pub(crate) fn const_data_query(db: &dyn DefDatabase, konst: ConstId) -> Arc<ConstData> {
314         let loc = konst.lookup(db);
315         let item_tree = loc.id.item_tree(db);
316         let konst = &item_tree[loc.id.value];
317
318         Arc::new(ConstData {
319             name: konst.name.clone(),
320             type_ref: konst.type_ref.clone(),
321             visibility: item_tree[konst.visibility].clone(),
322         })
323     }
324 }
325
326 #[derive(Debug, Clone, PartialEq, Eq)]
327 pub struct StaticData {
328     pub name: Name,
329     pub type_ref: Interned<TypeRef>,
330     pub visibility: RawVisibility,
331     pub mutable: bool,
332     pub is_extern: bool,
333 }
334
335 impl StaticData {
336     pub(crate) fn static_data_query(db: &dyn DefDatabase, konst: StaticId) -> Arc<StaticData> {
337         let loc = konst.lookup(db);
338         let item_tree = loc.id.item_tree(db);
339         let statik = &item_tree[loc.id.value];
340
341         Arc::new(StaticData {
342             name: statik.name.clone(),
343             type_ref: statik.type_ref.clone(),
344             visibility: item_tree[statik.visibility].clone(),
345             mutable: statik.mutable,
346             is_extern: matches!(loc.container, ItemContainerId::ExternBlockId(_)),
347         })
348     }
349 }
350
351 fn collect_items(
352     db: &dyn DefDatabase,
353     module: ModuleId,
354     expander: &mut Expander,
355     assoc_items: impl Iterator<Item = AssocItem>,
356     tree_id: item_tree::TreeId,
357     container: ItemContainerId,
358     limit: usize,
359 ) -> (Vec<(AstId<ast::Item>, MacroCallId)>, Vec<(Name, AssocItemId)>) {
360     if limit == 0 {
361         return Default::default();
362     }
363
364     let item_tree = tree_id.item_tree(db);
365     let crate_graph = db.crate_graph();
366     let cfg_options = &crate_graph[module.krate].cfg_options;
367     let def_map = module.def_map(db);
368
369     let mut items = Vec::new();
370     let mut attribute_calls = Vec::new();
371
372     'items: for item in assoc_items {
373         let attrs = item_tree.attrs(db, module.krate, ModItem::from(item).into());
374         if !attrs.is_cfg_enabled(cfg_options) {
375             continue;
376         }
377         for attr in &*attrs {
378             let ast_id = AstId::new(expander.current_file_id(), item.ast_id(&item_tree).upcast());
379             let ast_id_with_path = AstIdWithPath { path: (*attr.path).clone(), ast_id };
380             if let Ok(ResolvedAttr::Macro(call_id)) =
381                 def_map.resolve_attr_macro(db, module.local_id, ast_id_with_path, attr)
382             {
383                 attribute_calls.push((ast_id, call_id));
384                 let res = expander.enter_expand_id(db, call_id);
385                 let (mac_attrs, mac_items) =
386                     collect_macro_items(db, module, expander, container, limit, res);
387                 items.extend(mac_items);
388                 attribute_calls.extend(mac_attrs);
389                 continue 'items;
390             }
391         }
392
393         match item {
394             AssocItem::Function(id) => {
395                 let item = &item_tree[id];
396                 let def = FunctionLoc { container, id: ItemTreeId::new(tree_id, id) }.intern(db);
397                 items.push((item.name.clone(), def.into()));
398             }
399             AssocItem::Const(id) => {
400                 let item = &item_tree[id];
401                 let name = match item.name.clone() {
402                     Some(name) => name,
403                     None => continue,
404                 };
405                 let def = ConstLoc { container, id: ItemTreeId::new(tree_id, id) }.intern(db);
406                 items.push((name, def.into()));
407             }
408             AssocItem::TypeAlias(id) => {
409                 let item = &item_tree[id];
410                 let def = TypeAliasLoc { container, id: ItemTreeId::new(tree_id, id) }.intern(db);
411                 items.push((item.name.clone(), def.into()));
412             }
413             AssocItem::MacroCall(call) => {
414                 let call = &item_tree[call];
415                 let ast_id_map = db.ast_id_map(tree_id.file_id());
416                 let root = db.parse_or_expand(tree_id.file_id()).unwrap();
417                 let call = ast_id_map.get(call.ast_id).to_node(&root);
418                 let _cx = stdx::panic_context::enter(format!("collect_items MacroCall: {}", call));
419                 let res = expander.enter_expand(db, call);
420
421                 if let Ok(res) = res {
422                     let (mac_attrs, mac_items) =
423                         collect_macro_items(db, module, expander, container, limit, res);
424                     items.extend(mac_items);
425                     attribute_calls.extend(mac_attrs);
426                 }
427             }
428         }
429     }
430
431     (attribute_calls, items)
432 }
433
434 fn collect_macro_items(
435     db: &dyn DefDatabase,
436     module: ModuleId,
437     expander: &mut Expander,
438     container: ItemContainerId,
439     limit: usize,
440     res: ExpandResult<Option<(Mark, ast::MacroItems)>>,
441 ) -> (Vec<(AstId<ast::Item>, MacroCallId)>, Vec<(Name, AssocItemId)>) {
442     if let Some((mark, mac)) = res.value {
443         let src: InFile<ast::MacroItems> = expander.to_source(mac);
444         let tree_id = item_tree::TreeId::new(src.file_id, None);
445         let item_tree = tree_id.item_tree(db);
446         let iter = item_tree.top_level_items().iter().filter_map(ModItem::as_assoc_item);
447         let items = collect_items(db, module, expander, iter, tree_id, container, limit - 1);
448
449         expander.exit(db, mark);
450
451         return items;
452     }
453
454     Default::default()
455 }