1 //! Contains basic data about various HIR declarations.
5 use hir_expand::{name::Name, AstId, ExpandResult, InFile, MacroCallId};
10 body::{Expander, Mark},
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,
21 #[derive(Debug, Clone, PartialEq, Eq)]
22 pub struct FunctionData {
24 pub params: Vec<(Option<Name>, Interned<TypeRef>)>,
25 pub ret_type: Interned<TypeRef>,
26 pub async_ret_type: Option<Interned<TypeRef>>,
28 pub visibility: RawVisibility,
29 pub abi: Option<Interned<str>>,
30 pub legacy_const_generics_indices: Vec<u32>,
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];
43 let enabled_params = func
46 .filter(|¶m| item_tree.attrs(db, krate, param.into()).is_cfg_enabled(cfg_options));
48 // If last cfg-enabled param is a `...` param, it's a varargs function.
49 let is_varargs = enabled_params
52 .map_or(false, |param| matches!(item_tree[param], Param::Varargs));
54 let mut flags = func.flags;
56 flags.bits |= FnFlags::IS_VARARGS;
59 if matches!(loc.container, ItemContainerId::ExternBlockId(_)) {
60 flags.bits |= FnFlags::IS_IN_EXTERN_BLOCK;
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")
68 .map(|arg| parse_rustc_legacy_const_generics(arg))
71 Arc::new(FunctionData {
72 name: func.name.clone(),
73 params: enabled_params
75 .filter_map(|id| match &item_tree[id] {
76 Param::Normal(name, ty) => Some((name.clone(), ty.clone())),
77 Param::Varargs => None,
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,
90 pub fn has_body(&self) -> bool {
91 self.flags.bits & FnFlags::HAS_BODY != 0
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
100 pub fn is_default(&self) -> bool {
101 self.flags.bits & FnFlags::IS_DEFAULT != 0
104 pub fn is_const(&self) -> bool {
105 self.flags.bits & FnFlags::IS_CONST != 0
108 pub fn is_async(&self) -> bool {
109 self.flags.bits & FnFlags::IS_ASYNC != 0
112 pub fn is_unsafe(&self) -> bool {
113 self.flags.bits & FnFlags::IS_UNSAFE != 0
116 pub fn is_in_extern_block(&self) -> bool {
117 self.flags.bits & FnFlags::IS_IN_EXTERN_BLOCK != 0
120 pub fn is_varargs(&self) -> bool {
121 self.flags.bits & FnFlags::IS_VARARGS != 0
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) {
129 tt::TokenTree::Leaf(tt::Leaf::Literal(lit)) => match lit.text.parse() {
130 Ok(index) => indices.push(index),
136 if let Some(comma) = args.get(1) {
138 tt::TokenTree::Leaf(tt::Leaf::Punct(punct)) if punct.char == ',' => {}
147 #[derive(Debug, Clone, PartialEq, Eq)]
148 pub struct TypeAliasData {
150 pub type_ref: Option<Interned<TypeRef>>,
151 pub visibility: RawVisibility,
153 /// Bounds restricting the type alias itself (eg. `type Ty: Bound;` in a trait or impl).
154 pub bounds: Vec<Interned<TypeBound>>,
158 pub(crate) fn type_alias_data_query(
159 db: &dyn DefDatabase,
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];
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(),
176 #[derive(Debug, Clone, PartialEq, Eq)]
177 pub struct TraitData {
179 pub items: Vec<(Name, AssocItemId)>,
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
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)>>>,
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({:?} -> {:?} -> {:?})",
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 container = ItemContainerId::TraitId(tr);
205 let visibility = item_tree[tr_def.visibility].clone();
206 let mut expander = Expander::new(db, tr_loc.id.file_id(), module_id);
207 let skip_array_during_method_dispatch = item_tree
208 .attrs(db, tr_loc.container.krate(), ModItem::from(tr_loc.id.value).into())
209 .by_key("rustc_skip_array_during_method_dispatch")
212 let (items, attribute_calls) =
213 do_collect(db, module_id, &mut expander, &tr_def.items, tr_loc.id.tree_id(), container);
221 skip_array_during_method_dispatch,
226 pub fn associated_types(&self) -> impl Iterator<Item = TypeAliasId> + '_ {
227 self.items.iter().filter_map(|(_name, item)| match item {
228 AssocItemId::TypeAliasId(t) => Some(*t),
233 pub fn associated_type_by_name(&self, name: &Name) -> Option<TypeAliasId> {
234 self.items.iter().find_map(|(item_name, item)| match item {
235 AssocItemId::TypeAliasId(t) if item_name == name => Some(*t),
240 pub fn method_by_name(&self, name: &Name) -> Option<FunctionId> {
241 self.items.iter().find_map(|(item_name, item)| match item {
242 AssocItemId::FunctionId(t) if item_name == name => Some(*t),
247 pub fn attribute_calls(&self) -> impl Iterator<Item = (AstId<ast::Item>, MacroCallId)> + '_ {
248 self.attribute_calls.iter().flat_map(|it| it.iter()).copied()
252 #[derive(Debug, Clone, PartialEq, Eq)]
253 pub struct ImplData {
254 pub target_trait: Option<Interned<TraitRef>>,
255 pub self_ty: Interned<TypeRef>,
256 pub items: Vec<AssocItemId>,
257 pub is_negative: bool,
258 // box it as the vec is usually empty anyways
259 pub attribute_calls: Option<Box<Vec<(AstId<ast::Item>, MacroCallId)>>>,
263 pub(crate) fn impl_data_query(db: &dyn DefDatabase, id: ImplId) -> Arc<ImplData> {
264 let _p = profile::span("impl_data_query");
265 let impl_loc = id.lookup(db);
267 let item_tree = impl_loc.id.item_tree(db);
268 let impl_def = &item_tree[impl_loc.id.value];
269 let target_trait = impl_def.target_trait.clone();
270 let self_ty = impl_def.self_ty.clone();
271 let is_negative = impl_def.is_negative;
272 let module_id = impl_loc.container;
273 let container = ItemContainerId::ImplId(id);
274 let mut expander = Expander::new(db, impl_loc.id.file_id(), module_id);
276 let (items, attribute_calls) = do_collect(
281 impl_loc.id.tree_id(),
284 let items = items.into_iter().map(|(_, item)| item).collect();
286 Arc::new(ImplData { target_trait, self_ty, items, is_negative, attribute_calls })
289 pub fn attribute_calls(&self) -> impl Iterator<Item = (AstId<ast::Item>, MacroCallId)> + '_ {
290 self.attribute_calls.iter().flat_map(|it| it.iter()).copied()
294 #[derive(Debug, Clone, PartialEq, Eq)]
295 pub struct ConstData {
296 /// `None` for `const _: () = ();`
297 pub name: Option<Name>,
298 pub type_ref: Interned<TypeRef>,
299 pub visibility: RawVisibility,
303 pub(crate) fn const_data_query(db: &dyn DefDatabase, konst: ConstId) -> Arc<ConstData> {
304 let loc = konst.lookup(db);
305 let item_tree = loc.id.item_tree(db);
306 let konst = &item_tree[loc.id.value];
309 name: konst.name.clone(),
310 type_ref: konst.type_ref.clone(),
311 visibility: item_tree[konst.visibility].clone(),
316 #[derive(Debug, Clone, PartialEq, Eq)]
317 pub struct StaticData {
319 pub type_ref: Interned<TypeRef>,
320 pub visibility: RawVisibility,
326 pub(crate) fn static_data_query(db: &dyn DefDatabase, konst: StaticId) -> Arc<StaticData> {
327 let loc = konst.lookup(db);
328 let item_tree = loc.id.item_tree(db);
329 let statik = &item_tree[loc.id.value];
331 Arc::new(StaticData {
332 name: statik.name.clone(),
333 type_ref: statik.type_ref.clone(),
334 visibility: item_tree[statik.visibility].clone(),
335 mutable: statik.mutable,
336 is_extern: matches!(loc.container, ItemContainerId::ExternBlockId(_)),
342 db: &dyn DefDatabase,
344 expander: &mut Expander,
345 assoc_items: &[AssocItem],
346 tree_id: item_tree::TreeId,
347 container: ItemContainerId,
348 ) -> (Vec<(Name, AssocItemId)>, Option<Box<Vec<(AstId<ast::Item>, MacroCallId)>>>) {
349 let mut items = Vec::new();
350 let mut attribute_calls = Vec::new();
355 &mut attribute_calls,
358 assoc_items.iter().copied(),
364 let attribute_calls =
365 if attribute_calls.is_empty() { None } else { Some(Box::new(attribute_calls)) };
366 (items, attribute_calls)
370 db: &dyn DefDatabase,
371 items: &mut Vec<(Name, AssocItemId)>,
372 attr_calls: &mut Vec<(AstId<ast::Item>, MacroCallId)>,
374 expander: &mut Expander,
375 assoc_items: impl Iterator<Item = AssocItem>,
376 tree_id: item_tree::TreeId,
377 container: ItemContainerId,
384 let item_tree = tree_id.item_tree(db);
385 let crate_graph = db.crate_graph();
386 let cfg_options = &crate_graph[module.krate].cfg_options;
387 let def_map = module.def_map(db);
389 'items: for item in assoc_items {
390 let attrs = item_tree.attrs(db, module.krate, ModItem::from(item).into());
391 if !attrs.is_cfg_enabled(cfg_options) {
395 for attr in &*attrs {
396 let ast_id = AstId::new(expander.current_file_id(), item.ast_id(&item_tree).upcast());
397 let ast_id_with_path = AstIdWithPath { path: (*attr.path).clone(), ast_id };
399 if let Ok(ResolvedAttr::Macro(call_id)) =
400 def_map.resolve_attr_macro(db, module.local_id, ast_id_with_path, attr)
402 attr_calls.push((ast_id, call_id));
403 let res = expander.enter_expand_id(db, call_id);
404 collect_macro_items(db, items, attr_calls, module, expander, container, limit, res);
410 AssocItem::Function(id) => {
411 let item = &item_tree[id];
412 let def = FunctionLoc { container, id: ItemTreeId::new(tree_id, id) }.intern(db);
413 items.push((item.name.clone(), def.into()));
415 AssocItem::Const(id) => {
416 let item = &item_tree[id];
417 let name = match item.name.clone() {
421 let def = ConstLoc { container, id: ItemTreeId::new(tree_id, id) }.intern(db);
422 items.push((name, def.into()));
424 AssocItem::TypeAlias(id) => {
425 let item = &item_tree[id];
426 let def = TypeAliasLoc { container, id: ItemTreeId::new(tree_id, id) }.intern(db);
427 items.push((item.name.clone(), def.into()));
429 AssocItem::MacroCall(call) => {
430 let call = &item_tree[call];
431 let ast_id_map = db.ast_id_map(tree_id.file_id());
432 let root = db.parse_or_expand(tree_id.file_id()).unwrap();
433 let call = ast_id_map.get(call.ast_id).to_node(&root);
434 let _cx = stdx::panic_context::enter(format!("collect_items MacroCall: {}", call));
435 let res = expander.enter_expand(db, call);
437 if let Ok(res) = res {
439 db, items, attr_calls, module, expander, container, limit, res,
447 fn collect_macro_items(
448 db: &dyn DefDatabase,
449 items: &mut Vec<(Name, AssocItemId)>,
450 attr_calls: &mut Vec<(AstId<ast::Item>, MacroCallId)>,
452 expander: &mut Expander,
453 container: ItemContainerId,
455 res: ExpandResult<Option<(Mark, ast::MacroItems)>>,
457 if let Some((mark, mac)) = res.value {
458 let src: InFile<ast::MacroItems> = expander.to_source(mac);
459 let tree_id = item_tree::TreeId::new(src.file_id, None);
460 let item_tree = tree_id.item_tree(db);
461 let iter = item_tree.top_level_items().iter().filter_map(ModItem::as_assoc_item);
462 collect_items(db, items, attr_calls, module, expander, iter, tree_id, container, limit - 1);
464 expander.exit(db, mark);