aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_hir/src/code_model.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_hir/src/code_model.rs')
-rw-r--r--crates/ra_hir/src/code_model.rs211
1 files changed, 66 insertions, 145 deletions
diff --git a/crates/ra_hir/src/code_model.rs b/crates/ra_hir/src/code_model.rs
index 4578a0ba8..7ac1bf461 100644
--- a/crates/ra_hir/src/code_model.rs
+++ b/crates/ra_hir/src/code_model.rs
@@ -7,7 +7,6 @@ use std::sync::Arc;
7use either::Either; 7use either::Either;
8use hir_def::{ 8use hir_def::{
9 adt::VariantData, 9 adt::VariantData,
10 body::{Body, BodySourceMap},
11 builtin_type::BuiltinType, 10 builtin_type::BuiltinType,
12 docs::Documentation, 11 docs::Documentation,
13 expr::{BindingAnnotation, Pat, PatId}, 12 expr::{BindingAnnotation, Pat, PatId},
@@ -24,14 +23,15 @@ use hir_expand::{
24 name::{self, AsName}, 23 name::{self, AsName},
25 MacroDefId, 24 MacroDefId,
26}; 25};
27use hir_ty::expr::ExprValidator; 26use hir_ty::{
28use ra_db::{CrateId, Edition}; 27 autoderef, display::HirFormatter, expr::ExprValidator, ApplicationTy, Canonical, InEnvironment,
28 TraitEnvironment, Ty, TyDefId, TypeCtor, TypeWalk,
29};
30use ra_db::{CrateId, Edition, FileId};
29use ra_syntax::ast; 31use ra_syntax::ast;
30 32
31use crate::{ 33use crate::{
32 db::{DefDatabase, HirDatabase}, 34 db::{DefDatabase, HirDatabase},
33 ty::display::HirFormatter,
34 ty::{self, InEnvironment, InferenceResult, TraitEnvironment, Ty, TyDefId, TypeCtor, TypeWalk},
35 CallableDef, HirDisplay, InFile, Name, 35 CallableDef, HirDisplay, InFile, Name,
36}; 36};
37 37
@@ -40,7 +40,7 @@ use crate::{
40/// root module. 40/// root module.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 41#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
42pub struct Crate { 42pub struct Crate {
43 pub(crate) crate_id: CrateId, 43 pub(crate) id: CrateId,
44} 44}
45 45
46#[derive(Debug)] 46#[derive(Debug)]
@@ -50,33 +50,43 @@ pub struct CrateDependency {
50} 50}
51 51
52impl Crate { 52impl Crate {
53 pub fn crate_id(self) -> CrateId {
54 self.crate_id
55 }
56
57 pub fn dependencies(self, db: &impl DefDatabase) -> Vec<CrateDependency> { 53 pub fn dependencies(self, db: &impl DefDatabase) -> Vec<CrateDependency> {
58 db.crate_graph() 54 db.crate_graph()
59 .dependencies(self.crate_id) 55 .dependencies(self.id)
60 .map(|dep| { 56 .map(|dep| {
61 let krate = Crate { crate_id: dep.crate_id() }; 57 let krate = Crate { id: dep.crate_id() };
62 let name = dep.as_name(); 58 let name = dep.as_name();
63 CrateDependency { krate, name } 59 CrateDependency { krate, name }
64 }) 60 })
65 .collect() 61 .collect()
66 } 62 }
67 63
64 // FIXME: add `transitive_reverse_dependencies`.
65 pub fn reverse_dependencies(self, db: &impl DefDatabase) -> Vec<Crate> {
66 let crate_graph = db.crate_graph();
67 crate_graph
68 .iter()
69 .filter(|&krate| crate_graph.dependencies(krate).any(|it| it.crate_id == self.id))
70 .map(|id| Crate { id })
71 .collect()
72 }
73
68 pub fn root_module(self, db: &impl DefDatabase) -> Option<Module> { 74 pub fn root_module(self, db: &impl DefDatabase) -> Option<Module> {
69 let module_id = db.crate_def_map(self.crate_id).root; 75 let module_id = db.crate_def_map(self.id).root;
70 Some(Module::new(self, module_id)) 76 Some(Module::new(self, module_id))
71 } 77 }
72 78
79 pub fn root_file(self, db: &impl DefDatabase) -> FileId {
80 db.crate_graph().crate_root(self.id)
81 }
82
73 pub fn edition(self, db: &impl DefDatabase) -> Edition { 83 pub fn edition(self, db: &impl DefDatabase) -> Edition {
74 let crate_graph = db.crate_graph(); 84 let crate_graph = db.crate_graph();
75 crate_graph.edition(self.crate_id) 85 crate_graph.edition(self.id)
76 } 86 }
77 87
78 pub fn all(db: &impl DefDatabase) -> Vec<Crate> { 88 pub fn all(db: &impl DefDatabase) -> Vec<Crate> {
79 db.crate_graph().iter().map(|crate_id| Crate { crate_id }).collect() 89 db.crate_graph().iter().map(|id| Crate { id }).collect()
80 } 90 }
81} 91}
82 92
@@ -115,7 +125,7 @@ pub use hir_def::attr::Attrs;
115 125
116impl Module { 126impl Module {
117 pub(crate) fn new(krate: Crate, crate_module_id: LocalModuleId) -> Module { 127 pub(crate) fn new(krate: Crate, crate_module_id: LocalModuleId) -> Module {
118 Module { id: ModuleId { krate: krate.crate_id, local_id: crate_module_id } } 128 Module { id: ModuleId { krate: krate.id, local_id: crate_module_id } }
119 } 129 }
120 130
121 /// Name of this module. 131 /// Name of this module.
@@ -133,7 +143,7 @@ impl Module {
133 143
134 /// Returns the crate this module is part of. 144 /// Returns the crate this module is part of.
135 pub fn krate(self) -> Crate { 145 pub fn krate(self) -> Crate {
136 Crate { crate_id: self.id.krate } 146 Crate { id: self.id.krate }
137 } 147 }
138 148
139 /// Topmost parent of this module. Every module has a `crate_root`, but some 149 /// Topmost parent of this module. Every module has a `crate_root`, but some
@@ -144,13 +154,6 @@ impl Module {
144 self.with_module_id(def_map.root) 154 self.with_module_id(def_map.root)
145 } 155 }
146 156
147 /// Finds a child module with the specified name.
148 pub fn child(self, db: &impl DefDatabase, name: &Name) -> Option<Module> {
149 let def_map = db.crate_def_map(self.id.krate);
150 let child_id = def_map[self.id.local_id].children.get(name)?;
151 Some(self.with_module_id(*child_id))
152 }
153
154 /// Iterates over all child modules. 157 /// Iterates over all child modules.
155 pub fn children(self, db: &impl DefDatabase) -> impl Iterator<Item = Module> { 158 pub fn children(self, db: &impl DefDatabase) -> impl Iterator<Item = Module> {
156 let def_map = db.crate_def_map(self.id.krate); 159 let def_map = db.crate_def_map(self.id.krate);
@@ -224,7 +227,7 @@ impl Module {
224 def_map[self.id.local_id].impls.iter().copied().map(ImplBlock::from).collect() 227 def_map[self.id.local_id].impls.iter().copied().map(ImplBlock::from).collect()
225 } 228 }
226 229
227 fn with_module_id(self, module_id: LocalModuleId) -> Module { 230 pub(crate) fn with_module_id(self, module_id: LocalModuleId) -> Module {
228 Module::new(self.krate(), module_id) 231 Module::new(self.krate(), module_id)
229 } 232 }
230} 233}
@@ -251,8 +254,10 @@ impl StructField {
251 self.parent.variant_data(db).fields()[self.id].name.clone() 254 self.parent.variant_data(db).fields()[self.id].name.clone()
252 } 255 }
253 256
254 pub fn ty(&self, db: &impl HirDatabase) -> Ty { 257 pub fn ty(&self, db: &impl HirDatabase) -> Type {
255 db.field_types(self.parent.into())[self.id].clone() 258 let var_id = self.parent.into();
259 let ty = db.field_types(var_id)[self.id].clone();
260 Type::new(db, self.parent.module(db).id.krate.into(), var_id, ty)
256 } 261 }
257 262
258 pub fn parent_def(&self, _db: &impl HirDatabase) -> VariantDef { 263 pub fn parent_def(&self, _db: &impl HirDatabase) -> VariantDef {
@@ -287,23 +292,10 @@ impl Struct {
287 .collect() 292 .collect()
288 } 293 }
289 294
290 pub fn field(self, db: &impl HirDatabase, name: &Name) -> Option<StructField> {
291 db.struct_data(self.id.into())
292 .variant_data
293 .fields()
294 .iter()
295 .find(|(_id, data)| data.name == *name)
296 .map(|(id, _)| StructField { parent: self.into(), id })
297 }
298
299 pub fn ty(self, db: &impl HirDatabase) -> Type { 295 pub fn ty(self, db: &impl HirDatabase) -> Type {
300 Type::from_def(db, self.id.module(db).krate, self.id) 296 Type::from_def(db, self.id.module(db).krate, self.id)
301 } 297 }
302 298
303 pub fn constructor_ty(self, db: &impl HirDatabase) -> Ty {
304 db.value_ty(self.id.into())
305 }
306
307 fn variant_data(self, db: &impl DefDatabase) -> Arc<VariantData> { 299 fn variant_data(self, db: &impl DefDatabase) -> Arc<VariantData> {
308 db.struct_data(self.id.into()).variant_data.clone() 300 db.struct_data(self.id.into()).variant_data.clone()
309 } 301 }
@@ -336,15 +328,6 @@ impl Union {
336 .collect() 328 .collect()
337 } 329 }
338 330
339 pub fn field(self, db: &impl HirDatabase, name: &Name) -> Option<StructField> {
340 db.union_data(self.id)
341 .variant_data
342 .fields()
343 .iter()
344 .find(|(_id, data)| data.name == *name)
345 .map(|(id, _)| StructField { parent: self.into(), id })
346 }
347
348 fn variant_data(self, db: &impl DefDatabase) -> Arc<VariantData> { 331 fn variant_data(self, db: &impl DefDatabase) -> Arc<VariantData> {
349 db.union_data(self.id).variant_data.clone() 332 db.union_data(self.id).variant_data.clone()
350 } 333 }
@@ -376,11 +359,6 @@ impl Enum {
376 .collect() 359 .collect()
377 } 360 }
378 361
379 pub fn variant(self, db: &impl DefDatabase, name: &Name) -> Option<EnumVariant> {
380 let id = db.enum_data(self.id).variant(name)?;
381 Some(EnumVariant { parent: self, id })
382 }
383
384 pub fn ty(self, db: &impl HirDatabase) -> Type { 362 pub fn ty(self, db: &impl HirDatabase) -> Type {
385 Type::from_def(db, self.id.module(db).krate, self.id) 363 Type::from_def(db, self.id.module(db).krate, self.id)
386 } 364 }
@@ -412,14 +390,6 @@ impl EnumVariant {
412 .collect() 390 .collect()
413 } 391 }
414 392
415 pub fn field(self, db: &impl HirDatabase, name: &Name) -> Option<StructField> {
416 self.variant_data(db)
417 .fields()
418 .iter()
419 .find(|(_id, data)| data.name == *name)
420 .map(|(id, _)| StructField { parent: self.into(), id })
421 }
422
423 pub(crate) fn variant_data(self, db: &impl DefDatabase) -> Arc<VariantData> { 393 pub(crate) fn variant_data(self, db: &impl DefDatabase) -> Arc<VariantData> {
424 db.enum_data(self.parent.id).variants[self.id].variant_data.clone() 394 db.enum_data(self.parent.id).variants[self.id].variant_data.clone()
425 } 395 }
@@ -537,48 +507,8 @@ impl Function {
537 db.function_data(self.id).params.clone() 507 db.function_data(self.id).params.clone()
538 } 508 }
539 509
540 pub fn body_source_map(self, db: &impl HirDatabase) -> Arc<BodySourceMap> {
541 db.body_with_source_map(self.id.into()).1
542 }
543
544 pub fn body(self, db: &impl HirDatabase) -> Arc<Body> {
545 db.body(self.id.into())
546 }
547
548 pub fn ty(self, db: &impl HirDatabase) -> Ty {
549 db.value_ty(self.id.into())
550 }
551
552 pub fn infer(self, db: &impl HirDatabase) -> Arc<InferenceResult> {
553 db.infer(self.id.into())
554 }
555
556 /// The containing impl block, if this is a method.
557 pub fn impl_block(self, db: &impl DefDatabase) -> Option<ImplBlock> {
558 match self.container(db) {
559 Some(Container::ImplBlock(it)) => Some(it),
560 _ => None,
561 }
562 }
563
564 /// The containing trait, if this is a trait method definition.
565 pub fn parent_trait(self, db: &impl DefDatabase) -> Option<Trait> {
566 match self.container(db) {
567 Some(Container::Trait(it)) => Some(it),
568 _ => None,
569 }
570 }
571
572 pub fn container(self, db: &impl DefDatabase) -> Option<Container> {
573 match self.id.lookup(db).container {
574 ContainerId::TraitId(it) => Some(Container::Trait(it.into())),
575 ContainerId::ImplId(it) => Some(Container::ImplBlock(it.into())),
576 ContainerId::ModuleId(_) => None,
577 }
578 }
579
580 pub fn diagnostics(self, db: &impl HirDatabase, sink: &mut DiagnosticSink) { 510 pub fn diagnostics(self, db: &impl HirDatabase, sink: &mut DiagnosticSink) {
581 let infer = self.infer(db); 511 let infer = db.infer(self.id.into());
582 infer.add_diagnostics(db, self.id, sink); 512 infer.add_diagnostics(db, self.id, sink);
583 let mut validator = ExprValidator::new(self.id, infer, sink); 513 let mut validator = ExprValidator::new(self.id, infer, sink);
584 validator.validate_body(db); 514 validator.validate_body(db);
@@ -603,10 +533,6 @@ impl Const {
603 db.const_data(self.id).name.clone() 533 db.const_data(self.id).name.clone()
604 } 534 }
605 535
606 pub fn infer(self, db: &impl HirDatabase) -> Arc<InferenceResult> {
607 db.infer(self.id.into())
608 }
609
610 /// The containing impl block, if this is a type alias. 536 /// The containing impl block, if this is a type alias.
611 pub fn impl_block(self, db: &impl DefDatabase) -> Option<ImplBlock> { 537 pub fn impl_block(self, db: &impl DefDatabase) -> Option<ImplBlock> {
612 match self.container(db) { 538 match self.container(db) {
@@ -645,10 +571,6 @@ impl Static {
645 pub fn krate(self, db: &impl DefDatabase) -> Option<Crate> { 571 pub fn krate(self, db: &impl DefDatabase) -> Option<Crate> {
646 Some(self.module(db).krate()) 572 Some(self.module(db).krate())
647 } 573 }
648
649 pub fn infer(self, db: &impl HirDatabase) -> Arc<InferenceResult> {
650 db.infer(self.id.into())
651 }
652} 574}
653 575
654#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 576#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
@@ -763,15 +685,6 @@ impl AssocItem {
763 AssocItem::TypeAlias(t) => t.module(db), 685 AssocItem::TypeAlias(t) => t.module(db),
764 } 686 }
765 } 687 }
766
767 pub fn container(self, db: &impl DefDatabase) -> Container {
768 match self {
769 AssocItem::Function(f) => f.container(db),
770 AssocItem::Const(c) => c.container(db),
771 AssocItem::TypeAlias(t) => t.container(db),
772 }
773 .expect("AssocItem without container")
774 }
775} 688}
776 689
777#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] 690#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
@@ -878,11 +791,11 @@ pub struct ImplBlock {
878 791
879impl ImplBlock { 792impl ImplBlock {
880 pub fn all_in_crate(db: &impl HirDatabase, krate: Crate) -> Vec<ImplBlock> { 793 pub fn all_in_crate(db: &impl HirDatabase, krate: Crate) -> Vec<ImplBlock> {
881 let impls = db.impls_in_crate(krate.crate_id); 794 let impls = db.impls_in_crate(krate.id);
882 impls.all_impls().map(Self::from).collect() 795 impls.all_impls().map(Self::from).collect()
883 } 796 }
884 pub fn for_trait(db: &impl HirDatabase, krate: Crate, trait_: Trait) -> Vec<ImplBlock> { 797 pub fn for_trait(db: &impl HirDatabase, krate: Crate, trait_: Trait) -> Vec<ImplBlock> {
885 let impls = db.impls_in_crate(krate.crate_id); 798 let impls = db.impls_in_crate(krate.id);
886 impls.lookup_impl_blocks_for_trait(trait_.id).map(Self::from).collect() 799 impls.lookup_impl_blocks_for_trait(trait_.id).map(Self::from).collect()
887 } 800 }
888 801
@@ -915,7 +828,7 @@ impl ImplBlock {
915 } 828 }
916 829
917 pub fn krate(&self, db: &impl DefDatabase) -> Crate { 830 pub fn krate(&self, db: &impl DefDatabase) -> Crate {
918 Crate { crate_id: self.module(db).id.krate } 831 Crate { id: self.module(db).id.krate }
919 } 832 }
920} 833}
921 834
@@ -926,15 +839,19 @@ pub struct Type {
926} 839}
927 840
928impl Type { 841impl Type {
842 fn new(db: &impl HirDatabase, krate: CrateId, lexical_env: impl HasResolver, ty: Ty) -> Type {
843 let resolver = lexical_env.resolver(db);
844 let environment = TraitEnvironment::lower(db, &resolver);
845 Type { krate, ty: InEnvironment { value: ty, environment } }
846 }
847
929 fn from_def( 848 fn from_def(
930 db: &impl HirDatabase, 849 db: &impl HirDatabase,
931 krate: CrateId, 850 krate: CrateId,
932 def: impl HasResolver + Into<TyDefId>, 851 def: impl HasResolver + Into<TyDefId>,
933 ) -> Type { 852 ) -> Type {
934 let resolver = def.resolver(db);
935 let environment = TraitEnvironment::lower(db, &resolver);
936 let ty = db.ty(def.into()); 853 let ty = db.ty(def.into());
937 Type { krate, ty: InEnvironment { value: ty, environment } } 854 Type::new(db, krate, def, ty)
938 } 855 }
939 856
940 pub fn is_bool(&self) -> bool { 857 pub fn is_bool(&self) -> bool {
@@ -984,7 +901,7 @@ impl Type {
984 pub fn fields(&self, db: &impl HirDatabase) -> Vec<(StructField, Type)> { 901 pub fn fields(&self, db: &impl HirDatabase) -> Vec<(StructField, Type)> {
985 if let Ty::Apply(a_ty) = &self.ty.value { 902 if let Ty::Apply(a_ty) = &self.ty.value {
986 match a_ty.ctor { 903 match a_ty.ctor {
987 ty::TypeCtor::Adt(AdtId::StructId(s)) => { 904 TypeCtor::Adt(AdtId::StructId(s)) => {
988 let var_def = s.into(); 905 let var_def = s.into();
989 return db 906 return db
990 .field_types(var_def) 907 .field_types(var_def)
@@ -1006,7 +923,7 @@ impl Type {
1006 let mut res = Vec::new(); 923 let mut res = Vec::new();
1007 if let Ty::Apply(a_ty) = &self.ty.value { 924 if let Ty::Apply(a_ty) = &self.ty.value {
1008 match a_ty.ctor { 925 match a_ty.ctor {
1009 ty::TypeCtor::Tuple { .. } => { 926 TypeCtor::Tuple { .. } => {
1010 for ty in a_ty.parameters.iter() { 927 for ty in a_ty.parameters.iter() {
1011 let ty = ty.clone().subst(&a_ty.parameters); 928 let ty = ty.clone().subst(&a_ty.parameters);
1012 res.push(self.derived(ty)); 929 res.push(self.derived(ty));
@@ -1025,11 +942,16 @@ impl Type {
1025 ) -> Vec<(StructField, Type)> { 942 ) -> Vec<(StructField, Type)> {
1026 // FIXME: check that ty and def match 943 // FIXME: check that ty and def match
1027 match &self.ty.value { 944 match &self.ty.value {
1028 Ty::Apply(a_ty) => def 945 Ty::Apply(a_ty) => {
1029 .fields(db) 946 let field_types = db.field_types(def.into());
1030 .into_iter() 947 def.fields(db)
1031 .map(|it| (it, self.derived(it.ty(db).subst(&a_ty.parameters)))) 948 .into_iter()
1032 .collect(), 949 .map(|it| {
950 let ty = field_types[it.id].clone().subst(&a_ty.parameters);
951 (it, self.derived(ty))
952 })
953 .collect()
954 }
1033 _ => Vec::new(), 955 _ => Vec::new(),
1034 } 956 }
1035 } 957 }
@@ -1037,10 +959,10 @@ impl Type {
1037 pub fn autoderef<'a>(&'a self, db: &'a impl HirDatabase) -> impl Iterator<Item = Type> + 'a { 959 pub fn autoderef<'a>(&'a self, db: &'a impl HirDatabase) -> impl Iterator<Item = Type> + 'a {
1038 // There should be no inference vars in types passed here 960 // There should be no inference vars in types passed here
1039 // FIXME check that? 961 // FIXME check that?
1040 let canonical = crate::ty::Canonical { value: self.ty.value.clone(), num_vars: 0 }; 962 let canonical = Canonical { value: self.ty.value.clone(), num_vars: 0 };
1041 let environment = self.ty.environment.clone(); 963 let environment = self.ty.environment.clone();
1042 let ty = InEnvironment { value: canonical, environment: environment.clone() }; 964 let ty = InEnvironment { value: canonical, environment: environment.clone() };
1043 ty::autoderef(db, Some(self.krate), ty) 965 autoderef(db, Some(self.krate), ty)
1044 .map(|canonical| canonical.value) 966 .map(|canonical| canonical.value)
1045 .map(move |ty| self.derived(ty)) 967 .map(move |ty| self.derived(ty))
1046 } 968 }
@@ -1053,7 +975,7 @@ impl Type {
1053 krate: Crate, 975 krate: Crate,
1054 mut callback: impl FnMut(AssocItem) -> Option<T>, 976 mut callback: impl FnMut(AssocItem) -> Option<T>,
1055 ) -> Option<T> { 977 ) -> Option<T> {
1056 for krate in self.ty.value.def_crates(db, krate.crate_id)? { 978 for krate in self.ty.value.def_crates(db, krate.id)? {
1057 let impls = db.impls_in_crate(krate); 979 let impls = db.impls_in_crate(krate);
1058 980
1059 for impl_block in impls.lookup_impl_blocks(&self.ty.value) { 981 for impl_block in impls.lookup_impl_blocks(&self.ty.value) {
@@ -1080,15 +1002,14 @@ impl Type {
1080 // FIXME: provide required accessors such that it becomes implementable from outside. 1002 // FIXME: provide required accessors such that it becomes implementable from outside.
1081 pub fn is_equal_for_find_impls(&self, other: &Type) -> bool { 1003 pub fn is_equal_for_find_impls(&self, other: &Type) -> bool {
1082 match (&self.ty.value, &other.ty.value) { 1004 match (&self.ty.value, &other.ty.value) {
1083 (Ty::Apply(a_original_ty), Ty::Apply(ty::ApplicationTy { ctor, parameters })) => { 1005 (Ty::Apply(a_original_ty), Ty::Apply(ApplicationTy { ctor, parameters })) => match ctor
1084 match ctor { 1006 {
1085 TypeCtor::Ref(..) => match parameters.as_single() { 1007 TypeCtor::Ref(..) => match parameters.as_single() {
1086 Ty::Apply(a_ty) => a_original_ty.ctor == a_ty.ctor, 1008 Ty::Apply(a_ty) => a_original_ty.ctor == a_ty.ctor,
1087 _ => false, 1009 _ => false,
1088 }, 1010 },
1089 _ => a_original_ty.ctor == *ctor, 1011 _ => a_original_ty.ctor == *ctor,
1090 } 1012 },
1091 }
1092 _ => false, 1013 _ => false,
1093 } 1014 }
1094 } 1015 }