1 //! Contains basic data about various HIR declarations.
5 use hir_expand::{name::Name, AstId, ExpandResult, HirFileId, InFile, MacroCallId, MacroDefKind};
6 use smallvec::SmallVec;
11 body::{Expander, Mark},
14 item_tree::{self, AssocItem, FnFlags, ItemTree, ItemTreeId, ModItem, Param, TreeId},
16 attr_resolution::ResolvedAttr, diagnostics::DefDiagnostic, proc_macro::ProcMacroKind,
19 type_ref::{TraitRef, TypeBound, TypeRef},
20 visibility::RawVisibility,
21 AssocItemId, AstIdWithPath, ConstId, ConstLoc, FunctionId, FunctionLoc, HasModule, ImplId,
22 Intern, ItemContainerId, ItemLoc, Lookup, Macro2Id, MacroRulesId, ModuleId, ProcMacroId,
23 StaticId, TraitId, TypeAliasId, TypeAliasLoc,
26 #[derive(Debug, Clone, PartialEq, Eq)]
27 pub struct FunctionData {
29 pub params: Vec<(Option<Name>, Interned<TypeRef>)>,
30 pub ret_type: Interned<TypeRef>,
31 pub async_ret_type: Option<Interned<TypeRef>>,
33 pub visibility: RawVisibility,
34 pub abi: Option<Interned<str>>,
35 pub legacy_const_generics_indices: Box<[u32]>,
40 pub(crate) fn fn_data_query(db: &dyn DefDatabase, func: FunctionId) -> Arc<FunctionData> {
41 let loc = func.lookup(db);
42 let krate = loc.container.module(db).krate;
43 let crate_graph = db.crate_graph();
44 let cfg_options = &crate_graph[krate].cfg_options;
45 let item_tree = loc.id.item_tree(db);
46 let func = &item_tree[loc.id.value];
47 let visibility = if let ItemContainerId::TraitId(trait_id) = loc.container {
48 db.trait_data(trait_id).visibility.clone()
50 item_tree[func.visibility].clone()
53 let enabled_params = func
56 .filter(|¶m| item_tree.attrs(db, krate, param.into()).is_cfg_enabled(cfg_options));
58 // If last cfg-enabled param is a `...` param, it's a varargs function.
59 let is_varargs = enabled_params
62 .map_or(false, |param| matches!(item_tree[param], Param::Varargs));
64 let mut flags = func.flags;
66 flags |= FnFlags::IS_VARARGS;
68 if flags.contains(FnFlags::HAS_SELF_PARAM) {
69 // If there's a self param in the syntax, but it is cfg'd out, remove the flag.
70 let is_cfgd_out = match func.params.clone().next() {
72 !item_tree.attrs(db, krate, param.into()).is_cfg_enabled(cfg_options)
75 stdx::never!("fn HAS_SELF_PARAM but no parameters allocated");
80 cov_mark::hit!(cfgd_out_self_param);
81 flags.remove(FnFlags::HAS_SELF_PARAM);
85 let legacy_const_generics_indices = item_tree
86 .attrs(db, krate, ModItem::from(loc.id.value).into())
87 .by_key("rustc_legacy_const_generics")
90 .map(parse_rustc_legacy_const_generics)
93 Arc::new(FunctionData {
94 name: func.name.clone(),
95 params: enabled_params
97 .filter_map(|id| match &item_tree[id] {
98 Param::Normal(name, ty) => Some((name.clone(), ty.clone())),
99 Param::Varargs => None,
102 ret_type: func.ret_type.clone(),
103 async_ret_type: func.async_ret_type.clone(),
104 attrs: item_tree.attrs(db, krate, ModItem::from(loc.id.value).into()),
106 abi: func.abi.clone(),
107 legacy_const_generics_indices,
112 pub fn has_body(&self) -> bool {
113 self.flags.contains(FnFlags::HAS_BODY)
116 /// True if the first param is `self`. This is relevant to decide whether this
117 /// can be called as a method.
118 pub fn has_self_param(&self) -> bool {
119 self.flags.contains(FnFlags::HAS_SELF_PARAM)
122 pub fn has_default_kw(&self) -> bool {
123 self.flags.contains(FnFlags::HAS_DEFAULT_KW)
126 pub fn has_const_kw(&self) -> bool {
127 self.flags.contains(FnFlags::HAS_CONST_KW)
130 pub fn has_async_kw(&self) -> bool {
131 self.flags.contains(FnFlags::HAS_ASYNC_KW)
134 pub fn has_unsafe_kw(&self) -> bool {
135 self.flags.contains(FnFlags::HAS_UNSAFE_KW)
138 pub fn is_varargs(&self) -> bool {
139 self.flags.contains(FnFlags::IS_VARARGS)
143 fn parse_rustc_legacy_const_generics(tt: &tt::Subtree) -> Box<[u32]> {
144 let mut indices = Vec::new();
145 for args in tt.token_trees.chunks(2) {
147 tt::TokenTree::Leaf(tt::Leaf::Literal(lit)) => match lit.text.parse() {
148 Ok(index) => indices.push(index),
154 if let Some(comma) = args.get(1) {
156 tt::TokenTree::Leaf(tt::Leaf::Punct(punct)) if punct.char == ',' => {}
162 indices.into_boxed_slice()
165 #[derive(Debug, Clone, PartialEq, Eq)]
166 pub struct TypeAliasData {
168 pub type_ref: Option<Interned<TypeRef>>,
169 pub visibility: RawVisibility,
171 /// Bounds restricting the type alias itself (eg. `type Ty: Bound;` in a trait or impl).
172 pub bounds: Vec<Interned<TypeBound>>,
176 pub(crate) fn type_alias_data_query(
177 db: &dyn DefDatabase,
179 ) -> Arc<TypeAliasData> {
180 let loc = typ.lookup(db);
181 let item_tree = loc.id.item_tree(db);
182 let typ = &item_tree[loc.id.value];
183 let visibility = if let ItemContainerId::TraitId(trait_id) = loc.container {
184 db.trait_data(trait_id).visibility.clone()
186 item_tree[typ.visibility].clone()
189 Arc::new(TypeAliasData {
190 name: typ.name.clone(),
191 type_ref: typ.type_ref.clone(),
193 is_extern: matches!(loc.container, ItemContainerId::ExternBlockId(_)),
194 bounds: typ.bounds.to_vec(),
199 #[derive(Debug, Clone, PartialEq, Eq)]
200 pub struct TraitData {
202 pub items: Vec<(Name, AssocItemId)>,
205 pub visibility: RawVisibility,
206 /// Whether the trait has `#[rust_skip_array_during_method_dispatch]`. `hir_ty` will ignore
207 /// method calls to this trait's methods when the receiver is an array and the crate edition is
209 pub skip_array_during_method_dispatch: bool,
210 // box it as the vec is usually empty anyways
211 pub attribute_calls: Option<Box<Vec<(AstId<ast::Item>, MacroCallId)>>>,
215 pub(crate) fn trait_data_query(db: &dyn DefDatabase, tr: TraitId) -> Arc<TraitData> {
216 db.trait_data_with_diagnostics(tr).0
219 pub(crate) fn trait_data_with_diagnostics_query(
220 db: &dyn DefDatabase,
222 ) -> (Arc<TraitData>, Arc<[DefDiagnostic]>) {
223 let tr_loc @ ItemLoc { container: module_id, id: tree_id } = tr.lookup(db);
224 let item_tree = tree_id.item_tree(db);
225 let tr_def = &item_tree[tree_id.value];
226 let _cx = stdx::panic_context::enter(format!(
227 "trait_data_query({:?} -> {:?} -> {:?})",
230 let name = tr_def.name.clone();
231 let is_auto = tr_def.is_auto;
232 let is_unsafe = tr_def.is_unsafe;
233 let visibility = item_tree[tr_def.visibility].clone();
234 let skip_array_during_method_dispatch = item_tree
235 .attrs(db, module_id.krate(), ModItem::from(tree_id.value).into())
236 .by_key("rustc_skip_array_during_method_dispatch")
240 AssocItemCollector::new(db, module_id, tree_id.file_id(), ItemContainerId::TraitId(tr));
241 collector.collect(&item_tree, tree_id.tree_id(), &tr_def.items);
242 let (items, attribute_calls, diagnostics) = collector.finish();
252 skip_array_during_method_dispatch,
258 pub fn associated_types(&self) -> impl Iterator<Item = TypeAliasId> + '_ {
259 self.items.iter().filter_map(|(_name, item)| match item {
260 AssocItemId::TypeAliasId(t) => Some(*t),
265 pub fn associated_type_by_name(&self, name: &Name) -> Option<TypeAliasId> {
266 self.items.iter().find_map(|(item_name, item)| match item {
267 AssocItemId::TypeAliasId(t) if item_name == name => Some(*t),
272 pub fn method_by_name(&self, name: &Name) -> Option<FunctionId> {
273 self.items.iter().find_map(|(item_name, item)| match item {
274 AssocItemId::FunctionId(t) if item_name == name => Some(*t),
279 pub fn attribute_calls(&self) -> impl Iterator<Item = (AstId<ast::Item>, MacroCallId)> + '_ {
280 self.attribute_calls.iter().flat_map(|it| it.iter()).copied()
284 #[derive(Debug, Clone, PartialEq, Eq)]
285 pub struct ImplData {
286 pub target_trait: Option<Interned<TraitRef>>,
287 pub self_ty: Interned<TypeRef>,
288 pub items: Vec<AssocItemId>,
289 pub is_negative: bool,
290 // box it as the vec is usually empty anyways
291 pub attribute_calls: Option<Box<Vec<(AstId<ast::Item>, MacroCallId)>>>,
295 pub(crate) fn impl_data_query(db: &dyn DefDatabase, id: ImplId) -> Arc<ImplData> {
296 db.impl_data_with_diagnostics(id).0
299 pub(crate) fn impl_data_with_diagnostics_query(
300 db: &dyn DefDatabase,
302 ) -> (Arc<ImplData>, Arc<[DefDiagnostic]>) {
303 let _p = profile::span("impl_data_with_diagnostics_query");
304 let ItemLoc { container: module_id, id: tree_id } = id.lookup(db);
306 let item_tree = tree_id.item_tree(db);
307 let impl_def = &item_tree[tree_id.value];
308 let target_trait = impl_def.target_trait.clone();
309 let self_ty = impl_def.self_ty.clone();
310 let is_negative = impl_def.is_negative;
313 AssocItemCollector::new(db, module_id, tree_id.file_id(), ItemContainerId::ImplId(id));
314 collector.collect(&item_tree, tree_id.tree_id(), &impl_def.items);
316 let (items, attribute_calls, diagnostics) = collector.finish();
317 let items = items.into_iter().map(|(_, item)| item).collect();
320 Arc::new(ImplData { target_trait, self_ty, items, is_negative, attribute_calls }),
325 pub fn attribute_calls(&self) -> impl Iterator<Item = (AstId<ast::Item>, MacroCallId)> + '_ {
326 self.attribute_calls.iter().flat_map(|it| it.iter()).copied()
330 #[derive(Debug, Clone, PartialEq, Eq)]
331 pub struct Macro2Data {
333 pub visibility: RawVisibility,
337 pub(crate) fn macro2_data_query(db: &dyn DefDatabase, makro: Macro2Id) -> Arc<Macro2Data> {
338 let loc = makro.lookup(db);
339 let item_tree = loc.id.item_tree(db);
340 let makro = &item_tree[loc.id.value];
342 Arc::new(Macro2Data {
343 name: makro.name.clone(),
344 visibility: item_tree[makro.visibility].clone(),
348 #[derive(Debug, Clone, PartialEq, Eq)]
349 pub struct MacroRulesData {
351 pub macro_export: bool,
354 impl MacroRulesData {
355 pub(crate) fn macro_rules_data_query(
356 db: &dyn DefDatabase,
358 ) -> Arc<MacroRulesData> {
359 let loc = makro.lookup(db);
360 let item_tree = loc.id.item_tree(db);
361 let makro = &item_tree[loc.id.value];
363 let macro_export = item_tree
364 .attrs(db, loc.container.krate(), ModItem::from(loc.id.value).into())
365 .by_key("macro_export")
368 Arc::new(MacroRulesData { name: makro.name.clone(), macro_export })
371 #[derive(Debug, Clone, PartialEq, Eq)]
372 pub struct ProcMacroData {
374 /// Derive helpers, if this is a derive
375 pub helpers: Option<Box<[Name]>>,
379 pub(crate) fn proc_macro_data_query(
380 db: &dyn DefDatabase,
382 ) -> Arc<ProcMacroData> {
383 let loc = makro.lookup(db);
384 let item_tree = loc.id.item_tree(db);
385 let makro = &item_tree[loc.id.value];
387 let (name, helpers) = if let Some(def) = item_tree
388 .attrs(db, loc.container.krate(), ModItem::from(loc.id.value).into())
389 .parse_proc_macro_decl(&makro.name)
394 ProcMacroKind::CustomDerive { helpers } => Some(helpers),
395 ProcMacroKind::FnLike | ProcMacroKind::Attr => None,
400 stdx::never!("proc macro declaration is not a proc macro");
401 (makro.name.clone(), None)
403 Arc::new(ProcMacroData { name, helpers })
407 #[derive(Debug, Clone, PartialEq, Eq)]
408 pub struct ConstData {
409 /// `None` for `const _: () = ();`
410 pub name: Option<Name>,
411 pub type_ref: Interned<TypeRef>,
412 pub visibility: RawVisibility,
416 pub(crate) fn const_data_query(db: &dyn DefDatabase, konst: ConstId) -> Arc<ConstData> {
417 let loc = konst.lookup(db);
418 let item_tree = loc.id.item_tree(db);
419 let konst = &item_tree[loc.id.value];
420 let visibility = if let ItemContainerId::TraitId(trait_id) = loc.container {
421 db.trait_data(trait_id).visibility.clone()
423 item_tree[konst.visibility].clone()
427 name: konst.name.clone(),
428 type_ref: konst.type_ref.clone(),
434 #[derive(Debug, Clone, PartialEq, Eq)]
435 pub struct StaticData {
437 pub type_ref: Interned<TypeRef>,
438 pub visibility: RawVisibility,
444 pub(crate) fn static_data_query(db: &dyn DefDatabase, konst: StaticId) -> Arc<StaticData> {
445 let loc = konst.lookup(db);
446 let item_tree = loc.id.item_tree(db);
447 let statik = &item_tree[loc.id.value];
449 Arc::new(StaticData {
450 name: statik.name.clone(),
451 type_ref: statik.type_ref.clone(),
452 visibility: item_tree[statik.visibility].clone(),
453 mutable: statik.mutable,
454 is_extern: matches!(loc.container, ItemContainerId::ExternBlockId(_)),
459 struct AssocItemCollector<'a> {
460 db: &'a dyn DefDatabase,
462 def_map: Arc<DefMap>,
463 inactive_diagnostics: Vec<DefDiagnostic>,
464 container: ItemContainerId,
467 items: Vec<(Name, AssocItemId)>,
468 attr_calls: Vec<(AstId<ast::Item>, MacroCallId)>,
471 impl<'a> AssocItemCollector<'a> {
473 db: &'a dyn DefDatabase,
476 container: ItemContainerId,
481 def_map: module_id.def_map(db),
483 expander: Expander::new(db, file_id, module_id),
485 attr_calls: Vec::new(),
486 inactive_diagnostics: Vec::new(),
493 Vec<(Name, AssocItemId)>,
494 Option<Box<Vec<(AstId<ast::Item>, MacroCallId)>>>,
499 if self.attr_calls.is_empty() { None } else { Some(Box::new(self.attr_calls)) },
500 self.inactive_diagnostics,
504 // FIXME: proc-macro diagnostics
505 fn collect(&mut self, item_tree: &ItemTree, tree_id: TreeId, assoc_items: &[AssocItem]) {
506 let container = self.container;
507 self.items.reserve(assoc_items.len());
509 'items: for &item in assoc_items {
510 let attrs = item_tree.attrs(self.db, self.module_id.krate, ModItem::from(item).into());
511 if !attrs.is_cfg_enabled(self.expander.cfg_options()) {
512 self.inactive_diagnostics.push(DefDiagnostic::unconfigured_code(
513 self.module_id.local_id,
514 InFile::new(self.expander.current_file_id(), item.ast_id(&item_tree).upcast()),
515 attrs.cfg().unwrap(),
516 self.expander.cfg_options().clone(),
521 'attrs: for attr in &*attrs {
523 AstId::new(self.expander.current_file_id(), item.ast_id(&item_tree).upcast());
524 let ast_id_with_path = AstIdWithPath { path: (*attr.path).clone(), ast_id };
526 if let Ok(ResolvedAttr::Macro(call_id)) = self.def_map.resolve_attr_macro(
528 self.module_id.local_id,
532 self.attr_calls.push((ast_id, call_id));
533 // If proc attribute macro expansion is disabled, skip expanding it here
534 if !self.db.enable_proc_attr_macros() {
537 let loc = self.db.lookup_intern_macro_call(call_id);
538 if let MacroDefKind::ProcMacro(exp, ..) = loc.def.kind {
539 // If there's no expander for the proc macro (e.g. the
540 // proc macro is ignored, or building the proc macro
541 // crate failed), skip expansion like we would if it was
542 // disabled. This is analogous to the handling in
543 // `DefCollector::collect_macros`.
548 match self.expander.enter_expand_id::<ast::MacroItems>(self.db, call_id) {
549 ExpandResult { value: Some((mark, _)), .. } => {
550 self.collect_macro_items(mark);
553 ExpandResult { .. } => {}
559 AssocItem::Function(id) => {
560 let item = &item_tree[id];
563 FunctionLoc { container, id: ItemTreeId::new(tree_id, id) }.intern(self.db);
564 self.items.push((item.name.clone(), def.into()));
566 AssocItem::Const(id) => {
567 let item = &item_tree[id];
569 let name = match item.name.clone() {
574 ConstLoc { container, id: ItemTreeId::new(tree_id, id) }.intern(self.db);
575 self.items.push((name, def.into()));
577 AssocItem::TypeAlias(id) => {
578 let item = &item_tree[id];
580 let def = TypeAliasLoc { container, id: ItemTreeId::new(tree_id, id) }
582 self.items.push((item.name.clone(), def.into()));
584 AssocItem::MacroCall(call) => {
585 if let Some(root) = self.db.parse_or_expand(self.expander.current_file_id()) {
586 let call = &item_tree[call];
588 let ast_id_map = self.db.ast_id_map(self.expander.current_file_id());
589 let call = ast_id_map.get(call.ast_id).to_node(&root);
590 let _cx = stdx::panic_context::enter(format!(
591 "collect_items MacroCall: {}",
594 let res = self.expander.enter_expand::<ast::MacroItems>(self.db, call);
596 if let Ok(ExpandResult { value: Some((mark, _)), .. }) = res {
597 self.collect_macro_items(mark);
605 fn collect_macro_items(&mut self, mark: Mark) {
606 let tree_id = item_tree::TreeId::new(self.expander.current_file_id(), None);
607 let item_tree = tree_id.item_tree(self.db);
608 let iter: SmallVec<[_; 2]> =
609 item_tree.top_level_items().iter().filter_map(ModItem::as_assoc_item).collect();
611 self.collect(&item_tree, tree_id, &iter);
613 self.expander.exit(self.db, mark);