diff options
Diffstat (limited to 'crates/ra_hir/src/ty')
-rw-r--r-- | crates/ra_hir/src/ty/autoderef.rs | 103 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/display.rs | 93 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/infer.rs | 748 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/infer/coerce.rs | 339 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/infer/expr.rs | 667 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/infer/pat.rs | 183 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/infer/path.rs | 258 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/infer/unify.rs | 164 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/lower.rs | 831 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/method_resolution.rs | 375 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/op.rs | 52 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/primitive.rs | 160 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/tests.rs | 4895 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/tests/coercion.rs | 369 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/tests/never_type.rs | 246 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/traits.rs | 326 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/traits/chalk.rs | 884 |
17 files changed, 0 insertions, 10693 deletions
diff --git a/crates/ra_hir/src/ty/autoderef.rs b/crates/ra_hir/src/ty/autoderef.rs deleted file mode 100644 index 41c99d227..000000000 --- a/crates/ra_hir/src/ty/autoderef.rs +++ /dev/null | |||
@@ -1,103 +0,0 @@ | |||
1 | //! In certain situations, rust automatically inserts derefs as necessary: for | ||
2 | //! example, field accesses `foo.bar` still work when `foo` is actually a | ||
3 | //! reference to a type with the field `bar`. This is an approximation of the | ||
4 | //! logic in rustc (which lives in librustc_typeck/check/autoderef.rs). | ||
5 | |||
6 | use std::iter::successors; | ||
7 | |||
8 | use hir_def::{lang_item::LangItemTarget, resolver::Resolver}; | ||
9 | use hir_expand::name; | ||
10 | use log::{info, warn}; | ||
11 | |||
12 | use crate::{db::HirDatabase, Trait}; | ||
13 | |||
14 | use super::{traits::Solution, Canonical, Substs, Ty, TypeWalk}; | ||
15 | |||
16 | const AUTODEREF_RECURSION_LIMIT: usize = 10; | ||
17 | |||
18 | pub(crate) fn autoderef<'a>( | ||
19 | db: &'a impl HirDatabase, | ||
20 | resolver: &'a Resolver, | ||
21 | ty: Canonical<Ty>, | ||
22 | ) -> impl Iterator<Item = Canonical<Ty>> + 'a { | ||
23 | successors(Some(ty), move |ty| deref(db, resolver, ty)).take(AUTODEREF_RECURSION_LIMIT) | ||
24 | } | ||
25 | |||
26 | pub(crate) fn deref( | ||
27 | db: &impl HirDatabase, | ||
28 | resolver: &Resolver, | ||
29 | ty: &Canonical<Ty>, | ||
30 | ) -> Option<Canonical<Ty>> { | ||
31 | if let Some(derefed) = ty.value.builtin_deref() { | ||
32 | Some(Canonical { value: derefed, num_vars: ty.num_vars }) | ||
33 | } else { | ||
34 | deref_by_trait(db, resolver, ty) | ||
35 | } | ||
36 | } | ||
37 | |||
38 | fn deref_by_trait( | ||
39 | db: &impl HirDatabase, | ||
40 | resolver: &Resolver, | ||
41 | ty: &Canonical<Ty>, | ||
42 | ) -> Option<Canonical<Ty>> { | ||
43 | let krate = resolver.krate()?; | ||
44 | let deref_trait = match db.lang_item(krate.into(), "deref".into())? { | ||
45 | LangItemTarget::TraitId(t) => Trait::from(t), | ||
46 | _ => return None, | ||
47 | }; | ||
48 | let target = deref_trait.associated_type_by_name(db, &name::TARGET_TYPE)?; | ||
49 | |||
50 | let generic_params = db.generic_params(target.id.into()); | ||
51 | if generic_params.count_params_including_parent() != 1 { | ||
52 | // the Target type + Deref trait should only have one generic parameter, | ||
53 | // namely Deref's Self type | ||
54 | return None; | ||
55 | } | ||
56 | |||
57 | // FIXME make the Canonical handling nicer | ||
58 | |||
59 | let env = super::lower::trait_env(db, resolver); | ||
60 | |||
61 | let parameters = Substs::build_for_generics(&generic_params) | ||
62 | .push(ty.value.clone().shift_bound_vars(1)) | ||
63 | .build(); | ||
64 | |||
65 | let projection = super::traits::ProjectionPredicate { | ||
66 | ty: Ty::Bound(0), | ||
67 | projection_ty: super::ProjectionTy { associated_ty: target, parameters }, | ||
68 | }; | ||
69 | |||
70 | let obligation = super::Obligation::Projection(projection); | ||
71 | |||
72 | let in_env = super::traits::InEnvironment { value: obligation, environment: env }; | ||
73 | |||
74 | let canonical = super::Canonical { num_vars: 1 + ty.num_vars, value: in_env }; | ||
75 | |||
76 | let solution = db.trait_solve(krate.into(), canonical)?; | ||
77 | |||
78 | match &solution { | ||
79 | Solution::Unique(vars) => { | ||
80 | // FIXME: vars may contain solutions for any inference variables | ||
81 | // that happened to be inside ty. To correctly handle these, we | ||
82 | // would have to pass the solution up to the inference context, but | ||
83 | // that requires a larger refactoring (especially if the deref | ||
84 | // happens during method resolution). So for the moment, we just | ||
85 | // check that we're not in the situation we're we would actually | ||
86 | // need to handle the values of the additional variables, i.e. | ||
87 | // they're just being 'passed through'. In the 'standard' case where | ||
88 | // we have `impl<T> Deref for Foo<T> { Target = T }`, that should be | ||
89 | // the case. | ||
90 | for i in 1..vars.0.num_vars { | ||
91 | if vars.0.value[i] != Ty::Bound((i - 1) as u32) { | ||
92 | warn!("complex solution for derefing {:?}: {:?}, ignoring", ty, solution); | ||
93 | return None; | ||
94 | } | ||
95 | } | ||
96 | Some(Canonical { value: vars.0.value[0].clone(), num_vars: vars.0.num_vars }) | ||
97 | } | ||
98 | Solution::Ambig(_) => { | ||
99 | info!("Ambiguous solution for derefing {:?}: {:?}", ty, solution); | ||
100 | None | ||
101 | } | ||
102 | } | ||
103 | } | ||
diff --git a/crates/ra_hir/src/ty/display.rs b/crates/ra_hir/src/ty/display.rs deleted file mode 100644 index 9bb3ece6c..000000000 --- a/crates/ra_hir/src/ty/display.rs +++ /dev/null | |||
@@ -1,93 +0,0 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | |||
3 | use std::fmt; | ||
4 | |||
5 | use crate::db::HirDatabase; | ||
6 | |||
7 | pub struct HirFormatter<'a, 'b, DB> { | ||
8 | pub db: &'a DB, | ||
9 | fmt: &'a mut fmt::Formatter<'b>, | ||
10 | buf: String, | ||
11 | curr_size: usize, | ||
12 | max_size: Option<usize>, | ||
13 | } | ||
14 | |||
15 | pub trait HirDisplay { | ||
16 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result; | ||
17 | |||
18 | fn display<'a, DB>(&'a self, db: &'a DB) -> HirDisplayWrapper<'a, DB, Self> | ||
19 | where | ||
20 | Self: Sized, | ||
21 | { | ||
22 | HirDisplayWrapper(db, self, None) | ||
23 | } | ||
24 | |||
25 | fn display_truncated<'a, DB>( | ||
26 | &'a self, | ||
27 | db: &'a DB, | ||
28 | max_size: Option<usize>, | ||
29 | ) -> HirDisplayWrapper<'a, DB, Self> | ||
30 | where | ||
31 | Self: Sized, | ||
32 | { | ||
33 | HirDisplayWrapper(db, self, max_size) | ||
34 | } | ||
35 | } | ||
36 | |||
37 | impl<'a, 'b, DB> HirFormatter<'a, 'b, DB> | ||
38 | where | ||
39 | DB: HirDatabase, | ||
40 | { | ||
41 | pub fn write_joined<T: HirDisplay>( | ||
42 | &mut self, | ||
43 | iter: impl IntoIterator<Item = T>, | ||
44 | sep: &str, | ||
45 | ) -> fmt::Result { | ||
46 | let mut first = true; | ||
47 | for e in iter { | ||
48 | if !first { | ||
49 | write!(self, "{}", sep)?; | ||
50 | } | ||
51 | first = false; | ||
52 | e.hir_fmt(self)?; | ||
53 | } | ||
54 | Ok(()) | ||
55 | } | ||
56 | |||
57 | /// This allows using the `write!` macro directly with a `HirFormatter`. | ||
58 | pub fn write_fmt(&mut self, args: fmt::Arguments) -> fmt::Result { | ||
59 | // We write to a buffer first to track output size | ||
60 | self.buf.clear(); | ||
61 | fmt::write(&mut self.buf, args)?; | ||
62 | self.curr_size += self.buf.len(); | ||
63 | |||
64 | // Then we write to the internal formatter from the buffer | ||
65 | self.fmt.write_str(&self.buf) | ||
66 | } | ||
67 | |||
68 | pub fn should_truncate(&self) -> bool { | ||
69 | if let Some(max_size) = self.max_size { | ||
70 | self.curr_size >= max_size | ||
71 | } else { | ||
72 | false | ||
73 | } | ||
74 | } | ||
75 | } | ||
76 | |||
77 | pub struct HirDisplayWrapper<'a, DB, T>(&'a DB, &'a T, Option<usize>); | ||
78 | |||
79 | impl<'a, DB, T> fmt::Display for HirDisplayWrapper<'a, DB, T> | ||
80 | where | ||
81 | DB: HirDatabase, | ||
82 | T: HirDisplay, | ||
83 | { | ||
84 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
85 | self.1.hir_fmt(&mut HirFormatter { | ||
86 | db: self.0, | ||
87 | fmt: f, | ||
88 | buf: String::with_capacity(20), | ||
89 | curr_size: 0, | ||
90 | max_size: self.2, | ||
91 | }) | ||
92 | } | ||
93 | } | ||
diff --git a/crates/ra_hir/src/ty/infer.rs b/crates/ra_hir/src/ty/infer.rs deleted file mode 100644 index ddc7d262a..000000000 --- a/crates/ra_hir/src/ty/infer.rs +++ /dev/null | |||
@@ -1,748 +0,0 @@ | |||
1 | //! Type inference, i.e. the process of walking through the code and determining | ||
2 | //! the type of each expression and pattern. | ||
3 | //! | ||
4 | //! For type inference, compare the implementations in rustc (the various | ||
5 | //! check_* methods in librustc_typeck/check/mod.rs are a good entry point) and | ||
6 | //! IntelliJ-Rust (org.rust.lang.core.types.infer). Our entry point for | ||
7 | //! inference here is the `infer` function, which infers the types of all | ||
8 | //! expressions in a given function. | ||
9 | //! | ||
10 | //! During inference, types (i.e. the `Ty` struct) can contain type 'variables' | ||
11 | //! which represent currently unknown types; as we walk through the expressions, | ||
12 | //! we might determine that certain variables need to be equal to each other, or | ||
13 | //! to certain types. To record this, we use the union-find implementation from | ||
14 | //! the `ena` crate, which is extracted from rustc. | ||
15 | |||
16 | use std::borrow::Cow; | ||
17 | use std::mem; | ||
18 | use std::ops::Index; | ||
19 | use std::sync::Arc; | ||
20 | |||
21 | use ena::unify::{InPlaceUnificationTable, NoError, UnifyKey, UnifyValue}; | ||
22 | use rustc_hash::FxHashMap; | ||
23 | |||
24 | use hir_def::{ | ||
25 | data::{ConstData, FunctionData}, | ||
26 | path::known, | ||
27 | resolver::{HasResolver, Resolver, TypeNs}, | ||
28 | type_ref::{Mutability, TypeRef}, | ||
29 | AdtId, DefWithBodyId, | ||
30 | }; | ||
31 | use hir_expand::{diagnostics::DiagnosticSink, name}; | ||
32 | use ra_arena::map::ArenaMap; | ||
33 | use ra_prof::profile; | ||
34 | use test_utils::tested_by; | ||
35 | |||
36 | use super::{ | ||
37 | lower, | ||
38 | traits::{Guidance, Obligation, ProjectionPredicate, Solution}, | ||
39 | ApplicationTy, InEnvironment, ProjectionTy, Substs, TraitEnvironment, TraitRef, Ty, TypableDef, | ||
40 | TypeCtor, TypeWalk, Uncertain, | ||
41 | }; | ||
42 | use crate::{ | ||
43 | code_model::TypeAlias, | ||
44 | db::HirDatabase, | ||
45 | expr::{BindingAnnotation, Body, ExprId, PatId}, | ||
46 | ty::infer::diagnostics::InferenceDiagnostic, | ||
47 | Adt, AssocItem, DefWithBody, FloatTy, Function, IntTy, Path, StructField, Trait, VariantDef, | ||
48 | }; | ||
49 | |||
50 | macro_rules! ty_app { | ||
51 | ($ctor:pat, $param:pat) => { | ||
52 | crate::ty::Ty::Apply(crate::ty::ApplicationTy { ctor: $ctor, parameters: $param }) | ||
53 | }; | ||
54 | ($ctor:pat) => { | ||
55 | ty_app!($ctor, _) | ||
56 | }; | ||
57 | } | ||
58 | |||
59 | mod unify; | ||
60 | mod path; | ||
61 | mod expr; | ||
62 | mod pat; | ||
63 | mod coerce; | ||
64 | |||
65 | /// The entry point of type inference. | ||
66 | pub fn infer_query(db: &impl HirDatabase, def: DefWithBody) -> Arc<InferenceResult> { | ||
67 | let _p = profile("infer_query"); | ||
68 | let resolver = DefWithBodyId::from(def).resolver(db); | ||
69 | let mut ctx = InferenceContext::new(db, def, resolver); | ||
70 | |||
71 | match &def { | ||
72 | DefWithBody::Const(c) => ctx.collect_const(&db.const_data(c.id)), | ||
73 | DefWithBody::Function(f) => ctx.collect_fn(&db.function_data(f.id)), | ||
74 | DefWithBody::Static(s) => ctx.collect_const(&db.static_data(s.id)), | ||
75 | } | ||
76 | |||
77 | ctx.infer_body(); | ||
78 | |||
79 | Arc::new(ctx.resolve_all()) | ||
80 | } | ||
81 | |||
82 | #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] | ||
83 | enum ExprOrPatId { | ||
84 | ExprId(ExprId), | ||
85 | PatId(PatId), | ||
86 | } | ||
87 | |||
88 | impl_froms!(ExprOrPatId: ExprId, PatId); | ||
89 | |||
90 | /// Binding modes inferred for patterns. | ||
91 | /// https://doc.rust-lang.org/reference/patterns.html#binding-modes | ||
92 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] | ||
93 | enum BindingMode { | ||
94 | Move, | ||
95 | Ref(Mutability), | ||
96 | } | ||
97 | |||
98 | impl BindingMode { | ||
99 | pub fn convert(annotation: BindingAnnotation) -> BindingMode { | ||
100 | match annotation { | ||
101 | BindingAnnotation::Unannotated | BindingAnnotation::Mutable => BindingMode::Move, | ||
102 | BindingAnnotation::Ref => BindingMode::Ref(Mutability::Shared), | ||
103 | BindingAnnotation::RefMut => BindingMode::Ref(Mutability::Mut), | ||
104 | } | ||
105 | } | ||
106 | } | ||
107 | |||
108 | impl Default for BindingMode { | ||
109 | fn default() -> Self { | ||
110 | BindingMode::Move | ||
111 | } | ||
112 | } | ||
113 | |||
114 | /// A mismatch between an expected and an inferred type. | ||
115 | #[derive(Clone, PartialEq, Eq, Debug, Hash)] | ||
116 | pub struct TypeMismatch { | ||
117 | pub expected: Ty, | ||
118 | pub actual: Ty, | ||
119 | } | ||
120 | |||
121 | /// The result of type inference: A mapping from expressions and patterns to types. | ||
122 | #[derive(Clone, PartialEq, Eq, Debug, Default)] | ||
123 | pub struct InferenceResult { | ||
124 | /// For each method call expr, records the function it resolves to. | ||
125 | method_resolutions: FxHashMap<ExprId, Function>, | ||
126 | /// For each field access expr, records the field it resolves to. | ||
127 | field_resolutions: FxHashMap<ExprId, StructField>, | ||
128 | /// For each field in record literal, records the field it resolves to. | ||
129 | record_field_resolutions: FxHashMap<ExprId, StructField>, | ||
130 | /// For each struct literal, records the variant it resolves to. | ||
131 | variant_resolutions: FxHashMap<ExprOrPatId, VariantDef>, | ||
132 | /// For each associated item record what it resolves to | ||
133 | assoc_resolutions: FxHashMap<ExprOrPatId, AssocItem>, | ||
134 | diagnostics: Vec<InferenceDiagnostic>, | ||
135 | pub(super) type_of_expr: ArenaMap<ExprId, Ty>, | ||
136 | pub(super) type_of_pat: ArenaMap<PatId, Ty>, | ||
137 | pub(super) type_mismatches: ArenaMap<ExprId, TypeMismatch>, | ||
138 | } | ||
139 | |||
140 | impl InferenceResult { | ||
141 | pub fn method_resolution(&self, expr: ExprId) -> Option<Function> { | ||
142 | self.method_resolutions.get(&expr).copied() | ||
143 | } | ||
144 | pub fn field_resolution(&self, expr: ExprId) -> Option<StructField> { | ||
145 | self.field_resolutions.get(&expr).copied() | ||
146 | } | ||
147 | pub fn record_field_resolution(&self, expr: ExprId) -> Option<StructField> { | ||
148 | self.record_field_resolutions.get(&expr).copied() | ||
149 | } | ||
150 | pub fn variant_resolution_for_expr(&self, id: ExprId) -> Option<VariantDef> { | ||
151 | self.variant_resolutions.get(&id.into()).copied() | ||
152 | } | ||
153 | pub fn variant_resolution_for_pat(&self, id: PatId) -> Option<VariantDef> { | ||
154 | self.variant_resolutions.get(&id.into()).copied() | ||
155 | } | ||
156 | pub fn assoc_resolutions_for_expr(&self, id: ExprId) -> Option<AssocItem> { | ||
157 | self.assoc_resolutions.get(&id.into()).copied() | ||
158 | } | ||
159 | pub fn assoc_resolutions_for_pat(&self, id: PatId) -> Option<AssocItem> { | ||
160 | self.assoc_resolutions.get(&id.into()).copied() | ||
161 | } | ||
162 | pub fn type_mismatch_for_expr(&self, expr: ExprId) -> Option<&TypeMismatch> { | ||
163 | self.type_mismatches.get(expr) | ||
164 | } | ||
165 | pub(crate) fn add_diagnostics( | ||
166 | &self, | ||
167 | db: &impl HirDatabase, | ||
168 | owner: Function, | ||
169 | sink: &mut DiagnosticSink, | ||
170 | ) { | ||
171 | self.diagnostics.iter().for_each(|it| it.add_to(db, owner, sink)) | ||
172 | } | ||
173 | } | ||
174 | |||
175 | impl Index<ExprId> for InferenceResult { | ||
176 | type Output = Ty; | ||
177 | |||
178 | fn index(&self, expr: ExprId) -> &Ty { | ||
179 | self.type_of_expr.get(expr).unwrap_or(&Ty::Unknown) | ||
180 | } | ||
181 | } | ||
182 | |||
183 | impl Index<PatId> for InferenceResult { | ||
184 | type Output = Ty; | ||
185 | |||
186 | fn index(&self, pat: PatId) -> &Ty { | ||
187 | self.type_of_pat.get(pat).unwrap_or(&Ty::Unknown) | ||
188 | } | ||
189 | } | ||
190 | |||
191 | /// The inference context contains all information needed during type inference. | ||
192 | #[derive(Clone, Debug)] | ||
193 | struct InferenceContext<'a, D: HirDatabase> { | ||
194 | db: &'a D, | ||
195 | owner: DefWithBody, | ||
196 | body: Arc<Body>, | ||
197 | resolver: Resolver, | ||
198 | var_unification_table: InPlaceUnificationTable<TypeVarId>, | ||
199 | trait_env: Arc<TraitEnvironment>, | ||
200 | obligations: Vec<Obligation>, | ||
201 | result: InferenceResult, | ||
202 | /// The return type of the function being inferred. | ||
203 | return_ty: Ty, | ||
204 | |||
205 | /// Impls of `CoerceUnsized` used in coercion. | ||
206 | /// (from_ty_ctor, to_ty_ctor) => coerce_generic_index | ||
207 | // FIXME: Use trait solver for this. | ||
208 | // Chalk seems unable to work well with builtin impl of `Unsize` now. | ||
209 | coerce_unsized_map: FxHashMap<(TypeCtor, TypeCtor), usize>, | ||
210 | } | ||
211 | |||
212 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | ||
213 | fn new(db: &'a D, owner: DefWithBody, resolver: Resolver) -> Self { | ||
214 | InferenceContext { | ||
215 | result: InferenceResult::default(), | ||
216 | var_unification_table: InPlaceUnificationTable::new(), | ||
217 | obligations: Vec::default(), | ||
218 | return_ty: Ty::Unknown, // set in collect_fn_signature | ||
219 | trait_env: lower::trait_env(db, &resolver), | ||
220 | coerce_unsized_map: Self::init_coerce_unsized_map(db, &resolver), | ||
221 | db, | ||
222 | owner, | ||
223 | body: db.body(owner.into()), | ||
224 | resolver, | ||
225 | } | ||
226 | } | ||
227 | |||
228 | fn resolve_all(mut self) -> InferenceResult { | ||
229 | // FIXME resolve obligations as well (use Guidance if necessary) | ||
230 | let mut result = mem::replace(&mut self.result, InferenceResult::default()); | ||
231 | let mut tv_stack = Vec::new(); | ||
232 | for ty in result.type_of_expr.values_mut() { | ||
233 | let resolved = self.resolve_ty_completely(&mut tv_stack, mem::replace(ty, Ty::Unknown)); | ||
234 | *ty = resolved; | ||
235 | } | ||
236 | for ty in result.type_of_pat.values_mut() { | ||
237 | let resolved = self.resolve_ty_completely(&mut tv_stack, mem::replace(ty, Ty::Unknown)); | ||
238 | *ty = resolved; | ||
239 | } | ||
240 | result | ||
241 | } | ||
242 | |||
243 | fn write_expr_ty(&mut self, expr: ExprId, ty: Ty) { | ||
244 | self.result.type_of_expr.insert(expr, ty); | ||
245 | } | ||
246 | |||
247 | fn write_method_resolution(&mut self, expr: ExprId, func: Function) { | ||
248 | self.result.method_resolutions.insert(expr, func); | ||
249 | } | ||
250 | |||
251 | fn write_field_resolution(&mut self, expr: ExprId, field: StructField) { | ||
252 | self.result.field_resolutions.insert(expr, field); | ||
253 | } | ||
254 | |||
255 | fn write_variant_resolution(&mut self, id: ExprOrPatId, variant: VariantDef) { | ||
256 | self.result.variant_resolutions.insert(id, variant); | ||
257 | } | ||
258 | |||
259 | fn write_assoc_resolution(&mut self, id: ExprOrPatId, item: AssocItem) { | ||
260 | self.result.assoc_resolutions.insert(id, item); | ||
261 | } | ||
262 | |||
263 | fn write_pat_ty(&mut self, pat: PatId, ty: Ty) { | ||
264 | self.result.type_of_pat.insert(pat, ty); | ||
265 | } | ||
266 | |||
267 | fn push_diagnostic(&mut self, diagnostic: InferenceDiagnostic) { | ||
268 | self.result.diagnostics.push(diagnostic); | ||
269 | } | ||
270 | |||
271 | fn make_ty(&mut self, type_ref: &TypeRef) -> Ty { | ||
272 | let ty = Ty::from_hir( | ||
273 | self.db, | ||
274 | // FIXME use right resolver for block | ||
275 | &self.resolver, | ||
276 | type_ref, | ||
277 | ); | ||
278 | let ty = self.insert_type_vars(ty); | ||
279 | self.normalize_associated_types_in(ty) | ||
280 | } | ||
281 | |||
282 | fn unify_substs(&mut self, substs1: &Substs, substs2: &Substs, depth: usize) -> bool { | ||
283 | substs1.0.iter().zip(substs2.0.iter()).all(|(t1, t2)| self.unify_inner(t1, t2, depth)) | ||
284 | } | ||
285 | |||
286 | fn unify(&mut self, ty1: &Ty, ty2: &Ty) -> bool { | ||
287 | self.unify_inner(ty1, ty2, 0) | ||
288 | } | ||
289 | |||
290 | fn unify_inner(&mut self, ty1: &Ty, ty2: &Ty, depth: usize) -> bool { | ||
291 | if depth > 1000 { | ||
292 | // prevent stackoverflows | ||
293 | panic!("infinite recursion in unification"); | ||
294 | } | ||
295 | if ty1 == ty2 { | ||
296 | return true; | ||
297 | } | ||
298 | // try to resolve type vars first | ||
299 | let ty1 = self.resolve_ty_shallow(ty1); | ||
300 | let ty2 = self.resolve_ty_shallow(ty2); | ||
301 | match (&*ty1, &*ty2) { | ||
302 | (Ty::Apply(a_ty1), Ty::Apply(a_ty2)) if a_ty1.ctor == a_ty2.ctor => { | ||
303 | self.unify_substs(&a_ty1.parameters, &a_ty2.parameters, depth + 1) | ||
304 | } | ||
305 | _ => self.unify_inner_trivial(&ty1, &ty2), | ||
306 | } | ||
307 | } | ||
308 | |||
309 | fn unify_inner_trivial(&mut self, ty1: &Ty, ty2: &Ty) -> bool { | ||
310 | match (ty1, ty2) { | ||
311 | (Ty::Unknown, _) | (_, Ty::Unknown) => true, | ||
312 | |||
313 | (Ty::Infer(InferTy::TypeVar(tv1)), Ty::Infer(InferTy::TypeVar(tv2))) | ||
314 | | (Ty::Infer(InferTy::IntVar(tv1)), Ty::Infer(InferTy::IntVar(tv2))) | ||
315 | | (Ty::Infer(InferTy::FloatVar(tv1)), Ty::Infer(InferTy::FloatVar(tv2))) | ||
316 | | ( | ||
317 | Ty::Infer(InferTy::MaybeNeverTypeVar(tv1)), | ||
318 | Ty::Infer(InferTy::MaybeNeverTypeVar(tv2)), | ||
319 | ) => { | ||
320 | // both type vars are unknown since we tried to resolve them | ||
321 | self.var_unification_table.union(*tv1, *tv2); | ||
322 | true | ||
323 | } | ||
324 | |||
325 | // The order of MaybeNeverTypeVar matters here. | ||
326 | // Unifying MaybeNeverTypeVar and TypeVar will let the latter become MaybeNeverTypeVar. | ||
327 | // Unifying MaybeNeverTypeVar and other concrete type will let the former become it. | ||
328 | (Ty::Infer(InferTy::TypeVar(tv)), other) | ||
329 | | (other, Ty::Infer(InferTy::TypeVar(tv))) | ||
330 | | (Ty::Infer(InferTy::MaybeNeverTypeVar(tv)), other) | ||
331 | | (other, Ty::Infer(InferTy::MaybeNeverTypeVar(tv))) | ||
332 | | (Ty::Infer(InferTy::IntVar(tv)), other @ ty_app!(TypeCtor::Int(_))) | ||
333 | | (other @ ty_app!(TypeCtor::Int(_)), Ty::Infer(InferTy::IntVar(tv))) | ||
334 | | (Ty::Infer(InferTy::FloatVar(tv)), other @ ty_app!(TypeCtor::Float(_))) | ||
335 | | (other @ ty_app!(TypeCtor::Float(_)), Ty::Infer(InferTy::FloatVar(tv))) => { | ||
336 | // the type var is unknown since we tried to resolve it | ||
337 | self.var_unification_table.union_value(*tv, TypeVarValue::Known(other.clone())); | ||
338 | true | ||
339 | } | ||
340 | |||
341 | _ => false, | ||
342 | } | ||
343 | } | ||
344 | |||
345 | fn new_type_var(&mut self) -> Ty { | ||
346 | Ty::Infer(InferTy::TypeVar(self.var_unification_table.new_key(TypeVarValue::Unknown))) | ||
347 | } | ||
348 | |||
349 | fn new_integer_var(&mut self) -> Ty { | ||
350 | Ty::Infer(InferTy::IntVar(self.var_unification_table.new_key(TypeVarValue::Unknown))) | ||
351 | } | ||
352 | |||
353 | fn new_float_var(&mut self) -> Ty { | ||
354 | Ty::Infer(InferTy::FloatVar(self.var_unification_table.new_key(TypeVarValue::Unknown))) | ||
355 | } | ||
356 | |||
357 | fn new_maybe_never_type_var(&mut self) -> Ty { | ||
358 | Ty::Infer(InferTy::MaybeNeverTypeVar( | ||
359 | self.var_unification_table.new_key(TypeVarValue::Unknown), | ||
360 | )) | ||
361 | } | ||
362 | |||
363 | /// Replaces Ty::Unknown by a new type var, so we can maybe still infer it. | ||
364 | fn insert_type_vars_shallow(&mut self, ty: Ty) -> Ty { | ||
365 | match ty { | ||
366 | Ty::Unknown => self.new_type_var(), | ||
367 | Ty::Apply(ApplicationTy { ctor: TypeCtor::Int(Uncertain::Unknown), .. }) => { | ||
368 | self.new_integer_var() | ||
369 | } | ||
370 | Ty::Apply(ApplicationTy { ctor: TypeCtor::Float(Uncertain::Unknown), .. }) => { | ||
371 | self.new_float_var() | ||
372 | } | ||
373 | _ => ty, | ||
374 | } | ||
375 | } | ||
376 | |||
377 | fn insert_type_vars(&mut self, ty: Ty) -> Ty { | ||
378 | ty.fold(&mut |ty| self.insert_type_vars_shallow(ty)) | ||
379 | } | ||
380 | |||
381 | fn resolve_obligations_as_possible(&mut self) { | ||
382 | let obligations = mem::replace(&mut self.obligations, Vec::new()); | ||
383 | for obligation in obligations { | ||
384 | let in_env = InEnvironment::new(self.trait_env.clone(), obligation.clone()); | ||
385 | let canonicalized = self.canonicalizer().canonicalize_obligation(in_env); | ||
386 | let solution = self | ||
387 | .db | ||
388 | .trait_solve(self.resolver.krate().unwrap().into(), canonicalized.value.clone()); | ||
389 | |||
390 | match solution { | ||
391 | Some(Solution::Unique(substs)) => { | ||
392 | canonicalized.apply_solution(self, substs.0); | ||
393 | } | ||
394 | Some(Solution::Ambig(Guidance::Definite(substs))) => { | ||
395 | canonicalized.apply_solution(self, substs.0); | ||
396 | self.obligations.push(obligation); | ||
397 | } | ||
398 | Some(_) => { | ||
399 | // FIXME use this when trying to resolve everything at the end | ||
400 | self.obligations.push(obligation); | ||
401 | } | ||
402 | None => { | ||
403 | // FIXME obligation cannot be fulfilled => diagnostic | ||
404 | } | ||
405 | }; | ||
406 | } | ||
407 | } | ||
408 | |||
409 | /// Resolves the type as far as currently possible, replacing type variables | ||
410 | /// by their known types. All types returned by the infer_* functions should | ||
411 | /// be resolved as far as possible, i.e. contain no type variables with | ||
412 | /// known type. | ||
413 | fn resolve_ty_as_possible(&mut self, tv_stack: &mut Vec<TypeVarId>, ty: Ty) -> Ty { | ||
414 | self.resolve_obligations_as_possible(); | ||
415 | |||
416 | ty.fold(&mut |ty| match ty { | ||
417 | Ty::Infer(tv) => { | ||
418 | let inner = tv.to_inner(); | ||
419 | if tv_stack.contains(&inner) { | ||
420 | tested_by!(type_var_cycles_resolve_as_possible); | ||
421 | // recursive type | ||
422 | return tv.fallback_value(); | ||
423 | } | ||
424 | if let Some(known_ty) = | ||
425 | self.var_unification_table.inlined_probe_value(inner).known() | ||
426 | { | ||
427 | // known_ty may contain other variables that are known by now | ||
428 | tv_stack.push(inner); | ||
429 | let result = self.resolve_ty_as_possible(tv_stack, known_ty.clone()); | ||
430 | tv_stack.pop(); | ||
431 | result | ||
432 | } else { | ||
433 | ty | ||
434 | } | ||
435 | } | ||
436 | _ => ty, | ||
437 | }) | ||
438 | } | ||
439 | |||
440 | /// If `ty` is a type variable with known type, returns that type; | ||
441 | /// otherwise, return ty. | ||
442 | fn resolve_ty_shallow<'b>(&mut self, ty: &'b Ty) -> Cow<'b, Ty> { | ||
443 | let mut ty = Cow::Borrowed(ty); | ||
444 | // The type variable could resolve to a int/float variable. Hence try | ||
445 | // resolving up to three times; each type of variable shouldn't occur | ||
446 | // more than once | ||
447 | for i in 0..3 { | ||
448 | if i > 0 { | ||
449 | tested_by!(type_var_resolves_to_int_var); | ||
450 | } | ||
451 | match &*ty { | ||
452 | Ty::Infer(tv) => { | ||
453 | let inner = tv.to_inner(); | ||
454 | match self.var_unification_table.inlined_probe_value(inner).known() { | ||
455 | Some(known_ty) => { | ||
456 | // The known_ty can't be a type var itself | ||
457 | ty = Cow::Owned(known_ty.clone()); | ||
458 | } | ||
459 | _ => return ty, | ||
460 | } | ||
461 | } | ||
462 | _ => return ty, | ||
463 | } | ||
464 | } | ||
465 | log::error!("Inference variable still not resolved: {:?}", ty); | ||
466 | ty | ||
467 | } | ||
468 | |||
469 | /// Recurses through the given type, normalizing associated types mentioned | ||
470 | /// in it by replacing them by type variables and registering obligations to | ||
471 | /// resolve later. This should be done once for every type we get from some | ||
472 | /// type annotation (e.g. from a let type annotation, field type or function | ||
473 | /// call). `make_ty` handles this already, but e.g. for field types we need | ||
474 | /// to do it as well. | ||
475 | fn normalize_associated_types_in(&mut self, ty: Ty) -> Ty { | ||
476 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
477 | ty.fold(&mut |ty| match ty { | ||
478 | Ty::Projection(proj_ty) => self.normalize_projection_ty(proj_ty), | ||
479 | _ => ty, | ||
480 | }) | ||
481 | } | ||
482 | |||
483 | fn normalize_projection_ty(&mut self, proj_ty: ProjectionTy) -> Ty { | ||
484 | let var = self.new_type_var(); | ||
485 | let predicate = ProjectionPredicate { projection_ty: proj_ty, ty: var.clone() }; | ||
486 | let obligation = Obligation::Projection(predicate); | ||
487 | self.obligations.push(obligation); | ||
488 | var | ||
489 | } | ||
490 | |||
491 | /// Resolves the type completely; type variables without known type are | ||
492 | /// replaced by Ty::Unknown. | ||
493 | fn resolve_ty_completely(&mut self, tv_stack: &mut Vec<TypeVarId>, ty: Ty) -> Ty { | ||
494 | ty.fold(&mut |ty| match ty { | ||
495 | Ty::Infer(tv) => { | ||
496 | let inner = tv.to_inner(); | ||
497 | if tv_stack.contains(&inner) { | ||
498 | tested_by!(type_var_cycles_resolve_completely); | ||
499 | // recursive type | ||
500 | return tv.fallback_value(); | ||
501 | } | ||
502 | if let Some(known_ty) = | ||
503 | self.var_unification_table.inlined_probe_value(inner).known() | ||
504 | { | ||
505 | // known_ty may contain other variables that are known by now | ||
506 | tv_stack.push(inner); | ||
507 | let result = self.resolve_ty_completely(tv_stack, known_ty.clone()); | ||
508 | tv_stack.pop(); | ||
509 | result | ||
510 | } else { | ||
511 | tv.fallback_value() | ||
512 | } | ||
513 | } | ||
514 | _ => ty, | ||
515 | }) | ||
516 | } | ||
517 | |||
518 | fn resolve_variant(&mut self, path: Option<&Path>) -> (Ty, Option<VariantDef>) { | ||
519 | let path = match path { | ||
520 | Some(path) => path, | ||
521 | None => return (Ty::Unknown, None), | ||
522 | }; | ||
523 | let resolver = &self.resolver; | ||
524 | let def: TypableDef = | ||
525 | // FIXME: this should resolve assoc items as well, see this example: | ||
526 | // https://play.rust-lang.org/?gist=087992e9e22495446c01c0d4e2d69521 | ||
527 | match resolver.resolve_path_in_type_ns_fully(self.db, &path) { | ||
528 | Some(TypeNs::AdtId(AdtId::StructId(it))) => it.into(), | ||
529 | Some(TypeNs::AdtId(AdtId::UnionId(it))) => it.into(), | ||
530 | Some(TypeNs::AdtSelfType(adt)) => adt.into(), | ||
531 | Some(TypeNs::EnumVariantId(it)) => it.into(), | ||
532 | Some(TypeNs::TypeAliasId(it)) => it.into(), | ||
533 | |||
534 | Some(TypeNs::SelfType(_)) | | ||
535 | Some(TypeNs::GenericParam(_)) | | ||
536 | Some(TypeNs::BuiltinType(_)) | | ||
537 | Some(TypeNs::TraitId(_)) | | ||
538 | Some(TypeNs::AdtId(AdtId::EnumId(_))) | | ||
539 | None => { | ||
540 | return (Ty::Unknown, None) | ||
541 | } | ||
542 | }; | ||
543 | // FIXME remove the duplication between here and `Ty::from_path`? | ||
544 | let substs = Ty::substs_from_path(self.db, resolver, path, def); | ||
545 | match def { | ||
546 | TypableDef::Adt(Adt::Struct(s)) => { | ||
547 | let ty = s.ty(self.db); | ||
548 | let ty = self.insert_type_vars(ty.apply_substs(substs)); | ||
549 | (ty, Some(s.into())) | ||
550 | } | ||
551 | TypableDef::EnumVariant(var) => { | ||
552 | let ty = var.parent_enum(self.db).ty(self.db); | ||
553 | let ty = self.insert_type_vars(ty.apply_substs(substs)); | ||
554 | (ty, Some(var.into())) | ||
555 | } | ||
556 | TypableDef::Adt(Adt::Enum(_)) | ||
557 | | TypableDef::Adt(Adt::Union(_)) | ||
558 | | TypableDef::TypeAlias(_) | ||
559 | | TypableDef::Function(_) | ||
560 | | TypableDef::Const(_) | ||
561 | | TypableDef::Static(_) | ||
562 | | TypableDef::BuiltinType(_) => (Ty::Unknown, None), | ||
563 | } | ||
564 | } | ||
565 | |||
566 | fn collect_const(&mut self, data: &ConstData) { | ||
567 | self.return_ty = self.make_ty(&data.type_ref); | ||
568 | } | ||
569 | |||
570 | fn collect_fn(&mut self, data: &FunctionData) { | ||
571 | let body = Arc::clone(&self.body); // avoid borrow checker problem | ||
572 | for (type_ref, pat) in data.params.iter().zip(body.params.iter()) { | ||
573 | let ty = self.make_ty(type_ref); | ||
574 | |||
575 | self.infer_pat(*pat, &ty, BindingMode::default()); | ||
576 | } | ||
577 | self.return_ty = self.make_ty(&data.ret_type); | ||
578 | } | ||
579 | |||
580 | fn infer_body(&mut self) { | ||
581 | self.infer_expr(self.body.body_expr, &Expectation::has_type(self.return_ty.clone())); | ||
582 | } | ||
583 | |||
584 | fn resolve_into_iter_item(&self) -> Option<TypeAlias> { | ||
585 | let path = known::std_iter_into_iterator(); | ||
586 | let trait_: Trait = self.resolver.resolve_known_trait(self.db, &path)?.into(); | ||
587 | trait_.associated_type_by_name(self.db, &name::ITEM_TYPE) | ||
588 | } | ||
589 | |||
590 | fn resolve_ops_try_ok(&self) -> Option<TypeAlias> { | ||
591 | let path = known::std_ops_try(); | ||
592 | let trait_: Trait = self.resolver.resolve_known_trait(self.db, &path)?.into(); | ||
593 | trait_.associated_type_by_name(self.db, &name::OK_TYPE) | ||
594 | } | ||
595 | |||
596 | fn resolve_future_future_output(&self) -> Option<TypeAlias> { | ||
597 | let path = known::std_future_future(); | ||
598 | let trait_: Trait = self.resolver.resolve_known_trait(self.db, &path)?.into(); | ||
599 | trait_.associated_type_by_name(self.db, &name::OUTPUT_TYPE) | ||
600 | } | ||
601 | |||
602 | fn resolve_boxed_box(&self) -> Option<Adt> { | ||
603 | let path = known::std_boxed_box(); | ||
604 | let struct_ = self.resolver.resolve_known_struct(self.db, &path)?; | ||
605 | Some(Adt::Struct(struct_.into())) | ||
606 | } | ||
607 | } | ||
608 | |||
609 | /// The ID of a type variable. | ||
610 | #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] | ||
611 | pub struct TypeVarId(pub(super) u32); | ||
612 | |||
613 | impl UnifyKey for TypeVarId { | ||
614 | type Value = TypeVarValue; | ||
615 | |||
616 | fn index(&self) -> u32 { | ||
617 | self.0 | ||
618 | } | ||
619 | |||
620 | fn from_index(i: u32) -> Self { | ||
621 | TypeVarId(i) | ||
622 | } | ||
623 | |||
624 | fn tag() -> &'static str { | ||
625 | "TypeVarId" | ||
626 | } | ||
627 | } | ||
628 | |||
629 | /// The value of a type variable: either we already know the type, or we don't | ||
630 | /// know it yet. | ||
631 | #[derive(Clone, PartialEq, Eq, Debug)] | ||
632 | pub enum TypeVarValue { | ||
633 | Known(Ty), | ||
634 | Unknown, | ||
635 | } | ||
636 | |||
637 | impl TypeVarValue { | ||
638 | fn known(&self) -> Option<&Ty> { | ||
639 | match self { | ||
640 | TypeVarValue::Known(ty) => Some(ty), | ||
641 | TypeVarValue::Unknown => None, | ||
642 | } | ||
643 | } | ||
644 | } | ||
645 | |||
646 | impl UnifyValue for TypeVarValue { | ||
647 | type Error = NoError; | ||
648 | |||
649 | fn unify_values(value1: &Self, value2: &Self) -> Result<Self, NoError> { | ||
650 | match (value1, value2) { | ||
651 | // We should never equate two type variables, both of which have | ||
652 | // known types. Instead, we recursively equate those types. | ||
653 | (TypeVarValue::Known(t1), TypeVarValue::Known(t2)) => panic!( | ||
654 | "equating two type variables, both of which have known types: {:?} and {:?}", | ||
655 | t1, t2 | ||
656 | ), | ||
657 | |||
658 | // If one side is known, prefer that one. | ||
659 | (TypeVarValue::Known(..), TypeVarValue::Unknown) => Ok(value1.clone()), | ||
660 | (TypeVarValue::Unknown, TypeVarValue::Known(..)) => Ok(value2.clone()), | ||
661 | |||
662 | (TypeVarValue::Unknown, TypeVarValue::Unknown) => Ok(TypeVarValue::Unknown), | ||
663 | } | ||
664 | } | ||
665 | } | ||
666 | |||
667 | /// The kinds of placeholders we need during type inference. There's separate | ||
668 | /// values for general types, and for integer and float variables. The latter | ||
669 | /// two are used for inference of literal values (e.g. `100` could be one of | ||
670 | /// several integer types). | ||
671 | #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] | ||
672 | pub enum InferTy { | ||
673 | TypeVar(TypeVarId), | ||
674 | IntVar(TypeVarId), | ||
675 | FloatVar(TypeVarId), | ||
676 | MaybeNeverTypeVar(TypeVarId), | ||
677 | } | ||
678 | |||
679 | impl InferTy { | ||
680 | fn to_inner(self) -> TypeVarId { | ||
681 | match self { | ||
682 | InferTy::TypeVar(ty) | ||
683 | | InferTy::IntVar(ty) | ||
684 | | InferTy::FloatVar(ty) | ||
685 | | InferTy::MaybeNeverTypeVar(ty) => ty, | ||
686 | } | ||
687 | } | ||
688 | |||
689 | fn fallback_value(self) -> Ty { | ||
690 | match self { | ||
691 | InferTy::TypeVar(..) => Ty::Unknown, | ||
692 | InferTy::IntVar(..) => Ty::simple(TypeCtor::Int(Uncertain::Known(IntTy::i32()))), | ||
693 | InferTy::FloatVar(..) => Ty::simple(TypeCtor::Float(Uncertain::Known(FloatTy::f64()))), | ||
694 | InferTy::MaybeNeverTypeVar(..) => Ty::simple(TypeCtor::Never), | ||
695 | } | ||
696 | } | ||
697 | } | ||
698 | |||
699 | /// When inferring an expression, we propagate downward whatever type hint we | ||
700 | /// are able in the form of an `Expectation`. | ||
701 | #[derive(Clone, PartialEq, Eq, Debug)] | ||
702 | struct Expectation { | ||
703 | ty: Ty, | ||
704 | // FIXME: In some cases, we need to be aware whether the expectation is that | ||
705 | // the type match exactly what we passed, or whether it just needs to be | ||
706 | // coercible to the expected type. See Expectation::rvalue_hint in rustc. | ||
707 | } | ||
708 | |||
709 | impl Expectation { | ||
710 | /// The expectation that the type of the expression needs to equal the given | ||
711 | /// type. | ||
712 | fn has_type(ty: Ty) -> Self { | ||
713 | Expectation { ty } | ||
714 | } | ||
715 | |||
716 | /// This expresses no expectation on the type. | ||
717 | fn none() -> Self { | ||
718 | Expectation { ty: Ty::Unknown } | ||
719 | } | ||
720 | } | ||
721 | |||
722 | mod diagnostics { | ||
723 | use hir_expand::diagnostics::DiagnosticSink; | ||
724 | |||
725 | use crate::{db::HirDatabase, diagnostics::NoSuchField, expr::ExprId, Function, HasSource}; | ||
726 | |||
727 | #[derive(Debug, PartialEq, Eq, Clone)] | ||
728 | pub(super) enum InferenceDiagnostic { | ||
729 | NoSuchField { expr: ExprId, field: usize }, | ||
730 | } | ||
731 | |||
732 | impl InferenceDiagnostic { | ||
733 | pub(super) fn add_to( | ||
734 | &self, | ||
735 | db: &impl HirDatabase, | ||
736 | owner: Function, | ||
737 | sink: &mut DiagnosticSink, | ||
738 | ) { | ||
739 | match self { | ||
740 | InferenceDiagnostic::NoSuchField { expr, field } => { | ||
741 | let file = owner.source(db).file_id; | ||
742 | let field = owner.body_source_map(db).field_syntax(*expr, *field); | ||
743 | sink.push(NoSuchField { file, field }) | ||
744 | } | ||
745 | } | ||
746 | } | ||
747 | } | ||
748 | } | ||
diff --git a/crates/ra_hir/src/ty/infer/coerce.rs b/crates/ra_hir/src/ty/infer/coerce.rs deleted file mode 100644 index 54765da35..000000000 --- a/crates/ra_hir/src/ty/infer/coerce.rs +++ /dev/null | |||
@@ -1,339 +0,0 @@ | |||
1 | //! Coercion logic. Coercions are certain type conversions that can implicitly | ||
2 | //! happen in certain places, e.g. weakening `&mut` to `&` or deref coercions | ||
3 | //! like going from `&Vec<T>` to `&[T]`. | ||
4 | //! | ||
5 | //! See: https://doc.rust-lang.org/nomicon/coercions.html | ||
6 | |||
7 | use hir_def::{lang_item::LangItemTarget, resolver::Resolver}; | ||
8 | use rustc_hash::FxHashMap; | ||
9 | use test_utils::tested_by; | ||
10 | |||
11 | use crate::{ | ||
12 | db::HirDatabase, | ||
13 | ty::{autoderef, Substs, Ty, TypeCtor, TypeWalk}, | ||
14 | Adt, Mutability, | ||
15 | }; | ||
16 | |||
17 | use super::{InferTy, InferenceContext, TypeVarValue}; | ||
18 | |||
19 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | ||
20 | /// Unify two types, but may coerce the first one to the second one | ||
21 | /// using "implicit coercion rules" if needed. | ||
22 | pub(super) fn coerce(&mut self, from_ty: &Ty, to_ty: &Ty) -> bool { | ||
23 | let from_ty = self.resolve_ty_shallow(from_ty).into_owned(); | ||
24 | let to_ty = self.resolve_ty_shallow(to_ty); | ||
25 | self.coerce_inner(from_ty, &to_ty) | ||
26 | } | ||
27 | |||
28 | /// Merge two types from different branches, with possible implicit coerce. | ||
29 | /// | ||
30 | /// Note that it is only possible that one type are coerced to another. | ||
31 | /// Coercing both types to another least upper bound type is not possible in rustc, | ||
32 | /// which will simply result in "incompatible types" error. | ||
33 | pub(super) fn coerce_merge_branch<'t>(&mut self, ty1: &Ty, ty2: &Ty) -> Ty { | ||
34 | if self.coerce(ty1, ty2) { | ||
35 | ty2.clone() | ||
36 | } else if self.coerce(ty2, ty1) { | ||
37 | ty1.clone() | ||
38 | } else { | ||
39 | tested_by!(coerce_merge_fail_fallback); | ||
40 | // For incompatible types, we use the latter one as result | ||
41 | // to be better recovery for `if` without `else`. | ||
42 | ty2.clone() | ||
43 | } | ||
44 | } | ||
45 | |||
46 | pub(super) fn init_coerce_unsized_map( | ||
47 | db: &'a D, | ||
48 | resolver: &Resolver, | ||
49 | ) -> FxHashMap<(TypeCtor, TypeCtor), usize> { | ||
50 | let krate = resolver.krate().unwrap(); | ||
51 | let impls = match db.lang_item(krate.into(), "coerce_unsized".into()) { | ||
52 | Some(LangItemTarget::TraitId(trait_)) => { | ||
53 | db.impls_for_trait(krate.into(), trait_.into()) | ||
54 | } | ||
55 | _ => return FxHashMap::default(), | ||
56 | }; | ||
57 | |||
58 | impls | ||
59 | .iter() | ||
60 | .filter_map(|impl_block| { | ||
61 | // `CoerseUnsized` has one generic parameter for the target type. | ||
62 | let trait_ref = impl_block.target_trait_ref(db)?; | ||
63 | let cur_from_ty = trait_ref.substs.0.get(0)?; | ||
64 | let cur_to_ty = trait_ref.substs.0.get(1)?; | ||
65 | |||
66 | match (&cur_from_ty, cur_to_ty) { | ||
67 | (ty_app!(ctor1, st1), ty_app!(ctor2, st2)) => { | ||
68 | // FIXME: We return the first non-equal bound as the type parameter to coerce to unsized type. | ||
69 | // This works for smart-pointer-like coercion, which covers all impls from std. | ||
70 | st1.iter().zip(st2.iter()).enumerate().find_map(|(i, (ty1, ty2))| { | ||
71 | match (ty1, ty2) { | ||
72 | (Ty::Param { idx: p1, .. }, Ty::Param { idx: p2, .. }) | ||
73 | if p1 != p2 => | ||
74 | { | ||
75 | Some(((*ctor1, *ctor2), i)) | ||
76 | } | ||
77 | _ => None, | ||
78 | } | ||
79 | }) | ||
80 | } | ||
81 | _ => None, | ||
82 | } | ||
83 | }) | ||
84 | .collect() | ||
85 | } | ||
86 | |||
87 | fn coerce_inner(&mut self, mut from_ty: Ty, to_ty: &Ty) -> bool { | ||
88 | match (&from_ty, to_ty) { | ||
89 | // Never type will make type variable to fallback to Never Type instead of Unknown. | ||
90 | (ty_app!(TypeCtor::Never), Ty::Infer(InferTy::TypeVar(tv))) => { | ||
91 | let var = self.new_maybe_never_type_var(); | ||
92 | self.var_unification_table.union_value(*tv, TypeVarValue::Known(var)); | ||
93 | return true; | ||
94 | } | ||
95 | (ty_app!(TypeCtor::Never), _) => return true, | ||
96 | |||
97 | // Trivial cases, this should go after `never` check to | ||
98 | // avoid infer result type to be never | ||
99 | _ => { | ||
100 | if self.unify_inner_trivial(&from_ty, &to_ty) { | ||
101 | return true; | ||
102 | } | ||
103 | } | ||
104 | } | ||
105 | |||
106 | // Pointer weakening and function to pointer | ||
107 | match (&mut from_ty, to_ty) { | ||
108 | // `*mut T`, `&mut T, `&T`` -> `*const T` | ||
109 | // `&mut T` -> `&T` | ||
110 | // `&mut T` -> `*mut T` | ||
111 | (ty_app!(c1@TypeCtor::RawPtr(_)), ty_app!(c2@TypeCtor::RawPtr(Mutability::Shared))) | ||
112 | | (ty_app!(c1@TypeCtor::Ref(_)), ty_app!(c2@TypeCtor::RawPtr(Mutability::Shared))) | ||
113 | | (ty_app!(c1@TypeCtor::Ref(_)), ty_app!(c2@TypeCtor::Ref(Mutability::Shared))) | ||
114 | | (ty_app!(c1@TypeCtor::Ref(Mutability::Mut)), ty_app!(c2@TypeCtor::RawPtr(_))) => { | ||
115 | *c1 = *c2; | ||
116 | } | ||
117 | |||
118 | // Illegal mutablity conversion | ||
119 | ( | ||
120 | ty_app!(TypeCtor::RawPtr(Mutability::Shared)), | ||
121 | ty_app!(TypeCtor::RawPtr(Mutability::Mut)), | ||
122 | ) | ||
123 | | ( | ||
124 | ty_app!(TypeCtor::Ref(Mutability::Shared)), | ||
125 | ty_app!(TypeCtor::Ref(Mutability::Mut)), | ||
126 | ) => return false, | ||
127 | |||
128 | // `{function_type}` -> `fn()` | ||
129 | (ty_app!(TypeCtor::FnDef(_)), ty_app!(TypeCtor::FnPtr { .. })) => { | ||
130 | match from_ty.callable_sig(self.db) { | ||
131 | None => return false, | ||
132 | Some(sig) => { | ||
133 | let num_args = sig.params_and_return.len() as u16 - 1; | ||
134 | from_ty = | ||
135 | Ty::apply(TypeCtor::FnPtr { num_args }, Substs(sig.params_and_return)); | ||
136 | } | ||
137 | } | ||
138 | } | ||
139 | |||
140 | _ => {} | ||
141 | } | ||
142 | |||
143 | if let Some(ret) = self.try_coerce_unsized(&from_ty, &to_ty) { | ||
144 | return ret; | ||
145 | } | ||
146 | |||
147 | // Auto Deref if cannot coerce | ||
148 | match (&from_ty, to_ty) { | ||
149 | // FIXME: DerefMut | ||
150 | (ty_app!(TypeCtor::Ref(_), st1), ty_app!(TypeCtor::Ref(_), st2)) => { | ||
151 | self.unify_autoderef_behind_ref(&st1[0], &st2[0]) | ||
152 | } | ||
153 | |||
154 | // Otherwise, normal unify | ||
155 | _ => self.unify(&from_ty, to_ty), | ||
156 | } | ||
157 | } | ||
158 | |||
159 | /// Coerce a type using `from_ty: CoerceUnsized<ty_ty>` | ||
160 | /// | ||
161 | /// See: https://doc.rust-lang.org/nightly/std/marker/trait.CoerceUnsized.html | ||
162 | fn try_coerce_unsized(&mut self, from_ty: &Ty, to_ty: &Ty) -> Option<bool> { | ||
163 | let (ctor1, st1, ctor2, st2) = match (from_ty, to_ty) { | ||
164 | (ty_app!(ctor1, st1), ty_app!(ctor2, st2)) => (ctor1, st1, ctor2, st2), | ||
165 | _ => return None, | ||
166 | }; | ||
167 | |||
168 | let coerce_generic_index = *self.coerce_unsized_map.get(&(*ctor1, *ctor2))?; | ||
169 | |||
170 | // Check `Unsize` first | ||
171 | match self.check_unsize_and_coerce( | ||
172 | st1.0.get(coerce_generic_index)?, | ||
173 | st2.0.get(coerce_generic_index)?, | ||
174 | 0, | ||
175 | ) { | ||
176 | Some(true) => {} | ||
177 | ret => return ret, | ||
178 | } | ||
179 | |||
180 | let ret = st1 | ||
181 | .iter() | ||
182 | .zip(st2.iter()) | ||
183 | .enumerate() | ||
184 | .filter(|&(idx, _)| idx != coerce_generic_index) | ||
185 | .all(|(_, (ty1, ty2))| self.unify(ty1, ty2)); | ||
186 | |||
187 | Some(ret) | ||
188 | } | ||
189 | |||
190 | /// Check if `from_ty: Unsize<to_ty>`, and coerce to `to_ty` if it holds. | ||
191 | /// | ||
192 | /// It should not be directly called. It is only used by `try_coerce_unsized`. | ||
193 | /// | ||
194 | /// See: https://doc.rust-lang.org/nightly/std/marker/trait.Unsize.html | ||
195 | fn check_unsize_and_coerce(&mut self, from_ty: &Ty, to_ty: &Ty, depth: usize) -> Option<bool> { | ||
196 | if depth > 1000 { | ||
197 | panic!("Infinite recursion in coercion"); | ||
198 | } | ||
199 | |||
200 | match (&from_ty, &to_ty) { | ||
201 | // `[T; N]` -> `[T]` | ||
202 | (ty_app!(TypeCtor::Array, st1), ty_app!(TypeCtor::Slice, st2)) => { | ||
203 | Some(self.unify(&st1[0], &st2[0])) | ||
204 | } | ||
205 | |||
206 | // `T` -> `dyn Trait` when `T: Trait` | ||
207 | (_, Ty::Dyn(_)) => { | ||
208 | // FIXME: Check predicates | ||
209 | Some(true) | ||
210 | } | ||
211 | |||
212 | // `(..., T)` -> `(..., U)` when `T: Unsize<U>` | ||
213 | ( | ||
214 | ty_app!(TypeCtor::Tuple { cardinality: len1 }, st1), | ||
215 | ty_app!(TypeCtor::Tuple { cardinality: len2 }, st2), | ||
216 | ) => { | ||
217 | if len1 != len2 || *len1 == 0 { | ||
218 | return None; | ||
219 | } | ||
220 | |||
221 | match self.check_unsize_and_coerce( | ||
222 | st1.last().unwrap(), | ||
223 | st2.last().unwrap(), | ||
224 | depth + 1, | ||
225 | ) { | ||
226 | Some(true) => {} | ||
227 | ret => return ret, | ||
228 | } | ||
229 | |||
230 | let ret = st1[..st1.len() - 1] | ||
231 | .iter() | ||
232 | .zip(&st2[..st2.len() - 1]) | ||
233 | .all(|(ty1, ty2)| self.unify(ty1, ty2)); | ||
234 | |||
235 | Some(ret) | ||
236 | } | ||
237 | |||
238 | // Foo<..., T, ...> is Unsize<Foo<..., U, ...>> if: | ||
239 | // - T: Unsize<U> | ||
240 | // - Foo is a struct | ||
241 | // - Only the last field of Foo has a type involving T | ||
242 | // - T is not part of the type of any other fields | ||
243 | // - Bar<T>: Unsize<Bar<U>>, if the last field of Foo has type Bar<T> | ||
244 | ( | ||
245 | ty_app!(TypeCtor::Adt(Adt::Struct(struct1)), st1), | ||
246 | ty_app!(TypeCtor::Adt(Adt::Struct(struct2)), st2), | ||
247 | ) if struct1 == struct2 => { | ||
248 | let field_tys = self.db.field_types(struct1.id.into()); | ||
249 | let struct_data = self.db.struct_data(struct1.id.0); | ||
250 | |||
251 | let mut fields = struct_data.variant_data.fields().iter(); | ||
252 | let (last_field_id, _data) = fields.next_back()?; | ||
253 | |||
254 | // Get the generic parameter involved in the last field. | ||
255 | let unsize_generic_index = { | ||
256 | let mut index = None; | ||
257 | let mut multiple_param = false; | ||
258 | field_tys[last_field_id].walk(&mut |ty| match ty { | ||
259 | &Ty::Param { idx, .. } => { | ||
260 | if index.is_none() { | ||
261 | index = Some(idx); | ||
262 | } else if Some(idx) != index { | ||
263 | multiple_param = true; | ||
264 | } | ||
265 | } | ||
266 | _ => {} | ||
267 | }); | ||
268 | |||
269 | if multiple_param { | ||
270 | return None; | ||
271 | } | ||
272 | index? | ||
273 | }; | ||
274 | |||
275 | // Check other fields do not involve it. | ||
276 | let mut multiple_used = false; | ||
277 | fields.for_each(|(field_id, _data)| { | ||
278 | field_tys[field_id].walk(&mut |ty| match ty { | ||
279 | &Ty::Param { idx, .. } if idx == unsize_generic_index => { | ||
280 | multiple_used = true | ||
281 | } | ||
282 | _ => {} | ||
283 | }) | ||
284 | }); | ||
285 | if multiple_used { | ||
286 | return None; | ||
287 | } | ||
288 | |||
289 | let unsize_generic_index = unsize_generic_index as usize; | ||
290 | |||
291 | // Check `Unsize` first | ||
292 | match self.check_unsize_and_coerce( | ||
293 | st1.get(unsize_generic_index)?, | ||
294 | st2.get(unsize_generic_index)?, | ||
295 | depth + 1, | ||
296 | ) { | ||
297 | Some(true) => {} | ||
298 | ret => return ret, | ||
299 | } | ||
300 | |||
301 | // Then unify other parameters | ||
302 | let ret = st1 | ||
303 | .iter() | ||
304 | .zip(st2.iter()) | ||
305 | .enumerate() | ||
306 | .filter(|&(idx, _)| idx != unsize_generic_index) | ||
307 | .all(|(_, (ty1, ty2))| self.unify(ty1, ty2)); | ||
308 | |||
309 | Some(ret) | ||
310 | } | ||
311 | |||
312 | _ => None, | ||
313 | } | ||
314 | } | ||
315 | |||
316 | /// Unify `from_ty` to `to_ty` with optional auto Deref | ||
317 | /// | ||
318 | /// Note that the parameters are already stripped the outer reference. | ||
319 | fn unify_autoderef_behind_ref(&mut self, from_ty: &Ty, to_ty: &Ty) -> bool { | ||
320 | let canonicalized = self.canonicalizer().canonicalize_ty(from_ty.clone()); | ||
321 | let to_ty = self.resolve_ty_shallow(&to_ty); | ||
322 | // FIXME: Auto DerefMut | ||
323 | for derefed_ty in | ||
324 | autoderef::autoderef(self.db, &self.resolver.clone(), canonicalized.value.clone()) | ||
325 | { | ||
326 | let derefed_ty = canonicalized.decanonicalize_ty(derefed_ty.value); | ||
327 | match (&*self.resolve_ty_shallow(&derefed_ty), &*to_ty) { | ||
328 | // Stop when constructor matches. | ||
329 | (ty_app!(from_ctor, st1), ty_app!(to_ctor, st2)) if from_ctor == to_ctor => { | ||
330 | // It will not recurse to `coerce`. | ||
331 | return self.unify_substs(st1, st2, 0); | ||
332 | } | ||
333 | _ => {} | ||
334 | } | ||
335 | } | ||
336 | |||
337 | false | ||
338 | } | ||
339 | } | ||
diff --git a/crates/ra_hir/src/ty/infer/expr.rs b/crates/ra_hir/src/ty/infer/expr.rs deleted file mode 100644 index 663ff9435..000000000 --- a/crates/ra_hir/src/ty/infer/expr.rs +++ /dev/null | |||
@@ -1,667 +0,0 @@ | |||
1 | //! Type inference for expressions. | ||
2 | |||
3 | use std::iter::{repeat, repeat_with}; | ||
4 | use std::sync::Arc; | ||
5 | |||
6 | use hir_def::{ | ||
7 | builtin_type::Signedness, | ||
8 | generics::GenericParams, | ||
9 | path::{GenericArg, GenericArgs}, | ||
10 | resolver::resolver_for_expr, | ||
11 | }; | ||
12 | use hir_expand::name; | ||
13 | |||
14 | use crate::{ | ||
15 | db::HirDatabase, | ||
16 | expr::{Array, BinaryOp, Expr, ExprId, Literal, Statement, UnaryOp}, | ||
17 | ty::{ | ||
18 | autoderef, method_resolution, op, CallableDef, InferTy, IntTy, Mutability, Namespace, | ||
19 | Obligation, ProjectionPredicate, ProjectionTy, Substs, TraitRef, Ty, TypeCtor, TypeWalk, | ||
20 | Uncertain, | ||
21 | }, | ||
22 | Adt, Name, | ||
23 | }; | ||
24 | |||
25 | use super::{BindingMode, Expectation, InferenceContext, InferenceDiagnostic, TypeMismatch}; | ||
26 | |||
27 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | ||
28 | pub(super) fn infer_expr(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty { | ||
29 | let ty = self.infer_expr_inner(tgt_expr, expected); | ||
30 | let could_unify = self.unify(&ty, &expected.ty); | ||
31 | if !could_unify { | ||
32 | self.result.type_mismatches.insert( | ||
33 | tgt_expr, | ||
34 | TypeMismatch { expected: expected.ty.clone(), actual: ty.clone() }, | ||
35 | ); | ||
36 | } | ||
37 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
38 | ty | ||
39 | } | ||
40 | |||
41 | /// Infer type of expression with possibly implicit coerce to the expected type. | ||
42 | /// Return the type after possible coercion. | ||
43 | fn infer_expr_coerce(&mut self, expr: ExprId, expected: &Expectation) -> Ty { | ||
44 | let ty = self.infer_expr_inner(expr, &expected); | ||
45 | let ty = if !self.coerce(&ty, &expected.ty) { | ||
46 | self.result | ||
47 | .type_mismatches | ||
48 | .insert(expr, TypeMismatch { expected: expected.ty.clone(), actual: ty.clone() }); | ||
49 | // Return actual type when type mismatch. | ||
50 | // This is needed for diagnostic when return type mismatch. | ||
51 | ty | ||
52 | } else if expected.ty == Ty::Unknown { | ||
53 | ty | ||
54 | } else { | ||
55 | expected.ty.clone() | ||
56 | }; | ||
57 | |||
58 | self.resolve_ty_as_possible(&mut vec![], ty) | ||
59 | } | ||
60 | |||
61 | fn infer_expr_inner(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty { | ||
62 | let body = Arc::clone(&self.body); // avoid borrow checker problem | ||
63 | let ty = match &body[tgt_expr] { | ||
64 | Expr::Missing => Ty::Unknown, | ||
65 | Expr::If { condition, then_branch, else_branch } => { | ||
66 | // if let is desugared to match, so this is always simple if | ||
67 | self.infer_expr(*condition, &Expectation::has_type(Ty::simple(TypeCtor::Bool))); | ||
68 | |||
69 | let then_ty = self.infer_expr_inner(*then_branch, &expected); | ||
70 | let else_ty = match else_branch { | ||
71 | Some(else_branch) => self.infer_expr_inner(*else_branch, &expected), | ||
72 | None => Ty::unit(), | ||
73 | }; | ||
74 | |||
75 | self.coerce_merge_branch(&then_ty, &else_ty) | ||
76 | } | ||
77 | Expr::Block { statements, tail } => self.infer_block(statements, *tail, expected), | ||
78 | Expr::TryBlock { body } => { | ||
79 | let _inner = self.infer_expr(*body, expected); | ||
80 | // FIXME should be std::result::Result<{inner}, _> | ||
81 | Ty::Unknown | ||
82 | } | ||
83 | Expr::Loop { body } => { | ||
84 | self.infer_expr(*body, &Expectation::has_type(Ty::unit())); | ||
85 | // FIXME handle break with value | ||
86 | Ty::simple(TypeCtor::Never) | ||
87 | } | ||
88 | Expr::While { condition, body } => { | ||
89 | // while let is desugared to a match loop, so this is always simple while | ||
90 | self.infer_expr(*condition, &Expectation::has_type(Ty::simple(TypeCtor::Bool))); | ||
91 | self.infer_expr(*body, &Expectation::has_type(Ty::unit())); | ||
92 | Ty::unit() | ||
93 | } | ||
94 | Expr::For { iterable, body, pat } => { | ||
95 | let iterable_ty = self.infer_expr(*iterable, &Expectation::none()); | ||
96 | |||
97 | let pat_ty = match self.resolve_into_iter_item() { | ||
98 | Some(into_iter_item_alias) => { | ||
99 | let pat_ty = self.new_type_var(); | ||
100 | let projection = ProjectionPredicate { | ||
101 | ty: pat_ty.clone(), | ||
102 | projection_ty: ProjectionTy { | ||
103 | associated_ty: into_iter_item_alias, | ||
104 | parameters: Substs::single(iterable_ty), | ||
105 | }, | ||
106 | }; | ||
107 | self.obligations.push(Obligation::Projection(projection)); | ||
108 | self.resolve_ty_as_possible(&mut vec![], pat_ty) | ||
109 | } | ||
110 | None => Ty::Unknown, | ||
111 | }; | ||
112 | |||
113 | self.infer_pat(*pat, &pat_ty, BindingMode::default()); | ||
114 | self.infer_expr(*body, &Expectation::has_type(Ty::unit())); | ||
115 | Ty::unit() | ||
116 | } | ||
117 | Expr::Lambda { body, args, arg_types } => { | ||
118 | assert_eq!(args.len(), arg_types.len()); | ||
119 | |||
120 | let mut sig_tys = Vec::new(); | ||
121 | |||
122 | for (arg_pat, arg_type) in args.iter().zip(arg_types.iter()) { | ||
123 | let expected = if let Some(type_ref) = arg_type { | ||
124 | self.make_ty(type_ref) | ||
125 | } else { | ||
126 | Ty::Unknown | ||
127 | }; | ||
128 | let arg_ty = self.infer_pat(*arg_pat, &expected, BindingMode::default()); | ||
129 | sig_tys.push(arg_ty); | ||
130 | } | ||
131 | |||
132 | // add return type | ||
133 | let ret_ty = self.new_type_var(); | ||
134 | sig_tys.push(ret_ty.clone()); | ||
135 | let sig_ty = Ty::apply( | ||
136 | TypeCtor::FnPtr { num_args: sig_tys.len() as u16 - 1 }, | ||
137 | Substs(sig_tys.into()), | ||
138 | ); | ||
139 | let closure_ty = | ||
140 | Ty::apply_one(TypeCtor::Closure { def: self.owner, expr: tgt_expr }, sig_ty); | ||
141 | |||
142 | // Eagerly try to relate the closure type with the expected | ||
143 | // type, otherwise we often won't have enough information to | ||
144 | // infer the body. | ||
145 | self.coerce(&closure_ty, &expected.ty); | ||
146 | |||
147 | self.infer_expr(*body, &Expectation::has_type(ret_ty)); | ||
148 | closure_ty | ||
149 | } | ||
150 | Expr::Call { callee, args } => { | ||
151 | let callee_ty = self.infer_expr(*callee, &Expectation::none()); | ||
152 | let (param_tys, ret_ty) = match callee_ty.callable_sig(self.db) { | ||
153 | Some(sig) => (sig.params().to_vec(), sig.ret().clone()), | ||
154 | None => { | ||
155 | // Not callable | ||
156 | // FIXME: report an error | ||
157 | (Vec::new(), Ty::Unknown) | ||
158 | } | ||
159 | }; | ||
160 | self.register_obligations_for_call(&callee_ty); | ||
161 | self.check_call_arguments(args, ¶m_tys); | ||
162 | let ret_ty = self.normalize_associated_types_in(ret_ty); | ||
163 | ret_ty | ||
164 | } | ||
165 | Expr::MethodCall { receiver, args, method_name, generic_args } => self | ||
166 | .infer_method_call(tgt_expr, *receiver, &args, &method_name, generic_args.as_ref()), | ||
167 | Expr::Match { expr, arms } => { | ||
168 | let input_ty = self.infer_expr(*expr, &Expectation::none()); | ||
169 | |||
170 | let mut result_ty = self.new_maybe_never_type_var(); | ||
171 | |||
172 | for arm in arms { | ||
173 | for &pat in &arm.pats { | ||
174 | let _pat_ty = self.infer_pat(pat, &input_ty, BindingMode::default()); | ||
175 | } | ||
176 | if let Some(guard_expr) = arm.guard { | ||
177 | self.infer_expr( | ||
178 | guard_expr, | ||
179 | &Expectation::has_type(Ty::simple(TypeCtor::Bool)), | ||
180 | ); | ||
181 | } | ||
182 | |||
183 | let arm_ty = self.infer_expr_inner(arm.expr, &expected); | ||
184 | result_ty = self.coerce_merge_branch(&result_ty, &arm_ty); | ||
185 | } | ||
186 | |||
187 | result_ty | ||
188 | } | ||
189 | Expr::Path(p) => { | ||
190 | // FIXME this could be more efficient... | ||
191 | let resolver = resolver_for_expr(self.db, self.owner.into(), tgt_expr); | ||
192 | self.infer_path(&resolver, p, tgt_expr.into()).unwrap_or(Ty::Unknown) | ||
193 | } | ||
194 | Expr::Continue => Ty::simple(TypeCtor::Never), | ||
195 | Expr::Break { expr } => { | ||
196 | if let Some(expr) = expr { | ||
197 | // FIXME handle break with value | ||
198 | self.infer_expr(*expr, &Expectation::none()); | ||
199 | } | ||
200 | Ty::simple(TypeCtor::Never) | ||
201 | } | ||
202 | Expr::Return { expr } => { | ||
203 | if let Some(expr) = expr { | ||
204 | self.infer_expr(*expr, &Expectation::has_type(self.return_ty.clone())); | ||
205 | } | ||
206 | Ty::simple(TypeCtor::Never) | ||
207 | } | ||
208 | Expr::RecordLit { path, fields, spread } => { | ||
209 | let (ty, def_id) = self.resolve_variant(path.as_ref()); | ||
210 | if let Some(variant) = def_id { | ||
211 | self.write_variant_resolution(tgt_expr.into(), variant); | ||
212 | } | ||
213 | |||
214 | self.unify(&ty, &expected.ty); | ||
215 | |||
216 | let substs = ty.substs().unwrap_or_else(Substs::empty); | ||
217 | let field_types = | ||
218 | def_id.map(|it| self.db.field_types(it.into())).unwrap_or_default(); | ||
219 | for (field_idx, field) in fields.iter().enumerate() { | ||
220 | let field_def = def_id.and_then(|it| match it.field(self.db, &field.name) { | ||
221 | Some(field) => Some(field), | ||
222 | None => { | ||
223 | self.push_diagnostic(InferenceDiagnostic::NoSuchField { | ||
224 | expr: tgt_expr, | ||
225 | field: field_idx, | ||
226 | }); | ||
227 | None | ||
228 | } | ||
229 | }); | ||
230 | if let Some(field_def) = field_def { | ||
231 | self.result.record_field_resolutions.insert(field.expr, field_def); | ||
232 | } | ||
233 | let field_ty = field_def | ||
234 | .map_or(Ty::Unknown, |it| field_types[it.id].clone()) | ||
235 | .subst(&substs); | ||
236 | self.infer_expr_coerce(field.expr, &Expectation::has_type(field_ty)); | ||
237 | } | ||
238 | if let Some(expr) = spread { | ||
239 | self.infer_expr(*expr, &Expectation::has_type(ty.clone())); | ||
240 | } | ||
241 | ty | ||
242 | } | ||
243 | Expr::Field { expr, name } => { | ||
244 | let receiver_ty = self.infer_expr(*expr, &Expectation::none()); | ||
245 | let canonicalized = self.canonicalizer().canonicalize_ty(receiver_ty); | ||
246 | let ty = autoderef::autoderef( | ||
247 | self.db, | ||
248 | &self.resolver.clone(), | ||
249 | canonicalized.value.clone(), | ||
250 | ) | ||
251 | .find_map(|derefed_ty| match canonicalized.decanonicalize_ty(derefed_ty.value) { | ||
252 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
253 | TypeCtor::Tuple { .. } => name | ||
254 | .as_tuple_index() | ||
255 | .and_then(|idx| a_ty.parameters.0.get(idx).cloned()), | ||
256 | TypeCtor::Adt(Adt::Struct(s)) => s.field(self.db, name).map(|field| { | ||
257 | self.write_field_resolution(tgt_expr, field); | ||
258 | self.db.field_types(s.id.into())[field.id] | ||
259 | .clone() | ||
260 | .subst(&a_ty.parameters) | ||
261 | }), | ||
262 | _ => None, | ||
263 | }, | ||
264 | _ => None, | ||
265 | }) | ||
266 | .unwrap_or(Ty::Unknown); | ||
267 | let ty = self.insert_type_vars(ty); | ||
268 | self.normalize_associated_types_in(ty) | ||
269 | } | ||
270 | Expr::Await { expr } => { | ||
271 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
272 | let ty = match self.resolve_future_future_output() { | ||
273 | Some(future_future_output_alias) => { | ||
274 | let ty = self.new_type_var(); | ||
275 | let projection = ProjectionPredicate { | ||
276 | ty: ty.clone(), | ||
277 | projection_ty: ProjectionTy { | ||
278 | associated_ty: future_future_output_alias, | ||
279 | parameters: Substs::single(inner_ty), | ||
280 | }, | ||
281 | }; | ||
282 | self.obligations.push(Obligation::Projection(projection)); | ||
283 | self.resolve_ty_as_possible(&mut vec![], ty) | ||
284 | } | ||
285 | None => Ty::Unknown, | ||
286 | }; | ||
287 | ty | ||
288 | } | ||
289 | Expr::Try { expr } => { | ||
290 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
291 | let ty = match self.resolve_ops_try_ok() { | ||
292 | Some(ops_try_ok_alias) => { | ||
293 | let ty = self.new_type_var(); | ||
294 | let projection = ProjectionPredicate { | ||
295 | ty: ty.clone(), | ||
296 | projection_ty: ProjectionTy { | ||
297 | associated_ty: ops_try_ok_alias, | ||
298 | parameters: Substs::single(inner_ty), | ||
299 | }, | ||
300 | }; | ||
301 | self.obligations.push(Obligation::Projection(projection)); | ||
302 | self.resolve_ty_as_possible(&mut vec![], ty) | ||
303 | } | ||
304 | None => Ty::Unknown, | ||
305 | }; | ||
306 | ty | ||
307 | } | ||
308 | Expr::Cast { expr, type_ref } => { | ||
309 | let _inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
310 | let cast_ty = self.make_ty(type_ref); | ||
311 | // FIXME check the cast... | ||
312 | cast_ty | ||
313 | } | ||
314 | Expr::Ref { expr, mutability } => { | ||
315 | let expectation = | ||
316 | if let Some((exp_inner, exp_mutability)) = &expected.ty.as_reference() { | ||
317 | if *exp_mutability == Mutability::Mut && *mutability == Mutability::Shared { | ||
318 | // FIXME: throw type error - expected mut reference but found shared ref, | ||
319 | // which cannot be coerced | ||
320 | } | ||
321 | Expectation::has_type(Ty::clone(exp_inner)) | ||
322 | } else { | ||
323 | Expectation::none() | ||
324 | }; | ||
325 | // FIXME reference coercions etc. | ||
326 | let inner_ty = self.infer_expr(*expr, &expectation); | ||
327 | Ty::apply_one(TypeCtor::Ref(*mutability), inner_ty) | ||
328 | } | ||
329 | Expr::Box { expr } => { | ||
330 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
331 | if let Some(box_) = self.resolve_boxed_box() { | ||
332 | Ty::apply_one(TypeCtor::Adt(box_), inner_ty) | ||
333 | } else { | ||
334 | Ty::Unknown | ||
335 | } | ||
336 | } | ||
337 | Expr::UnaryOp { expr, op } => { | ||
338 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
339 | match op { | ||
340 | UnaryOp::Deref => { | ||
341 | let canonicalized = self.canonicalizer().canonicalize_ty(inner_ty); | ||
342 | if let Some(derefed_ty) = | ||
343 | autoderef::deref(self.db, &self.resolver, &canonicalized.value) | ||
344 | { | ||
345 | canonicalized.decanonicalize_ty(derefed_ty.value) | ||
346 | } else { | ||
347 | Ty::Unknown | ||
348 | } | ||
349 | } | ||
350 | UnaryOp::Neg => { | ||
351 | match &inner_ty { | ||
352 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
353 | TypeCtor::Int(Uncertain::Unknown) | ||
354 | | TypeCtor::Int(Uncertain::Known(IntTy { | ||
355 | signedness: Signedness::Signed, | ||
356 | .. | ||
357 | })) | ||
358 | | TypeCtor::Float(..) => inner_ty, | ||
359 | _ => Ty::Unknown, | ||
360 | }, | ||
361 | Ty::Infer(InferTy::IntVar(..)) | Ty::Infer(InferTy::FloatVar(..)) => { | ||
362 | inner_ty | ||
363 | } | ||
364 | // FIXME: resolve ops::Neg trait | ||
365 | _ => Ty::Unknown, | ||
366 | } | ||
367 | } | ||
368 | UnaryOp::Not => { | ||
369 | match &inner_ty { | ||
370 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
371 | TypeCtor::Bool | TypeCtor::Int(_) => inner_ty, | ||
372 | _ => Ty::Unknown, | ||
373 | }, | ||
374 | Ty::Infer(InferTy::IntVar(..)) => inner_ty, | ||
375 | // FIXME: resolve ops::Not trait for inner_ty | ||
376 | _ => Ty::Unknown, | ||
377 | } | ||
378 | } | ||
379 | } | ||
380 | } | ||
381 | Expr::BinaryOp { lhs, rhs, op } => match op { | ||
382 | Some(op) => { | ||
383 | let lhs_expectation = match op { | ||
384 | BinaryOp::LogicOp(..) => Expectation::has_type(Ty::simple(TypeCtor::Bool)), | ||
385 | _ => Expectation::none(), | ||
386 | }; | ||
387 | let lhs_ty = self.infer_expr(*lhs, &lhs_expectation); | ||
388 | // FIXME: find implementation of trait corresponding to operation | ||
389 | // symbol and resolve associated `Output` type | ||
390 | let rhs_expectation = op::binary_op_rhs_expectation(*op, lhs_ty); | ||
391 | let rhs_ty = self.infer_expr(*rhs, &Expectation::has_type(rhs_expectation)); | ||
392 | |||
393 | // FIXME: similar as above, return ty is often associated trait type | ||
394 | op::binary_op_return_ty(*op, rhs_ty) | ||
395 | } | ||
396 | _ => Ty::Unknown, | ||
397 | }, | ||
398 | Expr::Index { base, index } => { | ||
399 | let _base_ty = self.infer_expr(*base, &Expectation::none()); | ||
400 | let _index_ty = self.infer_expr(*index, &Expectation::none()); | ||
401 | // FIXME: use `std::ops::Index::Output` to figure out the real return type | ||
402 | Ty::Unknown | ||
403 | } | ||
404 | Expr::Tuple { exprs } => { | ||
405 | let mut tys = match &expected.ty { | ||
406 | ty_app!(TypeCtor::Tuple { .. }, st) => st | ||
407 | .iter() | ||
408 | .cloned() | ||
409 | .chain(repeat_with(|| self.new_type_var())) | ||
410 | .take(exprs.len()) | ||
411 | .collect::<Vec<_>>(), | ||
412 | _ => (0..exprs.len()).map(|_| self.new_type_var()).collect(), | ||
413 | }; | ||
414 | |||
415 | for (expr, ty) in exprs.iter().zip(tys.iter_mut()) { | ||
416 | self.infer_expr_coerce(*expr, &Expectation::has_type(ty.clone())); | ||
417 | } | ||
418 | |||
419 | Ty::apply(TypeCtor::Tuple { cardinality: tys.len() as u16 }, Substs(tys.into())) | ||
420 | } | ||
421 | Expr::Array(array) => { | ||
422 | let elem_ty = match &expected.ty { | ||
423 | ty_app!(TypeCtor::Array, st) | ty_app!(TypeCtor::Slice, st) => { | ||
424 | st.as_single().clone() | ||
425 | } | ||
426 | _ => self.new_type_var(), | ||
427 | }; | ||
428 | |||
429 | match array { | ||
430 | Array::ElementList(items) => { | ||
431 | for expr in items.iter() { | ||
432 | self.infer_expr_coerce(*expr, &Expectation::has_type(elem_ty.clone())); | ||
433 | } | ||
434 | } | ||
435 | Array::Repeat { initializer, repeat } => { | ||
436 | self.infer_expr_coerce( | ||
437 | *initializer, | ||
438 | &Expectation::has_type(elem_ty.clone()), | ||
439 | ); | ||
440 | self.infer_expr( | ||
441 | *repeat, | ||
442 | &Expectation::has_type(Ty::simple(TypeCtor::Int(Uncertain::Known( | ||
443 | IntTy::usize(), | ||
444 | )))), | ||
445 | ); | ||
446 | } | ||
447 | } | ||
448 | |||
449 | Ty::apply_one(TypeCtor::Array, elem_ty) | ||
450 | } | ||
451 | Expr::Literal(lit) => match lit { | ||
452 | Literal::Bool(..) => Ty::simple(TypeCtor::Bool), | ||
453 | Literal::String(..) => { | ||
454 | Ty::apply_one(TypeCtor::Ref(Mutability::Shared), Ty::simple(TypeCtor::Str)) | ||
455 | } | ||
456 | Literal::ByteString(..) => { | ||
457 | let byte_type = Ty::simple(TypeCtor::Int(Uncertain::Known(IntTy::u8()))); | ||
458 | let slice_type = Ty::apply_one(TypeCtor::Slice, byte_type); | ||
459 | Ty::apply_one(TypeCtor::Ref(Mutability::Shared), slice_type) | ||
460 | } | ||
461 | Literal::Char(..) => Ty::simple(TypeCtor::Char), | ||
462 | Literal::Int(_v, ty) => Ty::simple(TypeCtor::Int((*ty).into())), | ||
463 | Literal::Float(_v, ty) => Ty::simple(TypeCtor::Float((*ty).into())), | ||
464 | }, | ||
465 | }; | ||
466 | // use a new type variable if we got Ty::Unknown here | ||
467 | let ty = self.insert_type_vars_shallow(ty); | ||
468 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
469 | self.write_expr_ty(tgt_expr, ty.clone()); | ||
470 | ty | ||
471 | } | ||
472 | |||
473 | fn infer_block( | ||
474 | &mut self, | ||
475 | statements: &[Statement], | ||
476 | tail: Option<ExprId>, | ||
477 | expected: &Expectation, | ||
478 | ) -> Ty { | ||
479 | let mut diverges = false; | ||
480 | for stmt in statements { | ||
481 | match stmt { | ||
482 | Statement::Let { pat, type_ref, initializer } => { | ||
483 | let decl_ty = | ||
484 | type_ref.as_ref().map(|tr| self.make_ty(tr)).unwrap_or(Ty::Unknown); | ||
485 | |||
486 | // Always use the declared type when specified | ||
487 | let mut ty = decl_ty.clone(); | ||
488 | |||
489 | if let Some(expr) = initializer { | ||
490 | let actual_ty = | ||
491 | self.infer_expr_coerce(*expr, &Expectation::has_type(decl_ty.clone())); | ||
492 | if decl_ty == Ty::Unknown { | ||
493 | ty = actual_ty; | ||
494 | } | ||
495 | } | ||
496 | |||
497 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
498 | self.infer_pat(*pat, &ty, BindingMode::default()); | ||
499 | } | ||
500 | Statement::Expr(expr) => { | ||
501 | if let ty_app!(TypeCtor::Never) = self.infer_expr(*expr, &Expectation::none()) { | ||
502 | diverges = true; | ||
503 | } | ||
504 | } | ||
505 | } | ||
506 | } | ||
507 | |||
508 | let ty = if let Some(expr) = tail { | ||
509 | self.infer_expr_coerce(expr, expected) | ||
510 | } else { | ||
511 | self.coerce(&Ty::unit(), &expected.ty); | ||
512 | Ty::unit() | ||
513 | }; | ||
514 | if diverges { | ||
515 | Ty::simple(TypeCtor::Never) | ||
516 | } else { | ||
517 | ty | ||
518 | } | ||
519 | } | ||
520 | |||
521 | fn infer_method_call( | ||
522 | &mut self, | ||
523 | tgt_expr: ExprId, | ||
524 | receiver: ExprId, | ||
525 | args: &[ExprId], | ||
526 | method_name: &Name, | ||
527 | generic_args: Option<&GenericArgs>, | ||
528 | ) -> Ty { | ||
529 | let receiver_ty = self.infer_expr(receiver, &Expectation::none()); | ||
530 | let canonicalized_receiver = self.canonicalizer().canonicalize_ty(receiver_ty.clone()); | ||
531 | let resolved = method_resolution::lookup_method( | ||
532 | &canonicalized_receiver.value, | ||
533 | self.db, | ||
534 | method_name, | ||
535 | &self.resolver, | ||
536 | ); | ||
537 | let (derefed_receiver_ty, method_ty, def_generics) = match resolved { | ||
538 | Some((ty, func)) => { | ||
539 | let ty = canonicalized_receiver.decanonicalize_ty(ty); | ||
540 | self.write_method_resolution(tgt_expr, func); | ||
541 | ( | ||
542 | ty, | ||
543 | self.db.type_for_def(func.into(), Namespace::Values), | ||
544 | Some(self.db.generic_params(func.id.into())), | ||
545 | ) | ||
546 | } | ||
547 | None => (receiver_ty, Ty::Unknown, None), | ||
548 | }; | ||
549 | let substs = self.substs_for_method_call(def_generics, generic_args, &derefed_receiver_ty); | ||
550 | let method_ty = method_ty.apply_substs(substs); | ||
551 | let method_ty = self.insert_type_vars(method_ty); | ||
552 | self.register_obligations_for_call(&method_ty); | ||
553 | let (expected_receiver_ty, param_tys, ret_ty) = match method_ty.callable_sig(self.db) { | ||
554 | Some(sig) => { | ||
555 | if !sig.params().is_empty() { | ||
556 | (sig.params()[0].clone(), sig.params()[1..].to_vec(), sig.ret().clone()) | ||
557 | } else { | ||
558 | (Ty::Unknown, Vec::new(), sig.ret().clone()) | ||
559 | } | ||
560 | } | ||
561 | None => (Ty::Unknown, Vec::new(), Ty::Unknown), | ||
562 | }; | ||
563 | // Apply autoref so the below unification works correctly | ||
564 | // FIXME: return correct autorefs from lookup_method | ||
565 | let actual_receiver_ty = match expected_receiver_ty.as_reference() { | ||
566 | Some((_, mutability)) => Ty::apply_one(TypeCtor::Ref(mutability), derefed_receiver_ty), | ||
567 | _ => derefed_receiver_ty, | ||
568 | }; | ||
569 | self.unify(&expected_receiver_ty, &actual_receiver_ty); | ||
570 | |||
571 | self.check_call_arguments(args, ¶m_tys); | ||
572 | let ret_ty = self.normalize_associated_types_in(ret_ty); | ||
573 | ret_ty | ||
574 | } | ||
575 | |||
576 | fn check_call_arguments(&mut self, args: &[ExprId], param_tys: &[Ty]) { | ||
577 | // Quoting https://github.com/rust-lang/rust/blob/6ef275e6c3cb1384ec78128eceeb4963ff788dca/src/librustc_typeck/check/mod.rs#L3325 -- | ||
578 | // We do this in a pretty awful way: first we type-check any arguments | ||
579 | // that are not closures, then we type-check the closures. This is so | ||
580 | // that we have more information about the types of arguments when we | ||
581 | // type-check the functions. This isn't really the right way to do this. | ||
582 | for &check_closures in &[false, true] { | ||
583 | let param_iter = param_tys.iter().cloned().chain(repeat(Ty::Unknown)); | ||
584 | for (&arg, param_ty) in args.iter().zip(param_iter) { | ||
585 | let is_closure = match &self.body[arg] { | ||
586 | Expr::Lambda { .. } => true, | ||
587 | _ => false, | ||
588 | }; | ||
589 | |||
590 | if is_closure != check_closures { | ||
591 | continue; | ||
592 | } | ||
593 | |||
594 | let param_ty = self.normalize_associated_types_in(param_ty); | ||
595 | self.infer_expr_coerce(arg, &Expectation::has_type(param_ty.clone())); | ||
596 | } | ||
597 | } | ||
598 | } | ||
599 | |||
600 | fn substs_for_method_call( | ||
601 | &mut self, | ||
602 | def_generics: Option<Arc<GenericParams>>, | ||
603 | generic_args: Option<&GenericArgs>, | ||
604 | receiver_ty: &Ty, | ||
605 | ) -> Substs { | ||
606 | let (parent_param_count, param_count) = | ||
607 | def_generics.as_ref().map_or((0, 0), |g| (g.count_parent_params(), g.params.len())); | ||
608 | let mut substs = Vec::with_capacity(parent_param_count + param_count); | ||
609 | // Parent arguments are unknown, except for the receiver type | ||
610 | if let Some(parent_generics) = def_generics.and_then(|p| p.parent_params.clone()) { | ||
611 | for param in &parent_generics.params { | ||
612 | if param.name == name::SELF_TYPE { | ||
613 | substs.push(receiver_ty.clone()); | ||
614 | } else { | ||
615 | substs.push(Ty::Unknown); | ||
616 | } | ||
617 | } | ||
618 | } | ||
619 | // handle provided type arguments | ||
620 | if let Some(generic_args) = generic_args { | ||
621 | // if args are provided, it should be all of them, but we can't rely on that | ||
622 | for arg in generic_args.args.iter().take(param_count) { | ||
623 | match arg { | ||
624 | GenericArg::Type(type_ref) => { | ||
625 | let ty = self.make_ty(type_ref); | ||
626 | substs.push(ty); | ||
627 | } | ||
628 | } | ||
629 | } | ||
630 | }; | ||
631 | let supplied_params = substs.len(); | ||
632 | for _ in supplied_params..parent_param_count + param_count { | ||
633 | substs.push(Ty::Unknown); | ||
634 | } | ||
635 | assert_eq!(substs.len(), parent_param_count + param_count); | ||
636 | Substs(substs.into()) | ||
637 | } | ||
638 | |||
639 | fn register_obligations_for_call(&mut self, callable_ty: &Ty) { | ||
640 | if let Ty::Apply(a_ty) = callable_ty { | ||
641 | if let TypeCtor::FnDef(def) = a_ty.ctor { | ||
642 | let generic_predicates = self.db.generic_predicates(def.into()); | ||
643 | for predicate in generic_predicates.iter() { | ||
644 | let predicate = predicate.clone().subst(&a_ty.parameters); | ||
645 | if let Some(obligation) = Obligation::from_predicate(predicate) { | ||
646 | self.obligations.push(obligation); | ||
647 | } | ||
648 | } | ||
649 | // add obligation for trait implementation, if this is a trait method | ||
650 | match def { | ||
651 | CallableDef::Function(f) => { | ||
652 | if let Some(trait_) = f.parent_trait(self.db) { | ||
653 | // construct a TraitDef | ||
654 | let substs = a_ty.parameters.prefix( | ||
655 | self.db | ||
656 | .generic_params(trait_.id.into()) | ||
657 | .count_params_including_parent(), | ||
658 | ); | ||
659 | self.obligations.push(Obligation::Trait(TraitRef { trait_, substs })); | ||
660 | } | ||
661 | } | ||
662 | CallableDef::Struct(_) | CallableDef::EnumVariant(_) => {} | ||
663 | } | ||
664 | } | ||
665 | } | ||
666 | } | ||
667 | } | ||
diff --git a/crates/ra_hir/src/ty/infer/pat.rs b/crates/ra_hir/src/ty/infer/pat.rs deleted file mode 100644 index 641d61e87..000000000 --- a/crates/ra_hir/src/ty/infer/pat.rs +++ /dev/null | |||
@@ -1,183 +0,0 @@ | |||
1 | //! Type inference for patterns. | ||
2 | |||
3 | use std::iter::repeat; | ||
4 | use std::sync::Arc; | ||
5 | |||
6 | use test_utils::tested_by; | ||
7 | |||
8 | use super::{BindingMode, InferenceContext}; | ||
9 | use crate::{ | ||
10 | db::HirDatabase, | ||
11 | expr::{BindingAnnotation, Pat, PatId, RecordFieldPat}, | ||
12 | ty::{Mutability, Substs, Ty, TypeCtor, TypeWalk}, | ||
13 | Name, Path, | ||
14 | }; | ||
15 | |||
16 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | ||
17 | fn infer_tuple_struct_pat( | ||
18 | &mut self, | ||
19 | path: Option<&Path>, | ||
20 | subpats: &[PatId], | ||
21 | expected: &Ty, | ||
22 | default_bm: BindingMode, | ||
23 | ) -> Ty { | ||
24 | let (ty, def) = self.resolve_variant(path); | ||
25 | |||
26 | self.unify(&ty, expected); | ||
27 | |||
28 | let substs = ty.substs().unwrap_or_else(Substs::empty); | ||
29 | |||
30 | let field_tys = def.map(|it| self.db.field_types(it.into())).unwrap_or_default(); | ||
31 | for (i, &subpat) in subpats.iter().enumerate() { | ||
32 | let expected_ty = def | ||
33 | .and_then(|d| d.field(self.db, &Name::new_tuple_field(i))) | ||
34 | .map_or(Ty::Unknown, |field| field_tys[field.id].clone()) | ||
35 | .subst(&substs); | ||
36 | let expected_ty = self.normalize_associated_types_in(expected_ty); | ||
37 | self.infer_pat(subpat, &expected_ty, default_bm); | ||
38 | } | ||
39 | |||
40 | ty | ||
41 | } | ||
42 | |||
43 | fn infer_record_pat( | ||
44 | &mut self, | ||
45 | path: Option<&Path>, | ||
46 | subpats: &[RecordFieldPat], | ||
47 | expected: &Ty, | ||
48 | default_bm: BindingMode, | ||
49 | id: PatId, | ||
50 | ) -> Ty { | ||
51 | let (ty, def) = self.resolve_variant(path); | ||
52 | if let Some(variant) = def { | ||
53 | self.write_variant_resolution(id.into(), variant); | ||
54 | } | ||
55 | |||
56 | self.unify(&ty, expected); | ||
57 | |||
58 | let substs = ty.substs().unwrap_or_else(Substs::empty); | ||
59 | |||
60 | let field_tys = def.map(|it| self.db.field_types(it.into())).unwrap_or_default(); | ||
61 | for subpat in subpats { | ||
62 | let matching_field = def.and_then(|it| it.field(self.db, &subpat.name)); | ||
63 | let expected_ty = matching_field | ||
64 | .map_or(Ty::Unknown, |field| field_tys[field.id].clone()) | ||
65 | .subst(&substs); | ||
66 | let expected_ty = self.normalize_associated_types_in(expected_ty); | ||
67 | self.infer_pat(subpat.pat, &expected_ty, default_bm); | ||
68 | } | ||
69 | |||
70 | ty | ||
71 | } | ||
72 | |||
73 | pub(super) fn infer_pat( | ||
74 | &mut self, | ||
75 | pat: PatId, | ||
76 | mut expected: &Ty, | ||
77 | mut default_bm: BindingMode, | ||
78 | ) -> Ty { | ||
79 | let body = Arc::clone(&self.body); // avoid borrow checker problem | ||
80 | |||
81 | let is_non_ref_pat = match &body[pat] { | ||
82 | Pat::Tuple(..) | ||
83 | | Pat::TupleStruct { .. } | ||
84 | | Pat::Record { .. } | ||
85 | | Pat::Range { .. } | ||
86 | | Pat::Slice { .. } => true, | ||
87 | // FIXME: Path/Lit might actually evaluate to ref, but inference is unimplemented. | ||
88 | Pat::Path(..) | Pat::Lit(..) => true, | ||
89 | Pat::Wild | Pat::Bind { .. } | Pat::Ref { .. } | Pat::Missing => false, | ||
90 | }; | ||
91 | if is_non_ref_pat { | ||
92 | while let Some((inner, mutability)) = expected.as_reference() { | ||
93 | expected = inner; | ||
94 | default_bm = match default_bm { | ||
95 | BindingMode::Move => BindingMode::Ref(mutability), | ||
96 | BindingMode::Ref(Mutability::Shared) => BindingMode::Ref(Mutability::Shared), | ||
97 | BindingMode::Ref(Mutability::Mut) => BindingMode::Ref(mutability), | ||
98 | } | ||
99 | } | ||
100 | } else if let Pat::Ref { .. } = &body[pat] { | ||
101 | tested_by!(match_ergonomics_ref); | ||
102 | // When you encounter a `&pat` pattern, reset to Move. | ||
103 | // This is so that `w` is by value: `let (_, &w) = &(1, &2);` | ||
104 | default_bm = BindingMode::Move; | ||
105 | } | ||
106 | |||
107 | // Lose mutability. | ||
108 | let default_bm = default_bm; | ||
109 | let expected = expected; | ||
110 | |||
111 | let ty = match &body[pat] { | ||
112 | Pat::Tuple(ref args) => { | ||
113 | let expectations = match expected.as_tuple() { | ||
114 | Some(parameters) => &*parameters.0, | ||
115 | _ => &[], | ||
116 | }; | ||
117 | let expectations_iter = expectations.iter().chain(repeat(&Ty::Unknown)); | ||
118 | |||
119 | let inner_tys = args | ||
120 | .iter() | ||
121 | .zip(expectations_iter) | ||
122 | .map(|(&pat, ty)| self.infer_pat(pat, ty, default_bm)) | ||
123 | .collect(); | ||
124 | |||
125 | Ty::apply(TypeCtor::Tuple { cardinality: args.len() as u16 }, Substs(inner_tys)) | ||
126 | } | ||
127 | Pat::Ref { pat, mutability } => { | ||
128 | let expectation = match expected.as_reference() { | ||
129 | Some((inner_ty, exp_mut)) => { | ||
130 | if *mutability != exp_mut { | ||
131 | // FIXME: emit type error? | ||
132 | } | ||
133 | inner_ty | ||
134 | } | ||
135 | _ => &Ty::Unknown, | ||
136 | }; | ||
137 | let subty = self.infer_pat(*pat, expectation, default_bm); | ||
138 | Ty::apply_one(TypeCtor::Ref(*mutability), subty) | ||
139 | } | ||
140 | Pat::TupleStruct { path: p, args: subpats } => { | ||
141 | self.infer_tuple_struct_pat(p.as_ref(), subpats, expected, default_bm) | ||
142 | } | ||
143 | Pat::Record { path: p, args: fields } => { | ||
144 | self.infer_record_pat(p.as_ref(), fields, expected, default_bm, pat) | ||
145 | } | ||
146 | Pat::Path(path) => { | ||
147 | // FIXME use correct resolver for the surrounding expression | ||
148 | let resolver = self.resolver.clone(); | ||
149 | self.infer_path(&resolver, &path, pat.into()).unwrap_or(Ty::Unknown) | ||
150 | } | ||
151 | Pat::Bind { mode, name: _, subpat } => { | ||
152 | let mode = if mode == &BindingAnnotation::Unannotated { | ||
153 | default_bm | ||
154 | } else { | ||
155 | BindingMode::convert(*mode) | ||
156 | }; | ||
157 | let inner_ty = if let Some(subpat) = subpat { | ||
158 | self.infer_pat(*subpat, expected, default_bm) | ||
159 | } else { | ||
160 | expected.clone() | ||
161 | }; | ||
162 | let inner_ty = self.insert_type_vars_shallow(inner_ty); | ||
163 | |||
164 | let bound_ty = match mode { | ||
165 | BindingMode::Ref(mutability) => { | ||
166 | Ty::apply_one(TypeCtor::Ref(mutability), inner_ty.clone()) | ||
167 | } | ||
168 | BindingMode::Move => inner_ty.clone(), | ||
169 | }; | ||
170 | let bound_ty = self.resolve_ty_as_possible(&mut vec![], bound_ty); | ||
171 | self.write_pat_ty(pat, bound_ty); | ||
172 | return inner_ty; | ||
173 | } | ||
174 | _ => Ty::Unknown, | ||
175 | }; | ||
176 | // use a new type variable if we got Ty::Unknown here | ||
177 | let ty = self.insert_type_vars_shallow(ty); | ||
178 | self.unify(&ty, expected); | ||
179 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
180 | self.write_pat_ty(pat, ty.clone()); | ||
181 | ty | ||
182 | } | ||
183 | } | ||
diff --git a/crates/ra_hir/src/ty/infer/path.rs b/crates/ra_hir/src/ty/infer/path.rs deleted file mode 100644 index ee54d8217..000000000 --- a/crates/ra_hir/src/ty/infer/path.rs +++ /dev/null | |||
@@ -1,258 +0,0 @@ | |||
1 | //! Path expression resolution. | ||
2 | |||
3 | use hir_def::{ | ||
4 | path::PathSegment, | ||
5 | resolver::{ResolveValueResult, Resolver, TypeNs, ValueNs}, | ||
6 | }; | ||
7 | |||
8 | use crate::{ | ||
9 | db::HirDatabase, | ||
10 | ty::{method_resolution, Namespace, Substs, Ty, TypableDef, TypeWalk}, | ||
11 | AssocItem, Container, Function, Name, Path, | ||
12 | }; | ||
13 | |||
14 | use super::{ExprOrPatId, InferenceContext, TraitRef}; | ||
15 | |||
16 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | ||
17 | pub(super) fn infer_path( | ||
18 | &mut self, | ||
19 | resolver: &Resolver, | ||
20 | path: &Path, | ||
21 | id: ExprOrPatId, | ||
22 | ) -> Option<Ty> { | ||
23 | let ty = self.resolve_value_path(resolver, path, id)?; | ||
24 | let ty = self.insert_type_vars(ty); | ||
25 | let ty = self.normalize_associated_types_in(ty); | ||
26 | Some(ty) | ||
27 | } | ||
28 | |||
29 | fn resolve_value_path( | ||
30 | &mut self, | ||
31 | resolver: &Resolver, | ||
32 | path: &Path, | ||
33 | id: ExprOrPatId, | ||
34 | ) -> Option<Ty> { | ||
35 | let (value, self_subst) = if let crate::PathKind::Type(type_ref) = &path.kind { | ||
36 | if path.segments.is_empty() { | ||
37 | // This can't actually happen syntax-wise | ||
38 | return None; | ||
39 | } | ||
40 | let ty = self.make_ty(type_ref); | ||
41 | let remaining_segments_for_ty = &path.segments[..path.segments.len() - 1]; | ||
42 | let ty = Ty::from_type_relative_path(self.db, resolver, ty, remaining_segments_for_ty); | ||
43 | self.resolve_ty_assoc_item( | ||
44 | ty, | ||
45 | &path.segments.last().expect("path had at least one segment").name, | ||
46 | id, | ||
47 | )? | ||
48 | } else { | ||
49 | let value_or_partial = resolver.resolve_path_in_value_ns(self.db, &path)?; | ||
50 | |||
51 | match value_or_partial { | ||
52 | ResolveValueResult::ValueNs(it) => (it, None), | ||
53 | ResolveValueResult::Partial(def, remaining_index) => { | ||
54 | self.resolve_assoc_item(def, path, remaining_index, id)? | ||
55 | } | ||
56 | } | ||
57 | }; | ||
58 | |||
59 | let typable: TypableDef = match value { | ||
60 | ValueNs::LocalBinding(pat) => { | ||
61 | let ty = self.result.type_of_pat.get(pat)?.clone(); | ||
62 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
63 | return Some(ty); | ||
64 | } | ||
65 | ValueNs::FunctionId(it) => it.into(), | ||
66 | ValueNs::ConstId(it) => it.into(), | ||
67 | ValueNs::StaticId(it) => it.into(), | ||
68 | ValueNs::StructId(it) => it.into(), | ||
69 | ValueNs::EnumVariantId(it) => it.into(), | ||
70 | }; | ||
71 | |||
72 | let mut ty = self.db.type_for_def(typable, Namespace::Values); | ||
73 | if let Some(self_subst) = self_subst { | ||
74 | ty = ty.subst(&self_subst); | ||
75 | } | ||
76 | |||
77 | let substs = Ty::substs_from_path(self.db, &self.resolver, path, typable); | ||
78 | let ty = ty.subst(&substs); | ||
79 | Some(ty) | ||
80 | } | ||
81 | |||
82 | fn resolve_assoc_item( | ||
83 | &mut self, | ||
84 | def: TypeNs, | ||
85 | path: &Path, | ||
86 | remaining_index: usize, | ||
87 | id: ExprOrPatId, | ||
88 | ) -> Option<(ValueNs, Option<Substs>)> { | ||
89 | assert!(remaining_index < path.segments.len()); | ||
90 | // there may be more intermediate segments between the resolved one and | ||
91 | // the end. Only the last segment needs to be resolved to a value; from | ||
92 | // the segments before that, we need to get either a type or a trait ref. | ||
93 | |||
94 | let resolved_segment = &path.segments[remaining_index - 1]; | ||
95 | let remaining_segments = &path.segments[remaining_index..]; | ||
96 | let is_before_last = remaining_segments.len() == 1; | ||
97 | |||
98 | match (def, is_before_last) { | ||
99 | (TypeNs::TraitId(trait_), true) => { | ||
100 | let segment = | ||
101 | remaining_segments.last().expect("there should be at least one segment here"); | ||
102 | let trait_ref = TraitRef::from_resolved_path( | ||
103 | self.db, | ||
104 | &self.resolver, | ||
105 | trait_.into(), | ||
106 | resolved_segment, | ||
107 | None, | ||
108 | ); | ||
109 | self.resolve_trait_assoc_item(trait_ref, segment, id) | ||
110 | } | ||
111 | (def, _) => { | ||
112 | // Either we already have a type (e.g. `Vec::new`), or we have a | ||
113 | // trait but it's not the last segment, so the next segment | ||
114 | // should resolve to an associated type of that trait (e.g. `<T | ||
115 | // as Iterator>::Item::default`) | ||
116 | let remaining_segments_for_ty = &remaining_segments[..remaining_segments.len() - 1]; | ||
117 | let ty = Ty::from_partly_resolved_hir_path( | ||
118 | self.db, | ||
119 | &self.resolver, | ||
120 | def, | ||
121 | resolved_segment, | ||
122 | remaining_segments_for_ty, | ||
123 | ); | ||
124 | if let Ty::Unknown = ty { | ||
125 | return None; | ||
126 | } | ||
127 | |||
128 | let ty = self.insert_type_vars(ty); | ||
129 | let ty = self.normalize_associated_types_in(ty); | ||
130 | |||
131 | let segment = | ||
132 | remaining_segments.last().expect("there should be at least one segment here"); | ||
133 | |||
134 | self.resolve_ty_assoc_item(ty, &segment.name, id) | ||
135 | } | ||
136 | } | ||
137 | } | ||
138 | |||
139 | fn resolve_trait_assoc_item( | ||
140 | &mut self, | ||
141 | trait_ref: TraitRef, | ||
142 | segment: &PathSegment, | ||
143 | id: ExprOrPatId, | ||
144 | ) -> Option<(ValueNs, Option<Substs>)> { | ||
145 | let trait_ = trait_ref.trait_; | ||
146 | let item = trait_.items(self.db).iter().copied().find_map(|item| match item { | ||
147 | AssocItem::Function(func) => { | ||
148 | if segment.name == func.name(self.db) { | ||
149 | Some(AssocItem::Function(func)) | ||
150 | } else { | ||
151 | None | ||
152 | } | ||
153 | } | ||
154 | |||
155 | AssocItem::Const(konst) => { | ||
156 | if konst.name(self.db).map_or(false, |n| n == segment.name) { | ||
157 | Some(AssocItem::Const(konst)) | ||
158 | } else { | ||
159 | None | ||
160 | } | ||
161 | } | ||
162 | AssocItem::TypeAlias(_) => None, | ||
163 | })?; | ||
164 | let def = match item { | ||
165 | AssocItem::Function(f) => ValueNs::FunctionId(f.id), | ||
166 | AssocItem::Const(c) => ValueNs::ConstId(c.id), | ||
167 | AssocItem::TypeAlias(_) => unreachable!(), | ||
168 | }; | ||
169 | let substs = Substs::build_for_def(self.db, item) | ||
170 | .use_parent_substs(&trait_ref.substs) | ||
171 | .fill_with_params() | ||
172 | .build(); | ||
173 | |||
174 | self.write_assoc_resolution(id, item); | ||
175 | Some((def, Some(substs))) | ||
176 | } | ||
177 | |||
178 | fn resolve_ty_assoc_item( | ||
179 | &mut self, | ||
180 | ty: Ty, | ||
181 | name: &Name, | ||
182 | id: ExprOrPatId, | ||
183 | ) -> Option<(ValueNs, Option<Substs>)> { | ||
184 | if let Ty::Unknown = ty { | ||
185 | return None; | ||
186 | } | ||
187 | |||
188 | let canonical_ty = self.canonicalizer().canonicalize_ty(ty.clone()); | ||
189 | |||
190 | method_resolution::iterate_method_candidates( | ||
191 | &canonical_ty.value, | ||
192 | self.db, | ||
193 | &self.resolver.clone(), | ||
194 | Some(name), | ||
195 | method_resolution::LookupMode::Path, | ||
196 | move |_ty, item| { | ||
197 | let def = match item { | ||
198 | AssocItem::Function(f) => ValueNs::FunctionId(f.id), | ||
199 | AssocItem::Const(c) => ValueNs::ConstId(c.id), | ||
200 | AssocItem::TypeAlias(_) => unreachable!(), | ||
201 | }; | ||
202 | let substs = match item.container(self.db) { | ||
203 | Container::ImplBlock(_) => self.find_self_types(&def, ty.clone()), | ||
204 | Container::Trait(t) => { | ||
205 | // we're picking this method | ||
206 | let trait_substs = Substs::build_for_def(self.db, t) | ||
207 | .push(ty.clone()) | ||
208 | .fill(std::iter::repeat_with(|| self.new_type_var())) | ||
209 | .build(); | ||
210 | let substs = Substs::build_for_def(self.db, item) | ||
211 | .use_parent_substs(&trait_substs) | ||
212 | .fill_with_params() | ||
213 | .build(); | ||
214 | self.obligations.push(super::Obligation::Trait(TraitRef { | ||
215 | trait_: t, | ||
216 | substs: trait_substs, | ||
217 | })); | ||
218 | Some(substs) | ||
219 | } | ||
220 | }; | ||
221 | |||
222 | self.write_assoc_resolution(id, item); | ||
223 | Some((def, substs)) | ||
224 | }, | ||
225 | ) | ||
226 | } | ||
227 | |||
228 | fn find_self_types(&self, def: &ValueNs, actual_def_ty: Ty) -> Option<Substs> { | ||
229 | if let ValueNs::FunctionId(func) = def { | ||
230 | let func = Function::from(*func); | ||
231 | // We only do the infer if parent has generic params | ||
232 | let gen = self.db.generic_params(func.id.into()); | ||
233 | if gen.count_parent_params() == 0 { | ||
234 | return None; | ||
235 | } | ||
236 | |||
237 | let impl_block = func.impl_block(self.db)?.target_ty(self.db); | ||
238 | let impl_block_substs = impl_block.substs()?; | ||
239 | let actual_substs = actual_def_ty.substs()?; | ||
240 | |||
241 | let mut new_substs = vec![Ty::Unknown; gen.count_parent_params()]; | ||
242 | |||
243 | // The following code *link up* the function actual parma type | ||
244 | // and impl_block type param index | ||
245 | impl_block_substs.iter().zip(actual_substs.iter()).for_each(|(param, pty)| { | ||
246 | if let Ty::Param { idx, .. } = param { | ||
247 | if let Some(s) = new_substs.get_mut(*idx as usize) { | ||
248 | *s = pty.clone(); | ||
249 | } | ||
250 | } | ||
251 | }); | ||
252 | |||
253 | Some(Substs(new_substs.into())) | ||
254 | } else { | ||
255 | None | ||
256 | } | ||
257 | } | ||
258 | } | ||
diff --git a/crates/ra_hir/src/ty/infer/unify.rs b/crates/ra_hir/src/ty/infer/unify.rs deleted file mode 100644 index 64d9394cf..000000000 --- a/crates/ra_hir/src/ty/infer/unify.rs +++ /dev/null | |||
@@ -1,164 +0,0 @@ | |||
1 | //! Unification and canonicalization logic. | ||
2 | |||
3 | use super::{InferenceContext, Obligation}; | ||
4 | use crate::db::HirDatabase; | ||
5 | use crate::ty::{ | ||
6 | Canonical, InEnvironment, InferTy, ProjectionPredicate, ProjectionTy, Substs, TraitRef, Ty, | ||
7 | TypeWalk, | ||
8 | }; | ||
9 | use crate::util::make_mut_slice; | ||
10 | |||
11 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | ||
12 | pub(super) fn canonicalizer<'b>(&'b mut self) -> Canonicalizer<'a, 'b, D> | ||
13 | where | ||
14 | 'a: 'b, | ||
15 | { | ||
16 | Canonicalizer { ctx: self, free_vars: Vec::new(), var_stack: Vec::new() } | ||
17 | } | ||
18 | } | ||
19 | |||
20 | pub(super) struct Canonicalizer<'a, 'b, D: HirDatabase> | ||
21 | where | ||
22 | 'a: 'b, | ||
23 | { | ||
24 | ctx: &'b mut InferenceContext<'a, D>, | ||
25 | free_vars: Vec<InferTy>, | ||
26 | /// A stack of type variables that is used to detect recursive types (which | ||
27 | /// are an error, but we need to protect against them to avoid stack | ||
28 | /// overflows). | ||
29 | var_stack: Vec<super::TypeVarId>, | ||
30 | } | ||
31 | |||
32 | pub(super) struct Canonicalized<T> { | ||
33 | pub value: Canonical<T>, | ||
34 | free_vars: Vec<InferTy>, | ||
35 | } | ||
36 | |||
37 | impl<'a, 'b, D: HirDatabase> Canonicalizer<'a, 'b, D> | ||
38 | where | ||
39 | 'a: 'b, | ||
40 | { | ||
41 | fn add(&mut self, free_var: InferTy) -> usize { | ||
42 | self.free_vars.iter().position(|&v| v == free_var).unwrap_or_else(|| { | ||
43 | let next_index = self.free_vars.len(); | ||
44 | self.free_vars.push(free_var); | ||
45 | next_index | ||
46 | }) | ||
47 | } | ||
48 | |||
49 | fn do_canonicalize_ty(&mut self, ty: Ty) -> Ty { | ||
50 | ty.fold(&mut |ty| match ty { | ||
51 | Ty::Infer(tv) => { | ||
52 | let inner = tv.to_inner(); | ||
53 | if self.var_stack.contains(&inner) { | ||
54 | // recursive type | ||
55 | return tv.fallback_value(); | ||
56 | } | ||
57 | if let Some(known_ty) = | ||
58 | self.ctx.var_unification_table.inlined_probe_value(inner).known() | ||
59 | { | ||
60 | self.var_stack.push(inner); | ||
61 | let result = self.do_canonicalize_ty(known_ty.clone()); | ||
62 | self.var_stack.pop(); | ||
63 | result | ||
64 | } else { | ||
65 | let root = self.ctx.var_unification_table.find(inner); | ||
66 | let free_var = match tv { | ||
67 | InferTy::TypeVar(_) => InferTy::TypeVar(root), | ||
68 | InferTy::IntVar(_) => InferTy::IntVar(root), | ||
69 | InferTy::FloatVar(_) => InferTy::FloatVar(root), | ||
70 | InferTy::MaybeNeverTypeVar(_) => InferTy::MaybeNeverTypeVar(root), | ||
71 | }; | ||
72 | let position = self.add(free_var); | ||
73 | Ty::Bound(position as u32) | ||
74 | } | ||
75 | } | ||
76 | _ => ty, | ||
77 | }) | ||
78 | } | ||
79 | |||
80 | fn do_canonicalize_trait_ref(&mut self, mut trait_ref: TraitRef) -> TraitRef { | ||
81 | for ty in make_mut_slice(&mut trait_ref.substs.0) { | ||
82 | *ty = self.do_canonicalize_ty(ty.clone()); | ||
83 | } | ||
84 | trait_ref | ||
85 | } | ||
86 | |||
87 | fn into_canonicalized<T>(self, result: T) -> Canonicalized<T> { | ||
88 | Canonicalized { | ||
89 | value: Canonical { value: result, num_vars: self.free_vars.len() }, | ||
90 | free_vars: self.free_vars, | ||
91 | } | ||
92 | } | ||
93 | |||
94 | fn do_canonicalize_projection_ty(&mut self, mut projection_ty: ProjectionTy) -> ProjectionTy { | ||
95 | for ty in make_mut_slice(&mut projection_ty.parameters.0) { | ||
96 | *ty = self.do_canonicalize_ty(ty.clone()); | ||
97 | } | ||
98 | projection_ty | ||
99 | } | ||
100 | |||
101 | fn do_canonicalize_projection_predicate( | ||
102 | &mut self, | ||
103 | projection: ProjectionPredicate, | ||
104 | ) -> ProjectionPredicate { | ||
105 | let ty = self.do_canonicalize_ty(projection.ty); | ||
106 | let projection_ty = self.do_canonicalize_projection_ty(projection.projection_ty); | ||
107 | |||
108 | ProjectionPredicate { ty, projection_ty } | ||
109 | } | ||
110 | |||
111 | // FIXME: add some point, we need to introduce a `Fold` trait that abstracts | ||
112 | // over all the things that can be canonicalized (like Chalk and rustc have) | ||
113 | |||
114 | pub(crate) fn canonicalize_ty(mut self, ty: Ty) -> Canonicalized<Ty> { | ||
115 | let result = self.do_canonicalize_ty(ty); | ||
116 | self.into_canonicalized(result) | ||
117 | } | ||
118 | |||
119 | pub(crate) fn canonicalize_obligation( | ||
120 | mut self, | ||
121 | obligation: InEnvironment<Obligation>, | ||
122 | ) -> Canonicalized<InEnvironment<Obligation>> { | ||
123 | let result = match obligation.value { | ||
124 | Obligation::Trait(tr) => Obligation::Trait(self.do_canonicalize_trait_ref(tr)), | ||
125 | Obligation::Projection(pr) => { | ||
126 | Obligation::Projection(self.do_canonicalize_projection_predicate(pr)) | ||
127 | } | ||
128 | }; | ||
129 | self.into_canonicalized(InEnvironment { | ||
130 | value: result, | ||
131 | environment: obligation.environment, | ||
132 | }) | ||
133 | } | ||
134 | } | ||
135 | |||
136 | impl<T> Canonicalized<T> { | ||
137 | pub fn decanonicalize_ty(&self, mut ty: Ty) -> Ty { | ||
138 | ty.walk_mut_binders( | ||
139 | &mut |ty, binders| match ty { | ||
140 | &mut Ty::Bound(idx) => { | ||
141 | if idx as usize >= binders && (idx as usize - binders) < self.free_vars.len() { | ||
142 | *ty = Ty::Infer(self.free_vars[idx as usize - binders]); | ||
143 | } | ||
144 | } | ||
145 | _ => {} | ||
146 | }, | ||
147 | 0, | ||
148 | ); | ||
149 | ty | ||
150 | } | ||
151 | |||
152 | pub fn apply_solution( | ||
153 | &self, | ||
154 | ctx: &mut InferenceContext<'_, impl HirDatabase>, | ||
155 | solution: Canonical<Vec<Ty>>, | ||
156 | ) { | ||
157 | // the solution may contain new variables, which we need to convert to new inference vars | ||
158 | let new_vars = Substs((0..solution.num_vars).map(|_| ctx.new_type_var()).collect()); | ||
159 | for (i, ty) in solution.value.into_iter().enumerate() { | ||
160 | let var = self.free_vars[i]; | ||
161 | ctx.unify(&Ty::Infer(var), &ty.subst_bound_vars(&new_vars)); | ||
162 | } | ||
163 | } | ||
164 | } | ||
diff --git a/crates/ra_hir/src/ty/lower.rs b/crates/ra_hir/src/ty/lower.rs deleted file mode 100644 index a39beb2a0..000000000 --- a/crates/ra_hir/src/ty/lower.rs +++ /dev/null | |||
@@ -1,831 +0,0 @@ | |||
1 | //! Methods for lowering the HIR to types. There are two main cases here: | ||
2 | //! | ||
3 | //! - Lowering a type reference like `&usize` or `Option<foo::bar::Baz>` to a | ||
4 | //! type: The entry point for this is `Ty::from_hir`. | ||
5 | //! - Building the type for an item: This happens through the `type_for_def` query. | ||
6 | //! | ||
7 | //! This usually involves resolving names, collecting generic arguments etc. | ||
8 | use std::iter; | ||
9 | use std::sync::Arc; | ||
10 | |||
11 | use hir_def::{ | ||
12 | builtin_type::{BuiltinFloat, BuiltinInt, BuiltinType}, | ||
13 | generics::WherePredicate, | ||
14 | path::{GenericArg, PathSegment}, | ||
15 | resolver::{HasResolver, Resolver, TypeNs}, | ||
16 | type_ref::{TypeBound, TypeRef}, | ||
17 | AdtId, GenericDefId, LocalStructFieldId, VariantId, | ||
18 | }; | ||
19 | use ra_arena::map::ArenaMap; | ||
20 | |||
21 | use super::{ | ||
22 | FnSig, GenericPredicate, ProjectionPredicate, ProjectionTy, Substs, TraitRef, Ty, TypeCtor, | ||
23 | TypeWalk, | ||
24 | }; | ||
25 | use crate::{ | ||
26 | db::HirDatabase, | ||
27 | ty::{ | ||
28 | primitive::{FloatTy, IntTy, Uncertain}, | ||
29 | Adt, | ||
30 | }, | ||
31 | util::make_mut_slice, | ||
32 | Const, Enum, EnumVariant, Function, GenericDef, ImplBlock, ModuleDef, Path, Static, Struct, | ||
33 | Trait, TypeAlias, Union, | ||
34 | }; | ||
35 | |||
36 | // FIXME: this is only really used in `type_for_def`, which contains a bunch of | ||
37 | // impossible cases. Perhaps we should recombine `TypeableDef` and `Namespace` | ||
38 | // into a `AsTypeDef`, `AsValueDef` enums? | ||
39 | #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] | ||
40 | pub enum Namespace { | ||
41 | Types, | ||
42 | Values, | ||
43 | // Note that only type inference uses this enum, and it doesn't care about macros. | ||
44 | // Macro, | ||
45 | } | ||
46 | |||
47 | impl Ty { | ||
48 | pub(crate) fn from_hir(db: &impl HirDatabase, resolver: &Resolver, type_ref: &TypeRef) -> Self { | ||
49 | match type_ref { | ||
50 | TypeRef::Never => Ty::simple(TypeCtor::Never), | ||
51 | TypeRef::Tuple(inner) => { | ||
52 | let inner_tys: Arc<[Ty]> = | ||
53 | inner.iter().map(|tr| Ty::from_hir(db, resolver, tr)).collect(); | ||
54 | Ty::apply( | ||
55 | TypeCtor::Tuple { cardinality: inner_tys.len() as u16 }, | ||
56 | Substs(inner_tys), | ||
57 | ) | ||
58 | } | ||
59 | TypeRef::Path(path) => Ty::from_hir_path(db, resolver, path), | ||
60 | TypeRef::RawPtr(inner, mutability) => { | ||
61 | let inner_ty = Ty::from_hir(db, resolver, inner); | ||
62 | Ty::apply_one(TypeCtor::RawPtr(*mutability), inner_ty) | ||
63 | } | ||
64 | TypeRef::Array(inner) => { | ||
65 | let inner_ty = Ty::from_hir(db, resolver, inner); | ||
66 | Ty::apply_one(TypeCtor::Array, inner_ty) | ||
67 | } | ||
68 | TypeRef::Slice(inner) => { | ||
69 | let inner_ty = Ty::from_hir(db, resolver, inner); | ||
70 | Ty::apply_one(TypeCtor::Slice, inner_ty) | ||
71 | } | ||
72 | TypeRef::Reference(inner, mutability) => { | ||
73 | let inner_ty = Ty::from_hir(db, resolver, inner); | ||
74 | Ty::apply_one(TypeCtor::Ref(*mutability), inner_ty) | ||
75 | } | ||
76 | TypeRef::Placeholder => Ty::Unknown, | ||
77 | TypeRef::Fn(params) => { | ||
78 | let sig = Substs(params.iter().map(|tr| Ty::from_hir(db, resolver, tr)).collect()); | ||
79 | Ty::apply(TypeCtor::FnPtr { num_args: sig.len() as u16 - 1 }, sig) | ||
80 | } | ||
81 | TypeRef::DynTrait(bounds) => { | ||
82 | let self_ty = Ty::Bound(0); | ||
83 | let predicates = bounds | ||
84 | .iter() | ||
85 | .flat_map(|b| { | ||
86 | GenericPredicate::from_type_bound(db, resolver, b, self_ty.clone()) | ||
87 | }) | ||
88 | .collect(); | ||
89 | Ty::Dyn(predicates) | ||
90 | } | ||
91 | TypeRef::ImplTrait(bounds) => { | ||
92 | let self_ty = Ty::Bound(0); | ||
93 | let predicates = bounds | ||
94 | .iter() | ||
95 | .flat_map(|b| { | ||
96 | GenericPredicate::from_type_bound(db, resolver, b, self_ty.clone()) | ||
97 | }) | ||
98 | .collect(); | ||
99 | Ty::Opaque(predicates) | ||
100 | } | ||
101 | TypeRef::Error => Ty::Unknown, | ||
102 | } | ||
103 | } | ||
104 | |||
105 | /// This is only for `generic_predicates_for_param`, where we can't just | ||
106 | /// lower the self types of the predicates since that could lead to cycles. | ||
107 | /// So we just check here if the `type_ref` resolves to a generic param, and which. | ||
108 | fn from_hir_only_param( | ||
109 | db: &impl HirDatabase, | ||
110 | resolver: &Resolver, | ||
111 | type_ref: &TypeRef, | ||
112 | ) -> Option<u32> { | ||
113 | let path = match type_ref { | ||
114 | TypeRef::Path(path) => path, | ||
115 | _ => return None, | ||
116 | }; | ||
117 | if let crate::PathKind::Type(_) = &path.kind { | ||
118 | return None; | ||
119 | } | ||
120 | if path.segments.len() > 1 { | ||
121 | return None; | ||
122 | } | ||
123 | let resolution = match resolver.resolve_path_in_type_ns(db, path) { | ||
124 | Some((it, None)) => it, | ||
125 | _ => return None, | ||
126 | }; | ||
127 | if let TypeNs::GenericParam(idx) = resolution { | ||
128 | Some(idx) | ||
129 | } else { | ||
130 | None | ||
131 | } | ||
132 | } | ||
133 | |||
134 | pub(crate) fn from_type_relative_path( | ||
135 | db: &impl HirDatabase, | ||
136 | resolver: &Resolver, | ||
137 | ty: Ty, | ||
138 | remaining_segments: &[PathSegment], | ||
139 | ) -> Ty { | ||
140 | if remaining_segments.len() == 1 { | ||
141 | // resolve unselected assoc types | ||
142 | let segment = &remaining_segments[0]; | ||
143 | Ty::select_associated_type(db, resolver, ty, segment) | ||
144 | } else if remaining_segments.len() > 1 { | ||
145 | // FIXME report error (ambiguous associated type) | ||
146 | Ty::Unknown | ||
147 | } else { | ||
148 | ty | ||
149 | } | ||
150 | } | ||
151 | |||
152 | pub(crate) fn from_partly_resolved_hir_path( | ||
153 | db: &impl HirDatabase, | ||
154 | resolver: &Resolver, | ||
155 | resolution: TypeNs, | ||
156 | resolved_segment: &PathSegment, | ||
157 | remaining_segments: &[PathSegment], | ||
158 | ) -> Ty { | ||
159 | let ty = match resolution { | ||
160 | TypeNs::TraitId(trait_) => { | ||
161 | let trait_ref = TraitRef::from_resolved_path( | ||
162 | db, | ||
163 | resolver, | ||
164 | trait_.into(), | ||
165 | resolved_segment, | ||
166 | None, | ||
167 | ); | ||
168 | return if remaining_segments.len() == 1 { | ||
169 | let segment = &remaining_segments[0]; | ||
170 | match trait_ref | ||
171 | .trait_ | ||
172 | .associated_type_by_name_including_super_traits(db, &segment.name) | ||
173 | { | ||
174 | Some(associated_ty) => { | ||
175 | // FIXME handle type parameters on the segment | ||
176 | Ty::Projection(ProjectionTy { | ||
177 | associated_ty, | ||
178 | parameters: trait_ref.substs, | ||
179 | }) | ||
180 | } | ||
181 | None => { | ||
182 | // FIXME: report error (associated type not found) | ||
183 | Ty::Unknown | ||
184 | } | ||
185 | } | ||
186 | } else if remaining_segments.len() > 1 { | ||
187 | // FIXME report error (ambiguous associated type) | ||
188 | Ty::Unknown | ||
189 | } else { | ||
190 | Ty::Dyn(Arc::new([GenericPredicate::Implemented(trait_ref)])) | ||
191 | }; | ||
192 | } | ||
193 | TypeNs::GenericParam(idx) => { | ||
194 | // FIXME: maybe return name in resolution? | ||
195 | let name = resolved_segment.name.clone(); | ||
196 | Ty::Param { idx, name } | ||
197 | } | ||
198 | TypeNs::SelfType(impl_block) => ImplBlock::from(impl_block).target_ty(db), | ||
199 | TypeNs::AdtSelfType(adt) => Adt::from(adt).ty(db), | ||
200 | |||
201 | TypeNs::AdtId(it) => Ty::from_hir_path_inner(db, resolver, resolved_segment, it.into()), | ||
202 | TypeNs::BuiltinType(it) => { | ||
203 | Ty::from_hir_path_inner(db, resolver, resolved_segment, it.into()) | ||
204 | } | ||
205 | TypeNs::TypeAliasId(it) => { | ||
206 | Ty::from_hir_path_inner(db, resolver, resolved_segment, it.into()) | ||
207 | } | ||
208 | // FIXME: report error | ||
209 | TypeNs::EnumVariantId(_) => return Ty::Unknown, | ||
210 | }; | ||
211 | |||
212 | Ty::from_type_relative_path(db, resolver, ty, remaining_segments) | ||
213 | } | ||
214 | |||
215 | pub(crate) fn from_hir_path(db: &impl HirDatabase, resolver: &Resolver, path: &Path) -> Ty { | ||
216 | // Resolve the path (in type namespace) | ||
217 | if let crate::PathKind::Type(type_ref) = &path.kind { | ||
218 | let ty = Ty::from_hir(db, resolver, &type_ref); | ||
219 | let remaining_segments = &path.segments[..]; | ||
220 | return Ty::from_type_relative_path(db, resolver, ty, remaining_segments); | ||
221 | } | ||
222 | let (resolution, remaining_index) = match resolver.resolve_path_in_type_ns(db, path) { | ||
223 | Some(it) => it, | ||
224 | None => return Ty::Unknown, | ||
225 | }; | ||
226 | let (resolved_segment, remaining_segments) = match remaining_index { | ||
227 | None => ( | ||
228 | path.segments.last().expect("resolved path has at least one element"), | ||
229 | &[] as &[PathSegment], | ||
230 | ), | ||
231 | Some(i) => (&path.segments[i - 1], &path.segments[i..]), | ||
232 | }; | ||
233 | Ty::from_partly_resolved_hir_path( | ||
234 | db, | ||
235 | resolver, | ||
236 | resolution, | ||
237 | resolved_segment, | ||
238 | remaining_segments, | ||
239 | ) | ||
240 | } | ||
241 | |||
242 | fn select_associated_type( | ||
243 | db: &impl HirDatabase, | ||
244 | resolver: &Resolver, | ||
245 | self_ty: Ty, | ||
246 | segment: &PathSegment, | ||
247 | ) -> Ty { | ||
248 | let param_idx = match self_ty { | ||
249 | Ty::Param { idx, .. } => idx, | ||
250 | _ => return Ty::Unknown, // Error: Ambiguous associated type | ||
251 | }; | ||
252 | let def = match resolver.generic_def() { | ||
253 | Some(def) => def, | ||
254 | None => return Ty::Unknown, // this can't actually happen | ||
255 | }; | ||
256 | let predicates = db.generic_predicates_for_param(def.into(), param_idx); | ||
257 | let traits_from_env = predicates.iter().filter_map(|pred| match pred { | ||
258 | GenericPredicate::Implemented(tr) if tr.self_ty() == &self_ty => Some(tr.trait_), | ||
259 | _ => None, | ||
260 | }); | ||
261 | let traits = traits_from_env.flat_map(|t| t.all_super_traits(db)); | ||
262 | for t in traits { | ||
263 | if let Some(associated_ty) = t.associated_type_by_name(db, &segment.name) { | ||
264 | let substs = | ||
265 | Substs::build_for_def(db, t).push(self_ty.clone()).fill_with_unknown().build(); | ||
266 | // FIXME handle type parameters on the segment | ||
267 | return Ty::Projection(ProjectionTy { associated_ty, parameters: substs }); | ||
268 | } | ||
269 | } | ||
270 | Ty::Unknown | ||
271 | } | ||
272 | |||
273 | fn from_hir_path_inner( | ||
274 | db: &impl HirDatabase, | ||
275 | resolver: &Resolver, | ||
276 | segment: &PathSegment, | ||
277 | typable: TypableDef, | ||
278 | ) -> Ty { | ||
279 | let ty = db.type_for_def(typable, Namespace::Types); | ||
280 | let substs = Ty::substs_from_path_segment(db, resolver, segment, typable); | ||
281 | ty.subst(&substs) | ||
282 | } | ||
283 | |||
284 | pub(super) fn substs_from_path_segment( | ||
285 | db: &impl HirDatabase, | ||
286 | resolver: &Resolver, | ||
287 | segment: &PathSegment, | ||
288 | resolved: TypableDef, | ||
289 | ) -> Substs { | ||
290 | let def_generic: Option<GenericDef> = match resolved { | ||
291 | TypableDef::Function(func) => Some(func.into()), | ||
292 | TypableDef::Adt(adt) => Some(adt.into()), | ||
293 | TypableDef::EnumVariant(var) => Some(var.parent_enum(db).into()), | ||
294 | TypableDef::TypeAlias(t) => Some(t.into()), | ||
295 | TypableDef::Const(_) | TypableDef::Static(_) | TypableDef::BuiltinType(_) => None, | ||
296 | }; | ||
297 | substs_from_path_segment(db, resolver, segment, def_generic, false) | ||
298 | } | ||
299 | |||
300 | /// Collect generic arguments from a path into a `Substs`. See also | ||
301 | /// `create_substs_for_ast_path` and `def_to_ty` in rustc. | ||
302 | pub(super) fn substs_from_path( | ||
303 | db: &impl HirDatabase, | ||
304 | resolver: &Resolver, | ||
305 | path: &Path, | ||
306 | resolved: TypableDef, | ||
307 | ) -> Substs { | ||
308 | let last = path.segments.last().expect("path should have at least one segment"); | ||
309 | let segment = match resolved { | ||
310 | TypableDef::Function(_) | ||
311 | | TypableDef::Adt(_) | ||
312 | | TypableDef::Const(_) | ||
313 | | TypableDef::Static(_) | ||
314 | | TypableDef::TypeAlias(_) | ||
315 | | TypableDef::BuiltinType(_) => last, | ||
316 | TypableDef::EnumVariant(_) => { | ||
317 | // the generic args for an enum variant may be either specified | ||
318 | // on the segment referring to the enum, or on the segment | ||
319 | // referring to the variant. So `Option::<T>::None` and | ||
320 | // `Option::None::<T>` are both allowed (though the former is | ||
321 | // preferred). See also `def_ids_for_path_segments` in rustc. | ||
322 | let len = path.segments.len(); | ||
323 | let segment = if len >= 2 && path.segments[len - 2].args_and_bindings.is_some() { | ||
324 | // Option::<T>::None | ||
325 | &path.segments[len - 2] | ||
326 | } else { | ||
327 | // Option::None::<T> | ||
328 | last | ||
329 | }; | ||
330 | segment | ||
331 | } | ||
332 | }; | ||
333 | Ty::substs_from_path_segment(db, resolver, segment, resolved) | ||
334 | } | ||
335 | } | ||
336 | |||
337 | pub(super) fn substs_from_path_segment( | ||
338 | db: &impl HirDatabase, | ||
339 | resolver: &Resolver, | ||
340 | segment: &PathSegment, | ||
341 | def_generic: Option<GenericDef>, | ||
342 | add_self_param: bool, | ||
343 | ) -> Substs { | ||
344 | let mut substs = Vec::new(); | ||
345 | let def_generics = def_generic.map(|def| db.generic_params(def.into())); | ||
346 | |||
347 | let (parent_param_count, param_count) = | ||
348 | def_generics.map_or((0, 0), |g| (g.count_parent_params(), g.params.len())); | ||
349 | substs.extend(iter::repeat(Ty::Unknown).take(parent_param_count)); | ||
350 | if add_self_param { | ||
351 | // FIXME this add_self_param argument is kind of a hack: Traits have the | ||
352 | // Self type as an implicit first type parameter, but it can't be | ||
353 | // actually provided in the type arguments | ||
354 | // (well, actually sometimes it can, in the form of type-relative paths: `<Foo as Default>::default()`) | ||
355 | substs.push(Ty::Unknown); | ||
356 | } | ||
357 | if let Some(generic_args) = &segment.args_and_bindings { | ||
358 | // if args are provided, it should be all of them, but we can't rely on that | ||
359 | let self_param_correction = if add_self_param { 1 } else { 0 }; | ||
360 | let param_count = param_count - self_param_correction; | ||
361 | for arg in generic_args.args.iter().take(param_count) { | ||
362 | match arg { | ||
363 | GenericArg::Type(type_ref) => { | ||
364 | let ty = Ty::from_hir(db, resolver, type_ref); | ||
365 | substs.push(ty); | ||
366 | } | ||
367 | } | ||
368 | } | ||
369 | } | ||
370 | // add placeholders for args that were not provided | ||
371 | let supplied_params = substs.len(); | ||
372 | for _ in supplied_params..parent_param_count + param_count { | ||
373 | substs.push(Ty::Unknown); | ||
374 | } | ||
375 | assert_eq!(substs.len(), parent_param_count + param_count); | ||
376 | |||
377 | // handle defaults | ||
378 | if let Some(def_generic) = def_generic { | ||
379 | let default_substs = db.generic_defaults(def_generic); | ||
380 | assert_eq!(substs.len(), default_substs.len()); | ||
381 | |||
382 | for (i, default_ty) in default_substs.iter().enumerate() { | ||
383 | if substs[i] == Ty::Unknown { | ||
384 | substs[i] = default_ty.clone(); | ||
385 | } | ||
386 | } | ||
387 | } | ||
388 | |||
389 | Substs(substs.into()) | ||
390 | } | ||
391 | |||
392 | impl TraitRef { | ||
393 | pub(crate) fn from_path( | ||
394 | db: &impl HirDatabase, | ||
395 | resolver: &Resolver, | ||
396 | path: &Path, | ||
397 | explicit_self_ty: Option<Ty>, | ||
398 | ) -> Option<Self> { | ||
399 | let resolved = match resolver.resolve_path_in_type_ns_fully(db, &path)? { | ||
400 | TypeNs::TraitId(tr) => tr, | ||
401 | _ => return None, | ||
402 | }; | ||
403 | let segment = path.segments.last().expect("path should have at least one segment"); | ||
404 | Some(TraitRef::from_resolved_path(db, resolver, resolved.into(), segment, explicit_self_ty)) | ||
405 | } | ||
406 | |||
407 | pub(super) fn from_resolved_path( | ||
408 | db: &impl HirDatabase, | ||
409 | resolver: &Resolver, | ||
410 | resolved: Trait, | ||
411 | segment: &PathSegment, | ||
412 | explicit_self_ty: Option<Ty>, | ||
413 | ) -> Self { | ||
414 | let mut substs = TraitRef::substs_from_path(db, resolver, segment, resolved); | ||
415 | if let Some(self_ty) = explicit_self_ty { | ||
416 | make_mut_slice(&mut substs.0)[0] = self_ty; | ||
417 | } | ||
418 | TraitRef { trait_: resolved, substs } | ||
419 | } | ||
420 | |||
421 | pub(crate) fn from_hir( | ||
422 | db: &impl HirDatabase, | ||
423 | resolver: &Resolver, | ||
424 | type_ref: &TypeRef, | ||
425 | explicit_self_ty: Option<Ty>, | ||
426 | ) -> Option<Self> { | ||
427 | let path = match type_ref { | ||
428 | TypeRef::Path(path) => path, | ||
429 | _ => return None, | ||
430 | }; | ||
431 | TraitRef::from_path(db, resolver, path, explicit_self_ty) | ||
432 | } | ||
433 | |||
434 | fn substs_from_path( | ||
435 | db: &impl HirDatabase, | ||
436 | resolver: &Resolver, | ||
437 | segment: &PathSegment, | ||
438 | resolved: Trait, | ||
439 | ) -> Substs { | ||
440 | let has_self_param = | ||
441 | segment.args_and_bindings.as_ref().map(|a| a.has_self_type).unwrap_or(false); | ||
442 | substs_from_path_segment(db, resolver, segment, Some(resolved.into()), !has_self_param) | ||
443 | } | ||
444 | |||
445 | pub(crate) fn for_trait(db: &impl HirDatabase, trait_: Trait) -> TraitRef { | ||
446 | let substs = Substs::identity(&db.generic_params(trait_.id.into())); | ||
447 | TraitRef { trait_, substs } | ||
448 | } | ||
449 | |||
450 | pub(crate) fn from_type_bound( | ||
451 | db: &impl HirDatabase, | ||
452 | resolver: &Resolver, | ||
453 | bound: &TypeBound, | ||
454 | self_ty: Ty, | ||
455 | ) -> Option<TraitRef> { | ||
456 | match bound { | ||
457 | TypeBound::Path(path) => TraitRef::from_path(db, resolver, path, Some(self_ty)), | ||
458 | TypeBound::Error => None, | ||
459 | } | ||
460 | } | ||
461 | } | ||
462 | |||
463 | impl GenericPredicate { | ||
464 | pub(crate) fn from_where_predicate<'a>( | ||
465 | db: &'a impl HirDatabase, | ||
466 | resolver: &'a Resolver, | ||
467 | where_predicate: &'a WherePredicate, | ||
468 | ) -> impl Iterator<Item = GenericPredicate> + 'a { | ||
469 | let self_ty = Ty::from_hir(db, resolver, &where_predicate.type_ref); | ||
470 | GenericPredicate::from_type_bound(db, resolver, &where_predicate.bound, self_ty) | ||
471 | } | ||
472 | |||
473 | pub(crate) fn from_type_bound<'a>( | ||
474 | db: &'a impl HirDatabase, | ||
475 | resolver: &'a Resolver, | ||
476 | bound: &'a TypeBound, | ||
477 | self_ty: Ty, | ||
478 | ) -> impl Iterator<Item = GenericPredicate> + 'a { | ||
479 | let trait_ref = TraitRef::from_type_bound(db, &resolver, bound, self_ty); | ||
480 | iter::once(trait_ref.clone().map_or(GenericPredicate::Error, GenericPredicate::Implemented)) | ||
481 | .chain( | ||
482 | trait_ref.into_iter().flat_map(move |tr| { | ||
483 | assoc_type_bindings_from_type_bound(db, resolver, bound, tr) | ||
484 | }), | ||
485 | ) | ||
486 | } | ||
487 | } | ||
488 | |||
489 | fn assoc_type_bindings_from_type_bound<'a>( | ||
490 | db: &'a impl HirDatabase, | ||
491 | resolver: &'a Resolver, | ||
492 | bound: &'a TypeBound, | ||
493 | trait_ref: TraitRef, | ||
494 | ) -> impl Iterator<Item = GenericPredicate> + 'a { | ||
495 | let last_segment = match bound { | ||
496 | TypeBound::Path(path) => path.segments.last(), | ||
497 | TypeBound::Error => None, | ||
498 | }; | ||
499 | last_segment | ||
500 | .into_iter() | ||
501 | .flat_map(|segment| segment.args_and_bindings.iter()) | ||
502 | .flat_map(|args_and_bindings| args_and_bindings.bindings.iter()) | ||
503 | .map(move |(name, type_ref)| { | ||
504 | let associated_ty = | ||
505 | match trait_ref.trait_.associated_type_by_name_including_super_traits(db, &name) { | ||
506 | None => return GenericPredicate::Error, | ||
507 | Some(t) => t, | ||
508 | }; | ||
509 | let projection_ty = | ||
510 | ProjectionTy { associated_ty, parameters: trait_ref.substs.clone() }; | ||
511 | let ty = Ty::from_hir(db, resolver, type_ref); | ||
512 | let projection_predicate = ProjectionPredicate { projection_ty, ty }; | ||
513 | GenericPredicate::Projection(projection_predicate) | ||
514 | }) | ||
515 | } | ||
516 | |||
517 | /// Build the declared type of an item. This depends on the namespace; e.g. for | ||
518 | /// `struct Foo(usize)`, we have two types: The type of the struct itself, and | ||
519 | /// the constructor function `(usize) -> Foo` which lives in the values | ||
520 | /// namespace. | ||
521 | pub(crate) fn type_for_def(db: &impl HirDatabase, def: TypableDef, ns: Namespace) -> Ty { | ||
522 | match (def, ns) { | ||
523 | (TypableDef::Function(f), Namespace::Values) => type_for_fn(db, f), | ||
524 | (TypableDef::Adt(Adt::Struct(s)), Namespace::Values) => type_for_struct_constructor(db, s), | ||
525 | (TypableDef::Adt(adt), Namespace::Types) => type_for_adt(db, adt), | ||
526 | (TypableDef::EnumVariant(v), Namespace::Values) => type_for_enum_variant_constructor(db, v), | ||
527 | (TypableDef::TypeAlias(t), Namespace::Types) => type_for_type_alias(db, t), | ||
528 | (TypableDef::Const(c), Namespace::Values) => type_for_const(db, c), | ||
529 | (TypableDef::Static(c), Namespace::Values) => type_for_static(db, c), | ||
530 | (TypableDef::BuiltinType(t), Namespace::Types) => type_for_builtin(t), | ||
531 | |||
532 | // 'error' cases: | ||
533 | (TypableDef::Function(_), Namespace::Types) => Ty::Unknown, | ||
534 | (TypableDef::Adt(Adt::Union(_)), Namespace::Values) => Ty::Unknown, | ||
535 | (TypableDef::Adt(Adt::Enum(_)), Namespace::Values) => Ty::Unknown, | ||
536 | (TypableDef::EnumVariant(_), Namespace::Types) => Ty::Unknown, | ||
537 | (TypableDef::TypeAlias(_), Namespace::Values) => Ty::Unknown, | ||
538 | (TypableDef::Const(_), Namespace::Types) => Ty::Unknown, | ||
539 | (TypableDef::Static(_), Namespace::Types) => Ty::Unknown, | ||
540 | (TypableDef::BuiltinType(_), Namespace::Values) => Ty::Unknown, | ||
541 | } | ||
542 | } | ||
543 | |||
544 | /// Build the signature of a callable item (function, struct or enum variant). | ||
545 | pub(crate) fn callable_item_sig(db: &impl HirDatabase, def: CallableDef) -> FnSig { | ||
546 | match def { | ||
547 | CallableDef::Function(f) => fn_sig_for_fn(db, f), | ||
548 | CallableDef::Struct(s) => fn_sig_for_struct_constructor(db, s), | ||
549 | CallableDef::EnumVariant(e) => fn_sig_for_enum_variant_constructor(db, e), | ||
550 | } | ||
551 | } | ||
552 | |||
553 | /// Build the type of all specific fields of a struct or enum variant. | ||
554 | pub(crate) fn field_types_query( | ||
555 | db: &impl HirDatabase, | ||
556 | variant_id: VariantId, | ||
557 | ) -> Arc<ArenaMap<LocalStructFieldId, Ty>> { | ||
558 | let (resolver, var_data) = match variant_id { | ||
559 | VariantId::StructId(it) => (it.resolver(db), db.struct_data(it.0).variant_data.clone()), | ||
560 | VariantId::EnumVariantId(it) => ( | ||
561 | it.parent.resolver(db), | ||
562 | db.enum_data(it.parent).variants[it.local_id].variant_data.clone(), | ||
563 | ), | ||
564 | }; | ||
565 | let mut res = ArenaMap::default(); | ||
566 | for (field_id, field_data) in var_data.fields().iter() { | ||
567 | res.insert(field_id, Ty::from_hir(db, &resolver, &field_data.type_ref)) | ||
568 | } | ||
569 | Arc::new(res) | ||
570 | } | ||
571 | |||
572 | /// This query exists only to be used when resolving short-hand associated types | ||
573 | /// like `T::Item`. | ||
574 | /// | ||
575 | /// See the analogous query in rustc and its comment: | ||
576 | /// https://github.com/rust-lang/rust/blob/9150f844e2624eb013ec78ca08c1d416e6644026/src/librustc_typeck/astconv.rs#L46 | ||
577 | /// This is a query mostly to handle cycles somewhat gracefully; e.g. the | ||
578 | /// following bounds are disallowed: `T: Foo<U::Item>, U: Foo<T::Item>`, but | ||
579 | /// these are fine: `T: Foo<U::Item>, U: Foo<()>`. | ||
580 | pub(crate) fn generic_predicates_for_param_query( | ||
581 | db: &impl HirDatabase, | ||
582 | def: GenericDef, | ||
583 | param_idx: u32, | ||
584 | ) -> Arc<[GenericPredicate]> { | ||
585 | let resolver = GenericDefId::from(def).resolver(db); | ||
586 | resolver | ||
587 | .where_predicates_in_scope() | ||
588 | // we have to filter out all other predicates *first*, before attempting to lower them | ||
589 | .filter(|pred| Ty::from_hir_only_param(db, &resolver, &pred.type_ref) == Some(param_idx)) | ||
590 | .flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred)) | ||
591 | .collect() | ||
592 | } | ||
593 | |||
594 | pub(crate) fn trait_env( | ||
595 | db: &impl HirDatabase, | ||
596 | resolver: &Resolver, | ||
597 | ) -> Arc<super::TraitEnvironment> { | ||
598 | let predicates = resolver | ||
599 | .where_predicates_in_scope() | ||
600 | .flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred)) | ||
601 | .collect::<Vec<_>>(); | ||
602 | |||
603 | Arc::new(super::TraitEnvironment { predicates }) | ||
604 | } | ||
605 | |||
606 | /// Resolve the where clause(s) of an item with generics. | ||
607 | pub(crate) fn generic_predicates_query( | ||
608 | db: &impl HirDatabase, | ||
609 | def: GenericDef, | ||
610 | ) -> Arc<[GenericPredicate]> { | ||
611 | let resolver = GenericDefId::from(def).resolver(db); | ||
612 | resolver | ||
613 | .where_predicates_in_scope() | ||
614 | .flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred)) | ||
615 | .collect() | ||
616 | } | ||
617 | |||
618 | /// Resolve the default type params from generics | ||
619 | pub(crate) fn generic_defaults_query(db: &impl HirDatabase, def: GenericDef) -> Substs { | ||
620 | let resolver = GenericDefId::from(def).resolver(db); | ||
621 | let generic_params = db.generic_params(def.into()); | ||
622 | |||
623 | let defaults = generic_params | ||
624 | .params_including_parent() | ||
625 | .into_iter() | ||
626 | .map(|p| p.default.as_ref().map_or(Ty::Unknown, |t| Ty::from_hir(db, &resolver, t))) | ||
627 | .collect(); | ||
628 | |||
629 | Substs(defaults) | ||
630 | } | ||
631 | |||
632 | fn fn_sig_for_fn(db: &impl HirDatabase, def: Function) -> FnSig { | ||
633 | let data = db.function_data(def.id); | ||
634 | let resolver = def.id.resolver(db); | ||
635 | let params = data.params.iter().map(|tr| Ty::from_hir(db, &resolver, tr)).collect::<Vec<_>>(); | ||
636 | let ret = Ty::from_hir(db, &resolver, &data.ret_type); | ||
637 | FnSig::from_params_and_return(params, ret) | ||
638 | } | ||
639 | |||
640 | /// Build the declared type of a function. This should not need to look at the | ||
641 | /// function body. | ||
642 | fn type_for_fn(db: &impl HirDatabase, def: Function) -> Ty { | ||
643 | let generics = db.generic_params(def.id.into()); | ||
644 | let substs = Substs::identity(&generics); | ||
645 | Ty::apply(TypeCtor::FnDef(def.into()), substs) | ||
646 | } | ||
647 | |||
648 | /// Build the declared type of a const. | ||
649 | fn type_for_const(db: &impl HirDatabase, def: Const) -> Ty { | ||
650 | let data = db.const_data(def.id); | ||
651 | let resolver = def.id.resolver(db); | ||
652 | |||
653 | Ty::from_hir(db, &resolver, &data.type_ref) | ||
654 | } | ||
655 | |||
656 | /// Build the declared type of a static. | ||
657 | fn type_for_static(db: &impl HirDatabase, def: Static) -> Ty { | ||
658 | let data = db.static_data(def.id); | ||
659 | let resolver = def.id.resolver(db); | ||
660 | |||
661 | Ty::from_hir(db, &resolver, &data.type_ref) | ||
662 | } | ||
663 | |||
664 | /// Build the declared type of a static. | ||
665 | fn type_for_builtin(def: BuiltinType) -> Ty { | ||
666 | Ty::simple(match def { | ||
667 | BuiltinType::Char => TypeCtor::Char, | ||
668 | BuiltinType::Bool => TypeCtor::Bool, | ||
669 | BuiltinType::Str => TypeCtor::Str, | ||
670 | BuiltinType::Int(t) => TypeCtor::Int(IntTy::from(t).into()), | ||
671 | BuiltinType::Float(t) => TypeCtor::Float(FloatTy::from(t).into()), | ||
672 | }) | ||
673 | } | ||
674 | |||
675 | impl From<BuiltinInt> for IntTy { | ||
676 | fn from(t: BuiltinInt) -> Self { | ||
677 | IntTy { signedness: t.signedness, bitness: t.bitness } | ||
678 | } | ||
679 | } | ||
680 | |||
681 | impl From<BuiltinFloat> for FloatTy { | ||
682 | fn from(t: BuiltinFloat) -> Self { | ||
683 | FloatTy { bitness: t.bitness } | ||
684 | } | ||
685 | } | ||
686 | |||
687 | impl From<Option<BuiltinInt>> for Uncertain<IntTy> { | ||
688 | fn from(t: Option<BuiltinInt>) -> Self { | ||
689 | match t { | ||
690 | None => Uncertain::Unknown, | ||
691 | Some(t) => Uncertain::Known(t.into()), | ||
692 | } | ||
693 | } | ||
694 | } | ||
695 | |||
696 | impl From<Option<BuiltinFloat>> for Uncertain<FloatTy> { | ||
697 | fn from(t: Option<BuiltinFloat>) -> Self { | ||
698 | match t { | ||
699 | None => Uncertain::Unknown, | ||
700 | Some(t) => Uncertain::Known(t.into()), | ||
701 | } | ||
702 | } | ||
703 | } | ||
704 | |||
705 | fn fn_sig_for_struct_constructor(db: &impl HirDatabase, def: Struct) -> FnSig { | ||
706 | let struct_data = db.struct_data(def.id.into()); | ||
707 | let fields = struct_data.variant_data.fields(); | ||
708 | let resolver = def.id.resolver(db); | ||
709 | let params = fields | ||
710 | .iter() | ||
711 | .map(|(_, field)| Ty::from_hir(db, &resolver, &field.type_ref)) | ||
712 | .collect::<Vec<_>>(); | ||
713 | let ret = type_for_adt(db, def); | ||
714 | FnSig::from_params_and_return(params, ret) | ||
715 | } | ||
716 | |||
717 | /// Build the type of a tuple struct constructor. | ||
718 | fn type_for_struct_constructor(db: &impl HirDatabase, def: Struct) -> Ty { | ||
719 | let struct_data = db.struct_data(def.id.into()); | ||
720 | if struct_data.variant_data.is_unit() { | ||
721 | return type_for_adt(db, def); // Unit struct | ||
722 | } | ||
723 | let generics = db.generic_params(def.id.into()); | ||
724 | let substs = Substs::identity(&generics); | ||
725 | Ty::apply(TypeCtor::FnDef(def.into()), substs) | ||
726 | } | ||
727 | |||
728 | fn fn_sig_for_enum_variant_constructor(db: &impl HirDatabase, def: EnumVariant) -> FnSig { | ||
729 | let var_data = def.variant_data(db); | ||
730 | let fields = var_data.fields(); | ||
731 | let resolver = def.parent.id.resolver(db); | ||
732 | let params = fields | ||
733 | .iter() | ||
734 | .map(|(_, field)| Ty::from_hir(db, &resolver, &field.type_ref)) | ||
735 | .collect::<Vec<_>>(); | ||
736 | let generics = db.generic_params(def.parent_enum(db).id.into()); | ||
737 | let substs = Substs::identity(&generics); | ||
738 | let ret = type_for_adt(db, def.parent_enum(db)).subst(&substs); | ||
739 | FnSig::from_params_and_return(params, ret) | ||
740 | } | ||
741 | |||
742 | /// Build the type of a tuple enum variant constructor. | ||
743 | fn type_for_enum_variant_constructor(db: &impl HirDatabase, def: EnumVariant) -> Ty { | ||
744 | let var_data = def.variant_data(db); | ||
745 | if var_data.is_unit() { | ||
746 | return type_for_adt(db, def.parent_enum(db)); // Unit variant | ||
747 | } | ||
748 | let generics = db.generic_params(def.parent_enum(db).id.into()); | ||
749 | let substs = Substs::identity(&generics); | ||
750 | Ty::apply(TypeCtor::FnDef(def.into()), substs) | ||
751 | } | ||
752 | |||
753 | fn type_for_adt(db: &impl HirDatabase, adt: impl Into<Adt>) -> Ty { | ||
754 | let adt = adt.into(); | ||
755 | let adt_id: AdtId = adt.into(); | ||
756 | let generics = db.generic_params(adt_id.into()); | ||
757 | Ty::apply(TypeCtor::Adt(adt), Substs::identity(&generics)) | ||
758 | } | ||
759 | |||
760 | fn type_for_type_alias(db: &impl HirDatabase, t: TypeAlias) -> Ty { | ||
761 | let generics = db.generic_params(t.id.into()); | ||
762 | let resolver = t.id.resolver(db); | ||
763 | let type_ref = t.type_ref(db); | ||
764 | let substs = Substs::identity(&generics); | ||
765 | let inner = Ty::from_hir(db, &resolver, &type_ref.unwrap_or(TypeRef::Error)); | ||
766 | inner.subst(&substs) | ||
767 | } | ||
768 | |||
769 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] | ||
770 | pub enum TypableDef { | ||
771 | Function(Function), | ||
772 | Adt(Adt), | ||
773 | EnumVariant(EnumVariant), | ||
774 | TypeAlias(TypeAlias), | ||
775 | Const(Const), | ||
776 | Static(Static), | ||
777 | BuiltinType(BuiltinType), | ||
778 | } | ||
779 | impl_froms!( | ||
780 | TypableDef: Function, | ||
781 | Adt(Struct, Enum, Union), | ||
782 | EnumVariant, | ||
783 | TypeAlias, | ||
784 | Const, | ||
785 | Static, | ||
786 | BuiltinType | ||
787 | ); | ||
788 | |||
789 | impl From<ModuleDef> for Option<TypableDef> { | ||
790 | fn from(def: ModuleDef) -> Option<TypableDef> { | ||
791 | let res = match def { | ||
792 | ModuleDef::Function(f) => f.into(), | ||
793 | ModuleDef::Adt(adt) => adt.into(), | ||
794 | ModuleDef::EnumVariant(v) => v.into(), | ||
795 | ModuleDef::TypeAlias(t) => t.into(), | ||
796 | ModuleDef::Const(v) => v.into(), | ||
797 | ModuleDef::Static(v) => v.into(), | ||
798 | ModuleDef::BuiltinType(t) => t.into(), | ||
799 | ModuleDef::Module(_) | ModuleDef::Trait(_) => return None, | ||
800 | }; | ||
801 | Some(res) | ||
802 | } | ||
803 | } | ||
804 | |||
805 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] | ||
806 | pub enum CallableDef { | ||
807 | Function(Function), | ||
808 | Struct(Struct), | ||
809 | EnumVariant(EnumVariant), | ||
810 | } | ||
811 | impl_froms!(CallableDef: Function, Struct, EnumVariant); | ||
812 | |||
813 | impl CallableDef { | ||
814 | pub fn krate(self, db: &impl HirDatabase) -> Option<crate::Crate> { | ||
815 | match self { | ||
816 | CallableDef::Function(f) => f.krate(db), | ||
817 | CallableDef::Struct(s) => s.krate(db), | ||
818 | CallableDef::EnumVariant(e) => e.parent_enum(db).krate(db), | ||
819 | } | ||
820 | } | ||
821 | } | ||
822 | |||
823 | impl From<CallableDef> for GenericDef { | ||
824 | fn from(def: CallableDef) -> GenericDef { | ||
825 | match def { | ||
826 | CallableDef::Function(f) => f.into(), | ||
827 | CallableDef::Struct(s) => s.into(), | ||
828 | CallableDef::EnumVariant(e) => e.into(), | ||
829 | } | ||
830 | } | ||
831 | } | ||
diff --git a/crates/ra_hir/src/ty/method_resolution.rs b/crates/ra_hir/src/ty/method_resolution.rs deleted file mode 100644 index caa5f5f74..000000000 --- a/crates/ra_hir/src/ty/method_resolution.rs +++ /dev/null | |||
@@ -1,375 +0,0 @@ | |||
1 | //! This module is concerned with finding methods that a given type provides. | ||
2 | //! For details about how this works in rustc, see the method lookup page in the | ||
3 | //! [rustc guide](https://rust-lang.github.io/rustc-guide/method-lookup.html) | ||
4 | //! and the corresponding code mostly in librustc_typeck/check/method/probe.rs. | ||
5 | use std::sync::Arc; | ||
6 | |||
7 | use arrayvec::ArrayVec; | ||
8 | use hir_def::{lang_item::LangItemTarget, resolver::Resolver, AstItemDef}; | ||
9 | use rustc_hash::FxHashMap; | ||
10 | |||
11 | use crate::{ | ||
12 | db::HirDatabase, | ||
13 | ty::primitive::{FloatBitness, Uncertain}, | ||
14 | ty::{Ty, TypeCtor}, | ||
15 | AssocItem, Crate, Function, ImplBlock, Module, Mutability, Name, Trait, | ||
16 | }; | ||
17 | |||
18 | use super::{autoderef, lower, Canonical, InEnvironment, TraitEnvironment, TraitRef}; | ||
19 | |||
20 | /// This is used as a key for indexing impls. | ||
21 | #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] | ||
22 | pub enum TyFingerprint { | ||
23 | Apply(TypeCtor), | ||
24 | } | ||
25 | |||
26 | impl TyFingerprint { | ||
27 | /// Creates a TyFingerprint for looking up an impl. Only certain types can | ||
28 | /// have impls: if we have some `struct S`, we can have an `impl S`, but not | ||
29 | /// `impl &S`. Hence, this will return `None` for reference types and such. | ||
30 | fn for_impl(ty: &Ty) -> Option<TyFingerprint> { | ||
31 | match ty { | ||
32 | Ty::Apply(a_ty) => Some(TyFingerprint::Apply(a_ty.ctor)), | ||
33 | _ => None, | ||
34 | } | ||
35 | } | ||
36 | } | ||
37 | |||
38 | #[derive(Debug, PartialEq, Eq)] | ||
39 | pub struct CrateImplBlocks { | ||
40 | impls: FxHashMap<TyFingerprint, Vec<ImplBlock>>, | ||
41 | impls_by_trait: FxHashMap<Trait, Vec<ImplBlock>>, | ||
42 | } | ||
43 | |||
44 | impl CrateImplBlocks { | ||
45 | pub(crate) fn impls_in_crate_query( | ||
46 | db: &impl HirDatabase, | ||
47 | krate: Crate, | ||
48 | ) -> Arc<CrateImplBlocks> { | ||
49 | let mut crate_impl_blocks = | ||
50 | CrateImplBlocks { impls: FxHashMap::default(), impls_by_trait: FxHashMap::default() }; | ||
51 | if let Some(module) = krate.root_module(db) { | ||
52 | crate_impl_blocks.collect_recursive(db, module); | ||
53 | } | ||
54 | Arc::new(crate_impl_blocks) | ||
55 | } | ||
56 | pub fn lookup_impl_blocks(&self, ty: &Ty) -> impl Iterator<Item = ImplBlock> + '_ { | ||
57 | let fingerprint = TyFingerprint::for_impl(ty); | ||
58 | fingerprint.and_then(|f| self.impls.get(&f)).into_iter().flatten().copied() | ||
59 | } | ||
60 | |||
61 | pub fn lookup_impl_blocks_for_trait(&self, tr: Trait) -> impl Iterator<Item = ImplBlock> + '_ { | ||
62 | self.impls_by_trait.get(&tr).into_iter().flatten().copied() | ||
63 | } | ||
64 | |||
65 | pub fn all_impls<'a>(&'a self) -> impl Iterator<Item = ImplBlock> + 'a { | ||
66 | self.impls.values().chain(self.impls_by_trait.values()).flatten().copied() | ||
67 | } | ||
68 | |||
69 | fn collect_recursive(&mut self, db: &impl HirDatabase, module: Module) { | ||
70 | for impl_block in module.impl_blocks(db) { | ||
71 | let target_ty = impl_block.target_ty(db); | ||
72 | |||
73 | if impl_block.target_trait(db).is_some() { | ||
74 | if let Some(tr) = impl_block.target_trait_ref(db) { | ||
75 | self.impls_by_trait.entry(tr.trait_).or_default().push(impl_block); | ||
76 | } | ||
77 | } else { | ||
78 | if let Some(target_ty_fp) = TyFingerprint::for_impl(&target_ty) { | ||
79 | self.impls.entry(target_ty_fp).or_default().push(impl_block); | ||
80 | } | ||
81 | } | ||
82 | } | ||
83 | |||
84 | for child in module.children(db) { | ||
85 | self.collect_recursive(db, child); | ||
86 | } | ||
87 | } | ||
88 | } | ||
89 | |||
90 | fn def_crates(db: &impl HirDatabase, cur_crate: Crate, ty: &Ty) -> Option<ArrayVec<[Crate; 2]>> { | ||
91 | // Types like slice can have inherent impls in several crates, (core and alloc). | ||
92 | // The corresponding impls are marked with lang items, so we can use them to find the required crates. | ||
93 | macro_rules! lang_item_crate { | ||
94 | ($($name:expr),+ $(,)?) => {{ | ||
95 | let mut v = ArrayVec::<[LangItemTarget; 2]>::new(); | ||
96 | $( | ||
97 | v.extend(db.lang_item(cur_crate.crate_id, $name.into())); | ||
98 | )+ | ||
99 | v | ||
100 | }}; | ||
101 | } | ||
102 | |||
103 | let lang_item_targets = match ty { | ||
104 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
105 | TypeCtor::Adt(def_id) => return Some(std::iter::once(def_id.krate(db)?).collect()), | ||
106 | TypeCtor::Bool => lang_item_crate!("bool"), | ||
107 | TypeCtor::Char => lang_item_crate!("char"), | ||
108 | TypeCtor::Float(Uncertain::Known(f)) => match f.bitness { | ||
109 | // There are two lang items: one in libcore (fXX) and one in libstd (fXX_runtime) | ||
110 | FloatBitness::X32 => lang_item_crate!("f32", "f32_runtime"), | ||
111 | FloatBitness::X64 => lang_item_crate!("f64", "f64_runtime"), | ||
112 | }, | ||
113 | TypeCtor::Int(Uncertain::Known(i)) => lang_item_crate!(i.ty_to_string()), | ||
114 | TypeCtor::Str => lang_item_crate!("str_alloc", "str"), | ||
115 | TypeCtor::Slice => lang_item_crate!("slice_alloc", "slice"), | ||
116 | TypeCtor::RawPtr(Mutability::Shared) => lang_item_crate!("const_ptr"), | ||
117 | TypeCtor::RawPtr(Mutability::Mut) => lang_item_crate!("mut_ptr"), | ||
118 | _ => return None, | ||
119 | }, | ||
120 | _ => return None, | ||
121 | }; | ||
122 | let res = lang_item_targets | ||
123 | .into_iter() | ||
124 | .filter_map(|it| match it { | ||
125 | LangItemTarget::ImplBlockId(it) => Some(it), | ||
126 | _ => None, | ||
127 | }) | ||
128 | .map(|it| it.module(db).krate.into()) | ||
129 | .collect(); | ||
130 | Some(res) | ||
131 | } | ||
132 | |||
133 | /// Look up the method with the given name, returning the actual autoderefed | ||
134 | /// receiver type (but without autoref applied yet). | ||
135 | pub(crate) fn lookup_method( | ||
136 | ty: &Canonical<Ty>, | ||
137 | db: &impl HirDatabase, | ||
138 | name: &Name, | ||
139 | resolver: &Resolver, | ||
140 | ) -> Option<(Ty, Function)> { | ||
141 | iterate_method_candidates(ty, db, resolver, Some(name), LookupMode::MethodCall, |ty, f| match f | ||
142 | { | ||
143 | AssocItem::Function(f) => Some((ty.clone(), f)), | ||
144 | _ => None, | ||
145 | }) | ||
146 | } | ||
147 | |||
148 | /// Whether we're looking up a dotted method call (like `v.len()`) or a path | ||
149 | /// (like `Vec::new`). | ||
150 | #[derive(Copy, Clone, Debug, PartialEq, Eq)] | ||
151 | pub enum LookupMode { | ||
152 | /// Looking up a method call like `v.len()`: We only consider candidates | ||
153 | /// that have a `self` parameter, and do autoderef. | ||
154 | MethodCall, | ||
155 | /// Looking up a path like `Vec::new` or `Vec::default`: We consider all | ||