]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/lib.rs
Merge #8450
[rust.git] / crates / hir_def / src / 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 #[allow(unused)]
11 macro_rules! eprintln {
12     ($($tt:tt)*) => { stdx::eprintln!($($tt)*) };
13 }
14
15 pub mod db;
16
17 pub mod attr;
18 pub mod path;
19 pub mod type_ref;
20 pub mod builtin_type;
21 pub mod builtin_attr;
22 pub mod diagnostics;
23 pub mod per_ns;
24 pub mod item_scope;
25
26 pub mod dyn_map;
27 pub mod keys;
28
29 pub mod item_tree;
30 pub mod intern;
31
32 pub mod adt;
33 pub mod data;
34 pub mod generics;
35 pub mod lang_item;
36
37 pub mod expr;
38 pub mod body;
39 pub mod resolver;
40
41 mod trace;
42 pub mod nameres;
43
44 pub mod src;
45 pub mod child_by_source;
46
47 pub mod visibility;
48 pub mod find_path;
49 pub mod import_map;
50
51 #[cfg(test)]
52 mod test_db;
53
54 use std::{
55     hash::{Hash, Hasher},
56     sync::Arc,
57 };
58
59 use adt::VariantData;
60 use base_db::{impl_intern_key, salsa, CrateId};
61 use hir_expand::{
62     ast_id_map::FileAstId,
63     eager::{expand_eager_macro, ErrorEmitted, ErrorSink},
64     hygiene::Hygiene,
65     AstId, AttrId, HirFileId, InFile, MacroCallId, MacroCallKind, MacroDefId, MacroDefKind,
66 };
67 use la_arena::Idx;
68 use nameres::DefMap;
69 use syntax::ast;
70
71 use crate::builtin_type::BuiltinType;
72 use item_tree::{
73     Const, Enum, Function, Impl, ItemTreeId, ItemTreeNode, ModItem, Static, Struct, Trait,
74     TypeAlias, Union,
75 };
76 use stdx::impl_from;
77
78 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
79 pub struct ModuleId {
80     krate: CrateId,
81     /// If this `ModuleId` was derived from a `DefMap` for a block expression, this stores the
82     /// `BlockId` of that block expression. If `None`, this module is part of the crate-level
83     /// `DefMap` of `krate`.
84     block: Option<BlockId>,
85     /// The module's ID in its originating `DefMap`.
86     pub local_id: LocalModuleId,
87 }
88
89 impl ModuleId {
90     pub fn def_map(&self, db: &dyn db::DefDatabase) -> Arc<DefMap> {
91         match self.block {
92             Some(block) => {
93                 db.block_def_map(block).unwrap_or_else(|| {
94                     // NOTE: This should be unreachable - all `ModuleId`s come from their `DefMap`s,
95                     // so the `DefMap` here must exist.
96                     unreachable!("no `block_def_map` for `ModuleId` {:?}", self);
97                 })
98             }
99             None => db.crate_def_map(self.krate),
100         }
101     }
102
103     pub fn krate(&self) -> CrateId {
104         self.krate
105     }
106
107     pub fn containing_module(&self, db: &dyn db::DefDatabase) -> Option<ModuleId> {
108         self.def_map(db).containing_module(self.local_id)
109     }
110 }
111
112 /// An ID of a module, **local** to a specific crate
113 pub type LocalModuleId = Idx<nameres::ModuleData>;
114
115 #[derive(Debug)]
116 pub struct ItemLoc<N: ItemTreeNode> {
117     pub container: ModuleId,
118     pub id: ItemTreeId<N>,
119 }
120
121 impl<N: ItemTreeNode> Clone for ItemLoc<N> {
122     fn clone(&self) -> Self {
123         Self { container: self.container, id: self.id }
124     }
125 }
126
127 impl<N: ItemTreeNode> Copy for ItemLoc<N> {}
128
129 impl<N: ItemTreeNode> PartialEq for ItemLoc<N> {
130     fn eq(&self, other: &Self) -> bool {
131         self.container == other.container && self.id == other.id
132     }
133 }
134
135 impl<N: ItemTreeNode> Eq for ItemLoc<N> {}
136
137 impl<N: ItemTreeNode> Hash for ItemLoc<N> {
138     fn hash<H: Hasher>(&self, state: &mut H) {
139         self.container.hash(state);
140         self.id.hash(state);
141     }
142 }
143
144 #[derive(Debug)]
145 pub struct AssocItemLoc<N: ItemTreeNode> {
146     pub container: AssocContainerId,
147     pub id: ItemTreeId<N>,
148 }
149
150 impl<N: ItemTreeNode> Clone for AssocItemLoc<N> {
151     fn clone(&self) -> Self {
152         Self { container: self.container, id: self.id }
153     }
154 }
155
156 impl<N: ItemTreeNode> Copy for AssocItemLoc<N> {}
157
158 impl<N: ItemTreeNode> PartialEq for AssocItemLoc<N> {
159     fn eq(&self, other: &Self) -> bool {
160         self.container == other.container && self.id == other.id
161     }
162 }
163
164 impl<N: ItemTreeNode> Eq for AssocItemLoc<N> {}
165
166 impl<N: ItemTreeNode> Hash for AssocItemLoc<N> {
167     fn hash<H: Hasher>(&self, state: &mut H) {
168         self.container.hash(state);
169         self.id.hash(state);
170     }
171 }
172
173 macro_rules! impl_intern {
174     ($id:ident, $loc:ident, $intern:ident, $lookup:ident) => {
175         impl_intern_key!($id);
176
177         impl Intern for $loc {
178             type ID = $id;
179             fn intern(self, db: &dyn db::DefDatabase) -> $id {
180                 db.$intern(self)
181             }
182         }
183
184         impl Lookup for $id {
185             type Data = $loc;
186             fn lookup(&self, db: &dyn db::DefDatabase) -> $loc {
187                 db.$lookup(*self)
188             }
189         }
190     };
191 }
192
193 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
194 pub struct FunctionId(salsa::InternId);
195 type FunctionLoc = AssocItemLoc<Function>;
196 impl_intern!(FunctionId, FunctionLoc, intern_function, lookup_intern_function);
197
198 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
199 pub struct StructId(salsa::InternId);
200 type StructLoc = ItemLoc<Struct>;
201 impl_intern!(StructId, StructLoc, intern_struct, lookup_intern_struct);
202
203 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
204 pub struct UnionId(salsa::InternId);
205 pub type UnionLoc = ItemLoc<Union>;
206 impl_intern!(UnionId, UnionLoc, intern_union, lookup_intern_union);
207
208 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
209 pub struct EnumId(salsa::InternId);
210 pub type EnumLoc = ItemLoc<Enum>;
211 impl_intern!(EnumId, EnumLoc, intern_enum, lookup_intern_enum);
212
213 // FIXME: rename to `VariantId`, only enums can ave variants
214 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
215 pub struct EnumVariantId {
216     pub parent: EnumId,
217     pub local_id: LocalEnumVariantId,
218 }
219
220 pub type LocalEnumVariantId = Idx<adt::EnumVariantData>;
221
222 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
223 pub struct FieldId {
224     pub parent: VariantId,
225     pub local_id: LocalFieldId,
226 }
227
228 pub type LocalFieldId = Idx<adt::FieldData>;
229
230 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
231 pub struct ConstId(salsa::InternId);
232 type ConstLoc = AssocItemLoc<Const>;
233 impl_intern!(ConstId, ConstLoc, intern_const, lookup_intern_const);
234
235 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
236 pub struct StaticId(salsa::InternId);
237 pub type StaticLoc = ItemLoc<Static>;
238 impl_intern!(StaticId, StaticLoc, intern_static, lookup_intern_static);
239
240 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
241 pub struct TraitId(salsa::InternId);
242 pub type TraitLoc = ItemLoc<Trait>;
243 impl_intern!(TraitId, TraitLoc, intern_trait, lookup_intern_trait);
244
245 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
246 pub struct TypeAliasId(salsa::InternId);
247 type TypeAliasLoc = AssocItemLoc<TypeAlias>;
248 impl_intern!(TypeAliasId, TypeAliasLoc, intern_type_alias, lookup_intern_type_alias);
249
250 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
251 pub struct ImplId(salsa::InternId);
252 type ImplLoc = ItemLoc<Impl>;
253 impl_intern!(ImplId, ImplLoc, intern_impl, lookup_intern_impl);
254
255 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
256 pub struct BlockId(salsa::InternId);
257 #[derive(Debug, Hash, PartialEq, Eq, Clone)]
258 pub struct BlockLoc {
259     ast_id: AstId<ast::BlockExpr>,
260     /// The containing module.
261     module: ModuleId,
262 }
263 impl_intern!(BlockId, BlockLoc, intern_block, lookup_intern_block);
264
265 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
266 pub struct TypeParamId {
267     pub parent: GenericDefId,
268     pub local_id: LocalTypeParamId,
269 }
270
271 pub type LocalTypeParamId = Idx<generics::TypeParamData>;
272
273 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
274 pub struct LifetimeParamId {
275     pub parent: GenericDefId,
276     pub local_id: LocalLifetimeParamId,
277 }
278 pub type LocalLifetimeParamId = Idx<generics::LifetimeParamData>;
279
280 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
281 pub struct ConstParamId {
282     pub parent: GenericDefId,
283     pub local_id: LocalConstParamId,
284 }
285 pub type LocalConstParamId = Idx<generics::ConstParamData>;
286
287 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
288 pub enum AssocContainerId {
289     ModuleId(ModuleId),
290     ImplId(ImplId),
291     TraitId(TraitId),
292 }
293 impl_from!(ModuleId for AssocContainerId);
294
295 /// A Data Type
296 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
297 pub enum AdtId {
298     StructId(StructId),
299     UnionId(UnionId),
300     EnumId(EnumId),
301 }
302 impl_from!(StructId, UnionId, EnumId for AdtId);
303
304 /// A generic param
305 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
306 pub enum GenericParamId {
307     TypeParamId(TypeParamId),
308     LifetimeParamId(LifetimeParamId),
309     ConstParamId(ConstParamId),
310 }
311 impl_from!(TypeParamId, LifetimeParamId, ConstParamId for GenericParamId);
312
313 /// The defs which can be visible in the module.
314 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
315 pub enum ModuleDefId {
316     ModuleId(ModuleId),
317     FunctionId(FunctionId),
318     AdtId(AdtId),
319     // Can't be directly declared, but can be imported.
320     EnumVariantId(EnumVariantId),
321     ConstId(ConstId),
322     StaticId(StaticId),
323     TraitId(TraitId),
324     TypeAliasId(TypeAliasId),
325     BuiltinType(BuiltinType),
326 }
327 impl_from!(
328     ModuleId,
329     FunctionId,
330     AdtId(StructId, EnumId, UnionId),
331     EnumVariantId,
332     ConstId,
333     StaticId,
334     TraitId,
335     TypeAliasId,
336     BuiltinType
337     for ModuleDefId
338 );
339
340 /// The defs which have a body.
341 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
342 pub enum DefWithBodyId {
343     FunctionId(FunctionId),
344     StaticId(StaticId),
345     ConstId(ConstId),
346 }
347
348 impl_from!(FunctionId, ConstId, StaticId for DefWithBodyId);
349
350 impl DefWithBodyId {
351     pub fn as_generic_def_id(self) -> Option<GenericDefId> {
352         match self {
353             DefWithBodyId::FunctionId(f) => Some(f.into()),
354             DefWithBodyId::StaticId(_) => None,
355             DefWithBodyId::ConstId(c) => Some(c.into()),
356         }
357     }
358 }
359
360 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
361 pub enum AssocItemId {
362     FunctionId(FunctionId),
363     ConstId(ConstId),
364     TypeAliasId(TypeAliasId),
365 }
366 // FIXME: not every function, ... is actually an assoc item. maybe we should make
367 // sure that you can only turn actual assoc items into AssocItemIds. This would
368 // require not implementing From, and instead having some checked way of
369 // casting them, and somehow making the constructors private, which would be annoying.
370 impl_from!(FunctionId, ConstId, TypeAliasId for AssocItemId);
371
372 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
373 pub enum GenericDefId {
374     FunctionId(FunctionId),
375     AdtId(AdtId),
376     TraitId(TraitId),
377     TypeAliasId(TypeAliasId),
378     ImplId(ImplId),
379     // enum variants cannot have generics themselves, but their parent enums
380     // can, and this makes some code easier to write
381     EnumVariantId(EnumVariantId),
382     // consts can have type parameters from their parents (i.e. associated consts of traits)
383     ConstId(ConstId),
384 }
385 impl_from!(
386     FunctionId,
387     AdtId(StructId, EnumId, UnionId),
388     TraitId,
389     TypeAliasId,
390     ImplId,
391     EnumVariantId,
392     ConstId
393     for GenericDefId
394 );
395
396 impl From<AssocItemId> for GenericDefId {
397     fn from(item: AssocItemId) -> Self {
398         match item {
399             AssocItemId::FunctionId(f) => f.into(),
400             AssocItemId::ConstId(c) => c.into(),
401             AssocItemId::TypeAliasId(t) => t.into(),
402         }
403     }
404 }
405
406 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
407 pub enum AttrDefId {
408     ModuleId(ModuleId),
409     FieldId(FieldId),
410     AdtId(AdtId),
411     FunctionId(FunctionId),
412     EnumVariantId(EnumVariantId),
413     StaticId(StaticId),
414     ConstId(ConstId),
415     TraitId(TraitId),
416     TypeAliasId(TypeAliasId),
417     MacroDefId(MacroDefId),
418     ImplId(ImplId),
419     GenericParamId(GenericParamId),
420 }
421
422 impl_from!(
423     ModuleId,
424     FieldId,
425     AdtId(StructId, EnumId, UnionId),
426     EnumVariantId,
427     StaticId,
428     ConstId,
429     FunctionId,
430     TraitId,
431     TypeAliasId,
432     MacroDefId,
433     ImplId,
434     GenericParamId
435     for AttrDefId
436 );
437
438 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
439 pub enum VariantId {
440     EnumVariantId(EnumVariantId),
441     StructId(StructId),
442     UnionId(UnionId),
443 }
444 impl_from!(EnumVariantId, StructId, UnionId for VariantId);
445
446 impl VariantId {
447     pub fn variant_data(self, db: &dyn db::DefDatabase) -> Arc<VariantData> {
448         match self {
449             VariantId::StructId(it) => db.struct_data(it).variant_data.clone(),
450             VariantId::UnionId(it) => db.union_data(it).variant_data.clone(),
451             VariantId::EnumVariantId(it) => {
452                 db.enum_data(it.parent).variants[it.local_id].variant_data.clone()
453             }
454         }
455     }
456
457     pub fn file_id(self, db: &dyn db::DefDatabase) -> HirFileId {
458         match self {
459             VariantId::EnumVariantId(it) => it.parent.lookup(db).id.file_id(),
460             VariantId::StructId(it) => it.lookup(db).id.file_id(),
461             VariantId::UnionId(it) => it.lookup(db).id.file_id(),
462         }
463     }
464 }
465
466 trait Intern {
467     type ID;
468     fn intern(self, db: &dyn db::DefDatabase) -> Self::ID;
469 }
470
471 pub trait Lookup {
472     type Data;
473     fn lookup(&self, db: &dyn db::DefDatabase) -> Self::Data;
474 }
475
476 pub trait HasModule {
477     fn module(&self, db: &dyn db::DefDatabase) -> ModuleId;
478 }
479
480 impl HasModule for AssocContainerId {
481     fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
482         match *self {
483             AssocContainerId::ModuleId(it) => it,
484             AssocContainerId::ImplId(it) => it.lookup(db).container,
485             AssocContainerId::TraitId(it) => it.lookup(db).container,
486         }
487     }
488 }
489
490 impl<N: ItemTreeNode> HasModule for AssocItemLoc<N> {
491     fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
492         self.container.module(db)
493     }
494 }
495
496 impl HasModule for AdtId {
497     fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
498         match self {
499             AdtId::StructId(it) => it.lookup(db).container,
500             AdtId::UnionId(it) => it.lookup(db).container,
501             AdtId::EnumId(it) => it.lookup(db).container,
502         }
503     }
504 }
505
506 impl HasModule for VariantId {
507     fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
508         match self {
509             VariantId::EnumVariantId(it) => it.parent.lookup(db).container,
510             VariantId::StructId(it) => it.lookup(db).container,
511             VariantId::UnionId(it) => it.lookup(db).container,
512         }
513     }
514 }
515
516 impl HasModule for DefWithBodyId {
517     fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
518         match self {
519             DefWithBodyId::FunctionId(it) => it.lookup(db).module(db),
520             DefWithBodyId::StaticId(it) => it.lookup(db).module(db),
521             DefWithBodyId::ConstId(it) => it.lookup(db).module(db),
522         }
523     }
524 }
525
526 impl DefWithBodyId {
527     pub fn as_mod_item(self, db: &dyn db::DefDatabase) -> ModItem {
528         match self {
529             DefWithBodyId::FunctionId(it) => it.lookup(db).id.value.into(),
530             DefWithBodyId::StaticId(it) => it.lookup(db).id.value.into(),
531             DefWithBodyId::ConstId(it) => it.lookup(db).id.value.into(),
532         }
533     }
534 }
535
536 impl HasModule for GenericDefId {
537     fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
538         match self {
539             GenericDefId::FunctionId(it) => it.lookup(db).module(db),
540             GenericDefId::AdtId(it) => it.module(db),
541             GenericDefId::TraitId(it) => it.lookup(db).container,
542             GenericDefId::TypeAliasId(it) => it.lookup(db).module(db),
543             GenericDefId::ImplId(it) => it.lookup(db).container,
544             GenericDefId::EnumVariantId(it) => it.parent.lookup(db).container,
545             GenericDefId::ConstId(it) => it.lookup(db).module(db),
546         }
547     }
548 }
549
550 impl HasModule for StaticLoc {
551     fn module(&self, _db: &dyn db::DefDatabase) -> ModuleId {
552         self.container
553     }
554 }
555
556 impl ModuleDefId {
557     /// Returns the module containing `self` (or `self`, if `self` is itself a module).
558     ///
559     /// Returns `None` if `self` refers to a primitive type.
560     pub fn module(&self, db: &dyn db::DefDatabase) -> Option<ModuleId> {
561         Some(match self {
562             ModuleDefId::ModuleId(id) => *id,
563             ModuleDefId::FunctionId(id) => id.lookup(db).module(db),
564             ModuleDefId::AdtId(id) => id.module(db),
565             ModuleDefId::EnumVariantId(id) => id.parent.lookup(db).container,
566             ModuleDefId::ConstId(id) => id.lookup(db).container.module(db),
567             ModuleDefId::StaticId(id) => id.lookup(db).container,
568             ModuleDefId::TraitId(id) => id.lookup(db).container,
569             ModuleDefId::TypeAliasId(id) => id.lookup(db).module(db),
570             ModuleDefId::BuiltinType(_) => return None,
571         })
572     }
573 }
574
575 impl AttrDefId {
576     pub fn krate(&self, db: &dyn db::DefDatabase) -> CrateId {
577         match self {
578             AttrDefId::ModuleId(it) => it.krate,
579             AttrDefId::FieldId(it) => it.parent.module(db).krate,
580             AttrDefId::AdtId(it) => it.module(db).krate,
581             AttrDefId::FunctionId(it) => it.lookup(db).module(db).krate,
582             AttrDefId::EnumVariantId(it) => it.parent.lookup(db).container.krate,
583             AttrDefId::StaticId(it) => it.lookup(db).module(db).krate,
584             AttrDefId::ConstId(it) => it.lookup(db).module(db).krate,
585             AttrDefId::TraitId(it) => it.lookup(db).container.krate,
586             AttrDefId::TypeAliasId(it) => it.lookup(db).module(db).krate,
587             AttrDefId::ImplId(it) => it.lookup(db).container.krate,
588             AttrDefId::GenericParamId(it) => {
589                 match it {
590                     GenericParamId::TypeParamId(it) => it.parent,
591                     GenericParamId::LifetimeParamId(it) => it.parent,
592                     GenericParamId::ConstParamId(it) => it.parent,
593                 }
594                 .module(db)
595                 .krate
596             }
597             // FIXME: `MacroDefId` should store the defining module, then this can implement
598             // `HasModule`
599             AttrDefId::MacroDefId(it) => it.krate,
600         }
601     }
602 }
603
604 /// A helper trait for converting to MacroCallId
605 pub trait AsMacroCall {
606     fn as_call_id(
607         &self,
608         db: &dyn db::DefDatabase,
609         krate: CrateId,
610         resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
611     ) -> Option<MacroCallId> {
612         self.as_call_id_with_errors(db, krate, resolver, &mut |_| ()).ok()?.ok()
613     }
614
615     fn as_call_id_with_errors(
616         &self,
617         db: &dyn db::DefDatabase,
618         krate: CrateId,
619         resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
620         error_sink: &mut dyn FnMut(mbe::ExpandError),
621     ) -> Result<Result<MacroCallId, ErrorEmitted>, UnresolvedMacro>;
622 }
623
624 impl AsMacroCall for InFile<&ast::MacroCall> {
625     fn as_call_id_with_errors(
626         &self,
627         db: &dyn db::DefDatabase,
628         krate: CrateId,
629         resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
630         mut error_sink: &mut dyn FnMut(mbe::ExpandError),
631     ) -> Result<Result<MacroCallId, ErrorEmitted>, UnresolvedMacro> {
632         let ast_id = AstId::new(self.file_id, db.ast_id_map(self.file_id).ast_id(self.value));
633         let h = Hygiene::new(db.upcast(), self.file_id);
634         let path = self.value.path().and_then(|path| path::ModPath::from_src(path, &h));
635
636         let path = match error_sink
637             .option(path, || mbe::ExpandError::Other("malformed macro invocation".into()))
638         {
639             Ok(path) => path,
640             Err(error) => {
641                 return Ok(Err(error));
642             }
643         };
644
645         macro_call_as_call_id(
646             &AstIdWithPath::new(ast_id.file_id, ast_id.value, path),
647             db,
648             krate,
649             resolver,
650             error_sink,
651         )
652     }
653 }
654
655 /// Helper wrapper for `AstId` with `ModPath`
656 #[derive(Clone, Debug, Eq, PartialEq)]
657 struct AstIdWithPath<T: ast::AstNode> {
658     ast_id: AstId<T>,
659     path: path::ModPath,
660 }
661
662 impl<T: ast::AstNode> AstIdWithPath<T> {
663     fn new(file_id: HirFileId, ast_id: FileAstId<T>, path: path::ModPath) -> AstIdWithPath<T> {
664         AstIdWithPath { ast_id: AstId::new(file_id, ast_id), path }
665     }
666 }
667
668 pub struct UnresolvedMacro;
669
670 fn macro_call_as_call_id(
671     call: &AstIdWithPath<ast::MacroCall>,
672     db: &dyn db::DefDatabase,
673     krate: CrateId,
674     resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
675     error_sink: &mut dyn FnMut(mbe::ExpandError),
676 ) -> Result<Result<MacroCallId, ErrorEmitted>, UnresolvedMacro> {
677     let def: MacroDefId = resolver(call.path.clone()).ok_or(UnresolvedMacro)?;
678
679     let res = if let MacroDefKind::BuiltInEager(..) = def.kind {
680         let macro_call = InFile::new(call.ast_id.file_id, call.ast_id.to_node(db.upcast()));
681         let hygiene = Hygiene::new(db.upcast(), call.ast_id.file_id);
682
683         expand_eager_macro(
684             db.upcast(),
685             krate,
686             macro_call,
687             def,
688             &|path: ast::Path| resolver(path::ModPath::from_src(path, &hygiene)?),
689             error_sink,
690         )
691         .map(MacroCallId::from)
692     } else {
693         Ok(def
694             .as_lazy_macro(db.upcast(), krate, MacroCallKind::FnLike { ast_id: call.ast_id })
695             .into())
696     };
697     Ok(res)
698 }
699
700 fn derive_macro_as_call_id(
701     item_attr: &AstIdWithPath<ast::Item>,
702     derive_attr: AttrId,
703     db: &dyn db::DefDatabase,
704     krate: CrateId,
705     resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
706 ) -> Result<MacroCallId, UnresolvedMacro> {
707     let def: MacroDefId = resolver(item_attr.path.clone()).ok_or(UnresolvedMacro)?;
708     let last_segment = item_attr.path.segments().last().ok_or(UnresolvedMacro)?;
709     let res = def
710         .as_lazy_macro(
711             db.upcast(),
712             krate,
713             MacroCallKind::Derive {
714                 ast_id: item_attr.ast_id,
715                 derive_name: last_segment.to_string(),
716                 derive_attr,
717             },
718         )
719         .into();
720     Ok(res)
721 }