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