1 //! Contains basic data about various HIR declarations.
5 use hir_expand::{name::Name, AstId, ExpandResult, HirFileId, MacroCallId, MacroDefKind};
6 use smallvec::SmallVec;
11 body::{Expander, Mark},
14 item_tree::{self, AssocItem, FnFlags, ItemTree, ItemTreeId, ModItem, Param, TreeId},
15 nameres::{attr_resolution::ResolvedAttr, DefMap},
16 type_ref::{TraitRef, TypeBound, TypeRef},
17 visibility::RawVisibility,
18 AssocItemId, AstIdWithPath, ConstId, ConstLoc, FunctionId, FunctionLoc, HasModule, ImplId,
19 Intern, ItemContainerId, ItemLoc, Lookup, Macro2Id, MacroRulesId, ModuleId, ProcMacroId,
20 StaticId, TraitId, TypeAliasId, TypeAliasLoc,
23 #[derive(Debug, Clone, PartialEq, Eq)]
24 pub struct FunctionData {
26 pub params: Vec<(Option<Name>, Interned<TypeRef>)>,
27 pub ret_type: Interned<TypeRef>,
28 pub async_ret_type: Option<Interned<TypeRef>>,
30 pub visibility: RawVisibility,
31 pub abi: Option<Interned<str>>,
32 pub legacy_const_generics_indices: Box<[u32]>,
37 pub(crate) fn fn_data_query(db: &dyn DefDatabase, func: FunctionId) -> Arc<FunctionData> {
38 let loc = func.lookup(db);
39 let krate = loc.container.module(db).krate;
40 let crate_graph = db.crate_graph();
41 let cfg_options = &crate_graph[krate].cfg_options;
42 let item_tree = loc.id.item_tree(db);
43 let func = &item_tree[loc.id.value];
44 let visibility = if let ItemContainerId::TraitId(trait_id) = loc.container {
45 db.trait_data(trait_id).visibility.clone()
47 item_tree[func.visibility].clone()
50 let enabled_params = func
53 .filter(|¶m| item_tree.attrs(db, krate, param.into()).is_cfg_enabled(cfg_options));
55 // If last cfg-enabled param is a `...` param, it's a varargs function.
56 let is_varargs = enabled_params
59 .map_or(false, |param| matches!(item_tree[param], Param::Varargs));
61 let mut flags = func.flags;
63 flags |= FnFlags::IS_VARARGS;
65 if flags.contains(FnFlags::HAS_SELF_PARAM) {
66 // If there's a self param in the syntax, but it is cfg'd out, remove the flag.
67 let is_cfgd_out = match func.params.clone().next() {
69 !item_tree.attrs(db, krate, param.into()).is_cfg_enabled(cfg_options)
72 stdx::never!("fn HAS_SELF_PARAM but no parameters allocated");
77 cov_mark::hit!(cfgd_out_self_param);
78 flags.remove(FnFlags::HAS_SELF_PARAM);
82 let legacy_const_generics_indices = item_tree
83 .attrs(db, krate, ModItem::from(loc.id.value).into())
84 .by_key("rustc_legacy_const_generics")
87 .map(parse_rustc_legacy_const_generics)
90 Arc::new(FunctionData {
91 name: func.name.clone(),
92 params: enabled_params
94 .filter_map(|id| match &item_tree[id] {
95 Param::Normal(name, ty) => Some((name.clone(), ty.clone())),
96 Param::Varargs => None,
99 ret_type: func.ret_type.clone(),
100 async_ret_type: func.async_ret_type.clone(),
101 attrs: item_tree.attrs(db, krate, ModItem::from(loc.id.value).into()),
103 abi: func.abi.clone(),
104 legacy_const_generics_indices,
109 pub fn has_body(&self) -> bool {
110 self.flags.contains(FnFlags::HAS_BODY)
113 /// True if the first param is `self`. This is relevant to decide whether this
114 /// can be called as a method.
115 pub fn has_self_param(&self) -> bool {
116 self.flags.contains(FnFlags::HAS_SELF_PARAM)
119 pub fn has_default_kw(&self) -> bool {
120 self.flags.contains(FnFlags::HAS_DEFAULT_KW)
123 pub fn has_const_kw(&self) -> bool {
124 self.flags.contains(FnFlags::HAS_CONST_KW)
127 pub fn has_async_kw(&self) -> bool {
128 self.flags.contains(FnFlags::HAS_ASYNC_KW)
131 pub fn has_unsafe_kw(&self) -> bool {
132 self.flags.contains(FnFlags::HAS_UNSAFE_KW)
135 pub fn is_varargs(&self) -> bool {
136 self.flags.contains(FnFlags::IS_VARARGS)
140 fn parse_rustc_legacy_const_generics(tt: &tt::Subtree) -> Box<[u32]> {
141 let mut indices = Vec::new();
142 for args in tt.token_trees.chunks(2) {
144 tt::TokenTree::Leaf(tt::Leaf::Literal(lit)) => match lit.text.parse() {
145 Ok(index) => indices.push(index),
151 if let Some(comma) = args.get(1) {
153 tt::TokenTree::Leaf(tt::Leaf::Punct(punct)) if punct.char == ',' => {}
159 indices.into_boxed_slice()
162 #[derive(Debug, Clone, PartialEq, Eq)]
163 pub struct TypeAliasData {
165 pub type_ref: Option<Interned<TypeRef>>,
166 pub visibility: RawVisibility,
168 /// Bounds restricting the type alias itself (eg. `type Ty: Bound;` in a trait or impl).
169 pub bounds: Vec<Interned<TypeBound>>,
173 pub(crate) fn type_alias_data_query(
174 db: &dyn DefDatabase,
176 ) -> Arc<TypeAliasData> {
177 let loc = typ.lookup(db);
178 let item_tree = loc.id.item_tree(db);
179 let typ = &item_tree[loc.id.value];
180 let visibility = if let ItemContainerId::TraitId(trait_id) = loc.container {
181 db.trait_data(trait_id).visibility.clone()
183 item_tree[typ.visibility].clone()
186 Arc::new(TypeAliasData {
187 name: typ.name.clone(),
188 type_ref: typ.type_ref.clone(),
190 is_extern: matches!(loc.container, ItemContainerId::ExternBlockId(_)),
191 bounds: typ.bounds.to_vec(),
196 #[derive(Debug, Clone, PartialEq, Eq)]
197 pub struct TraitData {
199 pub items: Vec<(Name, AssocItemId)>,
202 pub visibility: RawVisibility,
203 /// Whether the trait has `#[rust_skip_array_during_method_dispatch]`. `hir_ty` will ignore
204 /// method calls to this trait's methods when the receiver is an array and the crate edition is
206 pub skip_array_during_method_dispatch: bool,
207 // box it as the vec is usually empty anyways
208 pub attribute_calls: Option<Box<Vec<(AstId<ast::Item>, MacroCallId)>>>,
212 pub(crate) fn trait_data_query(db: &dyn DefDatabase, tr: TraitId) -> Arc<TraitData> {
213 let tr_loc @ ItemLoc { container: module_id, id: tree_id } = tr.lookup(db);
214 let item_tree = tree_id.item_tree(db);
215 let tr_def = &item_tree[tree_id.value];
216 let _cx = stdx::panic_context::enter(format!(
217 "trait_data_query({:?} -> {:?} -> {:?})",
220 let name = tr_def.name.clone();
221 let is_auto = tr_def.is_auto;
222 let is_unsafe = tr_def.is_unsafe;
223 let visibility = item_tree[tr_def.visibility].clone();
224 let skip_array_during_method_dispatch = item_tree
225 .attrs(db, module_id.krate(), ModItem::from(tree_id.value).into())
226 .by_key("rustc_skip_array_during_method_dispatch")
230 AssocItemCollector::new(db, module_id, tree_id.file_id(), ItemContainerId::TraitId(tr));
231 collector.collect(&item_tree, tree_id.tree_id(), &tr_def.items);
232 let (items, attribute_calls) = collector.finish();
241 skip_array_during_method_dispatch,
245 pub fn associated_types(&self) -> impl Iterator<Item = TypeAliasId> + '_ {
246 self.items.iter().filter_map(|(_name, item)| match item {
247 AssocItemId::TypeAliasId(t) => Some(*t),
252 pub fn associated_type_by_name(&self, name: &Name) -> Option<TypeAliasId> {
253 self.items.iter().find_map(|(item_name, item)| match item {
254 AssocItemId::TypeAliasId(t) if item_name == name => Some(*t),
259 pub fn method_by_name(&self, name: &Name) -> Option<FunctionId> {
260 self.items.iter().find_map(|(item_name, item)| match item {
261 AssocItemId::FunctionId(t) if item_name == name => Some(*t),
266 pub fn attribute_calls(&self) -> impl Iterator<Item = (AstId<ast::Item>, MacroCallId)> + '_ {
267 self.attribute_calls.iter().flat_map(|it| it.iter()).copied()
271 #[derive(Debug, Clone, PartialEq, Eq)]
272 pub struct ImplData {
273 pub target_trait: Option<Interned<TraitRef>>,
274 pub self_ty: Interned<TypeRef>,
275 pub items: Vec<AssocItemId>,
276 pub is_negative: bool,
277 // box it as the vec is usually empty anyways
278 pub attribute_calls: Option<Box<Vec<(AstId<ast::Item>, MacroCallId)>>>,
282 pub(crate) fn impl_data_query(db: &dyn DefDatabase, id: ImplId) -> Arc<ImplData> {
283 let _p = profile::span("impl_data_query");
284 let ItemLoc { container: module_id, id: tree_id } = id.lookup(db);
286 let item_tree = tree_id.item_tree(db);
287 let impl_def = &item_tree[tree_id.value];
288 let target_trait = impl_def.target_trait.clone();
289 let self_ty = impl_def.self_ty.clone();
290 let is_negative = impl_def.is_negative;
293 AssocItemCollector::new(db, module_id, tree_id.file_id(), ItemContainerId::ImplId(id));
294 collector.collect(&item_tree, tree_id.tree_id(), &impl_def.items);
296 let (items, attribute_calls) = collector.finish();
297 let items = items.into_iter().map(|(_, item)| item).collect();
299 Arc::new(ImplData { target_trait, self_ty, items, is_negative, attribute_calls })
302 pub fn attribute_calls(&self) -> impl Iterator<Item = (AstId<ast::Item>, MacroCallId)> + '_ {
303 self.attribute_calls.iter().flat_map(|it| it.iter()).copied()
307 #[derive(Debug, Clone, PartialEq, Eq)]
308 pub struct Macro2Data {
310 pub visibility: RawVisibility,
314 pub(crate) fn macro2_data_query(db: &dyn DefDatabase, makro: Macro2Id) -> Arc<Macro2Data> {
315 let loc = makro.lookup(db);
316 let item_tree = loc.id.item_tree(db);
317 let makro = &item_tree[loc.id.value];
319 Arc::new(Macro2Data {
320 name: makro.name.clone(),
321 visibility: item_tree[makro.visibility].clone(),
325 #[derive(Debug, Clone, PartialEq, Eq)]
326 pub struct MacroRulesData {
328 pub macro_export: bool,
331 impl MacroRulesData {
332 pub(crate) fn macro_rules_data_query(
333 db: &dyn DefDatabase,
335 ) -> Arc<MacroRulesData> {
336 let loc = makro.lookup(db);
337 let item_tree = loc.id.item_tree(db);
338 let makro = &item_tree[loc.id.value];
340 let macro_export = item_tree
341 .attrs(db, loc.container.krate(), ModItem::from(loc.id.value).into())
342 .by_key("macro_export")
345 Arc::new(MacroRulesData { name: makro.name.clone(), macro_export })
348 #[derive(Debug, Clone, PartialEq, Eq)]
349 pub struct ProcMacroData {
351 // FIXME: Record deriver helper here?
355 pub(crate) fn proc_macro_data_query(
356 db: &dyn DefDatabase,
358 ) -> Arc<ProcMacroData> {
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 name = if let Some(def) = item_tree
364 .attrs(db, loc.container.krate(), ModItem::from(loc.id.value).into())
365 .parse_proc_macro_decl(&makro.name)
370 stdx::never!("proc macro declaration is not a proc macro");
373 Arc::new(ProcMacroData { name })
377 #[derive(Debug, Clone, PartialEq, Eq)]
378 pub struct ConstData {
379 /// `None` for `const _: () = ();`
380 pub name: Option<Name>,
381 pub type_ref: Interned<TypeRef>,
382 pub visibility: RawVisibility,
386 pub(crate) fn const_data_query(db: &dyn DefDatabase, konst: ConstId) -> Arc<ConstData> {
387 let loc = konst.lookup(db);
388 let item_tree = loc.id.item_tree(db);
389 let konst = &item_tree[loc.id.value];
390 let visibility = if let ItemContainerId::TraitId(trait_id) = loc.container {
391 db.trait_data(trait_id).visibility.clone()
393 item_tree[konst.visibility].clone()
397 name: konst.name.clone(),
398 type_ref: konst.type_ref.clone(),
404 #[derive(Debug, Clone, PartialEq, Eq)]
405 pub struct StaticData {
407 pub type_ref: Interned<TypeRef>,
408 pub visibility: RawVisibility,
414 pub(crate) fn static_data_query(db: &dyn DefDatabase, konst: StaticId) -> Arc<StaticData> {
415 let loc = konst.lookup(db);
416 let item_tree = loc.id.item_tree(db);
417 let statik = &item_tree[loc.id.value];
419 Arc::new(StaticData {
420 name: statik.name.clone(),
421 type_ref: statik.type_ref.clone(),
422 visibility: item_tree[statik.visibility].clone(),
423 mutable: statik.mutable,
424 is_extern: matches!(loc.container, ItemContainerId::ExternBlockId(_)),
429 struct AssocItemCollector<'a> {
430 db: &'a dyn DefDatabase,
432 def_map: Arc<DefMap>,
433 container: ItemContainerId,
436 items: Vec<(Name, AssocItemId)>,
437 attr_calls: Vec<(AstId<ast::Item>, MacroCallId)>,
440 impl<'a> AssocItemCollector<'a> {
442 db: &'a dyn DefDatabase,
445 container: ItemContainerId,
450 def_map: module_id.def_map(db),
452 expander: Expander::new(db, file_id, module_id),
454 attr_calls: Vec::new(),
460 ) -> (Vec<(Name, AssocItemId)>, Option<Box<Vec<(AstId<ast::Item>, MacroCallId)>>>) {
463 if self.attr_calls.is_empty() { None } else { Some(Box::new(self.attr_calls)) },
467 // FIXME: proc-macro diagnostics
468 fn collect(&mut self, item_tree: &ItemTree, tree_id: TreeId, assoc_items: &[AssocItem]) {
469 let container = self.container;
470 self.items.reserve(assoc_items.len());
472 'items: for &item in assoc_items {
473 let attrs = item_tree.attrs(self.db, self.module_id.krate, ModItem::from(item).into());
474 if !attrs.is_cfg_enabled(self.expander.cfg_options()) {
478 'attrs: for attr in &*attrs {
480 AstId::new(self.expander.current_file_id(), item.ast_id(&item_tree).upcast());
481 let ast_id_with_path = AstIdWithPath { path: (*attr.path).clone(), ast_id };
483 if let Ok(ResolvedAttr::Macro(call_id)) = self.def_map.resolve_attr_macro(
485 self.module_id.local_id,
489 self.attr_calls.push((ast_id, call_id));
490 // If proc attribute macro expansion is disabled, skip expanding it here
491 if !self.db.enable_proc_attr_macros() {
494 let loc = self.db.lookup_intern_macro_call(call_id);
495 if let MacroDefKind::ProcMacro(exp, ..) = loc.def.kind {
496 // If there's no expander for the proc macro (e.g. the
497 // proc macro is ignored, or building the proc macro
498 // crate failed), skip expansion like we would if it was
499 // disabled. This is analogous to the handling in
500 // `DefCollector::collect_macros`.
505 match self.expander.enter_expand_id::<ast::MacroItems>(self.db, call_id) {
506 ExpandResult { value: Some((mark, _)), .. } => {
507 self.collect_macro_items(mark);
510 ExpandResult { .. } => {}
516 AssocItem::Function(id) => {
517 let item = &item_tree[id];
520 FunctionLoc { container, id: ItemTreeId::new(tree_id, id) }.intern(self.db);
521 self.items.push((item.name.clone(), def.into()));
523 AssocItem::Const(id) => {
524 let item = &item_tree[id];
526 let name = match item.name.clone() {
531 ConstLoc { container, id: ItemTreeId::new(tree_id, id) }.intern(self.db);
532 self.items.push((name, def.into()));
534 AssocItem::TypeAlias(id) => {
535 let item = &item_tree[id];
537 let def = TypeAliasLoc { container, id: ItemTreeId::new(tree_id, id) }
539 self.items.push((item.name.clone(), def.into()));
541 AssocItem::MacroCall(call) => {
542 if let Some(root) = self.db.parse_or_expand(self.expander.current_file_id()) {
543 let call = &item_tree[call];
545 let ast_id_map = self.db.ast_id_map(self.expander.current_file_id());
546 let call = ast_id_map.get(call.ast_id).to_node(&root);
547 let _cx = stdx::panic_context::enter(format!(
548 "collect_items MacroCall: {}",
551 let res = self.expander.enter_expand::<ast::MacroItems>(self.db, call);
553 if let Ok(ExpandResult { value: Some((mark, _)), .. }) = res {
554 self.collect_macro_items(mark);
562 fn collect_macro_items(&mut self, mark: Mark) {
563 let tree_id = item_tree::TreeId::new(self.expander.current_file_id(), None);
564 let item_tree = tree_id.item_tree(self.db);
565 let iter: SmallVec<[_; 2]> =
566 item_tree.top_level_items().iter().filter_map(ModItem::as_assoc_item).collect();
568 self.collect(&item_tree, tree_id, &iter);
570 self.expander.exit(self.db, mark);