diff options
author | Seivan Heidari <[email protected]> | 2019-11-28 07:19:14 +0000 |
---|---|---|
committer | Seivan Heidari <[email protected]> | 2019-11-28 07:19:14 +0000 |
commit | 18a0937585b836ec5ed054b9ae48e0156ab6d9ef (patch) | |
tree | 9de2c0267ddcc00df717f90034d0843d751a851b /crates/ra_hir/src/ty | |
parent | a7394b44c870f585eacfeb3036a33471aff49ff8 (diff) | |
parent | 484acc8a61d599662ed63a4cbda091d38a982551 (diff) |
Merge branch 'master' of https://github.com/rust-analyzer/rust-analyzer into feature/themes
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 | ||
156 | /// candidates including associated constants, but don't do autoderef. | ||
157 | Path, | ||
158 | } | ||
159 | |||
160 | // This would be nicer if it just returned an iterator, but that runs into | ||
161 | // lifetime problems, because we need to borrow temp `CrateImplBlocks`. | ||
162 | // FIXME add a context type here? | ||
163 | pub(crate) fn iterate_method_candidates<T>( | ||
164 | ty: &Canonical<Ty>, | ||
165 | db: &impl HirDatabase, | ||
166 | resolver: &Resolver, | ||
167 | name: Option<&Name>, | ||
168 | mode: LookupMode, | ||
169 | mut callback: impl FnMut(&Ty, AssocItem) -> Option<T>, | ||
170 | ) -> Option<T> { | ||
171 | let krate = resolver.krate()?; | ||
172 | match mode { | ||
173 | LookupMode::MethodCall => { | ||
174 | // For method calls, rust first does any number of autoderef, and then one | ||
175 | // autoref (i.e. when the method takes &self or &mut self). We just ignore | ||
176 | // the autoref currently -- when we find a method matching the given name, | ||
177 | // we assume it fits. | ||
178 | |||
179 | // Also note that when we've got a receiver like &S, even if the method we | ||
180 | // find in the end takes &self, we still do the autoderef step (just as | ||
181 | // rustc does an autoderef and then autoref again). | ||
182 | |||
183 | for derefed_ty in autoderef::autoderef(db, resolver, ty.clone()) { | ||
184 | if let Some(result) = iterate_inherent_methods( | ||
185 | &derefed_ty, | ||
186 | db, | ||
187 | name, | ||
188 | mode, | ||
189 | krate.into(), | ||
190 | &mut callback, | ||
191 | ) { | ||
192 | return Some(result); | ||
193 | } | ||
194 | if let Some(result) = iterate_trait_method_candidates( | ||
195 | &derefed_ty, | ||
196 | db, | ||
197 | resolver, | ||
198 | name, | ||
199 | mode, | ||
200 | &mut callback, | ||
201 | ) { | ||
202 | return Some(result); | ||
203 | } | ||
204 | } | ||
205 | } | ||
206 | LookupMode::Path => { | ||
207 | // No autoderef for path lookups | ||
208 | if let Some(result) = | ||
209 | iterate_inherent_methods(&ty, db, name, mode, krate.into(), &mut callback) | ||
210 | { | ||
211 | return Some(result); | ||
212 | } | ||
213 | if let Some(result) = | ||
214 | iterate_trait_method_candidates(&ty, db, resolver, name, mode, &mut callback) | ||
215 | { | ||
216 | return Some(result); | ||
217 | } | ||
218 | } | ||
219 | } | ||
220 | None | ||
221 | } | ||
222 | |||
223 | fn iterate_trait_method_candidates<T>( | ||
224 | ty: &Canonical<Ty>, | ||
225 | db: &impl HirDatabase, | ||
226 | resolver: &Resolver, | ||
227 | name: Option<&Name>, | ||
228 | mode: LookupMode, | ||
229 | mut callback: impl FnMut(&Ty, AssocItem) -> Option<T>, | ||
230 | ) -> Option<T> { | ||
231 | let krate = resolver.krate()?; | ||
232 | // FIXME: maybe put the trait_env behind a query (need to figure out good input parameters for that) | ||
233 | let env = lower::trait_env(db, resolver); | ||
234 | // if ty is `impl Trait` or `dyn Trait`, the trait doesn't need to be in scope | ||
235 | let inherent_trait = ty.value.inherent_trait().into_iter(); | ||
236 | // if we have `T: Trait` in the param env, the trait doesn't need to be in scope | ||
237 | let traits_from_env = env | ||
238 | .trait_predicates_for_self_ty(&ty.value) | ||
239 | .map(|tr| tr.trait_) | ||
240 | .flat_map(|t| t.all_super_traits(db)); | ||
241 | let traits = inherent_trait | ||
242 | .chain(traits_from_env) | ||
243 | .chain(resolver.traits_in_scope(db).into_iter().map(Trait::from)); | ||
244 | 'traits: for t in traits { | ||
245 | let data = db.trait_data(t.id); | ||
246 | |||
247 | // we'll be lazy about checking whether the type implements the | ||
248 | // trait, but if we find out it doesn't, we'll skip the rest of the | ||
249 | // iteration | ||
250 | let mut known_implemented = false; | ||
251 | for &item in data.items.iter() { | ||
252 | if !is_valid_candidate(db, name, mode, item.into()) { | ||
253 | continue; | ||
254 | } | ||
255 | if !known_implemented { | ||
256 | let goal = generic_implements_goal(db, env.clone(), t, ty.clone()); | ||
257 | if db.trait_solve(krate.into(), goal).is_none() { | ||
258 | continue 'traits; | ||
259 | } | ||
260 | } | ||
261 | known_implemented = true; | ||
262 | if let Some(result) = callback(&ty.value, item.into()) { | ||
263 | return Some(result); | ||
264 | } | ||
265 | } | ||
266 | } | ||
267 | None | ||
268 | } | ||
269 | |||
270 | fn iterate_inherent_methods<T>( | ||
271 | ty: &Canonical<Ty>, | ||
272 | db: &impl HirDatabase, | ||
273 | name: Option<&Name>, | ||
274 | mode: LookupMode, | ||
275 | krate: Crate, | ||
276 | mut callback: impl FnMut(&Ty, AssocItem) -> Option<T>, | ||
277 | ) -> Option<T> { | ||
278 | for krate in def_crates(db, krate, &ty.value)? { | ||
279 | let impls = db.impls_in_crate(krate); | ||
280 | |||
281 | for impl_block in impls.lookup_impl_blocks(&ty.value) { | ||
282 | for item in impl_block.items(db) { | ||
283 | if !is_valid_candidate(db, name, mode, item) { | ||
284 | continue; | ||
285 | } | ||
286 | if let Some(result) = callback(&ty.value, item) { | ||
287 | return Some(result); | ||
288 | } | ||
289 | } | ||
290 | } | ||
291 | } | ||
292 | None | ||
293 | } | ||
294 | |||
295 | fn is_valid_candidate( | ||
296 | db: &impl HirDatabase, | ||
297 | name: Option<&Name>, | ||
298 | mode: LookupMode, | ||
299 | item: AssocItem, | ||
300 | ) -> bool { | ||
301 | match item { | ||
302 | AssocItem::Function(m) => { | ||
303 | let data = db.function_data(m.id); | ||
304 | name.map_or(true, |name| data.name == *name) | ||
305 | && (data.has_self_param || mode == LookupMode::Path) | ||
306 | } | ||
307 | AssocItem::Const(c) => { | ||
308 | name.map_or(true, |name| Some(name) == c.name(db).as_ref()) | ||
309 | && (mode == LookupMode::Path) | ||
310 | } | ||
311 | _ => false, | ||
312 | } | ||
313 | } | ||
314 | |||
315 | pub(crate) fn implements_trait( | ||
316 | ty: &Canonical<Ty>, | ||
317 | db: &impl HirDatabase, | ||
318 | resolver: &Resolver, | ||
319 | krate: Crate, | ||
320 | trait_: Trait, | ||
321 | ) -> bool { | ||
322 | if ty.value.inherent_trait() == Some(trait_) { | ||
323 | // FIXME this is a bit of a hack, since Chalk should say the same thing | ||
324 | // anyway, but currently Chalk doesn't implement `dyn/impl Trait` yet | ||
325 | return true; | ||
326 | } | ||
327 | let env = lower::trait_env(db, resolver); | ||
328 | let goal = generic_implements_goal(db, env, trait_, ty.clone()); | ||
329 | let solution = db.trait_solve(krate, goal); | ||
330 | |||
331 | solution.is_some() | ||
332 | } | ||
333 | |||
334 | impl Ty { | ||
335 | // This would be nicer if it just returned an iterator, but that runs into | ||
336 | // lifetime problems, because we need to borrow temp `CrateImplBlocks`. | ||
337 | pub fn iterate_impl_items<T>( | ||
338 | self, | ||
339 | db: &impl HirDatabase, | ||
340 | krate: Crate, | ||
341 | mut callback: impl FnMut(AssocItem) -> Option<T>, | ||
342 | ) -> Option<T> { | ||
343 | for krate in def_crates(db, krate, &self)? { | ||
344 | let impls = db.impls_in_crate(krate); | ||
345 | |||
346 | for impl_block in impls.lookup_impl_blocks(&self) { | ||
347 | for item in impl_block.items(db) { | ||
348 | if let Some(result) = callback(item) { | ||
349 | return Some(result); | ||
350 | } | ||
351 | } | ||
352 | } | ||
353 | } | ||
354 | None | ||
355 | } | ||
356 | } | ||
357 | |||
358 | /// This creates Substs for a trait with the given Self type and type variables | ||
359 | /// for all other parameters, to query Chalk with it. | ||
360 | fn generic_implements_goal( | ||
361 | db: &impl HirDatabase, | ||
362 | env: Arc<TraitEnvironment>, | ||
363 | trait_: Trait, | ||
364 | self_ty: Canonical<Ty>, | ||
365 | ) -> Canonical<InEnvironment<super::Obligation>> { | ||
366 | let num_vars = self_ty.num_vars; | ||
367 | let substs = super::Substs::build_for_def(db, trait_) | ||
368 | .push(self_ty.value) | ||
369 | .fill_with_bound_vars(num_vars as u32) | ||
370 | .build(); | ||
371 | let num_vars = substs.len() - 1 + self_ty.num_vars; | ||
372 | let trait_ref = TraitRef { trait_, substs }; | ||
373 | let obligation = super::Obligation::Trait(trait_ref); | ||
374 | Canonical { num_vars, value: InEnvironment::new(env, obligation) } | ||
375 | } | ||
diff --git a/crates/ra_hir/src/ty/op.rs b/crates/ra_hir/src/ty/op.rs deleted file mode 100644 index bcfa3a6a2..000000000 --- a/crates/ra_hir/src/ty/op.rs +++ /dev/null | |||
@@ -1,52 +0,0 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | |||
3 | use super::{InferTy, Ty, TypeCtor}; | ||
4 | use crate::{ | ||
5 | expr::{BinaryOp, CmpOp}, | ||
6 | ty::ApplicationTy, | ||
7 | }; | ||
8 | |||
9 | pub(super) fn binary_op_return_ty(op: BinaryOp, rhs_ty: Ty) -> Ty { | ||
10 | match op { | ||
11 | BinaryOp::LogicOp(_) | BinaryOp::CmpOp(_) => Ty::simple(TypeCtor::Bool), | ||
12 | BinaryOp::Assignment { .. } => Ty::unit(), | ||
13 | BinaryOp::ArithOp(_) => match rhs_ty { | ||
14 | Ty::Apply(ApplicationTy { ctor, .. }) => match ctor { | ||
15 | TypeCtor::Int(..) | TypeCtor::Float(..) => rhs_ty, | ||
16 | _ => Ty::Unknown, | ||
17 | }, | ||
18 | Ty::Infer(InferTy::IntVar(..)) | Ty::Infer(InferTy::FloatVar(..)) => rhs_ty, | ||
19 | _ => Ty::Unknown, | ||
20 | }, | ||
21 | } | ||
22 | } | ||
23 | |||
24 | pub(super) fn binary_op_rhs_expectation(op: BinaryOp, lhs_ty: Ty) -> Ty { | ||
25 | match op { | ||
26 | BinaryOp::LogicOp(..) => Ty::simple(TypeCtor::Bool), | ||
27 | BinaryOp::Assignment { op: None } | BinaryOp::CmpOp(CmpOp::Eq { negated: _ }) => { | ||
28 | match lhs_ty { | ||
29 | Ty::Apply(ApplicationTy { ctor, .. }) => match ctor { | ||
30 | TypeCtor::Int(..) | ||
31 | | TypeCtor::Float(..) | ||
32 | | TypeCtor::Str | ||
33 | | TypeCtor::Char | ||
34 | | TypeCtor::Bool => lhs_ty, | ||
35 | _ => Ty::Unknown, | ||
36 | }, | ||
37 | Ty::Infer(InferTy::IntVar(..)) | Ty::Infer(InferTy::FloatVar(..)) => lhs_ty, | ||
38 | _ => Ty::Unknown, | ||
39 | } | ||
40 | } | ||
41 | BinaryOp::CmpOp(CmpOp::Ord { .. }) | ||
42 | | BinaryOp::Assignment { op: Some(_) } | ||
43 | | BinaryOp::ArithOp(_) => match lhs_ty { | ||
44 | Ty::Apply(ApplicationTy { ctor, .. }) => match ctor { | ||
45 | TypeCtor::Int(..) | TypeCtor::Float(..) => lhs_ty, | ||
46 | _ => Ty::Unknown, | ||
47 | }, | ||
48 | Ty::Infer(InferTy::IntVar(..)) | Ty::Infer(InferTy::FloatVar(..)) => lhs_ty, | ||
49 | _ => Ty::Unknown, | ||
50 | }, | ||
51 | } | ||
52 | } | ||
diff --git a/crates/ra_hir/src/ty/primitive.rs b/crates/ra_hir/src/ty/primitive.rs deleted file mode 100644 index 47789db87..000000000 --- a/crates/ra_hir/src/ty/primitive.rs +++ /dev/null | |||
@@ -1,160 +0,0 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | |||
3 | use std::fmt; | ||
4 | |||
5 | pub use hir_def::builtin_type::{FloatBitness, IntBitness, Signedness}; | ||
6 | |||
7 | #[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)] | ||
8 | pub enum Uncertain<T> { | ||
9 | Unknown, | ||
10 | Known(T), | ||
11 | } | ||
12 | |||
13 | impl From<IntTy> for Uncertain<IntTy> { | ||
14 | fn from(ty: IntTy) -> Self { | ||
15 | Uncertain::Known(ty) | ||
16 | } | ||
17 | } | ||
18 | |||
19 | impl fmt::Display for Uncertain<IntTy> { | ||
20 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
21 | match *self { | ||
22 | Uncertain::Unknown => write!(f, "{{integer}}"), | ||
23 | Uncertain::Known(ty) => write!(f, "{}", ty), | ||
24 | } | ||
25 | } | ||
26 | } | ||
27 | |||
28 | impl From<FloatTy> for Uncertain<FloatTy> { | ||
29 | fn from(ty: FloatTy) -> Self { | ||
30 | Uncertain::Known(ty) | ||
31 | } | ||
32 | } | ||
33 | |||
34 | impl fmt::Display for Uncertain<FloatTy> { | ||
35 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
36 | match *self { | ||
37 | Uncertain::Unknown => write!(f, "{{float}}"), | ||
38 | Uncertain::Known(ty) => write!(f, "{}", ty), | ||
39 | } | ||
40 | } | ||
41 | } | ||
42 | |||
43 | #[derive(Copy, Clone, Eq, PartialEq, Hash)] | ||
44 | pub struct IntTy { | ||
45 | pub signedness: Signedness, | ||
46 | pub bitness: IntBitness, | ||
47 | } | ||
48 | |||
49 | impl fmt::Debug for IntTy { | ||
50 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
51 | fmt::Display::fmt(self, f) | ||
52 | } | ||
53 | } | ||
54 | |||
55 | impl fmt::Display for IntTy { | ||
56 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
57 | write!(f, "{}", self.ty_to_string()) | ||
58 | } | ||
59 | } | ||
60 | |||
61 | impl IntTy { | ||
62 | pub fn isize() -> IntTy { | ||
63 | IntTy { signedness: Signedness::Signed, bitness: IntBitness::Xsize } | ||
64 | } | ||
65 | |||
66 | pub fn i8() -> IntTy { | ||
67 | IntTy { signedness: Signedness::Signed, bitness: IntBitness::X8 } | ||
68 | } | ||
69 | |||
70 | pub fn i16() -> IntTy { | ||
71 | IntTy { signedness: Signedness::Signed, bitness: IntBitness::X16 } | ||
72 | } | ||
73 | |||
74 | pub fn i32() -> IntTy { | ||
75 | IntTy { signedness: Signedness::Signed, bitness: IntBitness::X32 } | ||
76 | } | ||
77 | |||
78 | pub fn i64() -> IntTy { | ||
79 | IntTy { signedness: Signedness::Signed, bitness: IntBitness::X64 } | ||
80 | } | ||
81 | |||
82 | pub fn i128() -> IntTy { | ||
83 | IntTy { signedness: Signedness::Signed, bitness: IntBitness::X128 } | ||
84 | } | ||
85 | |||
86 | pub fn usize() -> IntTy { | ||
87 | IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::Xsize } | ||
88 | } | ||
89 | |||
90 | pub fn u8() -> IntTy { | ||
91 | IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::X8 } | ||
92 | } | ||
93 | |||
94 | pub fn u16() -> IntTy { | ||
95 | IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::X16 } | ||
96 | } | ||
97 | |||
98 | pub fn u32() -> IntTy { | ||
99 | IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::X32 } | ||
100 | } | ||
101 | |||
102 | pub fn u64() -> IntTy { | ||
103 | IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::X64 } | ||
104 | } | ||
105 | |||
106 | pub fn u128() -> IntTy { | ||
107 | IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::X128 } | ||
108 | } | ||
109 | |||
110 | pub(crate) fn ty_to_string(self) -> &'static str { | ||
111 | match (self.signedness, self.bitness) { | ||
112 | (Signedness::Signed, IntBitness::Xsize) => "isize", | ||
113 | (Signedness::Signed, IntBitness::X8) => "i8", | ||
114 | (Signedness::Signed, IntBitness::X16) => "i16", | ||
115 | (Signedness::Signed, IntBitness::X32) => "i32", | ||
116 | (Signedness::Signed, IntBitness::X64) => "i64", | ||
117 | (Signedness::Signed, IntBitness::X128) => "i128", | ||
118 | (Signedness::Unsigned, IntBitness::Xsize) => "usize", | ||
119 | (Signedness::Unsigned, IntBitness::X8) => "u8", | ||
120 | (Signedness::Unsigned, IntBitness::X16) => "u16", | ||
121 | (Signedness::Unsigned, IntBitness::X32) => "u32", | ||
122 | (Signedness::Unsigned, IntBitness::X64) => "u64", | ||
123 | (Signedness::Unsigned, IntBitness::X128) => "u128", | ||
124 | } | ||
125 | } | ||
126 | } | ||
127 | |||
128 | #[derive(Copy, Clone, PartialEq, Eq, Hash)] | ||
129 | pub struct FloatTy { | ||
130 | pub bitness: FloatBitness, | ||
131 | } | ||
132 | |||
133 | impl fmt::Debug for FloatTy { | ||
134 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
135 | fmt::Display::fmt(self, f) | ||
136 | } | ||
137 | } | ||
138 | |||
139 | impl fmt::Display for FloatTy { | ||
140 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
141 | write!(f, "{}", self.ty_to_string()) | ||
142 | } | ||
143 | } | ||
144 | |||
145 | impl FloatTy { | ||
146 | pub fn f32() -> FloatTy { | ||
147 | FloatTy { bitness: FloatBitness::X32 } | ||
148 | } | ||
149 | |||
150 | pub fn f64() -> FloatTy { | ||
151 | FloatTy { bitness: FloatBitness::X64 } | ||
152 | } | ||
153 | |||
154 | pub(crate) fn ty_to_string(self) -> &'static str { | ||
155 | match self.bitness { | ||
156 | FloatBitness::X32 => "f32", | ||
157 | FloatBitness::X64 => "f64", | ||
158 | } | ||
159 | } | ||
160 | } | ||
diff --git a/crates/ra_hir/src/ty/tests.rs b/crates/ra_hir/src/ty/tests.rs deleted file mode 100644 index 3209c66bd..000000000 --- a/crates/ra_hir/src/ty/tests.rs +++ /dev/null | |||
@@ -1,4895 +0,0 @@ | |||
1 | mod never_type; | ||
2 | mod coercion; | ||
3 | |||
4 | use std::fmt::Write; | ||
5 | use std::sync::Arc; | ||
6 | |||
7 | use insta::assert_snapshot; | ||
8 | use ra_db::{fixture::WithFixture, salsa::Database, FilePosition, SourceDatabase}; | ||
9 | use ra_syntax::{ | ||
10 | algo, | ||
11 | ast::{self, AstNode}, | ||
12 | SyntaxKind::*, | ||
13 | }; | ||
14 | use rustc_hash::FxHashSet; | ||
15 | use test_utils::covers; | ||
16 | |||
17 | use crate::{ | ||
18 | expr::BodySourceMap, test_db::TestDB, ty::display::HirDisplay, ty::InferenceResult, Source, | ||
19 | SourceAnalyzer, | ||
20 | }; | ||
21 | |||
22 | // These tests compare the inference results for all expressions in a file | ||
23 | // against snapshots of the expected results using insta. Use cargo-insta to | ||
24 | // update the snapshots. | ||
25 | |||
26 | #[test] | ||
27 | fn cfg_impl_block() { | ||
28 | let (db, pos) = TestDB::with_position( | ||
29 | r#" | ||
30 | //- /main.rs crate:main deps:foo cfg:test | ||
31 | use foo::S as T; | ||
32 | struct S; | ||
33 | |||
34 | #[cfg(test)] | ||
35 | impl S { | ||
36 | fn foo1(&self) -> i32 { 0 } | ||
37 | } | ||
38 | |||
39 | #[cfg(not(test))] | ||
40 | impl S { | ||
41 | fn foo2(&self) -> i32 { 0 } | ||
42 | } | ||
43 | |||
44 | fn test() { | ||
45 | let t = (S.foo1(), S.foo2(), T.foo3(), T.foo4()); | ||
46 | t<|>; | ||
47 | } | ||
48 | |||
49 | //- /foo.rs crate:foo | ||
50 | struct S; | ||
51 | |||
52 | #[cfg(not(test))] | ||
53 | impl S { | ||
54 | fn foo3(&self) -> i32 { 0 } | ||
55 | } | ||
56 | |||
57 | #[cfg(test)] | ||
58 | impl S { | ||
59 | fn foo4(&self) -> i32 { 0 } | ||
60 | } | ||
61 | "#, | ||
62 | ); | ||
63 | assert_eq!("(i32, {unknown}, i32, {unknown})", type_at_pos(&db, pos)); | ||
64 | } | ||
65 | |||
66 | #[test] | ||
67 | fn infer_await() { | ||
68 | let (db, pos) = TestDB::with_position( | ||
69 | r#" | ||
70 | //- /main.rs crate:main deps:std | ||
71 | |||
72 | struct IntFuture; | ||
73 | |||
74 | impl Future for IntFuture { | ||
75 | type Output = u64; | ||
76 | } | ||
77 | |||
78 | fn test() { | ||
79 | let r = IntFuture; | ||
80 | let v = r.await; | ||
81 | v<|>; | ||
82 | } | ||
83 | |||
84 | //- /std.rs crate:std | ||
85 | #[prelude_import] use future::*; | ||
86 | mod future { | ||
87 | trait Future { | ||
88 | type Output; | ||
89 | } | ||
90 | } | ||
91 | |||
92 | "#, | ||
93 | ); | ||
94 | assert_eq!("u64", type_at_pos(&db, pos)); | ||
95 | } | ||
96 | |||
97 | #[test] | ||
98 | fn infer_box() { | ||
99 | let (db, pos) = TestDB::with_position( | ||
100 | r#" | ||
101 | //- /main.rs crate:main deps:std | ||
102 | |||
103 | fn test() { | ||
104 | let x = box 1; | ||
105 | let t = (x, box x, box &1, box [1]); | ||
106 | t<|>; | ||
107 | } | ||
108 | |||
109 | //- /std.rs crate:std | ||
110 | #[prelude_import] use prelude::*; | ||
111 | mod prelude {} | ||
112 | |||
113 | mod boxed { | ||
114 | pub struct Box<T: ?Sized> { | ||
115 | inner: *mut T, | ||
116 | } | ||
117 | } | ||
118 | |||
119 | "#, | ||
120 | ); | ||
121 | assert_eq!("(Box<i32>, Box<Box<i32>>, Box<&i32>, Box<[i32;_]>)", type_at_pos(&db, pos)); | ||
122 | } | ||
123 | |||
124 | #[test] | ||
125 | fn infer_adt_self() { | ||
126 | let (db, pos) = TestDB::with_position( | ||
127 | r#" | ||
128 | //- /main.rs | ||
129 | enum Nat { Succ(Self), Demo(Nat), Zero } | ||
130 | |||
131 | fn test() { | ||
132 | let foo: Nat = Nat::Zero; | ||
133 | if let Nat::Succ(x) = foo { | ||
134 | x<|> | ||
135 | } | ||
136 | } | ||
137 | |||
138 | "#, | ||
139 | ); | ||
140 | assert_eq!("Nat", type_at_pos(&db, pos)); | ||
141 | } | ||
142 | |||
143 | #[test] | ||
144 | fn infer_try() { | ||
145 | let (db, pos) = TestDB::with_position( | ||
146 | r#" | ||
147 | //- /main.rs crate:main deps:std | ||
148 | |||
149 | fn test() { | ||
150 | let r: Result<i32, u64> = Result::Ok(1); | ||
151 | let v = r?; | ||
152 | v<|>; | ||
153 | } | ||
154 | |||
155 | //- /std.rs crate:std | ||
156 | |||
157 | #[prelude_import] use ops::*; | ||
158 | mod ops { | ||
159 | trait Try { | ||
160 | type Ok; | ||
161 | type Error; | ||
162 | } | ||
163 | } | ||
164 | |||
165 | #[prelude_import] use result::*; | ||
166 | mod result { | ||
167 | enum Result<O, E> { | ||
168 | Ok(O), | ||
169 | Err(E) | ||
170 | } | ||
171 | |||
172 | impl<O, E> crate::ops::Try for Result<O, E> { | ||
173 | type Ok = O; | ||
174 | type Error = E; | ||
175 | } | ||
176 | } | ||
177 | |||
178 | "#, | ||
179 | ); | ||
180 | assert_eq!("i32", type_at_pos(&db, pos)); | ||
181 | } | ||
182 | |||
183 | #[test] | ||
184 | fn infer_for_loop() { | ||
185 | let (db, pos) = TestDB::with_position( | ||
186 | r#" | ||
187 | //- /main.rs crate:main deps:std | ||
188 | |||
189 | use std::collections::Vec; | ||
190 | |||
191 | fn test() { | ||
192 | let v = Vec::new(); | ||
193 | v.push("foo"); | ||
194 | for x in v { | ||
195 | x<|>; | ||
196 | } | ||
197 | } | ||
198 | |||
199 | //- /std.rs crate:std | ||
200 | |||
201 | #[prelude_import] use iter::*; | ||
202 | mod iter { | ||
203 | trait IntoIterator { | ||
204 | type Item; | ||
205 | } | ||
206 | } | ||
207 | |||
208 | mod collections { | ||
209 | struct Vec<T> {} | ||
210 | impl<T> Vec<T> { | ||
211 | fn new() -> Self { Vec {} } | ||
212 | fn push(&mut self, t: T) { } | ||
213 | } | ||
214 | |||
215 | impl<T> crate::iter::IntoIterator for Vec<T> { | ||
216 | type Item=T; | ||
217 | } | ||
218 | } | ||
219 | "#, | ||
220 | ); | ||
221 | assert_eq!("&str", type_at_pos(&db, pos)); | ||
222 | } | ||
223 | |||
224 | #[test] | ||
225 | fn infer_while_let() { | ||
226 | let (db, pos) = TestDB::with_position( | ||
227 | r#" | ||
228 | //- /main.rs | ||
229 | enum Option<T> { Some(T), None } | ||
230 | |||
231 | fn test() { | ||
232 | let foo: Option<f32> = None; | ||
233 | while let Option::Some(x) = foo { | ||
234 | <|>x | ||
235 | } | ||
236 | } | ||
237 | |||
238 | "#, | ||
239 | ); | ||
240 | assert_eq!("f32", type_at_pos(&db, pos)); | ||
241 | } | ||
242 | |||
243 | #[test] | ||
244 | fn infer_basics() { | ||
245 | assert_snapshot!( | ||
246 | infer(r#" | ||
247 | fn test(a: u32, b: isize, c: !, d: &str) { | ||
248 | a; | ||
249 | b; | ||
250 | c; | ||
251 | d; | ||
252 | 1usize; | ||
253 | 1isize; | ||
254 | "test"; | ||
255 | 1.0f32; | ||
256 | }"#), | ||
257 | @r###" | ||
258 | [9; 10) 'a': u32 | ||
259 | [17; 18) 'b': isize | ||
260 | [27; 28) 'c': ! | ||
261 | [33; 34) 'd': &str | ||
262 | [42; 121) '{ ...f32; }': ! | ||
263 | [48; 49) 'a': u32 | ||
264 | [55; 56) 'b': isize | ||
265 | [62; 63) 'c': ! | ||
266 | [69; 70) 'd': &str | ||
267 | [76; 82) '1usize': usize | ||
268 | [88; 94) '1isize': isize | ||
269 | [100; 106) '"test"': &str | ||
270 | [112; 118) '1.0f32': f32 | ||
271 | "### | ||
272 | ); | ||
273 | } | ||
274 | |||
275 | #[test] | ||
276 | fn infer_let() { | ||
277 | assert_snapshot!( | ||
278 | infer(r#" | ||
279 | fn test() { | ||
280 | let a = 1isize; | ||
281 | let b: usize = 1; | ||
282 | let c = b; | ||
283 | let d: u32; | ||
284 | let e; | ||
285 | let f: i32 = e; | ||
286 | } | ||
287 | "#), | ||
288 | @r###" | ||
289 | [11; 118) '{ ...= e; }': () | ||
290 | [21; 22) 'a': isize | ||
291 | [25; 31) '1isize': isize | ||
292 | [41; 42) 'b': usize | ||
293 | [52; 53) '1': usize | ||
294 | [63; 64) 'c': usize | ||
295 | [67; 68) 'b': usize | ||
296 | [78; 79) 'd': u32 | ||
297 | [94; 95) 'e': i32 | ||
298 | [105; 106) 'f': i32 | ||
299 | [114; 115) 'e': i32 | ||
300 | "### | ||
301 | ); | ||
302 | } | ||
303 | |||
304 | #[test] | ||
305 | fn infer_paths() { | ||
306 | assert_snapshot!( | ||
307 | infer(r#" | ||
308 | fn a() -> u32 { 1 } | ||
309 | |||
310 | mod b { | ||
311 | fn c() -> u32 { 1 } | ||
312 | } | ||
313 | |||
314 | fn test() { | ||
315 | a(); | ||
316 | b::c(); | ||
317 | } | ||
318 | "#), | ||
319 | @r###" | ||
320 | [15; 20) '{ 1 }': u32 | ||
321 | [17; 18) '1': u32 | ||
322 | [48; 53) '{ 1 }': u32 | ||
323 | [50; 51) '1': u32 | ||
324 | [67; 91) '{ ...c(); }': () | ||
325 | [73; 74) 'a': fn a() -> u32 | ||
326 | [73; 76) 'a()': u32 | ||
327 | [82; 86) 'b::c': fn c() -> u32 | ||
328 | [82; 88) 'b::c()': u32 | ||
329 | "### | ||
330 | ); | ||
331 | } | ||
332 | |||
333 | #[test] | ||
334 | fn infer_path_type() { | ||
335 | assert_snapshot!( | ||
336 | infer(r#" | ||
337 | struct S; | ||
338 | |||
339 | impl S { | ||
340 | fn foo() -> i32 { 1 } | ||
341 | } | ||
342 | |||
343 | fn test() { | ||
344 | S::foo(); | ||
345 | <S>::foo(); | ||
346 | } | ||
347 | "#), | ||
348 | @r###" | ||
349 | [41; 46) '{ 1 }': i32 | ||
350 | [43; 44) '1': i32 | ||
351 | [60; 93) '{ ...o(); }': () | ||
352 | [66; 72) 'S::foo': fn foo() -> i32 | ||
353 | [66; 74) 'S::foo()': i32 | ||
354 | [80; 88) '<S>::foo': fn foo() -> i32 | ||
355 | [80; 90) '<S>::foo()': i32 | ||
356 | "### | ||
357 | ); | ||
358 | } | ||
359 | |||
360 | #[test] | ||
361 | fn infer_slice_method() { | ||
362 | assert_snapshot!( | ||
363 | infer(r#" | ||
364 | #[lang = "slice"] | ||
365 | impl<T> [T] { | ||
366 | fn foo(&self) -> T { | ||
367 | loop {} | ||
368 | } | ||
369 | } | ||
370 | |||
371 | #[lang = "slice_alloc"] | ||
372 | impl<T> [T] {} | ||
373 | |||
374 | fn test() { | ||
375 | <[_]>::foo(b"foo"); | ||
376 | } | ||
377 | "#), | ||
378 | @r###" | ||
379 | [45; 49) 'self': &[T] | ||
380 | [56; 79) '{ ... }': T | ||
381 | [66; 73) 'loop {}': ! | ||
382 | [71; 73) '{}': () | ||
383 | [133; 160) '{ ...o"); }': () | ||
384 | [139; 149) '<[_]>::foo': fn foo<u8>(&[T]) -> T | ||
385 | [139; 157) '<[_]>:..."foo")': u8 | ||
386 | [150; 156) 'b"foo"': &[u8] | ||
387 | "### | ||
388 | ); | ||
389 | } | ||
390 | |||
391 | #[test] | ||
392 | fn infer_struct() { | ||
393 | assert_snapshot!( | ||
394 | infer(r#" | ||
395 | struct A { | ||
396 | b: B, | ||
397 | c: C, | ||
398 | } | ||
399 | struct B; | ||
400 | struct C(usize); | ||
401 | |||
402 | fn test() { | ||
403 | let c = C(1); | ||
404 | B; | ||
405 | let a: A = A { b: B, c: C(1) }; | ||
406 | a.b; | ||
407 | a.c; | ||
408 | } | ||
409 | "#), | ||
410 | @r###" | ||
411 | [72; 154) '{ ...a.c; }': () | ||
412 | [82; 83) 'c': C | ||
413 | [86; 87) 'C': C(usize) -> C | ||
414 | [86; 90) 'C(1)': C | ||
415 | [88; 89) '1': usize | ||
416 | [96; 97) 'B': B | ||
417 | [107; 108) 'a': A | ||
418 | [114; 133) 'A { b:...C(1) }': A | ||
419 | [121; 122) 'B': B | ||
420 | [127; 128) 'C': C(usize) -> C | ||
421 | [127; 131) 'C(1)': C | ||
422 | [129; 130) '1': usize | ||
423 | [139; 140) 'a': A | ||
424 | [139; 142) 'a.b': B | ||
425 | [148; 149) 'a': A | ||
426 | [148; 151) 'a.c': C | ||
427 | "### | ||
428 | ); | ||
429 | } | ||
430 | |||
431 | #[test] | ||
432 | fn infer_enum() { | ||
433 | assert_snapshot!( | ||
434 | infer(r#" | ||
435 | enum E { | ||
436 | V1 { field: u32 }, | ||
437 | V2 | ||
438 | } | ||
439 | fn test() { | ||
440 | E::V1 { field: 1 }; | ||
441 | E::V2; | ||
442 | }"#), | ||
443 | @r###" | ||
444 | [48; 82) '{ E:...:V2; }': () | ||
445 | [52; 70) 'E::V1 ...d: 1 }': E | ||
446 | [67; 68) '1': u32 | ||
447 | [74; 79) 'E::V2': E | ||
448 | "### | ||
449 | ); | ||
450 | } | ||
451 | |||
452 | #[test] | ||
453 | fn infer_refs() { | ||
454 | assert_snapshot!( | ||
455 | infer(r#" | ||
456 | fn test(a: &u32, b: &mut u32, c: *const u32, d: *mut u32) { | ||
457 | a; | ||
458 | *a; | ||
459 | &a; | ||
460 | &mut a; | ||
461 | b; | ||
462 | *b; | ||
463 | &b; | ||
464 | c; | ||
465 | *c; | ||
466 | d; | ||
467 | *d; | ||
468 | } | ||
469 | "#), | ||
470 | @r###" | ||
471 | [9; 10) 'a': &u32 | ||
472 | [18; 19) 'b': &mut u32 | ||
473 | [31; 32) 'c': *const u32 | ||
474 | [46; 47) 'd': *mut u32 | ||
475 | [59; 150) '{ ... *d; }': () | ||
476 | [65; 66) 'a': &u32 | ||
477 | [72; 74) '*a': u32 | ||
478 | [73; 74) 'a': &u32 | ||
479 | [80; 82) '&a': &&u32 | ||
480 | [81; 82) 'a': &u32 | ||
481 | [88; 94) '&mut a': &mut &u32 | ||
482 | [93; 94) 'a': &u32 | ||
483 | [100; 101) 'b': &mut u32 | ||
484 | [107; 109) '*b': u32 | ||
485 | [108; 109) 'b': &mut u32 | ||
486 | [115; 117) '&b': &&mut u32 | ||
487 | [116; 117) 'b': &mut u32 | ||
488 | [123; 124) 'c': *const u32 | ||
489 | [130; 132) '*c': u32 | ||
490 | [131; 132) 'c': *const u32 | ||
491 | [138; 139) 'd': *mut u32 | ||
492 | [145; 147) '*d': u32 | ||
493 | [146; 147) 'd': *mut u32 | ||
494 | "### | ||
495 | ); | ||
496 | } | ||
497 | |||
498 | #[test] | ||
499 | fn infer_literals() { | ||
500 | assert_snapshot!( | ||
501 | infer(r##" | ||
502 | fn test() { | ||
503 | 5i32; | ||
504 | 5f32; | ||
505 | 5f64; | ||
506 | "hello"; | ||
507 | b"bytes"; | ||
508 | 'c'; | ||
509 | b'b'; | ||
510 | 3.14; | ||
511 | 5000; | ||
512 | false; | ||
513 | true; | ||
514 | r#" | ||
515 | //! doc | ||
516 | // non-doc | ||
517 | mod foo {} | ||
518 | "#; | ||
519 | br#"yolo"#; | ||
520 | } | ||
521 | "##), | ||
522 | @r###" | ||
523 | [11; 221) '{ ...o"#; }': () | ||
524 | [17; 21) '5i32': i32 | ||
525 | [27; 31) '5f32': f32 | ||
526 | [37; 41) '5f64': f64 | ||
527 | [47; 54) '"hello"': &str | ||
528 | [60; 68) 'b"bytes"': &[u8] | ||
529 | [74; 77) ''c'': char | ||
530 | [83; 87) 'b'b'': u8 | ||
531 | [93; 97) '3.14': f64 | ||
532 | [103; 107) '5000': i32 | ||
533 | [113; 118) 'false': bool | ||
534 | [124; 128) 'true': bool | ||
535 | [134; 202) 'r#" ... "#': &str | ||
536 | [208; 218) 'br#"yolo"#': &[u8] | ||
537 | "### | ||
538 | ); | ||
539 | } | ||
540 | |||
541 | #[test] | ||
542 | fn infer_unary_op() { | ||
543 | assert_snapshot!( | ||
544 | infer(r#" | ||
545 | enum SomeType {} | ||
546 | |||
547 | fn test(x: SomeType) { | ||
548 | let b = false; | ||
549 | let c = !b; | ||
550 | let a = 100; | ||
551 | let d: i128 = -a; | ||
552 | let e = -100; | ||
553 | let f = !!!true; | ||
554 | let g = !42; | ||
555 | let h = !10u32; | ||
556 | let j = !a; | ||
557 | -3.14; | ||
558 | !3; | ||
559 | -x; | ||
560 | !x; | ||
561 | -"hello"; | ||
562 | !"hello"; | ||
563 | } | ||
564 | "#), | ||
565 | @r###" | ||
566 | [27; 28) 'x': SomeType | ||
567 | [40; 272) '{ ...lo"; }': () | ||
568 | [50; 51) 'b': bool | ||
569 | [54; 59) 'false': bool | ||
570 | [69; 70) 'c': bool | ||
571 | [73; 75) '!b': bool | ||
572 | [74; 75) 'b': bool | ||
573 | [85; 86) 'a': i128 | ||
574 | [89; 92) '100': i128 | ||
575 | [102; 103) 'd': i128 | ||
576 | [112; 114) '-a': i128 | ||
577 | [113; 114) 'a': i128 | ||
578 | [124; 125) 'e': i32 | ||
579 | [128; 132) '-100': i32 | ||
580 | [129; 132) '100': i32 | ||
581 | [142; 143) 'f': bool | ||
582 | [146; 153) '!!!true': bool | ||
583 | [147; 153) '!!true': bool | ||
584 | [148; 153) '!true': bool | ||
585 | [149; 153) 'true': bool | ||
586 | [163; 164) 'g': i32 | ||
587 | [167; 170) '!42': i32 | ||
588 | [168; 170) '42': i32 | ||
589 | [180; 181) 'h': u32 | ||
590 | [184; 190) '!10u32': u32 | ||
591 | [185; 190) '10u32': u32 | ||
592 | [200; 201) 'j': i128 | ||
593 | [204; 206) '!a': i128 | ||
594 | [205; 206) 'a': i128 | ||
595 | [212; 217) '-3.14': f64 | ||
596 | [213; 217) '3.14': f64 | ||
597 | [223; 225) '!3': i32 | ||
598 | [224; 225) '3': i32 | ||
599 | [231; 233) '-x': {unknown} | ||
600 | [232; 233) 'x': SomeType | ||
601 | [239; 241) '!x': {unknown} | ||
602 | [240; 241) 'x': SomeType | ||
603 | [247; 255) '-"hello"': {unknown} | ||
604 | [248; 255) '"hello"': &str | ||
605 | [261; 269) '!"hello"': {unknown} | ||
606 | [262; 269) '"hello"': &str | ||
607 | "### | ||
608 | ); | ||
609 | } | ||
610 | |||
611 | #[test] | ||
612 | fn infer_backwards() { | ||
613 | assert_snapshot!( | ||
614 | infer(r#" | ||
615 | fn takes_u32(x: u32) {} | ||
616 | |||
617 | struct S { i32_field: i32 } | ||
618 | |||
619 | fn test() -> &mut &f64 { | ||
620 | let a = unknown_function(); | ||
621 | takes_u32(a); | ||
622 | let b = unknown_function(); | ||
623 | S { i32_field: b }; | ||
624 | let c = unknown_function(); | ||
625 | &mut &c | ||
626 | } | ||
627 | "#), | ||
628 | @r###" | ||
629 | [14; 15) 'x': u32 | ||
630 | [22; 24) '{}': () | ||
631 | [78; 231) '{ ...t &c }': &mut &f64 | ||
632 | [88; 89) 'a': u32 | ||
633 | [92; 108) 'unknow...nction': {unknown} | ||
634 | [92; 110) 'unknow...tion()': u32 | ||
635 | [116; 125) 'takes_u32': fn takes_u32(u32) -> () | ||
636 | [116; 128) 'takes_u32(a)': () | ||
637 | [126; 127) 'a': u32 | ||
638 | [138; 139) 'b': i32 | ||
639 | [142; 158) 'unknow...nction': {unknown} | ||
640 | [142; 160) 'unknow...tion()': i32 | ||
641 | [166; 184) 'S { i3...d: b }': S | ||
642 | [181; 182) 'b': i32 | ||
643 | [194; 195) 'c': f64 | ||
644 | [198; 214) 'unknow...nction': {unknown} | ||
645 | [198; 216) 'unknow...tion()': f64 | ||
646 | [222; 229) '&mut &c': &mut &f64 | ||
647 | [227; 229) '&c': &f64 | ||
648 | [228; 229) 'c': f64 | ||
649 | "### | ||
650 | ); | ||
651 | } | ||
652 | |||
653 | #[test] | ||
654 | fn infer_self() { | ||
655 | assert_snapshot!( | ||
656 | infer(r#" | ||
657 | struct S; | ||
658 | |||
659 | impl S { | ||
660 | fn test(&self) { | ||
661 | self; | ||
662 | } | ||
663 | fn test2(self: &Self) { | ||
664 | self; | ||
665 | } | ||
666 | fn test3() -> Self { | ||
667 | S {} | ||
668 | } | ||
669 | fn test4() -> Self { | ||
670 | Self {} | ||
671 | } | ||
672 | } | ||
673 | "#), | ||
674 | @r###" | ||
675 | [34; 38) 'self': &S | ||
676 | [40; 61) '{ ... }': () | ||
677 | [50; 54) 'self': &S | ||
678 | [75; 79) 'self': &S | ||
679 | [88; 109) '{ ... }': () | ||
680 | [98; 102) 'self': &S | ||
681 | [133; 153) '{ ... }': S | ||
682 | [143; 147) 'S {}': S | ||
683 | [177; 200) '{ ... }': S | ||
684 | [187; 194) 'Self {}': S | ||
685 | "### | ||
686 | ); | ||
687 | } | ||
688 | |||
689 | #[test] | ||
690 | fn infer_binary_op() { | ||
691 | assert_snapshot!( | ||
692 | infer(r#" | ||
693 | fn f(x: bool) -> i32 { | ||
694 | 0i32 | ||
695 | } | ||
696 | |||
697 | fn test() -> bool { | ||
698 | let x = a && b; | ||
699 | let y = true || false; | ||
700 | let z = x == y; | ||
701 | let t = x != y; | ||
702 | let minus_forty: isize = -40isize; | ||
703 | let h = minus_forty <= CONST_2; | ||
704 | let c = f(z || y) + 5; | ||
705 | let d = b; | ||
706 | let g = minus_forty ^= i; | ||
707 | let ten: usize = 10; | ||
708 | let ten_is_eleven = ten == some_num; | ||
709 | |||
710 | ten < 3 | ||
711 | } | ||
712 | "#), | ||
713 | @r###" | ||
714 | [6; 7) 'x': bool | ||
715 | [22; 34) '{ 0i32 }': i32 | ||
716 | [28; 32) '0i32': i32 | ||
717 | [54; 370) '{ ... < 3 }': bool | ||
718 | [64; 65) 'x': bool | ||
719 | [68; 69) 'a': bool | ||
720 | [68; 74) 'a && b': bool | ||
721 | [73; 74) 'b': bool | ||
722 | [84; 85) 'y': bool | ||
723 | [88; 92) 'true': bool | ||
724 | [88; 101) 'true || false': bool | ||
725 | [96; 101) 'false': bool | ||
726 | [111; 112) 'z': bool | ||
727 | [115; 116) 'x': bool | ||
728 | [115; 121) 'x == y': bool | ||
729 | [120; 121) 'y': bool | ||
730 | [131; 132) 't': bool | ||
731 | [135; 136) 'x': bool | ||
732 | [135; 141) 'x != y': bool | ||
733 | [140; 141) 'y': bool | ||
734 | [151; 162) 'minus_forty': isize | ||
735 | [172; 180) '-40isize': isize | ||
736 | [173; 180) '40isize': isize | ||
737 | [190; 191) 'h': bool | ||
738 | [194; 205) 'minus_forty': isize | ||
739 | [194; 216) 'minus_...ONST_2': bool | ||
740 | [209; 216) 'CONST_2': isize | ||
741 | [226; 227) 'c': i32 | ||
742 | [230; 231) 'f': fn f(bool) -> i32 | ||
743 | [230; 239) 'f(z || y)': i32 | ||
744 | [230; 243) 'f(z || y) + 5': i32 | ||
745 | [232; 233) 'z': bool | ||
746 | [232; 238) 'z || y': bool | ||
747 | [237; 238) 'y': bool | ||
748 | [242; 243) '5': i32 | ||
749 | [253; 254) 'd': {unknown} | ||
750 | [257; 258) 'b': {unknown} | ||
751 | [268; 269) 'g': () | ||
752 | [272; 283) 'minus_forty': isize | ||
753 | [272; 288) 'minus_...y ^= i': () | ||
754 | [287; 288) 'i': isize | ||
755 | [298; 301) 'ten': usize | ||
756 | [311; 313) '10': usize | ||
757 | [323; 336) 'ten_is_eleven': bool | ||
758 | [339; 342) 'ten': usize | ||
759 | [339; 354) 'ten == some_num': bool | ||
760 | [346; 354) 'some_num': usize | ||
761 | [361; 364) 'ten': usize | ||
762 | [361; 368) 'ten < 3': bool | ||
763 | [367; 368) '3': usize | ||
764 | "### | ||
765 | ); | ||
766 | } | ||
767 | |||
768 | #[test] | ||
769 | fn infer_field_autoderef() { | ||
770 | assert_snapshot!( | ||
771 | infer(r#" | ||
772 | struct A { | ||
773 | b: B, | ||
774 | } | ||
775 | struct B; | ||
776 | |||
777 | fn test1(a: A) { | ||
778 | let a1 = a; | ||
779 | a1.b; | ||
780 | let a2 = &a; | ||
781 | a2.b; | ||
782 | let a3 = &mut a; | ||
783 | a3.b; | ||
784 | let a4 = &&&&&&&a; | ||
785 | a4.b; | ||
786 | let a5 = &mut &&mut &&mut a; | ||
787 | a5.b; | ||
788 | } | ||
789 | |||
790 | fn test2(a1: *const A, a2: *mut A) { | ||
791 | a1.b; | ||
792 | a2.b; | ||
793 | } | ||
794 | "#), | ||
795 | @r###" | ||
796 | [44; 45) 'a': A | ||
797 | [50; 213) '{ ...5.b; }': () | ||
798 | [60; 62) 'a1': A | ||
799 | [65; 66) 'a': A | ||
800 | [72; 74) 'a1': A | ||
801 | [72; 76) 'a1.b': B | ||
802 | [86; 88) 'a2': &A | ||
803 | [91; 93) '&a': &A | ||
804 | [92; 93) 'a': A | ||
805 | [99; 101) 'a2': &A | ||
806 | [99; 103) 'a2.b': B | ||
807 | [113; 115) 'a3': &mut A | ||
808 | [118; 124) '&mut a': &mut A | ||
809 | [123; 124) 'a': A | ||
810 | [130; 132) 'a3': &mut A | ||
811 | [130; 134) 'a3.b': B | ||
812 | [144; 146) 'a4': &&&&&&&A | ||
813 | [149; 157) '&&&&&&&a': &&&&&&&A | ||
814 | [150; 157) '&&&&&&a': &&&&&&A | ||
815 | [151; 157) '&&&&&a': &&&&&A | ||
816 | [152; 157) '&&&&a': &&&&A | ||
817 | [153; 157) '&&&a': &&&A | ||
818 | [154; 157) '&&a': &&A | ||
819 | [155; 157) '&a': &A | ||
820 | [156; 157) 'a': A | ||
821 | [163; 165) 'a4': &&&&&&&A | ||
822 | [163; 167) 'a4.b': B | ||
823 | [177; 179) 'a5': &mut &&mut &&mut A | ||
824 | [182; 200) '&mut &...&mut a': &mut &&mut &&mut A | ||
825 | [187; 200) '&&mut &&mut a': &&mut &&mut A | ||
826 | [188; 200) '&mut &&mut a': &mut &&mut A | ||
827 | [193; 200) '&&mut a': &&mut A | ||
828 | [194; 200) '&mut a': &mut A | ||
829 | [199; 200) 'a': A | ||
830 | [206; 208) 'a5': &mut &&mut &&mut A | ||
831 | [206; 210) 'a5.b': B | ||
832 | [224; 226) 'a1': *const A | ||
833 | [238; 240) 'a2': *mut A | ||
834 | [250; 273) '{ ...2.b; }': () | ||
835 | [256; 258) 'a1': *const A | ||
836 | [256; 260) 'a1.b': B | ||
837 | [266; 268) 'a2': *mut A | ||
838 | [266; 270) 'a2.b': B | ||
839 | "### | ||
840 | ); | ||
841 | } | ||
842 | |||
843 | #[test] | ||
844 | fn infer_argument_autoderef() { | ||
845 | assert_snapshot!( | ||
846 | infer(r#" | ||
847 | #[lang = "deref"] | ||
848 | pub trait Deref { | ||
849 | type Target; | ||
850 | fn deref(&self) -> &Self::Target; | ||
851 | } | ||
852 | |||
853 | struct A<T>(T); | ||
854 | |||
855 | impl<T> A<T> { | ||
856 | fn foo(&self) -> &T { | ||
857 | &self.0 | ||
858 | } | ||
859 | } | ||
860 | |||
861 | struct B<T>(T); | ||
862 | |||
863 | impl<T> Deref for B<T> { | ||
864 | type Target = T; | ||
865 | fn deref(&self) -> &Self::Target { | ||
866 | &self.0 | ||
867 | } | ||
868 | } | ||
869 | |||
870 | fn test() { | ||
871 | let t = A::foo(&&B(B(A(42)))); | ||
872 | } | ||
873 | "#), | ||
874 | @r###" | ||
875 | [68; 72) 'self': &Self | ||
876 | [139; 143) 'self': &A<T> | ||
877 | [151; 174) '{ ... }': &T | ||
878 | [161; 168) '&self.0': &T | ||
879 | [162; 166) 'self': &A<T> | ||
880 | [162; 168) 'self.0': T | ||
881 | [255; 259) 'self': &B<T> | ||
882 | [278; 301) '{ ... }': &T | ||
883 | [288; 295) '&self.0': &T | ||
884 | [289; 293) 'self': &B<T> | ||
885 | [289; 295) 'self.0': T | ||
886 | [315; 353) '{ ...))); }': () | ||
887 | [325; 326) 't': &i32 | ||
888 | [329; 335) 'A::foo': fn foo<i32>(&A<T>) -> &T | ||
889 | [329; 350) 'A::foo...42))))': &i32 | ||
890 | [336; 349) '&&B(B(A(42)))': &&B<B<A<i32>>> | ||
891 | [337; 349) '&B(B(A(42)))': &B<B<A<i32>>> | ||
892 | [338; 339) 'B': B<B<A<i32>>>(T) -> B<T> | ||
893 | [338; 349) 'B(B(A(42)))': B<B<A<i32>>> | ||
894 | [340; 341) 'B': B<A<i32>>(T) -> B<T> | ||
895 | [340; 348) 'B(A(42))': B<A<i32>> | ||
896 | [342; 343) 'A': A<i32>(T) -> A<T> | ||
897 | [342; 347) 'A(42)': A<i32> | ||
898 | [344; 346) '42': i32 | ||
899 | "### | ||
900 | ); | ||
901 | } | ||
902 | |||
903 | #[test] | ||
904 | fn infer_method_argument_autoderef() { | ||
905 | assert_snapshot!( | ||
906 | infer(r#" | ||
907 | #[lang = "deref"] | ||
908 | pub trait Deref { | ||
909 | type Target; | ||
910 | fn deref(&self) -> &Self::Target; | ||
911 | } | ||
912 | |||
913 | struct A<T>(*mut T); | ||
914 | |||
915 | impl<T> A<T> { | ||
916 | fn foo(&self, x: &A<T>) -> &T { | ||
917 | &*x.0 | ||
918 | } | ||
919 | } | ||
920 | |||
921 | struct B<T>(T); | ||
922 | |||
923 | impl<T> Deref for B<T> { | ||
924 | type Target = T; | ||
925 | fn deref(&self) -> &Self::Target { | ||
926 | &self.0 | ||
927 | } | ||
928 | } | ||
929 | |||
930 | fn test(a: A<i32>) { | ||
931 | let t = A(0 as *mut _).foo(&&B(B(a))); | ||
932 | } | ||
933 | "#), | ||
934 | @r###" | ||
935 | [68; 72) 'self': &Self | ||
936 | [144; 148) 'self': &A<T> | ||
937 | [150; 151) 'x': &A<T> | ||
938 | [166; 187) '{ ... }': &T | ||
939 | [176; 181) '&*x.0': &T | ||
940 | [177; 181) '*x.0': T | ||
941 | [178; 179) 'x': &A<T> | ||
942 | [178; 181) 'x.0': *mut T | ||
943 | [268; 272) 'self': &B<T> | ||
944 | [291; 314) '{ ... }': &T | ||
945 | [301; 308) '&self.0': &T | ||
946 | [302; 306) 'self': &B<T> | ||
947 | [302; 308) 'self.0': T | ||
948 | [326; 327) 'a': A<i32> | ||
949 | [337; 383) '{ ...))); }': () | ||
950 | [347; 348) 't': &i32 | ||
951 | [351; 352) 'A': A<i32>(*mut T) -> A<T> | ||
952 | [351; 365) 'A(0 as *mut _)': A<i32> | ||
953 | [351; 380) 'A(0 as...B(a)))': &i32 | ||
954 | [353; 354) '0': i32 | ||
955 | [353; 364) '0 as *mut _': *mut i32 | ||
956 | [370; 379) '&&B(B(a))': &&B<B<A<i32>>> | ||
957 | [371; 379) '&B(B(a))': &B<B<A<i32>>> | ||
958 | [372; 373) 'B': B<B<A<i32>>>(T) -> B<T> | ||
959 | [372; 379) 'B(B(a))': B<B<A<i32>>> | ||
960 | [374; 375) 'B': B<A<i32>>(T) -> B<T> | ||
961 | [374; 378) 'B(a)': B<A<i32>> | ||
962 | [376; 377) 'a': A<i32> | ||
963 | "### | ||
964 | ); | ||
965 | } | ||
966 | |||
967 | #[test] | ||
968 | fn bug_484() { | ||
969 | assert_snapshot!( | ||
970 | infer(r#" | ||
971 | fn test() { | ||
972 | let x = if true {}; | ||
973 | } | ||
974 | "#), | ||
975 | @r###" | ||
976 | [11; 37) '{ l... {}; }': () | ||
977 | [20; 21) 'x': () | ||
978 | [24; 34) 'if true {}': () | ||
979 | [27; 31) 'true': bool | ||
980 | [32; 34) '{}': () | ||
981 | "### | ||
982 | ); | ||
983 | } | ||
984 | |||
985 | #[test] | ||
986 | fn infer_in_elseif() { | ||
987 | assert_snapshot!( | ||
988 | infer(r#" | ||
989 | struct Foo { field: i32 } | ||
990 | fn main(foo: Foo) { | ||
991 | if true { | ||
992 | |||
993 | } else if false { | ||
994 | foo.field | ||
995 | } | ||
996 | } | ||
997 | "#), | ||
998 | @r###" | ||
999 | [35; 38) 'foo': Foo | ||
1000 | [45; 109) '{ ... } }': () | ||
1001 | [51; 107) 'if tru... }': () | ||
1002 | [54; 58) 'true': bool | ||
1003 | [59; 67) '{ }': () | ||
1004 | [73; 107) 'if fal... }': () | ||
1005 | [76; 81) 'false': bool | ||
1006 | [82; 107) '{ ... }': i32 | ||
1007 | [92; 95) 'foo': Foo | ||
1008 | [92; 101) 'foo.field': i32 | ||
1009 | "### | ||
1010 | ) | ||
1011 | } | ||
1012 | |||
1013 | #[test] | ||
1014 | fn infer_if_match_with_return() { | ||
1015 | assert_snapshot!( | ||
1016 | infer(r#" | ||
1017 | fn foo() { | ||
1018 | let _x1 = if true { | ||
1019 | 1 | ||
1020 | } else { | ||
1021 | return; | ||
1022 | }; | ||
1023 | let _x2 = if true { | ||
1024 | 2 | ||
1025 | } else { | ||
1026 | return | ||
1027 | }; | ||
1028 | let _x3 = match true { | ||
1029 | true => 3, | ||
1030 | _ => { | ||
1031 | return; | ||
1032 | } | ||
1033 | }; | ||
1034 | let _x4 = match true { | ||
1035 | true => 4, | ||
1036 | _ => return | ||
1037 | }; | ||
1038 | }"#), | ||
1039 | @r###" | ||
1040 | [10; 323) '{ ... }; }': () | ||
1041 | [20; 23) '_x1': i32 | ||
1042 | [26; 80) 'if tru... }': i32 | ||
1043 | [29; 33) 'true': bool | ||
1044 | [34; 51) '{ ... }': i32 | ||
1045 | [44; 45) '1': i32 | ||
1046 | [57; 80) '{ ... }': ! | ||
1047 | [67; 73) 'return': ! | ||
1048 | [90; 93) '_x2': i32 | ||
1049 | [96; 149) 'if tru... }': i32 | ||
1050 | [99; 103) 'true': bool | ||
1051 | [104; 121) '{ ... }': i32 | ||
1052 | [114; 115) '2': i32 | ||
1053 | [127; 149) '{ ... }': ! | ||
1054 | [137; 143) 'return': ! | ||
1055 | [159; 162) '_x3': i32 | ||
1056 | [165; 247) 'match ... }': i32 | ||
1057 | [171; 175) 'true': bool | ||
1058 | [186; 190) 'true': bool | ||
1059 | [194; 195) '3': i32 | ||
1060 | [205; 206) '_': bool | ||
1061 | [210; 241) '{ ... }': ! | ||
1062 | [224; 230) 'return': ! | ||
1063 | [257; 260) '_x4': i32 | ||
1064 | [263; 320) 'match ... }': i32 | ||
1065 | [269; 273) 'true': bool | ||
1066 | [284; 288) 'true': bool | ||
1067 | [292; 293) '4': i32 | ||
1068 | [303; 304) '_': bool | ||
1069 | [308; 314) 'return': ! | ||
1070 | "### | ||
1071 | ) | ||
1072 | } | ||
1073 | |||
1074 | #[test] | ||
1075 | fn infer_inherent_method() { | ||
1076 | assert_snapshot!( | ||
1077 | infer(r#" | ||
1078 | struct A; | ||
1079 | |||
1080 | impl A { | ||
1081 | fn foo(self, x: u32) -> i32 {} | ||
1082 | } | ||
1083 | |||
1084 | mod b { | ||
1085 | impl super::A { | ||
1086 | fn bar(&self, x: u64) -> i64 {} | ||
1087 | } | ||
1088 | } | ||
1089 | |||
1090 | fn test(a: A) { | ||
1091 | a.foo(1); | ||
1092 | (&a).bar(1); | ||
1093 | a.bar(1); | ||
1094 | } | ||
1095 | "#), | ||
1096 | @r###" | ||
1097 | [32; 36) 'self': A | ||
1098 | [38; 39) 'x': u32 | ||
1099 | [53; 55) '{}': () | ||
1100 | [103; 107) 'self': &A | ||
1101 | [109; 110) 'x': u64 | ||
1102 | [124; 126) '{}': () | ||
1103 | [144; 145) 'a': A | ||
1104 | [150; 198) '{ ...(1); }': () | ||
1105 | [156; 157) 'a': A | ||
1106 | [156; 164) 'a.foo(1)': i32 | ||
1107 | [162; 163) '1': u32 | ||
1108 | [170; 181) '(&a).bar(1)': i64 | ||
1109 | [171; 173) '&a': &A | ||
1110 | [172; 173) 'a': A | ||
1111 | [179; 180) '1': u64 | ||
1112 | [187; 188) 'a': A | ||
1113 | [187; 195) 'a.bar(1)': i64 | ||
1114 | [193; 194) '1': u64 | ||
1115 | "### | ||
1116 | ); | ||
1117 | } | ||
1118 | |||
1119 | #[test] | ||
1120 | fn infer_inherent_method_str() { | ||
1121 | assert_snapshot!( | ||
1122 | infer(r#" | ||
1123 | #[lang = "str"] | ||
1124 | impl str { | ||
1125 | fn foo(&self) -> i32 {} | ||
1126 | } | ||
1127 | |||
1128 | fn test() { | ||
1129 | "foo".foo(); | ||
1130 | } | ||
1131 | "#), | ||
1132 | @r###" | ||
1133 | [40; 44) 'self': &str | ||
1134 | [53; 55) '{}': () | ||
1135 | [69; 89) '{ ...o(); }': () | ||
1136 | [75; 80) '"foo"': &str | ||
1137 | [75; 86) '"foo".foo()': i32 | ||
1138 | "### | ||
1139 | ); | ||
1140 | } | ||
1141 | |||
1142 | #[test] | ||
1143 | fn infer_tuple() { | ||
1144 | assert_snapshot!( | ||
1145 | infer(r#" | ||
1146 | fn test(x: &str, y: isize) { | ||
1147 | let a: (u32, &str) = (1, "a"); | ||
1148 | let b = (a, x); | ||
1149 | let c = (y, x); | ||
1150 | let d = (c, x); | ||
1151 | let e = (1, "e"); | ||
1152 | let f = (e, "d"); | ||
1153 | } | ||
1154 | "#), | ||
1155 | @r###" | ||
1156 | [9; 10) 'x': &str | ||
1157 | [18; 19) 'y': isize | ||
1158 | [28; 170) '{ ...d"); }': () | ||
1159 | [38; 39) 'a': (u32, &str) | ||
1160 | [55; 63) '(1, "a")': (u32, &str) | ||
1161 | [56; 57) '1': u32 | ||
1162 | [59; 62) '"a"': &str | ||
1163 | [73; 74) 'b': ((u32, &str), &str) | ||
1164 | [77; 83) '(a, x)': ((u32, &str), &str) | ||
1165 | [78; 79) 'a': (u32, &str) | ||
1166 | [81; 82) 'x': &str | ||
1167 | [93; 94) 'c': (isize, &str) | ||
1168 | [97; 103) '(y, x)': (isize, &str) | ||
1169 | [98; 99) 'y': isize | ||
1170 | [101; 102) 'x': &str | ||
1171 | [113; 114) 'd': ((isize, &str), &str) | ||
1172 | [117; 123) '(c, x)': ((isize, &str), &str) | ||
1173 | [118; 119) 'c': (isize, &str) | ||
1174 | [121; 122) 'x': &str | ||
1175 | [133; 134) 'e': (i32, &str) | ||
1176 | [137; 145) '(1, "e")': (i32, &str) | ||
1177 | [138; 139) '1': i32 | ||
1178 | [141; 144) '"e"': &str | ||
1179 | [155; 156) 'f': ((i32, &str), &str) | ||
1180 | [159; 167) '(e, "d")': ((i32, &str), &str) | ||
1181 | [160; 161) 'e': (i32, &str) | ||
1182 | [163; 166) '"d"': &str | ||
1183 | "### | ||
1184 | ); | ||
1185 | } | ||
1186 | |||
1187 | #[test] | ||
1188 | fn infer_array() { | ||
1189 | assert_snapshot!( | ||
1190 | infer(r#" | ||
1191 | fn test(x: &str, y: isize) { | ||
1192 | let a = [x]; | ||
1193 | let b = [a, a]; | ||
1194 | let c = [b, b]; | ||
1195 | |||
1196 | let d = [y, 1, 2, 3]; | ||
1197 | let d = [1, y, 2, 3]; | ||
1198 | let e = [y]; | ||
1199 | let f = [d, d]; | ||
1200 | let g = [e, e]; | ||
1201 | |||
1202 | let h = [1, 2]; | ||
1203 | let i = ["a", "b"]; | ||
1204 | |||
1205 | let b = [a, ["b"]]; | ||
1206 | let x: [u8; 0] = []; | ||
1207 | } | ||
1208 | "#), | ||
1209 | @r###" | ||
1210 | [9; 10) 'x': &str | ||
1211 | [18; 19) 'y': isize | ||
1212 | [28; 293) '{ ... []; }': () | ||
1213 | [38; 39) 'a': [&str;_] | ||
1214 | [42; 45) '[x]': [&str;_] | ||
1215 | [43; 44) 'x': &str | ||
1216 | [55; 56) 'b': [[&str;_];_] | ||
1217 | [59; 65) '[a, a]': [[&str;_];_] | ||
1218 | [60; 61) 'a': [&str;_] | ||
1219 | [63; 64) 'a': [&str;_] | ||
1220 | [75; 76) 'c': [[[&str;_];_];_] | ||
1221 | [79; 85) '[b, b]': [[[&str;_];_];_] | ||
1222 | [80; 81) 'b': [[&str;_];_] | ||
1223 | [83; 84) 'b': [[&str;_];_] | ||
1224 | [96; 97) 'd': [isize;_] | ||
1225 | [100; 112) '[y, 1, 2, 3]': [isize;_] | ||
1226 | [101; 102) 'y': isize | ||
1227 | [104; 105) '1': isize | ||
1228 | [107; 108) '2': isize | ||
1229 | [110; 111) '3': isize | ||
1230 | [122; 123) 'd': [isize;_] | ||
1231 | [126; 138) '[1, y, 2, 3]': [isize;_] | ||
1232 | [127; 128) '1': isize | ||
1233 | [130; 131) 'y': isize | ||
1234 | [133; 134) '2': isize | ||
1235 | [136; 137) '3': isize | ||
1236 | [148; 149) 'e': [isize;_] | ||
1237 | [152; 155) '[y]': [isize;_] | ||
1238 | [153; 154) 'y': isize | ||
1239 | [165; 166) 'f': [[isize;_];_] | ||
1240 | [169; 175) '[d, d]': [[isize;_];_] | ||
1241 | [170; 171) 'd': [isize;_] | ||
1242 | [173; 174) 'd': [isize;_] | ||
1243 | [185; 186) 'g': [[isize;_];_] | ||
1244 | [189; 195) '[e, e]': [[isize;_];_] | ||
1245 | [190; 191) 'e': [isize;_] | ||
1246 | [193; 194) 'e': [isize;_] | ||
1247 | [206; 207) 'h': [i32;_] | ||
1248 | [210; 216) '[1, 2]': [i32;_] | ||
1249 | [211; 212) '1': i32 | ||
1250 | [214; 215) '2': i32 | ||
1251 | [226; 227) 'i': [&str;_] | ||
1252 | [230; 240) '["a", "b"]': [&str;_] | ||
1253 | [231; 234) '"a"': &str | ||
1254 | [236; 239) '"b"': &str | ||
1255 | [251; 252) 'b': [[&str;_];_] | ||
1256 | [255; 265) '[a, ["b"]]': [[&str;_];_] | ||
1257 | [256; 257) 'a': [&str;_] | ||
1258 | [259; 264) '["b"]': [&str;_] | ||
1259 | [260; 263) '"b"': &str | ||
1260 | [275; 276) 'x': [u8;_] | ||
1261 | [288; 290) '[]': [u8;_] | ||
1262 | "### | ||
1263 | ); | ||
1264 | } | ||
1265 | |||
1266 | #[test] | ||
1267 | fn infer_pattern() { | ||
1268 | assert_snapshot!( | ||
1269 | infer(r#" | ||
1270 | fn test(x: &i32) { | ||
1271 | let y = x; | ||
1272 | let &z = x; | ||
1273 | let a = z; | ||
1274 | let (c, d) = (1, "hello"); | ||
1275 | |||
1276 | for (e, f) in some_iter { | ||
1277 | let g = e; | ||
1278 | } | ||
1279 | |||
1280 | if let [val] = opt { | ||
1281 | let h = val; | ||
1282 | } | ||
1283 | |||
1284 | let lambda = |a: u64, b, c: i32| { a + b; c }; | ||
1285 | |||
1286 | let ref ref_to_x = x; | ||
1287 | let mut mut_x = x; | ||
1288 | let ref mut mut_ref_to_x = x; | ||
1289 | let k = mut_ref_to_x; | ||
1290 | } | ||
1291 | "#), | ||
1292 | @r###" | ||
1293 | [9; 10) 'x': &i32 | ||
1294 | [18; 369) '{ ...o_x; }': () | ||
1295 | [28; 29) 'y': &i32 | ||
1296 | [32; 33) 'x': &i32 | ||
1297 | [43; 45) '&z': &i32 | ||
1298 | [44; 45) 'z': i32 | ||
1299 | [48; 49) 'x': &i32 | ||
1300 | [59; 60) 'a': i32 | ||
1301 | [63; 64) 'z': i32 | ||
1302 | [74; 80) '(c, d)': (i32, &str) | ||
1303 | [75; 76) 'c': i32 | ||
1304 | [78; 79) 'd': &str | ||
1305 | [83; 95) '(1, "hello")': (i32, &str) | ||
1306 | [84; 85) '1': i32 | ||
1307 | [87; 94) '"hello"': &str | ||
1308 | [102; 152) 'for (e... }': () | ||
1309 | [106; 112) '(e, f)': ({unknown}, {unknown}) | ||
1310 | [107; 108) 'e': {unknown} | ||
1311 | [110; 111) 'f': {unknown} | ||
1312 | [116; 125) 'some_iter': {unknown} | ||
1313 | [126; 152) '{ ... }': () | ||
1314 | [140; 141) 'g': {unknown} | ||
1315 | [144; 145) 'e': {unknown} | ||
1316 | [158; 205) 'if let... }': () | ||
1317 | [165; 170) '[val]': {unknown} | ||
1318 | [173; 176) 'opt': {unknown} | ||
1319 | [177; 205) '{ ... }': () | ||
1320 | [191; 192) 'h': {unknown} | ||
1321 | [195; 198) 'val': {unknown} | ||
1322 | [215; 221) 'lambda': |u64, u64, i32| -> i32 | ||
1323 | [224; 256) '|a: u6...b; c }': |u64, u64, i32| -> i32 | ||
1324 | [225; 226) 'a': u64 | ||
1325 | [233; 234) 'b': u64 | ||
1326 | [236; 237) 'c': i32 | ||
1327 | [244; 256) '{ a + b; c }': i32 | ||
1328 | [246; 247) 'a': u64 | ||
1329 | [246; 251) 'a + b': u64 | ||
1330 | [250; 251) 'b': u64 | ||
1331 | [253; 254) 'c': i32 | ||
1332 | [267; 279) 'ref ref_to_x': &&i32 | ||
1333 | [282; 283) 'x': &i32 | ||
1334 | [293; 302) 'mut mut_x': &i32 | ||
1335 | [305; 306) 'x': &i32 | ||
1336 | [316; 336) 'ref mu...f_to_x': &mut &i32 | ||
1337 | [339; 340) 'x': &i32 | ||
1338 | [350; 351) 'k': &mut &i32 | ||
1339 | [354; 366) 'mut_ref_to_x': &mut &i32 | ||
1340 | "### | ||
1341 | ); | ||
1342 | } | ||
1343 | |||
1344 | #[test] | ||
1345 | fn infer_pattern_match_ergonomics() { | ||
1346 | assert_snapshot!( | ||
1347 | infer(r#" | ||
1348 | struct A<T>(T); | ||
1349 | |||
1350 | fn test() { | ||
1351 | let A(n) = &A(1); | ||
1352 | let A(n) = &mut A(1); | ||
1353 | } | ||
1354 | "#), | ||
1355 | @r###" | ||
1356 | [28; 79) '{ ...(1); }': () | ||
1357 | [38; 42) 'A(n)': A<i32> | ||
13 |