]> git.lizzy.rs Git - rust.git/blob - crates/ra_hir/src/code_model.rs
Merge #1683
[rust.git] / crates / ra_hir / src / code_model.rs
1 pub(crate) mod src;
2 pub(crate) mod docs;
3
4 use std::sync::Arc;
5
6 use ra_db::{CrateId, Edition, FileId, SourceRootId};
7 use ra_syntax::ast::{self, NameOwner, TypeAscriptionOwner};
8
9 use crate::{
10     adt::{EnumVariantId, StructFieldId, VariantDef},
11     diagnostics::DiagnosticSink,
12     expr::{validation::ExprValidator, Body, BodySourceMap},
13     generics::HasGenericParams,
14     ids::{
15         AstItemDef, ConstId, EnumId, FunctionId, MacroDefId, StaticId, StructId, TraitId,
16         TypeAliasId,
17     },
18     impl_block::ImplBlock,
19     name::{
20         BOOL, CHAR, F32, F64, I128, I16, I32, I64, I8, ISIZE, SELF_TYPE, STR, U128, U16, U32, U64,
21         U8, USIZE,
22     },
23     nameres::{CrateModuleId, ImportId, ModuleScope, Namespace},
24     resolve::Resolver,
25     traits::{TraitData, TraitItem},
26     ty::{
27         primitive::{FloatBitness, FloatTy, IntBitness, IntTy, Signedness},
28         InferenceResult, TraitRef,
29     },
30     type_ref::Mutability,
31     type_ref::TypeRef,
32     AsName, AstDatabase, AstId, DefDatabase, Either, HasSource, HirDatabase, Name, Ty,
33 };
34
35 /// hir::Crate describes a single crate. It's the main interface with which
36 /// a crate's dependencies interact. Mostly, it should be just a proxy for the
37 /// root module.
38 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
39 pub struct Crate {
40     pub(crate) crate_id: CrateId,
41 }
42
43 #[derive(Debug)]
44 pub struct CrateDependency {
45     pub krate: Crate,
46     pub name: Name,
47 }
48
49 impl Crate {
50     pub fn crate_id(self) -> CrateId {
51         self.crate_id
52     }
53
54     pub fn dependencies(self, db: &impl DefDatabase) -> Vec<CrateDependency> {
55         db.crate_graph()
56             .dependencies(self.crate_id)
57             .map(|dep| {
58                 let krate = Crate { crate_id: dep.crate_id() };
59                 let name = dep.as_name();
60                 CrateDependency { krate, name }
61             })
62             .collect()
63     }
64
65     pub fn root_module(self, db: &impl DefDatabase) -> Option<Module> {
66         let module_id = db.crate_def_map(self).root();
67         let module = Module { krate: self, module_id };
68         Some(module)
69     }
70
71     pub fn edition(self, db: &impl DefDatabase) -> Edition {
72         let crate_graph = db.crate_graph();
73         crate_graph.edition(self.crate_id)
74     }
75
76     // FIXME: should this be in source_binder?
77     pub fn source_root_crates(db: &impl DefDatabase, source_root: SourceRootId) -> Vec<Crate> {
78         let crate_ids = db.source_root_crates(source_root);
79         crate_ids.iter().map(|&crate_id| Crate { crate_id }).collect()
80     }
81 }
82
83 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
84 pub struct Module {
85     pub(crate) krate: Crate,
86     pub(crate) module_id: CrateModuleId,
87 }
88
89 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
90 pub enum BuiltinType {
91     Char,
92     Bool,
93     Str,
94     Int(IntTy),
95     Float(FloatTy),
96 }
97
98 impl BuiltinType {
99     #[rustfmt::skip]
100     pub(crate) const ALL: &'static [(Name, BuiltinType)] = &[
101         (CHAR, BuiltinType::Char),
102         (BOOL, BuiltinType::Bool),
103         (STR, BuiltinType::Str),
104
105         (ISIZE, BuiltinType::Int(IntTy { signedness: Signedness::Signed, bitness: IntBitness::Xsize })),
106         (I8,    BuiltinType::Int(IntTy { signedness: Signedness::Signed, bitness: IntBitness::X8 })),
107         (I16,   BuiltinType::Int(IntTy { signedness: Signedness::Signed, bitness: IntBitness::X16 })),
108         (I32,   BuiltinType::Int(IntTy { signedness: Signedness::Signed, bitness: IntBitness::X32 })),
109         (I64,   BuiltinType::Int(IntTy { signedness: Signedness::Signed, bitness: IntBitness::X64 })),
110         (I128,  BuiltinType::Int(IntTy { signedness: Signedness::Signed, bitness: IntBitness::X128 })),
111
112         (USIZE, BuiltinType::Int(IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::Xsize })),
113         (U8,    BuiltinType::Int(IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::X8 })),
114         (U16,   BuiltinType::Int(IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::X16 })),
115         (U32,   BuiltinType::Int(IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::X32 })),
116         (U64,   BuiltinType::Int(IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::X64 })),
117         (U128,  BuiltinType::Int(IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::X128 })),
118
119         (F32, BuiltinType::Float(FloatTy { bitness: FloatBitness::X32 })),
120         (F64, BuiltinType::Float(FloatTy { bitness: FloatBitness::X64 })),
121     ];
122 }
123
124 /// The defs which can be visible in the module.
125 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
126 pub enum ModuleDef {
127     Module(Module),
128     Function(Function),
129     Struct(Struct),
130     Union(Union),
131     Enum(Enum),
132     // Can't be directly declared, but can be imported.
133     EnumVariant(EnumVariant),
134     Const(Const),
135     Static(Static),
136     Trait(Trait),
137     TypeAlias(TypeAlias),
138     BuiltinType(BuiltinType),
139 }
140 impl_froms!(
141     ModuleDef: Module,
142     Function,
143     Struct,
144     Union,
145     Enum,
146     EnumVariant,
147     Const,
148     Static,
149     Trait,
150     TypeAlias,
151     BuiltinType
152 );
153
154 pub enum ModuleSource {
155     SourceFile(ast::SourceFile),
156     Module(ast::Module),
157 }
158
159 impl ModuleSource {
160     pub(crate) fn new(
161         db: &(impl DefDatabase + AstDatabase),
162         file_id: Option<FileId>,
163         decl_id: Option<AstId<ast::Module>>,
164     ) -> ModuleSource {
165         match (file_id, decl_id) {
166             (Some(file_id), _) => {
167                 let source_file = db.parse(file_id).tree().to_owned();
168                 ModuleSource::SourceFile(source_file)
169             }
170             (None, Some(item_id)) => {
171                 let module = item_id.to_node(db);
172                 assert!(module.item_list().is_some(), "expected inline module");
173                 ModuleSource::Module(module)
174             }
175             (None, None) => panic!(),
176         }
177     }
178 }
179
180 impl Module {
181     /// Name of this module.
182     pub fn name(self, db: &impl DefDatabase) -> Option<Name> {
183         let def_map = db.crate_def_map(self.krate);
184         let parent = def_map[self.module_id].parent?;
185         def_map[parent].children.iter().find_map(|(name, module_id)| {
186             if *module_id == self.module_id {
187                 Some(name.clone())
188             } else {
189                 None
190             }
191         })
192     }
193
194     /// Returns the syntax of the last path segment corresponding to this import
195     pub fn import_source(
196         self,
197         db: &impl HirDatabase,
198         import: ImportId,
199     ) -> Either<ast::UseTree, ast::ExternCrateItem> {
200         let src = self.definition_source(db);
201         let (_, source_map) = db.raw_items_with_source_map(src.file_id);
202         source_map.get(&src.ast, import)
203     }
204
205     /// Returns the crate this module is part of.
206     pub fn krate(self, _db: &impl DefDatabase) -> Option<Crate> {
207         Some(self.krate)
208     }
209
210     /// Topmost parent of this module. Every module has a `crate_root`, but some
211     /// might be missing `krate`. This can happen if a module's file is not included
212     /// in the module tree of any target in `Cargo.toml`.
213     pub fn crate_root(self, db: &impl DefDatabase) -> Module {
214         let def_map = db.crate_def_map(self.krate);
215         self.with_module_id(def_map.root())
216     }
217
218     /// Finds a child module with the specified name.
219     pub fn child(self, db: &impl HirDatabase, name: &Name) -> Option<Module> {
220         let def_map = db.crate_def_map(self.krate);
221         let child_id = def_map[self.module_id].children.get(name)?;
222         Some(self.with_module_id(*child_id))
223     }
224
225     /// Iterates over all child modules.
226     pub fn children(self, db: &impl DefDatabase) -> impl Iterator<Item = Module> {
227         let def_map = db.crate_def_map(self.krate);
228         let children = def_map[self.module_id]
229             .children
230             .iter()
231             .map(|(_, module_id)| self.with_module_id(*module_id))
232             .collect::<Vec<_>>();
233         children.into_iter()
234     }
235
236     /// Finds a parent module.
237     pub fn parent(self, db: &impl DefDatabase) -> Option<Module> {
238         let def_map = db.crate_def_map(self.krate);
239         let parent_id = def_map[self.module_id].parent?;
240         Some(self.with_module_id(parent_id))
241     }
242
243     pub fn path_to_root(self, db: &impl HirDatabase) -> Vec<Module> {
244         let mut res = vec![self];
245         let mut curr = self;
246         while let Some(next) = curr.parent(db) {
247             res.push(next);
248             curr = next
249         }
250         res
251     }
252
253     /// Returns a `ModuleScope`: a set of items, visible in this module.
254     pub fn scope(self, db: &impl HirDatabase) -> ModuleScope {
255         db.crate_def_map(self.krate)[self.module_id].scope.clone()
256     }
257
258     pub fn diagnostics(self, db: &impl HirDatabase, sink: &mut DiagnosticSink) {
259         db.crate_def_map(self.krate).add_diagnostics(db, self.module_id, sink);
260         for decl in self.declarations(db) {
261             match decl {
262                 crate::ModuleDef::Function(f) => f.diagnostics(db, sink),
263                 crate::ModuleDef::Module(m) => {
264                     // Only add diagnostics from inline modules
265                     if let ModuleSource::Module(_) = m.definition_source(db).ast {
266                         m.diagnostics(db, sink)
267                     }
268                 }
269                 _ => (),
270             }
271         }
272
273         for impl_block in self.impl_blocks(db) {
274             for item in impl_block.items(db) {
275                 if let crate::ImplItem::Method(f) = item {
276                     f.diagnostics(db, sink);
277                 }
278             }
279         }
280     }
281
282     pub(crate) fn resolver(self, db: &impl DefDatabase) -> Resolver {
283         let def_map = db.crate_def_map(self.krate);
284         Resolver::default().push_module_scope(def_map, self.module_id)
285     }
286
287     pub fn declarations(self, db: &impl DefDatabase) -> Vec<ModuleDef> {
288         let def_map = db.crate_def_map(self.krate);
289         def_map[self.module_id]
290             .scope
291             .entries()
292             .filter_map(|(_name, res)| if res.import.is_none() { Some(res.def) } else { None })
293             .flat_map(|per_ns| {
294                 per_ns.take_types().into_iter().chain(per_ns.take_values().into_iter())
295             })
296             .collect()
297     }
298
299     pub fn impl_blocks(self, db: &impl DefDatabase) -> Vec<ImplBlock> {
300         let module_impl_blocks = db.impls_in_module(self);
301         module_impl_blocks
302             .impls
303             .iter()
304             .map(|(impl_id, _)| ImplBlock::from_id(self, impl_id))
305             .collect()
306     }
307
308     fn with_module_id(self, module_id: CrateModuleId) -> Module {
309         Module { module_id, krate: self.krate }
310     }
311 }
312
313 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
314 pub struct StructField {
315     pub(crate) parent: VariantDef,
316     pub(crate) id: StructFieldId,
317 }
318
319 #[derive(Debug)]
320 pub enum FieldSource {
321     Named(ast::NamedFieldDef),
322     Pos(ast::PosFieldDef),
323 }
324
325 impl StructField {
326     pub fn name(&self, db: &impl HirDatabase) -> Name {
327         self.parent.variant_data(db).fields().unwrap()[self.id].name.clone()
328     }
329
330     pub fn ty(&self, db: &impl HirDatabase) -> Ty {
331         db.type_for_field(*self)
332     }
333
334     pub fn parent_def(&self, _db: &impl HirDatabase) -> VariantDef {
335         self.parent
336     }
337 }
338
339 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
340 pub struct Struct {
341     pub(crate) id: StructId,
342 }
343
344 impl Struct {
345     pub fn module(self, db: &impl HirDatabase) -> Module {
346         self.id.module(db)
347     }
348
349     pub fn name(self, db: &impl DefDatabase) -> Option<Name> {
350         db.struct_data(self).name.clone()
351     }
352
353     pub fn fields(self, db: &impl HirDatabase) -> Vec<StructField> {
354         db.struct_data(self)
355             .variant_data
356             .fields()
357             .into_iter()
358             .flat_map(|it| it.iter())
359             .map(|(id, _)| StructField { parent: self.into(), id })
360             .collect()
361     }
362
363     pub fn field(self, db: &impl HirDatabase, name: &Name) -> Option<StructField> {
364         db.struct_data(self)
365             .variant_data
366             .fields()
367             .into_iter()
368             .flat_map(|it| it.iter())
369             .find(|(_id, data)| data.name == *name)
370             .map(|(id, _)| StructField { parent: self.into(), id })
371     }
372
373     pub fn ty(self, db: &impl HirDatabase) -> Ty {
374         db.type_for_def(self.into(), Namespace::Types)
375     }
376
377     pub fn constructor_ty(self, db: &impl HirDatabase) -> Ty {
378         db.type_for_def(self.into(), Namespace::Values)
379     }
380
381     // FIXME move to a more general type
382     /// Builds a resolver for type references inside this struct.
383     pub(crate) fn resolver(self, db: &impl HirDatabase) -> Resolver {
384         // take the outer scope...
385         let r = self.module(db).resolver(db);
386         // ...and add generic params, if present
387         let p = self.generic_params(db);
388         let r = if !p.params.is_empty() { r.push_generic_params_scope(p) } else { r };
389         r
390     }
391 }
392
393 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
394 pub struct Union {
395     pub(crate) id: StructId,
396 }
397
398 impl Union {
399     pub fn name(self, db: &impl DefDatabase) -> Option<Name> {
400         db.struct_data(Struct { id: self.id }).name.clone()
401     }
402
403     pub fn module(self, db: &impl HirDatabase) -> Module {
404         self.id.module(db)
405     }
406
407     pub fn ty(self, db: &impl HirDatabase) -> Ty {
408         db.type_for_def(self.into(), Namespace::Types)
409     }
410
411     // FIXME move to a more general type
412     /// Builds a resolver for type references inside this union.
413     pub(crate) fn resolver(self, db: &impl HirDatabase) -> Resolver {
414         // take the outer scope...
415         let r = self.module(db).resolver(db);
416         // ...and add generic params, if present
417         let p = self.generic_params(db);
418         let r = if !p.params.is_empty() { r.push_generic_params_scope(p) } else { r };
419         r
420     }
421 }
422
423 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
424 pub struct Enum {
425     pub(crate) id: EnumId,
426 }
427
428 impl Enum {
429     pub fn module(self, db: &impl HirDatabase) -> Module {
430         self.id.module(db)
431     }
432
433     pub fn name(self, db: &impl DefDatabase) -> Option<Name> {
434         db.enum_data(self).name.clone()
435     }
436
437     pub fn variants(self, db: &impl DefDatabase) -> Vec<EnumVariant> {
438         db.enum_data(self).variants.iter().map(|(id, _)| EnumVariant { parent: self, id }).collect()
439     }
440
441     pub fn variant(self, db: &impl DefDatabase, name: &Name) -> Option<EnumVariant> {
442         db.enum_data(self)
443             .variants
444             .iter()
445             .find(|(_id, data)| data.name.as_ref() == Some(name))
446             .map(|(id, _)| EnumVariant { parent: self, id })
447     }
448
449     pub fn ty(self, db: &impl HirDatabase) -> Ty {
450         db.type_for_def(self.into(), Namespace::Types)
451     }
452
453     // FIXME: move to a more general type
454     /// Builds a resolver for type references inside this struct.
455     pub(crate) fn resolver(self, db: &impl HirDatabase) -> Resolver {
456         // take the outer scope...
457         let r = self.module(db).resolver(db);
458         // ...and add generic params, if present
459         let p = self.generic_params(db);
460         let r = if !p.params.is_empty() { r.push_generic_params_scope(p) } else { r };
461         r
462     }
463 }
464
465 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
466 pub struct EnumVariant {
467     pub(crate) parent: Enum,
468     pub(crate) id: EnumVariantId,
469 }
470
471 impl EnumVariant {
472     pub fn module(self, db: &impl HirDatabase) -> Module {
473         self.parent.module(db)
474     }
475     pub fn parent_enum(self, _db: &impl DefDatabase) -> Enum {
476         self.parent
477     }
478
479     pub fn name(self, db: &impl DefDatabase) -> Option<Name> {
480         db.enum_data(self.parent).variants[self.id].name.clone()
481     }
482
483     pub fn fields(self, db: &impl HirDatabase) -> Vec<StructField> {
484         self.variant_data(db)
485             .fields()
486             .into_iter()
487             .flat_map(|it| it.iter())
488             .map(|(id, _)| StructField { parent: self.into(), id })
489             .collect()
490     }
491
492     pub fn field(self, db: &impl HirDatabase, name: &Name) -> Option<StructField> {
493         self.variant_data(db)
494             .fields()
495             .into_iter()
496             .flat_map(|it| it.iter())
497             .find(|(_id, data)| data.name == *name)
498             .map(|(id, _)| StructField { parent: self.into(), id })
499     }
500 }
501
502 /// The defs which have a body.
503 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
504 pub enum DefWithBody {
505     Function(Function),
506     Static(Static),
507     Const(Const),
508 }
509
510 impl_froms!(DefWithBody: Function, Const, Static);
511
512 impl DefWithBody {
513     pub fn infer(self, db: &impl HirDatabase) -> Arc<InferenceResult> {
514         db.infer(self)
515     }
516
517     pub fn body(self, db: &impl HirDatabase) -> Arc<Body> {
518         db.body_hir(self)
519     }
520
521     pub fn body_source_map(self, db: &impl HirDatabase) -> Arc<BodySourceMap> {
522         db.body_with_source_map(self).1
523     }
524
525     /// Builds a resolver for code inside this item.
526     pub(crate) fn resolver(self, db: &impl HirDatabase) -> Resolver {
527         match self {
528             DefWithBody::Const(c) => c.resolver(db),
529             DefWithBody::Function(f) => f.resolver(db),
530             DefWithBody::Static(s) => s.resolver(db),
531         }
532     }
533 }
534
535 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
536 pub struct Function {
537     pub(crate) id: FunctionId,
538 }
539
540 #[derive(Debug, Clone, PartialEq, Eq)]
541 pub struct FnData {
542     pub(crate) name: Name,
543     pub(crate) params: Vec<TypeRef>,
544     pub(crate) ret_type: TypeRef,
545     /// True if the first param is `self`. This is relevant to decide whether this
546     /// can be called as a method.
547     pub(crate) has_self_param: bool,
548 }
549
550 impl FnData {
551     pub(crate) fn fn_data_query(
552         db: &(impl DefDatabase + AstDatabase),
553         func: Function,
554     ) -> Arc<FnData> {
555         let src = func.source(db);
556         let name = src.ast.name().map(|n| n.as_name()).unwrap_or_else(Name::missing);
557         let mut params = Vec::new();
558         let mut has_self_param = false;
559         if let Some(param_list) = src.ast.param_list() {
560             if let Some(self_param) = param_list.self_param() {
561                 let self_type = if let Some(type_ref) = self_param.ascribed_type() {
562                     TypeRef::from_ast(type_ref)
563                 } else {
564                     let self_type = TypeRef::Path(SELF_TYPE.into());
565                     match self_param.kind() {
566                         ast::SelfParamKind::Owned => self_type,
567                         ast::SelfParamKind::Ref => {
568                             TypeRef::Reference(Box::new(self_type), Mutability::Shared)
569                         }
570                         ast::SelfParamKind::MutRef => {
571                             TypeRef::Reference(Box::new(self_type), Mutability::Mut)
572                         }
573                     }
574                 };
575                 params.push(self_type);
576                 has_self_param = true;
577             }
578             for param in param_list.params() {
579                 let type_ref = TypeRef::from_ast_opt(param.ascribed_type());
580                 params.push(type_ref);
581             }
582         }
583         let ret_type = if let Some(type_ref) = src.ast.ret_type().and_then(|rt| rt.type_ref()) {
584             TypeRef::from_ast(type_ref)
585         } else {
586             TypeRef::unit()
587         };
588
589         let sig = FnData { name, params, ret_type, has_self_param };
590         Arc::new(sig)
591     }
592     pub fn name(&self) -> &Name {
593         &self.name
594     }
595
596     pub fn params(&self) -> &[TypeRef] {
597         &self.params
598     }
599
600     pub fn ret_type(&self) -> &TypeRef {
601         &self.ret_type
602     }
603
604     /// True if the first arg is `self`. This is relevant to decide whether this
605     /// can be called as a method.
606     pub fn has_self_param(&self) -> bool {
607         self.has_self_param
608     }
609 }
610
611 impl Function {
612     pub fn module(self, db: &impl DefDatabase) -> Module {
613         self.id.module(db)
614     }
615
616     pub fn name(self, db: &impl HirDatabase) -> Name {
617         self.data(db).name.clone()
618     }
619
620     pub(crate) fn body_source_map(self, db: &impl HirDatabase) -> Arc<BodySourceMap> {
621         db.body_with_source_map(self.into()).1
622     }
623
624     pub fn body(self, db: &impl HirDatabase) -> Arc<Body> {
625         db.body_hir(self.into())
626     }
627
628     pub fn ty(self, db: &impl HirDatabase) -> Ty {
629         db.type_for_def(self.into(), Namespace::Values)
630     }
631
632     pub fn data(self, db: &impl HirDatabase) -> Arc<FnData> {
633         db.fn_data(self)
634     }
635
636     pub fn infer(self, db: &impl HirDatabase) -> Arc<InferenceResult> {
637         db.infer(self.into())
638     }
639
640     /// The containing impl block, if this is a method.
641     pub fn impl_block(self, db: &impl DefDatabase) -> Option<ImplBlock> {
642         let module_impls = db.impls_in_module(self.module(db));
643         ImplBlock::containing(module_impls, self.into())
644     }
645
646     /// The containing trait, if this is a trait method definition.
647     pub fn parent_trait(self, db: &impl DefDatabase) -> Option<Trait> {
648         db.trait_items_index(self.module(db)).get_parent_trait(self.into())
649     }
650
651     pub fn container(self, db: &impl DefDatabase) -> Option<Container> {
652         if let Some(impl_block) = self.impl_block(db) {
653             Some(impl_block.into())
654         } else if let Some(trait_) = self.parent_trait(db) {
655             Some(trait_.into())
656         } else {
657             None
658         }
659     }
660
661     // FIXME: move to a more general type for 'body-having' items
662     /// Builds a resolver for code inside this item.
663     pub(crate) fn resolver(self, db: &impl HirDatabase) -> Resolver {
664         // take the outer scope...
665         let r = self.container(db).map_or_else(|| self.module(db).resolver(db), |c| c.resolver(db));
666         // ...and add generic params, if present
667         let p = self.generic_params(db);
668         let r = if !p.params.is_empty() { r.push_generic_params_scope(p) } else { r };
669         r
670     }
671
672     pub fn diagnostics(self, db: &impl HirDatabase, sink: &mut DiagnosticSink) {
673         let infer = self.infer(db);
674         infer.add_diagnostics(db, self, sink);
675         let mut validator = ExprValidator::new(self, infer, sink);
676         validator.validate_body(db);
677     }
678 }
679
680 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
681 pub struct Const {
682     pub(crate) id: ConstId,
683 }
684
685 impl Const {
686     pub fn module(self, db: &impl DefDatabase) -> Module {
687         self.id.module(db)
688     }
689
690     pub fn data(self, db: &impl HirDatabase) -> Arc<ConstData> {
691         db.const_data(self)
692     }
693
694     pub fn infer(self, db: &impl HirDatabase) -> Arc<InferenceResult> {
695         db.infer(self.into())
696     }
697
698     /// The containing impl block, if this is a method.
699     pub fn impl_block(self, db: &impl DefDatabase) -> Option<ImplBlock> {
700         let module_impls = db.impls_in_module(self.module(db));
701         ImplBlock::containing(module_impls, self.into())
702     }
703
704     // FIXME: move to a more general type for 'body-having' items
705     /// Builds a resolver for code inside this item.
706     pub(crate) fn resolver(self, db: &impl HirDatabase) -> Resolver {
707         // take the outer scope...
708         let r = self
709             .impl_block(db)
710             .map(|ib| ib.resolver(db))
711             .unwrap_or_else(|| self.module(db).resolver(db));
712         r
713     }
714 }
715
716 #[derive(Debug, Clone, PartialEq, Eq)]
717 pub struct ConstData {
718     pub(crate) name: Name,
719     pub(crate) type_ref: TypeRef,
720 }
721
722 impl ConstData {
723     pub fn name(&self) -> &Name {
724         &self.name
725     }
726
727     pub fn type_ref(&self) -> &TypeRef {
728         &self.type_ref
729     }
730
731     pub(crate) fn const_data_query(
732         db: &(impl DefDatabase + AstDatabase),
733         konst: Const,
734     ) -> Arc<ConstData> {
735         let node = konst.source(db).ast;
736         const_data_for(&node)
737     }
738
739     pub(crate) fn static_data_query(
740         db: &(impl DefDatabase + AstDatabase),
741         konst: Static,
742     ) -> Arc<ConstData> {
743         let node = konst.source(db).ast;
744         const_data_for(&node)
745     }
746 }
747
748 fn const_data_for<N: NameOwner + TypeAscriptionOwner>(node: &N) -> Arc<ConstData> {
749     let name = node.name().map(|n| n.as_name()).unwrap_or_else(Name::missing);
750     let type_ref = TypeRef::from_ast_opt(node.ascribed_type());
751     let sig = ConstData { name, type_ref };
752     Arc::new(sig)
753 }
754
755 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
756 pub struct Static {
757     pub(crate) id: StaticId,
758 }
759
760 impl Static {
761     pub fn module(self, db: &impl DefDatabase) -> Module {
762         self.id.module(db)
763     }
764
765     pub fn data(self, db: &impl HirDatabase) -> Arc<ConstData> {
766         db.static_data(self)
767     }
768
769     /// Builds a resolver for code inside this item.
770     pub(crate) fn resolver(self, db: &impl HirDatabase) -> Resolver {
771         // take the outer scope...
772         self.module(db).resolver(db)
773     }
774
775     pub fn infer(self, db: &impl HirDatabase) -> Arc<InferenceResult> {
776         db.infer(self.into())
777     }
778 }
779
780 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
781 pub struct Trait {
782     pub(crate) id: TraitId,
783 }
784
785 impl Trait {
786     pub fn module(self, db: &impl DefDatabase) -> Module {
787         self.id.module(db)
788     }
789
790     pub fn name(self, db: &impl DefDatabase) -> Option<Name> {
791         self.trait_data(db).name().clone()
792     }
793
794     pub fn items(self, db: &impl DefDatabase) -> Vec<TraitItem> {
795         self.trait_data(db).items().to_vec()
796     }
797
798     pub fn associated_type_by_name(self, db: &impl DefDatabase, name: Name) -> Option<TypeAlias> {
799         let trait_data = self.trait_data(db);
800         trait_data
801             .items()
802             .iter()
803             .filter_map(|item| match item {
804                 TraitItem::TypeAlias(t) => Some(*t),
805                 _ => None,
806             })
807             .find(|t| t.name(db) == name)
808     }
809
810     pub(crate) fn trait_data(self, db: &impl DefDatabase) -> Arc<TraitData> {
811         db.trait_data(self)
812     }
813
814     pub fn trait_ref(self, db: &impl HirDatabase) -> TraitRef {
815         TraitRef::for_trait(db, self)
816     }
817
818     pub fn is_auto(self, db: &impl DefDatabase) -> bool {
819         self.trait_data(db).is_auto()
820     }
821
822     pub(crate) fn resolver(self, db: &impl DefDatabase) -> Resolver {
823         let r = self.module(db).resolver(db);
824         // add generic params, if present
825         let p = self.generic_params(db);
826         let r = if !p.params.is_empty() { r.push_generic_params_scope(p) } else { r };
827         r
828     }
829 }
830
831 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
832 pub struct TypeAlias {
833     pub(crate) id: TypeAliasId,
834 }
835
836 impl TypeAlias {
837     pub fn module(self, db: &impl DefDatabase) -> Module {
838         self.id.module(db)
839     }
840
841     /// The containing impl block, if this is a method.
842     pub fn impl_block(self, db: &impl DefDatabase) -> Option<ImplBlock> {
843         let module_impls = db.impls_in_module(self.module(db));
844         ImplBlock::containing(module_impls, self.into())
845     }
846
847     /// The containing trait, if this is a trait method definition.
848     pub fn parent_trait(self, db: &impl DefDatabase) -> Option<Trait> {
849         db.trait_items_index(self.module(db)).get_parent_trait(self.into())
850     }
851
852     pub fn container(self, db: &impl DefDatabase) -> Option<Container> {
853         if let Some(impl_block) = self.impl_block(db) {
854             Some(impl_block.into())
855         } else if let Some(trait_) = self.parent_trait(db) {
856             Some(trait_.into())
857         } else {
858             None
859         }
860     }
861
862     pub fn type_ref(self, db: &impl DefDatabase) -> Option<TypeRef> {
863         db.type_alias_data(self).type_ref.clone()
864     }
865
866     pub fn ty(self, db: &impl HirDatabase) -> Ty {
867         db.type_for_def(self.into(), Namespace::Types)
868     }
869
870     pub fn name(self, db: &impl DefDatabase) -> Name {
871         db.type_alias_data(self).name.clone()
872     }
873
874     /// Builds a resolver for the type references in this type alias.
875     pub(crate) fn resolver(self, db: &impl HirDatabase) -> Resolver {
876         // take the outer scope...
877         let r = self
878             .impl_block(db)
879             .map(|ib| ib.resolver(db))
880             .unwrap_or_else(|| self.module(db).resolver(db));
881         // ...and add generic params, if present
882         let p = self.generic_params(db);
883         let r = if !p.params.is_empty() { r.push_generic_params_scope(p) } else { r };
884         r
885     }
886 }
887
888 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
889 pub struct MacroDef {
890     pub(crate) id: MacroDefId,
891 }
892
893 impl MacroDef {}
894
895 pub enum Container {
896     Trait(Trait),
897     ImplBlock(ImplBlock),
898 }
899 impl_froms!(Container: Trait, ImplBlock);
900
901 impl Container {
902     pub(crate) fn resolver(self, db: &impl DefDatabase) -> Resolver {
903         match self {
904             Container::Trait(trait_) => trait_.resolver(db),
905             Container::ImplBlock(impl_block) => impl_block.resolver(db),
906         }
907     }
908 }