hir_ty/infer/coerce.rs
1//! # Type Coercion
2//!
3//! Under certain circumstances we will coerce from one type to another,
4//! for example by auto-borrowing. This occurs in situations where the
5//! compiler has a firm 'expected type' that was supplied from the user,
6//! and where the actual type is similar to that expected type in purpose
7//! but not in representation (so actual subtyping is inappropriate).
8//!
9//! ## Reborrowing
10//!
11//! Note that if we are expecting a reference, we will *reborrow*
12//! even if the argument provided was already a reference. This is
13//! useful for freezing mut things (that is, when the expected type is &T
14//! but you have &mut T) and also for avoiding the linearity
15//! of mut things (when the expected is &mut T and you have &mut T). See
16//! the various `tests/ui/coerce/*.rs` tests for
17//! examples of where this is useful.
18//!
19//! ## Subtle note
20//!
21//! When inferring the generic arguments of functions, the argument
22//! order is relevant, which can lead to the following edge case:
23//!
24//! ```ignore (illustrative)
25//! fn foo<T>(a: T, b: T) {
26//! // ...
27//! }
28//!
29//! foo(&7i32, &mut 7i32);
30//! // This compiles, as we first infer `T` to be `&i32`,
31//! // and then coerce `&mut 7i32` to `&7i32`.
32//!
33//! foo(&mut 7i32, &7i32);
34//! // This does not compile, as we first infer `T` to be `&mut i32`
35//! // and are then unable to coerce `&7i32` to `&mut i32`.
36//! ```
37
38use hir_def::{
39 CallableDefId,
40 attrs::AttrFlags,
41 hir::{ExprId, ExprOrPatId},
42 signatures::FunctionSignature,
43};
44use rustc_ast_ir::Mutability;
45use rustc_type_ir::{
46 BoundVar, DebruijnIndex, TyVid, TypeAndMut, TypeFoldable, TypeFolder, TypeSuperFoldable,
47 TypeVisitableExt,
48 error::TypeError,
49 inherent::{Const as _, GenericArg as _, IntoKind, Safety, SliceLike, Ty as _},
50};
51use smallvec::{SmallVec, smallvec};
52use tracing::{debug, instrument};
53
54use crate::{
55 Adjust, Adjustment, AutoBorrow, ParamEnvAndCrate, PointerCast, TargetFeatures,
56 autoderef::Autoderef,
57 db::{HirDatabase, InternedClosureId},
58 infer::{
59 AllowTwoPhase, AutoBorrowMutability, InferenceContext, TypeMismatch, expr::ExprIsRead,
60 },
61 next_solver::{
62 Binder, BoundConst, BoundRegion, BoundRegionKind, BoundTy, BoundTyKind, CallableIdWrapper,
63 Canonical, ClauseKind, CoercePredicate, Const, ConstKind, DbInterner, ErrorGuaranteed,
64 GenericArgs, ParamEnv, PolyFnSig, PredicateKind, Region, RegionKind, TraitRef, Ty, TyKind,
65 TypingMode,
66 infer::{
67 DbInternerInferExt, InferCtxt, InferOk, InferResult,
68 relate::RelateResult,
69 select::{ImplSource, SelectionError},
70 traits::{Obligation, ObligationCause, PredicateObligation, PredicateObligations},
71 },
72 obligation_ctxt::ObligationCtxt,
73 },
74 utils::TargetFeatureIsSafeInTarget,
75};
76
77trait CoerceDelegate<'db> {
78 fn infcx(&self) -> &InferCtxt<'db>;
79 fn param_env(&self) -> ParamEnv<'db>;
80 fn target_features(&self) -> (&TargetFeatures<'db>, TargetFeatureIsSafeInTarget);
81
82 fn set_diverging(&mut self, diverging_ty: Ty<'db>);
83
84 fn set_tainted_by_errors(&mut self);
85
86 fn type_var_is_sized(&mut self, var: TyVid) -> bool;
87}
88
89struct Coerce<D> {
90 delegate: D,
91 use_lub: bool,
92 /// Determines whether or not allow_two_phase_borrow is set on any
93 /// autoref adjustments we create while coercing. We don't want to
94 /// allow deref coercions to create two-phase borrows, at least initially,
95 /// but we do need two-phase borrows for function argument reborrows.
96 /// See rust#47489 and rust#48598
97 /// See docs on the "AllowTwoPhase" type for a more detailed discussion
98 allow_two_phase: AllowTwoPhase,
99 /// Whether we allow `NeverToAny` coercions. This is unsound if we're
100 /// coercing a place expression without it counting as a read in the MIR.
101 /// This is a side-effect of HIR not really having a great distinction
102 /// between places and values.
103 coerce_never: bool,
104 cause: ObligationCause,
105}
106
107type CoerceResult<'db> = InferResult<'db, (Vec<Adjustment<'db>>, Ty<'db>)>;
108
109/// Coercing a mutable reference to an immutable works, while
110/// coercing `&T` to `&mut T` should be forbidden.
111fn coerce_mutbls<'db>(from_mutbl: Mutability, to_mutbl: Mutability) -> RelateResult<'db, ()> {
112 if from_mutbl >= to_mutbl { Ok(()) } else { Err(TypeError::Mutability) }
113}
114
115/// This always returns `Ok(...)`.
116fn success<'db>(
117 adj: Vec<Adjustment<'db>>,
118 target: Ty<'db>,
119 obligations: PredicateObligations<'db>,
120) -> CoerceResult<'db> {
121 Ok(InferOk { value: (adj, target), obligations })
122}
123
124impl<'db, D> Coerce<D>
125where
126 D: CoerceDelegate<'db>,
127{
128 #[inline]
129 fn set_tainted_by_errors(&mut self) {
130 self.delegate.set_tainted_by_errors();
131 }
132
133 #[inline]
134 fn infcx(&self) -> &InferCtxt<'db> {
135 self.delegate.infcx()
136 }
137
138 #[inline]
139 fn param_env(&self) -> ParamEnv<'db> {
140 self.delegate.param_env()
141 }
142
143 #[inline]
144 fn interner(&self) -> DbInterner<'db> {
145 self.infcx().interner
146 }
147
148 #[inline]
149 fn db(&self) -> &'db dyn HirDatabase {
150 self.interner().db
151 }
152
153 pub(crate) fn commit_if_ok<T, E>(
154 &mut self,
155 f: impl FnOnce(&mut Self) -> Result<T, E>,
156 ) -> Result<T, E> {
157 let snapshot = self.infcx().start_snapshot();
158 let result = f(self);
159 match result {
160 Ok(_) => {}
161 Err(_) => {
162 self.infcx().rollback_to(snapshot);
163 }
164 }
165 result
166 }
167
168 fn unify_raw(&self, a: Ty<'db>, b: Ty<'db>) -> InferResult<'db, Ty<'db>> {
169 debug!("unify(a: {:?}, b: {:?}, use_lub: {})", a, b, self.use_lub);
170 self.infcx().commit_if_ok(|_| {
171 let at = self.infcx().at(&self.cause, self.param_env());
172
173 let res = if self.use_lub {
174 at.lub(b, a)
175 } else {
176 at.sup(b, a)
177 .map(|InferOk { value: (), obligations }| InferOk { value: b, obligations })
178 };
179
180 // In the new solver, lazy norm may allow us to shallowly equate
181 // more types, but we emit possibly impossible-to-satisfy obligations.
182 // Filter these cases out to make sure our coercion is more accurate.
183 match res {
184 Ok(InferOk { value, obligations }) => {
185 let mut ocx = ObligationCtxt::new(self.infcx());
186 ocx.register_obligations(obligations);
187 if ocx.try_evaluate_obligations().is_empty() {
188 Ok(InferOk { value, obligations: ocx.into_pending_obligations() })
189 } else {
190 Err(TypeError::Mismatch)
191 }
192 }
193 res => res,
194 }
195 })
196 }
197
198 /// Unify two types (using sub or lub).
199 fn unify(&mut self, a: Ty<'db>, b: Ty<'db>) -> CoerceResult<'db> {
200 self.unify_raw(a, b)
201 .and_then(|InferOk { value: ty, obligations }| success(vec![], ty, obligations))
202 }
203
204 /// Unify two types (using sub or lub) and produce a specific coercion.
205 fn unify_and(
206 &mut self,
207 a: Ty<'db>,
208 b: Ty<'db>,
209 adjustments: impl IntoIterator<Item = Adjustment<'db>>,
210 final_adjustment: Adjust,
211 ) -> CoerceResult<'db> {
212 self.unify_raw(a, b).and_then(|InferOk { value: ty, obligations }| {
213 success(
214 adjustments
215 .into_iter()
216 .chain(std::iter::once(Adjustment { target: ty, kind: final_adjustment }))
217 .collect(),
218 ty,
219 obligations,
220 )
221 })
222 }
223
224 #[instrument(skip(self))]
225 fn coerce(&mut self, a: Ty<'db>, b: Ty<'db>) -> CoerceResult<'db> {
226 // First, remove any resolved type variables (at the top level, at least):
227 let a = self.infcx().shallow_resolve(a);
228 let b = self.infcx().shallow_resolve(b);
229 debug!("Coerce.tys({:?} => {:?})", a, b);
230
231 // Coercing from `!` to any type is allowed:
232 if a.is_never() {
233 // If we're coercing into an inference var, mark it as possibly diverging.
234 if b.is_infer() {
235 self.delegate.set_diverging(b);
236 }
237
238 if self.coerce_never {
239 return success(
240 vec![Adjustment { kind: Adjust::NeverToAny, target: b }],
241 b,
242 PredicateObligations::new(),
243 );
244 } else {
245 // Otherwise the only coercion we can do is unification.
246 return self.unify(a, b);
247 }
248 }
249
250 // Coercing *from* an unresolved inference variable means that
251 // we have no information about the source type. This will always
252 // ultimately fall back to some form of subtyping.
253 if a.is_infer() {
254 return self.coerce_from_inference_variable(a, b);
255 }
256
257 // Consider coercing the subtype to a DST
258 //
259 // NOTE: this is wrapped in a `commit_if_ok` because it creates
260 // a "spurious" type variable, and we don't want to have that
261 // type variable in memory if the coercion fails.
262 let unsize = self.commit_if_ok(|this| this.coerce_unsized(a, b));
263 match unsize {
264 Ok(_) => {
265 debug!("coerce: unsize successful");
266 return unsize;
267 }
268 Err(error) => {
269 debug!(?error, "coerce: unsize failed");
270 }
271 }
272
273 // Examine the supertype and consider type-specific coercions, such
274 // as auto-borrowing, coercing pointer mutability, a `dyn*` coercion,
275 // or pin-ergonomics.
276 match b.kind() {
277 TyKind::RawPtr(_, b_mutbl) => {
278 return self.coerce_raw_ptr(a, b, b_mutbl);
279 }
280 TyKind::Ref(r_b, _, mutbl_b) => {
281 return self.coerce_borrowed_pointer(a, b, r_b, mutbl_b);
282 }
283 _ => {}
284 }
285
286 match a.kind() {
287 TyKind::FnDef(..) => {
288 // Function items are coercible to any closure
289 // type; function pointers are not (that would
290 // require double indirection).
291 // Additionally, we permit coercion of function
292 // items to drop the unsafe qualifier.
293 self.coerce_from_fn_item(a, b)
294 }
295 TyKind::FnPtr(a_sig_tys, a_hdr) => {
296 // We permit coercion of fn pointers to drop the
297 // unsafe qualifier.
298 self.coerce_from_fn_pointer(a_sig_tys.with(a_hdr), b)
299 }
300 TyKind::Closure(closure_def_id_a, args_a) => {
301 // Non-capturing closures are coercible to
302 // function pointers or unsafe function pointers.
303 // It cannot convert closures that require unsafe.
304 self.coerce_closure_to_fn(a, closure_def_id_a.0, args_a, b)
305 }
306 _ => {
307 // Otherwise, just use unification rules.
308 self.unify(a, b)
309 }
310 }
311 }
312
313 /// Coercing *from* an inference variable. In this case, we have no information
314 /// about the source type, so we can't really do a true coercion and we always
315 /// fall back to subtyping (`unify_and`).
316 fn coerce_from_inference_variable(&mut self, a: Ty<'db>, b: Ty<'db>) -> CoerceResult<'db> {
317 debug!("coerce_from_inference_variable(a={:?}, b={:?})", a, b);
318 debug_assert!(a.is_infer() && self.infcx().shallow_resolve(a) == a);
319 debug_assert!(self.infcx().shallow_resolve(b) == b);
320
321 if b.is_infer() {
322 // Two unresolved type variables: create a `Coerce` predicate.
323 let target_ty = if self.use_lub { self.infcx().next_ty_var() } else { b };
324
325 let mut obligations = PredicateObligations::with_capacity(2);
326 for &source_ty in &[a, b] {
327 if source_ty != target_ty {
328 obligations.push(Obligation::new(
329 self.interner(),
330 self.cause.clone(),
331 self.param_env(),
332 Binder::dummy(PredicateKind::Coerce(CoercePredicate {
333 a: source_ty,
334 b: target_ty,
335 })),
336 ));
337 }
338 }
339
340 debug!(
341 "coerce_from_inference_variable: two inference variables, target_ty={:?}, obligations={:?}",
342 target_ty, obligations
343 );
344 success(vec![], target_ty, obligations)
345 } else {
346 // One unresolved type variable: just apply subtyping, we may be able
347 // to do something useful.
348 self.unify(a, b)
349 }
350 }
351
352 /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`.
353 /// To match `A` with `B`, autoderef will be performed,
354 /// calling `deref`/`deref_mut` where necessary.
355 fn coerce_borrowed_pointer(
356 &mut self,
357 a: Ty<'db>,
358 b: Ty<'db>,
359 r_b: Region<'db>,
360 mutbl_b: Mutability,
361 ) -> CoerceResult<'db> {
362 debug!("coerce_borrowed_pointer(a={:?}, b={:?})", a, b);
363 debug_assert!(self.infcx().shallow_resolve(a) == a);
364 debug_assert!(self.infcx().shallow_resolve(b) == b);
365
366 // If we have a parameter of type `&M T_a` and the value
367 // provided is `expr`, we will be adding an implicit borrow,
368 // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore,
369 // to type check, we will construct the type that `&M*expr` would
370 // yield.
371
372 let (r_a, mt_a) = match a.kind() {
373 TyKind::Ref(r_a, ty, mutbl) => {
374 let mt_a = TypeAndMut::<DbInterner<'db>> { ty, mutbl };
375 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
376 (r_a, mt_a)
377 }
378 _ => return self.unify(a, b),
379 };
380
381 let mut first_error = None;
382 let mut r_borrow_var = None;
383 let mut autoderef = Autoderef::new_with_tracking(self.infcx(), self.param_env(), a);
384 let mut found = None;
385
386 for (referent_ty, autoderefs) in autoderef.by_ref() {
387 if autoderefs == 0 {
388 // Don't let this pass, otherwise it would cause
389 // &T to autoref to &&T.
390 continue;
391 }
392
393 // At this point, we have deref'd `a` to `referent_ty`. So
394 // imagine we are coercing from `&'a mut Vec<T>` to `&'b mut [T]`.
395 // In the autoderef loop for `&'a mut Vec<T>`, we would get
396 // three callbacks:
397 //
398 // - `&'a mut Vec<T>` -- 0 derefs, just ignore it
399 // - `Vec<T>` -- 1 deref
400 // - `[T]` -- 2 deref
401 //
402 // At each point after the first callback, we want to
403 // check to see whether this would match out target type
404 // (`&'b mut [T]`) if we autoref'd it. We can't just
405 // compare the referent types, though, because we still
406 // have to consider the mutability. E.g., in the case
407 // we've been considering, we have an `&mut` reference, so
408 // the `T` in `[T]` needs to be unified with equality.
409 //
410 // Therefore, we construct reference types reflecting what
411 // the types will be after we do the final auto-ref and
412 // compare those. Note that this means we use the target
413 // mutability [1], since it may be that we are coercing
414 // from `&mut T` to `&U`.
415 //
416 // One fine point concerns the region that we use. We
417 // choose the region such that the region of the final
418 // type that results from `unify` will be the region we
419 // want for the autoref:
420 //
421 // - if in sub mode, that means we want to use `'b` (the
422 // region from the target reference) for both
423 // pointers [2]. This is because sub mode (somewhat
424 // arbitrarily) returns the subtype region. In the case
425 // where we are coercing to a target type, we know we
426 // want to use that target type region (`'b`) because --
427 // for the program to type-check -- it must be the
428 // smaller of the two.
429 // - One fine point. It may be surprising that we can
430 // use `'b` without relating `'a` and `'b`. The reason
431 // that this is ok is that what we produce is
432 // effectively a `&'b *x` expression (if you could
433 // annotate the region of a borrow), and regionck has
434 // code that adds edges from the region of a borrow
435 // (`'b`, here) into the regions in the borrowed
436 // expression (`*x`, here). (Search for "link".)
437 // - if in lub mode, things can get fairly complicated. The
438 // easiest thing is just to make a fresh
439 // region variable [4], which effectively means we defer
440 // the decision to region inference (and regionck, which will add
441 // some more edges to this variable). However, this can wind up
442 // creating a crippling number of variables in some cases --
443 // e.g., #32278 -- so we optimize one particular case [3].
444 // Let me try to explain with some examples:
445 // - The "running example" above represents the simple case,
446 // where we have one `&` reference at the outer level and
447 // ownership all the rest of the way down. In this case,
448 // we want `LUB('a, 'b)` as the resulting region.
449 // - However, if there are nested borrows, that region is
450 // too strong. Consider a coercion from `&'a &'x Rc<T>` to
451 // `&'b T`. In this case, `'a` is actually irrelevant.
452 // The pointer we want is `LUB('x, 'b`). If we choose `LUB('a,'b)`
453 // we get spurious errors (`ui/regions-lub-ref-ref-rc.rs`).
454 // (The errors actually show up in borrowck, typically, because
455 // this extra edge causes the region `'a` to be inferred to something
456 // too big, which then results in borrowck errors.)
457 // - We could track the innermost shared reference, but there is already
458 // code in regionck that has the job of creating links between
459 // the region of a borrow and the regions in the thing being
460 // borrowed (here, `'a` and `'x`), and it knows how to handle
461 // all the various cases. So instead we just make a region variable
462 // and let regionck figure it out.
463 let r = if !self.use_lub {
464 r_b // [2] above
465 } else if autoderefs == 1 {
466 r_a // [3] above
467 } else {
468 if r_borrow_var.is_none() {
469 // create var lazily, at most once
470 let r = self.infcx().next_region_var();
471 r_borrow_var = Some(r); // [4] above
472 }
473 r_borrow_var.unwrap()
474 };
475 let derefd_ty_a = Ty::new_ref(
476 self.interner(),
477 r,
478 referent_ty,
479 mutbl_b, // [1] above
480 );
481 match self.unify_raw(derefd_ty_a, b) {
482 Ok(ok) => {
483 found = Some(ok);
484 break;
485 }
486 Err(err) => {
487 if first_error.is_none() {
488 first_error = Some(err);
489 }
490 }
491 }
492 }
493
494 // Extract type or return an error. We return the first error
495 // we got, which should be from relating the "base" type
496 // (e.g., in example above, the failure from relating `Vec<T>`
497 // to the target type), since that should be the least
498 // confusing.
499 let Some(InferOk { value: ty, mut obligations }) = found else {
500 if let Some(first_error) = first_error {
501 debug!("coerce_borrowed_pointer: failed with err = {:?}", first_error);
502 return Err(first_error);
503 } else {
504 // This may happen in the new trait solver since autoderef requires
505 // the pointee to be structurally normalizable, or else it'll just bail.
506 // So when we have a type like `&<not well formed>`, then we get no
507 // autoderef steps (even though there should be at least one). That means
508 // we get no type mismatches, since the loop above just exits early.
509 return Err(TypeError::Mismatch);
510 }
511 };
512
513 if ty == a && mt_a.mutbl.is_not() && autoderef.step_count() == 1 {
514 // As a special case, if we would produce `&'a *x`, that's
515 // a total no-op. We end up with the type `&'a T` just as
516 // we started with. In that case, just skip it
517 // altogether. This is just an optimization.
518 //
519 // Note that for `&mut`, we DO want to reborrow --
520 // otherwise, this would be a move, which might be an
521 // error. For example `foo(self.x)` where `self` and
522 // `self.x` both have `&mut `type would be a move of
523 // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
524 // which is a borrow.
525 assert!(mutbl_b.is_not()); // can only coerce &T -> &U
526 return success(vec![], ty, obligations);
527 }
528
529 let InferOk { value: mut adjustments, obligations: o } =
530 autoderef.adjust_steps_as_infer_ok();
531 obligations.extend(o);
532
533 // Now apply the autoref.
534 let mutbl = AutoBorrowMutability::new(mutbl_b, self.allow_two_phase);
535 adjustments.push(Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)), target: ty });
536
537 debug!("coerce_borrowed_pointer: succeeded ty={:?} adjustments={:?}", ty, adjustments);
538
539 success(adjustments, ty, obligations)
540 }
541
542 /// Performs [unsized coercion] by emulating a fulfillment loop on a
543 /// `CoerceUnsized` goal until all `CoerceUnsized` and `Unsize` goals
544 /// are successfully selected.
545 ///
546 /// [unsized coercion](https://doc.rust-lang.org/reference/type-coercions.html#unsized-coercions)
547 #[instrument(skip(self), level = "debug")]
548 fn coerce_unsized(&mut self, source: Ty<'db>, target: Ty<'db>) -> CoerceResult<'db> {
549 debug!(?source, ?target);
550 debug_assert!(self.infcx().shallow_resolve(source) == source);
551 debug_assert!(self.infcx().shallow_resolve(target) == target);
552
553 // We don't apply any coercions incase either the source or target
554 // aren't sufficiently well known but tend to instead just equate
555 // them both.
556 if source.is_infer() {
557 debug!("coerce_unsized: source is a TyVar, bailing out");
558 return Err(TypeError::Mismatch);
559 }
560 if target.is_infer() {
561 debug!("coerce_unsized: target is a TyVar, bailing out");
562 return Err(TypeError::Mismatch);
563 }
564
565 // This is an optimization because coercion is one of the most common
566 // operations that we do in typeck, since it happens at every assignment
567 // and call arg (among other positions).
568 //
569 // These targets are known to never be RHS in `LHS: CoerceUnsized<RHS>`.
570 // That's because these are built-in types for which a core-provided impl
571 // doesn't exist, and for which a user-written impl is invalid.
572 //
573 // This is technically incomplete when users write impossible bounds like
574 // `where T: CoerceUnsized<usize>`, for example, but that trait is unstable
575 // and coercion is allowed to be incomplete. The only case where this matters
576 // is impossible bounds.
577 //
578 // Note that some of these types implement `LHS: Unsize<RHS>`, but they
579 // do not implement *`CoerceUnsized`* which is the root obligation of the
580 // check below.
581 match target.kind() {
582 TyKind::Bool
583 | TyKind::Char
584 | TyKind::Int(_)
585 | TyKind::Uint(_)
586 | TyKind::Float(_)
587 | TyKind::Infer(rustc_type_ir::IntVar(_) | rustc_type_ir::FloatVar(_))
588 | TyKind::Str
589 | TyKind::Array(_, _)
590 | TyKind::Slice(_)
591 | TyKind::FnDef(_, _)
592 | TyKind::FnPtr(_, _)
593 | TyKind::Dynamic(_, _)
594 | TyKind::Closure(_, _)
595 | TyKind::CoroutineClosure(_, _)
596 | TyKind::Coroutine(_, _)
597 | TyKind::CoroutineWitness(_, _)
598 | TyKind::Never
599 | TyKind::Tuple(_) => return Err(TypeError::Mismatch),
600 _ => {}
601 }
602 // Additionally, we ignore `&str -> &str` coercions, which happen very
603 // commonly since strings are one of the most used argument types in Rust,
604 // we do coercions when type checking call expressions.
605 if let TyKind::Ref(_, source_pointee, Mutability::Not) = source.kind()
606 && source_pointee.is_str()
607 && let TyKind::Ref(_, target_pointee, Mutability::Not) = target.kind()
608 && target_pointee.is_str()
609 {
610 return Err(TypeError::Mismatch);
611 }
612
613 let lang_items = self.interner().lang_items();
614 let traits = (lang_items.Unsize, lang_items.CoerceUnsized);
615 let (Some(unsize_did), Some(coerce_unsized_did)) = traits else {
616 debug!("missing Unsize or CoerceUnsized traits");
617 return Err(TypeError::Mismatch);
618 };
619
620 // Note, we want to avoid unnecessary unsizing. We don't want to coerce to
621 // a DST unless we have to. This currently comes out in the wash since
622 // we can't unify [T] with U. But to properly support DST, we need to allow
623 // that, at which point we will need extra checks on the target here.
624
625 // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
626 let reborrow = match (source.kind(), target.kind()) {
627 (TyKind::Ref(_, ty_a, mutbl_a), TyKind::Ref(_, _, mutbl_b)) => {
628 coerce_mutbls(mutbl_a, mutbl_b)?;
629
630 let r_borrow = self.infcx().next_region_var();
631
632 // We don't allow two-phase borrows here, at least for initial
633 // implementation. If it happens that this coercion is a function argument,
634 // the reborrow in coerce_borrowed_ptr will pick it up.
635 let mutbl = AutoBorrowMutability::new(mutbl_b, AllowTwoPhase::No);
636
637 Some((
638 Adjustment { kind: Adjust::Deref(None), target: ty_a },
639 Adjustment {
640 kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)),
641 target: Ty::new_ref(self.interner(), r_borrow, ty_a, mutbl_b),
642 },
643 ))
644 }
645 (TyKind::Ref(_, ty_a, mt_a), TyKind::RawPtr(_, mt_b)) => {
646 coerce_mutbls(mt_a, mt_b)?;
647
648 Some((
649 Adjustment { kind: Adjust::Deref(None), target: ty_a },
650 Adjustment {
651 kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
652 target: Ty::new_ptr(self.interner(), ty_a, mt_b),
653 },
654 ))
655 }
656 _ => None,
657 };
658 let coerce_source = reborrow.as_ref().map_or(source, |(_, r)| r.target);
659
660 // Setup either a subtyping or a LUB relationship between
661 // the `CoerceUnsized` target type and the expected type.
662 // We only have the latter, so we use an inference variable
663 // for the former and let type inference do the rest.
664 let coerce_target = self.infcx().next_ty_var();
665
666 let mut coercion = self.unify_and(
667 coerce_target,
668 target,
669 reborrow.into_iter().flat_map(|(deref, autoref)| [deref, autoref]),
670 Adjust::Pointer(PointerCast::Unsize),
671 )?;
672
673 // Create an obligation for `Source: CoerceUnsized<Target>`.
674 let cause = self.cause.clone();
675
676 // Use a FIFO queue for this custom fulfillment procedure.
677 //
678 // A Vec (or SmallVec) is not a natural choice for a queue. However,
679 // this code path is hot, and this queue usually has a max length of 1
680 // and almost never more than 3. By using a SmallVec we avoid an
681 // allocation, at the (very small) cost of (occasionally) having to
682 // shift subsequent elements down when removing the front element.
683 let mut queue: SmallVec<[PredicateObligation<'db>; 4]> = smallvec![Obligation::new(
684 self.interner(),
685 cause,
686 self.param_env(),
687 TraitRef::new(
688 self.interner(),
689 coerce_unsized_did.into(),
690 [coerce_source, coerce_target]
691 )
692 )];
693 // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
694 // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
695 // inference might unify those two inner type variables later.
696 let traits = [coerce_unsized_did, unsize_did];
697 while !queue.is_empty() {
698 let obligation = queue.remove(0);
699 let trait_pred = match obligation.predicate.kind().no_bound_vars() {
700 Some(PredicateKind::Clause(ClauseKind::Trait(trait_pred)))
701 if traits.contains(&trait_pred.def_id().0) =>
702 {
703 self.infcx().resolve_vars_if_possible(trait_pred)
704 }
705 // Eagerly process alias-relate obligations in new trait solver,
706 // since these can be emitted in the process of solving trait goals,
707 // but we need to constrain vars before processing goals mentioning
708 // them.
709 Some(PredicateKind::AliasRelate(..)) => {
710 let mut ocx = ObligationCtxt::new(self.infcx());
711 ocx.register_obligation(obligation);
712 if !ocx.try_evaluate_obligations().is_empty() {
713 return Err(TypeError::Mismatch);
714 }
715 coercion.obligations.extend(ocx.into_pending_obligations());
716 continue;
717 }
718 _ => {
719 coercion.obligations.push(obligation);
720 continue;
721 }
722 };
723 debug!("coerce_unsized resolve step: {:?}", trait_pred);
724 match self.infcx().select(&obligation.with(self.interner(), trait_pred)) {
725 // Uncertain or unimplemented.
726 Ok(None) => {
727 if trait_pred.def_id().0 == unsize_did {
728 let self_ty = trait_pred.self_ty();
729 let unsize_ty = trait_pred.trait_ref.args.inner()[1].expect_ty();
730 debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_pred);
731 match (self_ty.kind(), unsize_ty.kind()) {
732 (TyKind::Infer(rustc_type_ir::TyVar(v)), TyKind::Dynamic(..))
733 if self.delegate.type_var_is_sized(v) =>
734 {
735 debug!("coerce_unsized: have sized infer {:?}", v);
736 coercion.obligations.push(obligation);
737 // `$0: Unsize<dyn Trait>` where we know that `$0: Sized`, try going
738 // for unsizing.
739 }
740 _ => {
741 // Some other case for `$0: Unsize<Something>`. Note that we
742 // hit this case even if `Something` is a sized type, so just
743 // don't do the coercion.
744 debug!("coerce_unsized: ambiguous unsize");
745 return Err(TypeError::Mismatch);
746 }
747 }
748 } else {
749 debug!("coerce_unsized: early return - ambiguous");
750 if !coerce_source.references_non_lt_error()
751 && !coerce_target.references_non_lt_error()
752 {
753 // rustc always early-returns here, even when the types contains errors. However not bailing
754 // improves error recovery, and while we don't implement generic consts properly, it also helps
755 // correct code.
756 return Err(TypeError::Mismatch);
757 }
758 }
759 }
760 Err(SelectionError::Unimplemented) => {
761 debug!("coerce_unsized: early return - can't prove obligation");
762 return Err(TypeError::Mismatch);
763 }
764
765 Err(SelectionError::TraitDynIncompatible(_)) => {
766 // Dyn compatibility errors in coercion will *always* be due to the
767 // fact that the RHS of the coercion is a non-dyn compatible `dyn Trait`
768 // written in source somewhere (otherwise we will never have lowered
769 // the dyn trait from HIR to middle).
770 //
771 // There's no reason to emit yet another dyn compatibility error,
772 // especially since the span will differ slightly and thus not be
773 // deduplicated at all!
774 self.set_tainted_by_errors();
775 }
776 Err(_err) => {
777 // FIXME: Report an error:
778 // let guar = self.err_ctxt().report_selection_error(
779 // obligation.clone(),
780 // &obligation,
781 // &err,
782 // );
783 self.set_tainted_by_errors();
784 // Treat this like an obligation and follow through
785 // with the unsizing - the lack of a coercion should
786 // be silent, as it causes a type mismatch later.
787 }
788
789 Ok(Some(ImplSource::UserDefined(impl_source))) => {
790 queue.extend(impl_source.nested);
791 }
792 Ok(Some(impl_source)) => queue.extend(impl_source.nested_obligations()),
793 }
794 }
795
796 Ok(coercion)
797 }
798
799 fn coerce_from_safe_fn(
800 &mut self,
801 fn_ty_a: PolyFnSig<'db>,
802 b: Ty<'db>,
803 adjustment: Option<Adjust>,
804 ) -> CoerceResult<'db> {
805 debug_assert!(self.infcx().shallow_resolve(b) == b);
806
807 self.commit_if_ok(|this| {
808 if let TyKind::FnPtr(_, hdr_b) = b.kind()
809 && fn_ty_a.safety().is_safe()
810 && !hdr_b.safety.is_safe()
811 {
812 let unsafe_a = Ty::safe_to_unsafe_fn_ty(this.interner(), fn_ty_a);
813 this.unify_and(
814 unsafe_a,
815 b,
816 adjustment.map(|kind| Adjustment {
817 kind,
818 target: Ty::new_fn_ptr(this.interner(), fn_ty_a),
819 }),
820 Adjust::Pointer(PointerCast::UnsafeFnPointer),
821 )
822 } else {
823 let a = Ty::new_fn_ptr(this.interner(), fn_ty_a);
824 match adjustment {
825 Some(adjust) => this.unify_and(a, b, [], adjust),
826 None => this.unify(a, b),
827 }
828 }
829 })
830 }
831
832 fn coerce_from_fn_pointer(&mut self, fn_ty_a: PolyFnSig<'db>, b: Ty<'db>) -> CoerceResult<'db> {
833 debug!(?fn_ty_a, ?b, "coerce_from_fn_pointer");
834 debug_assert!(self.infcx().shallow_resolve(b) == b);
835
836 self.coerce_from_safe_fn(fn_ty_a, b, None)
837 }
838
839 fn coerce_from_fn_item(&mut self, a: Ty<'db>, b: Ty<'db>) -> CoerceResult<'db> {
840 debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
841 debug_assert!(self.infcx().shallow_resolve(a) == a);
842 debug_assert!(self.infcx().shallow_resolve(b) == b);
843
844 match b.kind() {
845 TyKind::FnPtr(_, b_hdr) => {
846 let a_sig = a.fn_sig(self.interner());
847 if let TyKind::FnDef(def_id, _) = a.kind() {
848 // Intrinsics are not coercible to function pointers
849 if let CallableDefId::FunctionId(def_id) = def_id.0 {
850 if FunctionSignature::is_intrinsic(self.db(), def_id) {
851 return Err(TypeError::IntrinsicCast);
852 }
853
854 let attrs = AttrFlags::query(self.db(), def_id.into());
855 if attrs.contains(AttrFlags::RUSTC_FORCE_INLINE) {
856 return Err(TypeError::ForceInlineCast);
857 }
858
859 if b_hdr.safety.is_safe() && attrs.contains(AttrFlags::HAS_TARGET_FEATURE) {
860 let fn_target_features =
861 TargetFeatures::from_fn_no_implications(self.db(), def_id);
862 // Allow the coercion if the current function has all the features that would be
863 // needed to call the coercee safely.
864 let (target_features, target_feature_is_safe) =
865 self.delegate.target_features();
866 if target_feature_is_safe == TargetFeatureIsSafeInTarget::No
867 && !target_features.enabled.is_superset(&fn_target_features.enabled)
868 {
869 return Err(TypeError::TargetFeatureCast(
870 CallableIdWrapper(def_id.into()).into(),
871 ));
872 }
873 }
874 }
875 }
876
877 self.coerce_from_safe_fn(
878 a_sig,
879 b,
880 Some(Adjust::Pointer(PointerCast::ReifyFnPointer)),
881 )
882 }
883 _ => self.unify(a, b),
884 }
885 }
886
887 /// Attempts to coerce from the type of a non-capturing closure
888 /// into a function pointer.
889 fn coerce_closure_to_fn(
890 &mut self,
891 a: Ty<'db>,
892 _closure_def_id_a: InternedClosureId,
893 args_a: GenericArgs<'db>,
894 b: Ty<'db>,
895 ) -> CoerceResult<'db> {
896 debug_assert!(self.infcx().shallow_resolve(a) == a);
897 debug_assert!(self.infcx().shallow_resolve(b) == b);
898
899 match b.kind() {
900 // FIXME: We need to have an `upvars_mentioned()` query:
901 // At this point we haven't done capture analysis, which means
902 // that the ClosureArgs just contains an inference variable instead
903 // of tuple of captured types.
904 //
905 // All we care here is if any variable is being captured and not the exact paths,
906 // so we check `upvars_mentioned` for root variables being captured.
907 TyKind::FnPtr(_, hdr) =>
908 // if self
909 // .db
910 // .upvars_mentioned(closure_def_id_a.expect_local())
911 // .is_none_or(|u| u.is_empty()) =>
912 {
913 // We coerce the closure, which has fn type
914 // `extern "rust-call" fn((arg0,arg1,...)) -> _`
915 // to
916 // `fn(arg0,arg1,...) -> _`
917 // or
918 // `unsafe fn(arg0,arg1,...) -> _`
919 let safety = hdr.safety;
920 let closure_sig = args_a.closure_sig_untupled().map_bound(|mut sig| {
921 sig.safety = hdr.safety;
922 sig
923 });
924 let pointer_ty = Ty::new_fn_ptr(self.interner(), closure_sig);
925 debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})", a, b, pointer_ty);
926 self.unify_and(
927 pointer_ty,
928 b,
929 [],
930 Adjust::Pointer(PointerCast::ClosureFnPointer(safety)),
931 )
932 }
933 _ => self.unify(a, b),
934 }
935 }
936
937 fn coerce_raw_ptr(&mut self, a: Ty<'db>, b: Ty<'db>, mutbl_b: Mutability) -> CoerceResult<'db> {
938 debug!("coerce_raw_ptr(a={:?}, b={:?})", a, b);
939 debug_assert!(self.infcx().shallow_resolve(a) == a);
940 debug_assert!(self.infcx().shallow_resolve(b) == b);
941
942 let (is_ref, mt_a) = match a.kind() {
943 TyKind::Ref(_, ty, mutbl) => (true, TypeAndMut::<DbInterner<'db>> { ty, mutbl }),
944 TyKind::RawPtr(ty, mutbl) => (false, TypeAndMut { ty, mutbl }),
945 _ => return self.unify(a, b),
946 };
947 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
948
949 // Check that the types which they point at are compatible.
950 let a_raw = Ty::new_ptr(self.interner(), mt_a.ty, mutbl_b);
951 // Although references and raw ptrs have the same
952 // representation, we still register an Adjust::DerefRef so that
953 // regionck knows that the region for `a` must be valid here.
954 if is_ref {
955 self.unify_and(
956 a_raw,
957 b,
958 [Adjustment { kind: Adjust::Deref(None), target: mt_a.ty }],
959 Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)),
960 )
961 } else if mt_a.mutbl != mutbl_b {
962 self.unify_and(a_raw, b, [], Adjust::Pointer(PointerCast::MutToConstPointer))
963 } else {
964 self.unify(a_raw, b)
965 }
966 }
967}
968
969struct InferenceCoercionDelegate<'a, 'b, 'db>(&'a mut InferenceContext<'b, 'db>);
970
971impl<'db> CoerceDelegate<'db> for InferenceCoercionDelegate<'_, '_, 'db> {
972 #[inline]
973 fn infcx(&self) -> &InferCtxt<'db> {
974 &self.0.table.infer_ctxt
975 }
976 #[inline]
977 fn param_env(&self) -> ParamEnv<'db> {
978 self.0.table.param_env
979 }
980
981 #[inline]
982 fn target_features(&self) -> (&TargetFeatures<'db>, TargetFeatureIsSafeInTarget) {
983 self.0.target_features()
984 }
985
986 #[inline]
987 fn set_diverging(&mut self, diverging_ty: Ty<'db>) {
988 self.0.table.set_diverging(diverging_ty);
989 }
990
991 #[inline]
992 fn set_tainted_by_errors(&mut self) {
993 self.0.set_tainted_by_errors();
994 }
995
996 #[inline]
997 fn type_var_is_sized(&mut self, var: TyVid) -> bool {
998 self.0.table.type_var_is_sized(var)
999 }
1000}
1001
1002impl<'db> InferenceContext<'_, 'db> {
1003 /// Attempt to coerce an expression to a type, and return the
1004 /// adjusted type of the expression, if successful.
1005 /// Adjustments are only recorded if the coercion succeeded.
1006 /// The expressions *must not* have any preexisting adjustments.
1007 pub(crate) fn coerce(
1008 &mut self,
1009 expr: ExprOrPatId,
1010 expr_ty: Ty<'db>,
1011 mut target: Ty<'db>,
1012 allow_two_phase: AllowTwoPhase,
1013 expr_is_read: ExprIsRead,
1014 ) -> RelateResult<'db, Ty<'db>> {
1015 let source = self.table.try_structurally_resolve_type(expr_ty);
1016 target = self.table.try_structurally_resolve_type(target);
1017 debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
1018
1019 let cause = ObligationCause::new();
1020 let coerce_never = match expr {
1021 ExprOrPatId::ExprId(idx) => {
1022 self.expr_guaranteed_to_constitute_read_for_never(idx, expr_is_read)
1023 }
1024 // `PatId` is passed for `PatKind::Path`.
1025 ExprOrPatId::PatId(_) => false,
1026 };
1027 let mut coerce = Coerce {
1028 delegate: InferenceCoercionDelegate(self),
1029 cause,
1030 allow_two_phase,
1031 coerce_never,
1032 use_lub: false,
1033 };
1034 let ok = coerce.commit_if_ok(|coerce| coerce.coerce(source, target))?;
1035
1036 let (adjustments, _) = self.table.register_infer_ok(ok);
1037 match expr {
1038 ExprOrPatId::ExprId(expr) => self.write_expr_adj(expr, adjustments.into_boxed_slice()),
1039 ExprOrPatId::PatId(pat) => self
1040 .write_pat_adj(pat, adjustments.into_iter().map(|adjust| adjust.target).collect()),
1041 }
1042 Ok(target)
1043 }
1044
1045 /// Given some expressions, their known unified type and another expression,
1046 /// tries to unify the types, potentially inserting coercions on any of the
1047 /// provided expressions and returns their LUB (aka "common supertype").
1048 ///
1049 /// This is really an internal helper. From outside the coercion
1050 /// module, you should instantiate a `CoerceMany` instance.
1051 fn try_find_coercion_lub(
1052 &mut self,
1053 exprs: &[ExprId],
1054 prev_ty: Ty<'db>,
1055 new: ExprId,
1056 new_ty: Ty<'db>,
1057 ) -> RelateResult<'db, Ty<'db>> {
1058 let prev_ty = self.table.try_structurally_resolve_type(prev_ty);
1059 let new_ty = self.table.try_structurally_resolve_type(new_ty);
1060 debug!(
1061 "coercion::try_find_coercion_lub({:?}, {:?}, exprs={:?} exprs)",
1062 prev_ty,
1063 new_ty,
1064 exprs.len()
1065 );
1066
1067 // The following check fixes #88097, where the compiler erroneously
1068 // attempted to coerce a closure type to itself via a function pointer.
1069 if prev_ty == new_ty {
1070 return Ok(prev_ty);
1071 }
1072
1073 let is_force_inline = |ty: Ty<'db>| {
1074 if let TyKind::FnDef(CallableIdWrapper(CallableDefId::FunctionId(did)), _) = ty.kind() {
1075 AttrFlags::query(self.db, did.into()).contains(AttrFlags::RUSTC_FORCE_INLINE)
1076 } else {
1077 false
1078 }
1079 };
1080 if is_force_inline(prev_ty) || is_force_inline(new_ty) {
1081 return Err(TypeError::ForceInlineCast);
1082 }
1083
1084 // Special-case that coercion alone cannot handle:
1085 // Function items or non-capturing closures of differing IDs or GenericArgs.
1086 let (a_sig, b_sig) = {
1087 let is_capturing_closure = |_ty: Ty<'db>| {
1088 // FIXME:
1089 // if let TyKind::Closure(closure_def_id, _args) = ty.kind() {
1090 // self.db.upvars_mentioned(closure_def_id.expect_local()).is_some()
1091 // } else {
1092 // false
1093 // }
1094 false
1095 };
1096 if is_capturing_closure(prev_ty) || is_capturing_closure(new_ty) {
1097 (None, None)
1098 } else {
1099 match (prev_ty.kind(), new_ty.kind()) {
1100 (TyKind::FnDef(..), TyKind::FnDef(..)) => {
1101 // Don't reify if the function types have a LUB, i.e., they
1102 // are the same function and their parameters have a LUB.
1103 match self.table.commit_if_ok(|table| {
1104 // We need to eagerly handle nested obligations due to lazy norm.
1105 let mut ocx = ObligationCtxt::new(&table.infer_ctxt);
1106 let value =
1107 ocx.lub(&ObligationCause::new(), table.param_env, prev_ty, new_ty)?;
1108 if ocx.try_evaluate_obligations().is_empty() {
1109 Ok(InferOk { value, obligations: ocx.into_pending_obligations() })
1110 } else {
1111 Err(TypeError::Mismatch)
1112 }
1113 }) {
1114 // We have a LUB of prev_ty and new_ty, just return it.
1115 Ok(ok) => return Ok(self.table.register_infer_ok(ok)),
1116 Err(_) => (
1117 Some(prev_ty.fn_sig(self.table.interner())),
1118 Some(new_ty.fn_sig(self.table.interner())),
1119 ),
1120 }
1121 }
1122 (TyKind::Closure(_, args), TyKind::FnDef(..)) => {
1123 let b_sig = new_ty.fn_sig(self.table.interner());
1124 let a_sig = args.closure_sig_untupled().map_bound(|mut sig| {
1125 sig.safety = b_sig.safety();
1126 sig
1127 });
1128 (Some(a_sig), Some(b_sig))
1129 }
1130 (TyKind::FnDef(..), TyKind::Closure(_, args)) => {
1131 let a_sig = prev_ty.fn_sig(self.table.interner());
1132 let b_sig = args.closure_sig_untupled().map_bound(|mut sig| {
1133 sig.safety = a_sig.safety();
1134 sig
1135 });
1136 (Some(a_sig), Some(b_sig))
1137 }
1138 (TyKind::Closure(_, args_a), TyKind::Closure(_, args_b)) => {
1139 (Some(args_a.closure_sig_untupled()), Some(args_b.closure_sig_untupled()))
1140 }
1141 _ => (None, None),
1142 }
1143 }
1144 };
1145 if let (Some(a_sig), Some(b_sig)) = (a_sig, b_sig) {
1146 // The signature must match.
1147 let sig = self
1148 .table
1149 .infer_ctxt
1150 .at(&ObligationCause::new(), self.table.param_env)
1151 .lub(a_sig, b_sig)
1152 .map(|ok| self.table.register_infer_ok(ok))?;
1153
1154 // Reify both sides and return the reified fn pointer type.
1155 let fn_ptr = Ty::new_fn_ptr(self.table.interner(), sig);
1156 let prev_adjustment = match prev_ty.kind() {
1157 TyKind::Closure(..) => {
1158 Adjust::Pointer(PointerCast::ClosureFnPointer(a_sig.safety()))
1159 }
1160 TyKind::FnDef(..) => Adjust::Pointer(PointerCast::ReifyFnPointer),
1161 _ => panic!("should not try to coerce a {prev_ty:?} to a fn pointer"),
1162 };
1163 let next_adjustment = match new_ty.kind() {
1164 TyKind::Closure(..) => {
1165 Adjust::Pointer(PointerCast::ClosureFnPointer(b_sig.safety()))
1166 }
1167 TyKind::FnDef(..) => Adjust::Pointer(PointerCast::ReifyFnPointer),
1168 _ => panic!("should not try to coerce a {new_ty:?} to a fn pointer"),
1169 };
1170 for &expr in exprs {
1171 self.write_expr_adj(
1172 expr,
1173 Box::new([Adjustment { kind: prev_adjustment.clone(), target: fn_ptr }]),
1174 );
1175 }
1176 self.write_expr_adj(
1177 new,
1178 Box::new([Adjustment { kind: next_adjustment, target: fn_ptr }]),
1179 );
1180 return Ok(fn_ptr);
1181 }
1182
1183 // Configure a Coerce instance to compute the LUB.
1184 // We don't allow two-phase borrows on any autorefs this creates since we
1185 // probably aren't processing function arguments here and even if we were,
1186 // they're going to get autorefed again anyway and we can apply 2-phase borrows
1187 // at that time.
1188 //
1189 // NOTE: we set `coerce_never` to `true` here because coercion LUBs only
1190 // operate on values and not places, so a never coercion is valid.
1191 let mut coerce = Coerce {
1192 delegate: InferenceCoercionDelegate(self),
1193 cause: ObligationCause::new(),
1194 allow_two_phase: AllowTwoPhase::No,
1195 coerce_never: true,
1196 use_lub: true,
1197 };
1198
1199 // First try to coerce the new expression to the type of the previous ones,
1200 // but only if the new expression has no coercion already applied to it.
1201 let mut first_error = None;
1202 if !coerce.delegate.0.result.expr_adjustments.contains_key(&new) {
1203 let result = coerce.commit_if_ok(|coerce| coerce.coerce(new_ty, prev_ty));
1204 match result {
1205 Ok(ok) => {
1206 let (adjustments, target) = self.table.register_infer_ok(ok);
1207 self.write_expr_adj(new, adjustments.into_boxed_slice());
1208 debug!(
1209 "coercion::try_find_coercion_lub: was able to coerce from new type {:?} to previous type {:?} ({:?})",
1210 new_ty, prev_ty, target
1211 );
1212 return Ok(target);
1213 }
1214 Err(e) => first_error = Some(e),
1215 }
1216 }
1217
1218 match coerce.commit_if_ok(|coerce| coerce.coerce(prev_ty, new_ty)) {
1219 Err(_) => {
1220 // Avoid giving strange errors on failed attempts.
1221 if let Some(e) = first_error {
1222 Err(e)
1223 } else {
1224 Err(self
1225 .table
1226 .commit_if_ok(|table| {
1227 table
1228 .infer_ctxt
1229 .at(&ObligationCause::new(), table.param_env)
1230 .lub(prev_ty, new_ty)
1231 })
1232 .unwrap_err())
1233 }
1234 }
1235 Ok(ok) => {
1236 let (adjustments, target) = self.table.register_infer_ok(ok);
1237 for &expr in exprs {
1238 self.write_expr_adj(expr, adjustments.as_slice().into());
1239 }
1240 debug!(
1241 "coercion::try_find_coercion_lub: was able to coerce previous type {:?} to new type {:?} ({:?})",
1242 prev_ty, new_ty, target
1243 );
1244 Ok(target)
1245 }
1246 }
1247 }
1248}
1249
1250/// CoerceMany encapsulates the pattern you should use when you have
1251/// many expressions that are all getting coerced to a common
1252/// type. This arises, for example, when you have a match (the result
1253/// of each arm is coerced to a common type). It also arises in less
1254/// obvious places, such as when you have many `break foo` expressions
1255/// that target the same loop, or the various `return` expressions in
1256/// a function.
1257///
1258/// The basic protocol is as follows:
1259///
1260/// - Instantiate the `CoerceMany` with an initial `expected_ty`.
1261/// This will also serve as the "starting LUB". The expectation is
1262/// that this type is something which all of the expressions *must*
1263/// be coercible to. Use a fresh type variable if needed.
1264/// - For each expression whose result is to be coerced, invoke `coerce()` with.
1265/// - In some cases we wish to coerce "non-expressions" whose types are implicitly
1266/// unit. This happens for example if you have a `break` with no expression,
1267/// or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
1268/// - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
1269/// from you so that you don't have to worry your pretty head about it.
1270/// But if an error is reported, the final type will be `err`.
1271/// - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
1272/// previously coerced expressions.
1273/// - When all done, invoke `complete()`. This will return the LUB of
1274/// all your expressions.
1275/// - WARNING: I don't believe this final type is guaranteed to be
1276/// related to your initial `expected_ty` in any particular way,
1277/// although it will typically be a subtype, so you should check it.
1278/// - Invoking `complete()` may cause us to go and adjust the "adjustments" on
1279/// previously coerced expressions.
1280///
1281/// Example:
1282///
1283/// ```ignore (illustrative)
1284/// let mut coerce = CoerceMany::new(expected_ty);
1285/// for expr in exprs {
1286/// let expr_ty = fcx.check_expr_with_expectation(expr, expected);
1287/// coerce.coerce(fcx, &cause, expr, expr_ty);
1288/// }
1289/// let final_ty = coerce.complete(fcx);
1290/// ```
1291#[derive(Debug, Clone)]
1292pub(crate) struct CoerceMany<'db, 'exprs> {
1293 expected_ty: Ty<'db>,
1294 final_ty: Option<Ty<'db>>,
1295 expressions: Expressions<'exprs>,
1296 pushed: usize,
1297}
1298
1299/// The type of a `CoerceMany` that is storing up the expressions into
1300/// a buffer. We use this for things like `break`.
1301pub(crate) type DynamicCoerceMany<'db> = CoerceMany<'db, 'db>;
1302
1303#[derive(Debug, Clone)]
1304enum Expressions<'exprs> {
1305 Dynamic(SmallVec<[ExprId; 4]>),
1306 UpFront(&'exprs [ExprId]),
1307}
1308
1309impl<'db, 'exprs> CoerceMany<'db, 'exprs> {
1310 /// The usual case; collect the set of expressions dynamically.
1311 /// If the full set of coercion sites is known before hand,
1312 /// consider `with_coercion_sites()` instead to avoid allocation.
1313 pub(crate) fn new(expected_ty: Ty<'db>) -> Self {
1314 Self::make(expected_ty, Expressions::Dynamic(SmallVec::new()))
1315 }
1316
1317 /// As an optimization, you can create a `CoerceMany` with a
1318 /// preexisting slice of expressions. In this case, you are
1319 /// expected to pass each element in the slice to `coerce(...)` in
1320 /// order. This is used with arrays in particular to avoid
1321 /// needlessly cloning the slice.
1322 pub(crate) fn with_coercion_sites(
1323 expected_ty: Ty<'db>,
1324 coercion_sites: &'exprs [ExprId],
1325 ) -> Self {
1326 Self::make(expected_ty, Expressions::UpFront(coercion_sites))
1327 }
1328
1329 fn make(expected_ty: Ty<'db>, expressions: Expressions<'exprs>) -> Self {
1330 CoerceMany { expected_ty, final_ty: None, expressions, pushed: 0 }
1331 }
1332
1333 /// Returns the "expected type" with which this coercion was
1334 /// constructed. This represents the "downward propagated" type
1335 /// that was given to us at the start of typing whatever construct
1336 /// we are typing (e.g., the match expression).
1337 ///
1338 /// Typically, this is used as the expected type when
1339 /// type-checking each of the alternative expressions whose types
1340 /// we are trying to merge.
1341 pub(crate) fn expected_ty(&self) -> Ty<'db> {
1342 self.expected_ty
1343 }
1344
1345 /// Returns the current "merged type", representing our best-guess
1346 /// at the LUB of the expressions we've seen so far (if any). This
1347 /// isn't *final* until you call `self.complete()`, which will return
1348 /// the merged type.
1349 pub(crate) fn merged_ty(&self) -> Ty<'db> {
1350 self.final_ty.unwrap_or(self.expected_ty)
1351 }
1352
1353 /// Indicates that the value generated by `expression`, which is
1354 /// of type `expression_ty`, is one of the possibilities that we
1355 /// could coerce from. This will record `expression`, and later
1356 /// calls to `coerce` may come back and add adjustments and things
1357 /// if necessary.
1358 pub(crate) fn coerce(
1359 &mut self,
1360 icx: &mut InferenceContext<'_, 'db>,
1361 cause: &ObligationCause,
1362 expression: ExprId,
1363 expression_ty: Ty<'db>,
1364 expr_is_read: ExprIsRead,
1365 ) {
1366 self.coerce_inner(icx, cause, expression, expression_ty, false, false, expr_is_read)
1367 }
1368
1369 /// Indicates that one of the inputs is a "forced unit". This
1370 /// occurs in a case like `if foo { ... };`, where the missing else
1371 /// generates a "forced unit". Another example is a `loop { break;
1372 /// }`, where the `break` has no argument expression. We treat
1373 /// these cases slightly differently for error-reporting
1374 /// purposes. Note that these tend to correspond to cases where
1375 /// the `()` expression is implicit in the source, and hence we do
1376 /// not take an expression argument.
1377 ///
1378 /// The `augment_error` gives you a chance to extend the error
1379 /// message, in case any results (e.g., we use this to suggest
1380 /// removing a `;`).
1381 pub(crate) fn coerce_forced_unit(
1382 &mut self,
1383 icx: &mut InferenceContext<'_, 'db>,
1384 expr: ExprId,
1385 cause: &ObligationCause,
1386 label_unit_as_expected: bool,
1387 expr_is_read: ExprIsRead,
1388 ) {
1389 self.coerce_inner(
1390 icx,
1391 cause,
1392 expr,
1393 icx.types.unit,
1394 true,
1395 label_unit_as_expected,
1396 expr_is_read,
1397 )
1398 }
1399
1400 /// The inner coercion "engine". If `expression` is `None`, this
1401 /// is a forced-unit case, and hence `expression_ty` must be
1402 /// `Nil`.
1403 pub(crate) fn coerce_inner(
1404 &mut self,
1405 icx: &mut InferenceContext<'_, 'db>,
1406 cause: &ObligationCause,
1407 expression: ExprId,
1408 mut expression_ty: Ty<'db>,
1409 force_unit: bool,
1410 label_expression_as_expected: bool,
1411 expr_is_read: ExprIsRead,
1412 ) {
1413 // Incorporate whatever type inference information we have
1414 // until now; in principle we might also want to process
1415 // pending obligations, but doing so should only improve
1416 // compatibility (hopefully that is true) by helping us
1417 // uncover never types better.
1418 if expression_ty.is_ty_var() {
1419 expression_ty = icx.shallow_resolve(expression_ty);
1420 }
1421
1422 let (expected, found) = if label_expression_as_expected {
1423 // In the case where this is a "forced unit", like
1424 // `break`, we want to call the `()` "expected"
1425 // since it is implied by the syntax.
1426 // (Note: not all force-units work this way.)"
1427 (expression_ty, self.merged_ty())
1428 } else {
1429 // Otherwise, the "expected" type for error
1430 // reporting is the current unification type,
1431 // which is basically the LUB of the expressions
1432 // we've seen so far (combined with the expected
1433 // type)
1434 (self.merged_ty(), expression_ty)
1435 };
1436
1437 // Handle the actual type unification etc.
1438 let result = if !force_unit {
1439 if self.pushed == 0 {
1440 // Special-case the first expression we are coercing.
1441 // To be honest, I'm not entirely sure why we do this.
1442 // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
1443 icx.coerce(
1444 expression.into(),
1445 expression_ty,
1446 self.expected_ty,
1447 AllowTwoPhase::No,
1448 expr_is_read,
1449 )
1450 } else {
1451 match self.expressions {
1452 Expressions::Dynamic(ref exprs) => icx.try_find_coercion_lub(
1453 exprs,
1454 self.merged_ty(),
1455 expression,
1456 expression_ty,
1457 ),
1458 Expressions::UpFront(coercion_sites) => icx.try_find_coercion_lub(
1459 &coercion_sites[0..self.pushed],
1460 self.merged_ty(),
1461 expression,
1462 expression_ty,
1463 ),
1464 }
1465 }
1466 } else {
1467 // this is a hack for cases where we default to `()` because
1468 // the expression etc has been omitted from the source. An
1469 // example is an `if let` without an else:
1470 //
1471 // if let Some(x) = ... { }
1472 //
1473 // we wind up with a second match arm that is like `_ =>
1474 // ()`. That is the case we are considering here. We take
1475 // a different path to get the right "expected, found"
1476 // message and so forth (and because we know that
1477 // `expression_ty` will be unit).
1478 //
1479 // Another example is `break` with no argument expression.
1480 assert!(expression_ty.is_unit(), "if let hack without unit type");
1481 icx.table.infer_ctxt.at(cause, icx.table.param_env).eq(expected, found).map(
1482 |infer_ok| {
1483 icx.table.register_infer_ok(infer_ok);
1484 expression_ty
1485 },
1486 )
1487 };
1488
1489 debug!(?result);
1490 match result {
1491 Ok(v) => {
1492 self.final_ty = Some(v);
1493 match self.expressions {
1494 Expressions::Dynamic(ref mut buffer) => buffer.push(expression),
1495 Expressions::UpFront(coercion_sites) => {
1496 // if the user gave us an array to validate, check that we got
1497 // the next expression in the list, as expected
1498 assert_eq!(coercion_sites[self.pushed], expression);
1499 }
1500 }
1501 }
1502 Err(_coercion_error) => {
1503 // Mark that we've failed to coerce the types here to suppress
1504 // any superfluous errors we might encounter while trying to
1505 // emit or provide suggestions on how to fix the initial error.
1506 icx.set_tainted_by_errors();
1507
1508 self.final_ty = Some(icx.types.error);
1509
1510 icx.result.type_mismatches.get_or_insert_default().insert(
1511 expression.into(),
1512 if label_expression_as_expected {
1513 TypeMismatch { expected: found, actual: expected }
1514 } else {
1515 TypeMismatch { expected, actual: found }
1516 },
1517 );
1518 }
1519 }
1520
1521 self.pushed += 1;
1522 }
1523
1524 pub(crate) fn complete(self, icx: &mut InferenceContext<'_, 'db>) -> Ty<'db> {
1525 if let Some(final_ty) = self.final_ty {
1526 final_ty
1527 } else {
1528 // If we only had inputs that were of type `!` (or no
1529 // inputs at all), then the final type is `!`.
1530 assert_eq!(self.pushed, 0);
1531 icx.types.never
1532 }
1533 }
1534}
1535
1536pub fn could_coerce<'db>(
1537 db: &'db dyn HirDatabase,
1538 env: ParamEnvAndCrate<'db>,
1539 tys: &Canonical<'db, (Ty<'db>, Ty<'db>)>,
1540) -> bool {
1541 coerce(db, env, tys).is_ok()
1542}
1543
1544struct HirCoercionDelegate<'a, 'db> {
1545 infcx: &'a InferCtxt<'db>,
1546 param_env: ParamEnv<'db>,
1547 target_features: &'a TargetFeatures<'db>,
1548}
1549
1550impl<'db> CoerceDelegate<'db> for HirCoercionDelegate<'_, 'db> {
1551 #[inline]
1552 fn infcx(&self) -> &InferCtxt<'db> {
1553 self.infcx
1554 }
1555 #[inline]
1556 fn param_env(&self) -> ParamEnv<'db> {
1557 self.param_env
1558 }
1559 fn target_features(&self) -> (&TargetFeatures<'db>, TargetFeatureIsSafeInTarget) {
1560 (self.target_features, TargetFeatureIsSafeInTarget::No)
1561 }
1562 fn set_diverging(&mut self, _diverging_ty: Ty<'db>) {}
1563 fn set_tainted_by_errors(&mut self) {}
1564 fn type_var_is_sized(&mut self, _var: TyVid) -> bool {
1565 false
1566 }
1567}
1568
1569fn coerce<'db>(
1570 db: &'db dyn HirDatabase,
1571 env: ParamEnvAndCrate<'db>,
1572 tys: &Canonical<'db, (Ty<'db>, Ty<'db>)>,
1573) -> Result<(Vec<Adjustment<'db>>, Ty<'db>), TypeError<DbInterner<'db>>> {
1574 let interner = DbInterner::new_with(db, env.krate);
1575 let infcx = interner.infer_ctxt().build(TypingMode::PostAnalysis);
1576 let ((ty1_with_vars, ty2_with_vars), vars) = infcx.instantiate_canonical(tys);
1577
1578 let cause = ObligationCause::new();
1579 // FIXME: Target features.
1580 let target_features = TargetFeatures::default();
1581 let mut coerce = Coerce {
1582 delegate: HirCoercionDelegate {
1583 infcx: &infcx,
1584 param_env: env.param_env,
1585 target_features: &target_features,
1586 },
1587 cause,
1588 allow_two_phase: AllowTwoPhase::No,
1589 coerce_never: true,
1590 use_lub: false,
1591 };
1592 let infer_ok = coerce.coerce(ty1_with_vars, ty2_with_vars)?;
1593 let mut ocx = ObligationCtxt::new(&infcx);
1594 let (adjustments, ty) = ocx.register_infer_ok_obligations(infer_ok);
1595 _ = ocx.try_evaluate_obligations();
1596 let (adjustments, ty) = infcx.resolve_vars_if_possible((adjustments, ty));
1597
1598 // default any type vars that weren't unified back to their original bound vars
1599 // (kind of hacky)
1600
1601 struct Resolver<'db> {
1602 interner: DbInterner<'db>,
1603 debruijn: DebruijnIndex,
1604 var_values: GenericArgs<'db>,
1605 }
1606
1607 impl<'db> TypeFolder<DbInterner<'db>> for Resolver<'db> {
1608 fn cx(&self) -> DbInterner<'db> {
1609 self.interner
1610 }
1611
1612 fn fold_binder<T>(&mut self, t: Binder<'db, T>) -> Binder<'db, T>
1613 where
1614 T: TypeFoldable<DbInterner<'db>>,
1615 {
1616 self.debruijn.shift_in(1);
1617 let result = t.super_fold_with(self);
1618 self.debruijn.shift_out(1);
1619 result
1620 }
1621
1622 fn fold_ty(&mut self, t: Ty<'db>) -> Ty<'db> {
1623 if !t.has_infer() {
1624 return t;
1625 }
1626
1627 if let TyKind::Infer(infer) = t.kind() {
1628 let var = self.var_values.iter().position(|arg| {
1629 arg.as_type().is_some_and(|ty| match ty.kind() {
1630 TyKind::Infer(it) => infer == it,
1631 _ => false,
1632 })
1633 });
1634 var.map_or_else(
1635 || Ty::new_error(self.interner, ErrorGuaranteed),
1636 |i| {
1637 Ty::new_bound(
1638 self.interner,
1639 self.debruijn,
1640 BoundTy { kind: BoundTyKind::Anon, var: BoundVar::from_usize(i) },
1641 )
1642 },
1643 )
1644 } else {
1645 t.super_fold_with(self)
1646 }
1647 }
1648
1649 fn fold_const(&mut self, c: Const<'db>) -> Const<'db> {
1650 if !c.has_infer() {
1651 return c;
1652 }
1653
1654 if let ConstKind::Infer(infer) = c.kind() {
1655 let var = self.var_values.iter().position(|arg| {
1656 arg.as_const().is_some_and(|ty| match ty.kind() {
1657 ConstKind::Infer(it) => infer == it,
1658 _ => false,
1659 })
1660 });
1661 var.map_or_else(
1662 || Const::new_error(self.interner, ErrorGuaranteed),
1663 |i| {
1664 Const::new_bound(
1665 self.interner,
1666 self.debruijn,
1667 BoundConst { var: BoundVar::from_usize(i) },
1668 )
1669 },
1670 )
1671 } else {
1672 c.super_fold_with(self)
1673 }
1674 }
1675
1676 fn fold_region(&mut self, r: Region<'db>) -> Region<'db> {
1677 if let RegionKind::ReVar(infer) = r.kind() {
1678 let var = self.var_values.iter().position(|arg| {
1679 arg.as_region().is_some_and(|ty| match ty.kind() {
1680 RegionKind::ReVar(it) => infer == it,
1681 _ => false,
1682 })
1683 });
1684 var.map_or_else(
1685 || Region::error(self.interner),
1686 |i| {
1687 Region::new_bound(
1688 self.interner,
1689 self.debruijn,
1690 BoundRegion {
1691 kind: BoundRegionKind::Anon,
1692 var: BoundVar::from_usize(i),
1693 },
1694 )
1695 },
1696 )
1697 } else {
1698 r
1699 }
1700 }
1701 }
1702
1703 // FIXME: We don't fallback correctly since this is done on `InferenceContext` and we only have `InferCtxt`.
1704 let (adjustments, ty) = (adjustments, ty).fold_with(&mut Resolver {
1705 interner,
1706 debruijn: DebruijnIndex::ZERO,
1707 var_values: vars.var_values,
1708 });
1709 Ok((adjustments, ty))
1710}