1 //! Contains basic data about various HIR declarations.
5 use hir_expand::{name::Name, InFile};
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,
20 #[derive(Debug, Clone, PartialEq, Eq)]
21 pub struct FunctionData {
23 pub params: Vec<Interned<TypeRef>>,
24 pub ret_type: Interned<TypeRef>,
25 pub async_ret_type: Option<Interned<TypeRef>>,
27 pub visibility: RawVisibility,
28 pub abi: Option<Interned<str>>,
29 pub legacy_const_generics_indices: Vec<u32>,
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];
42 let enabled_params = func
45 .filter(|¶m| item_tree.attrs(db, krate, param.into()).is_cfg_enabled(cfg_options));
47 // If last cfg-enabled param is a `...` param, it's a varargs function.
48 let is_varargs = enabled_params
51 .map_or(false, |param| matches!(item_tree[param], Param::Varargs));
53 let mut flags = func.flags;
55 flags.bits |= FnFlags::IS_VARARGS;
58 if matches!(loc.container, ItemContainerId::ExternBlockId(_)) {
59 flags.bits |= FnFlags::IS_IN_EXTERN_BLOCK;
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")
67 .map(|arg| parse_rustc_legacy_const_generics(arg))
70 Arc::new(FunctionData {
71 name: func.name.clone(),
72 params: enabled_params
74 .filter_map(|id| match &item_tree[id] {
75 Param::Normal(ty) => Some(ty.clone()),
76 Param::Varargs => None,
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,
89 pub fn has_body(&self) -> bool {
90 self.flags.bits & FnFlags::HAS_BODY != 0
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
99 pub fn is_default(&self) -> bool {
100 self.flags.bits & FnFlags::IS_DEFAULT != 0
103 pub fn is_const(&self) -> bool {
104 self.flags.bits & FnFlags::IS_CONST != 0
107 pub fn is_async(&self) -> bool {
108 self.flags.bits & FnFlags::IS_ASYNC != 0
111 pub fn is_unsafe(&self) -> bool {
112 self.flags.bits & FnFlags::IS_UNSAFE != 0
115 pub fn is_in_extern_block(&self) -> bool {
116 self.flags.bits & FnFlags::IS_IN_EXTERN_BLOCK != 0
119 pub fn is_varargs(&self) -> bool {
120 self.flags.bits & FnFlags::IS_VARARGS != 0
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) {
128 tt::TokenTree::Leaf(tt::Leaf::Literal(lit)) => match lit.text.parse() {
129 Ok(index) => indices.push(index),
135 if let Some(comma) = args.get(1) {
137 tt::TokenTree::Leaf(tt::Leaf::Punct(punct)) if punct.char == ',' => {}
146 #[derive(Debug, Clone, PartialEq, Eq)]
147 pub struct TypeAliasData {
149 pub type_ref: Option<Interned<TypeRef>>,
150 pub visibility: RawVisibility,
152 /// Bounds restricting the type alias itself (eg. `type Ty: Bound;` in a trait or impl).
153 pub bounds: Vec<Interned<TypeBound>>,
157 pub(crate) fn type_alias_data_query(
158 db: &dyn DefDatabase,
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];
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(),
175 #[derive(Debug, Clone, PartialEq, Eq)]
176 pub struct TraitData {
178 pub items: Vec<(Name, AssocItemId)>,
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
185 pub skip_array_during_method_dispatch: bool,
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({:?} -> {:?} -> {:?})",
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")
209 let items = collect_items(
213 tr_def.items.iter().copied(),
225 skip_array_during_method_dispatch,
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),
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),
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),
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,
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);
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);
273 let items = collect_items(
277 impl_def.items.iter().copied(),
278 impl_loc.id.tree_id(),
282 let items = items.into_iter().map(|(_, item)| item).collect();
284 Arc::new(ImplData { target_trait, self_ty, items, is_negative })
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,
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];
303 name: konst.name.clone(),
304 type_ref: konst.type_ref.clone(),
305 visibility: item_tree[konst.visibility].clone(),
310 #[derive(Debug, Clone, PartialEq, Eq)]
311 pub struct StaticData {
313 pub type_ref: Interned<TypeRef>,
314 pub visibility: RawVisibility,
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];
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(_)),
336 db: &dyn DefDatabase,
338 expander: &mut Expander,
339 assoc_items: impl Iterator<Item = AssocItem>,
340 tree_id: item_tree::TreeId,
341 container: ItemContainerId,
343 ) -> Vec<(Name, AssocItemId)> {
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;
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) {
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()));
365 AssocItem::Const(id) => {
366 let item = &item_tree[id];
367 let name = match item.name.clone() {
371 let def = ConstLoc { container, id: ItemTreeId::new(tree_id, id) }.intern(db);
372 items.push((name, def.into()));
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()));
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);
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);
393 item_tree.top_level_items().iter().filter_map(ModItem::as_assoc_item);
394 items.extend(collect_items(
404 expander.exit(db, mark);