Skip to main content

hir_def/
lib.rs

1//! `hir_def` crate contains everything between macro expansion and type
2//! inference.
3//!
4//! It defines various items (structs, enums, traits) which comprises Rust code,
5//! as well as an algorithm for resolving paths to such entities.
6//!
7//! Note that `hir_def` is a work in progress, so not all of the above is
8//! actually true.
9
10#![cfg_attr(feature = "in-rust-tree", feature(rustc_private))]
11
12stdx::rustc_crates! {
13    extern crate rustc_parse_format or ra_ap_rustc_parse_format;
14}
15
16pub extern crate ra_ap_rustc_abi as layout;
17pub extern crate ra_ap_rustc_abi as rustc_abi;
18pub extern crate ra_ap_rustc_type_ir as rustc_type_ir;
19
20pub mod attrs;
21pub mod builtin_type;
22pub mod item_scope;
23pub mod per_ns;
24
25pub mod signatures;
26
27pub mod dyn_map;
28
29pub mod item_tree;
30
31pub mod builtin_derive;
32pub mod lang_item;
33pub mod unstable_features;
34
35pub mod expr_store;
36pub mod hir;
37pub mod resolver;
38pub mod upvars;
39
40pub mod nameres;
41
42pub mod src;
43
44pub mod find_path;
45pub mod import_map;
46pub mod visibility;
47
48#[cfg(test)]
49mod macro_expansion_tests;
50#[cfg(test)]
51mod test_db;
52
53use std::{
54    fmt,
55    hash::{Hash, Hasher},
56};
57
58use base_db::{Crate, SourceDatabase, impl_intern_key};
59use hir_expand::{
60    AstId, EditionedFileId, ExpandResult, ExpandTo, HirFileId, InFile, MacroCallId, MacroCallKind,
61    MacroCallStyles, MacroDefId, MacroDefKind,
62    attrs::AttrId,
63    builtin::{BuiltinAttrExpander, BuiltinDeriveExpander, BuiltinFnLikeExpander, EagerExpander},
64    eager::expand_eager_macro_input,
65    impl_intern_lookup,
66    mod_path::ModPath,
67    name::Name,
68    proc_macro::{CustomProcMacroExpander, ProcMacroKind},
69};
70use intern::{Interned, sym};
71use nameres::DefMap;
72use rustc_abi::ExternAbi;
73use salsa::{Durability, Setter};
74use span::{AstIdNode, Edition, FileAstId, SyntaxContext};
75use stdx::impl_from;
76use syntax::{AstNode, ast};
77use thin_vec::ThinVec;
78
79use crate::{
80    attrs::AttrFlags,
81    builtin_derive::BuiltinDeriveImplTrait,
82    builtin_type::BuiltinType,
83    expr_store::ExpressionStoreSourceMap,
84    hir::generics::{GenericParams, LocalLifetimeParamId, LocalTypeOrConstParamId},
85    nameres::{
86        LocalDefMap,
87        assoc::{ImplItems, TraitItems},
88        block_def_map, crate_def_map, crate_local_def_map,
89        diagnostics::DefDiagnostics,
90    },
91    signatures::{EnumVariants, InactiveEnumVariantCode, VariantFields},
92};
93
94pub use crate::{
95    find_path::FindPathConfig, hir::type_ref, item_tree::file_item_tree,
96    lang_item::crate_notable_traits, signatures::LocalFieldId,
97};
98pub use hir_expand::{Intern, Lookup, tt};
99
100type FxIndexMap<K, V> = indexmap::IndexMap<K, V, rustc_hash::FxBuildHasher>;
101type ThinFxHashMap<K, V> = stdx::thin_map::ThinHashMap<K, V, rustc_hash::FxBuildHasher>;
102type ThinFxHashSet<T> = stdx::thin_map::ThinHashSet<T, rustc_hash::FxBuildHasher>;
103
104/// Whether to expand procedural macros during name resolution.
105///
106/// Note: this struct shouldn't be exposed to ide crates -- consider using
107/// [`set_expand_proc_attr_macros`] instead, if possible.
108#[salsa::input(singleton, debug)]
109pub(crate) struct ExpandProcAttrMacros {
110    #[returns(copy)]
111    pub(crate) enabled: bool,
112}
113
114pub fn set_expand_proc_attr_macros(db: &mut dyn SourceDatabase, enabled: bool) {
115    if let Some(expand_proc_attr_macros) = ExpandProcAttrMacros::try_get(db) {
116        if expand_proc_attr_macros.enabled(db) != enabled {
117            expand_proc_attr_macros.set_enabled(db).with_durability(Durability::HIGH).to(enabled);
118        }
119    } else {
120        _ = ExpandProcAttrMacros::builder(enabled).durability(Durability::HIGH).new(db);
121    }
122}
123
124#[derive(Debug)]
125pub struct ItemLoc<N: AstIdNode> {
126    pub container: ModuleId,
127    pub id: AstId<N>,
128}
129
130impl<N: AstIdNode> Clone for ItemLoc<N> {
131    fn clone(&self) -> Self {
132        *self
133    }
134}
135
136impl<N: AstIdNode> Copy for ItemLoc<N> {}
137
138impl<N: AstIdNode> PartialEq for ItemLoc<N> {
139    fn eq(&self, other: &Self) -> bool {
140        self.container == other.container && self.id == other.id
141    }
142}
143
144impl<N: AstIdNode> Eq for ItemLoc<N> {}
145
146impl<N: AstIdNode> Hash for ItemLoc<N> {
147    fn hash<H: Hasher>(&self, state: &mut H) {
148        self.container.hash(state);
149        self.id.hash(state);
150    }
151}
152
153impl<N: AstIdNode> HasModule for ItemLoc<N> {
154    #[inline]
155    fn module(&self, _db: &dyn SourceDatabase) -> ModuleId {
156        self.container
157    }
158}
159
160#[derive(Debug)]
161pub struct AssocItemLoc<N: AstIdNode> {
162    // FIXME: Store this as an erased `salsa::Id` to save space
163    pub container: ItemContainerId,
164    pub id: AstId<N>,
165}
166
167impl<N: AstIdNode> Clone for AssocItemLoc<N> {
168    fn clone(&self) -> Self {
169        *self
170    }
171}
172
173impl<N: AstIdNode> Copy for AssocItemLoc<N> {}
174
175impl<N: AstIdNode> PartialEq for AssocItemLoc<N> {
176    fn eq(&self, other: &Self) -> bool {
177        self.container == other.container && self.id == other.id
178    }
179}
180
181impl<N: AstIdNode> Eq for AssocItemLoc<N> {}
182
183impl<N: AstIdNode> Hash for AssocItemLoc<N> {
184    fn hash<H: Hasher>(&self, state: &mut H) {
185        self.container.hash(state);
186        self.id.hash(state);
187    }
188}
189
190impl<N: AstIdNode> HasModule for AssocItemLoc<N> {
191    #[inline]
192    fn module(&self, db: &dyn SourceDatabase) -> ModuleId {
193        self.container.module(db)
194    }
195}
196
197pub trait AstIdLoc {
198    type Container;
199    type Ast: AstNode;
200    fn ast_id(&self) -> AstId<Self::Ast>;
201    fn container(&self) -> Self::Container;
202}
203
204impl<N: AstIdNode> AstIdLoc for ItemLoc<N> {
205    type Container = ModuleId;
206    type Ast = N;
207    #[inline]
208    fn ast_id(&self) -> AstId<Self::Ast> {
209        self.id
210    }
211    #[inline]
212    fn container(&self) -> Self::Container {
213        self.container
214    }
215}
216
217impl<N: AstIdNode> AstIdLoc for AssocItemLoc<N> {
218    type Container = ItemContainerId;
219    type Ast = N;
220    #[inline]
221    fn ast_id(&self) -> AstId<Self::Ast> {
222        self.id
223    }
224    #[inline]
225    fn container(&self) -> Self::Container {
226        self.container
227    }
228}
229
230macro_rules! impl_intern {
231    ($id:ident, $loc:ident) => {
232        impl_intern_key!($id, $loc);
233        impl_intern_lookup!($id, $loc);
234    };
235}
236
237macro_rules! impl_loc {
238    ($loc:ident, $id:ident: $id_ty:ident, $container:ident: $container_type:ident) => {
239        impl AstIdLoc for $loc {
240            type Container = $container_type;
241            type Ast = ast::$id_ty;
242            fn ast_id(&self) -> AstId<Self::Ast> {
243                self.$id
244            }
245            fn container(&self) -> Self::Container {
246                self.$container
247            }
248        }
249
250        impl HasModule for $loc {
251            #[inline]
252            fn module(&self, db: &dyn SourceDatabase) -> ModuleId {
253                self.$container.module(db)
254            }
255        }
256    };
257}
258
259type FunctionLoc = AssocItemLoc<ast::Fn>;
260impl_intern!(FunctionId, FunctionLoc);
261
262type StructLoc = ItemLoc<ast::Struct>;
263impl_intern!(StructId, StructLoc);
264
265impl StructId {
266    pub fn fields(self, db: &dyn SourceDatabase) -> &VariantFields {
267        VariantFields::of(db, self.into())
268    }
269
270    pub fn fields_with_source_map(
271        self,
272        db: &dyn SourceDatabase,
273    ) -> (&VariantFields, &ExpressionStoreSourceMap) {
274        let r = VariantFields::with_source_map(db, self.into());
275        (&r.0, &r.1)
276    }
277}
278
279pub type UnionLoc = ItemLoc<ast::Union>;
280impl_intern!(UnionId, UnionLoc);
281
282impl UnionId {
283    pub fn fields(self, db: &dyn SourceDatabase) -> &VariantFields {
284        VariantFields::of(db, self.into())
285    }
286
287    pub fn fields_with_source_map(
288        self,
289        db: &dyn SourceDatabase,
290    ) -> (&VariantFields, &ExpressionStoreSourceMap) {
291        let r = VariantFields::with_source_map(db, self.into());
292        (&r.0, &r.1)
293    }
294}
295
296pub type EnumLoc = ItemLoc<ast::Enum>;
297impl_intern!(EnumId, EnumLoc);
298
299impl EnumId {
300    #[inline]
301    pub fn enum_variants(self, db: &dyn SourceDatabase) -> &EnumVariants {
302        &self.enum_variants_with_diagnostics(db).0
303    }
304
305    #[inline]
306    pub fn enum_variants_with_diagnostics(
307        self,
308        db: &dyn SourceDatabase,
309    ) -> &(EnumVariants, ThinVec<InactiveEnumVariantCode>) {
310        EnumVariants::of(db, self)
311    }
312}
313
314type ConstLoc = AssocItemLoc<ast::Const>;
315impl_intern!(ConstId, ConstLoc);
316
317pub type StaticLoc = AssocItemLoc<ast::Static>;
318impl_intern!(StaticId, StaticLoc);
319
320pub type TraitLoc = ItemLoc<ast::Trait>;
321impl_intern!(TraitId, TraitLoc);
322
323impl TraitId {
324    #[inline]
325    pub fn trait_items(self, db: &dyn SourceDatabase) -> &TraitItems {
326        TraitItems::query(db, self)
327    }
328}
329
330type TypeAliasLoc = AssocItemLoc<ast::TypeAlias>;
331impl_intern!(TypeAliasId, TypeAliasLoc);
332
333type ImplLoc = ItemLoc<ast::Impl>;
334impl_intern!(ImplId, ImplLoc);
335
336impl ImplId {
337    #[inline]
338    pub fn impl_items(self, db: &dyn SourceDatabase) -> &ImplItems {
339        &self.impl_items_with_diagnostics(db).0
340    }
341
342    #[inline]
343    pub fn impl_items_with_diagnostics(
344        self,
345        db: &dyn SourceDatabase,
346    ) -> &(ImplItems, DefDiagnostics) {
347        ImplItems::of(db, self)
348    }
349}
350
351#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
352pub struct BuiltinDeriveImplLoc {
353    pub adt: AdtId,
354    pub trait_: BuiltinDeriveImplTrait,
355    pub derive_attr_id: AttrId,
356    pub derive_index: u32,
357}
358
359#[salsa::interned(debug, unsafe(no_lifetime), revisions = usize::MAX)]
360#[derive(PartialOrd, Ord)]
361pub struct BuiltinDeriveImplId {
362    #[returns(ref)]
363    pub loc: BuiltinDeriveImplLoc,
364}
365
366type UseLoc = ItemLoc<ast::Use>;
367impl_intern!(UseId, UseLoc);
368
369type ExternCrateLoc = ItemLoc<ast::ExternCrate>;
370impl_intern!(ExternCrateId, ExternCrateLoc);
371
372type ExternBlockLoc = ItemLoc<ast::ExternBlock>;
373impl_intern!(ExternBlockId, ExternBlockLoc);
374
375impl ExternBlockId {
376    pub fn abi(self, db: &dyn SourceDatabase) -> ExternAbi {
377        signatures::extern_block_abi(db, self)
378    }
379}
380
381#[derive(Debug, Clone, PartialEq, Eq, Hash)]
382pub struct EnumVariantLoc {
383    pub id: AstId<ast::Variant>,
384    pub parent: EnumId,
385    pub name: Name,
386}
387impl_intern!(EnumVariantId, EnumVariantLoc);
388impl_loc!(EnumVariantLoc, id: Variant, parent: EnumId);
389
390impl EnumVariantLoc {
391    pub fn index(&self, db: &dyn SourceDatabase) -> usize {
392        self.parent
393            .enum_variants(db)
394            .variants
395            .get_full(&self.name)
396            .expect("parent enum should include this variant")
397            .0
398    }
399}
400
401impl EnumVariantId {
402    pub fn fields(self, db: &dyn SourceDatabase) -> &VariantFields {
403        VariantFields::of(db, self.into())
404    }
405
406    pub fn index(self, db: &dyn SourceDatabase) -> usize {
407        self.loc(db).index(db)
408    }
409
410    pub fn fields_with_source_map(
411        self,
412        db: &dyn SourceDatabase,
413    ) -> (&VariantFields, &ExpressionStoreSourceMap) {
414        let r = VariantFields::with_source_map(db, self.into());
415        (&r.0, &r.1)
416    }
417}
418
419#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
420pub struct Macro2Loc {
421    pub container: ModuleId,
422    pub id: AstId<ast::MacroDef>,
423    pub expander: MacroExpander,
424    pub allow_internal_unsafe: bool,
425    pub edition: Edition,
426}
427impl_intern!(Macro2Id, Macro2Loc);
428impl_loc!(Macro2Loc, id: MacroDef, container: ModuleId);
429
430#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
431pub struct MacroRulesLoc {
432    pub container: ModuleId,
433    pub id: AstId<ast::MacroRules>,
434    pub expander: MacroExpander,
435    pub flags: MacroRulesLocFlags,
436    pub edition: Edition,
437}
438impl_intern!(MacroRulesId, MacroRulesLoc);
439impl_loc!(MacroRulesLoc, id: MacroRules, container: ModuleId);
440
441bitflags::bitflags! {
442    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
443    pub struct MacroRulesLocFlags: u8 {
444        const ALLOW_INTERNAL_UNSAFE = 1 << 0;
445        const LOCAL_INNER = 1 << 1;
446    }
447}
448
449#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
450pub enum MacroExpander {
451    Declarative { styles: MacroCallStyles },
452    BuiltIn(BuiltinFnLikeExpander),
453    BuiltInAttr(BuiltinAttrExpander),
454    BuiltInDerive(BuiltinDeriveExpander),
455    BuiltInEager(EagerExpander),
456    UnimplementedBuiltIn,
457}
458
459#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
460pub struct ProcMacroLoc {
461    pub container: ModuleId,
462    pub id: AstId<ast::Fn>,
463    pub expander: CustomProcMacroExpander,
464    pub kind: ProcMacroKind,
465    pub edition: Edition,
466}
467impl_intern!(ProcMacroId, ProcMacroLoc);
468impl_loc!(ProcMacroLoc, id: Fn, container: ModuleId);
469
470#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, salsa::SalsaValue)]
471pub enum LoweringMode {
472    Analysis,
473    Ide,
474}
475
476pub use self::tracked_struct_token::TrackedStructToken;
477mod tracked_struct_token {
478    use super::LoweringMode;
479
480    /// A token that is required to construct tracked structs.
481    /// This exists to prevent one from accidentally creating a tracked struct outside of a query which may happen for some codepaths.
482    pub struct TrackedStructToken {
483        // #[non_exhaustive] doesn't work for us here, we want it module focused.
484        _private: (),
485    }
486
487    impl LoweringMode {
488        pub fn allow_tracked_structs(self) -> Option<TrackedStructToken> {
489            match self {
490                LoweringMode::Analysis => Some(TrackedStructToken { _private: () }),
491                LoweringMode::Ide => None,
492            }
493        }
494    }
495}
496
497#[salsa::tracked(constructor = new_)]
498#[derive(PartialOrd, Ord)]
499pub struct BlockIdLt<'db> {
500    #[returns(copy)]
501    pub ast_id: AstId<ast::BlockExpr>,
502    /// The containing module.
503    #[returns(copy)]
504    pub module: ModuleIdLt<'db>,
505}
506pub type BlockId = BlockIdLt<'static>;
507
508impl<'db> fmt::Debug for BlockIdLt<'db> {
509    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
510        f.debug_tuple("BlockId").field(&self.0).finish()
511    }
512}
513
514impl<'db> BlockIdLt<'db> {
515    pub fn new(
516        db: &'db dyn SourceDatabase,
517        ast_id: AstId<ast::BlockExpr>,
518        module: ModuleIdLt<'db>,
519        token: TrackedStructToken,
520    ) -> Self {
521        _ = token;
522        BlockIdLt::new_(db, ast_id, module)
523    }
524
525    /// # Safety
526    ///
527    /// The caller must ensure that the `ModuleId` is not leaked outside of query computations.
528    pub unsafe fn to_static(self) -> BlockId {
529        unsafe { std::mem::transmute(self) }
530    }
531}
532impl BlockId {
533    /// # Safety
534    ///
535    /// The caller must ensure that the `BlockId` comes from the given database.
536    pub unsafe fn to_db<'db>(self, _db: &'db dyn SourceDatabase) -> BlockIdLt<'db> {
537        unsafe { std::mem::transmute(self) }
538    }
539}
540
541#[salsa::tracked(debug)]
542#[derive(PartialOrd, Ord)]
543pub struct ModuleIdLt<'db> {
544    /// The crate this module belongs to.
545    #[returns(copy)]
546    pub krate: Crate,
547    /// If this `ModuleId` was derived from a `DefMap` for a block expression, this stores the
548    /// `BlockId` of that block expression. If `None`, this module is part of the crate-level
549    /// `DefMap` of `krate`.
550    #[returns(copy)]
551    pub block: Option<BlockIdLt<'db>>,
552    /// The parent module of this module, or `None` if this is the root module inside the def
553    /// map (including for block def maps).
554    pub containing_module_inside_def_map: Option<ModuleIdLt<'db>>,
555    /// The name of this module, or [`sym::__empty`] for the root module.
556    #[returns(clone)]
557    name_or_empty: Name,
558}
559pub type ModuleId = ModuleIdLt<'static>;
560
561impl<'db> ModuleIdLt<'db> {
562    /// # Safety
563    ///
564    /// The caller must ensure that the `ModuleId` is not leaked outside of query computations.
565    pub unsafe fn to_static(self) -> ModuleId {
566        unsafe { std::mem::transmute(self) }
567    }
568
569    pub fn def_map(self, db: &'db dyn SourceDatabase) -> &'db DefMap {
570        match self.block(db) {
571            Some(block) => block_def_map(db, block),
572            None => crate_def_map(db, self.krate(db)),
573        }
574    }
575
576    pub(crate) fn local_def_map(
577        self,
578        db: &'db dyn SourceDatabase,
579    ) -> (&'db DefMap, &'db LocalDefMap) {
580        match self.block(db) {
581            Some(block) => (block_def_map(db, block), self.only_local_def_map(db)),
582            None => {
583                let def_map = crate_local_def_map(db, self.krate(db));
584                (def_map.def_map(db), def_map.local(db))
585            }
586        }
587    }
588
589    pub(crate) fn only_local_def_map(self, db: &'db dyn SourceDatabase) -> &'db LocalDefMap {
590        crate_local_def_map(db, self.krate(db)).local(db)
591    }
592
593    pub fn crate_def_map(self, db: &'db dyn SourceDatabase) -> &'db DefMap {
594        crate_def_map(db, self.krate(db))
595    }
596
597    pub fn name(self, db: &dyn SourceDatabase) -> Option<Name> {
598        let name = self.name_or_empty(db);
599        if *name.symbol() == sym::__empty { None } else { Some(name) }
600    }
601
602    /// Returns the module containing `self`, either the parent `mod`, or the module (or block) containing
603    /// the block, if `self` corresponds to a block expression.
604    pub fn containing_module(self, db: &'db dyn SourceDatabase) -> Option<ModuleIdLt<'db>> {
605        self.containing_module_inside_def_map(db)
606            .or_else(|| self.block(db).map(|block| block.module(db)))
607    }
608
609    pub fn is_block_module(self, db: &dyn SourceDatabase) -> bool {
610        self.block(db).is_some() && self.containing_module_inside_def_map(db).is_none()
611    }
612}
613
614impl ModuleId {
615    /// # Safety
616    ///
617    /// The caller must ensure that the `ModuleId` comes from the given database.
618    pub unsafe fn to_db<'db>(self, _db: &'db dyn SourceDatabase) -> ModuleIdLt<'db> {
619        unsafe { std::mem::transmute(self) }
620    }
621}
622
623impl HasModule for ModuleId {
624    #[inline]
625    fn module(&self, _db: &dyn SourceDatabase) -> ModuleId {
626        *self
627    }
628}
629
630#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, salsa::SalsaValue)]
631pub struct FieldId {
632    // FIXME: Store this as an erased `salsa::Id` to save space
633    pub parent: VariantId,
634    pub local_id: LocalFieldId,
635}
636
637#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, salsa::SalsaValue)]
638pub struct TupleId(pub u32);
639
640#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, salsa::SalsaValue)]
641pub struct TupleFieldId {
642    pub tuple: TupleId,
643    pub index: u32,
644}
645
646#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
647pub struct TypeOrConstParamId {
648    // FIXME: Store this as an erased `salsa::Id` to save space
649    pub parent: GenericDefId,
650    pub local_id: LocalTypeOrConstParamId,
651}
652
653/// A TypeOrConstParamId with an invariant that it actually belongs to a type
654#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
655pub struct TypeParamId(TypeOrConstParamId);
656
657impl TypeParamId {
658    #[inline]
659    pub fn parent(&self) -> GenericDefId {
660        self.0.parent
661    }
662
663    #[inline]
664    pub fn local_id(&self) -> LocalTypeOrConstParamId {
665        self.0.local_id
666    }
667
668    #[inline]
669    pub fn trait_self(trait_: TraitId) -> TypeParamId {
670        TypeParamId::from_unchecked(TypeOrConstParamId {
671            parent: trait_.into(),
672            local_id: GenericParams::SELF_PARAM_ID_IN_SELF,
673        })
674    }
675
676    #[inline]
677    /// Caller should check if this toc id really belongs to a type
678    pub fn from_unchecked(it: TypeOrConstParamId) -> Self {
679        Self(it)
680    }
681}
682
683impl From<TypeParamId> for TypeOrConstParamId {
684    fn from(it: TypeParamId) -> Self {
685        it.0
686    }
687}
688
689/// A TypeOrConstParamId with an invariant that it actually belongs to a const
690#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
691pub struct ConstParamId(TypeOrConstParamId);
692
693impl ConstParamId {
694    pub fn parent(&self) -> GenericDefId {
695        self.0.parent
696    }
697    pub fn local_id(&self) -> LocalTypeOrConstParamId {
698        self.0.local_id
699    }
700}
701
702impl ConstParamId {
703    /// Caller should check if this toc id really belongs to a const
704    pub fn from_unchecked(it: TypeOrConstParamId) -> Self {
705        Self(it)
706    }
707}
708
709impl From<ConstParamId> for TypeOrConstParamId {
710    fn from(it: ConstParamId) -> Self {
711        it.0
712    }
713}
714
715#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
716pub struct LifetimeParamId {
717    // FIXME: Store this as an erased `salsa::Id` to save space
718    pub parent: GenericDefId,
719    pub local_id: LocalLifetimeParamId,
720}
721
722#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
723pub struct HrtbLifetimeParamId {
724    pub scope: GenericDefId,
725    pub local_id: usize,
726}
727
728#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, salsa::Supertype)]
729pub enum ItemContainerId {
730    ExternBlockId(ExternBlockId),
731    ModuleId(ModuleId),
732    ImplId(ImplId),
733    TraitId(TraitId),
734}
735impl_from!(ModuleId for ItemContainerId);
736
737/// A Data Type
738#[derive(Debug, PartialOrd, Ord, Clone, Copy, PartialEq, Eq, Hash, salsa::Supertype)]
739pub enum AdtId {
740    StructId(StructId),
741    UnionId(UnionId),
742    EnumId(EnumId),
743}
744impl_from!(StructId, UnionId, EnumId for AdtId);
745
746/// A macro
747#[derive(Debug, PartialOrd, Ord, Clone, Copy, PartialEq, Eq, Hash, salsa::Supertype)]
748pub enum MacroId {
749    Macro2Id(Macro2Id),
750    MacroRulesId(MacroRulesId),
751    ProcMacroId(ProcMacroId),
752}
753impl_from!(Macro2Id, MacroRulesId, ProcMacroId for MacroId);
754
755impl MacroId {
756    pub fn is_attribute(self, db: &dyn SourceDatabase) -> bool {
757        matches!(self, MacroId::ProcMacroId(it) if it.lookup(db).kind == ProcMacroKind::Attr)
758    }
759}
760
761#[salsa::tracked]
762impl MacroId {
763    /// Turns a MacroId into a MacroDefId, describing the macro's definition post name resolution.
764    #[salsa::tracked(returns(copy))]
765    pub fn definition(self, db: &dyn SourceDatabase) -> MacroDefId {
766        let kind = |expander, file_id, m| {
767            let in_file = InFile::new(file_id, m);
768            match expander {
769                MacroExpander::Declarative { styles } => MacroDefKind::Declarative(in_file, styles),
770                MacroExpander::BuiltIn(it) => MacroDefKind::BuiltIn(in_file, it),
771                MacroExpander::BuiltInAttr(it) => MacroDefKind::BuiltInAttr(in_file, it),
772                MacroExpander::BuiltInDerive(it) => MacroDefKind::BuiltInDerive(in_file, it),
773                MacroExpander::BuiltInEager(it) => MacroDefKind::BuiltInEager(in_file, it),
774                MacroExpander::UnimplementedBuiltIn => MacroDefKind::UnimplementedBuiltIn(in_file),
775            }
776        };
777
778        match self {
779            MacroId::Macro2Id(it) => {
780                let loc = it.lookup(db);
781
782                MacroDefId {
783                    krate: loc.container.krate(db),
784                    kind: kind(loc.expander, loc.id.file_id, loc.id.value.upcast()),
785                    local_inner: false,
786                    allow_internal_unsafe: loc.allow_internal_unsafe,
787                    edition: loc.edition,
788                }
789            }
790            MacroId::MacroRulesId(it) => {
791                let loc = it.lookup(db);
792
793                MacroDefId {
794                    krate: loc.container.krate(db),
795                    kind: kind(loc.expander, loc.id.file_id, loc.id.value.upcast()),
796                    local_inner: loc.flags.contains(MacroRulesLocFlags::LOCAL_INNER),
797                    allow_internal_unsafe: loc
798                        .flags
799                        .contains(MacroRulesLocFlags::ALLOW_INTERNAL_UNSAFE),
800                    edition: loc.edition,
801                }
802            }
803            MacroId::ProcMacroId(it) => {
804                let loc = it.lookup(db);
805
806                MacroDefId {
807                    krate: loc.container.krate(db),
808                    kind: MacroDefKind::ProcMacro(loc.id, loc.expander, loc.kind),
809                    local_inner: false,
810                    allow_internal_unsafe: false,
811                    edition: loc.edition,
812                }
813            }
814        }
815    }
816}
817
818/// A generic param
819#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
820pub enum GenericParamId {
821    TypeParamId(TypeParamId),
822    ConstParamId(ConstParamId),
823    LifetimeParamId(LifetimeParamId),
824}
825impl_from!(TypeParamId, LifetimeParamId, ConstParamId for GenericParamId);
826
827/// The defs which can be visible in the module.
828#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
829pub enum ModuleDefId {
830    ModuleId(ModuleId),
831    FunctionId(FunctionId),
832    AdtId(AdtId),
833    // Can't be directly declared, but can be imported.
834    EnumVariantId(EnumVariantId),
835    ConstId(ConstId),
836    StaticId(StaticId),
837    TraitId(TraitId),
838    TypeAliasId(TypeAliasId),
839    BuiltinType(BuiltinType),
840    MacroId(MacroId),
841}
842impl_from!(
843    MacroId(Macro2Id, MacroRulesId, ProcMacroId),
844    ModuleId,
845    FunctionId,
846    AdtId(StructId, EnumId, UnionId),
847    EnumVariantId,
848    ConstId,
849    StaticId,
850    TraitId,
851    TypeAliasId,
852    BuiltinType
853    for ModuleDefId
854);
855
856impl From<DefWithBodyId> for ModuleDefId {
857    #[inline]
858    fn from(value: DefWithBodyId) -> Self {
859        match value {
860            DefWithBodyId::FunctionId(id) => id.into(),
861            DefWithBodyId::StaticId(id) => id.into(),
862            DefWithBodyId::ConstId(id) => id.into(),
863            DefWithBodyId::VariantId(id) => id.into(),
864        }
865    }
866}
867
868/// The defs which have a body.
869#[derive(Debug, PartialOrd, Ord, Clone, Copy, PartialEq, Eq, Hash, salsa::Supertype)]
870pub enum DefWithBodyId {
871    /// A function body.
872    FunctionId(FunctionId),
873    /// A static item initializer.
874    StaticId(StaticId),
875    /// A const item initializer
876    ConstId(ConstId),
877    /// An enum variant discrimiant
878    VariantId(EnumVariantId),
879}
880impl_from!(FunctionId, ConstId, StaticId for DefWithBodyId);
881
882impl From<EnumVariantId> for DefWithBodyId {
883    fn from(id: EnumVariantId) -> Self {
884        DefWithBodyId::VariantId(id)
885    }
886}
887
888impl DefWithBodyId {
889    pub fn generic_def(self, db: &dyn SourceDatabase) -> GenericDefId {
890        match self {
891            DefWithBodyId::FunctionId(f) => f.into(),
892            DefWithBodyId::StaticId(s) => s.into(),
893            DefWithBodyId::ConstId(c) => c.into(),
894            DefWithBodyId::VariantId(c) => c.lookup(db).parent.into(),
895        }
896    }
897}
898
899#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, salsa::Supertype)]
900pub enum AssocItemId {
901    FunctionId(FunctionId),
902    ConstId(ConstId),
903    TypeAliasId(TypeAliasId),
904}
905
906// FIXME: not every function, ... is actually an assoc item. maybe we should make
907// sure that you can only turn actual assoc items into AssocItemIds. This would
908// require not implementing From, and instead having some checked way of
909// casting them, and somehow making the constructors private, which would be annoying.
910impl_from!(FunctionId, ConstId, TypeAliasId for AssocItemId);
911
912impl_from!(
913    AssocItemId {
914        FunctionId => FunctionId,
915        ConstId => ConstId,
916        TypeAliasId => TypeAliasId,
917    }
918    for ModuleDefId
919);
920
921#[derive(Debug, PartialOrd, Ord, Clone, Copy, PartialEq, Eq, Hash, salsa::Supertype)]
922pub enum GenericDefId {
923    AdtId(AdtId),
924    // consts can have type parameters from their parents (i.e. associated consts of traits)
925    ConstId(ConstId),
926    FunctionId(FunctionId),
927    ImplId(ImplId),
928    // can't actually have generics currently, but they might in the future
929    // More importantly, this completes the set of items that contain type references
930    // which is to be used by the signature expression store in the future.
931    StaticId(StaticId),
932    TraitId(TraitId),
933    TypeAliasId(TypeAliasId),
934}
935impl_from!(
936    AdtId(StructId, EnumId, UnionId),
937    ConstId,
938    FunctionId,
939    ImplId,
940    StaticId,
941    TraitId,
942    TypeAliasId
943    for GenericDefId
944);
945
946/// Owner of an expression store - either a body or a signature.
947/// This is used for queries that operate on expression stores generically,
948/// such as `expr_scopes`.
949// NOTE: This type cannot be `salsa::Supertype` as its variants are overlapping.
950#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord /* !salsa::Supertype */)]
951pub enum ExpressionStoreOwnerId {
952    Signature(GenericDefId),
953    /// A body, something with a root expression.
954    ///
955    /// An enum variant's body is considered its discriminant initializer.
956    Body(DefWithBodyId),
957    VariantFields(VariantId),
958}
959
960impl ExpressionStoreOwnerId {
961    // FIXME: Check callers of this, this method likely can be removed
962    pub fn as_def_with_body(self) -> Option<DefWithBodyId> {
963        if let Self::Body(v) = self { Some(v) } else { None }
964    }
965
966    pub fn generic_def(self, db: &dyn SourceDatabase) -> GenericDefId {
967        match self {
968            ExpressionStoreOwnerId::Signature(generic_def_id) => generic_def_id,
969            ExpressionStoreOwnerId::Body(def_with_body_id) => match def_with_body_id {
970                DefWithBodyId::FunctionId(id) => GenericDefId::FunctionId(id),
971                DefWithBodyId::StaticId(id) => GenericDefId::StaticId(id),
972                DefWithBodyId::ConstId(id) => GenericDefId::ConstId(id),
973                DefWithBodyId::VariantId(it) => it.lookup(db).parent.into(),
974            },
975            ExpressionStoreOwnerId::VariantFields(variant_id) => match variant_id {
976                VariantId::EnumVariantId(it) => it.lookup(db).parent.into(),
977                VariantId::StructId(it) => it.into(),
978                VariantId::UnionId(it) => it.into(),
979            },
980        }
981    }
982}
983
984impl From<GenericDefId> for ExpressionStoreOwnerId {
985    fn from(id: GenericDefId) -> Self {
986        ExpressionStoreOwnerId::Signature(id)
987    }
988}
989
990impl From<DefWithBodyId> for ExpressionStoreOwnerId {
991    fn from(id: DefWithBodyId) -> Self {
992        ExpressionStoreOwnerId::Body(id)
993    }
994}
995
996impl From<VariantId> for ExpressionStoreOwnerId {
997    fn from(id: VariantId) -> Self {
998        ExpressionStoreOwnerId::VariantFields(id)
999    }
1000}
1001
1002impl From<ImplId> for ExpressionStoreOwnerId {
1003    fn from(id: ImplId) -> Self {
1004        ExpressionStoreOwnerId::Signature(id.into())
1005    }
1006}
1007
1008impl GenericDefId {
1009    pub fn file_id_and_params_of(
1010        self,
1011        db: &dyn SourceDatabase,
1012    ) -> (HirFileId, Option<ast::GenericParamList>) {
1013        fn file_id_and_params_of_item_loc<Loc>(
1014            db: &dyn SourceDatabase,
1015            def: impl Lookup<Data = Loc>,
1016        ) -> (HirFileId, Option<ast::GenericParamList>)
1017        where
1018            Loc: src::HasSource,
1019            Loc::Value: ast::HasGenericParams,
1020        {
1021            let src = def.lookup(db).source(db);
1022            (src.file_id, ast::HasGenericParams::generic_param_list(&src.value))
1023        }
1024
1025        match self {
1026            GenericDefId::FunctionId(it) => file_id_and_params_of_item_loc(db, it),
1027            GenericDefId::TypeAliasId(it) => file_id_and_params_of_item_loc(db, it),
1028            GenericDefId::AdtId(AdtId::StructId(it)) => file_id_and_params_of_item_loc(db, it),
1029            GenericDefId::AdtId(AdtId::UnionId(it)) => file_id_and_params_of_item_loc(db, it),
1030            GenericDefId::AdtId(AdtId::EnumId(it)) => file_id_and_params_of_item_loc(db, it),
1031            GenericDefId::TraitId(it) => file_id_and_params_of_item_loc(db, it),
1032            GenericDefId::ImplId(it) => file_id_and_params_of_item_loc(db, it),
1033            GenericDefId::ConstId(it) => (it.lookup(db).id.file_id, None),
1034            GenericDefId::StaticId(it) => (it.lookup(db).id.file_id, None),
1035        }
1036    }
1037
1038    pub fn assoc_trait_container(self, db: &dyn SourceDatabase) -> Option<TraitId> {
1039        match match self {
1040            GenericDefId::FunctionId(f) => f.lookup(db).container,
1041            GenericDefId::TypeAliasId(t) => t.lookup(db).container,
1042            GenericDefId::ConstId(c) => c.lookup(db).container,
1043            _ => return None,
1044        } {
1045            ItemContainerId::TraitId(trait_) => Some(trait_),
1046            _ => None,
1047        }
1048    }
1049
1050    pub fn from_callable(db: &dyn SourceDatabase, def: CallableDefId) -> GenericDefId {
1051        match def {
1052            CallableDefId::FunctionId(f) => f.into(),
1053            CallableDefId::StructId(s) => s.into(),
1054            CallableDefId::EnumVariantId(e) => e.lookup(db).parent.into(),
1055        }
1056    }
1057}
1058
1059impl_from!(
1060    AssocItemId {
1061        FunctionId => FunctionId,
1062        ConstId => ConstId,
1063        TypeAliasId => TypeAliasId,
1064    }
1065    for GenericDefId
1066);
1067
1068#[derive(Debug, PartialOrd, Ord, Clone, Copy, PartialEq, Eq, Hash, salsa::Supertype)]
1069pub enum CallableDefId {
1070    FunctionId(FunctionId),
1071    StructId(StructId),
1072    EnumVariantId(EnumVariantId),
1073}
1074
1075impl_from!(FunctionId, StructId, EnumVariantId for CallableDefId);
1076impl_from!(
1077    CallableDefId {
1078        FunctionId => FunctionId,
1079        StructId => AdtId,
1080        EnumVariantId => EnumVariantId,
1081    }
1082    for ModuleDefId
1083);
1084
1085impl CallableDefId {
1086    pub fn krate(self, db: &dyn SourceDatabase) -> Crate {
1087        match self {
1088            CallableDefId::FunctionId(f) => f.krate(db),
1089            CallableDefId::StructId(s) => s.krate(db),
1090            CallableDefId::EnumVariantId(e) => e.krate(db),
1091        }
1092    }
1093}
1094
1095#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, salsa::Supertype)]
1096pub enum AttrDefId {
1097    ModuleId(ModuleId),
1098    AdtId(AdtId),
1099    FunctionId(FunctionId),
1100    EnumVariantId(EnumVariantId),
1101    StaticId(StaticId),
1102    ConstId(ConstId),
1103    TraitId(TraitId),
1104    TypeAliasId(TypeAliasId),
1105    MacroId(MacroId),
1106    ImplId(ImplId),
1107    ExternBlockId(ExternBlockId),
1108    ExternCrateId(ExternCrateId),
1109    UseId(UseId),
1110}
1111
1112impl_from!(
1113    ModuleId,
1114    AdtId(StructId, EnumId, UnionId),
1115    EnumVariantId,
1116    StaticId,
1117    ConstId,
1118    FunctionId,
1119    TraitId,
1120    TypeAliasId,
1121    MacroId(Macro2Id, MacroRulesId, ProcMacroId),
1122    ImplId,
1123    ExternCrateId,
1124    UseId
1125    for AttrDefId
1126);
1127
1128impl_from!(AssocItemId { FunctionId, ConstId, TypeAliasId } for AttrDefId);
1129impl_from!(
1130    VariantId { EnumVariantId => EnumVariantId, StructId => AdtId, UnionId => AdtId }
1131    for AttrDefId
1132);
1133
1134#[derive(
1135    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, salsa::Supertype, salsa::SalsaValue,
1136)]
1137pub enum VariantId {
1138    EnumVariantId(EnumVariantId),
1139    StructId(StructId),
1140    UnionId(UnionId),
1141}
1142impl_from!(EnumVariantId, StructId, UnionId for VariantId);
1143
1144impl VariantId {
1145    pub fn from_non_enum(adt_id: AdtId) -> Option<Self> {
1146        Some(match adt_id {
1147            AdtId::StructId(struct_id) => struct_id.into(),
1148            AdtId::UnionId(union_id) => union_id.into(),
1149            AdtId::EnumId(_) => return None,
1150        })
1151    }
1152
1153    pub fn fields(self, db: &dyn SourceDatabase) -> &VariantFields {
1154        VariantFields::of(db, self)
1155    }
1156
1157    pub fn fields_with_source_map(
1158        self,
1159        db: &dyn SourceDatabase,
1160    ) -> (&VariantFields, &ExpressionStoreSourceMap) {
1161        let r = VariantFields::with_source_map(db, self);
1162        (&r.0, &r.1)
1163    }
1164
1165    pub fn file_id(self, db: &dyn SourceDatabase) -> HirFileId {
1166        match self {
1167            VariantId::EnumVariantId(it) => it.lookup(db).id.file_id,
1168            VariantId::StructId(it) => it.lookup(db).id.file_id,
1169            VariantId::UnionId(it) => it.lookup(db).id.file_id,
1170        }
1171    }
1172
1173    pub fn adt_id(self, db: &dyn SourceDatabase) -> AdtId {
1174        match self {
1175            VariantId::EnumVariantId(it) => it.lookup(db).parent.into(),
1176            VariantId::StructId(it) => it.into(),
1177            VariantId::UnionId(it) => it.into(),
1178        }
1179    }
1180}
1181
1182pub trait HasModule {
1183    /// Returns the enclosing module this thing is defined within.
1184    fn module(&self, db: &dyn SourceDatabase) -> ModuleId;
1185    /// Returns the crate this thing is defined within.
1186    #[inline]
1187    #[doc(alias = "crate")]
1188    fn krate(&self, db: &dyn SourceDatabase) -> Crate {
1189        self.module(db).krate(db)
1190    }
1191}
1192
1193// In theory this impl should work out for us, but rustc thinks it collides with all the other
1194// manual impls that do not have a ModuleId container...
1195// impl<N, ItemId, Data> HasModule for ItemId
1196// where
1197//     N: ItemTreeNode,
1198//     ItemId: for<'db> Lookup<Database<'db> = dyn SourceDatabase + 'db, Data = Data> + Copy,
1199//     Data: ItemTreeLoc<Id = N, Container = ModuleId>,
1200// {
1201//     #[inline]
1202//     fn module(&self, db: &dyn SourceDatabase) -> ModuleId {
1203//         self.lookup(db).container()
1204//     }
1205// }
1206
1207impl<N, ItemId> HasModule for ItemId
1208where
1209    N: AstIdNode,
1210    ItemId: Lookup<Data = ItemLoc<N>> + Copy,
1211{
1212    #[inline]
1213    fn module(&self, db: &dyn SourceDatabase) -> ModuleId {
1214        self.lookup(db).container
1215    }
1216}
1217
1218// Technically this does not overlap with the above, but rustc currently forbids this, hence why we
1219// need to write the 3 impls manually instead
1220// impl<N, ItemId> HasModule for ItemId
1221// where
1222//     N: ItemTreeModItemNode,
1223//     ItemId: for<'db> Lookup<Database<'db> = dyn SourceDatabase + 'db, Data = AssocItemLoc<N>> + Copy,
1224// {
1225//     #[inline]
1226//     fn module(&self, db: &dyn SourceDatabase) -> ModuleId {
1227//         self.lookup(db).container.module(db)
1228//     }
1229// }
1230
1231// region: manual-assoc-has-module-impls
1232#[inline]
1233fn module_for_assoc_item_loc<'db>(
1234    db: &(dyn 'db + SourceDatabase),
1235    id: impl Lookup<Data = AssocItemLoc<impl AstIdNode>>,
1236) -> ModuleId {
1237    id.lookup(db).container.module(db)
1238}
1239
1240impl HasModule for BuiltinDeriveImplLoc {
1241    #[inline]
1242    fn module(&self, db: &dyn SourceDatabase) -> ModuleId {
1243        self.adt.module(db)
1244    }
1245}
1246
1247impl HasModule for BuiltinDeriveImplId {
1248    #[inline]
1249    fn module(&self, db: &dyn SourceDatabase) -> ModuleId {
1250        self.loc(db).module(db)
1251    }
1252}
1253
1254impl HasModule for FunctionId {
1255    #[inline]
1256    fn module(&self, db: &dyn SourceDatabase) -> ModuleId {
1257        module_for_assoc_item_loc(db, *self)
1258    }
1259}
1260
1261impl HasModule for ConstId {
1262    #[inline]
1263    fn module(&self, db: &dyn SourceDatabase) -> ModuleId {
1264        module_for_assoc_item_loc(db, *self)
1265    }
1266}
1267
1268impl HasModule for StaticId {
1269    #[inline]
1270    fn module(&self, db: &dyn SourceDatabase) -> ModuleId {
1271        module_for_assoc_item_loc(db, *self)
1272    }
1273}
1274
1275impl HasModule for TypeAliasId {
1276    #[inline]
1277    fn module(&self, db: &dyn SourceDatabase) -> ModuleId {
1278        module_for_assoc_item_loc(db, *self)
1279    }
1280}
1281// endregion: manual-assoc-has-module-impls
1282
1283impl HasModule for EnumVariantId {
1284    #[inline]
1285    fn module(&self, db: &dyn SourceDatabase) -> ModuleId {
1286        self.lookup(db).parent.module(db)
1287    }
1288}
1289
1290impl HasModule for MacroRulesId {
1291    #[inline]
1292    fn module(&self, db: &dyn SourceDatabase) -> ModuleId {
1293        self.lookup(db).container
1294    }
1295}
1296
1297impl HasModule for Macro2Id {
1298    #[inline]
1299    fn module(&self, db: &dyn SourceDatabase) -> ModuleId {
1300        self.lookup(db).container
1301    }
1302}
1303
1304impl HasModule for ProcMacroId {
1305    #[inline]
1306    fn module(&self, db: &dyn SourceDatabase) -> ModuleId {
1307        self.lookup(db).container
1308    }
1309}
1310
1311impl HasModule for ItemContainerId {
1312    fn module(&self, db: &dyn SourceDatabase) -> ModuleId {
1313        match *self {
1314            ItemContainerId::ModuleId(it) => it,
1315            ItemContainerId::ImplId(it) => it.module(db),
1316            ItemContainerId::TraitId(it) => it.module(db),
1317            ItemContainerId::ExternBlockId(it) => it.module(db),
1318        }
1319    }
1320}
1321
1322impl HasModule for AdtId {
1323    fn module(&self, db: &dyn SourceDatabase) -> ModuleId {
1324        match *self {
1325            AdtId::StructId(it) => it.module(db),
1326            AdtId::UnionId(it) => it.module(db),
1327            AdtId::EnumId(it) => it.module(db),
1328        }
1329    }
1330}
1331
1332impl HasModule for VariantId {
1333    fn module(&self, db: &dyn SourceDatabase) -> ModuleId {
1334        match *self {
1335            VariantId::EnumVariantId(it) => it.module(db),
1336            VariantId::StructId(it) => it.module(db),
1337            VariantId::UnionId(it) => it.module(db),
1338        }
1339    }
1340}
1341
1342impl HasModule for MacroId {
1343    fn module(&self, db: &dyn SourceDatabase) -> ModuleId {
1344        match *self {
1345            MacroId::MacroRulesId(it) => it.module(db),
1346            MacroId::Macro2Id(it) => it.module(db),
1347            MacroId::ProcMacroId(it) => it.module(db),
1348        }
1349    }
1350}
1351
1352impl HasModule for DefWithBodyId {
1353    fn module(&self, db: &dyn SourceDatabase) -> ModuleId {
1354        match self {
1355            DefWithBodyId::FunctionId(it) => it.module(db),
1356            DefWithBodyId::StaticId(it) => it.module(db),
1357            DefWithBodyId::ConstId(it) => it.module(db),
1358            DefWithBodyId::VariantId(it) => it.module(db),
1359        }
1360    }
1361}
1362
1363impl HasModule for ExpressionStoreOwnerId {
1364    fn module(&self, db: &dyn SourceDatabase) -> ModuleId {
1365        match self {
1366            ExpressionStoreOwnerId::Signature(def) => def.module(db),
1367            ExpressionStoreOwnerId::Body(def) => def.module(db),
1368            ExpressionStoreOwnerId::VariantFields(variant_id) => variant_id.module(db),
1369        }
1370    }
1371}
1372
1373impl HasModule for GenericDefId {
1374    fn module(&self, db: &dyn SourceDatabase) -> ModuleId {
1375        match self {
1376            GenericDefId::FunctionId(it) => it.module(db),
1377            GenericDefId::AdtId(it) => it.module(db),
1378            GenericDefId::TraitId(it) => it.module(db),
1379            GenericDefId::TypeAliasId(it) => it.module(db),
1380            GenericDefId::ImplId(it) => it.module(db),
1381            GenericDefId::ConstId(it) => it.module(db),
1382            GenericDefId::StaticId(it) => it.module(db),
1383        }
1384    }
1385}
1386
1387impl HasModule for AttrDefId {
1388    fn module(&self, db: &dyn SourceDatabase) -> ModuleId {
1389        match self {
1390            AttrDefId::ModuleId(it) => *it,
1391            AttrDefId::AdtId(it) => it.module(db),
1392            AttrDefId::FunctionId(it) => it.module(db),
1393            AttrDefId::EnumVariantId(it) => it.module(db),
1394            AttrDefId::StaticId(it) => it.module(db),
1395            AttrDefId::ConstId(it) => it.module(db),
1396            AttrDefId::TraitId(it) => it.module(db),
1397            AttrDefId::TypeAliasId(it) => it.module(db),
1398            AttrDefId::ImplId(it) => it.module(db),
1399            AttrDefId::ExternBlockId(it) => it.module(db),
1400            AttrDefId::MacroId(it) => it.module(db),
1401            AttrDefId::ExternCrateId(it) => it.module(db),
1402            AttrDefId::UseId(it) => it.module(db),
1403        }
1404    }
1405}
1406
1407impl ModuleDefId {
1408    /// Returns the module containing `self` (or `self`, if `self` is itself a module).
1409    ///
1410    /// Returns `None` if `self` refers to a primitive type.
1411    pub fn module(&self, db: &dyn SourceDatabase) -> Option<ModuleId> {
1412        Some(match self {
1413            ModuleDefId::ModuleId(id) => *id,
1414            ModuleDefId::FunctionId(id) => id.module(db),
1415            ModuleDefId::AdtId(id) => id.module(db),
1416            ModuleDefId::EnumVariantId(id) => id.module(db),
1417            ModuleDefId::ConstId(id) => id.module(db),
1418            ModuleDefId::StaticId(id) => id.module(db),
1419            ModuleDefId::TraitId(id) => id.module(db),
1420            ModuleDefId::TypeAliasId(id) => id.module(db),
1421            ModuleDefId::MacroId(id) => id.module(db),
1422            ModuleDefId::BuiltinType(_) => return None,
1423        })
1424    }
1425}
1426/// Helper wrapper for `AstId` with `ModPath`
1427#[derive(Clone, Debug, Eq, PartialEq)]
1428struct AstIdWithPath<T: AstIdNode> {
1429    ast_id: AstId<T>,
1430    path: Interned<ModPath>,
1431}
1432
1433impl<T: AstIdNode> AstIdWithPath<T> {
1434    fn new(file_id: HirFileId, ast_id: FileAstId<T>, path: Interned<ModPath>) -> AstIdWithPath<T> {
1435        AstIdWithPath { ast_id: AstId::new(file_id, ast_id), path }
1436    }
1437}
1438
1439pub fn macro_call_as_call_id(
1440    db: &dyn SourceDatabase,
1441    ast_id: AstId<ast::MacroCall>,
1442    path: &ModPath,
1443    call_site: SyntaxContext,
1444    expand_to: ExpandTo,
1445    krate: Crate,
1446    macro_depth: u32,
1447    recursion_limit: u32,
1448    resolver: impl Fn(&ModPath) -> Option<MacroDefId> + Copy,
1449    eager_callback: &mut dyn FnMut(
1450        InFile<(syntax::AstPtr<ast::MacroCall>, span::FileAstId<ast::MacroCall>)>,
1451        MacroCallId,
1452    ),
1453) -> Result<ExpandResult<Option<MacroCallId>>, UnresolvedMacro> {
1454    let def = resolver(path).ok_or_else(|| UnresolvedMacro { path: path.clone() })?;
1455
1456    let res = match def.kind {
1457        MacroDefKind::BuiltInEager(..) => expand_eager_macro_input(
1458            db,
1459            krate,
1460            &ast_id.to_node(db),
1461            ast_id,
1462            def,
1463            call_site,
1464            macro_depth,
1465            recursion_limit,
1466            &|path| resolver(path).filter(MacroDefId::is_fn_like),
1467            eager_callback,
1468        ),
1469        _ if def.is_fn_like() => ExpandResult {
1470            value: Some(def.make_call(
1471                db,
1472                krate,
1473                MacroCallKind::FnLike { ast_id, expand_to, eager: None },
1474                call_site,
1475                macro_depth,
1476            )),
1477            err: None,
1478        },
1479        _ => return Err(UnresolvedMacro { path: path.clone() }),
1480    };
1481    Ok(res)
1482}
1483
1484#[derive(Debug)]
1485pub struct UnresolvedMacro {
1486    pub path: ModPath,
1487}
1488
1489#[derive(Default, Debug, Eq, PartialEq, Clone, Copy)]
1490pub struct SyntheticSyntax;
1491
1492// Feature: Completions Attribute
1493// Crate authors can opt their type out of completions in some cases.
1494// This is done with the `#[rust_analyzer::completions(...)]` attribute.
1495//
1496// All completable things support `#[rust_analyzer::completions(ignore_flyimport)]`,
1497// which causes the thing to get excluded from flyimport completion. It will still
1498// be completed when in scope. This is analogous to the setting `rust-analyzer.completion.autoimport.exclude`
1499// with `"type": "always"`.
1500//
1501// In addition, traits support two more modes: `#[rust_analyzer::completions(ignore_flyimport_methods)]`,
1502// which means the trait itself may still be flyimported but its methods won't, and
1503// `#[rust_analyzer::completions(ignore_methods)]`, which means the methods won't be completed even when
1504// the trait is in scope (but the trait itself may still be completed). The methods will still be completed
1505// on `dyn Trait`, `impl Trait` or where the trait is specified in bounds. These modes correspond to
1506// the settings `rust-analyzer.completion.autoimport.exclude` with `"type": "methods"` and
1507// `rust-analyzer.completion.excludeTraits`, respectively.
1508//
1509// Malformed attributes will be ignored without warnings.
1510//
1511// Note that users have no way to override this attribute, so be careful and only include things
1512// users definitely do not want to be completed!
1513
1514/// `#[rust_analyzer::completions(...)]` options.
1515#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1516pub enum Complete {
1517    /// No `#[rust_analyzer::completions(...)]`.
1518    Yes,
1519    /// `#[rust_analyzer::completions(ignore_flyimport)]`.
1520    IgnoreFlyimport,
1521    /// `#[rust_analyzer::completions(ignore_flyimport_methods)]` (on a trait only).
1522    IgnoreFlyimportMethods,
1523    /// `#[rust_analyzer::completions(ignore_methods)]` (on a trait only).
1524    IgnoreMethods,
1525}
1526
1527impl Complete {
1528    #[inline]
1529    pub fn extract(is_trait: bool, attrs: AttrFlags) -> Complete {
1530        if attrs.contains(AttrFlags::COMPLETE_IGNORE_FLYIMPORT) {
1531            return Complete::IgnoreFlyimport;
1532        } else if is_trait {
1533            if attrs.contains(AttrFlags::COMPLETE_IGNORE_METHODS) {
1534                return Complete::IgnoreMethods;
1535            } else if attrs.contains(AttrFlags::COMPLETE_IGNORE_FLYIMPORT_METHODS) {
1536                return Complete::IgnoreFlyimportMethods;
1537            }
1538        }
1539        Complete::Yes
1540    }
1541
1542    #[inline]
1543    pub fn for_trait_item(trait_attr: Complete, item_attr: Complete) -> Complete {
1544        match (trait_attr, item_attr) {
1545            (
1546                Complete::IgnoreFlyimportMethods
1547                | Complete::IgnoreFlyimport
1548                | Complete::IgnoreMethods,
1549                _,
1550            ) => Complete::IgnoreFlyimport,
1551            _ => item_attr,
1552        }
1553    }
1554}
1555
1556// return: macro call id and include file id
1557#[salsa::tracked(returns(ref))]
1558pub fn include_macro_invoc(
1559    db: &dyn SourceDatabase,
1560    krate: Crate,
1561) -> Box<[(MacroCallId, EditionedFileId)]> {
1562    crate_def_map(db, krate)
1563        .modules
1564        .values()
1565        .flat_map(|m| m.scope.iter_macro_invoc())
1566        .filter_map(|(_, &invoc)| invoc.loc(db).include_file_id(db, invoc).map(|x| (invoc, x)))
1567        .collect()
1568}