]> git.lizzy.rs Git - rust.git/blob - crates/hir_ty/src/infer/coerce.rs
clippy::redundant_clone fixes
[rust.git] / crates / hir_ty / src / infer / coerce.rs
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 and
6 //! librustc_typeck/check/coercion.rs.
7
8 use chalk_ir::{cast::Cast, Mutability, TyVariableKind};
9 use hir_def::{expr::ExprId, lang_item::LangItemTarget};
10
11 use crate::{
12     autoderef, infer::TypeMismatch, static_lifetime, Canonical, DomainGoal, FnPointer, FnSig,
13     Interner, Solution, Substitution, Ty, TyBuilder, TyExt, TyKind,
14 };
15
16 use super::{InEnvironment, InferOk, InferResult, InferenceContext, TypeError};
17
18 impl<'a> InferenceContext<'a> {
19     /// Unify two types, but may coerce the first one to the second one
20     /// using "implicit coercion rules" if needed.
21     pub(super) fn coerce(&mut self, from_ty: &Ty, to_ty: &Ty) -> bool {
22         let from_ty = self.resolve_ty_shallow(from_ty);
23         let to_ty = self.resolve_ty_shallow(to_ty);
24         match self.coerce_inner(from_ty, &to_ty) {
25             Ok(result) => {
26                 self.table.register_infer_ok(result);
27                 true
28             }
29             Err(_) => {
30                 // FIXME deal with error
31                 false
32             }
33         }
34     }
35
36     /// Merge two types from different branches, with possible coercion.
37     ///
38     /// Mostly this means trying to coerce one to the other, but
39     ///  - if we have two function types for different functions or closures, we need to
40     ///    coerce both to function pointers;
41     ///  - if we were concerned with lifetime subtyping, we'd need to look for a
42     ///    least upper bound.
43     pub(super) fn coerce_merge_branch(&mut self, id: Option<ExprId>, ty1: &Ty, ty2: &Ty) -> Ty {
44         let ty1 = self.resolve_ty_shallow(ty1);
45         let ty2 = self.resolve_ty_shallow(ty2);
46         // Special case: two function types. Try to coerce both to
47         // pointers to have a chance at getting a match. See
48         // https://github.com/rust-lang/rust/blob/7b805396bf46dce972692a6846ce2ad8481c5f85/src/librustc_typeck/check/coercion.rs#L877-L916
49         let sig = match (ty1.kind(&Interner), ty2.kind(&Interner)) {
50             (TyKind::FnDef(..), TyKind::FnDef(..))
51             | (TyKind::Closure(..), TyKind::FnDef(..))
52             | (TyKind::FnDef(..), TyKind::Closure(..))
53             | (TyKind::Closure(..), TyKind::Closure(..)) => {
54                 // FIXME: we're ignoring safety here. To be more correct, if we have one FnDef and one Closure,
55                 // we should be coercing the closure to a fn pointer of the safety of the FnDef
56                 cov_mark::hit!(coerce_fn_reification);
57                 let sig = ty1.callable_sig(self.db).expect("FnDef without callable sig");
58                 Some(sig)
59             }
60             _ => None,
61         };
62         if let Some(sig) = sig {
63             let target_ty = TyKind::Function(sig.to_fn_ptr()).intern(&Interner);
64             let result1 = self.coerce_inner(ty1.clone(), &target_ty);
65             let result2 = self.coerce_inner(ty2.clone(), &target_ty);
66             if let (Ok(result1), Ok(result2)) = (result1, result2) {
67                 self.table.register_infer_ok(result1);
68                 self.table.register_infer_ok(result2);
69                 return target_ty;
70             }
71         }
72
73         // It might not seem like it, but order is important here: ty1 is our
74         // "previous" type, ty2 is the "new" one being added. If the previous
75         // type is a type variable and the new one is `!`, trying it the other
76         // way around first would mean we make the type variable `!`, instead of
77         // just marking it as possibly diverging.
78         if self.coerce(&ty2, &ty1) {
79             ty1
80         } else if self.coerce(&ty1, &ty2) {
81             ty2
82         } else {
83             if let Some(id) = id {
84                 self.result
85                     .type_mismatches
86                     .insert(id.into(), TypeMismatch { expected: ty1.clone(), actual: ty2 });
87             }
88             cov_mark::hit!(coerce_merge_fail_fallback);
89             ty1
90         }
91     }
92
93     fn coerce_inner(&mut self, from_ty: Ty, to_ty: &Ty) -> InferResult {
94         if from_ty.is_never() {
95             // Subtle: If we are coercing from `!` to `?T`, where `?T` is an unbound
96             // type variable, we want `?T` to fallback to `!` if not
97             // otherwise constrained. An example where this arises:
98             //
99             //     let _: Option<?T> = Some({ return; });
100             //
101             // here, we would coerce from `!` to `?T`.
102             match to_ty.kind(&Interner) {
103                 TyKind::InferenceVar(tv, TyVariableKind::General) => {
104                     self.table.set_diverging(*tv, true);
105                 }
106                 _ => {}
107             }
108             return Ok(InferOk { goals: Vec::new() });
109         }
110
111         // Consider coercing the subtype to a DST
112         if let Ok(ret) = self.try_coerce_unsized(&from_ty, &to_ty) {
113             return Ok(ret);
114         }
115
116         // Examine the supertype and consider auto-borrowing.
117         match to_ty.kind(&Interner) {
118             TyKind::Raw(mt, _) => {
119                 return self.coerce_ptr(from_ty, to_ty, *mt);
120             }
121             TyKind::Ref(mt, _, _) => {
122                 return self.coerce_ref(from_ty, to_ty, *mt);
123             }
124             _ => {}
125         }
126
127         match from_ty.kind(&Interner) {
128             TyKind::FnDef(..) => {
129                 // Function items are coercible to any closure
130                 // type; function pointers are not (that would
131                 // require double indirection).
132                 // Additionally, we permit coercion of function
133                 // items to drop the unsafe qualifier.
134                 self.coerce_from_fn_item(from_ty, to_ty)
135             }
136             TyKind::Function(from_fn_ptr) => {
137                 // We permit coercion of fn pointers to drop the
138                 // unsafe qualifier.
139                 self.coerce_from_fn_pointer(from_ty.clone(), from_fn_ptr, to_ty)
140             }
141             TyKind::Closure(_, from_substs) => {
142                 // Non-capturing closures are coercible to
143                 // function pointers or unsafe function pointers.
144                 // It cannot convert closures that require unsafe.
145                 self.coerce_closure_to_fn(from_ty.clone(), from_substs, to_ty)
146             }
147             _ => {
148                 // Otherwise, just use unification rules.
149                 self.table.try_unify(&from_ty, to_ty)
150             }
151         }
152     }
153
154     fn coerce_ptr(&mut self, from_ty: Ty, to_ty: &Ty, to_mt: Mutability) -> InferResult {
155         let (_is_ref, from_mt, from_inner) = match from_ty.kind(&Interner) {
156             TyKind::Ref(mt, _, ty) => (true, mt, ty),
157             TyKind::Raw(mt, ty) => (false, mt, ty),
158             _ => return self.table.try_unify(&from_ty, to_ty),
159         };
160
161         coerce_mutabilities(*from_mt, to_mt)?;
162
163         // Check that the types which they point at are compatible.
164         let from_raw = TyKind::Raw(to_mt, from_inner.clone()).intern(&Interner);
165         // FIXME: behavior differs based on is_ref once we're computing adjustments
166         self.table.try_unify(&from_raw, to_ty)
167     }
168
169     /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`.
170     /// To match `A` with `B`, autoderef will be performed,
171     /// calling `deref`/`deref_mut` where necessary.
172     fn coerce_ref(&mut self, from_ty: Ty, to_ty: &Ty, to_mt: Mutability) -> InferResult {
173         match from_ty.kind(&Interner) {
174             TyKind::Ref(mt, _, _) => {
175                 coerce_mutabilities(*mt, to_mt)?;
176             }
177             _ => return self.table.try_unify(&from_ty, to_ty),
178         };
179
180         // NOTE: this code is mostly copied and adapted from rustc, and
181         // currently more complicated than necessary, carrying errors around
182         // etc.. This complication will become necessary when we actually track
183         // details of coercion errors though, so I think it's useful to leave
184         // the structure like it is.
185
186         let canonicalized = self.canonicalize(from_ty);
187         let autoderef = autoderef::autoderef(
188             self.db,
189             self.resolver.krate(),
190             InEnvironment {
191                 goal: canonicalized.value.clone(),
192                 environment: self.trait_env.env.clone(),
193             },
194         );
195         let mut first_error = None;
196         let mut found = None;
197
198         for (autoderefs, referent_ty) in autoderef.enumerate() {
199             if autoderefs == 0 {
200                 // Don't let this pass, otherwise it would cause
201                 // &T to autoref to &&T.
202                 continue;
203             }
204
205             let referent_ty = canonicalized.decanonicalize_ty(referent_ty.value);
206
207             // At this point, we have deref'd `a` to `referent_ty`.  So
208             // imagine we are coercing from `&'a mut Vec<T>` to `&'b mut [T]`.
209             // In the autoderef loop for `&'a mut Vec<T>`, we would get
210             // three callbacks:
211             //
212             // - `&'a mut Vec<T>` -- 0 derefs, just ignore it
213             // - `Vec<T>` -- 1 deref
214             // - `[T]` -- 2 deref
215             //
216             // At each point after the first callback, we want to
217             // check to see whether this would match out target type
218             // (`&'b mut [T]`) if we autoref'd it. We can't just
219             // compare the referent types, though, because we still
220             // have to consider the mutability. E.g., in the case
221             // we've been considering, we have an `&mut` reference, so
222             // the `T` in `[T]` needs to be unified with equality.
223             //
224             // Therefore, we construct reference types reflecting what
225             // the types will be after we do the final auto-ref and
226             // compare those. Note that this means we use the target
227             // mutability [1], since it may be that we are coercing
228             // from `&mut T` to `&U`.
229             let lt = static_lifetime(); // FIXME: handle lifetimes correctly, see rustc
230             let derefd_from_ty = TyKind::Ref(to_mt, lt, referent_ty).intern(&Interner);
231             match self.table.try_unify(&derefd_from_ty, to_ty) {
232                 Ok(result) => {
233                     found = Some(result);
234                     break;
235                 }
236                 Err(err) => {
237                     if first_error.is_none() {
238                         first_error = Some(err);
239                     }
240                 }
241             }
242         }
243
244         // Extract type or return an error. We return the first error
245         // we got, which should be from relating the "base" type
246         // (e.g., in example above, the failure from relating `Vec<T>`
247         // to the target type), since that should be the least
248         // confusing.
249         let result = match found {
250             Some(d) => d,
251             None => {
252                 let err = first_error.expect("coerce_borrowed_pointer had no error");
253                 return Err(err);
254             }
255         };
256
257         Ok(result)
258     }
259
260     /// Attempts to coerce from the type of a Rust function item into a function pointer.
261     fn coerce_from_fn_item(&mut self, from_ty: Ty, to_ty: &Ty) -> InferResult {
262         match to_ty.kind(&Interner) {
263             TyKind::Function(_) => {
264                 let from_sig = from_ty.callable_sig(self.db).expect("FnDef had no sig");
265
266                 // FIXME check ABI: Intrinsics are not coercible to function pointers
267                 // FIXME Safe `#[target_feature]` functions are not assignable to safe fn pointers (RFC 2396)
268
269                 // FIXME rustc normalizes assoc types in the sig here, not sure if necessary
270
271                 let from_sig = from_sig.to_fn_ptr();
272                 let from_fn_pointer = TyKind::Function(from_sig.clone()).intern(&Interner);
273                 let ok = self.coerce_from_safe_fn(from_fn_pointer, &from_sig, to_ty)?;
274
275                 Ok(ok)
276             }
277             _ => self.table.try_unify(&from_ty, to_ty),
278         }
279     }
280
281     fn coerce_from_fn_pointer(
282         &mut self,
283         from_ty: Ty,
284         from_f: &FnPointer,
285         to_ty: &Ty,
286     ) -> InferResult {
287         self.coerce_from_safe_fn(from_ty, from_f, to_ty)
288     }
289
290     fn coerce_from_safe_fn(
291         &mut self,
292         from_ty: Ty,
293         from_fn_ptr: &FnPointer,
294         to_ty: &Ty,
295     ) -> InferResult {
296         if let TyKind::Function(to_fn_ptr) = to_ty.kind(&Interner) {
297             if let (chalk_ir::Safety::Safe, chalk_ir::Safety::Unsafe) =
298                 (from_fn_ptr.sig.safety, to_fn_ptr.sig.safety)
299             {
300                 let from_unsafe =
301                     TyKind::Function(safe_to_unsafe_fn_ty(from_fn_ptr.clone())).intern(&Interner);
302                 return self.table.try_unify(&from_unsafe, to_ty);
303             }
304         }
305         self.table.try_unify(&from_ty, to_ty)
306     }
307
308     /// Attempts to coerce from the type of a non-capturing closure into a
309     /// function pointer.
310     fn coerce_closure_to_fn(
311         &mut self,
312         from_ty: Ty,
313         from_substs: &Substitution,
314         to_ty: &Ty,
315     ) -> InferResult {
316         match to_ty.kind(&Interner) {
317             TyKind::Function(fn_ty) /* if from_substs is non-capturing (FIXME) */ => {
318                 // We coerce the closure, which has fn type
319                 //     `extern "rust-call" fn((arg0,arg1,...)) -> _`
320                 // to
321                 //     `fn(arg0,arg1,...) -> _`
322                 // or
323                 //     `unsafe fn(arg0,arg1,...) -> _`
324                 let safety = fn_ty.sig.safety;
325                 let pointer_ty = coerce_closure_fn_ty(from_substs, safety);
326                 self.table.try_unify(&pointer_ty, to_ty)
327             }
328             _ => self.table.try_unify(&from_ty, to_ty),
329         }
330     }
331
332     /// Coerce a type using `from_ty: CoerceUnsized<ty_ty>`
333     ///
334     /// See: https://doc.rust-lang.org/nightly/std/marker/trait.CoerceUnsized.html
335     fn try_coerce_unsized(&mut self, from_ty: &Ty, to_ty: &Ty) -> InferResult {
336         // These 'if' statements require some explanation.
337         // The `CoerceUnsized` trait is special - it is only
338         // possible to write `impl CoerceUnsized<B> for A` where
339         // A and B have 'matching' fields. This rules out the following
340         // two types of blanket impls:
341         //
342         // `impl<T> CoerceUnsized<T> for SomeType`
343         // `impl<T> CoerceUnsized<SomeType> for T`
344         //
345         // Both of these trigger a special `CoerceUnsized`-related error (E0376)
346         //
347         // We can take advantage of this fact to avoid performing unecessary work.
348         // If either `source` or `target` is a type variable, then any applicable impl
349         // would need to be generic over the self-type (`impl<T> CoerceUnsized<SomeType> for T`)
350         // or generic over the `CoerceUnsized` type parameter (`impl<T> CoerceUnsized<T> for
351         // SomeType`).
352         //
353         // However, these are exactly the kinds of impls which are forbidden by
354         // the compiler! Therefore, we can be sure that coercion will always fail
355         // when either the source or target type is a type variable. This allows us
356         // to skip performing any trait selection, and immediately bail out.
357         if from_ty.is_ty_var() {
358             return Err(TypeError);
359         }
360         if to_ty.is_ty_var() {
361             return Err(TypeError);
362         }
363
364         // Handle reborrows before trying to solve `Source: CoerceUnsized<Target>`.
365         let coerce_from = match (from_ty.kind(&Interner), to_ty.kind(&Interner)) {
366             (TyKind::Ref(from_mt, _, from_inner), TyKind::Ref(to_mt, _, _)) => {
367                 coerce_mutabilities(*from_mt, *to_mt)?;
368
369                 let lt = static_lifetime();
370                 TyKind::Ref(*to_mt, lt, from_inner.clone()).intern(&Interner)
371             }
372             (TyKind::Ref(from_mt, _, from_inner), TyKind::Raw(to_mt, _)) => {
373                 coerce_mutabilities(*from_mt, *to_mt)?;
374
375                 TyKind::Raw(*to_mt, from_inner.clone()).intern(&Interner)
376             }
377             _ => from_ty.clone(),
378         };
379
380         let krate = self.resolver.krate().unwrap();
381         let coerce_unsized_trait = match self.db.lang_item(krate, "coerce_unsized".into()) {
382             Some(LangItemTarget::TraitId(trait_)) => trait_,
383             _ => return Err(TypeError),
384         };
385
386         let trait_ref = {
387             let b = TyBuilder::trait_ref(self.db, coerce_unsized_trait);
388             if b.remaining() != 2 {
389                 // The CoerceUnsized trait should have two generic params: Self and T.
390                 return Err(TypeError);
391             }
392             b.push(coerce_from).push(to_ty.clone()).build()
393         };
394
395         let goal: InEnvironment<DomainGoal> =
396             InEnvironment::new(&self.trait_env.env, trait_ref.cast(&Interner));
397
398         let canonicalized = self.canonicalize(goal);
399
400         // FIXME: rustc's coerce_unsized is more specialized -- it only tries to
401         // solve `CoerceUnsized` and `Unsize` goals at this point and leaves the
402         // rest for later. Also, there's some logic about sized type variables.
403         // Need to find out in what cases this is necessary
404         let solution = self
405             .db
406             .trait_solve(krate, canonicalized.value.clone().cast(&Interner))
407             .ok_or(TypeError)?;
408
409         match solution {
410             Solution::Unique(v) => {
411                 canonicalized.apply_solution(
412                     &mut self.table,
413                     Canonical {
414                         binders: v.binders,
415                         // FIXME handle constraints
416                         value: v.value.subst,
417                     },
418                 );
419             }
420             // FIXME: should we accept ambiguous results here?
421             _ => return Err(TypeError),
422         };
423
424         Ok(InferOk { goals: Vec::new() })
425     }
426 }
427
428 fn coerce_closure_fn_ty(closure_substs: &Substitution, safety: chalk_ir::Safety) -> Ty {
429     let closure_sig = closure_substs.at(&Interner, 0).assert_ty_ref(&Interner).clone();
430     match closure_sig.kind(&Interner) {
431         TyKind::Function(fn_ty) => TyKind::Function(FnPointer {
432             num_binders: fn_ty.num_binders,
433             sig: FnSig { safety, ..fn_ty.sig },
434             substitution: fn_ty.substitution.clone(),
435         })
436         .intern(&Interner),
437         _ => TyKind::Error.intern(&Interner),
438     }
439 }
440
441 fn safe_to_unsafe_fn_ty(fn_ty: FnPointer) -> FnPointer {
442     FnPointer {
443         num_binders: fn_ty.num_binders,
444         sig: FnSig { safety: chalk_ir::Safety::Unsafe, ..fn_ty.sig },
445         substitution: fn_ty.substitution,
446     }
447 }
448
449 fn coerce_mutabilities(from: Mutability, to: Mutability) -> Result<(), TypeError> {
450     match (from, to) {
451         (Mutability::Mut, Mutability::Mut)
452         | (Mutability::Mut, Mutability::Not)
453         | (Mutability::Not, Mutability::Not) => Ok(()),
454         (Mutability::Not, Mutability::Mut) => Err(TypeError),
455     }
456 }