• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! Contains basic data about various HIR declarations.
2 
3 pub mod adt;
4 
5 use hir_expand::{
6     name::Name, AstId, ExpandResult, HirFileId, InFile, MacroCallId, MacroCallKind, MacroDefKind,
7 };
8 use intern::Interned;
9 use smallvec::SmallVec;
10 use syntax::{ast, Parse};
11 use triomphe::Arc;
12 
13 use crate::{
14     attr::Attrs,
15     db::DefDatabase,
16     expander::{Expander, Mark},
17     item_tree::{
18         self, AssocItem, FnFlags, ItemTree, ItemTreeId, MacroCall, ModItem, Param, TreeId,
19     },
20     macro_call_as_call_id, macro_id_to_def_id,
21     nameres::{
22         attr_resolution::ResolvedAttr,
23         diagnostics::DefDiagnostic,
24         proc_macro::{parse_macro_name_and_helper_attrs, ProcMacroKind},
25         DefMap, MacroSubNs,
26     },
27     type_ref::{TraitRef, TypeBound, TypeRef},
28     visibility::RawVisibility,
29     AssocItemId, AstIdWithPath, ConstId, ConstLoc, FunctionId, FunctionLoc, HasModule, ImplId,
30     Intern, ItemContainerId, ItemLoc, Lookup, Macro2Id, MacroRulesId, ModuleId, ProcMacroId,
31     StaticId, TraitAliasId, TraitId, TypeAliasId, TypeAliasLoc,
32 };
33 
34 #[derive(Debug, Clone, PartialEq, Eq)]
35 pub struct FunctionData {
36     pub name: Name,
37     pub params: Vec<Interned<TypeRef>>,
38     pub ret_type: Interned<TypeRef>,
39     pub attrs: Attrs,
40     pub visibility: RawVisibility,
41     pub abi: Option<Interned<str>>,
42     pub legacy_const_generics_indices: Box<[u32]>,
43     pub rustc_allow_incoherent_impl: bool,
44     flags: FnFlags,
45 }
46 
47 impl FunctionData {
fn_data_query(db: &dyn DefDatabase, func: FunctionId) -> Arc<FunctionData>48     pub(crate) fn fn_data_query(db: &dyn DefDatabase, func: FunctionId) -> Arc<FunctionData> {
49         let loc = func.lookup(db);
50         let krate = loc.container.module(db).krate;
51         let item_tree = loc.id.item_tree(db);
52         let func = &item_tree[loc.id.value];
53         let visibility = if let ItemContainerId::TraitId(trait_id) = loc.container {
54             trait_vis(db, trait_id)
55         } else {
56             item_tree[func.visibility].clone()
57         };
58 
59         let crate_graph = db.crate_graph();
60         let cfg_options = &crate_graph[krate].cfg_options;
61         let enabled_params = func
62             .params
63             .clone()
64             .filter(|&param| item_tree.attrs(db, krate, param.into()).is_cfg_enabled(cfg_options));
65 
66         // If last cfg-enabled param is a `...` param, it's a varargs function.
67         let is_varargs = enabled_params
68             .clone()
69             .next_back()
70             .map_or(false, |param| matches!(item_tree[param], Param::Varargs));
71 
72         let mut flags = func.flags;
73         if is_varargs {
74             flags |= FnFlags::IS_VARARGS;
75         }
76         if flags.contains(FnFlags::HAS_SELF_PARAM) {
77             // If there's a self param in the syntax, but it is cfg'd out, remove the flag.
78             let is_cfgd_out = match func.params.clone().next() {
79                 Some(param) => {
80                     !item_tree.attrs(db, krate, param.into()).is_cfg_enabled(cfg_options)
81                 }
82                 None => {
83                     stdx::never!("fn HAS_SELF_PARAM but no parameters allocated");
84                     true
85                 }
86             };
87             if is_cfgd_out {
88                 cov_mark::hit!(cfgd_out_self_param);
89                 flags.remove(FnFlags::HAS_SELF_PARAM);
90             }
91         }
92 
93         let attrs = item_tree.attrs(db, krate, ModItem::from(loc.id.value).into());
94         let legacy_const_generics_indices = attrs
95             .by_key("rustc_legacy_const_generics")
96             .tt_values()
97             .next()
98             .map(parse_rustc_legacy_const_generics)
99             .unwrap_or_default();
100         let rustc_allow_incoherent_impl = attrs.by_key("rustc_allow_incoherent_impl").exists();
101 
102         Arc::new(FunctionData {
103             name: func.name.clone(),
104             params: enabled_params
105                 .clone()
106                 .filter_map(|id| match &item_tree[id] {
107                     Param::Normal(ty) => Some(ty.clone()),
108                     Param::Varargs => None,
109                 })
110                 .collect(),
111             ret_type: func.ret_type.clone(),
112             attrs: item_tree.attrs(db, krate, ModItem::from(loc.id.value).into()),
113             visibility,
114             abi: func.abi.clone(),
115             legacy_const_generics_indices,
116             flags,
117             rustc_allow_incoherent_impl,
118         })
119     }
120 
has_body(&self) -> bool121     pub fn has_body(&self) -> bool {
122         self.flags.contains(FnFlags::HAS_BODY)
123     }
124 
125     /// True if the first param is `self`. This is relevant to decide whether this
126     /// can be called as a method.
has_self_param(&self) -> bool127     pub fn has_self_param(&self) -> bool {
128         self.flags.contains(FnFlags::HAS_SELF_PARAM)
129     }
130 
has_default_kw(&self) -> bool131     pub fn has_default_kw(&self) -> bool {
132         self.flags.contains(FnFlags::HAS_DEFAULT_KW)
133     }
134 
has_const_kw(&self) -> bool135     pub fn has_const_kw(&self) -> bool {
136         self.flags.contains(FnFlags::HAS_CONST_KW)
137     }
138 
has_async_kw(&self) -> bool139     pub fn has_async_kw(&self) -> bool {
140         self.flags.contains(FnFlags::HAS_ASYNC_KW)
141     }
142 
has_unsafe_kw(&self) -> bool143     pub fn has_unsafe_kw(&self) -> bool {
144         self.flags.contains(FnFlags::HAS_UNSAFE_KW)
145     }
146 
is_varargs(&self) -> bool147     pub fn is_varargs(&self) -> bool {
148         self.flags.contains(FnFlags::IS_VARARGS)
149     }
150 }
151 
parse_rustc_legacy_const_generics(tt: &crate::tt::Subtree) -> Box<[u32]>152 fn parse_rustc_legacy_const_generics(tt: &crate::tt::Subtree) -> Box<[u32]> {
153     let mut indices = Vec::new();
154     for args in tt.token_trees.chunks(2) {
155         match &args[0] {
156             tt::TokenTree::Leaf(tt::Leaf::Literal(lit)) => match lit.text.parse() {
157                 Ok(index) => indices.push(index),
158                 Err(_) => break,
159             },
160             _ => break,
161         }
162 
163         if let Some(comma) = args.get(1) {
164             match comma {
165                 tt::TokenTree::Leaf(tt::Leaf::Punct(punct)) if punct.char == ',' => {}
166                 _ => break,
167             }
168         }
169     }
170 
171     indices.into_boxed_slice()
172 }
173 
174 #[derive(Debug, Clone, PartialEq, Eq)]
175 pub struct TypeAliasData {
176     pub name: Name,
177     pub type_ref: Option<Interned<TypeRef>>,
178     pub visibility: RawVisibility,
179     pub is_extern: bool,
180     pub rustc_has_incoherent_inherent_impls: bool,
181     pub rustc_allow_incoherent_impl: bool,
182     /// Bounds restricting the type alias itself (eg. `type Ty: Bound;` in a trait or impl).
183     pub bounds: Vec<Interned<TypeBound>>,
184 }
185 
186 impl TypeAliasData {
type_alias_data_query( db: &dyn DefDatabase, typ: TypeAliasId, ) -> Arc<TypeAliasData>187     pub(crate) fn type_alias_data_query(
188         db: &dyn DefDatabase,
189         typ: TypeAliasId,
190     ) -> Arc<TypeAliasData> {
191         let loc = typ.lookup(db);
192         let item_tree = loc.id.item_tree(db);
193         let typ = &item_tree[loc.id.value];
194         let visibility = if let ItemContainerId::TraitId(trait_id) = loc.container {
195             trait_vis(db, trait_id)
196         } else {
197             item_tree[typ.visibility].clone()
198         };
199 
200         let attrs = item_tree.attrs(
201             db,
202             loc.container.module(db).krate(),
203             ModItem::from(loc.id.value).into(),
204         );
205         let rustc_has_incoherent_inherent_impls =
206             attrs.by_key("rustc_has_incoherent_inherent_impls").exists();
207         let rustc_allow_incoherent_impl = attrs.by_key("rustc_allow_incoherent_impl").exists();
208 
209         Arc::new(TypeAliasData {
210             name: typ.name.clone(),
211             type_ref: typ.type_ref.clone(),
212             visibility,
213             is_extern: matches!(loc.container, ItemContainerId::ExternBlockId(_)),
214             rustc_has_incoherent_inherent_impls,
215             rustc_allow_incoherent_impl,
216             bounds: typ.bounds.to_vec(),
217         })
218     }
219 }
220 
221 #[derive(Debug, Clone, PartialEq, Eq)]
222 pub struct TraitData {
223     pub name: Name,
224     pub items: Vec<(Name, AssocItemId)>,
225     pub is_auto: bool,
226     pub is_unsafe: bool,
227     pub rustc_has_incoherent_inherent_impls: bool,
228     pub skip_array_during_method_dispatch: bool,
229     pub fundamental: bool,
230     pub visibility: RawVisibility,
231     /// Whether the trait has `#[rust_skip_array_during_method_dispatch]`. `hir_ty` will ignore
232     /// method calls to this trait's methods when the receiver is an array and the crate edition is
233     /// 2015 or 2018.
234     // box it as the vec is usually empty anyways
235     pub attribute_calls: Option<Box<Vec<(AstId<ast::Item>, MacroCallId)>>>,
236 }
237 
238 impl TraitData {
trait_data_query(db: &dyn DefDatabase, tr: TraitId) -> Arc<TraitData>239     pub(crate) fn trait_data_query(db: &dyn DefDatabase, tr: TraitId) -> Arc<TraitData> {
240         db.trait_data_with_diagnostics(tr).0
241     }
242 
trait_data_with_diagnostics_query( db: &dyn DefDatabase, tr: TraitId, ) -> (Arc<TraitData>, Arc<[DefDiagnostic]>)243     pub(crate) fn trait_data_with_diagnostics_query(
244         db: &dyn DefDatabase,
245         tr: TraitId,
246     ) -> (Arc<TraitData>, Arc<[DefDiagnostic]>) {
247         let tr_loc @ ItemLoc { container: module_id, id: tree_id } = tr.lookup(db);
248         let item_tree = tree_id.item_tree(db);
249         let tr_def = &item_tree[tree_id.value];
250         let _cx = stdx::panic_context::enter(format!(
251             "trait_data_query({tr:?} -> {tr_loc:?} -> {tr_def:?})"
252         ));
253         let name = tr_def.name.clone();
254         let is_auto = tr_def.is_auto;
255         let is_unsafe = tr_def.is_unsafe;
256         let visibility = item_tree[tr_def.visibility].clone();
257         let attrs = item_tree.attrs(db, module_id.krate(), ModItem::from(tree_id.value).into());
258         let skip_array_during_method_dispatch =
259             attrs.by_key("rustc_skip_array_during_method_dispatch").exists();
260         let rustc_has_incoherent_inherent_impls =
261             attrs.by_key("rustc_has_incoherent_inherent_impls").exists();
262         let fundamental = attrs.by_key("fundamental").exists();
263         let mut collector =
264             AssocItemCollector::new(db, module_id, tree_id.file_id(), ItemContainerId::TraitId(tr));
265         collector.collect(&item_tree, tree_id.tree_id(), &tr_def.items);
266         let (items, attribute_calls, diagnostics) = collector.finish();
267 
268         (
269             Arc::new(TraitData {
270                 name,
271                 attribute_calls,
272                 items,
273                 is_auto,
274                 is_unsafe,
275                 visibility,
276                 skip_array_during_method_dispatch,
277                 rustc_has_incoherent_inherent_impls,
278                 fundamental,
279             }),
280             diagnostics.into(),
281         )
282     }
283 
associated_types(&self) -> impl Iterator<Item = TypeAliasId> + '_284     pub fn associated_types(&self) -> impl Iterator<Item = TypeAliasId> + '_ {
285         self.items.iter().filter_map(|(_name, item)| match item {
286             AssocItemId::TypeAliasId(t) => Some(*t),
287             _ => None,
288         })
289     }
290 
associated_type_by_name(&self, name: &Name) -> Option<TypeAliasId>291     pub fn associated_type_by_name(&self, name: &Name) -> Option<TypeAliasId> {
292         self.items.iter().find_map(|(item_name, item)| match item {
293             AssocItemId::TypeAliasId(t) if item_name == name => Some(*t),
294             _ => None,
295         })
296     }
297 
method_by_name(&self, name: &Name) -> Option<FunctionId>298     pub fn method_by_name(&self, name: &Name) -> Option<FunctionId> {
299         self.items.iter().find_map(|(item_name, item)| match item {
300             AssocItemId::FunctionId(t) if item_name == name => Some(*t),
301             _ => None,
302         })
303     }
304 
attribute_calls(&self) -> impl Iterator<Item = (AstId<ast::Item>, MacroCallId)> + '_305     pub fn attribute_calls(&self) -> impl Iterator<Item = (AstId<ast::Item>, MacroCallId)> + '_ {
306         self.attribute_calls.iter().flat_map(|it| it.iter()).copied()
307     }
308 }
309 
310 #[derive(Debug, Clone, PartialEq, Eq)]
311 pub struct TraitAliasData {
312     pub name: Name,
313     pub visibility: RawVisibility,
314 }
315 
316 impl TraitAliasData {
trait_alias_query(db: &dyn DefDatabase, id: TraitAliasId) -> Arc<TraitAliasData>317     pub(crate) fn trait_alias_query(db: &dyn DefDatabase, id: TraitAliasId) -> Arc<TraitAliasData> {
318         let loc = id.lookup(db);
319         let item_tree = loc.id.item_tree(db);
320         let alias = &item_tree[loc.id.value];
321         let visibility = item_tree[alias.visibility].clone();
322 
323         Arc::new(TraitAliasData { name: alias.name.clone(), visibility })
324     }
325 }
326 
327 #[derive(Debug, Clone, PartialEq, Eq)]
328 pub struct ImplData {
329     pub target_trait: Option<Interned<TraitRef>>,
330     pub self_ty: Interned<TypeRef>,
331     pub items: Vec<AssocItemId>,
332     pub is_negative: bool,
333     // box it as the vec is usually empty anyways
334     pub attribute_calls: Option<Box<Vec<(AstId<ast::Item>, MacroCallId)>>>,
335 }
336 
337 impl ImplData {
impl_data_query(db: &dyn DefDatabase, id: ImplId) -> Arc<ImplData>338     pub(crate) fn impl_data_query(db: &dyn DefDatabase, id: ImplId) -> Arc<ImplData> {
339         db.impl_data_with_diagnostics(id).0
340     }
341 
impl_data_with_diagnostics_query( db: &dyn DefDatabase, id: ImplId, ) -> (Arc<ImplData>, Arc<[DefDiagnostic]>)342     pub(crate) fn impl_data_with_diagnostics_query(
343         db: &dyn DefDatabase,
344         id: ImplId,
345     ) -> (Arc<ImplData>, Arc<[DefDiagnostic]>) {
346         let _p = profile::span("impl_data_with_diagnostics_query");
347         let ItemLoc { container: module_id, id: tree_id } = id.lookup(db);
348 
349         let item_tree = tree_id.item_tree(db);
350         let impl_def = &item_tree[tree_id.value];
351         let target_trait = impl_def.target_trait.clone();
352         let self_ty = impl_def.self_ty.clone();
353         let is_negative = impl_def.is_negative;
354 
355         let mut collector =
356             AssocItemCollector::new(db, module_id, tree_id.file_id(), ItemContainerId::ImplId(id));
357         collector.collect(&item_tree, tree_id.tree_id(), &impl_def.items);
358 
359         let (items, attribute_calls, diagnostics) = collector.finish();
360         let items = items.into_iter().map(|(_, item)| item).collect();
361 
362         (
363             Arc::new(ImplData { target_trait, self_ty, items, is_negative, attribute_calls }),
364             diagnostics.into(),
365         )
366     }
367 
attribute_calls(&self) -> impl Iterator<Item = (AstId<ast::Item>, MacroCallId)> + '_368     pub fn attribute_calls(&self) -> impl Iterator<Item = (AstId<ast::Item>, MacroCallId)> + '_ {
369         self.attribute_calls.iter().flat_map(|it| it.iter()).copied()
370     }
371 }
372 
373 #[derive(Debug, Clone, PartialEq, Eq)]
374 pub struct Macro2Data {
375     pub name: Name,
376     pub visibility: RawVisibility,
377     // It's a bit wasteful as currently this is only for builtin `Default` derive macro, but macro2
378     // are rarely used in practice so I think it's okay for now.
379     /// Derive helpers, if this is a derive rustc_builtin_macro
380     pub helpers: Option<Box<[Name]>>,
381 }
382 
383 impl Macro2Data {
macro2_data_query(db: &dyn DefDatabase, makro: Macro2Id) -> Arc<Macro2Data>384     pub(crate) fn macro2_data_query(db: &dyn DefDatabase, makro: Macro2Id) -> Arc<Macro2Data> {
385         let loc = makro.lookup(db);
386         let item_tree = loc.id.item_tree(db);
387         let makro = &item_tree[loc.id.value];
388 
389         let helpers = item_tree
390             .attrs(db, loc.container.krate(), ModItem::from(loc.id.value).into())
391             .by_key("rustc_builtin_macro")
392             .tt_values()
393             .next()
394             .and_then(|attr| parse_macro_name_and_helper_attrs(&attr.token_trees))
395             .map(|(_, helpers)| helpers);
396 
397         Arc::new(Macro2Data {
398             name: makro.name.clone(),
399             visibility: item_tree[makro.visibility].clone(),
400             helpers,
401         })
402     }
403 }
404 #[derive(Debug, Clone, PartialEq, Eq)]
405 pub struct MacroRulesData {
406     pub name: Name,
407     pub macro_export: bool,
408 }
409 
410 impl MacroRulesData {
macro_rules_data_query( db: &dyn DefDatabase, makro: MacroRulesId, ) -> Arc<MacroRulesData>411     pub(crate) fn macro_rules_data_query(
412         db: &dyn DefDatabase,
413         makro: MacroRulesId,
414     ) -> Arc<MacroRulesData> {
415         let loc = makro.lookup(db);
416         let item_tree = loc.id.item_tree(db);
417         let makro = &item_tree[loc.id.value];
418 
419         let macro_export = item_tree
420             .attrs(db, loc.container.krate(), ModItem::from(loc.id.value).into())
421             .by_key("macro_export")
422             .exists();
423 
424         Arc::new(MacroRulesData { name: makro.name.clone(), macro_export })
425     }
426 }
427 #[derive(Debug, Clone, PartialEq, Eq)]
428 pub struct ProcMacroData {
429     pub name: Name,
430     /// Derive helpers, if this is a derive
431     pub helpers: Option<Box<[Name]>>,
432 }
433 
434 impl ProcMacroData {
proc_macro_data_query( db: &dyn DefDatabase, makro: ProcMacroId, ) -> Arc<ProcMacroData>435     pub(crate) fn proc_macro_data_query(
436         db: &dyn DefDatabase,
437         makro: ProcMacroId,
438     ) -> Arc<ProcMacroData> {
439         let loc = makro.lookup(db);
440         let item_tree = loc.id.item_tree(db);
441         let makro = &item_tree[loc.id.value];
442 
443         let (name, helpers) = if let Some(def) = item_tree
444             .attrs(db, loc.container.krate(), ModItem::from(loc.id.value).into())
445             .parse_proc_macro_decl(&makro.name)
446         {
447             (
448                 def.name,
449                 match def.kind {
450                     ProcMacroKind::CustomDerive { helpers } => Some(helpers),
451                     ProcMacroKind::FnLike | ProcMacroKind::Attr => None,
452                 },
453             )
454         } else {
455             // eeeh...
456             stdx::never!("proc macro declaration is not a proc macro");
457             (makro.name.clone(), None)
458         };
459         Arc::new(ProcMacroData { name, helpers })
460     }
461 }
462 
463 #[derive(Debug, Clone, PartialEq, Eq)]
464 pub struct ConstData {
465     /// `None` for `const _: () = ();`
466     pub name: Option<Name>,
467     pub type_ref: Interned<TypeRef>,
468     pub visibility: RawVisibility,
469     pub rustc_allow_incoherent_impl: bool,
470 }
471 
472 impl ConstData {
const_data_query(db: &dyn DefDatabase, konst: ConstId) -> Arc<ConstData>473     pub(crate) fn const_data_query(db: &dyn DefDatabase, konst: ConstId) -> Arc<ConstData> {
474         let loc = konst.lookup(db);
475         let item_tree = loc.id.item_tree(db);
476         let konst = &item_tree[loc.id.value];
477         let visibility = if let ItemContainerId::TraitId(trait_id) = loc.container {
478             trait_vis(db, trait_id)
479         } else {
480             item_tree[konst.visibility].clone()
481         };
482 
483         let rustc_allow_incoherent_impl = item_tree
484             .attrs(db, loc.container.module(db).krate(), ModItem::from(loc.id.value).into())
485             .by_key("rustc_allow_incoherent_impl")
486             .exists();
487 
488         Arc::new(ConstData {
489             name: konst.name.clone(),
490             type_ref: konst.type_ref.clone(),
491             visibility,
492             rustc_allow_incoherent_impl,
493         })
494     }
495 }
496 
497 #[derive(Debug, Clone, PartialEq, Eq)]
498 pub struct StaticData {
499     pub name: Name,
500     pub type_ref: Interned<TypeRef>,
501     pub visibility: RawVisibility,
502     pub mutable: bool,
503     pub is_extern: bool,
504 }
505 
506 impl StaticData {
static_data_query(db: &dyn DefDatabase, konst: StaticId) -> Arc<StaticData>507     pub(crate) fn static_data_query(db: &dyn DefDatabase, konst: StaticId) -> Arc<StaticData> {
508         let loc = konst.lookup(db);
509         let item_tree = loc.id.item_tree(db);
510         let statik = &item_tree[loc.id.value];
511 
512         Arc::new(StaticData {
513             name: statik.name.clone(),
514             type_ref: statik.type_ref.clone(),
515             visibility: item_tree[statik.visibility].clone(),
516             mutable: statik.mutable,
517             is_extern: matches!(loc.container, ItemContainerId::ExternBlockId(_)),
518         })
519     }
520 }
521 
522 struct AssocItemCollector<'a> {
523     db: &'a dyn DefDatabase,
524     module_id: ModuleId,
525     def_map: Arc<DefMap>,
526     diagnostics: Vec<DefDiagnostic>,
527     container: ItemContainerId,
528     expander: Expander,
529 
530     items: Vec<(Name, AssocItemId)>,
531     attr_calls: Vec<(AstId<ast::Item>, MacroCallId)>,
532 }
533 
534 impl<'a> AssocItemCollector<'a> {
new( db: &'a dyn DefDatabase, module_id: ModuleId, file_id: HirFileId, container: ItemContainerId, ) -> Self535     fn new(
536         db: &'a dyn DefDatabase,
537         module_id: ModuleId,
538         file_id: HirFileId,
539         container: ItemContainerId,
540     ) -> Self {
541         Self {
542             db,
543             module_id,
544             def_map: module_id.def_map(db),
545             container,
546             expander: Expander::new(db, file_id, module_id),
547             items: Vec::new(),
548             attr_calls: Vec::new(),
549             diagnostics: Vec::new(),
550         }
551     }
552 
finish( self, ) -> ( Vec<(Name, AssocItemId)>, Option<Box<Vec<(AstId<ast::Item>, MacroCallId)>>>, Vec<DefDiagnostic>, )553     fn finish(
554         self,
555     ) -> (
556         Vec<(Name, AssocItemId)>,
557         Option<Box<Vec<(AstId<ast::Item>, MacroCallId)>>>,
558         Vec<DefDiagnostic>,
559     ) {
560         (
561             self.items,
562             if self.attr_calls.is_empty() { None } else { Some(Box::new(self.attr_calls)) },
563             self.diagnostics,
564         )
565     }
566 
collect(&mut self, item_tree: &ItemTree, tree_id: TreeId, assoc_items: &[AssocItem])567     fn collect(&mut self, item_tree: &ItemTree, tree_id: TreeId, assoc_items: &[AssocItem]) {
568         let container = self.container;
569         self.items.reserve(assoc_items.len());
570 
571         'items: for &item in assoc_items {
572             let attrs = item_tree.attrs(self.db, self.module_id.krate, ModItem::from(item).into());
573             if !attrs.is_cfg_enabled(self.expander.cfg_options()) {
574                 self.diagnostics.push(DefDiagnostic::unconfigured_code(
575                     self.module_id.local_id,
576                     InFile::new(self.expander.current_file_id(), item.ast_id(item_tree).upcast()),
577                     attrs.cfg().unwrap(),
578                     self.expander.cfg_options().clone(),
579                 ));
580                 continue;
581             }
582 
583             'attrs: for attr in &*attrs {
584                 let ast_id =
585                     AstId::new(self.expander.current_file_id(), item.ast_id(item_tree).upcast());
586                 let ast_id_with_path = AstIdWithPath { path: (*attr.path).clone(), ast_id };
587 
588                 match self.def_map.resolve_attr_macro(
589                     self.db,
590                     self.module_id.local_id,
591                     ast_id_with_path,
592                     attr,
593                 ) {
594                     Ok(ResolvedAttr::Macro(call_id)) => {
595                         self.attr_calls.push((ast_id, call_id));
596                         // If proc attribute macro expansion is disabled, skip expanding it here
597                         if !self.db.expand_proc_attr_macros() {
598                             continue 'attrs;
599                         }
600                         let loc = self.db.lookup_intern_macro_call(call_id);
601                         if let MacroDefKind::ProcMacro(exp, ..) = loc.def.kind {
602                             // If there's no expander for the proc macro (e.g. the
603                             // proc macro is ignored, or building the proc macro
604                             // crate failed), skip expansion like we would if it was
605                             // disabled. This is analogous to the handling in
606                             // `DefCollector::collect_macros`.
607                             if exp.is_dummy() {
608                                 continue 'attrs;
609                             }
610                         }
611 
612                         let res =
613                             self.expander.enter_expand_id::<ast::MacroItems>(self.db, call_id);
614                         self.collect_macro_items(res, &|| loc.kind.clone());
615                         continue 'items;
616                     }
617                     Ok(_) => (),
618                     Err(_) => {
619                         self.diagnostics.push(DefDiagnostic::unresolved_macro_call(
620                             self.module_id.local_id,
621                             MacroCallKind::Attr {
622                                 ast_id,
623                                 attr_args: Arc::new((tt::Subtree::empty(), Default::default())),
624                                 invoc_attr_index: attr.id,
625                             },
626                             attr.path().clone(),
627                         ));
628                     }
629                 }
630             }
631 
632             self.collect_item(item_tree, tree_id, container, item);
633         }
634     }
635 
collect_item( &mut self, item_tree: &ItemTree, tree_id: TreeId, container: ItemContainerId, item: AssocItem, )636     fn collect_item(
637         &mut self,
638         item_tree: &ItemTree,
639         tree_id: TreeId,
640         container: ItemContainerId,
641         item: AssocItem,
642     ) {
643         match item {
644             AssocItem::Function(id) => {
645                 let item = &item_tree[id];
646 
647                 let def =
648                     FunctionLoc { container, id: ItemTreeId::new(tree_id, id) }.intern(self.db);
649                 self.items.push((item.name.clone(), def.into()));
650             }
651             AssocItem::Const(id) => {
652                 let item = &item_tree[id];
653                 let Some(name) = item.name.clone() else { return };
654                 let def = ConstLoc { container, id: ItemTreeId::new(tree_id, id) }.intern(self.db);
655                 self.items.push((name, def.into()));
656             }
657             AssocItem::TypeAlias(id) => {
658                 let item = &item_tree[id];
659 
660                 let def =
661                     TypeAliasLoc { container, id: ItemTreeId::new(tree_id, id) }.intern(self.db);
662                 self.items.push((item.name.clone(), def.into()));
663             }
664             AssocItem::MacroCall(call) => {
665                 let file_id = self.expander.current_file_id();
666                 let MacroCall { ast_id, expand_to, ref path } = item_tree[call];
667                 let module = self.expander.module.local_id;
668 
669                 let resolver = |path| {
670                     self.def_map
671                         .resolve_path(
672                             self.db,
673                             module,
674                             &path,
675                             crate::item_scope::BuiltinShadowMode::Other,
676                             Some(MacroSubNs::Bang),
677                         )
678                         .0
679                         .take_macros()
680                         .map(|it| macro_id_to_def_id(self.db, it))
681                 };
682                 match macro_call_as_call_id(
683                     self.db.upcast(),
684                     &AstIdWithPath::new(file_id, ast_id, Clone::clone(path)),
685                     expand_to,
686                     self.expander.module.krate(),
687                     resolver,
688                 ) {
689                     Ok(Some(call_id)) => {
690                         let res =
691                             self.expander.enter_expand_id::<ast::MacroItems>(self.db, call_id);
692                         self.collect_macro_items(res, &|| hir_expand::MacroCallKind::FnLike {
693                             ast_id: InFile::new(file_id, ast_id),
694                             expand_to: hir_expand::ExpandTo::Items,
695                         });
696                     }
697                     Ok(None) => (),
698                     Err(_) => {
699                         self.diagnostics.push(DefDiagnostic::unresolved_macro_call(
700                             self.module_id.local_id,
701                             MacroCallKind::FnLike {
702                                 ast_id: InFile::new(file_id, ast_id),
703                                 expand_to,
704                             },
705                             Clone::clone(path),
706                         ));
707                     }
708                 }
709             }
710         }
711     }
712 
713     fn collect_macro_items(
714         &mut self,
715         ExpandResult { value, err }: ExpandResult<Option<(Mark, Parse<ast::MacroItems>)>>,
716         error_call_kind: &dyn Fn() -> hir_expand::MacroCallKind,
717     ) {
718         let Some((mark, parse)) = value else { return };
719 
720         if let Some(err) = err {
721             let diag = match err {
722                 // why is this reported here?
723                 hir_expand::ExpandError::UnresolvedProcMacro(krate) => {
724                     DefDiagnostic::unresolved_proc_macro(
725                         self.module_id.local_id,
726                         error_call_kind(),
727                         krate,
728                     )
729                 }
730                 _ => DefDiagnostic::macro_error(
731                     self.module_id.local_id,
732                     error_call_kind(),
733                     err.to_string(),
734                 ),
735             };
736             self.diagnostics.push(diag);
737         }
738         if let errors @ [_, ..] = parse.errors() {
739             self.diagnostics.push(DefDiagnostic::macro_expansion_parse_error(
740                 self.module_id.local_id,
741                 error_call_kind(),
742                 errors.into(),
743             ));
744         }
745 
746         let tree_id = item_tree::TreeId::new(self.expander.current_file_id(), None);
747         let item_tree = tree_id.item_tree(self.db);
748         let iter: SmallVec<[_; 2]> =
749             item_tree.top_level_items().iter().filter_map(ModItem::as_assoc_item).collect();
750 
751         self.collect(&item_tree, tree_id, &iter);
752 
753         self.expander.exit(self.db, mark);
754     }
755 }
756 
trait_vis(db: &dyn DefDatabase, trait_id: TraitId) -> RawVisibility757 fn trait_vis(db: &dyn DefDatabase, trait_id: TraitId) -> RawVisibility {
758     let ItemLoc { id: tree_id, .. } = trait_id.lookup(db);
759     let item_tree = tree_id.item_tree(db);
760     let tr_def = &item_tree[tree_id.value];
761     item_tree[tr_def.visibility].clone()
762 }
763