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