aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Cargo.lock17
-rw-r--r--crates/ra_hir/Cargo.toml20
-rw-r--r--crates/ra_hir/src/code_model.rs47
-rw-r--r--crates/ra_hir/src/db.rs117
-rw-r--r--crates/ra_hir/src/diagnostics.rs91
-rw-r--r--crates/ra_hir/src/lib.rs9
-rw-r--r--crates/ra_hir/src/source_binder.rs22
-rw-r--r--crates/ra_hir/src/ty.rs1111
-rw-r--r--crates/ra_hir/src/ty/primitive.rs3
-rw-r--r--crates/ra_hir/src/util.rs12
-rw-r--r--crates/ra_hir_def/src/lib.rs2
-rw-r--r--crates/ra_hir_ty/Cargo.toml12
-rw-r--r--crates/ra_hir_ty/src/autoderef.rs (renamed from crates/ra_hir/src/ty/autoderef.rs)2
-rw-r--r--crates/ra_hir_ty/src/db.rs116
-rw-r--r--crates/ra_hir_ty/src/diagnostics.rs91
-rw-r--r--crates/ra_hir_ty/src/display.rs (renamed from crates/ra_hir/src/ty/display.rs)0
-rw-r--r--crates/ra_hir_ty/src/expr.rs (renamed from crates/ra_hir/src/expr.rs)41
-rw-r--r--crates/ra_hir_ty/src/infer.rs (renamed from crates/ra_hir/src/ty/infer.rs)10
-rw-r--r--crates/ra_hir_ty/src/infer/coerce.rs (renamed from crates/ra_hir/src/ty/infer/coerce.rs)5
-rw-r--r--crates/ra_hir_ty/src/infer/expr.rs (renamed from crates/ra_hir/src/ty/infer/expr.rs)9
-rw-r--r--crates/ra_hir_ty/src/infer/pat.rs (renamed from crates/ra_hir/src/ty/infer/pat.rs)5
-rw-r--r--crates/ra_hir_ty/src/infer/path.rs (renamed from crates/ra_hir/src/ty/infer/path.rs)9
-rw-r--r--crates/ra_hir_ty/src/infer/unify.rs (renamed from crates/ra_hir/src/ty/infer/unify.rs)8
-rw-r--r--crates/ra_hir_ty/src/lib.rs1134
-rw-r--r--crates/ra_hir_ty/src/lower.rs (renamed from crates/ra_hir/src/ty/lower.rs)57
-rw-r--r--crates/ra_hir_ty/src/marks.rs (renamed from crates/ra_hir/src/marks.rs)0
-rw-r--r--crates/ra_hir_ty/src/method_resolution.rs (renamed from crates/ra_hir/src/ty/method_resolution.rs)11
-rw-r--r--crates/ra_hir_ty/src/op.rs (renamed from crates/ra_hir/src/ty/op.rs)2
-rw-r--r--crates/ra_hir_ty/src/test_db.rs (renamed from crates/ra_hir/src/test_db.rs)81
-rw-r--r--crates/ra_hir_ty/src/tests.rs (renamed from crates/ra_hir/src/ty/tests.rs)110
-rw-r--r--crates/ra_hir_ty/src/tests/coercion.rs (renamed from crates/ra_hir/src/ty/tests/coercion.rs)0
-rw-r--r--crates/ra_hir_ty/src/tests/never_type.rs (renamed from crates/ra_hir/src/ty/tests/never_type.rs)0
-rw-r--r--crates/ra_hir_ty/src/traits.rs (renamed from crates/ra_hir/src/ty/traits.rs)0
-rw-r--r--crates/ra_hir_ty/src/traits/chalk.rs (renamed from crates/ra_hir/src/ty/traits/chalk.rs)30
-rw-r--r--crates/ra_hir_ty/src/utils.rs (renamed from crates/ra_hir/src/ty/utils.rs)9
-rw-r--r--crates/ra_ide_api/src/impls.rs17
-rw-r--r--xtask/tests/tidy-tests/docs.rs1
37 files changed, 1629 insertions, 1582 deletions
diff --git a/Cargo.lock b/Cargo.lock
index f751be2e3..0f7a45d6c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -962,28 +962,13 @@ dependencies = [
962name = "ra_hir" 962name = "ra_hir"
963version = "0.1.0" 963version = "0.1.0"
964dependencies = [ 964dependencies = [
965 "arrayvec 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
966 "chalk-ir 0.1.0 (git+https://github.com/jackh726/chalk.git?rev=095cd38a4f16337913bba487f2055b9ca0179f30)",
967 "chalk-rust-ir 0.1.0 (git+https://github.com/jackh726/chalk.git?rev=095cd38a4f16337913bba487f2055b9ca0179f30)",
968 "chalk-solve 0.1.0 (git+https://github.com/jackh726/chalk.git?rev=095cd38a4f16337913bba487f2055b9ca0179f30)",
969 "ena 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)",
970 "insta 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)",
971 "lalrpop-intern 0.15.1 (registry+https://github.com/rust-lang/crates.io-index)",
972 "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", 965 "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)",
973 "once_cell 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
974 "parking_lot 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)",
975 "ra_arena 0.1.0",
976 "ra_cfg 0.1.0",
977 "ra_db 0.1.0", 966 "ra_db 0.1.0",
978 "ra_hir_def 0.1.0", 967 "ra_hir_def 0.1.0",
979 "ra_hir_expand 0.1.0", 968 "ra_hir_expand 0.1.0",
980 "ra_hir_ty 0.1.0", 969 "ra_hir_ty 0.1.0",
981 "ra_mbe 0.1.0",
982 "ra_prof 0.1.0",
983 "ra_syntax 0.1.0", 970 "ra_syntax 0.1.0",
984 "ra_tt 0.1.0",
985 "rustc-hash 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", 971 "rustc-hash 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
986 "test_utils 0.1.0",
987] 972]
988 973
989[[package]] 974[[package]]
@@ -1023,6 +1008,7 @@ dependencies = [
1023name = "ra_hir_ty" 1008name = "ra_hir_ty"
1024version = "0.1.0" 1009version = "0.1.0"
1025dependencies = [ 1010dependencies = [
1011 "arrayvec 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
1026 "chalk-ir 0.1.0 (git+https://github.com/jackh726/chalk.git?rev=095cd38a4f16337913bba487f2055b9ca0179f30)", 1012 "chalk-ir 0.1.0 (git+https://github.com/jackh726/chalk.git?rev=095cd38a4f16337913bba487f2055b9ca0179f30)",
1027 "chalk-rust-ir 0.1.0 (git+https://github.com/jackh726/chalk.git?rev=095cd38a4f16337913bba487f2055b9ca0179f30)", 1013 "chalk-rust-ir 0.1.0 (git+https://github.com/jackh726/chalk.git?rev=095cd38a4f16337913bba487f2055b9ca0179f30)",
1028 "chalk-solve 0.1.0 (git+https://github.com/jackh726/chalk.git?rev=095cd38a4f16337913bba487f2055b9ca0179f30)", 1014 "chalk-solve 0.1.0 (git+https://github.com/jackh726/chalk.git?rev=095cd38a4f16337913bba487f2055b9ca0179f30)",
@@ -1030,7 +1016,6 @@ dependencies = [
1030 "insta 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)", 1016 "insta 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)",
1031 "lalrpop-intern 0.15.1 (registry+https://github.com/rust-lang/crates.io-index)", 1017 "lalrpop-intern 0.15.1 (registry+https://github.com/rust-lang/crates.io-index)",
1032 "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", 1018 "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)",
1033 "parking_lot 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)",
1034 "ra_arena 0.1.0", 1019 "ra_arena 0.1.0",
1035 "ra_db 0.1.0", 1020 "ra_db 0.1.0",
1036 "ra_hir_def 0.1.0", 1021 "ra_hir_def 0.1.0",
diff --git a/crates/ra_hir/Cargo.toml b/crates/ra_hir/Cargo.toml
index caba85a4f..e79361e7c 100644
--- a/crates/ra_hir/Cargo.toml
+++ b/crates/ra_hir/Cargo.toml
@@ -8,31 +8,11 @@ authors = ["rust-analyzer developers"]
8doctest = false 8doctest = false
9 9
10[dependencies] 10[dependencies]
11arrayvec = "0.5.1"
12log = "0.4.5" 11log = "0.4.5"
13rustc-hash = "1.0" 12rustc-hash = "1.0"
14parking_lot = "0.10.0"
15ena = "0.13"
16once_cell = "1.0.1"
17 13
18ra_syntax = { path = "../ra_syntax" } 14ra_syntax = { path = "../ra_syntax" }
19ra_arena = { path = "../ra_arena" }
20ra_cfg = { path = "../ra_cfg" }
21ra_db = { path = "../ra_db" } 15ra_db = { path = "../ra_db" }
22mbe = { path = "../ra_mbe", package = "ra_mbe" }
23tt = { path = "../ra_tt", package = "ra_tt" }
24hir_expand = { path = "../ra_hir_expand", package = "ra_hir_expand" } 16hir_expand = { path = "../ra_hir_expand", package = "ra_hir_expand" }
25hir_def = { path = "../ra_hir_def", package = "ra_hir_def" } 17hir_def = { path = "../ra_hir_def", package = "ra_hir_def" }
26hir_ty = { path = "../ra_hir_ty", package = "ra_hir_ty" } 18hir_ty = { path = "../ra_hir_ty", package = "ra_hir_ty" }
27test_utils = { path = "../test_utils" }
28ra_prof = { path = "../ra_prof" }
29
30# https://github.com/rust-lang/chalk/pull/294
31chalk-solve = { git = "https://github.com/jackh726/chalk.git", rev = "095cd38a4f16337913bba487f2055b9ca0179f30" }
32chalk-rust-ir = { git = "https://github.com/jackh726/chalk.git", rev = "095cd38a4f16337913bba487f2055b9ca0179f30" }
33chalk-ir = { git = "https://github.com/jackh726/chalk.git", rev = "095cd38a4f16337913bba487f2055b9ca0179f30" }
34
35lalrpop-intern = "0.15.1"
36
37[dev-dependencies]
38insta = "0.12.0"
diff --git a/crates/ra_hir/src/code_model.rs b/crates/ra_hir/src/code_model.rs
index 52ad4e5d1..87c78d98e 100644
--- a/crates/ra_hir/src/code_model.rs
+++ b/crates/ra_hir/src/code_model.rs
@@ -6,8 +6,10 @@ use std::sync::Arc;
6 6
7use hir_def::{ 7use hir_def::{
8 adt::VariantData, 8 adt::VariantData,
9 body::{Body, BodySourceMap},
9 builtin_type::BuiltinType, 10 builtin_type::BuiltinType,
10 docs::Documentation, 11 docs::Documentation,
12 expr::{BindingAnnotation, Pat, PatId},
11 per_ns::PerNs, 13 per_ns::PerNs,
12 resolver::HasResolver, 14 resolver::HasResolver,
13 type_ref::{Mutability, TypeRef}, 15 type_ref::{Mutability, TypeRef},
@@ -20,12 +22,12 @@ use hir_expand::{
20 name::{self, AsName}, 22 name::{self, AsName},
21 AstId, MacroDefId, 23 AstId, MacroDefId,
22}; 24};
25use hir_ty::expr::ExprValidator;
23use ra_db::{CrateId, Edition, FileId, FilePosition}; 26use ra_db::{CrateId, Edition, FileId, FilePosition};
24use ra_syntax::{ast, AstNode, SyntaxNode}; 27use ra_syntax::{ast, AstNode, SyntaxNode};
25 28
26use crate::{ 29use crate::{
27 db::{DefDatabase, HirDatabase}, 30 db::{DefDatabase, HirDatabase},
28 expr::{BindingAnnotation, Body, BodySourceMap, ExprValidator, Pat, PatId},
29 ty::display::HirFormatter, 31 ty::display::HirFormatter,
30 ty::{ 32 ty::{
31 self, InEnvironment, InferenceResult, TraitEnvironment, TraitRef, Ty, TyDefId, TypeCtor, 33 self, InEnvironment, InferenceResult, TraitEnvironment, TraitRef, Ty, TyDefId, TypeCtor,
@@ -353,8 +355,8 @@ impl Struct {
353 .map(|(id, _)| StructField { parent: self.into(), id }) 355 .map(|(id, _)| StructField { parent: self.into(), id })
354 } 356 }
355 357
356 pub fn ty(self, db: &impl HirDatabase) -> Ty { 358 pub fn ty(self, db: &impl HirDatabase) -> Type {
357 db.ty(self.id.into()) 359 Type::from_def(db, self.id.module(db).krate, self.id)
358 } 360 }
359 361
360 pub fn constructor_ty(self, db: &impl HirDatabase) -> Ty { 362 pub fn constructor_ty(self, db: &impl HirDatabase) -> Ty {
@@ -380,8 +382,8 @@ impl Union {
380 Module { id: self.id.module(db) } 382 Module { id: self.id.module(db) }
381 } 383 }
382 384
383 pub fn ty(self, db: &impl HirDatabase) -> Ty { 385 pub fn ty(self, db: &impl HirDatabase) -> Type {
384 db.ty(self.id.into()) 386 Type::from_def(db, self.id.module(db).krate, self.id)
385 } 387 }
386 388
387 pub fn fields(self, db: &impl HirDatabase) -> Vec<StructField> { 389 pub fn fields(self, db: &impl HirDatabase) -> Vec<StructField> {
@@ -441,8 +443,8 @@ impl Enum {
441 .map(|(id, _)| EnumVariant { parent: self, id }) 443 .map(|(id, _)| EnumVariant { parent: self, id })
442 } 444 }
443 445
444 pub fn ty(self, db: &impl HirDatabase) -> Ty { 446 pub fn ty(self, db: &impl HirDatabase) -> Type {
445 db.ty(self.id.into()) 447 Type::from_def(db, self.id.module(db).krate, self.id)
446 } 448 }
447} 449}
448 450
@@ -640,7 +642,7 @@ impl Function {
640 pub fn diagnostics(self, db: &impl HirDatabase, sink: &mut DiagnosticSink) { 642 pub fn diagnostics(self, db: &impl HirDatabase, sink: &mut DiagnosticSink) {
641 let infer = self.infer(db); 643 let infer = self.infer(db);
642 infer.add_diagnostics(db, self.id, sink); 644 infer.add_diagnostics(db, self.id, sink);
643 let mut validator = ExprValidator::new(self, infer, sink); 645 let mut validator = ExprValidator::new(self.id, infer, sink);
644 validator.validate_body(db); 646 validator.validate_body(db);
645 } 647 }
646} 648}
@@ -946,13 +948,12 @@ impl ImplBlock {
946 db.impl_data(self.id).target_type.clone() 948 db.impl_data(self.id).target_type.clone()
947 } 949 }
948 950
949 pub fn target_ty(&self, db: &impl HirDatabase) -> Ty { 951 pub fn target_ty(&self, db: &impl HirDatabase) -> Type {
950 Ty::from_hir(db, &self.id.resolver(db), &self.target_type(db)) 952 let impl_data = db.impl_data(self.id);
951 } 953 let resolver = self.id.resolver(db);
952 954 let environment = TraitEnvironment::lower(db, &resolver);
953 pub fn target_trait_ref(&self, db: &impl HirDatabase) -> Option<TraitRef> { 955 let ty = Ty::from_hir(db, &resolver, &impl_data.target_type);
954 let target_ty = self.target_ty(db); 956 Type { krate: self.id.module(db).krate, ty: InEnvironment { value: ty, environment } }
955 TraitRef::from_hir(db, &self.id.resolver(db), &self.target_trait(db)?, Some(target_ty))
956 } 957 }
957 958
958 pub fn items(&self, db: &impl DefDatabase) -> Vec<AssocItem> { 959 pub fn items(&self, db: &impl DefDatabase) -> Vec<AssocItem> {
@@ -1130,6 +1131,22 @@ impl Type {
1130 Some(adt.into()) 1131 Some(adt.into())
1131 } 1132 }
1132 1133
1134 // FIXME: provide required accessors such that it becomes implementable from outside.
1135 pub fn is_equal_for_find_impls(&self, other: &Type) -> bool {
1136 match (&self.ty.value, &other.ty.value) {
1137 (Ty::Apply(a_original_ty), Ty::Apply(ty::ApplicationTy { ctor, parameters })) => {
1138 match ctor {
1139 TypeCtor::Ref(..) => match parameters.as_single() {
1140 Ty::Apply(a_ty) => a_original_ty.ctor == a_ty.ctor,
1141 _ => false,
1142 },
1143 _ => a_original_ty.ctor == *ctor,
1144 }
1145 }
1146 _ => false,
1147 }
1148 }
1149
1133 fn derived(&self, ty: Ty) -> Type { 1150 fn derived(&self, ty: Ty) -> Type {
1134 Type { 1151 Type {
1135 krate: self.krate, 1152 krate: self.krate,
diff --git a/crates/ra_hir/src/db.rs b/crates/ra_hir/src/db.rs
index e192c8f47..bfae3660b 100644
--- a/crates/ra_hir/src/db.rs
+++ b/crates/ra_hir/src/db.rs
@@ -1,18 +1,5 @@
1//! FIXME: write short doc here 1//! FIXME: write short doc here
2 2
3use std::sync::Arc;
4
5use hir_def::{DefWithBodyId, GenericDefId, ImplId, LocalStructFieldId, TraitId, VariantId};
6use ra_arena::map::ArenaMap;
7use ra_db::{salsa, CrateId};
8
9use crate::ty::{
10 method_resolution::CrateImplBlocks,
11 traits::{AssocTyValue, Impl},
12 CallableDef, FnSig, GenericPredicate, InferenceResult, Substs, Ty, TyDefId, TypeCtor,
13 ValueTyDefId,
14};
15
16pub use hir_def::db::{ 3pub use hir_def::db::{
17 BodyQuery, BodyWithSourceMapQuery, ConstDataQuery, CrateDefMapQuery, CrateLangItemsQuery, 4 BodyQuery, BodyWithSourceMapQuery, ConstDataQuery, CrateDefMapQuery, CrateLangItemsQuery,
18 DefDatabase, DefDatabaseStorage, DocumentationQuery, EnumDataQuery, ExprScopesQuery, 5 DefDatabase, DefDatabaseStorage, DocumentationQuery, EnumDataQuery, ExprScopesQuery,
@@ -24,104 +11,12 @@ pub use hir_expand::db::{
24 AstDatabase, AstDatabaseStorage, AstIdMapQuery, MacroArgQuery, MacroDefQuery, MacroExpandQuery, 11 AstDatabase, AstDatabaseStorage, AstIdMapQuery, MacroArgQuery, MacroDefQuery, MacroExpandQuery,
25 ParseMacroQuery, 12 ParseMacroQuery,
26}; 13};
27 14pub use hir_ty::db::{
28#[salsa::query_group(HirDatabaseStorage)] 15 AssociatedTyDataQuery, CallableItemSignatureQuery, FieldTypesQuery, GenericDefaultsQuery,
29#[salsa::requires(salsa::Database)] 16 GenericPredicatesQuery, HirDatabase, HirDatabaseStorage, ImplDatumQuery, ImplsForTraitQuery,
30pub trait HirDatabase: DefDatabase { 17 ImplsInCrateQuery, InferQuery, StructDatumQuery, TraitDatumQuery, TraitSolveQuery, TyQuery,
31 #[salsa::invoke(crate::ty::infer_query)] 18 ValueTyQuery,
32 fn infer(&self, def: DefWithBodyId) -> Arc<InferenceResult>; 19};
33
34 #[salsa::invoke(crate::ty::ty_query)]
35 fn ty(&self, def: TyDefId) -> Ty;
36
37 #[salsa::invoke(crate::ty::value_ty_query)]
38 fn value_ty(&self, def: ValueTyDefId) -> Ty;
39
40 #[salsa::invoke(crate::ty::field_types_query)]
41 fn field_types(&self, var: VariantId) -> Arc<ArenaMap<LocalStructFieldId, Ty>>;
42
43 #[salsa::invoke(crate::ty::callable_item_sig)]
44 fn callable_item_signature(&self, def: CallableDef) -> FnSig;
45
46 #[salsa::invoke(crate::ty::generic_predicates_for_param_query)]
47 fn generic_predicates_for_param(
48 &self,
49 def: GenericDefId,
50 param_idx: u32,
51 ) -> Arc<[GenericPredicate]>;
52
53 #[salsa::invoke(crate::ty::generic_predicates_query)]
54 fn generic_predicates(&self, def: GenericDefId) -> Arc<[GenericPredicate]>;
55
56 #[salsa::invoke(crate::ty::generic_defaults_query)]
57 fn generic_defaults(&self, def: GenericDefId) -> Substs;
58
59 #[salsa::invoke(crate::ty::method_resolution::CrateImplBlocks::impls_in_crate_query)]
60 fn impls_in_crate(&self, krate: CrateId) -> Arc<CrateImplBlocks>;
61
62 #[salsa::invoke(crate::ty::traits::impls_for_trait_query)]
63 fn impls_for_trait(&self, krate: CrateId, trait_: TraitId) -> Arc<[ImplId]>;
64
65 /// This provides the Chalk trait solver instance. Because Chalk always
66 /// works from a specific crate, this query is keyed on the crate; and
67 /// because Chalk does its own internal caching, the solver is wrapped in a
68 /// Mutex and the query does an untracked read internally, to make sure the
69 /// cached state is thrown away when input facts change.
70 #[salsa::invoke(crate::ty::traits::trait_solver_query)]
71 fn trait_solver(&self, krate: CrateId) -> crate::ty::traits::TraitSolver;
72
73 // Interned IDs for Chalk integration
74 #[salsa::interned]
75 fn intern_type_ctor(&self, type_ctor: TypeCtor) -> crate::ty::TypeCtorId;
76 #[salsa::interned]
77 fn intern_chalk_impl(&self, impl_: Impl) -> crate::ty::traits::GlobalImplId;
78 #[salsa::interned]
79 fn intern_assoc_ty_value(
80 &self,
81 assoc_ty_value: AssocTyValue,
82 ) -> crate::ty::traits::AssocTyValueId;
83
84 #[salsa::invoke(crate::ty::traits::chalk::associated_ty_data_query)]
85 fn associated_ty_data(
86 &self,
87 id: chalk_ir::TypeId,
88 ) -> Arc<chalk_rust_ir::AssociatedTyDatum<chalk_ir::family::ChalkIr>>;
89
90 #[salsa::invoke(crate::ty::traits::chalk::trait_datum_query)]
91 fn trait_datum(
92 &self,
93 krate: CrateId,
94 trait_id: chalk_ir::TraitId,
95 ) -> Arc<chalk_rust_ir::TraitDatum<chalk_ir::family::ChalkIr>>;
96
97 #[salsa::invoke(crate::ty::traits::chalk::struct_datum_query)]
98 fn struct_datum(
99 &self,
100 krate: CrateId,
101 struct_id: chalk_ir::StructId,
102 ) -> Arc<chalk_rust_ir::StructDatum<chalk_ir::family::ChalkIr>>;
103
104 #[salsa::invoke(crate::ty::traits::chalk::impl_datum_query)]
105 fn impl_datum(
106 &self,
107 krate: CrateId,
108 impl_id: chalk_ir::ImplId,
109 ) -> Arc<chalk_rust_ir::ImplDatum<chalk_ir::family::ChalkIr>>;
110
111 #[salsa::invoke(crate::ty::traits::chalk::associated_ty_value_query)]
112 fn associated_ty_value(
113 &self,
114 krate: CrateId,
115 id: chalk_rust_ir::AssociatedTyValueId,
116 ) -> Arc<chalk_rust_ir::AssociatedTyValue<chalk_ir::family::ChalkIr>>;
117
118 #[salsa::invoke(crate::ty::traits::trait_solve_query)]
119 fn trait_solve(
120 &self,
121 krate: CrateId,
122 goal: crate::ty::Canonical<crate::ty::InEnvironment<crate::ty::Obligation>>,
123 ) -> Option<crate::ty::traits::Solution>;
124}
125 20
126#[test] 21#[test]
127fn hir_database_is_object_safe() { 22fn hir_database_is_object_safe() {
diff --git a/crates/ra_hir/src/diagnostics.rs b/crates/ra_hir/src/diagnostics.rs
index 6db499e06..a9040ea3d 100644
--- a/crates/ra_hir/src/diagnostics.rs
+++ b/crates/ra_hir/src/diagnostics.rs
@@ -1,93 +1,4 @@
1//! FIXME: write short doc here 1//! FIXME: write short doc here
2
3use std::any::Any;
4
5use hir_expand::HirFileId;
6use ra_syntax::{ast, AstNode, AstPtr, SyntaxNodePtr};
7
8use crate::{db::AstDatabase, Name, Source};
9
10pub use hir_def::diagnostics::UnresolvedModule; 2pub use hir_def::diagnostics::UnresolvedModule;
11pub use hir_expand::diagnostics::{AstDiagnostic, Diagnostic, DiagnosticSink}; 3pub use hir_expand::diagnostics::{AstDiagnostic, Diagnostic, DiagnosticSink};
12 4pub use hir_ty::diagnostics::{MissingFields, MissingOkInTailExpr, NoSuchField};
13#[derive(Debug)]
14pub struct NoSuchField {
15 pub file: HirFileId,
16 pub field: AstPtr<ast::RecordField>,
17}
18
19impl Diagnostic for NoSuchField {
20 fn message(&self) -> String {
21 "no such field".to_string()
22 }
23
24 fn source(&self) -> Source<SyntaxNodePtr> {
25 Source { file_id: self.file, value: self.field.into() }
26 }
27
28 fn as_any(&self) -> &(dyn Any + Send + 'static) {
29 self
30 }
31}
32
33#[derive(Debug)]
34pub struct MissingFields {
35 pub file: HirFileId,
36 pub field_list: AstPtr<ast::RecordFieldList>,
37 pub missed_fields: Vec<Name>,
38}
39
40impl Diagnostic for MissingFields {
41 fn message(&self) -> String {
42 use std::fmt::Write;
43 let mut message = String::from("Missing structure fields:\n");
44 for field in &self.missed_fields {
45 write!(message, "- {}\n", field).unwrap();
46 }
47 message
48 }
49 fn source(&self) -> Source<SyntaxNodePtr> {
50 Source { file_id: self.file, value: self.field_list.into() }
51 }
52 fn as_any(&self) -> &(dyn Any + Send + 'static) {
53 self
54 }
55}
56
57impl AstDiagnostic for MissingFields {
58 type AST = ast::RecordFieldList;
59
60 fn ast(&self, db: &impl AstDatabase) -> Self::AST {
61 let root = db.parse_or_expand(self.source().file_id).unwrap();
62 let node = self.source().value.to_node(&root);
63 ast::RecordFieldList::cast(node).unwrap()
64 }
65}
66
67#[derive(Debug)]
68pub struct MissingOkInTailExpr {
69 pub file: HirFileId,
70 pub expr: AstPtr<ast::Expr>,
71}
72
73impl Diagnostic for MissingOkInTailExpr {
74 fn message(&self) -> String {
75 "wrap return expression in Ok".to_string()
76 }
77 fn source(&self) -> Source<SyntaxNodePtr> {
78 Source { file_id: self.file, value: self.expr.into() }
79 }
80 fn as_any(&self) -> &(dyn Any + Send + 'static) {
81 self
82 }
83}
84
85impl AstDiagnostic for MissingOkInTailExpr {
86 type AST = ast::Expr;
87
88 fn ast(&self, db: &impl AstDatabase) -> Self::AST {
89 let root = db.parse_or_expand(self.file).unwrap();
90 let node = self.source().value.to_node(&root);
91 ast::Expr::cast(node).unwrap()
92 }
93}
diff --git a/crates/ra_hir/src/lib.rs b/crates/ra_hir/src/lib.rs
index b88e4c745..3c12c61f0 100644
--- a/crates/ra_hir/src/lib.rs
+++ b/crates/ra_hir/src/lib.rs
@@ -32,20 +32,13 @@ pub mod db;
32pub mod source_binder; 32pub mod source_binder;
33 33
34mod ty; 34mod ty;
35mod expr;
36pub mod diagnostics; 35pub mod diagnostics;
37mod util;
38 36
39mod from_id; 37mod from_id;
40mod code_model; 38mod code_model;
41 39
42pub mod from_source; 40pub mod from_source;
43 41
44#[cfg(test)]
45mod test_db;
46#[cfg(test)]
47mod marks;
48
49pub use crate::{ 42pub use crate::{
50 code_model::{ 43 code_model::{
51 src::HasSource, Adt, AssocItem, AttrDef, Const, Container, Crate, CrateDependency, 44 src::HasSource, Adt, AssocItem, AttrDef, Const, Container, Crate, CrateDependency,
@@ -53,7 +46,6 @@ pub use crate::{
53 HasAttrs, ImplBlock, Import, Local, MacroDef, Module, ModuleDef, ModuleSource, ScopeDef, 46 HasAttrs, ImplBlock, Import, Local, MacroDef, Module, ModuleDef, ModuleSource, ScopeDef,
54 Static, Struct, StructField, Trait, Type, TypeAlias, Union, VariantDef, 47 Static, Struct, StructField, Trait, Type, TypeAlias, Union, VariantDef,
55 }, 48 },
56 expr::ExprScopes,
57 from_source::FromSource, 49 from_source::FromSource,
58 source_binder::{PathResolution, ScopeEntryWithSyntax, SourceAnalyzer}, 50 source_binder::{PathResolution, ScopeEntryWithSyntax, SourceAnalyzer},
59 ty::{ 51 ty::{
@@ -64,6 +56,7 @@ pub use crate::{
64}; 56};
65 57
66pub use hir_def::{ 58pub use hir_def::{
59 body::scope::ExprScopes,
67 builtin_type::BuiltinType, 60 builtin_type::BuiltinType,
68 docs::Documentation, 61 docs::Documentation,
69 path::{Path, PathKind}, 62 path::{Path, PathKind},
diff --git a/crates/ra_hir/src/source_binder.rs b/crates/ra_hir/src/source_binder.rs
index 05f5bca57..76c493f1a 100644
--- a/crates/ra_hir/src/source_binder.rs
+++ b/crates/ra_hir/src/source_binder.rs
@@ -8,6 +8,10 @@
8use std::sync::Arc; 8use std::sync::Arc;
9 9
10use hir_def::{ 10use hir_def::{
11 body::{
12 scope::{ExprScopes, ScopeId},
13 BodySourceMap,
14 },
11 expr::{ExprId, PatId}, 15 expr::{ExprId, PatId},
12 path::known, 16 path::known,
13 resolver::{self, resolver_for_scope, HasResolver, Resolver, TypeNs, ValueNs}, 17 resolver::{self, resolver_for_scope, HasResolver, Resolver, TypeNs, ValueNs},
@@ -25,7 +29,6 @@ use ra_syntax::{
25 29
26use crate::{ 30use crate::{
27 db::HirDatabase, 31 db::HirDatabase,
28 expr::{BodySourceMap, ExprScopes, ScopeId},
29 ty::{ 32 ty::{
30 method_resolution::{self, implements_trait}, 33 method_resolution::{self, implements_trait},
31 InEnvironment, TraitEnvironment, Ty, 34 InEnvironment, TraitEnvironment, Ty,
@@ -91,7 +94,7 @@ pub struct SourceAnalyzer {
91 body_owner: Option<DefWithBody>, 94 body_owner: Option<DefWithBody>,
92 body_source_map: Option<Arc<BodySourceMap>>, 95 body_source_map: Option<Arc<BodySourceMap>>,
93 infer: Option<Arc<crate::ty::InferenceResult>>, 96 infer: Option<Arc<crate::ty::InferenceResult>>,
94 scopes: Option<Arc<crate::expr::ExprScopes>>, 97 scopes: Option<Arc<ExprScopes>>,
95} 98}
96 99
97#[derive(Debug, Clone, PartialEq, Eq)] 100#[derive(Debug, Clone, PartialEq, Eq)]
@@ -455,21 +458,6 @@ impl SourceAnalyzer {
455 macro_file_kind: to_macro_file_kind(macro_call.value), 458 macro_file_kind: to_macro_file_kind(macro_call.value),
456 }) 459 })
457 } 460 }
458
459 #[cfg(test)]
460 pub(crate) fn body_source_map(&self) -> Arc<BodySourceMap> {
461 self.body_source_map.clone().unwrap()
462 }
463
464 #[cfg(test)]
465 pub(crate) fn inference_result(&self) -> Arc<crate::ty::InferenceResult> {
466 self.infer.clone().unwrap()
467 }
468
469 #[cfg(test)]
470 pub(crate) fn analyzed_declaration(&self) -> Option<DefWithBody> {
471 self.body_owner
472 }
473} 461}
474 462
475fn scope_for( 463fn scope_for(
diff --git a/crates/ra_hir/src/ty.rs b/crates/ra_hir/src/ty.rs
index e4ba8afa6..4ed69c00d 100644
--- a/crates/ra_hir/src/ty.rs
+++ b/crates/ra_hir/src/ty.rs
@@ -1,1113 +1,4 @@
1//! The type system. We currently use this to infer types for completion, hover 1//! The type system. We currently use this to infer types for completion, hover
2//! information and various assists. 2//! information and various assists.
3 3
4mod autoderef; 4pub use hir_ty::*;
5pub(crate) mod primitive;
6pub(crate) mod traits;
7pub(crate) mod method_resolution;
8mod op;
9mod lower;
10mod infer;
11pub(crate) mod display;
12pub(crate) mod utils;
13
14#[cfg(test)]
15mod tests;
16
17use std::ops::Deref;
18use std::sync::Arc;
19use std::{fmt, iter, mem};
20
21use hir_def::{
22 expr::ExprId, generics::GenericParams, type_ref::Mutability, AdtId, ContainerId, DefWithBodyId,
23 GenericDefId, HasModule, Lookup, TraitId, TypeAliasId,
24};
25use hir_expand::name::Name;
26use ra_db::{impl_intern_key, salsa, CrateId};
27
28use crate::{
29 db::HirDatabase,
30 ty::primitive::{FloatTy, IntTy, Uncertain},
31 util::make_mut_slice,
32};
33use display::{HirDisplay, HirFormatter};
34
35pub(crate) use autoderef::autoderef;
36pub(crate) use infer::{infer_query, InferTy, InferenceResult};
37pub use lower::CallableDef;
38pub(crate) use lower::{
39 callable_item_sig, field_types_query, generic_defaults_query,
40 generic_predicates_for_param_query, generic_predicates_query, ty_query, value_ty_query,
41 TyDefId, ValueTyDefId,
42};
43pub(crate) use traits::{InEnvironment, Obligation, ProjectionPredicate, TraitEnvironment};
44
45/// A type constructor or type name: this might be something like the primitive
46/// type `bool`, a struct like `Vec`, or things like function pointers or
47/// tuples.
48#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
49pub enum TypeCtor {
50 /// The primitive boolean type. Written as `bool`.
51 Bool,
52
53 /// The primitive character type; holds a Unicode scalar value
54 /// (a non-surrogate code point). Written as `char`.
55 Char,
56
57 /// A primitive integer type. For example, `i32`.
58 Int(Uncertain<IntTy>),
59
60 /// A primitive floating-point type. For example, `f64`.
61 Float(Uncertain<FloatTy>),
62
63 /// Structures, enumerations and unions.
64 Adt(AdtId),
65
66 /// The pointee of a string slice. Written as `str`.
67 Str,
68
69 /// The pointee of an array slice. Written as `[T]`.
70 Slice,
71
72 /// An array with the given length. Written as `[T; n]`.
73 Array,
74
75 /// A raw pointer. Written as `*mut T` or `*const T`
76 RawPtr(Mutability),
77
78 /// A reference; a pointer with an associated lifetime. Written as
79 /// `&'a mut T` or `&'a T`.
80 Ref(Mutability),
81
82 /// The anonymous type of a function declaration/definition. Each
83 /// function has a unique type, which is output (for a function
84 /// named `foo` returning an `i32`) as `fn() -> i32 {foo}`.
85 ///
86 /// This includes tuple struct / enum variant constructors as well.
87 ///
88 /// For example the type of `bar` here:
89 ///
90 /// ```
91 /// fn foo() -> i32 { 1 }
92 /// let bar = foo; // bar: fn() -> i32 {foo}
93 /// ```
94 FnDef(CallableDef),
95
96 /// A pointer to a function. Written as `fn() -> i32`.
97 ///
98 /// For example the type of `bar` here:
99 ///
100 /// ```
101 /// fn foo() -> i32 { 1 }
102 /// let bar: fn() -> i32 = foo;
103 /// ```
104 FnPtr { num_args: u16 },
105
106 /// The never type `!`.
107 Never,
108
109 /// A tuple type. For example, `(i32, bool)`.
110 Tuple { cardinality: u16 },
111
112 /// Represents an associated item like `Iterator::Item`. This is used
113 /// when we have tried to normalize a projection like `T::Item` but
114 /// couldn't find a better representation. In that case, we generate
115 /// an **application type** like `(Iterator::Item)<T>`.
116 AssociatedType(TypeAliasId),
117
118 /// The type of a specific closure.
119 ///
120 /// The closure signature is stored in a `FnPtr` type in the first type
121 /// parameter.
122 Closure { def: DefWithBodyId, expr: ExprId },
123}
124
125/// This exists just for Chalk, because Chalk just has a single `StructId` where
126/// we have different kinds of ADTs, primitive types and special type
127/// constructors like tuples and function pointers.
128#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
129pub struct TypeCtorId(salsa::InternId);
130impl_intern_key!(TypeCtorId);
131
132impl TypeCtor {
133 pub fn num_ty_params(self, db: &impl HirDatabase) -> usize {
134 match self {
135 TypeCtor::Bool
136 | TypeCtor::Char
137 | TypeCtor::Int(_)
138 | TypeCtor::Float(_)
139 | TypeCtor::Str
140 | TypeCtor::Never => 0,
141 TypeCtor::Slice
142 | TypeCtor::Array
143 | TypeCtor::RawPtr(_)
144 | TypeCtor::Ref(_)
145 | TypeCtor::Closure { .. } // 1 param representing the signature of the closure
146 => 1,
147 TypeCtor::Adt(adt) => {
148 let generic_params = db.generic_params(AdtId::from(adt).into());
149 generic_params.count_params_including_parent()
150 }
151 TypeCtor::FnDef(callable) => {
152 let generic_params = db.generic_params(callable.into());
153 generic_params.count_params_including_parent()
154 }
155 TypeCtor::AssociatedType(type_alias) => {
156 let generic_params = db.generic_params(type_alias.into());
157 generic_params.count_params_including_parent()
158 }
159 TypeCtor::FnPtr { num_args } => num_args as usize + 1,
160 TypeCtor::Tuple { cardinality } => cardinality as usize,
161 }
162 }
163
164 pub fn krate(self, db: &impl HirDatabase) -> Option<CrateId> {
165 match self {
166 TypeCtor::Bool
167 | TypeCtor::Char
168 | TypeCtor::Int(_)
169 | TypeCtor::Float(_)
170 | TypeCtor::Str
171 | TypeCtor::Never
172 | TypeCtor::Slice
173 | TypeCtor::Array
174 | TypeCtor::RawPtr(_)
175 | TypeCtor::Ref(_)
176 | TypeCtor::FnPtr { .. }
177 | TypeCtor::Tuple { .. } => None,
178 // Closure's krate is irrelevant for coherence I would think?
179 TypeCtor::Closure { .. } => None,
180 TypeCtor::Adt(adt) => Some(adt.module(db).krate),
181 TypeCtor::FnDef(callable) => Some(callable.krate(db)),
182 TypeCtor::AssociatedType(type_alias) => Some(type_alias.lookup(db).module(db).krate),
183 }
184 }
185
186 pub fn as_generic_def(self) -> Option<GenericDefId> {
187 match self {
188 TypeCtor::Bool
189 | TypeCtor::Char
190 | TypeCtor::Int(_)
191 | TypeCtor::Float(_)
192 | TypeCtor::Str
193 | TypeCtor::Never
194 | TypeCtor::Slice
195 | TypeCtor::Array
196 | TypeCtor::RawPtr(_)
197 | TypeCtor::Ref(_)
198 | TypeCtor::FnPtr { .. }
199 | TypeCtor::Tuple { .. }
200 | TypeCtor::Closure { .. } => None,
201 TypeCtor::Adt(adt) => Some(adt.into()),
202 TypeCtor::FnDef(callable) => Some(callable.into()),
203 TypeCtor::AssociatedType(type_alias) => Some(type_alias.into()),
204 }
205 }
206}
207
208/// A nominal type with (maybe 0) type parameters. This might be a primitive
209/// type like `bool`, a struct, tuple, function pointer, reference or
210/// several other things.
211#[derive(Clone, PartialEq, Eq, Debug, Hash)]
212pub struct ApplicationTy {
213 pub ctor: TypeCtor,
214 pub parameters: Substs,
215}
216
217/// A "projection" type corresponds to an (unnormalized)
218/// projection like `<P0 as Trait<P1..Pn>>::Foo`. Note that the
219/// trait and all its parameters are fully known.
220#[derive(Clone, PartialEq, Eq, Debug, Hash)]
221pub struct ProjectionTy {
222 pub associated_ty: TypeAliasId,
223 pub parameters: Substs,
224}
225
226impl ProjectionTy {
227 pub fn trait_ref(&self, db: &impl HirDatabase) -> TraitRef {
228 TraitRef { trait_: self.trait_(db).into(), substs: self.parameters.clone() }
229 }
230
231 fn trait_(&self, db: &impl HirDatabase) -> TraitId {
232 match self.associated_ty.lookup(db).container {
233 ContainerId::TraitId(it) => it,
234 _ => panic!("projection ty without parent trait"),
235 }
236 }
237}
238
239impl TypeWalk for ProjectionTy {
240 fn walk(&self, f: &mut impl FnMut(&Ty)) {
241 self.parameters.walk(f);
242 }
243
244 fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) {
245 self.parameters.walk_mut_binders(f, binders);
246 }
247}
248
249/// A type.
250///
251/// See also the `TyKind` enum in rustc (librustc/ty/sty.rs), which represents
252/// the same thing (but in a different way).
253///
254/// This should be cheap to clone.
255#[derive(Clone, PartialEq, Eq, Debug, Hash)]
256pub enum Ty {
257 /// A nominal type with (maybe 0) type parameters. This might be a primitive
258 /// type like `bool`, a struct, tuple, function pointer, reference or
259 /// several other things.
260 Apply(ApplicationTy),
261
262 /// A "projection" type corresponds to an (unnormalized)
263 /// projection like `<P0 as Trait<P1..Pn>>::Foo`. Note that the
264 /// trait and all its parameters are fully known.
265 Projection(ProjectionTy),
266
267 /// A type parameter; for example, `T` in `fn f<T>(x: T) {}
268 Param {
269 /// The index of the parameter (starting with parameters from the
270 /// surrounding impl, then the current function).
271 idx: u32,
272 /// The name of the parameter, for displaying.
273 // FIXME get rid of this
274 name: Name,
275 },
276
277 /// A bound type variable. Used during trait resolution to represent Chalk
278 /// variables, and in `Dyn` and `Opaque` bounds to represent the `Self` type.
279 Bound(u32),
280
281 /// A type variable used during type checking. Not to be confused with a
282 /// type parameter.
283 Infer(InferTy),
284
285 /// A trait object (`dyn Trait` or bare `Trait` in pre-2018 Rust).
286 ///
287 /// The predicates are quantified over the `Self` type, i.e. `Ty::Bound(0)`
288 /// represents the `Self` type inside the bounds. This is currently
289 /// implicit; Chalk has the `Binders` struct to make it explicit, but it
290 /// didn't seem worth the overhead yet.
291 Dyn(Arc<[GenericPredicate]>),
292
293 /// An opaque type (`impl Trait`).
294 ///
295 /// The predicates are quantified over the `Self` type; see `Ty::Dyn` for
296 /// more.
297 Opaque(Arc<[GenericPredicate]>),
298
299 /// A placeholder for a type which could not be computed; this is propagated
300 /// to avoid useless error messages. Doubles as a placeholder where type
301 /// variables are inserted before type checking, since we want to try to
302 /// infer a better type here anyway -- for the IDE use case, we want to try
303 /// to infer as much as possible even in the presence of type errors.
304 Unknown,
305}
306
307/// A list of substitutions for generic parameters.
308#[derive(Clone, PartialEq, Eq, Debug, Hash)]
309pub struct Substs(Arc<[Ty]>);
310
311impl TypeWalk for Substs {
312 fn walk(&self, f: &mut impl FnMut(&Ty)) {
313 for t in self.0.iter() {
314 t.walk(f);
315 }
316 }
317
318 fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) {
319 for t in make_mut_slice(&mut self.0) {
320 t.walk_mut_binders(f, binders);
321 }
322 }
323}
324
325impl Substs {
326 pub fn empty() -> Substs {
327 Substs(Arc::new([]))
328 }
329
330 pub fn single(ty: Ty) -> Substs {
331 Substs(Arc::new([ty]))
332 }
333
334 pub fn prefix(&self, n: usize) -> Substs {
335 Substs(self.0[..std::cmp::min(self.0.len(), n)].into())
336 }
337
338 pub fn as_single(&self) -> &Ty {
339 if self.0.len() != 1 {
340 panic!("expected substs of len 1, got {:?}", self);
341 }
342 &self.0[0]
343 }
344
345 /// Return Substs that replace each parameter by itself (i.e. `Ty::Param`).
346 pub fn identity(generic_params: &GenericParams) -> Substs {
347 Substs(
348 generic_params
349 .params_including_parent()
350 .into_iter()
351 .map(|p| Ty::Param { idx: p.idx, name: p.name.clone() })
352 .collect(),
353 )
354 }
355
356 /// Return Substs that replace each parameter by a bound variable.
357 pub fn bound_vars(generic_params: &GenericParams) -> Substs {
358 Substs(
359 generic_params
360 .params_including_parent()
361 .into_iter()
362 .map(|p| Ty::Bound(p.idx))
363 .collect(),
364 )
365 }
366
367 pub fn build_for_def(db: &impl HirDatabase, def: impl Into<GenericDefId>) -> SubstsBuilder {
368 let def = def.into();
369 let params = db.generic_params(def);
370 let param_count = params.count_params_including_parent();
371 Substs::builder(param_count)
372 }
373
374 pub fn build_for_generics(generic_params: &GenericParams) -> SubstsBuilder {
375 Substs::builder(generic_params.count_params_including_parent())
376 }
377
378 pub fn build_for_type_ctor(db: &impl HirDatabase, type_ctor: TypeCtor) -> SubstsBuilder {
379 Substs::builder(type_ctor.num_ty_params(db))
380 }
381
382 fn builder(param_count: usize) -> SubstsBuilder {
383 SubstsBuilder { vec: Vec::with_capacity(param_count), param_count }
384 }
385}
386
387#[derive(Debug, Clone)]
388pub struct SubstsBuilder {
389 vec: Vec<Ty>,
390 param_count: usize,
391}
392
393impl SubstsBuilder {
394 pub fn build(self) -> Substs {
395 assert_eq!(self.vec.len(), self.param_count);
396 Substs(self.vec.into())
397 }
398
399 pub fn push(mut self, ty: Ty) -> Self {
400 self.vec.push(ty);
401 self
402 }
403
404 fn remaining(&self) -> usize {
405 self.param_count - self.vec.len()
406 }
407
408 pub fn fill_with_bound_vars(self, starting_from: u32) -> Self {
409 self.fill((starting_from..).map(Ty::Bound))
410 }
411
412 pub fn fill_with_params(self) -> Self {
413 let start = self.vec.len() as u32;
414 self.fill((start..).map(|idx| Ty::Param { idx, name: Name::missing() }))
415 }
416
417 pub fn fill_with_unknown(self) -> Self {
418 self.fill(iter::repeat(Ty::Unknown))
419 }
420
421 pub fn fill(mut self, filler: impl Iterator<Item = Ty>) -> Self {
422 self.vec.extend(filler.take(self.remaining()));
423 assert_eq!(self.remaining(), 0);
424 self
425 }
426
427 pub fn use_parent_substs(mut self, parent_substs: &Substs) -> Self {
428 assert!(self.vec.is_empty());
429 assert!(parent_substs.len() <= self.param_count);
430 self.vec.extend(parent_substs.iter().cloned());
431 self
432 }
433}
434
435impl Deref for Substs {
436 type Target = [Ty];
437
438 fn deref(&self) -> &[Ty] {
439 &self.0
440 }
441}
442
443/// A trait with type parameters. This includes the `Self`, so this represents a concrete type implementing the trait.
444/// Name to be bikeshedded: TraitBound? TraitImplements?
445#[derive(Clone, PartialEq, Eq, Debug, Hash)]
446pub struct TraitRef {
447 /// FIXME name?
448 pub trait_: TraitId,
449 pub substs: Substs,
450}
451
452impl TraitRef {
453 pub fn self_ty(&self) -> &Ty {
454 &self.substs[0]
455 }
456}
457
458impl TypeWalk for TraitRef {
459 fn walk(&self, f: &mut impl FnMut(&Ty)) {
460 self.substs.walk(f);
461 }
462
463 fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) {
464 self.substs.walk_mut_binders(f, binders);
465 }
466}
467
468/// Like `generics::WherePredicate`, but with resolved types: A condition on the
469/// parameters of a generic item.
470#[derive(Debug, Clone, PartialEq, Eq, Hash)]
471pub enum GenericPredicate {
472 /// The given trait needs to be implemented for its type parameters.
473 Implemented(TraitRef),
474 /// An associated type bindings like in `Iterator<Item = T>`.
475 Projection(ProjectionPredicate),
476 /// We couldn't resolve the trait reference. (If some type parameters can't
477 /// be resolved, they will just be Unknown).
478 Error,
479}
480
481impl GenericPredicate {
482 pub fn is_error(&self) -> bool {
483 match self {
484 GenericPredicate::Error => true,
485 _ => false,
486 }
487 }
488
489 pub fn is_implemented(&self) -> bool {
490 match self {
491 GenericPredicate::Implemented(_) => true,
492 _ => false,
493 }
494 }
495
496 pub fn trait_ref(&self, db: &impl HirDatabase) -> Option<TraitRef> {
497 match self {
498 GenericPredicate::Implemented(tr) => Some(tr.clone()),
499 GenericPredicate::Projection(proj) => Some(proj.projection_ty.trait_ref(db)),
500 GenericPredicate::Error => None,
501 }
502 }
503}
504
505impl TypeWalk for GenericPredicate {
506 fn walk(&self, f: &mut impl FnMut(&Ty)) {
507 match self {
508 GenericPredicate::Implemented(trait_ref) => trait_ref.walk(f),
509 GenericPredicate::Projection(projection_pred) => projection_pred.walk(f),
510 GenericPredicate::Error => {}
511 }
512 }
513
514 fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) {
515 match self {
516 GenericPredicate::Implemented(trait_ref) => trait_ref.walk_mut_binders(f, binders),
517 GenericPredicate::Projection(projection_pred) => {
518 projection_pred.walk_mut_binders(f, binders)
519 }
520 GenericPredicate::Error => {}
521 }
522 }
523}
524
525/// Basically a claim (currently not validated / checked) that the contained
526/// type / trait ref contains no inference variables; any inference variables it
527/// contained have been replaced by bound variables, and `num_vars` tells us how
528/// many there are. This is used to erase irrelevant differences between types
529/// before using them in queries.
530#[derive(Debug, Clone, PartialEq, Eq, Hash)]
531pub struct Canonical<T> {
532 pub value: T,
533 pub num_vars: usize,
534}
535
536/// A function signature as seen by type inference: Several parameter types and
537/// one return type.
538#[derive(Clone, PartialEq, Eq, Debug)]
539pub struct FnSig {
540 params_and_return: Arc<[Ty]>,
541}
542
543impl FnSig {
544 pub fn from_params_and_return(mut params: Vec<Ty>, ret: Ty) -> FnSig {
545 params.push(ret);
546 FnSig { params_and_return: params.into() }
547 }
548
549 pub fn from_fn_ptr_substs(substs: &Substs) -> FnSig {
550 FnSig { params_and_return: Arc::clone(&substs.0) }
551 }
552
553 pub fn params(&self) -> &[Ty] {
554 &self.params_and_return[0..self.params_and_return.len() - 1]
555 }
556
557 pub fn ret(&self) -> &Ty {
558 &self.params_and_return[self.params_and_return.len() - 1]
559 }
560}
561
562impl TypeWalk for FnSig {
563 fn walk(&self, f: &mut impl FnMut(&Ty)) {
564 for t in self.params_and_return.iter() {
565 t.walk(f);
566 }
567 }
568
569 fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) {
570 for t in make_mut_slice(&mut self.params_and_return) {
571 t.walk_mut_binders(f, binders);
572 }
573 }
574}
575
576impl Ty {
577 pub fn simple(ctor: TypeCtor) -> Ty {
578 Ty::Apply(ApplicationTy { ctor, parameters: Substs::empty() })
579 }
580 pub fn apply_one(ctor: TypeCtor, param: Ty) -> Ty {
581 Ty::Apply(ApplicationTy { ctor, parameters: Substs::single(param) })
582 }
583 pub fn apply(ctor: TypeCtor, parameters: Substs) -> Ty {
584 Ty::Apply(ApplicationTy { ctor, parameters })
585 }
586 pub fn unit() -> Self {
587 Ty::apply(TypeCtor::Tuple { cardinality: 0 }, Substs::empty())
588 }
589
590 pub fn as_reference(&self) -> Option<(&Ty, Mutability)> {
591 match self {
592 Ty::Apply(ApplicationTy { ctor: TypeCtor::Ref(mutability), parameters }) => {
593 Some((parameters.as_single(), *mutability))
594 }
595 _ => None,
596 }
597 }
598
599 pub fn as_adt(&self) -> Option<(AdtId, &Substs)> {
600 match self {
601 Ty::Apply(ApplicationTy { ctor: TypeCtor::Adt(adt_def), parameters }) => {
602 Some((*adt_def, parameters))
603 }
604 _ => None,
605 }
606 }
607
608 pub fn as_tuple(&self) -> Option<&Substs> {
609 match self {
610 Ty::Apply(ApplicationTy { ctor: TypeCtor::Tuple { .. }, parameters }) => {
611 Some(parameters)
612 }
613 _ => None,
614 }
615 }
616
617 pub fn as_callable(&self) -> Option<(CallableDef, &Substs)> {
618 match self {
619 Ty::Apply(ApplicationTy { ctor: TypeCtor::FnDef(callable_def), parameters }) => {
620 Some((*callable_def, parameters))
621 }
622 _ => None,
623 }
624 }
625
626 fn builtin_deref(&self) -> Option<Ty> {
627 match self {
628 Ty::Apply(a_ty) => match a_ty.ctor {
629 TypeCtor::Ref(..) => Some(Ty::clone(a_ty.parameters.as_single())),
630 TypeCtor::RawPtr(..) => Some(Ty::clone(a_ty.parameters.as_single())),
631 _ => None,
632 },
633 _ => None,
634 }
635 }
636
637 fn callable_sig(&self, db: &impl HirDatabase) -> Option<FnSig> {
638 match self {
639 Ty::Apply(a_ty) => match a_ty.ctor {
640 TypeCtor::FnPtr { .. } => Some(FnSig::from_fn_ptr_substs(&a_ty.parameters)),
641 TypeCtor::FnDef(def) => {
642 let sig = db.callable_item_signature(def);
643 Some(sig.subst(&a_ty.parameters))
644 }
645 TypeCtor::Closure { .. } => {
646 let sig_param = &a_ty.parameters[0];
647 sig_param.callable_sig(db)
648 }
649 _ => None,
650 },
651 _ => None,
652 }
653 }
654
655 /// If this is a type with type parameters (an ADT or function), replaces
656 /// the `Substs` for these type parameters with the given ones. (So e.g. if
657 /// `self` is `Option<_>` and the substs contain `u32`, we'll have
658 /// `Option<u32>` afterwards.)
659 pub fn apply_substs(self, substs: Substs) -> Ty {
660 match self {
661 Ty::Apply(ApplicationTy { ctor, parameters: previous_substs }) => {
662 assert_eq!(previous_substs.len(), substs.len());
663 Ty::Apply(ApplicationTy { ctor, parameters: substs })
664 }
665 _ => self,
666 }
667 }
668
669 /// Returns the type parameters of this type if it has some (i.e. is an ADT
670 /// or function); so if `self` is `Option<u32>`, this returns the `u32`.
671 pub fn substs(&self) -> Option<Substs> {
672 match self {
673 Ty::Apply(ApplicationTy { parameters, .. }) => Some(parameters.clone()),
674 _ => None,
675 }
676 }
677
678 /// If this is an `impl Trait` or `dyn Trait`, returns that trait.
679 pub fn inherent_trait(&self) -> Option<TraitId> {
680 match self {
681 Ty::Dyn(predicates) | Ty::Opaque(predicates) => {
682 predicates.iter().find_map(|pred| match pred {
683 GenericPredicate::Implemented(tr) => Some(tr.trait_),
684 _ => None,
685 })
686 }
687 _ => None,
688 }
689 }
690}
691
692/// This allows walking structures that contain types to do something with those
693/// types, similar to Chalk's `Fold` trait.
694pub trait TypeWalk {
695 fn walk(&self, f: &mut impl FnMut(&Ty));
696 fn walk_mut(&mut self, f: &mut impl FnMut(&mut Ty)) {
697 self.walk_mut_binders(&mut |ty, _binders| f(ty), 0);
698 }
699 /// Walk the type, counting entered binders.
700 ///
701 /// `Ty::Bound` variables use DeBruijn indexing, which means that 0 refers
702 /// to the innermost binder, 1 to the next, etc.. So when we want to
703 /// substitute a certain bound variable, we can't just walk the whole type
704 /// and blindly replace each instance of a certain index; when we 'enter'
705 /// things that introduce new bound variables, we have to keep track of
706 /// that. Currently, the only thing that introduces bound variables on our
707 /// side are `Ty::Dyn` and `Ty::Opaque`, which each introduce a bound
708 /// variable for the self type.
709 fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize);
710
711 fn fold(mut self, f: &mut impl FnMut(Ty) -> Ty) -> Self
712 where
713 Self: Sized,
714 {
715 self.walk_mut(&mut |ty_mut| {
716 let ty = mem::replace(ty_mut, Ty::Unknown);
717 *ty_mut = f(ty);
718 });
719 self
720 }
721
722 /// Replaces type parameters in this type using the given `Substs`. (So e.g.
723 /// if `self` is `&[T]`, where type parameter T has index 0, and the
724 /// `Substs` contain `u32` at index 0, we'll have `&[u32]` afterwards.)
725 fn subst(self, substs: &Substs) -> Self
726 where
727 Self: Sized,
728 {
729 self.fold(&mut |ty| match ty {
730 Ty::Param { idx, name } => {
731 substs.get(idx as usize).cloned().unwrap_or(Ty::Param { idx, name })
732 }
733 ty => ty,
734 })
735 }
736
737 /// Substitutes `Ty::Bound` vars (as opposed to type parameters).
738 fn subst_bound_vars(mut self, substs: &Substs) -> Self
739 where
740 Self: Sized,
741 {
742 self.walk_mut_binders(
743 &mut |ty, binders| match ty {
744 &mut Ty::Bound(idx) => {
745 if idx as usize >= binders && (idx as usize - binders) < substs.len() {
746 *ty = substs.0[idx as usize - binders].clone();
747 }
748 }
749 _ => {}
750 },
751 0,
752 );
753 self
754 }
755
756 /// Shifts up `Ty::Bound` vars by `n`.
757 fn shift_bound_vars(self, n: i32) -> Self
758 where
759 Self: Sized,
760 {
761 self.fold(&mut |ty| match ty {
762 Ty::Bound(idx) => {
763 assert!(idx as i32 >= -n);
764 Ty::Bound((idx as i32 + n) as u32)
765 }
766 ty => ty,
767 })
768 }
769}
770
771impl TypeWalk for Ty {
772 fn walk(&self, f: &mut impl FnMut(&Ty)) {
773 match self {
774 Ty::Apply(a_ty) => {
775 for t in a_ty.parameters.iter() {
776 t.walk(f);
777 }
778 }
779 Ty::Projection(p_ty) => {
780 for t in p_ty.parameters.iter() {
781 t.walk(f);
782 }
783 }
784 Ty::Dyn(predicates) | Ty::Opaque(predicates) => {
785 for p in predicates.iter() {
786 p.walk(f);
787 }
788 }
789 Ty::Param { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {}
790 }
791 f(self);
792 }
793
794 fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) {
795 match self {
796 Ty::Apply(a_ty) => {
797 a_ty.parameters.walk_mut_binders(f, binders);
798 }
799 Ty::Projection(p_ty) => {
800 p_ty.parameters.walk_mut_binders(f, binders);
801 }
802 Ty::Dyn(predicates) | Ty::Opaque(predicates) => {
803 for p in make_mut_slice(predicates) {
804 p.walk_mut_binders(f, binders + 1);
805 }
806 }
807 Ty::Param { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {}
808 }
809 f(self, binders);
810 }
811}
812
813impl HirDisplay for &Ty {
814 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
815 HirDisplay::hir_fmt(*self, f)
816 }
817}
818
819impl HirDisplay for ApplicationTy {
820 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
821 if f.should_truncate() {
822 return write!(f, "…");
823 }
824
825 match self.ctor {
826 TypeCtor::Bool => write!(f, "bool")?,
827 TypeCtor::Char => write!(f, "char")?,
828 TypeCtor::Int(t) => write!(f, "{}", t)?,
829 TypeCtor::Float(t) => write!(f, "{}", t)?,
830 TypeCtor::Str => write!(f, "str")?,
831 TypeCtor::Slice => {
832 let t = self.parameters.as_single();
833 write!(f, "[{}]", t.display(f.db))?;
834 }
835 TypeCtor::Array => {
836 let t = self.parameters.as_single();
837 write!(f, "[{};_]", t.display(f.db))?;
838 }
839 TypeCtor::RawPtr(m) => {
840 let t = self.parameters.as_single();
841 write!(f, "*{}{}", m.as_keyword_for_ptr(), t.display(f.db))?;
842 }
843 TypeCtor::Ref(m) => {
844 let t = self.parameters.as_single();
845 write!(f, "&{}{}", m.as_keyword_for_ref(), t.display(f.db))?;
846 }
847 TypeCtor::Never => write!(f, "!")?,
848 TypeCtor::Tuple { .. } => {
849 let ts = &self.parameters;
850 if ts.len() == 1 {
851 write!(f, "({},)", ts[0].display(f.db))?;
852 } else {
853 write!(f, "(")?;
854 f.write_joined(&*ts.0, ", ")?;
855 write!(f, ")")?;
856 }
857 }
858 TypeCtor::FnPtr { .. } => {
859 let sig = FnSig::from_fn_ptr_substs(&self.parameters);
860 write!(f, "fn(")?;
861 f.write_joined(sig.params(), ", ")?;
862 write!(f, ") -> {}", sig.ret().display(f.db))?;
863 }
864 TypeCtor::FnDef(def) => {
865 let sig = f.db.callable_item_signature(def);
866 let name = match def {
867 CallableDef::FunctionId(ff) => f.db.function_data(ff).name.clone(),
868 CallableDef::StructId(s) => {
869 f.db.struct_data(s).name.clone().unwrap_or_else(Name::missing)
870 }
871 CallableDef::EnumVariantId(e) => {
872 let enum_data = f.db.enum_data(e.parent);
873 enum_data.variants[e.local_id].name.clone().unwrap_or_else(Name::missing)
874 }
875 };
876 match def {
877 CallableDef::FunctionId(_) => write!(f, "fn {}", name)?,
878 CallableDef::StructId(_) | CallableDef::EnumVariantId(_) => {
879 write!(f, "{}", name)?
880 }
881 }
882 if self.parameters.len() > 0 {
883 write!(f, "<")?;
884 f.write_joined(&*self.parameters.0, ", ")?;
885 write!(f, ">")?;
886 }
887 write!(f, "(")?;
888 f.write_joined(sig.params(), ", ")?;
889 write!(f, ") -> {}", sig.ret().display(f.db))?;
890 }
891 TypeCtor::Adt(def_id) => {
892 let name = match def_id {
893 AdtId::StructId(it) => f.db.struct_data(it).name.clone(),
894 AdtId::UnionId(it) => f.db.union_data(it).name.clone(),
895 AdtId::EnumId(it) => f.db.enum_data(it).name.clone(),
896 }
897 .unwrap_or_else(Name::missing);
898 write!(f, "{}", name)?;
899 if self.parameters.len() > 0 {
900 write!(f, "<")?;
901 f.write_joined(&*self.parameters.0, ", ")?;
902 write!(f, ">")?;
903 }
904 }
905 TypeCtor::AssociatedType(type_alias) => {
906 let trait_ = match type_alias.lookup(f.db).container {
907 ContainerId::TraitId(it) => it,
908 _ => panic!("not an associated type"),
909 };
910 let trait_name = f.db.trait_data(trait_).name.clone().unwrap_or_else(Name::missing);
911 let name = f.db.type_alias_data(type_alias).name.clone();
912 write!(f, "{}::{}", trait_name, name)?;
913 if self.parameters.len() > 0 {
914 write!(f, "<")?;
915 f.write_joined(&*self.parameters.0, ", ")?;
916 write!(f, ">")?;
917 }
918 }
919 TypeCtor::Closure { .. } => {
920 let sig = self.parameters[0]
921 .callable_sig(f.db)
922 .expect("first closure parameter should contain signature");
923 write!(f, "|")?;
924 f.write_joined(sig.params(), ", ")?;
925 write!(f, "| -> {}", sig.ret().display(f.db))?;
926 }
927 }
928 Ok(())
929 }
930}
931
932impl HirDisplay for ProjectionTy {
933 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
934 if f.should_truncate() {
935 return write!(f, "…");
936 }
937
938 let trait_name =
939 f.db.trait_data(self.trait_(f.db)).name.clone().unwrap_or_else(Name::missing);
940 write!(f, "<{} as {}", self.parameters[0].display(f.db), trait_name,)?;
941 if self.parameters.len() > 1 {
942 write!(f, "<")?;
943 f.write_joined(&self.parameters[1..], ", ")?;
944 write!(f, ">")?;
945 }
946 write!(f, ">::{}", f.db.type_alias_data(self.associated_ty).name)?;
947 Ok(())
948 }
949}
950
951impl HirDisplay for Ty {
952 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
953 if f.should_truncate() {
954 return write!(f, "…");
955 }
956
957 match self {
958 Ty::Apply(a_ty) => a_ty.hir_fmt(f)?,
959 Ty::Projection(p_ty) => p_ty.hir_fmt(f)?,
960 Ty::Param { name, .. } => write!(f, "{}", name)?,
961 Ty::Bound(idx) => write!(f, "?{}", idx)?,
962 Ty::Dyn(predicates) | Ty::Opaque(predicates) => {
963 match self {
964 Ty::Dyn(_) => write!(f, "dyn ")?,
965 Ty::Opaque(_) => write!(f, "impl ")?,
966 _ => unreachable!(),
967 };
968 // Note: This code is written to produce nice results (i.e.
969 // corresponding to surface Rust) for types that can occur in
970 // actual Rust. It will have weird results if the predicates
971 // aren't as expected (i.e. self types = $0, projection
972 // predicates for a certain trait come after the Implemented
973 // predicate for that trait).
974 let mut first = true;
975 let mut angle_open = false;
976 for p in predicates.iter() {
977 match p {
978 GenericPredicate::Implemented(trait_ref) => {
979 if angle_open {
980 write!(f, ">")?;
981 }
982 if !first {
983 write!(f, " + ")?;
984 }
985 // We assume that the self type is $0 (i.e. the
986 // existential) here, which is the only thing that's
987 // possible in actual Rust, and hence don't print it
988 write!(
989 f,
990 "{}",
991 f.db.trait_data(trait_ref.trait_)
992 .name
993 .clone()
994 .unwrap_or_else(Name::missing)
995 )?;
996 if trait_ref.substs.len() > 1 {
997 write!(f, "<")?;
998 f.write_joined(&trait_ref.substs[1..], ", ")?;
999 // there might be assoc type bindings, so we leave the angle brackets open
1000 angle_open = true;
1001 }
1002 }
1003 GenericPredicate::Projection(projection_pred) => {
1004 // in types in actual Rust, these will always come
1005 // after the corresponding Implemented predicate
1006 if angle_open {
1007 write!(f, ", ")?;
1008 } else {
1009 write!(f, "<")?;
1010 angle_open = true;
1011 }
1012 let name =
1013 f.db.type_alias_data(projection_pred.projection_ty.associated_ty)
1014 .name
1015 .clone();
1016 write!(f, "{} = ", name)?;
1017 projection_pred.ty.hir_fmt(f)?;
1018 }
1019 GenericPredicate::Error => {
1020 if angle_open {
1021 // impl Trait<X, {error}>
1022 write!(f, ", ")?;
1023 } else if !first {
1024 // impl Trait + {error}
1025 write!(f, " + ")?;
1026 }
1027 p.hir_fmt(f)?;
1028 }
1029 }
1030 first = false;
1031 }
1032 if angle_open {
1033 write!(f, ">")?;
1034 }
1035 }
1036 Ty::Unknown => write!(f, "{{unknown}}")?,
1037 Ty::Infer(..) => write!(f, "_")?,
1038 }
1039 Ok(())
1040 }
1041}
1042
1043impl TraitRef {
1044 fn hir_fmt_ext(&self, f: &mut HirFormatter<impl HirDatabase>, use_as: bool) -> fmt::Result {
1045 if f.should_truncate() {
1046 return write!(f, "…");
1047 }
1048
1049 self.substs[0].hir_fmt(f)?;
1050 if use_as {
1051 write!(f, " as ")?;
1052 } else {
1053 write!(f, ": ")?;
1054 }
1055 write!(f, "{}", f.db.trait_data(self.trait_).name.clone().unwrap_or_else(Name::missing))?;
1056 if self.substs.len() > 1 {
1057 write!(f, "<")?;
1058 f.write_joined(&self.substs[1..], ", ")?;
1059 write!(f, ">")?;
1060 }
1061 Ok(())
1062 }
1063}
1064
1065impl HirDisplay for TraitRef {
1066 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
1067 self.hir_fmt_ext(f, false)
1068 }
1069}
1070
1071impl HirDisplay for &GenericPredicate {
1072 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
1073 HirDisplay::hir_fmt(*self, f)
1074 }
1075}
1076
1077impl HirDisplay for GenericPredicate {
1078 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
1079 if f.should_truncate() {
1080 return write!(f, "…");
1081 }
1082
1083 match self {
1084 GenericPredicate::Implemented(trait_ref) => trait_ref.hir_fmt(f)?,
1085 GenericPredicate::Projection(projection_pred) => {
1086 write!(f, "<")?;
1087 projection_pred.projection_ty.trait_ref(f.db).hir_fmt_ext(f, true)?;
1088 write!(
1089 f,
1090 ">::{} = {}",
1091 f.db.type_alias_data(projection_pred.projection_ty.associated_ty).name,
1092 projection_pred.ty.display(f.db)
1093 )?;
1094 }
1095 GenericPredicate::Error => write!(f, "{{error}}")?,
1096 }
1097 Ok(())
1098 }
1099}
1100
1101impl HirDisplay for Obligation {
1102 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
1103 match self {
1104 Obligation::Trait(tr) => write!(f, "Implements({})", tr.display(f.db)),
1105 Obligation::Projection(proj) => write!(
1106 f,
1107 "Normalize({} => {})",
1108 proj.projection_ty.display(f.db),
1109 proj.ty.display(f.db)
1110 ),
1111 }
1112 }
1113}
diff --git a/crates/ra_hir/src/ty/primitive.rs b/crates/ra_hir/src/ty/primitive.rs
deleted file mode 100644
index 12dc96572..000000000
--- a/crates/ra_hir/src/ty/primitive.rs
+++ /dev/null
@@ -1,3 +0,0 @@
1//! FIXME: write short doc here
2
3pub use hir_ty::primitive::{FloatBitness, FloatTy, IntBitness, IntTy, Signedness, Uncertain};
diff --git a/crates/ra_hir/src/util.rs b/crates/ra_hir/src/util.rs
deleted file mode 100644
index 0095ee45d..000000000
--- a/crates/ra_hir/src/util.rs
+++ /dev/null
@@ -1,12 +0,0 @@
1//! Internal utility functions.
2
3use std::sync::Arc;
4
5/// Helper for mutating `Arc<[T]>` (i.e. `Arc::make_mut` for Arc slices).
6/// The underlying values are cloned if there are other strong references.
7pub(crate) fn make_mut_slice<T: Clone>(a: &mut Arc<[T]>) -> &mut [T] {
8 if Arc::get_mut(a).is_none() {
9 *a = a.iter().cloned().collect();
10 }
11 Arc::get_mut(a).unwrap()
12}
diff --git a/crates/ra_hir_def/src/lib.rs b/crates/ra_hir_def/src/lib.rs
index ea3f00bb3..ddf464c60 100644
--- a/crates/ra_hir_def/src/lib.rs
+++ b/crates/ra_hir_def/src/lib.rs
@@ -27,7 +27,7 @@ pub mod body;
27pub mod resolver; 27pub mod resolver;
28 28
29mod trace; 29mod trace;
30mod nameres; 30pub mod nameres;
31 31
32#[cfg(test)] 32#[cfg(test)]
33mod test_db; 33mod test_db;
diff --git a/crates/ra_hir_ty/Cargo.toml b/crates/ra_hir_ty/Cargo.toml
index 027b50865..429242870 100644
--- a/crates/ra_hir_ty/Cargo.toml
+++ b/crates/ra_hir_ty/Cargo.toml
@@ -8,18 +8,18 @@ authors = ["rust-analyzer developers"]
8doctest = false 8doctest = false
9 9
10[dependencies] 10[dependencies]
11arrayvec = "0.5.1"
12ena = "0.13"
11log = "0.4.5" 13log = "0.4.5"
12rustc-hash = "1.0" 14rustc-hash = "1.0"
13parking_lot = "0.10.0"
14ena = "0.13"
15 15
16ra_syntax = { path = "../ra_syntax" } 16hir_def = { path = "../ra_hir_def", package = "ra_hir_def" }
17hir_expand = { path = "../ra_hir_expand", package = "ra_hir_expand" }
17ra_arena = { path = "../ra_arena" } 18ra_arena = { path = "../ra_arena" }
18ra_db = { path = "../ra_db" } 19ra_db = { path = "../ra_db" }
19hir_expand = { path = "../ra_hir_expand", package = "ra_hir_expand" }
20hir_def = { path = "../ra_hir_def", package = "ra_hir_def" }
21test_utils = { path = "../test_utils" }
22ra_prof = { path = "../ra_prof" } 20ra_prof = { path = "../ra_prof" }
21ra_syntax = { path = "../ra_syntax" }
22test_utils = { path = "../test_utils" }
23 23
24# https://github.com/rust-lang/chalk/pull/294 24# https://github.com/rust-lang/chalk/pull/294
25chalk-solve = { git = "https://github.com/jackh726/chalk.git", rev = "095cd38a4f16337913bba487f2055b9ca0179f30" } 25chalk-solve = { git = "https://github.com/jackh726/chalk.git", rev = "095cd38a4f16337913bba487f2055b9ca0179f30" }
diff --git a/crates/ra_hir/src/ty/autoderef.rs b/crates/ra_hir_ty/src/autoderef.rs
index ae68234ac..9d1d4e48c 100644
--- a/crates/ra_hir/src/ty/autoderef.rs
+++ b/crates/ra_hir_ty/src/autoderef.rs
@@ -19,7 +19,7 @@ use super::{
19 19
20const AUTODEREF_RECURSION_LIMIT: usize = 10; 20const AUTODEREF_RECURSION_LIMIT: usize = 10;
21 21
22pub(crate) fn autoderef<'a>( 22pub fn autoderef<'a>(
23 db: &'a impl HirDatabase, 23 db: &'a impl HirDatabase,
24 krate: Option<CrateId>, 24 krate: Option<CrateId>,
25 ty: InEnvironment<Canonical<Ty>>, 25 ty: InEnvironment<Canonical<Ty>>,
diff --git a/crates/ra_hir_ty/src/db.rs b/crates/ra_hir_ty/src/db.rs
new file mode 100644
index 000000000..aa2659c4b
--- /dev/null
+++ b/crates/ra_hir_ty/src/db.rs
@@ -0,0 +1,116 @@
1//! FIXME: write short doc here
2
3use std::sync::Arc;
4
5use hir_def::{
6 db::DefDatabase, DefWithBodyId, GenericDefId, ImplId, LocalStructFieldId, TraitId, VariantId,
7};
8use ra_arena::map::ArenaMap;
9use ra_db::{salsa, CrateId};
10
11use crate::{
12 method_resolution::CrateImplBlocks,
13 traits::{AssocTyValue, Impl},
14 CallableDef, FnSig, GenericPredicate, InferenceResult, Substs, Ty, TyDefId, TypeCtor,
15 ValueTyDefId,
16};
17
18#[salsa::query_group(HirDatabaseStorage)]
19#[salsa::requires(salsa::Database)]
20pub trait HirDatabase: DefDatabase {
21 #[salsa::invoke(crate::infer_query)]
22 fn infer(&self, def: DefWithBodyId) -> Arc<InferenceResult>;
23
24 #[salsa::invoke(crate::lower::ty_query)]
25 fn ty(&self, def: TyDefId) -> Ty;
26
27 #[salsa::invoke(crate::lower::value_ty_query)]
28 fn value_ty(&self, def: ValueTyDefId) -> Ty;
29
30 #[salsa::invoke(crate::lower::field_types_query)]
31 fn field_types(&self, var: VariantId) -> Arc<ArenaMap<LocalStructFieldId, Ty>>;
32
33 #[salsa::invoke(crate::callable_item_sig)]
34 fn callable_item_signature(&self, def: CallableDef) -> FnSig;
35
36 #[salsa::invoke(crate::lower::generic_predicates_for_param_query)]
37 fn generic_predicates_for_param(
38 &self,
39 def: GenericDefId,
40 param_idx: u32,
41 ) -> Arc<[GenericPredicate]>;
42
43 #[salsa::invoke(crate::lower::generic_predicates_query)]
44 fn generic_predicates(&self, def: GenericDefId) -> Arc<[GenericPredicate]>;
45
46 #[salsa::invoke(crate::lower::generic_defaults_query)]
47 fn generic_defaults(&self, def: GenericDefId) -> Substs;
48
49 #[salsa::invoke(crate::method_resolution::CrateImplBlocks::impls_in_crate_query)]
50 fn impls_in_crate(&self, krate: CrateId) -> Arc<CrateImplBlocks>;
51
52 #[salsa::invoke(crate::traits::impls_for_trait_query)]
53 fn impls_for_trait(&self, krate: CrateId, trait_: TraitId) -> Arc<[ImplId]>;
54
55 /// This provides the Chalk trait solver instance. Because Chalk always
56 /// works from a specific crate, this query is keyed on the crate; and
57 /// because Chalk does its own internal caching, the solver is wrapped in a
58 /// Mutex and the query does an untracked read internally, to make sure the
59 /// cached state is thrown away when input facts change.
60 #[salsa::invoke(crate::traits::trait_solver_query)]
61 fn trait_solver(&self, krate: CrateId) -> crate::traits::TraitSolver;
62
63 // Interned IDs for Chalk integration
64 #[salsa::interned]
65 fn intern_type_ctor(&self, type_ctor: TypeCtor) -> crate::TypeCtorId;
66 #[salsa::interned]
67 fn intern_chalk_impl(&self, impl_: Impl) -> crate::traits::GlobalImplId;
68 #[salsa::interned]
69 fn intern_assoc_ty_value(&self, assoc_ty_value: AssocTyValue) -> crate::traits::AssocTyValueId;
70
71 #[salsa::invoke(crate::traits::chalk::associated_ty_data_query)]
72 fn associated_ty_data(
73 &self,
74 id: chalk_ir::TypeId,
75 ) -> Arc<chalk_rust_ir::AssociatedTyDatum<chalk_ir::family::ChalkIr>>;
76
77 #[salsa::invoke(crate::traits::chalk::trait_datum_query)]
78 fn trait_datum(
79 &self,
80 krate: CrateId,
81 trait_id: chalk_ir::TraitId,
82 ) -> Arc<chalk_rust_ir::TraitDatum<chalk_ir::family::ChalkIr>>;
83
84 #[salsa::invoke(crate::traits::chalk::struct_datum_query)]
85 fn struct_datum(
86 &self,
87 krate: CrateId,
88 struct_id: chalk_ir::StructId,
89 ) -> Arc<chalk_rust_ir::StructDatum<chalk_ir::family::ChalkIr>>;
90
91 #[salsa::invoke(crate::traits::chalk::impl_datum_query)]
92 fn impl_datum(
93 &self,
94 krate: CrateId,
95 impl_id: chalk_ir::ImplId,
96 ) -> Arc<chalk_rust_ir::ImplDatum<chalk_ir::family::ChalkIr>>;
97
98 #[salsa::invoke(crate::traits::chalk::associated_ty_value_query)]
99 fn associated_ty_value(
100 &self,
101 krate: CrateId,
102 id: chalk_rust_ir::AssociatedTyValueId,
103 ) -> Arc<chalk_rust_ir::AssociatedTyValue<chalk_ir::family::ChalkIr>>;
104
105 #[salsa::invoke(crate::traits::trait_solve_query)]
106 fn trait_solve(
107 &self,
108 krate: CrateId,
109 goal: crate::Canonical<crate::InEnvironment<crate::Obligation>>,
110 ) -> Option<crate::traits::Solution>;
111}
112
113#[test]
114fn hir_database_is_object_safe() {
115 fn _assert_object_safe(_: &dyn HirDatabase) {}
116}
diff --git a/crates/ra_hir_ty/src/diagnostics.rs b/crates/ra_hir_ty/src/diagnostics.rs
new file mode 100644
index 000000000..4a13fac23
--- /dev/null
+++ b/crates/ra_hir_ty/src/diagnostics.rs
@@ -0,0 +1,91 @@
1//! FIXME: write short doc here
2
3use std::any::Any;
4
5use hir_expand::{db::AstDatabase, name::Name, HirFileId, Source};
6use ra_syntax::{ast, AstNode, AstPtr, SyntaxNodePtr};
7
8pub use hir_def::diagnostics::UnresolvedModule;
9pub use hir_expand::diagnostics::{AstDiagnostic, Diagnostic, DiagnosticSink};
10
11#[derive(Debug)]
12pub struct NoSuchField {
13 pub file: HirFileId,
14 pub field: AstPtr<ast::RecordField>,
15}
16
17impl Diagnostic for NoSuchField {
18 fn message(&self) -> String {
19 "no such field".to_string()
20 }
21
22 fn source(&self) -> Source<SyntaxNodePtr> {
23 Source { file_id: self.file, value: self.field.into() }
24 }
25
26 fn as_any(&self) -> &(dyn Any + Send + 'static) {
27 self
28 }
29}
30
31#[derive(Debug)]
32pub struct MissingFields {
33 pub file: HirFileId,
34 pub field_list: AstPtr<ast::RecordFieldList>,
35 pub missed_fields: Vec<Name>,
36}
37
38impl Diagnostic for MissingFields {
39 fn message(&self) -> String {
40 use std::fmt::Write;
41 let mut message = String::from("Missing structure fields:\n");
42 for field in &self.missed_fields {
43 write!(message, "- {}\n", field).unwrap();
44 }
45 message
46 }
47 fn source(&self) -> Source<SyntaxNodePtr> {
48 Source { file_id: self.file, value: self.field_list.into() }
49 }
50 fn as_any(&self) -> &(dyn Any + Send + 'static) {
51 self
52 }
53}
54
55impl AstDiagnostic for MissingFields {
56 type AST = ast::RecordFieldList;
57
58 fn ast(&self, db: &impl AstDatabase) -> Self::AST {
59 let root = db.parse_or_expand(self.source().file_id).unwrap();
60 let node = self.source().value.to_node(&root);
61 ast::RecordFieldList::cast(node).unwrap()
62 }
63}
64
65#[derive(Debug)]
66pub struct MissingOkInTailExpr {
67 pub file: HirFileId,
68 pub expr: AstPtr<ast::Expr>,
69}
70
71impl Diagnostic for MissingOkInTailExpr {
72 fn message(&self) -> String {
73 "wrap return expression in Ok".to_string()
74 }
75 fn source(&self) -> Source<SyntaxNodePtr> {
76 Source { file_id: self.file, value: self.expr.into() }
77 }
78 fn as_any(&self) -> &(dyn Any + Send + 'static) {
79 self
80 }
81}
82
83impl AstDiagnostic for MissingOkInTailExpr {
84 type AST = ast::Expr;
85
86 fn ast(&self, db: &impl AstDatabase) -> Self::AST {
87 let root = db.parse_or_expand(self.file).unwrap();
88 let node = self.source().value.to_node(&root);
89 ast::Expr::cast(node).unwrap()
90 }
91}
diff --git a/crates/ra_hir/src/ty/display.rs b/crates/ra_hir_ty/src/display.rs
index 9bb3ece6c..9bb3ece6c 100644
--- a/crates/ra_hir/src/ty/display.rs
+++ b/crates/ra_hir_ty/src/display.rs
diff --git a/crates/ra_hir/src/expr.rs b/crates/ra_hir_ty/src/expr.rs
index 5c82c23d6..5c65f9370 100644
--- a/crates/ra_hir/src/expr.rs
+++ b/crates/ra_hir_ty/src/expr.rs
@@ -2,8 +2,12 @@
2 2
3use std::sync::Arc; 3use std::sync::Arc;
4 4
5use hir_def::{path::known, resolver::HasResolver, AdtId}; 5use hir_def::{
6use hir_expand::diagnostics::DiagnosticSink; 6 path::{known, Path},
7 resolver::HasResolver,
8 AdtId, FunctionId,
9};
10use hir_expand::{diagnostics::DiagnosticSink, name::Name};
7use ra_syntax::ast; 11use ra_syntax::ast;
8use ra_syntax::AstPtr; 12use ra_syntax::AstPtr;
9use rustc_hash::FxHashSet; 13use rustc_hash::FxHashSet;
@@ -11,8 +15,7 @@ use rustc_hash::FxHashSet;
11use crate::{ 15use crate::{
12 db::HirDatabase, 16 db::HirDatabase,
13 diagnostics::{MissingFields, MissingOkInTailExpr}, 17 diagnostics::{MissingFields, MissingOkInTailExpr},
14 ty::{ApplicationTy, InferenceResult, Ty, TypeCtor}, 18 ApplicationTy, InferenceResult, Ty, TypeCtor,
15 Function, Name, Path, Struct,
16}; 19};
17 20
18pub use hir_def::{ 21pub use hir_def::{
@@ -26,23 +29,23 @@ pub use hir_def::{
26 }, 29 },
27}; 30};
28 31
29pub(crate) struct ExprValidator<'a, 'b: 'a> { 32pub struct ExprValidator<'a, 'b: 'a> {
30 func: Function, 33 func: FunctionId,
31 infer: Arc<InferenceResult>, 34 infer: Arc<InferenceResult>,
32 sink: &'a mut DiagnosticSink<'b>, 35 sink: &'a mut DiagnosticSink<'b>,
33} 36}
34 37
35impl<'a, 'b> ExprValidator<'a, 'b> { 38impl<'a, 'b> ExprValidator<'a, 'b> {
36 pub(crate) fn new( 39 pub fn new(
37 func: Function, 40 func: FunctionId,
38 infer: Arc<InferenceResult>, 41 infer: Arc<InferenceResult>,
39 sink: &'a mut DiagnosticSink<'b>, 42 sink: &'a mut DiagnosticSink<'b>,
40 ) -> ExprValidator<'a, 'b> { 43 ) -> ExprValidator<'a, 'b> {
41 ExprValidator { func, infer, sink } 44 ExprValidator { func, infer, sink }
42 } 45 }
43 46
44 pub(crate) fn validate_body(&mut self, db: &impl HirDatabase) { 47 pub fn validate_body(&mut self, db: &impl HirDatabase) {
45 let body = self.func.body(db); 48 let body = db.body(self.func.into());
46 49
47 for e in body.exprs.iter() { 50 for e in body.exprs.iter() {
48 if let (id, Expr::RecordLit { path, fields, spread }) = e { 51 if let (id, Expr::RecordLit { path, fields, spread }) = e {
@@ -69,16 +72,18 @@ impl<'a, 'b> ExprValidator<'a, 'b> {
69 } 72 }
70 73
71 let struct_def = match self.infer[id].as_adt() { 74 let struct_def = match self.infer[id].as_adt() {
72 Some((AdtId::StructId(s), _)) => Struct::from(s), 75 Some((AdtId::StructId(s), _)) => s,
73 _ => return, 76 _ => return,
74 }; 77 };
78 let struct_data = db.struct_data(struct_def);
75 79
76 let lit_fields: FxHashSet<_> = fields.iter().map(|f| &f.name).collect(); 80 let lit_fields: FxHashSet<_> = fields.iter().map(|f| &f.name).collect();
77 let missed_fields: Vec<Name> = struct_def 81 let missed_fields: Vec<Name> = struct_data
78 .fields(db) 82 .variant_data
83 .fields()
79 .iter() 84 .iter()
80 .filter_map(|f| { 85 .filter_map(|(_f, d)| {
81 let name = f.name(db); 86 let name = d.name.clone();
82 if lit_fields.contains(&name) { 87 if lit_fields.contains(&name) {
83 None 88 None
84 } else { 89 } else {
@@ -89,7 +94,7 @@ impl<'a, 'b> ExprValidator<'a, 'b> {
89 if missed_fields.is_empty() { 94 if missed_fields.is_empty() {
90 return; 95 return;
91 } 96 }
92 let source_map = self.func.body_source_map(db); 97 let (_, source_map) = db.body_with_source_map(self.func.into());
93 98
94 if let Some(source_ptr) = source_map.expr_syntax(id) { 99 if let Some(source_ptr) = source_map.expr_syntax(id) {
95 if let Some(expr) = source_ptr.value.a() { 100 if let Some(expr) = source_ptr.value.a() {
@@ -121,7 +126,7 @@ impl<'a, 'b> ExprValidator<'a, 'b> {
121 126
122 let std_result_path = known::std_result_result(); 127 let std_result_path = known::std_result_result();
123 128
124 let resolver = self.func.id.resolver(db); 129 let resolver = self.func.resolver(db);
125 let std_result_enum = match resolver.resolve_known_enum(db, &std_result_path) { 130 let std_result_enum = match resolver.resolve_known_enum(db, &std_result_path) {
126 Some(it) => it, 131 Some(it) => it,
127 _ => return, 132 _ => return,
@@ -134,7 +139,7 @@ impl<'a, 'b> ExprValidator<'a, 'b> {
134 }; 139 };
135 140
136 if params.len() == 2 && &params[0] == &mismatch.actual { 141 if params.len() == 2 && &params[0] == &mismatch.actual {
137 let source_map = self.func.body_source_map(db); 142 let (_, source_map) = db.body_with_source_map(self.func.into());
138 143
139 if let Some(source_ptr) = source_map.expr_syntax(id) { 144 if let Some(source_ptr) = source_map.expr_syntax(id) {
140 if let Some(expr) = source_ptr.value.a() { 145 if let Some(expr) = source_ptr.value.a() {
diff --git a/crates/ra_hir/src/ty/infer.rs b/crates/ra_hir_ty/src/infer.rs
index 59e4e5f36..1e9f4b208 100644
--- a/crates/ra_hir/src/ty/infer.rs
+++ b/crates/ra_hir_ty/src/infer.rs
@@ -41,11 +41,11 @@ use super::{
41 ApplicationTy, InEnvironment, ProjectionTy, Substs, TraitEnvironment, TraitRef, Ty, TypeCtor, 41 ApplicationTy, InEnvironment, ProjectionTy, Substs, TraitEnvironment, TraitRef, Ty, TypeCtor,
42 TypeWalk, Uncertain, 42 TypeWalk, Uncertain,
43}; 43};
44use crate::{db::HirDatabase, ty::infer::diagnostics::InferenceDiagnostic}; 44use crate::{db::HirDatabase, infer::diagnostics::InferenceDiagnostic};
45 45
46macro_rules! ty_app { 46macro_rules! ty_app {
47 ($ctor:pat, $param:pat) => { 47 ($ctor:pat, $param:pat) => {
48 crate::ty::Ty::Apply(crate::ty::ApplicationTy { ctor: $ctor, parameters: $param }) 48 crate::Ty::Apply(crate::ApplicationTy { ctor: $ctor, parameters: $param })
49 }; 49 };
50 ($ctor:pat) => { 50 ($ctor:pat) => {
51 ty_app!($ctor, _) 51 ty_app!($ctor, _)
@@ -128,8 +128,8 @@ pub struct InferenceResult {
128 /// For each associated item record what it resolves to 128 /// For each associated item record what it resolves to
129 assoc_resolutions: FxHashMap<ExprOrPatId, AssocItemId>, 129 assoc_resolutions: FxHashMap<ExprOrPatId, AssocItemId>,
130 diagnostics: Vec<InferenceDiagnostic>, 130 diagnostics: Vec<InferenceDiagnostic>,
131 pub(super) type_of_expr: ArenaMap<ExprId, Ty>, 131 pub type_of_expr: ArenaMap<ExprId, Ty>,
132 pub(super) type_of_pat: ArenaMap<PatId, Ty>, 132 pub type_of_pat: ArenaMap<PatId, Ty>,
133 pub(super) type_mismatches: ArenaMap<ExprId, TypeMismatch>, 133 pub(super) type_mismatches: ArenaMap<ExprId, TypeMismatch>,
134} 134}
135 135
@@ -158,7 +158,7 @@ impl InferenceResult {
158 pub fn type_mismatch_for_expr(&self, expr: ExprId) -> Option<&TypeMismatch> { 158 pub fn type_mismatch_for_expr(&self, expr: ExprId) -> Option<&TypeMismatch> {
159 self.type_mismatches.get(expr) 159 self.type_mismatches.get(expr)
160 } 160 }
161 pub(crate) fn add_diagnostics( 161 pub fn add_diagnostics(
162 &self, 162 &self,
163 db: &impl HirDatabase, 163 db: &impl HirDatabase,
164 owner: FunctionId, 164 owner: FunctionId,
diff --git a/crates/ra_hir/src/ty/infer/coerce.rs b/crates/ra_hir_ty/src/infer/coerce.rs
index 3fb5d8a83..d66a21932 100644
--- a/crates/ra_hir/src/ty/infer/coerce.rs
+++ b/crates/ra_hir_ty/src/infer/coerce.rs
@@ -13,10 +13,7 @@ use hir_def::{
13use rustc_hash::FxHashMap; 13use rustc_hash::FxHashMap;
14use test_utils::tested_by; 14use test_utils::tested_by;
15 15
16use crate::{ 16use crate::{autoderef, db::HirDatabase, Substs, TraitRef, Ty, TypeCtor, TypeWalk};
17 db::HirDatabase,
18 ty::{autoderef, Substs, TraitRef, Ty, TypeCtor, TypeWalk},
19};
20 17
21use super::{InEnvironment, InferTy, InferenceContext, TypeVarValue}; 18use super::{InEnvironment, InferTy, InferenceContext, TypeVarValue};
22 19
diff --git a/crates/ra_hir/src/ty/infer/expr.rs b/crates/ra_hir_ty/src/infer/expr.rs
index f9ededa23..2f9ca4bbb 100644
--- a/crates/ra_hir/src/ty/infer/expr.rs
+++ b/crates/ra_hir_ty/src/infer/expr.rs
@@ -14,12 +14,9 @@ use hir_def::{
14use hir_expand::name::{self, Name}; 14use hir_expand::name::{self, Name};
15 15
16use crate::{ 16use crate::{
17 db::HirDatabase, 17 autoderef, db::HirDatabase, method_resolution, op, traits::InEnvironment, utils::variant_data,
18 ty::{ 18 CallableDef, InferTy, IntTy, Mutability, Obligation, ProjectionPredicate, ProjectionTy, Substs,
19 autoderef, method_resolution, op, traits::InEnvironment, utils::variant_data, CallableDef, 19 TraitRef, Ty, TypeCtor, TypeWalk, Uncertain,
20 InferTy, IntTy, Mutability, Obligation, ProjectionPredicate, ProjectionTy, Substs,
21 TraitRef, Ty, TypeCtor, TypeWalk, Uncertain,
22 },
23}; 20};
24 21
25use super::{BindingMode, Expectation, InferenceContext, InferenceDiagnostic, TypeMismatch}; 22use super::{BindingMode, Expectation, InferenceContext, InferenceDiagnostic, TypeMismatch};
diff --git a/crates/ra_hir/src/ty/infer/pat.rs b/crates/ra_hir_ty/src/infer/pat.rs
index a14774607..1ebb36239 100644
--- a/crates/ra_hir/src/ty/infer/pat.rs
+++ b/crates/ra_hir_ty/src/infer/pat.rs
@@ -12,10 +12,7 @@ use hir_expand::name::Name;
12use test_utils::tested_by; 12use test_utils::tested_by;
13 13
14use super::{BindingMode, InferenceContext}; 14use super::{BindingMode, InferenceContext};
15use crate::{ 15use crate::{db::HirDatabase, utils::variant_data, Substs, Ty, TypeCtor, TypeWalk};
16 db::HirDatabase,
17 ty::{utils::variant_data, Substs, Ty, TypeCtor, TypeWalk},
18};
19 16
20impl<'a, D: HirDatabase> InferenceContext<'a, D> { 17impl<'a, D: HirDatabase> InferenceContext<'a, D> {
21 fn infer_tuple_struct_pat( 18 fn infer_tuple_struct_pat(
diff --git a/crates/ra_hir/src/ty/infer/path.rs b/crates/ra_hir_ty/src/infer/path.rs
index 09ff79728..e6676e1aa 100644
--- a/crates/ra_hir/src/ty/infer/path.rs
+++ b/crates/ra_hir_ty/src/infer/path.rs
@@ -1,16 +1,13 @@
1//! Path expression resolution. 1//! Path expression resolution.
2 2
3use hir_def::{ 3use hir_def::{
4 path::{Path, PathSegment}, 4 path::{Path, PathKind, PathSegment},
5 resolver::{HasResolver, ResolveValueResult, Resolver, TypeNs, ValueNs}, 5 resolver::{HasResolver, ResolveValueResult, Resolver, TypeNs, ValueNs},
6 AssocItemId, ContainerId, Lookup, 6 AssocItemId, ContainerId, Lookup,
7}; 7};
8use hir_expand::name::Name; 8use hir_expand::name::Name;
9 9
10use crate::{ 10use crate::{db::HirDatabase, method_resolution, Substs, Ty, TypeWalk, ValueTyDefId};
11 db::HirDatabase,
12 ty::{method_resolution, Substs, Ty, TypeWalk, ValueTyDefId},
13};
14 11
15use super::{ExprOrPatId, InferenceContext, TraitRef}; 12use super::{ExprOrPatId, InferenceContext, TraitRef};
16 13
@@ -33,7 +30,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> {
33 path: &Path, 30 path: &Path,
34 id: ExprOrPatId, 31 id: ExprOrPatId,
35 ) -> Option<Ty> { 32 ) -> Option<Ty> {
36 let (value, self_subst) = if let crate::PathKind::Type(type_ref) = &path.kind { 33 let (value, self_subst) = if let PathKind::Type(type_ref) = &path.kind {
37 if path.segments.is_empty() { 34 if path.segments.is_empty() {
38 // This can't actually happen syntax-wise 35 // This can't actually happen syntax-wise
39 return None; 36 return None;
diff --git a/crates/ra_hir/src/ty/infer/unify.rs b/crates/ra_hir_ty/src/infer/unify.rs
index e27bb2f82..f3a875678 100644
--- a/crates/ra_hir/src/ty/infer/unify.rs
+++ b/crates/ra_hir_ty/src/infer/unify.rs
@@ -2,12 +2,8 @@
2 2
3use super::{InferenceContext, Obligation}; 3use super::{InferenceContext, Obligation};
4use crate::{ 4use crate::{
5 db::HirDatabase, 5 db::HirDatabase, utils::make_mut_slice, Canonical, InEnvironment, InferTy, ProjectionPredicate,
6 ty::{ 6 ProjectionTy, Substs, TraitRef, Ty, TypeWalk,
7 Canonical, InEnvironment, InferTy, ProjectionPredicate, ProjectionTy, Substs, TraitRef, Ty,
8 TypeWalk,
9 },
10 util::make_mut_slice,
11}; 7};
12 8
13impl<'a, D: HirDatabase> InferenceContext<'a, D> { 9impl<'a, D: HirDatabase> InferenceContext<'a, D> {
diff --git a/crates/ra_hir_ty/src/lib.rs b/crates/ra_hir_ty/src/lib.rs
index 28859ba63..f25846326 100644
--- a/crates/ra_hir_ty/src/lib.rs
+++ b/crates/ra_hir_ty/src/lib.rs
@@ -1,4 +1,1134 @@
1//! Work in Progress: everything related to types, type inference and trait 1//! The type system. We currently use this to infer types for completion, hover
2//! solving. 2//! information and various assists.
3 3
4macro_rules! impl_froms {
5 ($e:ident: $($v:ident $(($($sv:ident),*))?),*) => {
6 $(
7 impl From<$v> for $e {
8 fn from(it: $v) -> $e {
9 $e::$v(it)
10 }
11 }
12 $($(
13 impl From<$sv> for $e {
14 fn from(it: $sv) -> $e {
15 $e::$v($v::$sv(it))
16 }
17 }
18 )*)?
19 )*
20 }
21}
22
23mod autoderef;
4pub mod primitive; 24pub mod primitive;
25pub mod traits;
26pub mod method_resolution;
27mod op;
28mod lower;
29mod infer;
30pub mod display;
31pub(crate) mod utils;
32pub mod db;
33pub mod diagnostics;
34pub mod expr;
35
36#[cfg(test)]
37mod tests;
38#[cfg(test)]
39mod test_db;
40mod marks;
41
42use std::ops::Deref;
43use std::sync::Arc;
44use std::{fmt, iter, mem};
45
46use hir_def::{
47 expr::ExprId, generics::GenericParams, type_ref::Mutability, AdtId, ContainerId, DefWithBodyId,
48 GenericDefId, HasModule, Lookup, TraitId, TypeAliasId,
49};
50use hir_expand::name::Name;
51use ra_db::{impl_intern_key, salsa, CrateId};
52
53use crate::{
54 db::HirDatabase,
55 primitive::{FloatTy, IntTy, Uncertain},
56 utils::make_mut_slice,
57};
58use display::{HirDisplay, HirFormatter};
59
60pub use autoderef::autoderef;
61pub use infer::{infer_query, InferTy, InferenceResult};
62pub use lower::CallableDef;
63pub use lower::{callable_item_sig, TyDefId, ValueTyDefId};
64pub use traits::{InEnvironment, Obligation, ProjectionPredicate, TraitEnvironment};
65
66/// A type constructor or type name: this might be something like the primitive
67/// type `bool`, a struct like `Vec`, or things like function pointers or
68/// tuples.
69#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
70pub enum TypeCtor {
71 /// The primitive boolean type. Written as `bool`.
72 Bool,
73
74 /// The primitive character type; holds a Unicode scalar value
75 /// (a non-surrogate code point). Written as `char`.
76 Char,
77
78 /// A primitive integer type. For example, `i32`.
79 Int(Uncertain<IntTy>),
80
81 /// A primitive floating-point type. For example, `f64`.
82 Float(Uncertain<FloatTy>),
83
84 /// Structures, enumerations and unions.
85 Adt(AdtId),
86
87 /// The pointee of a string slice. Written as `str`.
88 Str,
89
90 /// The pointee of an array slice. Written as `[T]`.
91 Slice,
92
93 /// An array with the given length. Written as `[T; n]`.
94 Array,
95
96 /// A raw pointer. Written as `*mut T` or `*const T`
97 RawPtr(Mutability),
98
99 /// A reference; a pointer with an associated lifetime. Written as
100 /// `&'a mut T` or `&'a T`.
101 Ref(Mutability),
102
103 /// The anonymous type of a function declaration/definition. Each
104 /// function has a unique type, which is output (for a function
105 /// named `foo` returning an `i32`) as `fn() -> i32 {foo}`.
106 ///
107 /// This includes tuple struct / enum variant constructors as well.
108 ///
109 /// For example the type of `bar` here:
110 ///
111 /// ```
112 /// fn foo() -> i32 { 1 }
113 /// let bar = foo; // bar: fn() -> i32 {foo}
114 /// ```
115 FnDef(CallableDef),
116
117 /// A pointer to a function. Written as `fn() -> i32`.
118 ///
119 /// For example the type of `bar` here:
120 ///
121 /// ```
122 /// fn foo() -> i32 { 1 }
123 /// let bar: fn() -> i32 = foo;
124 /// ```
125 FnPtr { num_args: u16 },
126
127 /// The never type `!`.
128 Never,
129
130 /// A tuple type. For example, `(i32, bool)`.
131 Tuple { cardinality: u16 },
132
133 /// Represents an associated item like `Iterator::Item`. This is used
134 /// when we have tried to normalize a projection like `T::Item` but
135 /// couldn't find a better representation. In that case, we generate
136 /// an **application type** like `(Iterator::Item)<T>`.
137 AssociatedType(TypeAliasId),
138
139 /// The type of a specific closure.
140 ///
141 /// The closure signature is stored in a `FnPtr` type in the first type
142 /// parameter.
143 Closure { def: DefWithBodyId, expr: ExprId },
144}
145
146/// This exists just for Chalk, because Chalk just has a single `StructId` where
147/// we have different kinds of ADTs, primitive types and special type
148/// constructors like tuples and function pointers.
149#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
150pub struct TypeCtorId(salsa::InternId);
151impl_intern_key!(TypeCtorId);
152
153impl TypeCtor {
154 pub fn num_ty_params(self, db: &impl HirDatabase) -> usize {
155 match self {
156 TypeCtor::Bool
157 | TypeCtor::Char
158 | TypeCtor::Int(_)
159 | TypeCtor::Float(_)
160 | TypeCtor::Str
161 | TypeCtor::Never => 0,
162 TypeCtor::Slice
163 | TypeCtor::Array
164 | TypeCtor::RawPtr(_)
165 | TypeCtor::Ref(_)
166 | TypeCtor::Closure { .. } // 1 param representing the signature of the closure
167 => 1,
168 TypeCtor::Adt(adt) => {
169 let generic_params = db.generic_params(AdtId::from(adt).into());
170 generic_params.count_params_including_parent()
171 }
172 TypeCtor::FnDef(callable) => {
173 let generic_params = db.generic_params(callable.into());
174 generic_params.count_params_including_parent()
175 }
176 TypeCtor::AssociatedType(type_alias) => {
177 let generic_params = db.generic_params(type_alias.into());
178 generic_params.count_params_including_parent()
179 }
180 TypeCtor::FnPtr { num_args } => num_args as usize + 1,
181 TypeCtor::Tuple { cardinality } => cardinality as usize,
182 }
183 }
184
185 pub fn krate(self, db: &impl HirDatabase) -> Option<CrateId> {
186 match self {
187 TypeCtor::Bool
188 | TypeCtor::Char
189 | TypeCtor::Int(_)
190 | TypeCtor::Float(_)
191 | TypeCtor::Str
192 | TypeCtor::Never
193 | TypeCtor::Slice
194 | TypeCtor::Array
195 | TypeCtor::RawPtr(_)
196 | TypeCtor::Ref(_)
197 | TypeCtor::FnPtr { .. }
198 | TypeCtor::Tuple { .. } => None,
199 // Closure's krate is irrelevant for coherence I would think?
200 TypeCtor::Closure { .. } => None,
201 TypeCtor::Adt(adt) => Some(adt.module(db).krate),
202 TypeCtor::FnDef(callable) => Some(callable.krate(db)),
203 TypeCtor::AssociatedType(type_alias) => Some(type_alias.lookup(db).module(db).krate),
204 }
205 }
206
207 pub fn as_generic_def(self) -> Option<GenericDefId> {
208 match self {
209 TypeCtor::Bool
210 | TypeCtor::Char
211 | TypeCtor::Int(_)
212 | TypeCtor::Float(_)
213 | TypeCtor::Str
214 | TypeCtor::Never
215 | TypeCtor::Slice
216 | TypeCtor::Array
217 | TypeCtor::RawPtr(_)
218 | TypeCtor::Ref(_)
219 | TypeCtor::FnPtr { .. }
220 | TypeCtor::Tuple { .. }
221 | TypeCtor::Closure { .. } => None,
222 TypeCtor::Adt(adt) => Some(adt.into()),
223 TypeCtor::FnDef(callable) => Some(callable.into()),
224 TypeCtor::AssociatedType(type_alias) => Some(type_alias.into()),
225 }
226 }
227}
228
229/// A nominal type with (maybe 0) type parameters. This might be a primitive
230/// type like `bool`, a struct, tuple, function pointer, reference or
231/// several other things.
232#[derive(Clone, PartialEq, Eq, Debug, Hash)]
233pub struct ApplicationTy {
234 pub ctor: TypeCtor,
235 pub parameters: Substs,
236}
237
238/// A "projection" type corresponds to an (unnormalized)
239/// projection like `<P0 as Trait<P1..Pn>>::Foo`. Note that the
240/// trait and all its parameters are fully known.
241#[derive(Clone, PartialEq, Eq, Debug, Hash)]
242pub struct ProjectionTy {
243 pub associated_ty: TypeAliasId,
244 pub parameters: Substs,
245}
246
247impl ProjectionTy {
248 pub fn trait_ref(&self, db: &impl HirDatabase) -> TraitRef {
249 TraitRef { trait_: self.trait_(db).into(), substs: self.parameters.clone() }
250 }
251
252 fn trait_(&self, db: &impl HirDatabase) -> TraitId {
253 match self.associated_ty.lookup(db).container {
254 ContainerId::TraitId(it) => it,
255 _ => panic!("projection ty without parent trait"),
256 }
257 }
258}
259
260impl TypeWalk for ProjectionTy {
261 fn walk(&self, f: &mut impl FnMut(&Ty)) {
262 self.parameters.walk(f);
263 }
264
265 fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) {
266 self.parameters.walk_mut_binders(f, binders);
267 }
268}
269
270/// A type.
271///
272/// See also the `TyKind` enum in rustc (librustc/ty/sty.rs), which represents
273/// the same thing (but in a different way).
274///
275/// This should be cheap to clone.
276#[derive(Clone, PartialEq, Eq, Debug, Hash)]
277pub enum Ty {
278 /// A nominal type with (maybe 0) type parameters. This might be a primitive
279 /// type like `bool`, a struct, tuple, function pointer, reference or
280 /// several other things.
281 Apply(ApplicationTy),
282
283 /// A "projection" type corresponds to an (unnormalized)
284 /// projection like `<P0 as Trait<P1..Pn>>::Foo`. Note that the
285 /// trait and all its parameters are fully known.
286 Projection(ProjectionTy),
287
288 /// A type parameter; for example, `T` in `fn f<T>(x: T) {}
289 Param {
290 /// The index of the parameter (starting with parameters from the
291 /// surrounding impl, then the current function).
292 idx: u32,
293 /// The name of the parameter, for displaying.
294 // FIXME get rid of this
295 name: Name,
296 },
297
298 /// A bound type variable. Used during trait resolution to represent Chalk
299 /// variables, and in `Dyn` and `Opaque` bounds to represent the `Self` type.
300 Bound(u32),
301
302 /// A type variable used during type checking. Not to be confused with a
303 /// type parameter.
304 Infer(InferTy),
305
306 /// A trait object (`dyn Trait` or bare `Trait` in pre-2018 Rust).
307 ///
308 /// The predicates are quantified over the `Self` type, i.e. `Ty::Bound(0)`
309 /// represents the `Self` type inside the bounds. This is currently
310 /// implicit; Chalk has the `Binders` struct to make it explicit, but it
311 /// didn't seem worth the overhead yet.
312 Dyn(Arc<[GenericPredicate]>),
313
314 /// An opaque type (`impl Trait`).
315 ///
316 /// The predicates are quantified over the `Self` type; see `Ty::Dyn` for
317 /// more.
318 Opaque(Arc<[GenericPredicate]>),
319
320 /// A placeholder for a type which could not be computed; this is propagated
321 /// to avoid useless error messages. Doubles as a placeholder where type
322 /// variables are inserted before type checking, since we want to try to
323 /// infer a better type here anyway -- for the IDE use case, we want to try
324 /// to infer as much as possible even in the presence of type errors.
325 Unknown,
326}
327
328/// A list of substitutions for generic parameters.
329#[derive(Clone, PartialEq, Eq, Debug, Hash)]
330pub struct Substs(Arc<[Ty]>);
331
332impl TypeWalk for Substs {
333 fn walk(&self, f: &mut impl FnMut(&Ty)) {
334 for t in self.0.iter() {
335 t.walk(f);
336 }
337 }
338
339 fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) {
340 for t in make_mut_slice(&mut self.0) {
341 t.walk_mut_binders(f, binders);
342 }
343 }
344}
345
346impl Substs {
347 pub fn empty() -> Substs {
348 Substs(Arc::new([]))
349 }
350
351 pub fn single(ty: Ty) -> Substs {
352 Substs(Arc::new([ty]))
353 }
354
355 pub fn prefix(&self, n: usize) -> Substs {
356 Substs(self.0[..std::cmp::min(self.0.len(), n)].into())
357 }
358
359 pub fn as_single(&self) -> &Ty {
360 if self.0.len() != 1 {
361 panic!("expected substs of len 1, got {:?}", self);
362 }
363 &self.0[0]
364 }
365
366 /// Return Substs that replace each parameter by itself (i.e. `Ty::Param`).
367 pub fn identity(generic_params: &GenericParams) -> Substs {
368 Substs(
369 generic_params
370 .params_including_parent()
371 .into_iter()
372 .map(|p| Ty::Param { idx: p.idx, name: p.name.clone() })
373 .collect(),
374 )
375 }
376
377 /// Return Substs that replace each parameter by a bound variable.
378 pub fn bound_vars(generic_params: &GenericParams) -> Substs {
379 Substs(
380 generic_params
381 .params_including_parent()
382 .into_iter()
383 .map(|p| Ty::Bound(p.idx))
384 .collect(),
385 )
386 }
387
388 pub fn build_for_def(db: &impl HirDatabase, def: impl Into<GenericDefId>) -> SubstsBuilder {
389 let def = def.into();
390 let params = db.generic_params(def);
391 let param_count = params.count_params_including_parent();
392 Substs::builder(param_count)
393 }
394
395 pub fn build_for_generics(generic_params: &GenericParams) -> SubstsBuilder {
396 Substs::builder(generic_params.count_params_including_parent())
397 }
398
399 pub fn build_for_type_ctor(db: &impl HirDatabase, type_ctor: TypeCtor) -> SubstsBuilder {
400 Substs::builder(type_ctor.num_ty_params(db))
401 }
402
403 fn builder(param_count: usize) -> SubstsBuilder {
404 SubstsBuilder { vec: Vec::with_capacity(param_count), param_count }
405 }
406}
407
408#[derive(Debug, Clone)]
409pub struct SubstsBuilder {
410 vec: Vec<Ty>,
411 param_count: usize,
412}
413
414impl SubstsBuilder {
415 pub fn build(self) -> Substs {
416 assert_eq!(self.vec.len(), self.param_count);
417 Substs(self.vec.into())
418 }
419
420 pub fn push(mut self, ty: Ty) -> Self {
421 self.vec.push(ty);
422 self
423 }
424
425 fn remaining(&self) -> usize {
426 self.param_count - self.vec.len()
427 }
428
429 pub fn fill_with_bound_vars(self, starting_from: u32) -> Self {
430 self.fill((starting_from..).map(Ty::Bound))
431 }
432
433 pub fn fill_with_params(self) -> Self {
434 let start = self.vec.len() as u32;
435 self.fill((start..).map(|idx| Ty::Param { idx, name: Name::missing() }))
436 }
437
438 pub fn fill_with_unknown(self) -> Self {
439 self.fill(iter::repeat(Ty::Unknown))
440 }
441
442 pub fn fill(mut self, filler: impl Iterator<Item = Ty>) -> Self {
443 self.vec.extend(filler.take(self.remaining()));
444 assert_eq!(self.remaining(), 0);
445 self
446 }
447
448 pub fn use_parent_substs(mut self, parent_substs: &Substs) -> Self {
449 assert!(self.vec.is_empty());
450 assert!(parent_substs.len() <= self.param_count);
451 self.vec.extend(parent_substs.iter().cloned());
452 self
453 }
454}
455
456impl Deref for Substs {
457 type Target = [Ty];
458
459 fn deref(&self) -> &[Ty] {
460 &self.0
461 }
462}
463
464/// A trait with type parameters. This includes the `Self`, so this represents a concrete type implementing the trait.
465/// Name to be bikeshedded: TraitBound? TraitImplements?
466#[derive(Clone, PartialEq, Eq, Debug, Hash)]
467pub struct TraitRef {
468 /// FIXME name?
469 pub trait_: TraitId,
470 pub substs: Substs,
471}
472
473impl TraitRef {
474 pub fn self_ty(&self) -> &Ty {
475 &self.substs[0]
476 }
477}
478
479impl TypeWalk for TraitRef {
480 fn walk(&self, f: &mut impl FnMut(&Ty)) {
481 self.substs.walk(f);
482 }
483
484 fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) {
485 self.substs.walk_mut_binders(f, binders);
486 }
487}
488
489/// Like `generics::WherePredicate`, but with resolved types: A condition on the
490/// parameters of a generic item.
491#[derive(Debug, Clone, PartialEq, Eq, Hash)]
492pub enum GenericPredicate {
493 /// The given trait needs to be implemented for its type parameters.
494 Implemented(TraitRef),
495 /// An associated type bindings like in `Iterator<Item = T>`.
496 Projection(ProjectionPredicate),
497 /// We couldn't resolve the trait reference. (If some type parameters can't
498 /// be resolved, they will just be Unknown).
499 Error,
500}
501
502impl GenericPredicate {
503 pub fn is_error(&self) -> bool {
504 match self {
505 GenericPredicate::Error => true,
506 _ => false,
507 }
508 }
509
510 pub fn is_implemented(&self) -> bool {
511 match self {
512 GenericPredicate::Implemented(_) => true,
513 _ => false,
514 }
515 }
516
517 pub fn trait_ref(&self, db: &impl HirDatabase) -> Option<TraitRef> {
518 match self {
519 GenericPredicate::Implemented(tr) => Some(tr.clone()),
520 GenericPredicate::Projection(proj) => Some(proj.projection_ty.trait_ref(db)),
521 GenericPredicate::Error => None,
522 }
523 }
524}
525
526impl TypeWalk for GenericPredicate {
527 fn walk(&self, f: &mut impl FnMut(&Ty)) {
528 match self {
529 GenericPredicate::Implemented(trait_ref) => trait_ref.walk(f),
530 GenericPredicate::Projection(projection_pred) => projection_pred.walk(f),
531 GenericPredicate::Error => {}
532 }
533 }
534
535 fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) {
536 match self {
537 GenericPredicate::Implemented(trait_ref) => trait_ref.walk_mut_binders(f, binders),
538 GenericPredicate::Projection(projection_pred) => {
539 projection_pred.walk_mut_binders(f, binders)
540 }
541 GenericPredicate::Error => {}
542 }
543 }
544}
545
546/// Basically a claim (currently not validated / checked) that the contained
547/// type / trait ref contains no inference variables; any inference variables it
548/// contained have been replaced by bound variables, and `num_vars` tells us how
549/// many there are. This is used to erase irrelevant differences between types
550/// before using them in queries.
551#[derive(Debug, Clone, PartialEq, Eq, Hash)]
552pub struct Canonical<T> {
553 pub value: T,
554 pub num_vars: usize,
555}
556
557/// A function signature as seen by type inference: Several parameter types and
558/// one return type.
559#[derive(Clone, PartialEq, Eq, Debug)]
560pub struct FnSig {
561 params_and_return: Arc<[Ty]>,
562}
563
564impl FnSig {
565 pub fn from_params_and_return(mut params: Vec<Ty>, ret: Ty) -> FnSig {
566 params.push(ret);
567 FnSig { params_and_return: params.into() }
568 }
569
570 pub fn from_fn_ptr_substs(substs: &Substs) -> FnSig {
571 FnSig { params_and_return: Arc::clone(&substs.0) }
572 }
573
574 pub fn params(&self) -> &[Ty] {
575 &self.params_and_return[0..self.params_and_return.len() - 1]
576 }
577
578 pub fn ret(&self) -> &Ty {
579 &self.params_and_return[self.params_and_return.len() - 1]
580 }
581}
582
583impl TypeWalk for FnSig {
584 fn walk(&self, f: &mut impl FnMut(&Ty)) {
585 for t in self.params_and_return.iter() {
586 t.walk(f);
587 }
588 }
589
590 fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) {
591 for t in make_mut_slice(&mut self.params_and_return) {
592 t.walk_mut_binders(f, binders);
593 }
594 }
595}
596
597impl Ty {
598 pub fn simple(ctor: TypeCtor) -> Ty {
599 Ty::Apply(ApplicationTy { ctor, parameters: Substs::empty() })
600 }
601 pub fn apply_one(ctor: TypeCtor, param: Ty) -> Ty {
602 Ty::Apply(ApplicationTy { ctor, parameters: Substs::single(param) })
603 }
604 pub fn apply(ctor: TypeCtor, parameters: Substs) -> Ty {
605 Ty::Apply(ApplicationTy { ctor, parameters })
606 }
607 pub fn unit() -> Self {
608 Ty::apply(TypeCtor::Tuple { cardinality: 0 }, Substs::empty())
609 }
610
611 pub fn as_reference(&self) -> Option<(&Ty, Mutability)> {
612 match self {
613 Ty::Apply(ApplicationTy { ctor: TypeCtor::Ref(mutability), parameters }) => {
614 Some((parameters.as_single(), *mutability))
615 }
616 _ => None,
617 }
618 }
619
620 pub fn as_adt(&self) -> Option<(AdtId, &Substs)> {
621 match self {
622 Ty::Apply(ApplicationTy { ctor: TypeCtor::Adt(adt_def), parameters }) => {
623 Some((*adt_def, parameters))
624 }
625 _ => None,
626 }
627 }
628
629 pub fn as_tuple(&self) -> Option<&Substs> {
630 match self {
631 Ty::Apply(ApplicationTy { ctor: TypeCtor::Tuple { .. }, parameters }) => {
632 Some(parameters)
633 }
634 _ => None,
635 }
636 }
637
638 pub fn as_callable(&self) -> Option<(CallableDef, &Substs)> {
639 match self {
640 Ty::Apply(ApplicationTy { ctor: TypeCtor::FnDef(callable_def), parameters }) => {
641 Some((*callable_def, parameters))
642 }
643 _ => None,
644 }
645 }
646
647 fn builtin_deref(&self) -> Option<Ty> {
648 match self {
649 Ty::Apply(a_ty) => match a_ty.ctor {
650 TypeCtor::Ref(..) => Some(Ty::clone(a_ty.parameters.as_single())),
651 TypeCtor::RawPtr(..) => Some(Ty::clone(a_ty.parameters.as_single())),
652 _ => None,
653 },
654 _ => None,
655 }
656 }
657
658 fn callable_sig(&self, db: &impl HirDatabase) -> Option<FnSig> {
659 match self {
660 Ty::Apply(a_ty) => match a_ty.ctor {
661 TypeCtor::FnPtr { .. } => Some(FnSig::from_fn_ptr_substs(&a_ty.parameters)),
662 TypeCtor::FnDef(def) => {
663 let sig = db.callable_item_signature(def);
664 Some(sig.subst(&a_ty.parameters))
665 }
666 TypeCtor::Closure { .. } => {
667 let sig_param = &a_ty.parameters[0];
668 sig_param.callable_sig(db)
669 }
670 _ => None,
671 },
672 _ => None,
673 }
674 }
675
676 /// If this is a type with type parameters (an ADT or function), replaces
677 /// the `Substs` for these type parameters with the given ones. (So e.g. if
678 /// `self` is `Option<_>` and the substs contain `u32`, we'll have
679 /// `Option<u32>` afterwards.)
680 pub fn apply_substs(self, substs: Substs) -> Ty {
681 match self {
682 Ty::Apply(ApplicationTy { ctor, parameters: previous_substs }) => {
683 assert_eq!(previous_substs.len(), substs.len());
684 Ty::Apply(ApplicationTy { ctor, parameters: substs })
685 }
686 _ => self,
687 }
688 }
689
690 /// Returns the type parameters of this type if it has some (i.e. is an ADT
691 /// or function); so if `self` is `Option<u32>`, this returns the `u32`.
692 pub fn substs(&self) -> Option<Substs> {
693 match self {
694 Ty::Apply(ApplicationTy { parameters, .. }) => Some(parameters.clone()),
695 _ => None,
696 }
697 }
698
699 /// If this is an `impl Trait` or `dyn Trait`, returns that trait.
700 pub fn inherent_trait(&self) -> Option<TraitId> {
701 match self {
702 Ty::Dyn(predicates) | Ty::Opaque(predicates) => {
703 predicates.iter().find_map(|pred| match pred {
704 GenericPredicate::Implemented(tr) => Some(tr.trait_),
705 _ => None,
706 })
707 }
708 _ => None,
709 }
710 }
711}
712
713/// This allows walking structures that contain types to do something with those
714/// types, similar to Chalk's `Fold` trait.
715pub trait TypeWalk {
716 fn walk(&self, f: &mut impl FnMut(&Ty));
717 fn walk_mut(&mut self, f: &mut impl FnMut(&mut Ty)) {
718 self.walk_mut_binders(&mut |ty, _binders| f(ty), 0);
719 }
720 /// Walk the type, counting entered binders.
721 ///
722 /// `Ty::Bound` variables use DeBruijn indexing, which means that 0 refers
723 /// to the innermost binder, 1 to the next, etc.. So when we want to
724 /// substitute a certain bound variable, we can't just walk the whole type
725 /// and blindly replace each instance of a certain index; when we 'enter'
726 /// things that introduce new bound variables, we have to keep track of
727 /// that. Currently, the only thing that introduces bound variables on our
728 /// side are `Ty::Dyn` and `Ty::Opaque`, which each introduce a bound
729 /// variable for the self type.
730 fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize);
731
732 fn fold(mut self, f: &mut impl FnMut(Ty) -> Ty) -> Self
733 where
734 Self: Sized,
735 {
736 self.walk_mut(&mut |ty_mut| {
737 let ty = mem::replace(ty_mut, Ty::Unknown);
738 *ty_mut = f(ty);
739 });
740 self
741 }
742
743 /// Replaces type parameters in this type using the given `Substs`. (So e.g.
744 /// if `self` is `&[T]`, where type parameter T has index 0, and the
745 /// `Substs` contain `u32` at index 0, we'll have `&[u32]` afterwards.)
746 fn subst(self, substs: &Substs) -> Self
747 where
748 Self: Sized,
749 {
750 self.fold(&mut |ty| match ty {
751 Ty::Param { idx, name } => {
752 substs.get(idx as usize).cloned().unwrap_or(Ty::Param { idx, name })
753 }
754 ty => ty,
755 })
756 }
757
758 /// Substitutes `Ty::Bound` vars (as opposed to type parameters).
759 fn subst_bound_vars(mut self, substs: &Substs) -> Self
760 where
761 Self: Sized,
762 {
763 self.walk_mut_binders(
764 &mut |ty, binders| match ty {
765 &mut Ty::Bound(idx) => {
766 if idx as usize >= binders && (idx as usize - binders) < substs.len() {
767 *ty = substs.0[idx as usize - binders].clone();
768 }
769 }
770 _ => {}
771 },
772 0,
773 );
774 self
775 }
776
777 /// Shifts up `Ty::Bound` vars by `n`.
778 fn shift_bound_vars(self, n: i32) -> Self
779 where
780 Self: Sized,
781 {
782 self.fold(&mut |ty| match ty {
783 Ty::Bound(idx) => {
784 assert!(idx as i32 >= -n);
785 Ty::Bound((idx as i32 + n) as u32)
786 }
787 ty => ty,
788 })
789 }
790}
791
792impl TypeWalk for Ty {
793 fn walk(&self, f: &mut impl FnMut(&Ty)) {
794 match self {
795 Ty::Apply(a_ty) => {
796 for t in a_ty.parameters.iter() {
797 t.walk(f);
798 }
799 }
800 Ty::Projection(p_ty) => {
801 for t in p_ty.parameters.iter() {
802 t.walk(f);
803 }
804 }
805 Ty::Dyn(predicates) | Ty::Opaque(predicates) => {
806 for p in predicates.iter() {
807 p.walk(f);
808 }
809 }
810 Ty::Param { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {}
811 }
812 f(self);
813 }
814
815 fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) {
816 match self {
817 Ty::Apply(a_ty) => {
818 a_ty.parameters.walk_mut_binders(f, binders);
819 }
820 Ty::Projection(p_ty) => {
821 p_ty.parameters.walk_mut_binders(f, binders);
822 }
823 Ty::Dyn(predicates) | Ty::Opaque(predicates) => {
824 for p in make_mut_slice(predicates) {
825 p.walk_mut_binders(f, binders + 1);
826 }
827 }
828 Ty::Param { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {}
829 }
830 f(self, binders);
831 }
832}
833
834impl HirDisplay for &Ty {
835 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
836 HirDisplay::hir_fmt(*self, f)
837 }
838}
839
840impl HirDisplay for ApplicationTy {
841 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
842 if f.should_truncate() {
843 return write!(f, "…");
844 }
845
846 match self.ctor {
847 TypeCtor::Bool => write!(f, "bool")?,
848 TypeCtor::Char => write!(f, "char")?,
849 TypeCtor::Int(t) => write!(f, "{}", t)?,
850 TypeCtor::Float(t) => write!(f, "{}", t)?,
851 TypeCtor::Str => write!(f, "str")?,
852 TypeCtor::Slice => {
853 let t = self.parameters.as_single();
854 write!(f, "[{}]", t.display(f.db))?;
855 }
856 TypeCtor::Array => {
857 let t = self.parameters.as_single();
858 write!(f, "[{};_]", t.display(f.db))?;
859 }
860 TypeCtor::RawPtr(m) => {
861 let t = self.parameters.as_single();
862 write!(f, "*{}{}", m.as_keyword_for_ptr(), t.display(f.db))?;
863 }
864 TypeCtor::Ref(m) => {
865 let t = self.parameters.as_single();
866 write!(f, "&{}{}", m.as_keyword_for_ref(), t.display(f.db))?;
867 }
868 TypeCtor::Never => write!(f, "!")?,
869 TypeCtor::Tuple { .. } => {
870 let ts = &self.parameters;
871 if ts.len() == 1 {
872 write!(f, "({},)", ts[0].display(f.db))?;
873 } else {
874 write!(f, "(")?;
875 f.write_joined(&*ts.0, ", ")?;
876 write!(f, ")")?;
877 }
878 }
879 TypeCtor::FnPtr { .. } => {
880 let sig = FnSig::from_fn_ptr_substs(&self.parameters);
881 write!(f, "fn(")?;
882 f.write_joined(sig.params(), ", ")?;
883 write!(f, ") -> {}", sig.ret().display(f.db))?;
884 }
885 TypeCtor::FnDef(def) => {
886 let sig = f.db.callable_item_signature(def);
887 let name = match def {
888 CallableDef::FunctionId(ff) => f.db.function_data(ff).name.clone(),
889 CallableDef::StructId(s) => {
890 f.db.struct_data(s).name.clone().unwrap_or_else(Name::missing)
891 }
892 CallableDef::EnumVariantId(e) => {
893 let enum_data = f.db.enum_data(e.parent);
894 enum_data.variants[e.local_id].name.clone().unwrap_or_else(Name::missing)
895 }
896 };
897 match def {
898 CallableDef::FunctionId(_) => write!(f, "fn {}", name)?,
899 CallableDef::StructId(_) | CallableDef::EnumVariantId(_) => {
900 write!(f, "{}", name)?
901 }
902 }
903 if self.parameters.len() > 0 {
904 write!(f, "<")?;
905 f.write_joined(&*self.parameters.0, ", ")?;
906 write!(f, ">")?;
907 }
908 write!(f, "(")?;
909 f.write_joined(sig.params(), ", ")?;
910 write!(f, ") -> {}", sig.ret().display(f.db))?;
911 }
912 TypeCtor::Adt(def_id) => {
913 let name = match def_id {
914 AdtId::StructId(it) => f.db.struct_data(it).name.clone(),
915 AdtId::UnionId(it) => f.db.union_data(it).name.clone(),
916 AdtId::EnumId(it) => f.db.enum_data(it).name.clone(),
917 }
918 .unwrap_or_else(Name::missing);
919 write!(f, "{}", name)?;
920 if self.parameters.len() > 0 {
921 write!(f, "<")?;
922 f.write_joined(&*self.parameters.0, ", ")?;
923 write!(f, ">")?;
924 }
925 }
926 TypeCtor::AssociatedType(type_alias) => {
927 let trait_ = match type_alias.lookup(f.db).container {
928 ContainerId::TraitId(it) => it,
929 _ => panic!("not an associated type"),
930 };
931 let trait_name = f.db.trait_data(trait_).name.clone().unwrap_or_else(Name::missing);
932 let name = f.db.type_alias_data(type_alias).name.clone();
933 write!(f, "{}::{}", trait_name, name)?;
934 if self.parameters.len() > 0 {
935 write!(f, "<")?;
936 f.write_joined(&*self.parameters.0, ", ")?;
937 write!(f, ">")?;
938 }
939 }
940 TypeCtor::Closure { .. } => {
941 let sig = self.parameters[0]
942 .callable_sig(f.db)
943 .expect("first closure parameter should contain signature");
944 write!(f, "|")?;
945 f.write_joined(sig.params(), ", ")?;
946 write!(f, "| -> {}", sig.ret().display(f.db))?;
947 }
948 }
949 Ok(())
950 }
951}
952
953impl HirDisplay for ProjectionTy {
954 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
955 if f.should_truncate() {
956 return write!(f, "…");
957 }
958
959 let trait_name =
960 f.db.trait_data(self.trait_(f.db)).name.clone().unwrap_or_else(Name::missing);
961 write!(f, "<{} as {}", self.parameters[0].display(f.db), trait_name,)?;
962 if self.parameters.len() > 1 {
963 write!(f, "<")?;
964 f.write_joined(&self.parameters[1..], ", ")?;
965 write!(f, ">")?;
966 }
967 write!(f, ">::{}", f.db.type_alias_data(self.associated_ty).name)?;
968 Ok(())
969 }
970}
971
972impl HirDisplay for Ty {
973 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
974 if f.should_truncate() {
975 return write!(f, "…");
976 }
977
978 match self {
979 Ty::Apply(a_ty) => a_ty.hir_fmt(f)?,
980 Ty::Projection(p_ty) => p_ty.hir_fmt(f)?,
981 Ty::Param { name, .. } => write!(f, "{}", name)?,
982 Ty::Bound(idx) => write!(f, "?{}", idx)?,
983 Ty::Dyn(predicates) | Ty::Opaque(predicates) => {
984 match self {
985 Ty::Dyn(_) => write!(f, "dyn ")?,
986 Ty::Opaque(_) => write!(f, "impl ")?,
987 _ => unreachable!(),
988 };
989 // Note: This code is written to produce nice results (i.e.
990 // corresponding to surface Rust) for types that can occur in
991 // actual Rust. It will have weird results if the predicates
992 // aren't as expected (i.e. self types = $0, projection
993 // predicates for a certain trait come after the Implemented
994 // predicate for that trait).
995 let mut first = true;
996 let mut angle_open = false;
997 for p in predicates.iter() {
998 match p {
999 GenericPredicate::Implemented(trait_ref) => {
1000 if angle_open {
1001 write!(f, ">")?;
1002 }
1003 if !first {
1004 write!(f, " + ")?;
1005 }
1006 // We assume that the self type is $0 (i.e. the
1007 // existential) here, which is the only thing that's
1008 // possible in actual Rust, and hence don't print it
1009 write!(
1010 f,
1011 "{}",
1012 f.db.trait_data(trait_ref.trait_)
1013 .name
1014 .clone()
1015 .unwrap_or_else(Name::missing)
1016 )?;
1017 if trait_ref.substs.len() > 1 {
1018 write!(f, "<")?;
1019 f.write_joined(&trait_ref.substs[1..], ", ")?;
1020 // there might be assoc type bindings, so we leave the angle brackets open
1021 angle_open = true;
1022 }
1023 }
1024 GenericPredicate::Projection(projection_pred) => {
1025 // in types in actual Rust, these will always come
1026 // after the corresponding Implemented predicate
1027 if angle_open {
1028 write!(f, ", ")?;
1029 } else {
1030 write!(f, "<")?;
1031 angle_open = true;
1032 }
1033 let name =
1034 f.db.type_alias_data(projection_pred.projection_ty.associated_ty)
1035 .name
1036 .clone();
1037 write!(f, "{} = ", name)?;
1038 projection_pred.ty.hir_fmt(f)?;
1039 }
1040 GenericPredicate::Error => {
1041 if angle_open {
1042 // impl Trait<X, {error}>
1043 write!(f, ", ")?;
1044 } else if !first {
1045 // impl Trait + {error}
1046 write!(f, " + ")?;
1047 }
1048 p.hir_fmt(f)?;
1049 }
1050 }
1051 first = false;
1052 }
1053 if angle_open {
1054 write!(f, ">")?;
1055 }
1056 }
1057 Ty::Unknown => write!(f, "{{unknown}}")?,
1058 Ty::Infer(..) => write!(f, "_")?,
1059 }
1060 Ok(())
1061 }
1062}
1063
1064impl TraitRef {
1065 fn hir_fmt_ext(&self, f: &mut HirFormatter<impl HirDatabase>, use_as: bool) -> fmt::Result {
1066 if f.should_truncate() {
1067 return write!(f, "…");
1068 }
1069
1070 self.substs[0].hir_fmt(f)?;
1071 if use_as {
1072 write!(f, " as ")?;
1073 } else {
1074 write!(f, ": ")?;
1075 }
1076 write!(f, "{}", f.db.trait_data(self.trait_).name.clone().unwrap_or_else(Name::missing))?;
1077 if self.substs.len() > 1 {
1078 write!(f, "<")?;
1079 f.write_joined(&self.substs[1..], ", ")?;
1080 write!(f, ">")?;
1081 }
1082 Ok(())
1083 }
1084}
1085
1086impl HirDisplay for TraitRef {
1087 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
1088 self.hir_fmt_ext(f, false)
1089 }
1090}
1091
1092impl HirDisplay for &GenericPredicate {
1093 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
1094 HirDisplay::hir_fmt(*self, f)
1095 }
1096}
1097
1098impl HirDisplay for GenericPredicate {
1099 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
1100 if f.should_truncate() {
1101 return write!(f, "…");
1102 }
1103
1104 match self {
1105 GenericPredicate::Implemented(trait_ref) => trait_ref.hir_fmt(f)?,
1106 GenericPredicate::Projection(projection_pred) => {
1107 write!(f, "<")?;
1108 projection_pred.projection_ty.trait_ref(f.db).hir_fmt_ext(f, true)?;
1109 write!(
1110 f,
1111 ">::{} = {}",
1112 f.db.type_alias_data(projection_pred.projection_ty.associated_ty).name,
1113 projection_pred.ty.display(f.db)
1114 )?;
1115 }
1116 GenericPredicate::Error => write!(f, "{{error}}")?,
1117 }
1118 Ok(())
1119 }
1120}
1121
1122impl HirDisplay for Obligation {
1123 fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result {
1124 match self {
1125 Obligation::Trait(tr) => write!(f, "Implements({})", tr.display(f.db)),
1126 Obligation::Projection(proj) => write!(
1127 f,
1128 "Normalize({} => {})",
1129 proj.projection_ty.display(f.db),
1130 proj.ty.display(f.db)
1131 ),
1132 }
1133 }
1134}
diff --git a/crates/ra_hir/src/ty/lower.rs b/crates/ra_hir_ty/src/lower.rs
index 5dce2f342..53d955a12 100644
--- a/crates/ra_hir/src/ty/lower.rs
+++ b/crates/ra_hir_ty/src/lower.rs
@@ -11,7 +11,7 @@ use std::sync::Arc;
11use hir_def::{ 11use hir_def::{
12 builtin_type::BuiltinType, 12 builtin_type::BuiltinType,
13 generics::WherePredicate, 13 generics::WherePredicate,
14 path::{GenericArg, Path, PathSegment}, 14 path::{GenericArg, Path, PathKind, PathSegment},
15 resolver::{HasResolver, Resolver, TypeNs}, 15 resolver::{HasResolver, Resolver, TypeNs},
16 type_ref::{TypeBound, TypeRef}, 16 type_ref::{TypeBound, TypeRef},
17 AdtId, AstItemDef, ConstId, EnumId, EnumVariantId, FunctionId, GenericDefId, HasModule, 17 AdtId, AstItemDef, ConstId, EnumId, EnumVariantId, FunctionId, GenericDefId, HasModule,
@@ -26,16 +26,13 @@ use super::{
26}; 26};
27use crate::{ 27use crate::{
28 db::HirDatabase, 28 db::HirDatabase,
29 ty::{ 29 primitive::{FloatTy, IntTy},
30 primitive::{FloatTy, IntTy}, 30 utils::make_mut_slice,
31 utils::{all_super_traits, associated_type_by_name_including_super_traits, variant_data}, 31 utils::{all_super_traits, associated_type_by_name_including_super_traits, variant_data},
32 },
33 util::make_mut_slice,
34 ImplBlock, Trait,
35}; 32};
36 33
37impl Ty { 34impl Ty {
38 pub(crate) fn from_hir(db: &impl HirDatabase, resolver: &Resolver, type_ref: &TypeRef) -> Self { 35 pub fn from_hir(db: &impl HirDatabase, resolver: &Resolver, type_ref: &TypeRef) -> Self {
39 match type_ref { 36 match type_ref {
40 TypeRef::Never => Ty::simple(TypeCtor::Never), 37 TypeRef::Never => Ty::simple(TypeCtor::Never),
41 TypeRef::Tuple(inner) => { 38 TypeRef::Tuple(inner) => {
@@ -104,7 +101,7 @@ impl Ty {
104 TypeRef::Path(path) => path, 101 TypeRef::Path(path) => path,
105 _ => return None, 102 _ => return None,
106 }; 103 };
107 if let crate::PathKind::Type(_) = &path.kind { 104 if let PathKind::Type(_) = &path.kind {
108 return None; 105 return None;
109 } 106 }
110 if path.segments.len() > 1 { 107 if path.segments.len() > 1 {
@@ -148,13 +145,8 @@ impl Ty {
148 ) -> Ty { 145 ) -> Ty {
149 let ty = match resolution { 146 let ty = match resolution {
150 TypeNs::TraitId(trait_) => { 147 TypeNs::TraitId(trait_) => {
151 let trait_ref = TraitRef::from_resolved_path( 148 let trait_ref =
152 db, 149 TraitRef::from_resolved_path(db, resolver, trait_, resolved_segment, None);
153 resolver,
154 trait_.into(),
155 resolved_segment,
156 None,
157 );
158 return if remaining_segments.len() == 1 { 150 return if remaining_segments.len() == 1 {
159 let segment = &remaining_segments[0]; 151 let segment = &remaining_segments[0];
160 let associated_ty = associated_type_by_name_including_super_traits( 152 let associated_ty = associated_type_by_name_including_super_traits(
@@ -187,7 +179,11 @@ impl Ty {
187 let name = resolved_segment.name.clone(); 179 let name = resolved_segment.name.clone();
188 Ty::Param { idx, name } 180 Ty::Param { idx, name }
189 } 181 }
190 TypeNs::SelfType(impl_block) => ImplBlock::from(impl_block).target_ty(db), 182 TypeNs::SelfType(impl_id) => {
183 let impl_data = db.impl_data(impl_id);
184 let resolver = impl_id.resolver(db);
185 Ty::from_hir(db, &resolver, &impl_data.target_type)
186 }
191 TypeNs::AdtSelfType(adt) => db.ty(adt.into()), 187 TypeNs::AdtSelfType(adt) => db.ty(adt.into()),
192 188
193 TypeNs::AdtId(it) => Ty::from_hir_path_inner(db, resolver, resolved_segment, it.into()), 189 TypeNs::AdtId(it) => Ty::from_hir_path_inner(db, resolver, resolved_segment, it.into()),
@@ -206,7 +202,7 @@ impl Ty {
206 202
207 pub(crate) fn from_hir_path(db: &impl HirDatabase, resolver: &Resolver, path: &Path) -> Ty { 203 pub(crate) fn from_hir_path(db: &impl HirDatabase, resolver: &Resolver, path: &Path) -> Ty {
208 // Resolve the path (in type namespace) 204 // Resolve the path (in type namespace)
209 if let crate::PathKind::Type(type_ref) = &path.kind { 205 if let PathKind::Type(type_ref) = &path.kind {
210 let ty = Ty::from_hir(db, resolver, &type_ref); 206 let ty = Ty::from_hir(db, resolver, &type_ref);
211 let remaining_segments = &path.segments[..]; 207 let remaining_segments = &path.segments[..];
212 return Ty::from_type_relative_path(db, resolver, ty, remaining_segments); 208 return Ty::from_type_relative_path(db, resolver, ty, remaining_segments);
@@ -250,14 +246,11 @@ impl Ty {
250 GenericPredicate::Implemented(tr) if tr.self_ty() == &self_ty => Some(tr.trait_), 246 GenericPredicate::Implemented(tr) if tr.self_ty() == &self_ty => Some(tr.trait_),
251 _ => None, 247 _ => None,
252 }); 248 });
253 let traits = traits_from_env.flat_map(|t| all_super_traits(db, t)).map(Trait::from); 249 let traits = traits_from_env.flat_map(|t| all_super_traits(db, t));
254 for t in traits { 250 for t in traits {
255 if let Some(associated_ty) = db.trait_data(t.id).associated_type_by_name(&segment.name) 251 if let Some(associated_ty) = db.trait_data(t).associated_type_by_name(&segment.name) {
256 { 252 let substs =
257 let substs = Substs::build_for_def(db, t.id) 253 Substs::build_for_def(db, t).push(self_ty.clone()).fill_with_unknown().build();
258 .push(self_ty.clone())
259 .fill_with_unknown()
260 .build();
261 // FIXME handle type parameters on the segment 254 // FIXME handle type parameters on the segment
262 return Ty::Projection(ProjectionTy { associated_ty, parameters: substs }); 255 return Ty::Projection(ProjectionTy { associated_ty, parameters: substs });
263 } 256 }
@@ -391,7 +384,7 @@ impl TraitRef {
391 pub(super) fn from_resolved_path( 384 pub(super) fn from_resolved_path(
392 db: &impl HirDatabase, 385 db: &impl HirDatabase,
393 resolver: &Resolver, 386 resolver: &Resolver,
394 resolved: Trait, 387 resolved: TraitId,
395 segment: &PathSegment, 388 segment: &PathSegment,
396 explicit_self_ty: Option<Ty>, 389 explicit_self_ty: Option<Ty>,
397 ) -> Self { 390 ) -> Self {
@@ -399,7 +392,7 @@ impl TraitRef {
399 if let Some(self_ty) = explicit_self_ty { 392 if let Some(self_ty) = explicit_self_ty {
400 make_mut_slice(&mut substs.0)[0] = self_ty; 393 make_mut_slice(&mut substs.0)[0] = self_ty;
401 } 394 }
402 TraitRef { trait_: resolved.id, substs } 395 TraitRef { trait_: resolved, substs }
403 } 396 }
404 397
405 pub(crate) fn from_hir( 398 pub(crate) fn from_hir(
@@ -419,14 +412,14 @@ impl TraitRef {
419 db: &impl HirDatabase, 412 db: &impl HirDatabase,
420 resolver: &Resolver, 413 resolver: &Resolver,
421 segment: &PathSegment, 414 segment: &PathSegment,
422 resolved: Trait, 415 resolved: TraitId,
423 ) -> Substs { 416 ) -> Substs {
424 let has_self_param = 417 let has_self_param =
425 segment.args_and_bindings.as_ref().map(|a| a.has_self_type).unwrap_or(false); 418 segment.args_and_bindings.as_ref().map(|a| a.has_self_type).unwrap_or(false);
426 substs_from_path_segment(db, resolver, segment, Some(resolved.id.into()), !has_self_param) 419 substs_from_path_segment(db, resolver, segment, Some(resolved.into()), !has_self_param)
427 } 420 }
428 421
429 pub(crate) fn for_trait(db: &impl HirDatabase, trait_: TraitId) -> TraitRef { 422 pub fn for_trait(db: &impl HirDatabase, trait_: TraitId) -> TraitRef {
430 let substs = Substs::identity(&db.generic_params(trait_.into())); 423 let substs = Substs::identity(&db.generic_params(trait_.into()));
431 TraitRef { trait_, substs } 424 TraitRef { trait_, substs }
432 } 425 }
@@ -500,7 +493,7 @@ fn assoc_type_bindings_from_type_bound<'a>(
500} 493}
501 494
502/// Build the signature of a callable item (function, struct or enum variant). 495/// Build the signature of a callable item (function, struct or enum variant).
503pub(crate) fn callable_item_sig(db: &impl HirDatabase, def: CallableDef) -> FnSig { 496pub fn callable_item_sig(db: &impl HirDatabase, def: CallableDef) -> FnSig {
504 match def { 497 match def {
505 CallableDef::FunctionId(f) => fn_sig_for_fn(db, f), 498 CallableDef::FunctionId(f) => fn_sig_for_fn(db, f),
506 CallableDef::StructId(s) => fn_sig_for_struct_constructor(db, s), 499 CallableDef::StructId(s) => fn_sig_for_struct_constructor(db, s),
@@ -549,7 +542,7 @@ pub(crate) fn generic_predicates_for_param_query(
549} 542}
550 543
551impl TraitEnvironment { 544impl TraitEnvironment {
552 pub(crate) fn lower(db: &impl HirDatabase, resolver: &Resolver) -> Arc<TraitEnvironment> { 545 pub fn lower(db: &impl HirDatabase, resolver: &Resolver) -> Arc<TraitEnvironment> {
553 let predicates = resolver 546 let predicates = resolver
554 .where_predicates_in_scope() 547 .where_predicates_in_scope()
555 .flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred)) 548 .flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred))
diff --git a/crates/ra_hir/src/marks.rs b/crates/ra_hir_ty/src/marks.rs
index 0f754eb9c..0f754eb9c 100644
--- a/crates/ra_hir/src/marks.rs
+++ b/crates/ra_hir_ty/src/marks.rs
diff --git a/crates/ra_hir/src/ty/method_resolution.rs b/crates/ra_hir_ty/src/method_resolution.rs
index 5cc249855..53c541eb8 100644
--- a/crates/ra_hir/src/ty/method_resolution.rs
+++ b/crates/ra_hir_ty/src/method_resolution.rs
@@ -16,8 +16,9 @@ use rustc_hash::FxHashMap;
16 16
17use crate::{ 17use crate::{
18 db::HirDatabase, 18 db::HirDatabase,
19 ty::primitive::{FloatBitness, Uncertain}, 19 primitive::{FloatBitness, Uncertain},
20 ty::{utils::all_super_traits, Ty, TypeCtor}, 20 utils::all_super_traits,
21 Ty, TypeCtor,
21}; 22};
22 23
23use super::{autoderef, Canonical, InEnvironment, TraitEnvironment, TraitRef}; 24use super::{autoderef, Canonical, InEnvironment, TraitEnvironment, TraitRef};
@@ -97,7 +98,7 @@ impl CrateImplBlocks {
97} 98}
98 99
99impl Ty { 100impl Ty {
100 pub(crate) fn def_crates( 101 pub fn def_crates(
101 &self, 102 &self,
102 db: &impl HirDatabase, 103 db: &impl HirDatabase,
103 cur_crate: CrateId, 104 cur_crate: CrateId,
@@ -176,7 +177,7 @@ pub enum LookupMode {
176// This would be nicer if it just returned an iterator, but that runs into 177// This would be nicer if it just returned an iterator, but that runs into
177// lifetime problems, because we need to borrow temp `CrateImplBlocks`. 178// lifetime problems, because we need to borrow temp `CrateImplBlocks`.
178// FIXME add a context type here? 179// FIXME add a context type here?
179pub(crate) fn iterate_method_candidates<T>( 180pub fn iterate_method_candidates<T>(
180 ty: &Canonical<Ty>, 181 ty: &Canonical<Ty>,
181 db: &impl HirDatabase, 182 db: &impl HirDatabase,
182 resolver: &Resolver, 183 resolver: &Resolver,
@@ -323,7 +324,7 @@ fn is_valid_candidate(
323 } 324 }
324} 325}
325 326
326pub(crate) fn implements_trait( 327pub fn implements_trait(
327 ty: &Canonical<Ty>, 328 ty: &Canonical<Ty>,
328 db: &impl HirDatabase, 329 db: &impl HirDatabase,
329 resolver: &Resolver, 330 resolver: &Resolver,
diff --git a/crates/ra_hir/src/ty/op.rs b/crates/ra_hir_ty/src/op.rs
index cc6e244f4..09c47a76d 100644
--- a/crates/ra_hir/src/ty/op.rs
+++ b/crates/ra_hir_ty/src/op.rs
@@ -2,7 +2,7 @@
2use hir_def::expr::{BinaryOp, CmpOp}; 2use hir_def::expr::{BinaryOp, CmpOp};
3 3
4use super::{InferTy, Ty, TypeCtor}; 4use super::{InferTy, Ty, TypeCtor};
5use crate::ty::ApplicationTy; 5use crate::ApplicationTy;
6 6
7pub(super) fn binary_op_return_ty(op: BinaryOp, rhs_ty: Ty) -> Ty { 7pub(super) fn binary_op_return_ty(op: BinaryOp, rhs_ty: Ty) -> Ty {
8 match op { 8 match op {
diff --git a/crates/ra_hir/src/test_db.rs b/crates/ra_hir_ty/src/test_db.rs
index a2071f71c..874357008 100644
--- a/crates/ra_hir/src/test_db.rs
+++ b/crates/ra_hir_ty/src/test_db.rs
@@ -1,21 +1,23 @@
1//! Database used for testing `hir`. 1//! Database used for testing `hir`.
2 2
3use std::{panic, sync::Arc}; 3use std::{
4 panic,
5 sync::{Arc, Mutex},
6};
4 7
5use hir_def::{db::DefDatabase, ModuleId}; 8use hir_def::{db::DefDatabase, AssocItemId, ModuleDefId, ModuleId};
6use hir_expand::diagnostics::DiagnosticSink; 9use hir_expand::diagnostics::DiagnosticSink;
7use parking_lot::Mutex;
8use ra_db::{salsa, CrateId, FileId, FileLoader, FileLoaderDelegate, RelativePath, SourceDatabase}; 10use ra_db::{salsa, CrateId, FileId, FileLoader, FileLoaderDelegate, RelativePath, SourceDatabase};
9 11
10use crate::{db, debug::HirDebugHelper}; 12use crate::{db::HirDatabase, expr::ExprValidator};
11 13
12#[salsa::database( 14#[salsa::database(
13 ra_db::SourceDatabaseExtStorage, 15 ra_db::SourceDatabaseExtStorage,
14 ra_db::SourceDatabaseStorage, 16 ra_db::SourceDatabaseStorage,
15 db::InternDatabaseStorage, 17 hir_expand::db::AstDatabaseStorage,
16 db::AstDatabaseStorage, 18 hir_def::db::InternDatabaseStorage,
17 db::DefDatabaseStorage, 19 hir_def::db::DefDatabaseStorage,
18 db::HirDatabaseStorage 20 crate::db::HirDatabaseStorage
19)] 21)]
20#[derive(Debug, Default)] 22#[derive(Debug, Default)]
21pub struct TestDB { 23pub struct TestDB {
@@ -33,7 +35,7 @@ impl salsa::Database for TestDB {
33 } 35 }
34 36
35 fn salsa_event(&self, event: impl Fn() -> salsa::Event<TestDB>) { 37 fn salsa_event(&self, event: impl Fn() -> salsa::Event<TestDB>) {
36 let mut events = self.events.lock(); 38 let mut events = self.events.lock().unwrap();
37 if let Some(events) = &mut *events { 39 if let Some(events) = &mut *events {
38 events.push(event()); 40 events.push(event());
39 } 41 }
@@ -67,32 +69,53 @@ impl FileLoader for TestDB {
67 } 69 }
68} 70}
69 71
70// FIXME: improve `WithFixture` to bring useful hir debugging back 72impl TestDB {
71impl HirDebugHelper for TestDB { 73 pub fn module_for_file(&self, file_id: FileId) -> ModuleId {
72 fn crate_name(&self, _krate: CrateId) -> Option<String> { 74 for &krate in self.relevant_crates(file_id).iter() {
73 None 75 let crate_def_map = self.crate_def_map(krate);
74 } 76 for (module_id, data) in crate_def_map.modules.iter() {
75 77 if data.definition == Some(file_id) {
76 fn file_path(&self, _file_id: FileId) -> Option<String> { 78 return ModuleId { krate, module_id };
77 None 79 }
80 }
81 }
82 panic!("Can't find module for file")
78 } 83 }
79}
80 84
81impl TestDB { 85 // FIXME: don't duplicate this
82 pub fn diagnostics(&self) -> String { 86 pub fn diagnostics(&self) -> String {
83 let mut buf = String::new(); 87 let mut buf = String::new();
84 let crate_graph = self.crate_graph(); 88 let crate_graph = self.crate_graph();
85 for krate in crate_graph.iter().next() { 89 for krate in crate_graph.iter().next() {
86 let crate_def_map = self.crate_def_map(krate); 90 let crate_def_map = self.crate_def_map(krate);
91
92 let mut fns = Vec::new();
87 for (module_id, _) in crate_def_map.modules.iter() { 93 for (module_id, _) in crate_def_map.modules.iter() {
88 let module_id = ModuleId { krate, module_id }; 94 for decl in crate_def_map[module_id].scope.declarations() {
89 let module = crate::Module::from(module_id); 95 match decl {
90 module.diagnostics( 96 ModuleDefId::FunctionId(f) => fns.push(f),
91 self, 97 _ => (),
92 &mut DiagnosticSink::new(|d| { 98 }
93 buf += &format!("{:?}: {}\n", d.syntax_node(self).text(), d.message()); 99 }
94 }), 100
95 ) 101 for &impl_id in crate_def_map[module_id].impls.iter() {
102 let impl_data = self.impl_data(impl_id);
103 for item in impl_data.items.iter() {
104 if let AssocItemId::FunctionId(f) = item {
105 fns.push(*f)
106 }
107 }
108 }
109 }
110
111 for f in fns {
112 let infer = self.infer(f.into());
113 let mut sink = DiagnosticSink::new(|d| {
114 buf += &format!("{:?}: {}\n", d.syntax_node(self).text(), d.message());
115 });
116 infer.add_diagnostics(self, f, &mut sink);
117 let mut validator = ExprValidator::new(f, infer, &mut sink);
118 validator.validate_body(self);
96 } 119 }
97 } 120 }
98 buf 121 buf
@@ -101,9 +124,9 @@ impl TestDB {
101 124
102impl TestDB { 125impl TestDB {
103 pub fn log(&self, f: impl FnOnce()) -> Vec<salsa::Event<TestDB>> { 126 pub fn log(&self, f: impl FnOnce()) -> Vec<salsa::Event<TestDB>> {
104 *self.events.lock() = Some(Vec::new()); 127 *self.events.lock().unwrap() = Some(Vec::new());
105 f(); 128 f();
106 self.events.lock().take().unwrap() 129 self.events.lock().unwrap().take().unwrap()
107 } 130 }
108 131
109 pub fn log_executed(&self, f: impl FnOnce()) -> Vec<String> { 132 pub fn log_executed(&self, f: impl FnOnce()) -> Vec<String> {
diff --git a/crates/ra_hir/src/ty/tests.rs b/crates/ra_hir_ty/src/tests.rs
index 98eb863cb..c1744663a 100644
--- a/crates/ra_hir/src/ty/tests.rs
+++ b/crates/ra_hir_ty/src/tests.rs
@@ -4,20 +4,20 @@ mod coercion;
4use std::fmt::Write; 4use std::fmt::Write;
5use std::sync::Arc; 5use std::sync::Arc;
6 6
7use hir_def::{
8 body::BodySourceMap, db::DefDatabase, nameres::CrateDefMap, AssocItemId, DefWithBodyId,
9 LocalModuleId, Lookup, ModuleDefId,
10};
11use hir_expand::Source;
7use insta::assert_snapshot; 12use insta::assert_snapshot;
8use ra_db::{fixture::WithFixture, salsa::Database, FilePosition, SourceDatabase}; 13use ra_db::{fixture::WithFixture, salsa::Database, FilePosition, SourceDatabase};
9use ra_syntax::{ 14use ra_syntax::{
10 algo, 15 algo,
11 ast::{self, AstNode}, 16 ast::{self, AstNode},
12 SyntaxKind::*,
13}; 17};
14use rustc_hash::FxHashSet;
15use test_utils::covers; 18use test_utils::covers;
16 19
17use crate::{ 20use crate::{db::HirDatabase, display::HirDisplay, test_db::TestDB, InferenceResult};
18 expr::BodySourceMap, test_db::TestDB, ty::display::HirDisplay, ty::InferenceResult, Source,
19 SourceAnalyzer,
20};
21 21
22// These tests compare the inference results for all expressions in a file 22// These tests compare the inference results for all expressions in a file
23// against snapshots of the expected results using insta. Use cargo-insta to 23// against snapshots of the expected results using insta. Use cargo-insta to
@@ -4674,10 +4674,20 @@ fn test<T, U>() where T: Trait<U::Item>, U: Trait<T::Item> {
4674fn type_at_pos(db: &TestDB, pos: FilePosition) -> String { 4674fn type_at_pos(db: &TestDB, pos: FilePosition) -> String {
4675 let file = db.parse(pos.file_id).ok().unwrap(); 4675 let file = db.parse(pos.file_id).ok().unwrap();
4676 let expr = algo::find_node_at_offset::<ast::Expr>(file.syntax(), pos.offset).unwrap(); 4676 let expr = algo::find_node_at_offset::<ast::Expr>(file.syntax(), pos.offset).unwrap();
4677 let analyzer = 4677
4678 SourceAnalyzer::new(db, Source::new(pos.file_id.into(), expr.syntax()), Some(pos.offset)); 4678 let module = db.module_for_file(pos.file_id);
4679 let ty = analyzer.type_of(db, &expr).unwrap(); 4679 let crate_def_map = db.crate_def_map(module.krate);
4680 ty.display(db).to_string() 4680 for decl in crate_def_map[module.module_id].scope.declarations() {
4681 if let ModuleDefId::FunctionId(func) = decl {
4682 let (_body, source_map) = db.body_with_source_map(func.into());
4683 if let Some(expr_id) = source_map.node_expr(Source::new(pos.file_id.into(), &expr)) {
4684 let infer = db.infer(func.into());
4685 let ty = &infer[expr_id];
4686 return ty.display(db).to_string();
4687 }
4688 }
4689 }
4690 panic!("Can't find expression")
4681} 4691}
4682 4692
4683fn type_at(content: &str) -> String { 4693fn type_at(content: &str) -> String {
@@ -4687,7 +4697,6 @@ fn type_at(content: &str) -> String {
4687 4697
4688fn infer(content: &str) -> String { 4698fn infer(content: &str) -> String {
4689 let (db, file_id) = TestDB::with_single_file(content); 4699 let (db, file_id) = TestDB::with_single_file(content);
4690 let source_file = db.parse(file_id).ok().unwrap();
4691 4700
4692 let mut acc = String::new(); 4701 let mut acc = String::new();
4693 4702
@@ -4740,20 +4749,69 @@ fn infer(content: &str) -> String {
4740 } 4749 }
4741 }; 4750 };
4742 4751
4743 let mut analyzed = FxHashSet::default(); 4752 let module = db.module_for_file(file_id);
4744 for node in source_file.syntax().descendants() { 4753 let crate_def_map = db.crate_def_map(module.krate);
4745 if node.kind() == FN_DEF || node.kind() == CONST_DEF || node.kind() == STATIC_DEF { 4754
4746 let analyzer = SourceAnalyzer::new(&db, Source::new(file_id.into(), &node), None); 4755 let mut defs: Vec<DefWithBodyId> = Vec::new();
4747 if analyzed.insert(analyzer.analyzed_declaration()) { 4756 visit_module(&db, &crate_def_map, module.module_id, &mut |it| defs.push(it));
4748 infer_def(analyzer.inference_result(), analyzer.body_source_map()); 4757 defs.sort_by_key(|def| match def {
4749 } 4758 DefWithBodyId::FunctionId(it) => {
4759 it.lookup(&db).ast_id.to_node(&db).syntax().text_range().start()
4760 }
4761 DefWithBodyId::ConstId(it) => {
4762 it.lookup(&db).ast_id.to_node(&db).syntax().text_range().start()
4763 }
4764 DefWithBodyId::StaticId(it) => {
4765 it.lookup(&db).ast_id.to_node(&db).syntax().text_range().start()
4750 } 4766 }
4767 });
4768 for def in defs {
4769 let (_body, source_map) = db.body_with_source_map(def);
4770 let infer = db.infer(def);
4771 infer_def(infer, source_map);
4751 } 4772 }
4752 4773
4753 acc.truncate(acc.trim_end().len()); 4774 acc.truncate(acc.trim_end().len());
4754 acc 4775 acc
4755} 4776}
4756 4777
4778fn visit_module(
4779 db: &TestDB,
4780 crate_def_map: &CrateDefMap,
4781 module_id: LocalModuleId,
4782 cb: &mut dyn FnMut(DefWithBodyId),
4783) {
4784 for decl in crate_def_map[module_id].scope.declarations() {
4785 match decl {
4786 ModuleDefId::FunctionId(it) => cb(it.into()),
4787 ModuleDefId::ConstId(it) => cb(it.into()),
4788 ModuleDefId::StaticId(it) => cb(it.into()),
4789 ModuleDefId::TraitId(it) => {
4790 let trait_data = db.trait_data(it);
4791 for &(_, item) in trait_data.items.iter() {
4792 match item {
4793 AssocItemId::FunctionId(it) => cb(it.into()),
4794 AssocItemId::ConstId(it) => cb(it.into()),
4795 AssocItemId::TypeAliasId(_) => (),
4796 }
4797 }
4798 }
4799 ModuleDefId::ModuleId(it) => visit_module(db, crate_def_map, it.module_id, cb),
4800 _ => (),
4801 }
4802 }
4803 for &impl_id in crate_def_map[module_id].impls.iter() {
4804 let impl_data = db.impl_data(impl_id);
4805 for &item in impl_data.items.iter() {
4806 match item {
4807 AssocItemId::FunctionId(it) => cb(it.into()),
4808 AssocItemId::ConstId(it) => cb(it.into()),
4809 AssocItemId::TypeAliasId(_) => (),
4810 }
4811 }
4812 }
4813}
4814
4757fn ellipsize(mut text: String, max_len: usize) -> String { 4815fn ellipsize(mut text: String, max_len: usize) -> String {
4758 if text.len() <= max_len { 4816 if text.len() <= max_len {
4759 return text; 4817 return text;
@@ -4783,10 +4841,12 @@ fn typing_whitespace_inside_a_function_should_not_invalidate_types() {
4783 ", 4841 ",
4784 ); 4842 );
4785 { 4843 {
4786 let file = db.parse(pos.file_id).ok().unwrap();
4787 let node = file.syntax().token_at_offset(pos.offset).right_biased().unwrap().parent();
4788 let events = db.log_executed(|| { 4844 let events = db.log_executed(|| {
4789 SourceAnalyzer::new(&db, Source::new(pos.file_id.into(), &node), None); 4845 let module = db.module_for_file(pos.file_id);
4846 let crate_def_map = db.crate_def_map(module.krate);
4847 visit_module(&db, &crate_def_map, module.module_id, &mut |def| {
4848 db.infer(def);
4849 });
4790 }); 4850 });
4791 assert!(format!("{:?}", events).contains("infer")) 4851 assert!(format!("{:?}", events).contains("infer"))
4792 } 4852 }
@@ -4803,10 +4863,12 @@ fn typing_whitespace_inside_a_function_should_not_invalidate_types() {
4803 db.query_mut(ra_db::FileTextQuery).set(pos.file_id, Arc::new(new_text)); 4863 db.query_mut(ra_db::FileTextQuery).set(pos.file_id, Arc::new(new_text));
4804 4864
4805 { 4865 {
4806 let file = db.parse(pos.file_id).ok().unwrap();
4807 let node = file.syntax().token_at_offset(pos.offset).right_biased().unwrap().parent();
4808 let events = db.log_executed(|| { 4866 let events = db.log_executed(|| {
4809 SourceAnalyzer::new(&db, Source::new(pos.file_id.into(), &node), None); 4867 let module = db.module_for_file(pos.file_id);
4868 let crate_def_map = db.crate_def_map(module.krate);
4869 visit_module(&db, &crate_def_map, module.module_id, &mut |def| {
4870 db.infer(def);
4871 });
4810 }); 4872 });
4811 assert!(!format!("{:?}", events).contains("infer"), "{:#?}", events) 4873 assert!(!format!("{:?}", events).contains("infer"), "{:#?}", events)
4812 } 4874 }
diff --git a/crates/ra_hir/src/ty/tests/coercion.rs b/crates/ra_hir_ty/src/tests/coercion.rs
index 1530fcc63..1530fcc63 100644
--- a/crates/ra_hir/src/ty/tests/coercion.rs
+++ b/crates/ra_hir_ty/src/tests/coercion.rs
diff --git a/crates/ra_hir/src/ty/tests/never_type.rs b/crates/ra_hir_ty/src/tests/never_type.rs
index c202f545a..c202f545a 100644
--- a/crates/ra_hir/src/ty/tests/never_type.rs
+++ b/crates/ra_hir_ty/src/tests/never_type.rs
diff --git a/crates/ra_hir/src/ty/traits.rs b/crates/ra_hir_ty/src/traits.rs
index 76189a60b..76189a60b 100644
--- a/crates/ra_hir/src/ty/traits.rs
+++ b/crates/ra_hir_ty/src/traits.rs
diff --git a/crates/ra_hir/src/ty/traits/chalk.rs b/crates/ra_hir_ty/src/traits/chalk.rs
index 67ac5422c..810e8c21a 100644
--- a/crates/ra_hir/src/ty/traits/chalk.rs
+++ b/crates/ra_hir_ty/src/traits/chalk.rs
@@ -11,8 +11,8 @@ use chalk_rust_ir::{AssociatedTyDatum, AssociatedTyValue, ImplDatum, StructDatum
11use ra_db::CrateId; 11use ra_db::CrateId;
12 12
13use hir_def::{ 13use hir_def::{
14 lang_item::LangItemTarget, resolver::HasResolver, AssocItemId, AstItemDef, ContainerId, 14 expr::Expr, lang_item::LangItemTarget, resolver::HasResolver, AssocItemId, AstItemDef,
15 GenericDefId, ImplId, Lookup, TraitId, TypeAliasId, 15 ContainerId, GenericDefId, ImplId, Lookup, TraitId, TypeAliasId,
16}; 16};
17use hir_expand::name; 17use hir_expand::name;
18 18
@@ -21,8 +21,8 @@ use ra_db::salsa::{InternId, InternKey};
21use super::{AssocTyValue, Canonical, ChalkContext, Impl, Obligation}; 21use super::{AssocTyValue, Canonical, ChalkContext, Impl, Obligation};
22use crate::{ 22use crate::{
23 db::HirDatabase, 23 db::HirDatabase,
24 ty::display::HirDisplay, 24 display::HirDisplay,
25 ty::{ApplicationTy, GenericPredicate, ProjectionTy, Substs, TraitRef, Ty, TypeCtor, TypeWalk}, 25 {ApplicationTy, GenericPredicate, ProjectionTy, Substs, TraitRef, Ty, TypeCtor, TypeWalk},
26}; 26};
27 27
28/// This represents a trait whose name we could not resolve. 28/// This represents a trait whose name we could not resolve.
@@ -723,7 +723,7 @@ fn closure_fn_trait_impl_datum(
723 let _output = db.trait_data(fn_once_trait).associated_type_by_name(&name::OUTPUT_TYPE)?; 723 let _output = db.trait_data(fn_once_trait).associated_type_by_name(&name::OUTPUT_TYPE)?;
724 724
725 let num_args: u16 = match &db.body(data.def.into())[data.expr] { 725 let num_args: u16 = match &db.body(data.def.into())[data.expr] {
726 crate::expr::Expr::Lambda { args, .. } => args.len() as u16, 726 Expr::Lambda { args, .. } => args.len() as u16,
727 _ => { 727 _ => {
728 log::warn!("closure for closure type {:?} not found", data); 728 log::warn!("closure for closure type {:?} not found", data);
729 0 729 0
@@ -823,7 +823,7 @@ fn closure_fn_trait_output_assoc_ty_value(
823 let impl_id = Impl::ClosureFnTraitImpl(data.clone()).to_chalk(db); 823 let impl_id = Impl::ClosureFnTraitImpl(data.clone()).to_chalk(db);
824 824
825 let num_args: u16 = match &db.body(data.def.into())[data.expr] { 825 let num_args: u16 = match &db.body(data.def.into())[data.expr] {
826 crate::expr::Expr::Lambda { args, .. } => args.len() as u16, 826 Expr::Lambda { args, .. } => args.len() as u16,
827 _ => { 827 _ => {
828 log::warn!("closure for closure type {:?} not found", data); 828 log::warn!("closure for closure type {:?} not found", data);
829 0 829 0
@@ -869,38 +869,38 @@ fn id_to_chalk<T: InternKey>(salsa_id: T) -> chalk_ir::RawId {
869 chalk_ir::RawId { index: salsa_id.as_intern_id().as_u32() } 869 chalk_ir::RawId { index: salsa_id.as_intern_id().as_u32() }
870} 870}
871 871
872impl From<chalk_ir::StructId> for crate::ty::TypeCtorId { 872impl From<chalk_ir::StructId> for crate::TypeCtorId {
873 fn from(struct_id: chalk_ir::StructId) -> Self { 873 fn from(struct_id: chalk_ir::StructId) -> Self {
874 id_from_chalk(struct_id.0) 874 id_from_chalk(struct_id.0)
875 } 875 }
876} 876}
877 877
878impl From<crate::ty::TypeCtorId> for chalk_ir::StructId { 878impl From<crate::TypeCtorId> for chalk_ir::StructId {
879 fn from(type_ctor_id: crate::ty::TypeCtorId) -> Self { 879 fn from(type_ctor_id: crate::TypeCtorId) -> Self {
880 chalk_ir::StructId(id_to_chalk(type_ctor_id)) 880 chalk_ir::StructId(id_to_chalk(type_ctor_id))
881 } 881 }
882} 882}
883 883
884impl From<chalk_ir::ImplId> for crate::ty::traits::GlobalImplId { 884impl From<chalk_ir::ImplId> for crate::traits::GlobalImplId {
885 fn from(impl_id: chalk_ir::ImplId) -> Self { 885 fn from(impl_id: chalk_ir::ImplId) -> Self {
886 id_from_chalk(impl_id.0) 886 id_from_chalk(impl_id.0)
887 } 887 }
888} 888}
889 889
890impl From<crate::ty::traits::GlobalImplId> for chalk_ir::ImplId { 890impl From<crate::traits::GlobalImplId> for chalk_ir::ImplId {
891 fn from(impl_id: crate::ty::traits::GlobalImplId) -> Self { 891 fn from(impl_id: crate::traits::GlobalImplId) -> Self {
892 chalk_ir::ImplId(id_to_chalk(impl_id)) 892 chalk_ir::ImplId(id_to_chalk(impl_id))
893 } 893 }
894} 894}
895 895
896impl From<chalk_rust_ir::AssociatedTyValueId> for crate::ty::traits::AssocTyValueId { 896impl From<chalk_rust_ir::AssociatedTyValueId> for crate::traits::AssocTyValueId {
897 fn from(id: chalk_rust_ir::AssociatedTyValueId) -> Self { 897 fn from(id: chalk_rust_ir::AssociatedTyValueId) -> Self {
898 id_from_chalk(id.0) 898 id_from_chalk(id.0)
899 } 899 }
900} 900}
901 901
902impl From<crate::ty::traits::AssocTyValueId> for chalk_rust_ir::AssociatedTyValueId { 902impl From<crate::traits::AssocTyValueId> for chalk_rust_ir::AssociatedTyValueId {
903 fn from(assoc_ty_value_id: crate::ty::traits::AssocTyValueId) -> Self { 903 fn from(assoc_ty_value_id: crate::traits::AssocTyValueId) -> Self {
904 chalk_rust_ir::AssociatedTyValueId(id_to_chalk(assoc_ty_value_id)) 904 chalk_rust_ir::AssociatedTyValueId(id_to_chalk(assoc_ty_value_id))
905 } 905 }
906} 906}
diff --git a/crates/ra_hir/src/ty/utils.rs b/crates/ra_hir_ty/src/utils.rs
index f82e6ac9b..e4ba890ef 100644
--- a/crates/ra_hir/src/ty/utils.rs
+++ b/crates/ra_hir_ty/src/utils.rs
@@ -73,3 +73,12 @@ pub(super) fn variant_data(db: &impl DefDatabase, var: VariantId) -> Arc<Variant
73 } 73 }
74 } 74 }
75} 75}
76
77/// Helper for mutating `Arc<[T]>` (i.e. `Arc::make_mut` for Arc slices).
78/// The underlying values are cloned if there are other strong references.
79pub(crate) fn make_mut_slice<T: Clone>(a: &mut Arc<[T]>) -> &mut [T] {
80 if Arc::get_mut(a).is_none() {
81 *a = a.iter().cloned().collect();
82 }
83 Arc::get_mut(a).unwrap()
84}
diff --git a/crates/ra_ide_api/src/impls.rs b/crates/ra_ide_api/src/impls.rs
index b3ebd9145..aa480e399 100644
--- a/crates/ra_ide_api/src/impls.rs
+++ b/crates/ra_ide_api/src/impls.rs
@@ -1,6 +1,6 @@
1//! FIXME: write short doc here 1//! FIXME: write short doc here
2 2
3use hir::{ApplicationTy, FromSource, ImplBlock, Ty, TypeCtor}; 3use hir::{FromSource, ImplBlock};
4use ra_db::SourceDatabase; 4use ra_db::SourceDatabase;
5use ra_syntax::{algo::find_node_at_offset, ast, AstNode}; 5use ra_syntax::{algo::find_node_at_offset, ast, AstNode};
6 6
@@ -61,7 +61,7 @@ fn impls_for_def(
61 Some( 61 Some(
62 impls 62 impls
63 .into_iter() 63 .into_iter()
64 .filter(|impl_block| is_equal_for_find_impls(&ty, &impl_block.target_ty(db))) 64 .filter(|impl_block| ty.is_equal_for_find_impls(&impl_block.target_ty(db)))
65 .map(|imp| imp.to_nav(db)) 65 .map(|imp| imp.to_nav(db))
66 .collect(), 66 .collect(),
67 ) 67 )
@@ -82,19 +82,6 @@ fn impls_for_trait(
82 Some(impls.into_iter().map(|imp| imp.to_nav(db)).collect()) 82 Some(impls.into_iter().map(|imp| imp.to_nav(db)).collect())
83} 83}
84 84
85fn is_equal_for_find_impls(original_ty: &Ty, impl_ty: &Ty) -> bool {
86 match (original_ty, impl_ty) {
87 (Ty::Apply(a_original_ty), Ty::Apply(ApplicationTy { ctor, parameters })) => match ctor {
88 TypeCtor::Ref(..) => match parameters.as_single() {
89 Ty::Apply(a_ty) => a_original_ty.ctor == a_ty.ctor,
90 _ => false,
91 },
92 _ => a_original_ty.ctor == *ctor,
93 },
94 _ => false,
95 }
96}
97
98#[cfg(test)] 85#[cfg(test)]
99mod tests { 86mod tests {
100 use crate::mock_analysis::analysis_and_position; 87 use crate::mock_analysis::analysis_and_position;
diff --git a/xtask/tests/tidy-tests/docs.rs b/xtask/tests/tidy-tests/docs.rs
index fae871285..e0653b460 100644
--- a/xtask/tests/tidy-tests/docs.rs
+++ b/xtask/tests/tidy-tests/docs.rs
@@ -83,6 +83,7 @@ fn no_docs_comments() {
83 "ra_syntax", 83 "ra_syntax",
84 "ra_text_edit", 84 "ra_text_edit",
85 "ra_tt", 85 "ra_tt",
86 "ra_hir_ty",
86 ]; 87 ];
87 88
88 let mut has_fixmes = whitelist.iter().map(|it| (*it, false)).collect::<HashMap<&str, bool>>(); 89 let mut has_fixmes = whitelist.iter().map(|it| (*it, false)).collect::<HashMap<&str, bool>>();