]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/data.rs
parameters.split_last()
[rust.git] / crates / hir_def / src / data.rs
1 //! Contains basic data about various HIR declarations.
2
3 use std::{mem, sync::Arc};
4
5 use hir_expand::{name::Name, AstId, ExpandResult, HirFileId, 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, TreeId},
14     nameres::{attr_resolution::ResolvedAttr, DefMap},
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     // box it as the vec is usually empty anyways
188     pub attribute_calls: Option<Box<Vec<(AstId<ast::Item>, MacroCallId)>>>,
189 }
190
191 impl TraitData {
192     pub(crate) fn trait_data_query(db: &dyn DefDatabase, tr: TraitId) -> Arc<TraitData> {
193         let tr_loc = tr.lookup(db);
194         let item_tree = tr_loc.id.item_tree(db);
195         let tr_def = &item_tree[tr_loc.id.value];
196         let _cx = stdx::panic_context::enter(format!(
197             "trait_data_query({:?} -> {:?} -> {:?})",
198             tr, tr_loc, tr_def
199         ));
200         let name = tr_def.name.clone();
201         let is_auto = tr_def.is_auto;
202         let is_unsafe = tr_def.is_unsafe;
203         let module_id = tr_loc.container;
204         let visibility = item_tree[tr_def.visibility].clone();
205         let skip_array_during_method_dispatch = item_tree
206             .attrs(db, tr_loc.container.krate(), ModItem::from(tr_loc.id.value).into())
207             .by_key("rustc_skip_array_during_method_dispatch")
208             .exists();
209
210         let mut collector = AssocItemCollector::new(
211             db,
212             module_id,
213             tr_loc.id.file_id(),
214             ItemContainerId::TraitId(tr),
215         );
216         collector.collect(tr_loc.id.tree_id(), &tr_def.items);
217
218         Arc::new(TraitData {
219             name,
220             attribute_calls: collector.take_attr_calls(),
221             items: collector.items,
222             is_auto,
223             is_unsafe,
224             visibility,
225             skip_array_during_method_dispatch,
226         })
227     }
228
229     pub fn associated_types(&self) -> impl Iterator<Item = TypeAliasId> + '_ {
230         self.items.iter().filter_map(|(_name, item)| match item {
231             AssocItemId::TypeAliasId(t) => Some(*t),
232             _ => None,
233         })
234     }
235
236     pub fn associated_type_by_name(&self, name: &Name) -> Option<TypeAliasId> {
237         self.items.iter().find_map(|(item_name, item)| match item {
238             AssocItemId::TypeAliasId(t) if item_name == name => Some(*t),
239             _ => None,
240         })
241     }
242
243     pub fn method_by_name(&self, name: &Name) -> Option<FunctionId> {
244         self.items.iter().find_map(|(item_name, item)| match item {
245             AssocItemId::FunctionId(t) if item_name == name => Some(*t),
246             _ => None,
247         })
248     }
249
250     pub fn attribute_calls(&self) -> impl Iterator<Item = (AstId<ast::Item>, MacroCallId)> + '_ {
251         self.attribute_calls.iter().flat_map(|it| it.iter()).copied()
252     }
253 }
254
255 #[derive(Debug, Clone, PartialEq, Eq)]
256 pub struct ImplData {
257     pub target_trait: Option<Interned<TraitRef>>,
258     pub self_ty: Interned<TypeRef>,
259     pub items: Vec<AssocItemId>,
260     pub is_negative: bool,
261     // box it as the vec is usually empty anyways
262     pub attribute_calls: Option<Box<Vec<(AstId<ast::Item>, MacroCallId)>>>,
263 }
264
265 impl ImplData {
266     pub(crate) fn impl_data_query(db: &dyn DefDatabase, id: ImplId) -> Arc<ImplData> {
267         let _p = profile::span("impl_data_query");
268         let impl_loc = id.lookup(db);
269
270         let item_tree = impl_loc.id.item_tree(db);
271         let impl_def = &item_tree[impl_loc.id.value];
272         let target_trait = impl_def.target_trait.clone();
273         let self_ty = impl_def.self_ty.clone();
274         let is_negative = impl_def.is_negative;
275         let module_id = impl_loc.container;
276
277         let mut collector = AssocItemCollector::new(
278             db,
279             module_id,
280             impl_loc.id.file_id(),
281             ItemContainerId::ImplId(id),
282         );
283         collector.collect(impl_loc.id.tree_id(), &impl_def.items);
284
285         let attribute_calls = collector.take_attr_calls();
286         let items = collector.items.into_iter().map(|(_, item)| item).collect();
287
288         Arc::new(ImplData { target_trait, self_ty, items, is_negative, attribute_calls })
289     }
290
291     pub fn attribute_calls(&self) -> impl Iterator<Item = (AstId<ast::Item>, MacroCallId)> + '_ {
292         self.attribute_calls.iter().flat_map(|it| it.iter()).copied()
293     }
294 }
295
296 #[derive(Debug, Clone, PartialEq, Eq)]
297 pub struct ConstData {
298     /// `None` for `const _: () = ();`
299     pub name: Option<Name>,
300     pub type_ref: Interned<TypeRef>,
301     pub visibility: RawVisibility,
302 }
303
304 impl ConstData {
305     pub(crate) fn const_data_query(db: &dyn DefDatabase, konst: ConstId) -> Arc<ConstData> {
306         let loc = konst.lookup(db);
307         let item_tree = loc.id.item_tree(db);
308         let konst = &item_tree[loc.id.value];
309
310         Arc::new(ConstData {
311             name: konst.name.clone(),
312             type_ref: konst.type_ref.clone(),
313             visibility: item_tree[konst.visibility].clone(),
314         })
315     }
316 }
317
318 #[derive(Debug, Clone, PartialEq, Eq)]
319 pub struct StaticData {
320     pub name: Name,
321     pub type_ref: Interned<TypeRef>,
322     pub visibility: RawVisibility,
323     pub mutable: bool,
324     pub is_extern: bool,
325 }
326
327 impl StaticData {
328     pub(crate) fn static_data_query(db: &dyn DefDatabase, konst: StaticId) -> Arc<StaticData> {
329         let loc = konst.lookup(db);
330         let item_tree = loc.id.item_tree(db);
331         let statik = &item_tree[loc.id.value];
332
333         Arc::new(StaticData {
334             name: statik.name.clone(),
335             type_ref: statik.type_ref.clone(),
336             visibility: item_tree[statik.visibility].clone(),
337             mutable: statik.mutable,
338             is_extern: matches!(loc.container, ItemContainerId::ExternBlockId(_)),
339         })
340     }
341 }
342
343 struct AssocItemCollector<'a> {
344     db: &'a dyn DefDatabase,
345     module_id: ModuleId,
346     def_map: Arc<DefMap>,
347     container: ItemContainerId,
348     expander: Expander,
349
350     items: Vec<(Name, AssocItemId)>,
351     attr_calls: Vec<(AstId<ast::Item>, MacroCallId)>,
352 }
353
354 impl<'a> AssocItemCollector<'a> {
355     fn new(
356         db: &'a dyn DefDatabase,
357         module_id: ModuleId,
358         file_id: HirFileId,
359         container: ItemContainerId,
360     ) -> Self {
361         Self {
362             db,
363             module_id,
364             def_map: module_id.def_map(db),
365             container,
366             expander: Expander::new(db, file_id, module_id),
367
368             items: Vec::new(),
369             attr_calls: Vec::new(),
370         }
371     }
372
373     fn take_attr_calls(&mut self) -> Option<Box<Vec<(AstId<ast::Item>, MacroCallId)>>> {
374         let attribute_calls = mem::take(&mut self.attr_calls);
375         if attribute_calls.is_empty() {
376             None
377         } else {
378             Some(Box::new(attribute_calls))
379         }
380     }
381
382     fn collect(&mut self, tree_id: TreeId, assoc_items: &[AssocItem]) {
383         let item_tree = tree_id.item_tree(self.db);
384
385         'items: for &item in assoc_items {
386             let attrs = item_tree.attrs(self.db, self.module_id.krate, ModItem::from(item).into());
387             if !attrs.is_cfg_enabled(self.expander.cfg_options()) {
388                 continue;
389             }
390
391             for attr in &*attrs {
392                 let ast_id =
393                     AstId::new(self.expander.current_file_id(), item.ast_id(&item_tree).upcast());
394                 let ast_id_with_path = AstIdWithPath { path: (*attr.path).clone(), ast_id };
395
396                 if let Ok(ResolvedAttr::Macro(call_id)) = self.def_map.resolve_attr_macro(
397                     self.db,
398                     self.module_id.local_id,
399                     ast_id_with_path,
400                     attr,
401                 ) {
402                     self.attr_calls.push((ast_id, call_id));
403                     let res = self.expander.enter_expand_id(self.db, call_id);
404                     self.collect_macro_items(res);
405                     continue 'items;
406                 }
407             }
408
409             match item {
410                 AssocItem::Function(id) => {
411                     let item = &item_tree[id];
412                     let def =
413                         FunctionLoc { container: self.container, id: ItemTreeId::new(tree_id, id) }
414                             .intern(self.db);
415                     self.items.push((item.name.clone(), def.into()));
416                 }
417                 AssocItem::Const(id) => {
418                     let item = &item_tree[id];
419                     let name = match item.name.clone() {
420                         Some(name) => name,
421                         None => continue,
422                     };
423                     let def =
424                         ConstLoc { container: self.container, id: ItemTreeId::new(tree_id, id) }
425                             .intern(self.db);
426                     self.items.push((name, def.into()));
427                 }
428                 AssocItem::TypeAlias(id) => {
429                     let item = &item_tree[id];
430                     let def = TypeAliasLoc {
431                         container: self.container,
432                         id: ItemTreeId::new(tree_id, id),
433                     }
434                     .intern(self.db);
435                     self.items.push((item.name.clone(), def.into()));
436                 }
437                 AssocItem::MacroCall(call) => {
438                     let call = &item_tree[call];
439                     let ast_id_map = self.db.ast_id_map(self.expander.current_file_id());
440                     let root = self.db.parse_or_expand(self.expander.current_file_id()).unwrap();
441                     let call = ast_id_map.get(call.ast_id).to_node(&root);
442                     let _cx =
443                         stdx::panic_context::enter(format!("collect_items MacroCall: {}", call));
444                     let res = self.expander.enter_expand(self.db, call);
445
446                     if let Ok(res) = res {
447                         self.collect_macro_items(res);
448                     }
449                 }
450             }
451         }
452     }
453
454     fn collect_macro_items(&mut self, res: ExpandResult<Option<(Mark, ast::MacroItems)>>) {
455         if let Some((mark, mac)) = res.value {
456             let src: InFile<ast::MacroItems> = self.expander.to_source(mac);
457             let tree_id = item_tree::TreeId::new(src.file_id, None);
458             let item_tree = tree_id.item_tree(self.db);
459             let iter: Vec<_> =
460                 item_tree.top_level_items().iter().filter_map(ModItem::as_assoc_item).collect();
461
462             self.collect(tree_id, &iter);
463
464             self.expander.exit(self.db, mark);
465         }
466     }
467 }