]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_hir_typeck/src/coercion.rs
New upstream version 1.70.0+dfsg1
[rustc.git] / compiler / rustc_hir_typeck / src / coercion.rs
CommitLineData
1a4d82fc
JJ
1//! # Type Coercion
2//!
3//! Under certain circumstances we will coerce from one type to another,
9fa01778 4//! for example by auto-borrowing. This occurs in situations where the
1a4d82fc
JJ
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*
9fa01778 12//! even if the argument provided was already a reference. This is
f035d41b
XL
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
9fa01778 15//! of mut things (when the expected is &mut T and you have &mut T). See
9c376795 16//! the various `tests/ui/coerce/*.rs` tests for
1a4d82fc
JJ
17//! examples of where this is useful.
18//!
19//! ## Subtle note
20//!
5e7ed085 21//! When inferring the generic arguments of functions, the argument
f035d41b 22//! order is relevant, which can lead to the following edge case:
1a4d82fc 23//!
04454e1e 24//! ```ignore (illustrative)
f035d41b
XL
25//! fn foo<T>(a: T, b: T) {
26//! // ...
27//! }
1a4d82fc 28//!
f035d41b
XL
29//! foo(&7i32, &mut 7i32);
30//! // This compiles, as we first infer `T` to be `&i32`,
31//! // and then coerce `&mut 7i32` to `&7i32`.
1a4d82fc 32//!
f035d41b
XL
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//! ```
1a4d82fc 37
2b03887a 38use crate::FnCtxt;
5e7ed085 39use rustc_errors::{
f2b60f7d 40 struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, MultiSpan,
5e7ed085 41};
dfeec247 42use rustc_hir as hir;
29967ef6 43use rustc_hir::def_id::DefId;
f2b60f7d
FG
44use rustc_hir::intravisit::{self, Visitor};
45use rustc_hir::Expr;
2b03887a 46use rustc_hir_analysis::astconv::AstConv;
74b04a01 47use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
353b0b11
FG
48use rustc_infer::infer::{Coercion, DefineOpaqueTypes, InferOk, InferResult};
49use rustc_infer::traits::{Obligation, PredicateObligation};
6a06907d 50use rustc_middle::lint::in_external_macro;
ba9703b0
XL
51use rustc_middle::ty::adjustment::{
52 Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, PointerCast,
53};
54use rustc_middle::ty::error::TypeError;
ba9703b0
XL
55use rustc_middle::ty::relate::RelateResult;
56use rustc_middle::ty::subst::SubstsRef;
9ffffee4 57use rustc_middle::ty::visit::TypeVisitableExt;
487cf647 58use rustc_middle::ty::{self, Ty, TypeAndMut};
ba9703b0 59use rustc_session::parse::feature_err;
dfeec247 60use rustc_span::symbol::sym;
c295e0f8 61use rustc_span::{self, BytePos, DesugaringKind, Span};
dfeec247 62use rustc_target::spec::abi::Abi;
923072b8 63use rustc_trait_selection::infer::InferCtxtExt as _;
2b03887a 64use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt as _;
487cf647
FG
65use rustc_trait_selection::traits::{
66 self, NormalizeExt, ObligationCause, ObligationCauseCode, ObligationCtxt,
67};
ba9703b0 68
a1dfa0c6
XL
69use smallvec::{smallvec, SmallVec};
70use std::ops::Deref;
60c5eb7d 71
dc9dc135
XL
72struct Coerce<'a, 'tcx> {
73 fcx: &'a FnCtxt<'a, 'tcx>,
476ff2be 74 cause: ObligationCause<'tcx>,
54a0048b 75 use_lub: bool,
83c7162d
XL
76 /// Determines whether or not allow_two_phase_borrow is set on any
77 /// autoref adjustments we create while coercing. We don't want to
78 /// allow deref coercions to create two-phase borrows, at least initially,
79 /// but we do need two-phase borrows for function argument reborrows.
80 /// See #47489 and #48598
81 /// See docs on the "AllowTwoPhase" type for a more detailed discussion
82 allow_two_phase: AllowTwoPhase,
85aaf69f
SL
83}
84
dc9dc135
XL
85impl<'a, 'tcx> Deref for Coerce<'a, 'tcx> {
86 type Target = FnCtxt<'a, 'tcx>;
a7813a04
XL
87 fn deref(&self) -> &Self::Target {
88 &self.fcx
89 }
90}
91
7cac9316 92type CoerceResult<'tcx> = InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>;
54a0048b 93
f2b60f7d
FG
94struct CollectRetsVisitor<'tcx> {
95 ret_exprs: Vec<&'tcx hir::Expr<'tcx>>,
96}
97
98impl<'tcx> Visitor<'tcx> for CollectRetsVisitor<'tcx> {
99 fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
100 if let hir::ExprKind::Ret(_) = expr.kind {
101 self.ret_exprs.push(expr);
102 }
103 intravisit::walk_expr(self, expr);
104 }
105}
106
f035d41b
XL
107/// Coercing a mutable reference to an immutable works, while
108/// coercing `&T` to `&mut T` should be forbidden.
dfeec247
XL
109fn coerce_mutbls<'tcx>(
110 from_mutbl: hir::Mutability,
111 to_mutbl: hir::Mutability,
112) -> RelateResult<'tcx, ()> {
487cf647 113 if from_mutbl >= to_mutbl { Ok(()) } else { Err(TypeError::Mutability) }
54a0048b 114}
1a4d82fc 115
f9f354fc 116/// Do not require any adjustments, i.e. coerce `x -> x`.
dfeec247
XL
117fn identity(_: Ty<'_>) -> Vec<Adjustment<'_>> {
118 vec![]
119}
7cac9316 120
9c376795 121fn simple<'tcx>(kind: Adjust<'tcx>) -> impl FnOnce(Ty<'tcx>) -> Vec<Adjustment<'_>> {
7cac9316 122 move |target| vec![Adjustment { kind, target }]
8bb4bdeb
XL
123}
124
f9f354fc 125/// This always returns `Ok(...)`.
dfeec247
XL
126fn success<'tcx>(
127 adj: Vec<Adjustment<'tcx>>,
128 target: Ty<'tcx>,
129 obligations: traits::PredicateObligations<'tcx>,
130) -> CoerceResult<'tcx> {
131 Ok(InferOk { value: (adj, target), obligations })
8bb4bdeb
XL
132}
133
dc9dc135
XL
134impl<'f, 'tcx> Coerce<'f, 'tcx> {
135 fn new(
136 fcx: &'f FnCtxt<'f, 'tcx>,
137 cause: ObligationCause<'tcx>,
138 allow_two_phase: AllowTwoPhase,
139 ) -> Self {
dfeec247 140 Coerce { fcx, cause, allow_two_phase, use_lub: false }
54a0048b
SL
141 }
142
8bb4bdeb 143 fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>> {
f9f354fc 144 debug!("unify(a: {:?}, b: {:?}, use_lub: {})", a, b, self.use_lub);
a7813a04 145 self.commit_if_ok(|_| {
353b0b11 146 let at = self.at(&self.cause, self.fcx.param_env);
54a0048b 147 if self.use_lub {
353b0b11 148 at.lub(DefineOpaqueTypes::Yes, b, a)
54a0048b 149 } else {
353b0b11 150 at.sup(DefineOpaqueTypes::Yes, b, a)
7cac9316 151 .map(|InferOk { value: (), obligations }| InferOk { value: a, obligations })
54a0048b
SL
152 }
153 })
85aaf69f
SL
154 }
155
8bb4bdeb 156 /// Unify two types (using sub or lub) and produce a specific coercion.
dfeec247
XL
157 fn unify_and<F>(&self, a: Ty<'tcx>, b: Ty<'tcx>, f: F) -> CoerceResult<'tcx>
158 where
159 F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
7cac9316 160 {
5099ac24 161 self.unify(a, b)
dfeec247 162 .and_then(|InferOk { value: ty, obligations }| success(f(ty), ty, obligations))
54a0048b
SL
163 }
164
c295e0f8 165 #[instrument(skip(self))]
7cac9316 166 fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
94222f64 167 // First, remove any resolved type variables (at the top level, at least):
a7813a04 168 let a = self.shallow_resolve(a);
94222f64 169 let b = self.shallow_resolve(b);
54a0048b 170 debug!("Coerce.tys({:?} => {:?})", a, b);
92a42be0
SL
171
172 // Just ignore error types.
9ffffee4 173 if let Err(guar) = (a, b).error_reported() {
9c376795
FG
174 // Best-effort try to unify these types -- we're already on the error path,
175 // so this will have the side-effect of making sure we have no ambiguities
176 // due to `[type error]` and `_` not coercing together.
9ffffee4 177 let _ = self.commit_if_ok(|_| {
353b0b11 178 self.at(&self.cause, self.param_env).eq(DefineOpaqueTypes::Yes, a, b)
9ffffee4
FG
179 });
180 return success(vec![], self.fcx.tcx.ty_error(guar), vec![]);
92a42be0
SL
181 }
182
94222f64 183 // Coercing from `!` to any type is allowed:
5bcae85e 184 if a.is_never() {
c295e0f8 185 return success(simple(Adjust::NeverToAny)(b), b, vec![]);
5bcae85e
SL
186 }
187
94222f64
XL
188 // Coercing *from* an unresolved inference variable means that
189 // we have no information about the source type. This will always
190 // ultimately fall back to some form of subtyping.
191 if a.is_ty_var() {
192 return self.coerce_from_inference_variable(a, b, identity);
193 }
194
1a4d82fc 195 // Consider coercing the subtype to a DST
ea8adc8c
XL
196 //
197 // NOTE: this is wrapped in a `commit_if_ok` because it creates
198 // a "spurious" type variable, and we don't want to have that
199 // type variable in memory if the coercion fails.
200 let unsize = self.commit_if_ok(|_| self.coerce_unsized(a, b));
e74abb32
XL
201 match unsize {
202 Ok(_) => {
203 debug!("coerce: unsize successful");
204 return unsize;
205 }
3c0e092e
XL
206 Err(error) => {
207 debug!(?error, "coerce: unsize failed");
208 }
1a4d82fc
JJ
209 }
210
211 // Examine the supertype and consider auto-borrowing.
1b1a35ee 212 match *b.kind() {
b7449926 213 ty::RawPtr(mt_b) => {
92a42be0 214 return self.coerce_unsafe_ptr(a, b, mt_b.mutbl);
1a4d82fc 215 }
f9f354fc
XL
216 ty::Ref(r_b, _, mutbl_b) => {
217 return self.coerce_borrowed_pointer(a, b, r_b, mutbl_b);
1a4d82fc 218 }
2b03887a
FG
219 ty::Dynamic(predicates, region, ty::DynStar) if self.tcx.features().dyn_star => {
220 return self.coerce_dyn_star(a, b, predicates, region);
221 }
1a4d82fc
JJ
222 _ => {}
223 }
224
1b1a35ee 225 match *a.kind() {
b7449926 226 ty::FnDef(..) => {
92a42be0
SL
227 // Function items are coercible to any closure
228 // type; function pointers are not (that would
229 // require double indirection).
c30ab7b3
SL
230 // Additionally, we permit coercion of function
231 // items to drop the unsafe qualifier.
041b39d2 232 self.coerce_from_fn_item(a, b)
1a4d82fc 233 }
b7449926 234 ty::FnPtr(a_f) => {
92a42be0
SL
235 // We permit coercion of fn pointers to drop the
236 // unsafe qualifier.
237 self.coerce_from_fn_pointer(a, a_f, b)
238 }
29967ef6 239 ty::Closure(closure_def_id_a, substs_a) => {
8bb4bdeb 240 // Non-capturing closures are coercible to
532ac7d7
XL
241 // function pointers or unsafe function pointers.
242 // It cannot convert closures that require unsafe.
29967ef6 243 self.coerce_closure_to_fn(a, closure_def_id_a, substs_a, b)
8bb4bdeb 244 }
92a42be0 245 _ => {
54a0048b 246 // Otherwise, just use unification rules.
7cac9316 247 self.unify_and(a, b, identity)
92a42be0
SL
248 }
249 }
1a4d82fc
JJ
250 }
251
94222f64
XL
252 /// Coercing *from* an inference variable. In this case, we have no information
253 /// about the source type, so we can't really do a true coercion and we always
254 /// fall back to subtyping (`unify_and`).
255 fn coerce_from_inference_variable(
256 &self,
257 a: Ty<'tcx>,
258 b: Ty<'tcx>,
259 make_adjustments: impl FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
260 ) -> CoerceResult<'tcx> {
261 debug!("coerce_from_inference_variable(a={:?}, b={:?})", a, b);
064997fb
FG
262 assert!(a.is_ty_var() && self.shallow_resolve(a) == a);
263 assert!(self.shallow_resolve(b) == b);
94222f64
XL
264
265 if b.is_ty_var() {
266 // Two unresolved type variables: create a `Coerce` predicate.
267 let target_ty = if self.use_lub {
064997fb 268 self.next_ty_var(TypeVariableOrigin {
94222f64
XL
269 kind: TypeVariableOriginKind::LatticeVariable,
270 span: self.cause.span,
271 })
272 } else {
273 b
274 };
275
276 let mut obligations = Vec::with_capacity(2);
277 for &source_ty in &[a, b] {
278 if source_ty != target_ty {
279 obligations.push(Obligation::new(
487cf647 280 self.tcx(),
94222f64
XL
281 self.cause.clone(),
282 self.param_env,
c295e0f8 283 ty::Binder::dummy(ty::PredicateKind::Coerce(ty::CoercePredicate {
94222f64
XL
284 a: source_ty,
285 b: target_ty,
487cf647 286 })),
94222f64
XL
287 ));
288 }
289 }
290
291 debug!(
292 "coerce_from_inference_variable: two inference variables, target_ty={:?}, obligations={:?}",
293 target_ty, obligations
294 );
295 let adjustments = make_adjustments(target_ty);
296 InferResult::Ok(InferOk { value: (adjustments, target_ty), obligations })
297 } else {
298 // One unresolved type variable: just apply subtyping, we may be able
299 // to do something useful.
300 self.unify_and(a, b, make_adjustments)
301 }
302 }
303
85aaf69f
SL
304 /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`.
305 /// To match `A` with `B`, autoderef will be performed,
306 /// calling `deref`/`deref_mut` where necessary.
dfeec247
XL
307 fn coerce_borrowed_pointer(
308 &self,
309 a: Ty<'tcx>,
310 b: Ty<'tcx>,
311 r_b: ty::Region<'tcx>,
f9f354fc 312 mutbl_b: hir::Mutability,
dfeec247 313 ) -> CoerceResult<'tcx> {
54a0048b 314 debug!("coerce_borrowed_pointer(a={:?}, b={:?})", a, b);
1a4d82fc
JJ
315
316 // If we have a parameter of type `&M T_a` and the value
317 // provided is `expr`, we will be adding an implicit borrow,
9c376795 318 // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore,
1a4d82fc
JJ
319 // to type check, we will construct the type that `&M*expr` would
320 // yield.
321
1b1a35ee 322 let (r_a, mt_a) = match *a.kind() {
b7449926 323 ty::Ref(r_a, ty, mutbl) => {
94b46f34 324 let mt_a = ty::TypeAndMut { ty, mutbl };
f9f354fc 325 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
54a0048b 326 (r_a, mt_a)
1a4d82fc 327 }
7cac9316 328 _ => return self.unify_and(a, b, identity),
54a0048b 329 };
1a4d82fc 330
476ff2be 331 let span = self.cause.span;
9346a6ac 332
85aaf69f 333 let mut first_error = None;
54a0048b 334 let mut r_borrow_var = None;
3157f602 335 let mut autoderef = self.autoderef(span, a);
8bb4bdeb 336 let mut found = None;
3157f602
XL
337
338 for (referent_ty, autoderefs) in autoderef.by_ref() {
339 if autoderefs == 0 {
85aaf69f
SL
340 // Don't let this pass, otherwise it would cause
341 // &T to autoref to &&T.
c30ab7b3 342 continue;
85aaf69f 343 }
54a0048b 344
9c376795 345 // At this point, we have deref'd `a` to `referent_ty`. So
54a0048b
SL
346 // imagine we are coercing from `&'a mut Vec<T>` to `&'b mut [T]`.
347 // In the autoderef loop for `&'a mut Vec<T>`, we would get
348 // three callbacks:
349 //
350 // - `&'a mut Vec<T>` -- 0 derefs, just ignore it
351 // - `Vec<T>` -- 1 deref
352 // - `[T]` -- 2 deref
353 //
354 // At each point after the first callback, we want to
355 // check to see whether this would match out target type
356 // (`&'b mut [T]`) if we autoref'd it. We can't just
357 // compare the referent types, though, because we still
358 // have to consider the mutability. E.g., in the case
359 // we've been considering, we have an `&mut` reference, so
360 // the `T` in `[T]` needs to be unified with equality.
361 //
362 // Therefore, we construct reference types reflecting what
363 // the types will be after we do the final auto-ref and
364 // compare those. Note that this means we use the target
365 // mutability [1], since it may be that we are coercing
366 // from `&mut T` to `&U`.
367 //
368 // One fine point concerns the region that we use. We
369 // choose the region such that the region of the final
370 // type that results from `unify` will be the region we
371 // want for the autoref:
372 //
373 // - if in sub mode, that means we want to use `'b` (the
374 // region from the target reference) for both
375 // pointers [2]. This is because sub mode (somewhat
9c376795 376 // arbitrarily) returns the subtype region. In the case
54a0048b
SL
377 // where we are coercing to a target type, we know we
378 // want to use that target type region (`'b`) because --
379 // for the program to type-check -- it must be the
380 // smaller of the two.
381 // - One fine point. It may be surprising that we can
382 // use `'b` without relating `'a` and `'b`. The reason
383 // that this is ok is that what we produce is
384 // effectively a `&'b *x` expression (if you could
385 // annotate the region of a borrow), and regionck has
386 // code that adds edges from the region of a borrow
387 // (`'b`, here) into the regions in the borrowed
9c376795 388 // expression (`*x`, here). (Search for "link".)
54a0048b
SL
389 // - if in lub mode, things can get fairly complicated. The
390 // easiest thing is just to make a fresh
391 // region variable [4], which effectively means we defer
392 // the decision to region inference (and regionck, which will add
393 // some more edges to this variable). However, this can wind up
394 // creating a crippling number of variables in some cases --
0731742a 395 // e.g., #32278 -- so we optimize one particular case [3].
54a0048b
SL
396 // Let me try to explain with some examples:
397 // - The "running example" above represents the simple case,
398 // where we have one `&` reference at the outer level and
399 // ownership all the rest of the way down. In this case,
400 // we want `LUB('a, 'b)` as the resulting region.
401 // - However, if there are nested borrows, that region is
402 // too strong. Consider a coercion from `&'a &'x Rc<T>` to
403 // `&'b T`. In this case, `'a` is actually irrelevant.
404 // The pointer we want is `LUB('x, 'b`). If we choose `LUB('a,'b)`
416331ca 405 // we get spurious errors (`ui/regions-lub-ref-ref-rc.rs`).
54a0048b
SL
406 // (The errors actually show up in borrowck, typically, because
407 // this extra edge causes the region `'a` to be inferred to something
408 // too big, which then results in borrowck errors.)
409 // - We could track the innermost shared reference, but there is already
410 // code in regionck that has the job of creating links between
411 // the region of a borrow and the regions in the thing being
412 // borrowed (here, `'a` and `'x`), and it knows how to handle
413 // all the various cases. So instead we just make a region variable
414 // and let regionck figure it out.
415 let r = if !self.use_lub {
416 r_b // [2] above
3157f602 417 } else if autoderefs == 1 {
54a0048b 418 r_a // [3] above
85aaf69f 419 } else {
c30ab7b3 420 if r_borrow_var.is_none() {
f9f354fc 421 // create var lazily, at most once
54a0048b 422 let coercion = Coercion(span);
a7813a04 423 let r = self.next_region_var(coercion);
9e0c209e 424 r_borrow_var = Some(r); // [4] above
54a0048b
SL
425 }
426 r_borrow_var.unwrap()
427 };
dfeec247
XL
428 let derefd_ty_a = self.tcx.mk_ref(
429 r,
430 TypeAndMut {
431 ty: referent_ty,
f9f354fc 432 mutbl: mutbl_b, // [1] above
dfeec247
XL
433 },
434 );
54a0048b 435 match self.unify(derefd_ty_a, b) {
8bb4bdeb 436 Ok(ok) => {
7cac9316 437 found = Some(ok);
c30ab7b3
SL
438 break;
439 }
54a0048b
SL
440 Err(err) => {
441 if first_error.is_none() {
442 first_error = Some(err);
443 }
54a0048b 444 }
85aaf69f 445 }
3157f602 446 }
85aaf69f 447
54a0048b
SL
448 // Extract type or return an error. We return the first error
449 // we got, which should be from relating the "base" type
450 // (e.g., in example above, the failure from relating `Vec<T>`
451 // to the target type), since that should be the least
452 // confusing.
5e7ed085
FG
453 let Some(InferOk { value: ty, mut obligations }) = found else {
454 let err = first_error.expect("coerce_borrowed_pointer had no error");
455 debug!("coerce_borrowed_pointer: failed with err = {:?}", err);
456 return Err(err);
54a0048b
SL
457 };
458
487cf647 459 if ty == a && mt_a.mutbl.is_not() && autoderef.step_count() == 1 {
54a0048b
SL
460 // As a special case, if we would produce `&'a *x`, that's
461 // a total no-op. We end up with the type `&'a T` just as
9c376795 462 // we started with. In that case, just skip it
54a0048b
SL
463 // altogether. This is just an optimization.
464 //
465 // Note that for `&mut`, we DO want to reborrow --
466 // otherwise, this would be a move, which might be an
467 // error. For example `foo(self.x)` where `self` and
468 // `self.x` both have `&mut `type would be a move of
469 // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
470 // which is a borrow.
487cf647 471 assert!(mutbl_b.is_not()); // can only coerce &T -> &U
7cac9316 472 return success(vec![], ty, obligations);
85aaf69f 473 }
8bb4bdeb 474
dfeec247 475 let InferOk { value: mut adjustments, obligations: o } =
f035d41b 476 self.adjust_steps_as_infer_ok(&autoderef);
7cac9316
XL
477 obligations.extend(o);
478 obligations.extend(autoderef.into_obligations());
479
8bb4bdeb
XL
480 // Now apply the autoref. We have to extract the region out of
481 // the final ref type we got.
5e7ed085
FG
482 let ty::Ref(r_borrow, _, _) = ty.kind() else {
483 span_bug!(span, "expected a ref type, got {:?}", ty);
54a0048b 484 };
487cf647 485 let mutbl = AutoBorrowMutability::new(mutbl_b, self.allow_two_phase);
7cac9316 486 adjustments.push(Adjustment {
5099ac24 487 kind: Adjust::Borrow(AutoBorrow::Ref(*r_borrow, mutbl)),
dfeec247 488 target: ty,
7cac9316 489 });
8bb4bdeb 490
dfeec247 491 debug!("coerce_borrowed_pointer: succeeded ty={:?} adjustments={:?}", ty, adjustments);
8bb4bdeb 492
7cac9316 493 success(adjustments, ty, obligations)
1a4d82fc
JJ
494 }
495
62682a34
SL
496 // &[T; n] or &mut [T; n] -> &[T]
497 // or &mut [T; n] -> &mut [T]
1a4d82fc 498 // or &Concrete -> &Trait, etc.
c295e0f8 499 #[instrument(skip(self), level = "debug")]
f9f354fc 500 fn coerce_unsized(&self, mut source: Ty<'tcx>, mut target: Ty<'tcx>) -> CoerceResult<'tcx> {
f9f354fc
XL
501 source = self.shallow_resolve(source);
502 target = self.shallow_resolve(target);
c295e0f8 503 debug!(?source, ?target);
f9f354fc 504
487cf647
FG
505 // We don't apply any coercions incase either the source or target
506 // aren't sufficiently well known but tend to instead just equate
507 // them both.
f9f354fc
XL
508 if source.is_ty_var() {
509 debug!("coerce_unsized: source is a TyVar, bailing out");
510 return Err(TypeError::Mismatch);
511 }
512 if target.is_ty_var() {
513 debug!("coerce_unsized: target is a TyVar, bailing out");
514 return Err(TypeError::Mismatch);
515 }
516
dfeec247
XL
517 let traits =
518 (self.tcx.lang_items().unsize_trait(), self.tcx.lang_items().coerce_unsized_trait());
3c0e092e 519 let (Some(unsize_did), Some(coerce_unsized_did)) = traits else {
416331ca 520 debug!("missing Unsize or CoerceUnsized traits");
c1a9b12d 521 return Err(TypeError::Mismatch);
d9579d0f 522 };
1a4d82fc
JJ
523
524 // Note, we want to avoid unnecessary unsizing. We don't want to coerce to
525 // a DST unless we have to. This currently comes out in the wash since
526 // we can't unify [T] with U. But to properly support DST, we need to allow
d9579d0f 527 // that, at which point we will need extra checks on the target here.
1a4d82fc 528
d9579d0f 529 // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
1b1a35ee 530 let reborrow = match (source.kind(), target.kind()) {
b7449926 531 (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => {
94b46f34 532 coerce_mutbls(mutbl_a, mutbl_b)?;
d9579d0f 533
476ff2be 534 let coercion = Coercion(self.cause.span);
a7813a04 535 let r_borrow = self.next_region_var(coercion);
487cf647
FG
536
537 // We don't allow two-phase borrows here, at least for initial
538 // implementation. If it happens that this coercion is a function argument,
539 // the reborrow in coerce_borrowed_ptr will pick it up.
540 let mutbl = AutoBorrowMutability::new(mutbl_b, AllowTwoPhase::No);
541
dfeec247
XL
542 Some((
543 Adjustment { kind: Adjust::Deref(None), target: ty_a },
544 Adjustment {
545 kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)),
546 target: self
547 .tcx
548 .mk_ref(r_borrow, ty::TypeAndMut { mutbl: mutbl_b, ty: ty_a }),
549 },
550 ))
1a4d82fc 551 }
b7449926 552 (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(ty::TypeAndMut { mutbl: mt_b, .. })) => {
94b46f34 553 coerce_mutbls(mt_a, mt_b)?;
8bb4bdeb 554
dfeec247
XL
555 Some((
556 Adjustment { kind: Adjust::Deref(None), target: ty_a },
557 Adjustment {
558 kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
559 target: self.tcx.mk_ptr(ty::TypeAndMut { mutbl: mt_b, ty: ty_a }),
560 },
561 ))
7cac9316
XL
562 }
563 _ => None,
8bb4bdeb 564 };
487cf647 565 let coerce_source = reborrow.as_ref().map_or(source, |(_, r)| r.target);
8bb4bdeb
XL
566
567 // Setup either a subtyping or a LUB relationship between
568 // the `CoerceUnsized` target type and the expected type.
569 // We only have the latter, so we use an inference variable
570 // for the former and let type inference do the rest.
dc9dc135
XL
571 let origin = TypeVariableOrigin {
572 kind: TypeVariableOriginKind::MiscVariable,
573 span: self.cause.span,
574 };
8bb4bdeb 575 let coerce_target = self.next_ty_var(origin);
7cac9316 576 let mut coercion = self.unify_and(coerce_target, target, |target| {
dfeec247 577 let unsize = Adjustment { kind: Adjust::Pointer(PointerCast::Unsize), target };
7cac9316
XL
578 match reborrow {
579 None => vec![unsize],
dfeec247 580 Some((ref deref, ref autoref)) => vec![deref.clone(), autoref.clone(), unsize],
7cac9316
XL
581 }
582 })?;
d9579d0f 583
a7813a04 584 let mut selcx = traits::SelectionContext::new(self);
d9579d0f 585
d9579d0f 586 // Create an obligation for `Source: CoerceUnsized<Target>`.
e74abb32
XL
587 let cause = ObligationCause::new(
588 self.cause.span,
589 self.body_id,
590 ObligationCauseCode::Coercion { source, target },
591 );
a1dfa0c6
XL
592
593 // Use a FIFO queue for this custom fulfillment procedure.
594 //
595 // A Vec (or SmallVec) is not a natural choice for a queue. However,
596 // this code path is hot, and this queue usually has a max length of 1
597 // and almost never more than 3. By using a SmallVec we avoid an
598 // allocation, at the (very small) cost of (occasionally) having to
599 // shift subsequent elements down when removing the front element.
353b0b11 600 let mut queue: SmallVec<[PredicateObligation<'tcx>; 4]> = smallvec![Obligation::new(
dfeec247 601 self.tcx,
dfeec247 602 cause,
353b0b11
FG
603 self.fcx.param_env,
604 self.tcx.mk_trait_ref(coerce_unsized_did, [coerce_source, coerce_target])
dfeec247 605 )];
d9579d0f 606
041b39d2 607 let mut has_unsized_tuple_coercion = false;
923072b8 608 let mut has_trait_upcasting_coercion = None;
041b39d2 609
d9579d0f
AL
610 // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
611 // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
612 // inference might unify those two inner type variables later.
613 let traits = [coerce_unsized_did, unsize_did];
a1dfa0c6
XL
614 while !queue.is_empty() {
615 let obligation = queue.remove(0);
62682a34 616 debug!("coerce_unsized resolve step: {:?}", obligation);
5869c6ff 617 let bound_predicate = obligation.predicate.kind();
29967ef6 618 let trait_pred = match bound_predicate.skip_binder() {
487cf647
FG
619 ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred))
620 if traits.contains(&trait_pred.def_id()) =>
621 {
ba9703b0 622 if unsize_did == trait_pred.def_id() {
94222f64 623 let self_ty = trait_pred.self_ty();
3dfed10e 624 let unsize_ty = trait_pred.trait_ref.substs[1].expect_ty();
94222f64
XL
625 if let (ty::Dynamic(ref data_a, ..), ty::Dynamic(ref data_b, ..)) =
626 (self_ty.kind(), unsize_ty.kind())
04454e1e 627 && data_a.principal_def_id() != data_b.principal_def_id()
94222f64 628 {
04454e1e 629 debug!("coerce_unsized: found trait upcasting coercion");
923072b8 630 has_trait_upcasting_coercion = Some((self_ty, unsize_ty));
94222f64 631 }
1b1a35ee 632 if let ty::Tuple(..) = unsize_ty.kind() {
041b39d2
XL
633 debug!("coerce_unsized: found unsized tuple coercion");
634 has_unsized_tuple_coercion = true;
635 }
636 }
29967ef6 637 bound_predicate.rebind(trait_pred)
041b39d2 638 }
d9579d0f 639 _ => {
8bb4bdeb 640 coercion.obligations.push(obligation);
d9579d0f
AL
641 continue;
642 }
643 };
487cf647 644 match selcx.select(&obligation.with(selcx.tcx(), trait_pred)) {
d9579d0f 645 // Uncertain or unimplemented.
0731742a 646 Ok(None) => {
ba9703b0 647 if trait_pred.def_id() == unsize_did {
fc512014 648 let trait_pred = self.resolve_vars_if_possible(trait_pred);
ba9703b0
XL
649 let self_ty = trait_pred.skip_binder().self_ty();
650 let unsize_ty = trait_pred.skip_binder().trait_ref.substs[1].expect_ty();
651 debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_pred);
353b0b11
FG
652 match (self_ty.kind(), unsize_ty.kind()) {
653 (&ty::Infer(ty::TyVar(v)), ty::Dynamic(..))
654 if self.type_var_is_sized(v) =>
dfeec247 655 {
0731742a
XL
656 debug!("coerce_unsized: have sized infer {:?}", v);
657 coercion.obligations.push(obligation);
658 // `$0: Unsize<dyn Trait>` where we know that `$0: Sized`, try going
659 // for unsizing.
660 }
661 _ => {
662 // Some other case for `$0: Unsize<Something>`. Note that we
663 // hit this case even if `Something` is a sized type, so just
664 // don't do the coercion.
665 debug!("coerce_unsized: ambiguous unsize");
666 return Err(TypeError::Mismatch);
667 }
668 }
669 } else {
670 debug!("coerce_unsized: early return - ambiguous");
671 return Err(TypeError::Mismatch);
672 }
673 }
c30ab7b3 674 Err(traits::Unimplemented) => {
d9579d0f 675 debug!("coerce_unsized: early return - can't prove obligation");
c1a9b12d 676 return Err(TypeError::Mismatch);
c34b1796 677 }
d9579d0f
AL
678
679 // Object safety violations or miscellaneous.
680 Err(err) => {
487cf647 681 self.err_ctxt().report_selection_error(obligation.clone(), &obligation, &err);
d9579d0f
AL
682 // Treat this like an obligation and follow through
683 // with the unsizing - the lack of a coercion should
684 // be silent, as it causes a type mismatch later.
685 }
686
f035d41b 687 Ok(Some(impl_source)) => queue.extend(impl_source.nested_obligations()),
1a4d82fc 688 }
d9579d0f
AL
689 }
690
0531ce1d 691 if has_unsized_tuple_coercion && !self.tcx.features().unsized_tuple_coercion {
dfeec247 692 feature_err(
60c5eb7d
XL
693 &self.tcx.sess.parse_sess,
694 sym::unsized_tuple_coercion,
695 self.cause.span,
696 "unsized tuple coercion is not stable enough for use and is subject to change",
697 )
698 .emit();
041b39d2
XL
699 }
700
923072b8
FG
701 if let Some((sub, sup)) = has_trait_upcasting_coercion
702 && !self.tcx().features().trait_upcasting
703 {
704 // Renders better when we erase regions, since they're not really the point here.
705 let (sub, sup) = self.tcx.erase_regions((sub, sup));
706 let mut err = feature_err(
94222f64
XL
707 &self.tcx.sess.parse_sess,
708 sym::trait_upcasting,
709 self.cause.span,
923072b8
FG
710 &format!("cannot cast `{sub}` to `{sup}`, trait upcasting coercion is experimental"),
711 );
712 err.note(&format!("required when coercing `{source}` into `{target}`"));
713 err.emit();
94222f64
XL
714 }
715
8bb4bdeb 716 Ok(coercion)
1a4d82fc
JJ
717 }
718
2b03887a
FG
719 fn coerce_dyn_star(
720 &self,
721 a: Ty<'tcx>,
722 b: Ty<'tcx>,
487cf647 723 predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
2b03887a
FG
724 b_region: ty::Region<'tcx>,
725 ) -> CoerceResult<'tcx> {
726 if !self.tcx.features().dyn_star {
727 return Err(TypeError::Mismatch);
728 }
729
730 if let ty::Dynamic(a_data, _, _) = a.kind()
731 && let ty::Dynamic(b_data, _, _) = b.kind()
487cf647 732 && a_data.principal_def_id() == b_data.principal_def_id()
2b03887a 733 {
487cf647 734 return self.unify_and(a, b, |_| vec![]);
2b03887a
FG
735 }
736
737 // Check the obligations of the cast -- for example, when casting
738 // `usize` to `dyn* Clone + 'static`:
487cf647 739 let mut obligations: Vec<_> = predicates
2b03887a
FG
740 .iter()
741 .map(|predicate| {
742 // For each existential predicate (e.g., `?Self: Clone`) substitute
743 // the type of the expression (e.g., `usize` in our example above)
744 // and then require that the resulting predicate (e.g., `usize: Clone`)
745 // holds (it does).
746 let predicate = predicate.with_self_ty(self.tcx, a);
487cf647 747 Obligation::new(self.tcx, self.cause.clone(), self.param_env, predicate)
2b03887a 748 })
487cf647
FG
749 .chain([
750 // Enforce the region bound (e.g., `usize: 'static`, in our example).
751 Obligation::new(
752 self.tcx,
753 self.cause.clone(),
754 self.param_env,
755 ty::Binder::dummy(ty::PredicateKind::Clause(ty::Clause::TypeOutlives(
756 ty::OutlivesPredicate(a, b_region),
757 ))),
758 ),
759 ])
2b03887a
FG
760 .collect();
761
487cf647
FG
762 // Enforce that the type is `usize`/pointer-sized.
763 obligations.push(Obligation::new(
764 self.tcx,
765 self.cause.clone(),
766 self.param_env,
767 ty::Binder::dummy(
9ffffee4 768 self.tcx.at(self.cause.span).mk_trait_ref(hir::LangItem::PointerLike, [a]),
487cf647
FG
769 ),
770 ));
771
2b03887a
FG
772 Ok(InferOk {
773 value: (vec![Adjustment { kind: Adjust::DynStar, target: b }], b),
774 obligations,
775 })
776 }
777
dfeec247
XL
778 fn coerce_from_safe_fn<F, G>(
779 &self,
780 a: Ty<'tcx>,
781 fn_ty_a: ty::PolyFnSig<'tcx>,
782 b: Ty<'tcx>,
783 to_unsafe: F,
784 normal: G,
785 ) -> CoerceResult<'tcx>
786 where
787 F: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
788 G: FnOnce(Ty<'tcx>) -> Vec<Adjustment<'tcx>>,
7cac9316 789 {
064997fb 790 self.commit_if_ok(|snapshot| {
923072b8
FG
791 let result = if let ty::FnPtr(fn_ty_b) = b.kind()
792 && let (hir::Unsafety::Normal, hir::Unsafety::Unsafe) =
793 (fn_ty_a.unsafety(), fn_ty_b.unsafety())
794 {
795 let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a);
796 self.unify_and(unsafe_a, b, to_unsafe)
797 } else {
798 self.unify_and(a, b, normal)
799 };
800
801 // FIXME(#73154): This is a hack. Currently LUB can generate
802 // unsolvable constraints. Additionally, it returns `a`
803 // unconditionally, even when the "LUB" is `b`. In the future, we
804 // want the coerced type to be the actual supertype of these two,
805 // but for now, we want to just error to ensure we don't lock
806 // ourselves into a specific behavior with NLL.
807 self.leak_check(false, snapshot)?;
808
809 result
810 })
1a4d82fc
JJ
811 }
812
dfeec247
XL
813 fn coerce_from_fn_pointer(
814 &self,
815 a: Ty<'tcx>,
816 fn_ty_a: ty::PolyFnSig<'tcx>,
817 b: Ty<'tcx>,
818 ) -> CoerceResult<'tcx> {
c30ab7b3
SL
819 //! Attempts to coerce from the type of a Rust function item
820 //! into a closure or a `proc`.
821 //!
822
823 let b = self.shallow_resolve(b);
824 debug!("coerce_from_fn_pointer(a={:?}, b={:?})", a, b);
825
dfeec247
XL
826 self.coerce_from_safe_fn(
827 a,
828 fn_ty_a,
829 b,
830 simple(Adjust::Pointer(PointerCast::UnsafeFnPointer)),
831 identity,
832 )
c30ab7b3
SL
833 }
834
dfeec247 835 fn coerce_from_fn_item(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
c30ab7b3
SL
836 //! Attempts to coerce from the type of a Rust function item
837 //! into a closure or a `proc`.
1a4d82fc 838
a7813a04 839 let b = self.shallow_resolve(b);
94222f64 840 let InferOk { value: b, mut obligations } =
487cf647 841 self.at(&self.cause, self.param_env).normalize(b);
54a0048b 842 debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
1a4d82fc 843
1b1a35ee 844 match b.kind() {
f9f354fc 845 ty::FnPtr(b_sig) => {
041b39d2 846 let a_sig = a.fn_sig(self.tcx);
923072b8
FG
847 if let ty::FnDef(def_id, _) = *a.kind() {
848 // Intrinsics are not coercible to function pointers
849 if self.tcx.is_intrinsic(def_id) {
850 return Err(TypeError::IntrinsicCast);
851 }
852
853 // Safe `#[target_feature]` functions are not assignable to safe fn pointers (RFC 2396).
f9f354fc 854
923072b8
FG
855 if b_sig.unsafety() == hir::Unsafety::Normal
856 && !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()
857 {
858 return Err(TypeError::TargetFeatureCast(def_id));
859 }
f9f354fc
XL
860 }
861
94222f64 862 let InferOk { value: a_sig, obligations: o1 } =
487cf647 863 self.at(&self.cause, self.param_env).normalize(a_sig);
94222f64 864 obligations.extend(o1);
041b39d2
XL
865
866 let a_fn_pointer = self.tcx.mk_fn_ptr(a_sig);
ff7c6d11
XL
867 let InferOk { value, obligations: o2 } = self.coerce_from_safe_fn(
868 a_fn_pointer,
869 a_sig,
870 b,
871 |unsafe_ty| {
872 vec![
48663c56
XL
873 Adjustment {
874 kind: Adjust::Pointer(PointerCast::ReifyFnPointer),
dfeec247 875 target: a_fn_pointer,
48663c56
XL
876 },
877 Adjustment {
878 kind: Adjust::Pointer(PointerCast::UnsafeFnPointer),
dfeec247 879 target: unsafe_ty,
48663c56 880 },
ff7c6d11
XL
881 ]
882 },
dfeec247 883 simple(Adjust::Pointer(PointerCast::ReifyFnPointer)),
ff7c6d11 884 )?;
041b39d2
XL
885
886 obligations.extend(o2);
887 Ok(InferOk { value, obligations })
8bb4bdeb 888 }
7cac9316 889 _ => self.unify_and(a, b, identity),
8bb4bdeb
XL
890 }
891 }
892
dfeec247
XL
893 fn coerce_closure_to_fn(
894 &self,
895 a: Ty<'tcx>,
29967ef6 896 closure_def_id_a: DefId,
dfeec247
XL
897 substs_a: SubstsRef<'tcx>,
898 b: Ty<'tcx>,
899 ) -> CoerceResult<'tcx> {
8bb4bdeb
XL
900 //! Attempts to coerce from the type of a non-capturing closure
901 //! into a function pointer.
902 //!
903
904 let b = self.shallow_resolve(b);
905
1b1a35ee 906 match b.kind() {
29967ef6
XL
907 // At this point we haven't done capture analysis, which means
908 // that the ClosureSubsts just contains an inference variable instead
909 // of tuple of captured types.
910 //
911 // All we care here is if any variable is being captured and not the exact paths,
912 // so we check `upvars_mentioned` for root variables being captured.
913 ty::FnPtr(fn_ty)
914 if self
915 .tcx
916 .upvars_mentioned(closure_def_id_a.expect_local())
917 .map_or(true, |u| u.is_empty()) =>
918 {
8bb4bdeb
XL
919 // We coerce the closure, which has fn type
920 // `extern "rust-call" fn((arg0,arg1,...)) -> _`
921 // to
922 // `fn(arg0,arg1,...) -> _`
532ac7d7
XL
923 // or
924 // `unsafe fn(arg0,arg1,...) -> _`
ba9703b0 925 let closure_sig = substs_a.as_closure().sig();
532ac7d7 926 let unsafety = fn_ty.unsafety();
f9f354fc
XL
927 let pointer_ty =
928 self.tcx.mk_fn_ptr(self.tcx.signature_unclosure(closure_sig, unsafety));
dfeec247
XL
929 debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})", a, b, pointer_ty);
930 self.unify_and(
931 pointer_ty,
932 b,
933 simple(Adjust::Pointer(PointerCast::ClosureFnPointer(unsafety))),
934 )
1a4d82fc 935 }
7cac9316 936 _ => self.unify_and(a, b, identity),
54a0048b 937 }
1a4d82fc
JJ
938 }
939
dfeec247
XL
940 fn coerce_unsafe_ptr(
941 &self,
942 a: Ty<'tcx>,
943 b: Ty<'tcx>,
944 mutbl_b: hir::Mutability,
945 ) -> CoerceResult<'tcx> {
c30ab7b3 946 debug!("coerce_unsafe_ptr(a={:?}, b={:?})", a, b);
1a4d82fc 947
1b1a35ee 948 let (is_ref, mt_a) = match *a.kind() {
b7449926
XL
949 ty::Ref(_, ty, mutbl) => (true, ty::TypeAndMut { ty, mutbl }),
950 ty::RawPtr(mt) => (false, mt),
dfeec247 951 _ => return self.unify_and(a, b, identity),
1a4d82fc 952 };
f9f354fc 953 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
1a4d82fc
JJ
954
955 // Check that the types which they point at are compatible.
dfeec247 956 let a_unsafe = self.tcx.mk_ptr(ty::TypeAndMut { mutbl: mutbl_b, ty: mt_a.ty });
1a4d82fc 957 // Although references and unsafe ptrs have the same
c30ab7b3 958 // representation, we still register an Adjust::DerefRef so that
1a4d82fc 959 // regionck knows that the region for `a` must be valid here.
7cac9316
XL
960 if is_ref {
961 self.unify_and(a_unsafe, b, |target| {
dfeec247
XL
962 vec![
963 Adjustment { kind: Adjust::Deref(None), target: mt_a.ty },
964 Adjustment { kind: Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)), target },
965 ]
7cac9316 966 })
8bb4bdeb 967 } else if mt_a.mutbl != mutbl_b {
dfeec247 968 self.unify_and(a_unsafe, b, simple(Adjust::Pointer(PointerCast::MutToConstPointer)))
8bb4bdeb 969 } else {
7cac9316
XL
970 self.unify_and(a_unsafe, b, identity)
971 }
9346a6ac 972 }
85aaf69f
SL
973}
974
dc9dc135 975impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
a7813a04
XL
976 /// Attempt to coerce an expression to a type, and return the
977 /// adjusted type of the expression, if successful.
978 /// Adjustments are only recorded if the coercion succeeded.
979 /// The expressions *must not* have any pre-existing adjustments.
e1599b0c
XL
980 pub fn try_coerce(
981 &self,
dfeec247 982 expr: &hir::Expr<'_>,
e1599b0c
XL
983 expr_ty: Ty<'tcx>,
984 target: Ty<'tcx>,
985 allow_two_phase: AllowTwoPhase,
c295e0f8 986 cause: Option<ObligationCause<'tcx>>,
e1599b0c 987 ) -> RelateResult<'tcx, Ty<'tcx>> {
e74abb32 988 let source = self.resolve_vars_with_obligations(expr_ty);
a7813a04
XL
989 debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
990
c295e0f8
XL
991 let cause =
992 cause.unwrap_or_else(|| self.cause(expr.span, ObligationCauseCode::ExprAssignable));
83c7162d 993 let coerce = Coerce::new(self, cause, allow_two_phase);
7cac9316 994 let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?;
cc61c64b 995
7cac9316
XL
996 let (adjustments, _) = self.register_infer_ok_obligations(ok);
997 self.apply_adjustments(expr, adjustments);
9ffffee4 998 Ok(if let Err(guar) = expr_ty.error_reported() { self.tcx.ty_error(guar) } else { target })
cc61c64b
XL
999 }
1000
1001 /// Same as `try_coerce()`, but without side-effects.
c295e0f8
XL
1002 ///
1003 /// Returns false if the coercion creates any obligations that result in
1004 /// errors.
cc61c64b 1005 pub fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool {
e74abb32 1006 let source = self.resolve_vars_with_obligations(expr_ty);
c295e0f8 1007 debug!("coercion::can_with_predicates({:?} -> {:?})", source, target);
cc61c64b 1008
dfeec247 1009 let cause = self.cause(rustc_span::DUMMY_SP, ObligationCauseCode::ExprAssignable);
83c7162d
XL
1010 // We don't ever need two-phase here since we throw out the result of the coercion
1011 let coerce = Coerce::new(self, cause, AllowTwoPhase::No);
c295e0f8 1012 self.probe(|_| {
5e7ed085
FG
1013 let Ok(ok) = coerce.coerce(source, target) else {
1014 return false;
c295e0f8 1015 };
487cf647
FG
1016 let ocx = ObligationCtxt::new_in_snapshot(self);
1017 ocx.register_obligations(ok.obligations);
1018 ocx.select_where_possible().is_empty()
c295e0f8 1019 })
a7813a04 1020 }
54a0048b 1021
f9f354fc
XL
1022 /// Given a type and a target type, this function will calculate and return
1023 /// how many dereference steps needed to achieve `expr_ty <: target`. If
1024 /// it's not possible, return `None`.
1025 pub fn deref_steps(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> Option<usize> {
1026 let cause = self.cause(rustc_span::DUMMY_SP, ObligationCauseCode::ExprAssignable);
1027 // We don't ever need two-phase here since we throw out the result of the coercion
1028 let coerce = Coerce::new(self, cause, AllowTwoPhase::No);
1029 coerce
1030 .autoderef(rustc_span::DUMMY_SP, expr_ty)
1031 .find_map(|(ty, steps)| self.probe(|_| coerce.unify(ty, target)).ok().map(|_| steps))
1032 }
1033
923072b8
FG
1034 /// Given a type, this function will calculate and return the type given
1035 /// for `<Ty as Deref>::Target` only if `Ty` also implements `DerefMut`.
1036 ///
1037 /// This function is for diagnostics only, since it does not register
1038 /// trait or region sub-obligations. (presumably we could, but it's not
1039 /// particularly important for diagnostics...)
1040 pub fn deref_once_mutably_for_diagnostic(&self, expr_ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
1041 self.autoderef(rustc_span::DUMMY_SP, expr_ty).nth(1).and_then(|(deref_ty, _)| {
1042 self.infcx
1043 .type_implements_trait(
064997fb 1044 self.tcx.lang_items().deref_mut_trait()?,
487cf647 1045 [expr_ty],
923072b8
FG
1046 self.param_env,
1047 )
1048 .may_apply()
9ffffee4 1049 .then_some(deref_ty)
923072b8
FG
1050 })
1051 }
1052
a7813a04
XL
1053 /// Given some expressions, their known unified type and another expression,
1054 /// tries to unify the types, potentially inserting coercions on any of the
1055 /// provided expressions and returns their LUB (aka "common supertype").
cc61c64b
XL
1056 ///
1057 /// This is really an internal helper. From outside the coercion
1058 /// module, you should instantiate a `CoerceMany` instance.
dfeec247
XL
1059 fn try_find_coercion_lub<E>(
1060 &self,
1061 cause: &ObligationCause<'tcx>,
1062 exprs: &[E],
1063 prev_ty: Ty<'tcx>,
1064 new: &hir::Expr<'_>,
1065 new_ty: Ty<'tcx>,
1066 ) -> RelateResult<'tcx, Ty<'tcx>>
1067 where
1068 E: AsCoercionSite,
c30ab7b3 1069 {
e74abb32
XL
1070 let prev_ty = self.resolve_vars_with_obligations(prev_ty);
1071 let new_ty = self.resolve_vars_with_obligations(new_ty);
f035d41b
XL
1072 debug!(
1073 "coercion::try_find_coercion_lub({:?}, {:?}, exprs={:?} exprs)",
1074 prev_ty,
1075 new_ty,
1076 exprs.len()
1077 );
cc61c64b 1078
c295e0f8
XL
1079 // The following check fixes #88097, where the compiler erroneously
1080 // attempted to coerce a closure type to itself via a function pointer.
1081 if prev_ty == new_ty {
1082 return Ok(prev_ty);
1083 }
1084
a7813a04 1085 // Special-case that coercion alone cannot handle:
f9f354fc
XL
1086 // Function items or non-capturing closures of differing IDs or InternalSubsts.
1087 let (a_sig, b_sig) = {
487cf647
FG
1088 let is_capturing_closure = |ty: Ty<'tcx>| {
1089 if let &ty::Closure(closure_def_id, _substs) = ty.kind() {
29967ef6 1090 self.tcx.upvars_mentioned(closure_def_id.expect_local()).is_some()
f9f354fc
XL
1091 } else {
1092 false
1093 }
1094 };
487cf647 1095 if is_capturing_closure(prev_ty) || is_capturing_closure(new_ty) {
f9f354fc
XL
1096 (None, None)
1097 } else {
5869c6ff
XL
1098 match (prev_ty.kind(), new_ty.kind()) {
1099 (ty::FnDef(..), ty::FnDef(..)) => {
f9f354fc
XL
1100 // Don't reify if the function types have a LUB, i.e., they
1101 // are the same function and their parameters have a LUB.
353b0b11
FG
1102 match self.commit_if_ok(|_| {
1103 self.at(cause, self.param_env).lub(
1104 DefineOpaqueTypes::No,
1105 prev_ty,
1106 new_ty,
1107 )
1108 }) {
f9f354fc
XL
1109 // We have a LUB of prev_ty and new_ty, just return it.
1110 Ok(ok) => return Ok(self.register_infer_ok_obligations(ok)),
1111 Err(_) => {
1112 (Some(prev_ty.fn_sig(self.tcx)), Some(new_ty.fn_sig(self.tcx)))
1113 }
1114 }
1115 }
5869c6ff 1116 (ty::Closure(_, substs), ty::FnDef(..)) => {
f9f354fc
XL
1117 let b_sig = new_ty.fn_sig(self.tcx);
1118 let a_sig = self
1119 .tcx
1120 .signature_unclosure(substs.as_closure().sig(), b_sig.unsafety());
1121 (Some(a_sig), Some(b_sig))
1122 }
5869c6ff 1123 (ty::FnDef(..), ty::Closure(_, substs)) => {
f9f354fc
XL
1124 let a_sig = prev_ty.fn_sig(self.tcx);
1125 let b_sig = self
1126 .tcx
1127 .signature_unclosure(substs.as_closure().sig(), a_sig.unsafety());
1128 (Some(a_sig), Some(b_sig))
1129 }
5869c6ff 1130 (ty::Closure(_, substs_a), ty::Closure(_, substs_b)) => (
f9f354fc
XL
1131 Some(self.tcx.signature_unclosure(
1132 substs_a.as_closure().sig(),
1133 hir::Unsafety::Normal,
1134 )),
1135 Some(self.tcx.signature_unclosure(
1136 substs_b.as_closure().sig(),
1137 hir::Unsafety::Normal,
1138 )),
1139 ),
1140 _ => (None, None),
1141 }
041b39d2 1142 }
f9f354fc
XL
1143 };
1144 if let (Some(a_sig), Some(b_sig)) = (a_sig, b_sig) {
cdc7bbd5
XL
1145 // Intrinsics are not coercible to function pointers.
1146 if a_sig.abi() == Abi::RustIntrinsic
1147 || a_sig.abi() == Abi::PlatformIntrinsic
1148 || b_sig.abi() == Abi::RustIntrinsic
1149 || b_sig.abi() == Abi::PlatformIntrinsic
1150 {
1151 return Err(TypeError::IntrinsicCast);
1152 }
041b39d2 1153 // The signature must match.
487cf647 1154 let (a_sig, b_sig) = self.normalize(new.span, (a_sig, b_sig));
dfeec247
XL
1155 let sig = self
1156 .at(cause, self.param_env)
1157 .trace(prev_ty, new_ty)
353b0b11 1158 .lub(DefineOpaqueTypes::No, a_sig, b_sig)
dfeec247 1159 .map(|ok| self.register_infer_ok_obligations(ok))?;
041b39d2
XL
1160
1161 // Reify both sides and return the reified fn pointer type.
1162 let fn_ptr = self.tcx.mk_fn_ptr(sig);
1b1a35ee 1163 let prev_adjustment = match prev_ty.kind() {
f9f354fc
XL
1164 ty::Closure(..) => Adjust::Pointer(PointerCast::ClosureFnPointer(a_sig.unsafety())),
1165 ty::FnDef(..) => Adjust::Pointer(PointerCast::ReifyFnPointer),
1166 _ => unreachable!(),
1167 };
1b1a35ee 1168 let next_adjustment = match new_ty.kind() {
f9f354fc
XL
1169 ty::Closure(..) => Adjust::Pointer(PointerCast::ClosureFnPointer(b_sig.unsafety())),
1170 ty::FnDef(..) => Adjust::Pointer(PointerCast::ReifyFnPointer),
1171 _ => unreachable!(),
1172 };
1173 for expr in exprs.iter().map(|e| e.as_coercion_site()) {
dfeec247
XL
1174 self.apply_adjustments(
1175 expr,
f9f354fc 1176 vec![Adjustment { kind: prev_adjustment.clone(), target: fn_ptr }],
dfeec247 1177 );
54a0048b 1178 }
f9f354fc 1179 self.apply_adjustments(new, vec![Adjustment { kind: next_adjustment, target: fn_ptr }]);
041b39d2 1180 return Ok(fn_ptr);
54a0048b 1181 }
54a0048b 1182
83c7162d
XL
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 let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No);
a7813a04 1189 coerce.use_lub = true;
54a0048b 1190
a7813a04
XL
1191 // First try to coerce the new expression to the type of the previous ones,
1192 // but only if the new expression has no coercion already applied to it.
1193 let mut first_error = None;
3dfed10e 1194 if !self.typeck_results.borrow().adjustments().contains_key(new.hir_id) {
7cac9316 1195 let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
a7813a04 1196 match result {
8bb4bdeb 1197 Ok(ok) => {
7cac9316
XL
1198 let (adjustments, target) = self.register_infer_ok_obligations(ok);
1199 self.apply_adjustments(new, adjustments);
f035d41b 1200 debug!(
923072b8
FG
1201 "coercion::try_find_coercion_lub: was able to coerce from new type {:?} to previous type {:?} ({:?})",
1202 new_ty, prev_ty, target
f035d41b 1203 );
7cac9316 1204 return Ok(target);
a7813a04 1205 }
c30ab7b3 1206 Err(e) => first_error = Some(e),
a7813a04 1207 }
54a0048b 1208 }
54a0048b 1209
a7813a04
XL
1210 // Then try to coerce the previous expressions to the type of the new one.
1211 // This requires ensuring there are no coercions applied to *any* of the
1212 // previous expressions, other than noop reborrows (ignoring lifetimes).
cc61c64b
XL
1213 for expr in exprs {
1214 let expr = expr.as_coercion_site();
3dfed10e 1215 let noop = match self.typeck_results.borrow().expr_adjustments(expr) {
a2a8927a
XL
1216 &[
1217 Adjustment { kind: Adjust::Deref(_), .. },
1218 Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(_, mutbl_adj)), .. },
1219 ] => {
1b1a35ee 1220 match *self.node_ty(expr.hir_id).kind() {
b7449926 1221 ty::Ref(_, _, mt_orig) => {
2c00a5a8 1222 let mutbl_adj: hir::Mutability = mutbl_adj.into();
cc61c64b 1223 // Reborrow that we can safely ignore, because
7cac9316 1224 // the next adjustment can only be a Deref
cc61c64b 1225 // which will be merged into it.
94b46f34 1226 mutbl_adj == mt_orig
c30ab7b3
SL
1227 }
1228 _ => false,
a7813a04 1229 }
c30ab7b3 1230 }
7cac9316
XL
1231 &[Adjustment { kind: Adjust::NeverToAny, .. }] | &[] => true,
1232 _ => false,
a7813a04
XL
1233 };
1234
1235 if !noop {
f035d41b
XL
1236 debug!(
1237 "coercion::try_find_coercion_lub: older expression {:?} had adjustments, requiring LUB",
1238 expr,
1239 );
1240
dfeec247 1241 return self
353b0b11
FG
1242 .commit_if_ok(|_| {
1243 self.at(cause, self.param_env).lub(DefineOpaqueTypes::No, prev_ty, new_ty)
1244 })
dfeec247 1245 .map(|ok| self.register_infer_ok_obligations(ok));
54a0048b
SL
1246 }
1247 }
a7813a04 1248
7cac9316 1249 match self.commit_if_ok(|_| coerce.coerce(prev_ty, new_ty)) {
a7813a04
XL
1250 Err(_) => {
1251 // Avoid giving strange errors on failed attempts.
1252 if let Some(e) = first_error {
1253 Err(e)
1254 } else {
353b0b11
FG
1255 self.commit_if_ok(|_| {
1256 self.at(cause, self.param_env).lub(DefineOpaqueTypes::No, prev_ty, new_ty)
1257 })
1258 .map(|ok| self.register_infer_ok_obligations(ok))
54a0048b
SL
1259 }
1260 }
8bb4bdeb 1261 Ok(ok) => {
7cac9316 1262 let (adjustments, target) = self.register_infer_ok_obligations(ok);
cc61c64b
XL
1263 for expr in exprs {
1264 let expr = expr.as_coercion_site();
7cac9316 1265 self.apply_adjustments(expr, adjustments.clone());
cc61c64b 1266 }
923072b8
FG
1267 debug!(
1268 "coercion::try_find_coercion_lub: was able to coerce previous type {:?} to new type {:?} ({:?})",
1269 prev_ty, new_ty, target
1270 );
7cac9316 1271 Ok(target)
cc61c64b
XL
1272 }
1273 }
1274 }
1275}
1276
1277/// CoerceMany encapsulates the pattern you should use when you have
1278/// many expressions that are all getting coerced to a common
1279/// type. This arises, for example, when you have a match (the result
1280/// of each arm is coerced to a common type). It also arises in less
1281/// obvious places, such as when you have many `break foo` expressions
1282/// that target the same loop, or the various `return` expressions in
1283/// a function.
1284///
1285/// The basic protocol is as follows:
1286///
1287/// - Instantiate the `CoerceMany` with an initial `expected_ty`.
1288/// This will also serve as the "starting LUB". The expectation is
1289/// that this type is something which all of the expressions *must*
1290/// be coercible to. Use a fresh type variable if needed.
1291/// - For each expression whose result is to be coerced, invoke `coerce()` with.
1292/// - In some cases we wish to coerce "non-expressions" whose types are implicitly
1293/// unit. This happens for example if you have a `break` with no expression,
1294/// or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
1295/// - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
1296/// from you so that you don't have to worry your pretty head about it.
1297/// But if an error is reported, the final type will be `err`.
1298/// - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
1299/// previously coerced expressions.
1300/// - When all done, invoke `complete()`. This will return the LUB of
1301/// all your expressions.
1302/// - WARNING: I don't believe this final type is guaranteed to be
1303/// related to your initial `expected_ty` in any particular way,
1304/// although it will typically be a subtype, so you should check it.
1305/// - Invoking `complete()` may cause us to go and adjust the "adjustments" on
1306/// previously coerced expressions.
1307///
1308/// Example:
1309///
04454e1e 1310/// ```ignore (illustrative)
cc61c64b
XL
1311/// let mut coerce = CoerceMany::new(expected_ty);
1312/// for expr in exprs {
1313/// let expr_ty = fcx.check_expr_with_expectation(expr, expected);
1314/// coerce.coerce(fcx, &cause, expr, expr_ty);
1315/// }
1316/// let final_ty = coerce.complete(fcx);
1317/// ```
dc9dc135 1318pub struct CoerceMany<'tcx, 'exprs, E: AsCoercionSite> {
cc61c64b
XL
1319 expected_ty: Ty<'tcx>,
1320 final_ty: Option<Ty<'tcx>>,
dc9dc135 1321 expressions: Expressions<'tcx, 'exprs, E>,
cc61c64b
XL
1322 pushed: usize,
1323}
1324
1325/// The type of a `CoerceMany` that is storing up the expressions into
1326/// a buffer. We use this in `check/mod.rs` for things like `break`.
dfeec247 1327pub type DynamicCoerceMany<'tcx> = CoerceMany<'tcx, 'tcx, &'tcx hir::Expr<'tcx>>;
cc61c64b 1328
dc9dc135 1329enum Expressions<'tcx, 'exprs, E: AsCoercionSite> {
dfeec247 1330 Dynamic(Vec<&'tcx hir::Expr<'tcx>>),
cc61c64b
XL
1331 UpFront(&'exprs [E]),
1332}
1333
dc9dc135 1334impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
cc61c64b
XL
1335 /// The usual case; collect the set of expressions dynamically.
1336 /// If the full set of coercion sites is known before hand,
1337 /// consider `with_coercion_sites()` instead to avoid allocation.
1338 pub fn new(expected_ty: Ty<'tcx>) -> Self {
1339 Self::make(expected_ty, Expressions::Dynamic(vec![]))
1340 }
1341
1342 /// As an optimization, you can create a `CoerceMany` with a
1343 /// pre-existing slice of expressions. In this case, you are
1344 /// expected to pass each element in the slice to `coerce(...)` in
1345 /// order. This is used with arrays in particular to avoid
1346 /// needlessly cloning the slice.
dfeec247 1347 pub fn with_coercion_sites(expected_ty: Ty<'tcx>, coercion_sites: &'exprs [E]) -> Self {
cc61c64b
XL
1348 Self::make(expected_ty, Expressions::UpFront(coercion_sites))
1349 }
1350
dc9dc135 1351 fn make(expected_ty: Ty<'tcx>, expressions: Expressions<'tcx, 'exprs, E>) -> Self {
dfeec247 1352 CoerceMany { expected_ty, final_ty: None, expressions, pushed: 0 }
cc61c64b
XL
1353 }
1354
9fa01778
XL
1355 /// Returns the "expected type" with which this coercion was
1356 /// constructed. This represents the "downward propagated" type
cc61c64b
XL
1357 /// that was given to us at the start of typing whatever construct
1358 /// we are typing (e.g., the match expression).
1359 ///
1360 /// Typically, this is used as the expected type when
1361 /// type-checking each of the alternative expressions whose types
1362 /// we are trying to merge.
1363 pub fn expected_ty(&self) -> Ty<'tcx> {
1364 self.expected_ty
1365 }
1366
1367 /// Returns the current "merged type", representing our best-guess
1368 /// at the LUB of the expressions we've seen so far (if any). This
5e7ed085 1369 /// isn't *final* until you call `self.complete()`, which will return
cc61c64b
XL
1370 /// the merged type.
1371 pub fn merged_ty(&self) -> Ty<'tcx> {
1372 self.final_ty.unwrap_or(self.expected_ty)
1373 }
1374
1375 /// Indicates that the value generated by `expression`, which is
0bf4aa26
XL
1376 /// of type `expression_ty`, is one of the possibilities that we
1377 /// could coerce from. This will record `expression`, and later
cc61c64b
XL
1378 /// calls to `coerce` may come back and add adjustments and things
1379 /// if necessary.
dc9dc135
XL
1380 pub fn coerce<'a>(
1381 &mut self,
1382 fcx: &FnCtxt<'a, 'tcx>,
1383 cause: &ObligationCause<'tcx>,
dfeec247 1384 expression: &'tcx hir::Expr<'tcx>,
dc9dc135
XL
1385 expression_ty: Ty<'tcx>,
1386 ) {
dfeec247 1387 self.coerce_inner(fcx, cause, Some(expression), expression_ty, None, false)
cc61c64b
XL
1388 }
1389
1390 /// Indicates that one of the inputs is a "forced unit". This
3b2f2976 1391 /// occurs in a case like `if foo { ... };`, where the missing else
cc61c64b
XL
1392 /// generates a "forced unit". Another example is a `loop { break;
1393 /// }`, where the `break` has no argument expression. We treat
1394 /// these cases slightly differently for error-reporting
1395 /// purposes. Note that these tend to correspond to cases where
1396 /// the `()` expression is implicit in the source, and hence we do
1397 /// not take an expression argument.
1398 ///
1399 /// The `augment_error` gives you a chance to extend the error
1400 /// message, in case any results (e.g., we use this to suggest
1401 /// removing a `;`).
dc9dc135
XL
1402 pub fn coerce_forced_unit<'a>(
1403 &mut self,
1404 fcx: &FnCtxt<'a, 'tcx>,
1405 cause: &ObligationCause<'tcx>,
5e7ed085 1406 augment_error: &mut dyn FnMut(&mut Diagnostic),
dc9dc135
XL
1407 label_unit_as_expected: bool,
1408 ) {
dfeec247
XL
1409 self.coerce_inner(
1410 fcx,
1411 cause,
1412 None,
1413 fcx.tcx.mk_unit(),
1414 Some(augment_error),
1415 label_unit_as_expected,
1416 )
cc61c64b
XL
1417 }
1418
1419 /// The inner coercion "engine". If `expression` is `None`, this
1420 /// is a forced-unit case, and hence `expression_ty` must be
1421 /// `Nil`.
94222f64 1422 #[instrument(skip(self, fcx, augment_error, label_expression_as_expected), level = "debug")]
923072b8 1423 pub(crate) fn coerce_inner<'a>(
dc9dc135
XL
1424 &mut self,
1425 fcx: &FnCtxt<'a, 'tcx>,
1426 cause: &ObligationCause<'tcx>,
dfeec247 1427 expression: Option<&'tcx hir::Expr<'tcx>>,
dc9dc135 1428 mut expression_ty: Ty<'tcx>,
5e7ed085 1429 augment_error: Option<&mut dyn FnMut(&mut Diagnostic)>,
dc9dc135
XL
1430 label_expression_as_expected: bool,
1431 ) {
cc61c64b
XL
1432 // Incorporate whatever type inference information we have
1433 // until now; in principle we might also want to process
1434 // pending obligations, but doing so should only improve
1435 // compatibility (hopefully that is true) by helping us
1436 // uncover never types better.
1437 if expression_ty.is_ty_var() {
1438 expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1439 }
1440
1441 // If we see any error types, just propagate that error
1442 // upwards.
9ffffee4
FG
1443 if let Err(guar) = (expression_ty, self.merged_ty()).error_reported() {
1444 self.final_ty = Some(fcx.tcx.ty_error(guar));
cc61c64b
XL
1445 return;
1446 }
1447
1448 // Handle the actual type unification etc.
1449 let result = if let Some(expression) = expression {
1450 if self.pushed == 0 {
1451 // Special-case the first expression we are coercing.
1452 // To be honest, I'm not entirely sure why we do this.
83c7162d 1453 // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
c295e0f8
XL
1454 fcx.try_coerce(
1455 expression,
1456 expression_ty,
1457 self.expected_ty,
1458 AllowTwoPhase::No,
1459 Some(cause.clone()),
1460 )
cc61c64b
XL
1461 } else {
1462 match self.expressions {
e74abb32
XL
1463 Expressions::Dynamic(ref exprs) => fcx.try_find_coercion_lub(
1464 cause,
1465 exprs,
1466 self.merged_ty(),
1467 expression,
1468 expression_ty,
1469 ),
1470 Expressions::UpFront(ref coercion_sites) => fcx.try_find_coercion_lub(
1471 cause,
1472 &coercion_sites[0..self.pushed],
1473 self.merged_ty(),
1474 expression,
1475 expression_ty,
1476 ),
cc61c64b
XL
1477 }
1478 }
1479 } else {
1480 // this is a hack for cases where we default to `()` because
1481 // the expression etc has been omitted from the source. An
1482 // example is an `if let` without an else:
1483 //
1484 // if let Some(x) = ... { }
1485 //
1486 // we wind up with a second match arm that is like `_ =>
9c376795 1487 // ()`. That is the case we are considering here. We take
cc61c64b
XL
1488 // a different path to get the right "expected, found"
1489 // message and so forth (and because we know that
1490 // `expression_ty` will be unit).
1491 //
1492 // Another example is `break` with no argument expression.
b7449926 1493 assert!(expression_ty.is_unit(), "if let hack without unit type");
7cac9316 1494 fcx.at(cause, fcx.param_env)
9ffffee4 1495 // needed for tests/ui/type-alias-impl-trait/issue-65679-inst-opaque-ty-from-val-twice.rs
353b0b11
FG
1496 .eq_exp(
1497 DefineOpaqueTypes::Yes,
1498 label_expression_as_expected,
1499 expression_ty,
1500 self.merged_ty(),
1501 )
dfeec247
XL
1502 .map(|infer_ok| {
1503 fcx.register_infer_ok_obligations(infer_ok);
1504 expression_ty
1505 })
cc61c64b
XL
1506 };
1507
923072b8 1508 debug!(?result);
cc61c64b
XL
1509 match result {
1510 Ok(v) => {
1511 self.final_ty = Some(v);
1512 if let Some(e) = expression {
1513 match self.expressions {
1514 Expressions::Dynamic(ref mut buffer) => buffer.push(e),
1515 Expressions::UpFront(coercion_sites) => {
1516 // if the user gave us an array to validate, check that we got
1517 // the next expression in the list, as expected
dfeec247
XL
1518 assert_eq!(
1519 coercion_sites[self.pushed].as_coercion_site().hir_id,
1520 e.hir_id
1521 );
5bcae85e 1522 }
a7813a04 1523 }
cc61c64b 1524 self.pushed += 1;
a7813a04 1525 }
cc61c64b 1526 }
e74abb32 1527 Err(coercion_error) => {
f2b60f7d
FG
1528 // Mark that we've failed to coerce the types here to suppress
1529 // any superfluous errors we might encounter while trying to
1530 // emit or provide suggestions on how to fix the initial error.
487cf647
FG
1531 fcx.set_tainted_by_errors(
1532 fcx.tcx.sess.delay_span_bug(cause.span, "coercion error but no error emitted"),
1533 );
7cac9316 1534 let (expected, found) = if label_expression_as_expected {
cc61c64b
XL
1535 // In the case where this is a "forced unit", like
1536 // `break`, we want to call the `()` "expected"
1537 // since it is implied by the syntax.
7cac9316 1538 // (Note: not all force-units work this way.)"
f2b60f7d 1539 (expression_ty, self.merged_ty())
cc61c64b
XL
1540 } else {
1541 // Otherwise, the "expected" type for error
1542 // reporting is the current unification type,
1543 // which is basically the LUB of the expressions
1544 // we've seen so far (combined with the expected
1545 // type)
f2b60f7d 1546 (self.merged_ty(), expression_ty)
cc61c64b 1547 };
f2b60f7d 1548 let (expected, found) = fcx.resolve_vars_if_possible((expected, found));
cc61c64b 1549
e74abb32 1550 let mut err;
dfeec247 1551 let mut unsized_return = false;
f2b60f7d 1552 let mut visitor = CollectRetsVisitor { ret_exprs: vec![] };
a2a8927a 1553 match *cause.code() {
cc61c64b 1554 ObligationCauseCode::ReturnNoExpression => {
e74abb32 1555 err = struct_span_err!(
dfeec247
XL
1556 fcx.tcx.sess,
1557 cause.span,
1558 E0069,
1559 "`return;` in a function whose return type is not `()`"
1560 );
e74abb32 1561 err.span_label(cause.span, "return type is not `()`");
cc61c64b 1562 }
041b39d2 1563 ObligationCauseCode::BlockTailExpression(blk_id) => {
9c376795 1564 let parent_id = fcx.tcx.hir().parent_id(blk_id);
e74abb32 1565 err = self.report_return_mismatched_types(
9fa01778 1566 cause,
8faf50e0
XL
1567 expected,
1568 found,
9c376795 1569 coercion_error,
9fa01778
XL
1570 fcx,
1571 parent_id,
923072b8
FG
1572 expression,
1573 Some(blk_id),
8faf50e0 1574 );
dfeec247
XL
1575 if !fcx.tcx.features().unsized_locals {
1576 unsized_return = self.is_return_ty_unsized(fcx, blk_id);
1577 }
f2b60f7d
FG
1578 if let Some(expression) = expression
1579 && let hir::ExprKind::Loop(loop_blk, ..) = expression.kind {
1580 intravisit::walk_block(& mut visitor, loop_blk);
1581 }
9fa01778 1582 }
e74abb32
XL
1583 ObligationCauseCode::ReturnValue(id) => {
1584 err = self.report_return_mismatched_types(
dfeec247
XL
1585 cause,
1586 expected,
1587 found,
9c376795 1588 coercion_error,
dfeec247
XL
1589 fcx,
1590 id,
923072b8 1591 expression,
dfeec247
XL
1592 None,
1593 );
1594 if !fcx.tcx.features().unsized_locals {
9c376795 1595 let id = fcx.tcx.hir().parent_id(id);
dfeec247
XL
1596 unsized_return = self.is_return_ty_unsized(fcx, id);
1597 }
041b39d2 1598 }
cc61c64b 1599 _ => {
2b03887a 1600 err = fcx.err_ctxt().report_mismatched_types(
3c0e092e
XL
1601 cause,
1602 expected,
1603 found,
9c376795 1604 coercion_error,
3c0e092e 1605 );
cc61c64b
XL
1606 }
1607 }
1608
3b2f2976 1609 if let Some(augment_error) = augment_error {
e74abb32 1610 augment_error(&mut err);
cc61c64b
XL
1611 }
1612
923072b8
FG
1613 let is_insufficiently_polymorphic =
1614 matches!(coercion_error, TypeError::RegionsInsufficientlyPolymorphic(..));
1615
1616 if !is_insufficiently_polymorphic && let Some(expr) = expression {
3c0e092e
XL
1617 fcx.emit_coerce_suggestions(
1618 &mut err,
1619 expr,
1620 found,
1621 expected,
1622 None,
04454e1e 1623 Some(coercion_error),
3c0e092e 1624 );
60c5eb7d
XL
1625 }
1626
f2b60f7d
FG
1627 if visitor.ret_exprs.len() > 0 && let Some(expr) = expression {
1628 self.note_unreachable_loop_return(&mut err, &expr, &visitor.ret_exprs);
1629 }
9ffffee4 1630
487cf647 1631 let reported = err.emit_unless(unsized_return);
cc61c64b 1632
9ffffee4 1633 self.final_ty = Some(fcx.tcx.ty_error(reported));
a7813a04 1634 }
54a0048b 1635 }
1a4d82fc 1636 }
9ffffee4 1637
f2b60f7d
FG
1638 fn note_unreachable_loop_return(
1639 &self,
1640 err: &mut Diagnostic,
1641 expr: &hir::Expr<'tcx>,
1642 ret_exprs: &Vec<&'tcx hir::Expr<'tcx>>,
1643 ) {
1644 let hir::ExprKind::Loop(_, _, _, loop_span) = expr.kind else { return;};
1645 let mut span: MultiSpan = vec![loop_span].into();
1646 span.push_span_label(loop_span, "this might have zero elements to iterate on");
1647 const MAXITER: usize = 3;
1648 let iter = ret_exprs.iter().take(MAXITER);
1649 for ret_expr in iter {
1650 span.push_span_label(
1651 ret_expr.span,
1652 "if the loop doesn't execute, this value would never get returned",
1653 );
1654 }
1655 err.span_note(
1656 span,
1657 "the function expects a value to always be returned, but loops might run zero times",
1658 );
1659 if MAXITER < ret_exprs.len() {
1660 err.note(&format!(
1661 "if the loop doesn't execute, {} other values would never get returned",
1662 ret_exprs.len() - MAXITER
1663 ));
1664 }
1665 err.help(
1666 "return a value for the case when the loop has zero elements to iterate on, or \
1667 consider changing the return type to account for that possibility",
1668 );
1669 }
cc61c64b 1670
9fa01778
XL
1671 fn report_return_mismatched_types<'a>(
1672 &self,
1673 cause: &ObligationCause<'tcx>,
1674 expected: Ty<'tcx>,
1675 found: Ty<'tcx>,
e74abb32 1676 ty_err: TypeError<'tcx>,
dc9dc135 1677 fcx: &FnCtxt<'a, 'tcx>,
532ac7d7 1678 id: hir::HirId,
923072b8
FG
1679 expression: Option<&'tcx hir::Expr<'tcx>>,
1680 blk_id: Option<hir::HirId>,
5e7ed085 1681 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
2b03887a 1682 let mut err = fcx.err_ctxt().report_mismatched_types(cause, expected, found, ty_err);
9fa01778
XL
1683
1684 let mut pointing_at_return_type = false;
dfeec247 1685 let mut fn_output = None;
9fa01778 1686
9c376795 1687 let parent_id = fcx.tcx.hir().parent_id(id);
923072b8
FG
1688 let parent = fcx.tcx.hir().get(parent_id);
1689 if let Some(expr) = expression
064997fb
FG
1690 && let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(&hir::Closure { body, .. }), .. }) = parent
1691 && !matches!(fcx.tcx.hir().body(body).value.kind, hir::ExprKind::Block(..))
923072b8
FG
1692 {
1693 fcx.suggest_missing_semicolon(&mut err, expr, expected, true);
1694 }
9fa01778
XL
1695 // Verify that this is a tail expression of a function, otherwise the
1696 // label pointing out the cause for the type coercion will be wrong
1697 // as prior return coercions would not be relevant (#57664).
923072b8 1698 let fn_decl = if let (Some(expr), Some(blk_id)) = (expression, blk_id) {
cdc7bbd5
XL
1699 pointing_at_return_type =
1700 fcx.suggest_mismatched_types_on_tail(&mut err, expr, expected, found, blk_id);
5869c6ff
XL
1701 if let (Some(cond_expr), true, false) = (
1702 fcx.tcx.hir().get_if_cause(expr.hir_id),
e74abb32
XL
1703 expected.is_unit(),
1704 pointing_at_return_type,
04454e1e 1705 )
136023e0
XL
1706 // If the block is from an external macro or try (`?`) desugaring, then
1707 // do not suggest adding a semicolon, because there's nowhere to put it.
1708 // See issues #81943 and #87051.
04454e1e 1709 && matches!(
c295e0f8
XL
1710 cond_expr.span.desugaring_kind(),
1711 None | Some(DesugaringKind::WhileLoop)
1712 ) && !in_external_macro(fcx.tcx.sess, cond_expr.span)
136023e0
XL
1713 && !matches!(
1714 cond_expr.kind,
1715 hir::ExprKind::Match(.., hir::MatchSource::TryDesugar)
1716 )
04454e1e
FG
1717 {
1718 err.span_label(cond_expr.span, "expected this to be `()`");
1719 if expr.can_have_side_effects() {
1720 fcx.suggest_semicolon_at_end(cond_expr.span, &mut err);
e74abb32
XL
1721 }
1722 }
353b0b11
FG
1723 fcx.get_node_fn_decl(parent)
1724 .map(|(fn_id, fn_decl, _, is_main)| (fn_id, fn_decl, is_main))
9fa01778
XL
1725 } else {
1726 fcx.get_fn_decl(parent_id)
1727 };
1728
353b0b11 1729 if let Some((fn_id, fn_decl, can_suggest)) = fn_decl {
923072b8 1730 if blk_id.is_none() {
9fa01778 1731 pointing_at_return_type |= fcx.suggest_missing_return_type(
dfeec247
XL
1732 &mut err,
1733 &fn_decl,
1734 expected,
1735 found,
1736 can_suggest,
353b0b11 1737 fn_id,
dfeec247 1738 );
9fa01778
XL
1739 }
1740 if !pointing_at_return_type {
dfeec247 1741 fn_output = Some(&fn_decl.output); // `impl Trait` return type
9fa01778
XL
1742 }
1743 }
6a06907d
XL
1744
1745 let parent_id = fcx.tcx.hir().get_parent_item(id);
2b03887a 1746 let parent_item = fcx.tcx.hir().get_by_def_id(parent_id.def_id);
6a06907d 1747
353b0b11 1748 if let (Some(expr), Some(_), Some((fn_id, fn_decl, _, _))) =
923072b8 1749 (expression, blk_id, fcx.get_node_fn_decl(parent_item))
6a06907d 1750 {
cdc7bbd5 1751 fcx.suggest_missing_break_or_return_expr(
353b0b11 1752 &mut err, expr, fn_decl, expected, found, id, fn_id,
cdc7bbd5 1753 );
6a06907d
XL
1754 }
1755
f2b60f7d
FG
1756 let ret_coercion_span = fcx.ret_coercion_span.get();
1757
1758 if let Some(sp) = ret_coercion_span
1759 // If the closure has an explicit return type annotation, or if
1760 // the closure's return type has been inferred from outside
1761 // requirements (such as an Fn* trait bound), then a type error
1762 // may occur at the first return expression we see in the closure
1763 // (if it conflicts with the declared return type). Skip adding a
1764 // note in this case, since it would be incorrect.
487cf647
FG
1765 && let Some(fn_sig) = fcx.body_fn_sig()
1766 && fn_sig.output().is_ty_var()
f2b60f7d
FG
1767 {
1768 err.span_note(
1769 sp,
1770 &format!(
1771 "return type inferred to be `{}` here",
1772 expected
1773 ),
1774 );
1775 }
1776
1777 if let (Some(sp), Some(fn_output)) = (ret_coercion_span, fn_output) {
5869c6ff 1778 self.add_impl_trait_explanation(&mut err, cause, fcx, expected, sp, fn_output);
9fa01778 1779 }
f2b60f7d 1780
e74abb32 1781 err
9fa01778
XL
1782 }
1783
dfeec247
XL
1784 fn add_impl_trait_explanation<'a>(
1785 &self,
5e7ed085 1786 err: &mut Diagnostic,
1b1a35ee 1787 cause: &ObligationCause<'tcx>,
dfeec247
XL
1788 fcx: &FnCtxt<'a, 'tcx>,
1789 expected: Ty<'tcx>,
1790 sp: Span,
74b04a01 1791 fn_output: &hir::FnRetTy<'_>,
dfeec247
XL
1792 ) {
1793 let return_sp = fn_output.span();
1794 err.span_label(return_sp, "expected because this return type...");
1795 err.span_label(
1796 sp,
1797 format!("...is found to be `{}` here", fcx.resolve_vars_with_obligations(expected)),
1798 );
1799 let impl_trait_msg = "for information on `impl Trait`, see \
1800 <https://doc.rust-lang.org/book/ch10-02-traits.html\
1801 #returning-types-that-implement-traits>";
1802 let trait_obj_msg = "for information on trait objects, see \
1803 <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\
1804 #using-trait-objects-that-allow-for-values-of-different-types>";
1805 err.note("to return `impl Trait`, all returned values must be of the same type");
1806 err.note(impl_trait_msg);
1807 let snippet = fcx
1808 .tcx
1809 .sess
1810 .source_map()
1811 .span_to_snippet(return_sp)
1812 .unwrap_or_else(|_| "dyn Trait".to_string());
1813 let mut snippet_iter = snippet.split_whitespace();
1814 let has_impl = snippet_iter.next().map_or(false, |s| s == "impl");
1815 // Only suggest `Box<dyn Trait>` if `Trait` in `impl Trait` is object safe.
1816 let mut is_object_safe = false;
04454e1e 1817 if let hir::FnRetTy::Return(ty) = fn_output
dfeec247 1818 // Get the return type.
04454e1e
FG
1819 && let hir::TyKind::OpaqueDef(..) = ty.kind
1820 {
9c376795 1821 let ty = fcx.astconv().ast_ty_to_ty( ty);
04454e1e 1822 // Get the `impl Trait`'s `DefId`.
9c376795 1823 if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) = ty.kind()
04454e1e
FG
1824 // Get the `impl Trait`'s `Item` so that we can get its trait bounds and
1825 // get the `Trait`'s `DefId`.
1826 && let hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds, .. }) =
1827 fcx.tcx.hir().expect_item(def_id.expect_local()).kind
1828 {
1829 // Are of this `impl Trait`'s traits object safe?
1830 is_object_safe = bounds.iter().all(|bound| {
1831 bound
1832 .trait_ref()
1833 .and_then(|t| t.trait_def_id())
1834 .map_or(false, |def_id| {
9ffffee4 1835 fcx.tcx.check_is_object_safe(def_id)
dfeec247 1836 })
04454e1e 1837 })
dfeec247
XL
1838 }
1839 };
1840 if has_impl {
1841 if is_object_safe {
1b1a35ee
XL
1842 err.multipart_suggestion(
1843 "you could change the return type to be a boxed trait object",
1844 vec![
1845 (return_sp.with_hi(return_sp.lo() + BytePos(4)), "Box<dyn".to_string()),
1846 (return_sp.shrink_to_hi(), ">".to_string()),
1847 ],
1848 Applicability::MachineApplicable,
1849 );
5099ac24 1850 let sugg = [sp, cause.span]
1b1a35ee
XL
1851 .into_iter()
1852 .flat_map(|sp| {
5099ac24 1853 [
1b1a35ee
XL
1854 (sp.shrink_to_lo(), "Box::new(".to_string()),
1855 (sp.shrink_to_hi(), ")".to_string()),
1856 ]
1857 .into_iter()
1858 })
1859 .collect::<Vec<_>>();
1860 err.multipart_suggestion(
1861 "if you change the return type to expect trait objects, box the returned \
1862 expressions",
1863 sugg,
1864 Applicability::MaybeIncorrect,
1865 );
dfeec247
XL
1866 } else {
1867 err.help(&format!(
1868 "if the trait `{}` were object safe, you could return a boxed trait object",
1869 &snippet[5..]
1870 ));
1871 }
1872 err.note(trait_obj_msg);
1873 }
1b1a35ee 1874 err.help("you could instead create a new `enum` with a variant for each returned type");
dfeec247
XL
1875 }
1876
a2a8927a 1877 fn is_return_ty_unsized<'a>(&self, fcx: &FnCtxt<'a, 'tcx>, blk_id: hir::HirId) -> bool {
353b0b11 1878 if let Some((_, fn_decl, _)) = fcx.get_fn_decl(blk_id)
5e7ed085 1879 && let hir::FnRetTy::Return(ty) = fn_decl.output
9c376795 1880 && let ty = fcx.astconv().ast_ty_to_ty( ty)
5e7ed085
FG
1881 && let ty::Dynamic(..) = ty.kind()
1882 {
04454e1e 1883 return true;
dfeec247
XL
1884 }
1885 false
1886 }
1887
dc9dc135 1888 pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> {
cc61c64b
XL
1889 if let Some(final_ty) = self.final_ty {
1890 final_ty
1891 } else {
1892 // If we only had inputs that were of type `!` (or no
1893 // inputs at all), then the final type is `!`.
1894 assert_eq!(self.pushed, 0);
1895 fcx.tcx.types.never
1896 }
1897 }
1898}
1899
1900/// Something that can be converted into an expression to which we can
1901/// apply a coercion.
1902pub trait AsCoercionSite {
dfeec247 1903 fn as_coercion_site(&self) -> &hir::Expr<'_>;
cc61c64b
XL
1904}
1905
dfeec247
XL
1906impl AsCoercionSite for hir::Expr<'_> {
1907 fn as_coercion_site(&self) -> &hir::Expr<'_> {
cc61c64b
XL
1908 self
1909 }
1910}
1911
1912impl<'a, T> AsCoercionSite for &'a T
dfeec247
XL
1913where
1914 T: AsCoercionSite,
cc61c64b 1915{
dfeec247 1916 fn as_coercion_site(&self) -> &hir::Expr<'_> {
cc61c64b
XL
1917 (**self).as_coercion_site()
1918 }
1919}
1920
1921impl AsCoercionSite for ! {
dfeec247 1922 fn as_coercion_site(&self) -> &hir::Expr<'_> {
cc61c64b
XL
1923 unreachable!()
1924 }
1925}
1926
dfeec247
XL
1927impl AsCoercionSite for hir::Arm<'_> {
1928 fn as_coercion_site(&self) -> &hir::Expr<'_> {
cc61c64b
XL
1929 &self.body
1930 }
1a4d82fc 1931}