1 //! Contains basic data about various HIR declarations.
3 use std::{mem, sync::Arc};
5 use hir_expand::{name::Name, AstId, ExpandResult, HirFileId, InFile, MacroCallId};
10 body::{Expander, Mark},
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,
22 #[derive(Debug, Clone, PartialEq, Eq)]
23 pub struct FunctionData {
25 pub params: Vec<(Option<Name>, Interned<TypeRef>)>,
26 pub ret_type: Interned<TypeRef>,
27 pub async_ret_type: Option<Interned<TypeRef>>,
29 pub visibility: RawVisibility,
30 pub abi: Option<Interned<str>>,
31 pub legacy_const_generics_indices: Vec<u32>,
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];
44 let enabled_params = func
47 .filter(|¶m| item_tree.attrs(db, krate, param.into()).is_cfg_enabled(cfg_options));
49 // If last cfg-enabled param is a `...` param, it's a varargs function.
50 let is_varargs = enabled_params
53 .map_or(false, |param| matches!(item_tree[param], Param::Varargs));
55 let mut flags = func.flags;
57 flags |= FnFlags::IS_VARARGS;
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() {
63 !item_tree.attrs(db, krate, param.into()).is_cfg_enabled(cfg_options)
66 stdx::never!("fn HAS_SELF_PARAM but no parameters allocated");
71 cov_mark::hit!(cfgd_out_self_param);
72 flags.remove(FnFlags::HAS_SELF_PARAM);
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")
81 .map(parse_rustc_legacy_const_generics)
84 Arc::new(FunctionData {
85 name: func.name.clone(),
86 params: enabled_params
88 .filter_map(|id| match &item_tree[id] {
89 Param::Normal(name, ty) => Some((name.clone(), ty.clone())),
90 Param::Varargs => None,
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,
103 pub fn has_body(&self) -> bool {
104 self.flags.contains(FnFlags::HAS_BODY)
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)
113 pub fn has_default_kw(&self) -> bool {
114 self.flags.contains(FnFlags::HAS_DEFAULT_KW)
117 pub fn has_const_kw(&self) -> bool {
118 self.flags.contains(FnFlags::HAS_CONST_KW)
121 pub fn has_async_kw(&self) -> bool {
122 self.flags.contains(FnFlags::HAS_ASYNC_KW)
125 pub fn has_unsafe_kw(&self) -> bool {
126 self.flags.contains(FnFlags::HAS_UNSAFE_KW)
129 pub fn is_varargs(&self) -> bool {
130 self.flags.contains(FnFlags::IS_VARARGS)
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) {
138 tt::TokenTree::Leaf(tt::Leaf::Literal(lit)) => match lit.text.parse() {
139 Ok(index) => indices.push(index),
145 if let Some(comma) = args.get(1) {
147 tt::TokenTree::Leaf(tt::Leaf::Punct(punct)) if punct.char == ',' => {}
156 #[derive(Debug, Clone, PartialEq, Eq)]
157 pub struct TypeAliasData {
159 pub type_ref: Option<Interned<TypeRef>>,
160 pub visibility: RawVisibility,
162 /// Bounds restricting the type alias itself (eg. `type Ty: Bound;` in a trait or impl).
163 pub bounds: Vec<Interned<TypeBound>>,
167 pub(crate) fn type_alias_data_query(
168 db: &dyn DefDatabase,
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];
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(),
185 #[derive(Debug, Clone, PartialEq, Eq)]
186 pub struct TraitData {
188 pub items: Vec<(Name, AssocItemId)>,
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
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)>>>,
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({:?} -> {:?} -> {:?})",
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")
219 let mut collector = AssocItemCollector::new(
223 ItemContainerId::TraitId(tr),
225 collector.collect(tr_loc.id.tree_id(), &tr_def.items);
229 attribute_calls: collector.take_attr_calls(),
230 items: collector.items,
234 skip_array_during_method_dispatch,
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),
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),
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),
259 pub fn attribute_calls(&self) -> impl Iterator<Item = (AstId<ast::Item>, MacroCallId)> + '_ {
260 self.attribute_calls.iter().flat_map(|it| it.iter()).copied()
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)>>>,
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);
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;
286 let mut collector = AssocItemCollector::new(
289 impl_loc.id.file_id(),
290 ItemContainerId::ImplId(id),
292 collector.collect(impl_loc.id.tree_id(), &impl_def.items);
294 let attribute_calls = collector.take_attr_calls();
295 let items = collector.items.into_iter().map(|(_, item)| item).collect();
297 Arc::new(ImplData { target_trait, self_ty, items, is_negative, attribute_calls })
300 pub fn attribute_calls(&self) -> impl Iterator<Item = (AstId<ast::Item>, MacroCallId)> + '_ {
301 self.attribute_calls.iter().flat_map(|it| it.iter()).copied()
305 #[derive(Debug, Clone, PartialEq, Eq)]
306 pub struct Macro2Data {
308 pub visibility: RawVisibility,
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];
317 Arc::new(Macro2Data {
318 name: makro.name.clone(),
319 visibility: item_tree[makro.visibility].clone(),
323 #[derive(Debug, Clone, PartialEq, Eq)]
324 pub struct MacroRulesData {
326 pub macro_export: bool,
329 impl MacroRulesData {
330 pub(crate) fn macro_rules_data_query(
331 db: &dyn DefDatabase,
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];
338 let macro_export = item_tree
339 .attrs(db, loc.container.krate(), ModItem::from(loc.id.value).into())
340 .by_key("macro_export")
343 Arc::new(MacroRulesData { name: makro.name.clone(), macro_export })
346 #[derive(Debug, Clone, PartialEq, Eq)]
347 pub struct ProcMacroData {
349 // FIXME: Record deriver helper here?
353 pub(crate) fn proc_macro_data_query(
354 db: &dyn DefDatabase,
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];
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)
368 stdx::never!("proc macro declaration is not a proc macro");
371 Arc::new(ProcMacroData { name })
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,
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];
390 name: konst.name.clone(),
391 type_ref: konst.type_ref.clone(),
392 visibility: item_tree[konst.visibility].clone(),
397 #[derive(Debug, Clone, PartialEq, Eq)]
398 pub struct StaticData {
400 pub type_ref: Interned<TypeRef>,
401 pub visibility: RawVisibility,
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];
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(_)),
422 struct AssocItemCollector<'a> {
423 db: &'a dyn DefDatabase,
425 def_map: Arc<DefMap>,
426 container: ItemContainerId,
429 items: Vec<(Name, AssocItemId)>,
430 attr_calls: Vec<(AstId<ast::Item>, MacroCallId)>,
433 impl<'a> AssocItemCollector<'a> {
435 db: &'a dyn DefDatabase,
438 container: ItemContainerId,
443 def_map: module_id.def_map(db),
445 expander: Expander::new(db, file_id, module_id),
448 attr_calls: Vec::new(),
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() {
457 Some(Box::new(attribute_calls))
461 fn collect(&mut self, tree_id: TreeId, assoc_items: &[AssocItem]) {
462 let item_tree = tree_id.item_tree(self.db);
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()) {
470 for attr in &*attrs {
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 };
475 if let Ok(ResolvedAttr::Macro(call_id)) = self.def_map.resolve_attr_macro(
477 self.module_id.local_id,
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);
489 AssocItem::Function(id) => {
490 let item = &item_tree[id];
492 FunctionLoc { container: self.container, id: ItemTreeId::new(tree_id, id) }
494 self.items.push((item.name.clone(), def.into()));
496 AssocItem::Const(id) => {
497 let item = &item_tree[id];
498 let name = match item.name.clone() {
503 ConstLoc { container: self.container, id: ItemTreeId::new(tree_id, id) }
505 self.items.push((name, def.into()));
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),
514 self.items.push((item.name.clone(), def.into()));
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);
522 stdx::panic_context::enter(format!("collect_items MacroCall: {}", call));
523 let res = self.expander.enter_expand(self.db, call);
525 if let Ok(res) = res {
526 self.collect_macro_items(res);
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);
539 item_tree.top_level_items().iter().filter_map(ModItem::as_assoc_item).collect();
541 self.collect(tree_id, &iter);
543 self.expander.exit(self.db, mark);