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