]> git.lizzy.rs Git - rust.git/blob - crates/hir-def/src/data.rs
Auto merge of #12093 - nico-abram:uwu, r=Veykril
[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, Macro2Id, MacroRulesId, ModuleId, ProcMacroId, StaticId,
19     TraitId, TypeAliasId, TypeAliasLoc,
20 };
21
22 #[derive(Debug, Clone, PartialEq, Eq)]
23 pub struct FunctionData {
24     pub name: Name,
25     pub params: Vec<(Option<Name>, Interned<TypeRef>)>,
26     pub ret_type: Interned<TypeRef>,
27     pub async_ret_type: Option<Interned<TypeRef>>,
28     pub attrs: Attrs,
29     pub visibility: RawVisibility,
30     pub abi: Option<Interned<str>>,
31     pub legacy_const_generics_indices: Vec<u32>,
32     flags: FnFlags,
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 crate_graph = db.crate_graph();
40         let cfg_options = &crate_graph[krate].cfg_options;
41         let item_tree = loc.id.item_tree(db);
42         let func = &item_tree[loc.id.value];
43
44         let enabled_params = func
45             .params
46             .clone()
47             .filter(|&param| item_tree.attrs(db, krate, param.into()).is_cfg_enabled(cfg_options));
48
49         // If last cfg-enabled param is a `...` param, it's a varargs function.
50         let is_varargs = enabled_params
51             .clone()
52             .next_back()
53             .map_or(false, |param| matches!(item_tree[param], Param::Varargs));
54
55         let mut flags = func.flags;
56         if is_varargs {
57             flags |= FnFlags::IS_VARARGS;
58         }
59         if flags.contains(FnFlags::HAS_SELF_PARAM) {
60             // If there's a self param in the syntax, but it is cfg'd out, remove the flag.
61             let is_cfgd_out = match func.params.clone().next() {
62                 Some(param) => {
63                     !item_tree.attrs(db, krate, param.into()).is_cfg_enabled(cfg_options)
64                 }
65                 None => {
66                     stdx::never!("fn HAS_SELF_PARAM but no parameters allocated");
67                     true
68                 }
69             };
70             if is_cfgd_out {
71                 cov_mark::hit!(cfgd_out_self_param);
72                 flags.remove(FnFlags::HAS_SELF_PARAM);
73             }
74         }
75
76         let legacy_const_generics_indices = item_tree
77             .attrs(db, krate, ModItem::from(loc.id.value).into())
78             .by_key("rustc_legacy_const_generics")
79             .tt_values()
80             .next()
81             .map(parse_rustc_legacy_const_generics)
82             .unwrap_or_default();
83
84         Arc::new(FunctionData {
85             name: func.name.clone(),
86             params: enabled_params
87                 .clone()
88                 .filter_map(|id| match &item_tree[id] {
89                     Param::Normal(name, ty) => Some((name.clone(), ty.clone())),
90                     Param::Varargs => None,
91                 })
92                 .collect(),
93             ret_type: func.ret_type.clone(),
94             async_ret_type: func.async_ret_type.clone(),
95             attrs: item_tree.attrs(db, krate, ModItem::from(loc.id.value).into()),
96             visibility: item_tree[func.visibility].clone(),
97             abi: func.abi.clone(),
98             legacy_const_generics_indices,
99             flags,
100         })
101     }
102
103     pub fn has_body(&self) -> bool {
104         self.flags.contains(FnFlags::HAS_BODY)
105     }
106
107     /// True if the first param is `self`. This is relevant to decide whether this
108     /// can be called as a method.
109     pub fn has_self_param(&self) -> bool {
110         self.flags.contains(FnFlags::HAS_SELF_PARAM)
111     }
112
113     pub fn has_default_kw(&self) -> bool {
114         self.flags.contains(FnFlags::HAS_DEFAULT_KW)
115     }
116
117     pub fn has_const_kw(&self) -> bool {
118         self.flags.contains(FnFlags::HAS_CONST_KW)
119     }
120
121     pub fn has_async_kw(&self) -> bool {
122         self.flags.contains(FnFlags::HAS_ASYNC_KW)
123     }
124
125     pub fn has_unsafe_kw(&self) -> bool {
126         self.flags.contains(FnFlags::HAS_UNSAFE_KW)
127     }
128
129     pub fn is_varargs(&self) -> bool {
130         self.flags.contains(FnFlags::IS_VARARGS)
131     }
132 }
133
134 fn parse_rustc_legacy_const_generics(tt: &tt::Subtree) -> Vec<u32> {
135     let mut indices = Vec::new();
136     for args in tt.token_trees.chunks(2) {
137         match &args[0] {
138             tt::TokenTree::Leaf(tt::Leaf::Literal(lit)) => match lit.text.parse() {
139                 Ok(index) => indices.push(index),
140                 Err(_) => break,
141             },
142             _ => break,
143         }
144
145         if let Some(comma) = args.get(1) {
146             match comma {
147                 tt::TokenTree::Leaf(tt::Leaf::Punct(punct)) if punct.char == ',' => {}
148                 _ => break,
149             }
150         }
151     }
152
153     indices
154 }
155
156 #[derive(Debug, Clone, PartialEq, Eq)]
157 pub struct TypeAliasData {
158     pub name: Name,
159     pub type_ref: Option<Interned<TypeRef>>,
160     pub visibility: RawVisibility,
161     pub is_extern: bool,
162     /// Bounds restricting the type alias itself (eg. `type Ty: Bound;` in a trait or impl).
163     pub bounds: Vec<Interned<TypeBound>>,
164 }
165
166 impl TypeAliasData {
167     pub(crate) fn type_alias_data_query(
168         db: &dyn DefDatabase,
169         typ: TypeAliasId,
170     ) -> Arc<TypeAliasData> {
171         let loc = typ.lookup(db);
172         let item_tree = loc.id.item_tree(db);
173         let typ = &item_tree[loc.id.value];
174
175         Arc::new(TypeAliasData {
176             name: typ.name.clone(),
177             type_ref: typ.type_ref.clone(),
178             visibility: item_tree[typ.visibility].clone(),
179             is_extern: matches!(loc.container, ItemContainerId::ExternBlockId(_)),
180             bounds: typ.bounds.to_vec(),
181         })
182     }
183 }
184
185 #[derive(Debug, Clone, PartialEq, Eq)]
186 pub struct TraitData {
187     pub name: Name,
188     pub items: Vec<(Name, AssocItemId)>,
189     pub is_auto: bool,
190     pub is_unsafe: bool,
191     pub visibility: RawVisibility,
192     /// Whether the trait has `#[rust_skip_array_during_method_dispatch]`. `hir_ty` will ignore
193     /// method calls to this trait's methods when the receiver is an array and the crate edition is
194     /// 2015 or 2018.
195     pub skip_array_during_method_dispatch: bool,
196     // box it as the vec is usually empty anyways
197     pub attribute_calls: Option<Box<Vec<(AstId<ast::Item>, MacroCallId)>>>,
198 }
199
200 impl TraitData {
201     pub(crate) fn trait_data_query(db: &dyn DefDatabase, tr: TraitId) -> Arc<TraitData> {
202         let tr_loc = tr.lookup(db);
203         let item_tree = tr_loc.id.item_tree(db);
204         let tr_def = &item_tree[tr_loc.id.value];
205         let _cx = stdx::panic_context::enter(format!(
206             "trait_data_query({:?} -> {:?} -> {:?})",
207             tr, tr_loc, tr_def
208         ));
209         let name = tr_def.name.clone();
210         let is_auto = tr_def.is_auto;
211         let is_unsafe = tr_def.is_unsafe;
212         let module_id = tr_loc.container;
213         let visibility = item_tree[tr_def.visibility].clone();
214         let skip_array_during_method_dispatch = item_tree
215             .attrs(db, tr_loc.container.krate(), ModItem::from(tr_loc.id.value).into())
216             .by_key("rustc_skip_array_during_method_dispatch")
217             .exists();
218
219         let mut collector = AssocItemCollector::new(
220             db,
221             module_id,
222             tr_loc.id.file_id(),
223             ItemContainerId::TraitId(tr),
224         );
225         collector.collect(tr_loc.id.tree_id(), &tr_def.items);
226
227         Arc::new(TraitData {
228             name,
229             attribute_calls: collector.take_attr_calls(),
230             items: collector.items,
231             is_auto,
232             is_unsafe,
233             visibility,
234             skip_array_during_method_dispatch,
235         })
236     }
237
238     pub fn associated_types(&self) -> impl Iterator<Item = TypeAliasId> + '_ {
239         self.items.iter().filter_map(|(_name, item)| match item {
240             AssocItemId::TypeAliasId(t) => Some(*t),
241             _ => None,
242         })
243     }
244
245     pub fn associated_type_by_name(&self, name: &Name) -> Option<TypeAliasId> {
246         self.items.iter().find_map(|(item_name, item)| match item {
247             AssocItemId::TypeAliasId(t) if item_name == name => Some(*t),
248             _ => None,
249         })
250     }
251
252     pub fn method_by_name(&self, name: &Name) -> Option<FunctionId> {
253         self.items.iter().find_map(|(item_name, item)| match item {
254             AssocItemId::FunctionId(t) if item_name == name => Some(*t),
255             _ => None,
256         })
257     }
258
259     pub fn attribute_calls(&self) -> impl Iterator<Item = (AstId<ast::Item>, MacroCallId)> + '_ {
260         self.attribute_calls.iter().flat_map(|it| it.iter()).copied()
261     }
262 }
263
264 #[derive(Debug, Clone, PartialEq, Eq)]
265 pub struct ImplData {
266     pub target_trait: Option<Interned<TraitRef>>,
267     pub self_ty: Interned<TypeRef>,
268     pub items: Vec<AssocItemId>,
269     pub is_negative: bool,
270     // box it as the vec is usually empty anyways
271     pub attribute_calls: Option<Box<Vec<(AstId<ast::Item>, MacroCallId)>>>,
272 }
273
274 impl ImplData {
275     pub(crate) fn impl_data_query(db: &dyn DefDatabase, id: ImplId) -> Arc<ImplData> {
276         let _p = profile::span("impl_data_query");
277         let impl_loc = id.lookup(db);
278
279         let item_tree = impl_loc.id.item_tree(db);
280         let impl_def = &item_tree[impl_loc.id.value];
281         let target_trait = impl_def.target_trait.clone();
282         let self_ty = impl_def.self_ty.clone();
283         let is_negative = impl_def.is_negative;
284         let module_id = impl_loc.container;
285
286         let mut collector = AssocItemCollector::new(
287             db,
288             module_id,
289             impl_loc.id.file_id(),
290             ItemContainerId::ImplId(id),
291         );
292         collector.collect(impl_loc.id.tree_id(), &impl_def.items);
293
294         let attribute_calls = collector.take_attr_calls();
295         let items = collector.items.into_iter().map(|(_, item)| item).collect();
296
297         Arc::new(ImplData { target_trait, self_ty, items, is_negative, attribute_calls })
298     }
299
300     pub fn attribute_calls(&self) -> impl Iterator<Item = (AstId<ast::Item>, MacroCallId)> + '_ {
301         self.attribute_calls.iter().flat_map(|it| it.iter()).copied()
302     }
303 }
304
305 #[derive(Debug, Clone, PartialEq, Eq)]
306 pub struct Macro2Data {
307     pub name: Name,
308     pub visibility: RawVisibility,
309 }
310
311 impl Macro2Data {
312     pub(crate) fn macro2_data_query(db: &dyn DefDatabase, makro: Macro2Id) -> Arc<Macro2Data> {
313         let loc = makro.lookup(db);
314         let item_tree = loc.id.item_tree(db);
315         let makro = &item_tree[loc.id.value];
316
317         Arc::new(Macro2Data {
318             name: makro.name.clone(),
319             visibility: item_tree[makro.visibility].clone(),
320         })
321     }
322 }
323 #[derive(Debug, Clone, PartialEq, Eq)]
324 pub struct MacroRulesData {
325     pub name: Name,
326     pub macro_export: bool,
327 }
328
329 impl MacroRulesData {
330     pub(crate) fn macro_rules_data_query(
331         db: &dyn DefDatabase,
332         makro: MacroRulesId,
333     ) -> Arc<MacroRulesData> {
334         let loc = makro.lookup(db);
335         let item_tree = loc.id.item_tree(db);
336         let makro = &item_tree[loc.id.value];
337
338         let macro_export = item_tree
339             .attrs(db, loc.container.krate(), ModItem::from(loc.id.value).into())
340             .by_key("macro_export")
341             .exists();
342
343         Arc::new(MacroRulesData { name: makro.name.clone(), macro_export })
344     }
345 }
346 #[derive(Debug, Clone, PartialEq, Eq)]
347 pub struct ProcMacroData {
348     pub name: Name,
349     // FIXME: Record deriver helper here?
350 }
351
352 impl ProcMacroData {
353     pub(crate) fn proc_macro_data_query(
354         db: &dyn DefDatabase,
355         makro: ProcMacroId,
356     ) -> Arc<ProcMacroData> {
357         let loc = makro.lookup(db);
358         let item_tree = loc.id.item_tree(db);
359         let makro = &item_tree[loc.id.value];
360
361         let name = if let Some(def) = item_tree
362             .attrs(db, loc.container.krate(), ModItem::from(loc.id.value).into())
363             .parse_proc_macro_decl(&makro.name)
364         {
365             def.name
366         } else {
367             // eeeh...
368             stdx::never!("proc macro declaration is not a proc macro");
369             makro.name.clone()
370         };
371         Arc::new(ProcMacroData { name })
372     }
373 }
374
375 #[derive(Debug, Clone, PartialEq, Eq)]
376 pub struct ConstData {
377     /// `None` for `const _: () = ();`
378     pub name: Option<Name>,
379     pub type_ref: Interned<TypeRef>,
380     pub visibility: RawVisibility,
381 }
382
383 impl ConstData {
384     pub(crate) fn const_data_query(db: &dyn DefDatabase, konst: ConstId) -> Arc<ConstData> {
385         let loc = konst.lookup(db);
386         let item_tree = loc.id.item_tree(db);
387         let konst = &item_tree[loc.id.value];
388
389         Arc::new(ConstData {
390             name: konst.name.clone(),
391             type_ref: konst.type_ref.clone(),
392             visibility: item_tree[konst.visibility].clone(),
393         })
394     }
395 }
396
397 #[derive(Debug, Clone, PartialEq, Eq)]
398 pub struct StaticData {
399     pub name: Name,
400     pub type_ref: Interned<TypeRef>,
401     pub visibility: RawVisibility,
402     pub mutable: bool,
403     pub is_extern: bool,
404 }
405
406 impl StaticData {
407     pub(crate) fn static_data_query(db: &dyn DefDatabase, konst: StaticId) -> Arc<StaticData> {
408         let loc = konst.lookup(db);
409         let item_tree = loc.id.item_tree(db);
410         let statik = &item_tree[loc.id.value];
411
412         Arc::new(StaticData {
413             name: statik.name.clone(),
414             type_ref: statik.type_ref.clone(),
415             visibility: item_tree[statik.visibility].clone(),
416             mutable: statik.mutable,
417             is_extern: matches!(loc.container, ItemContainerId::ExternBlockId(_)),
418         })
419     }
420 }
421
422 struct AssocItemCollector<'a> {
423     db: &'a dyn DefDatabase,
424     module_id: ModuleId,
425     def_map: Arc<DefMap>,
426     container: ItemContainerId,
427     expander: Expander,
428
429     items: Vec<(Name, AssocItemId)>,
430     attr_calls: Vec<(AstId<ast::Item>, MacroCallId)>,
431 }
432
433 impl<'a> AssocItemCollector<'a> {
434     fn new(
435         db: &'a dyn DefDatabase,
436         module_id: ModuleId,
437         file_id: HirFileId,
438         container: ItemContainerId,
439     ) -> Self {
440         Self {
441             db,
442             module_id,
443             def_map: module_id.def_map(db),
444             container,
445             expander: Expander::new(db, file_id, module_id),
446
447             items: Vec::new(),
448             attr_calls: Vec::new(),
449         }
450     }
451
452     fn take_attr_calls(&mut self) -> Option<Box<Vec<(AstId<ast::Item>, MacroCallId)>>> {
453         let attribute_calls = mem::take(&mut self.attr_calls);
454         if attribute_calls.is_empty() {
455             None
456         } else {
457             Some(Box::new(attribute_calls))
458         }
459     }
460
461     fn collect(&mut self, tree_id: TreeId, assoc_items: &[AssocItem]) {
462         let item_tree = tree_id.item_tree(self.db);
463
464         'items: for &item in assoc_items {
465             let attrs = item_tree.attrs(self.db, self.module_id.krate, ModItem::from(item).into());
466             if !attrs.is_cfg_enabled(self.expander.cfg_options()) {
467                 continue;
468             }
469
470             for attr in &*attrs {
471                 let ast_id =
472                     AstId::new(self.expander.current_file_id(), item.ast_id(&item_tree).upcast());
473                 let ast_id_with_path = AstIdWithPath { path: (*attr.path).clone(), ast_id };
474
475                 if let Ok(ResolvedAttr::Macro(call_id)) = self.def_map.resolve_attr_macro(
476                     self.db,
477                     self.module_id.local_id,
478                     ast_id_with_path,
479                     attr,
480                 ) {
481                     self.attr_calls.push((ast_id, call_id));
482                     let res = self.expander.enter_expand_id(self.db, call_id);
483                     self.collect_macro_items(res);
484                     continue 'items;
485                 }
486             }
487
488             match item {
489                 AssocItem::Function(id) => {
490                     let item = &item_tree[id];
491                     let def =
492                         FunctionLoc { container: self.container, id: ItemTreeId::new(tree_id, id) }
493                             .intern(self.db);
494                     self.items.push((item.name.clone(), def.into()));
495                 }
496                 AssocItem::Const(id) => {
497                     let item = &item_tree[id];
498                     let name = match item.name.clone() {
499                         Some(name) => name,
500                         None => continue,
501                     };
502                     let def =
503                         ConstLoc { container: self.container, id: ItemTreeId::new(tree_id, id) }
504                             .intern(self.db);
505                     self.items.push((name, def.into()));
506                 }
507                 AssocItem::TypeAlias(id) => {
508                     let item = &item_tree[id];
509                     let def = TypeAliasLoc {
510                         container: self.container,
511                         id: ItemTreeId::new(tree_id, id),
512                     }
513                     .intern(self.db);
514                     self.items.push((item.name.clone(), def.into()));
515                 }
516                 AssocItem::MacroCall(call) => {
517                     let call = &item_tree[call];
518                     let ast_id_map = self.db.ast_id_map(self.expander.current_file_id());
519                     let root = self.db.parse_or_expand(self.expander.current_file_id()).unwrap();
520                     let call = ast_id_map.get(call.ast_id).to_node(&root);
521                     let _cx =
522                         stdx::panic_context::enter(format!("collect_items MacroCall: {}", call));
523                     let res = self.expander.enter_expand(self.db, call);
524
525                     if let Ok(res) = res {
526                         self.collect_macro_items(res);
527                     }
528                 }
529             }
530         }
531     }
532
533     fn collect_macro_items(&mut self, res: ExpandResult<Option<(Mark, ast::MacroItems)>>) {
534         if let Some((mark, mac)) = res.value {
535             let src: InFile<ast::MacroItems> = self.expander.to_source(mac);
536             let tree_id = item_tree::TreeId::new(src.file_id, None);
537             let item_tree = tree_id.item_tree(self.db);
538             let iter: Vec<_> =
539                 item_tree.top_level_items().iter().filter_map(ModItem::as_assoc_item).collect();
540
541             self.collect(tree_id, &iter);
542
543             self.expander.exit(self.db, mark);
544         }
545     }
546 }