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