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