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//! ```
3738use std::ops::{ControlFlow, Deref};
3940use rustc_errors::codes::*;
41use rustc_errors::{Applicability, Diag, struct_span_code_err};
42use rustc_hir::attrs::InlineAttr;
43use rustc_hir::def_id::{DefId, LocalDefId};
44use rustc_hir::{selfas hir, LangItem};
45use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer;
46use rustc_infer::infer::relate::RelateResult;
47use rustc_infer::infer::{DefineOpaqueTypes, InferOk, InferResult, RegionVariableOrigin};
48use rustc_infer::traits::{
49MatchExpressionArmCause, Obligation, PredicateObligation, PredicateObligations, SelectionError,
50};
51use rustc_middle::span_bug;
52use rustc_middle::ty::adjustment::{
53Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, DerefAdjustKind,
54PointerCoercion,
55};
56use rustc_middle::ty::error::TypeError;
57use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt};
58use rustc_span::{BytePos, DUMMY_SP, Span};
59use rustc_trait_selection::infer::InferCtxtExt as _;
60use rustc_trait_selection::solve::inspect::{self, InferCtxtProofTreeExt, ProofTreeVisitor};
61use rustc_trait_selection::solve::{Certainty, Goal, NoSolution};
62use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
63use rustc_trait_selection::traits::{
64self, ImplSource, NormalizeExt, ObligationCause, ObligationCauseCode, ObligationCtxt,
65};
66use smallvec::{SmallVec, smallvec};
67use tracing::{debug, instrument};
6869use crate::FnCtxt;
70use crate::errors::SuggestBoxingForReturnImplTrait;
7172struct Coerce<'a, 'tcx> {
73 fcx: &'a FnCtxt<'a, 'tcx>,
74 cause: ObligationCause<'tcx>,
75 use_lub: bool,
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
82allow_two_phase: AllowTwoPhase,
83/// Whether we allow `NeverToAny` coercions. This is unsound if we're
84 /// coercing a place expression without it counting as a read in the MIR.
85 /// This is a side-effect of HIR not really having a great distinction
86 /// between places and values.
87coerce_never: bool,
88}
8990impl<'a, 'tcx> Dereffor Coerce<'a, 'tcx> {
91type Target = FnCtxt<'a, 'tcx>;
92fn deref(&self) -> &Self::Target {
93self.fcx
94 }
95}
9697type CoerceResult<'tcx> = InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>;
9899/// Coercing a mutable reference to an immutable works, while
100/// coercing `&T` to `&mut T` should be forbidden.
101fn coerce_mutbls<'tcx>(
102 from_mutbl: hir::Mutability,
103 to_mutbl: hir::Mutability,
104) -> RelateResult<'tcx, ()> {
105if from_mutbl >= to_mutbl { Ok(()) } else { Err(TypeError::Mutability) }
106}
107108/// This always returns `Ok(...)`.
109fn success<'tcx>(
110 adj: Vec<Adjustment<'tcx>>,
111 target: Ty<'tcx>,
112 obligations: PredicateObligations<'tcx>,
113) -> CoerceResult<'tcx> {
114Ok(InferOk { value: (adj, target), obligations })
115}
116117/// Whether to force a leak check to occur in `Coerce::unify_raw`.
118/// Note that leak checks may still occur evn with `ForceLeakCheck::No`.
119///
120/// FIXME: We may want to change type relations to always leak-check
121/// after exiting a binder, at which point we will always do so and
122/// no longer need to handle this explicitly
123enum ForceLeakCheck {
124 Yes,
125 No,
126}
127128impl<'f, 'tcx> Coerce<'f, 'tcx> {
129fn new(
130 fcx: &'f FnCtxt<'f, 'tcx>,
131 cause: ObligationCause<'tcx>,
132 allow_two_phase: AllowTwoPhase,
133 coerce_never: bool,
134 ) -> Self {
135Coerce { fcx, cause, allow_two_phase, use_lub: false, coerce_never }
136 }
137138fn unify_raw(
139&self,
140 a: Ty<'tcx>,
141 b: Ty<'tcx>,
142 leak_check: ForceLeakCheck,
143 ) -> InferResult<'tcx, Ty<'tcx>> {
144{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:144",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(144u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("unify(a: {0:?}, b: {1:?}, use_lub: {2})",
a, b, self.use_lub) as &dyn Value))])
});
} else { ; }
};debug!("unify(a: {:?}, b: {:?}, use_lub: {})", a, b, self.use_lub);
145self.commit_if_ok(|snapshot| {
146let outer_universe = self.infcx.universe();
147148let at = self.at(&self.cause, self.fcx.param_env);
149150let res = if self.use_lub {
151at.lub(b, a)
152 } else {
153at.sup(DefineOpaqueTypes::Yes, b, a)
154 .map(|InferOk { value: (), obligations }| InferOk { value: b, obligations })
155 };
156157// In the new solver, lazy norm may allow us to shallowly equate
158 // more types, but we emit possibly impossible-to-satisfy obligations.
159 // Filter these cases out to make sure our coercion is more accurate.
160let res = match res {
161Ok(InferOk { value, obligations }) if self.next_trait_solver() => {
162let ocx = ObligationCtxt::new(self);
163ocx.register_obligations(obligations);
164if ocx.try_evaluate_obligations().is_empty() {
165Ok(InferOk { value, obligations: ocx.into_pending_obligations() })
166 } else {
167Err(TypeError::Mismatch)
168 }
169 }
170 res => res,
171 };
172173// We leak check here mostly because lub operations are
174 // kind of scuffed around binders. Instead of computing an actual
175 // lub'd binder we instead:
176 // - Equate the binders
177 // - Return the lhs of the lub operation
178 //
179 // This may lead to incomplete type inference for the resulting type
180 // of a `match` or `if .. else`, etc. This is a backwards compat
181 // hazard for if/when we start handling `lub` more correctly.
182 //
183 // In order to actually ensure that equating the binders *does*
184 // result in equal binders, and that the lhs is actually a supertype
185 // of the rhs, we must perform a leak check here.
186if #[allow(non_exhaustive_omitted_patterns)] match leak_check {
ForceLeakCheck::Yes => true,
_ => false,
}matches!(leak_check, ForceLeakCheck::Yes) {
187self.leak_check(outer_universe, Some(snapshot))?;
188 }
189190res191 })
192 }
193194/// Unify two types (using sub or lub).
195fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>, leak_check: ForceLeakCheck) -> CoerceResult<'tcx> {
196self.unify_raw(a, b, leak_check)
197 .and_then(|InferOk { value: ty, obligations }| success(::alloc::vec::Vec::new()vec![], ty, obligations))
198 }
199200/// Unify two types (using sub or lub) and produce a specific coercion.
201fn unify_and(
202&self,
203 a: Ty<'tcx>,
204 b: Ty<'tcx>,
205 adjustments: impl IntoIterator<Item = Adjustment<'tcx>>,
206 final_adjustment: Adjust,
207 leak_check: ForceLeakCheck,
208 ) -> CoerceResult<'tcx> {
209self.unify_raw(a, b, leak_check).and_then(|InferOk { value: ty, obligations }| {
210success(
211adjustments212 .into_iter()
213 .chain(std::iter::once(Adjustment { target: ty, kind: final_adjustment }))
214 .collect(),
215ty,
216obligations,
217 )
218 })
219 }
220221x;#[instrument(skip(self), ret)]222fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
223// First, remove any resolved type variables (at the top level, at least):
224let a = self.shallow_resolve(a);
225let b = self.shallow_resolve(b);
226debug!("Coerce.tys({:?} => {:?})", a, b);
227228// Coercing from `!` to any type is allowed:
229if a.is_never() {
230if self.coerce_never {
231return success(
232vec![Adjustment { kind: Adjust::NeverToAny, target: b }],
233 b,
234 PredicateObligations::new(),
235 );
236 } else {
237// Otherwise the only coercion we can do is unification.
238return self.unify(a, b, ForceLeakCheck::No);
239 }
240 }
241242// Coercing *from* an unresolved inference variable means that
243 // we have no information about the source type. This will always
244 // ultimately fall back to some form of subtyping.
245if a.is_ty_var() {
246return self.coerce_from_inference_variable(a, b);
247 }
248249// Consider coercing the subtype to a DST
250 //
251 // NOTE: this is wrapped in a `commit_if_ok` because it creates
252 // a "spurious" type variable, and we don't want to have that
253 // type variable in memory if the coercion fails.
254let unsize = self.commit_if_ok(|_| self.coerce_unsized(a, b));
255match unsize {
256Ok(_) => {
257debug!("coerce: unsize successful");
258return unsize;
259 }
260Err(error) => {
261debug!(?error, "coerce: unsize failed");
262 }
263 }
264265// Examine the target type and consider type-specific coercions, such
266 // as auto-borrowing, coercing pointer mutability, or pin-ergonomics.
267match *b.kind() {
268 ty::RawPtr(_, b_mutbl) => {
269return self.coerce_to_raw_ptr(a, b, b_mutbl);
270 }
271 ty::Ref(r_b, _, mutbl_b) => {
272return self.coerce_to_ref(a, b, r_b, mutbl_b);
273 }
274 ty::Adt(pin, _)
275if self.tcx.features().pin_ergonomics()
276 && self.tcx.is_lang_item(pin.did(), hir::LangItem::Pin) =>
277 {
278let pin_coerce = self.commit_if_ok(|_| self.coerce_to_pin_ref(a, b));
279if pin_coerce.is_ok() {
280return pin_coerce;
281 }
282 }
283_ => {}
284 }
285286match *a.kind() {
287 ty::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.
293self.coerce_from_fn_item(a, b)
294 }
295 ty::FnPtr(a_sig_tys, a_hdr) => {
296// We permit coercion of fn pointers to drop the
297 // unsafe qualifier.
298self.coerce_from_fn_pointer(a, a_sig_tys.with(a_hdr), b)
299 }
300 ty::Closure(..) => {
301// Non-capturing closures are coercible to
302 // function pointers or unsafe function pointers.
303 // It cannot convert closures that require unsafe.
304self.coerce_closure_to_fn(a, b)
305 }
306_ => {
307// Otherwise, just use unification rules.
308self.unify(a, b, ForceLeakCheck::No)
309 }
310 }
311 }
312313/// 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`).
316fn coerce_from_inference_variable(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
317{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:317",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(317u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_from_inference_variable(a={0:?}, b={1:?})",
a, b) as &dyn Value))])
});
} else { ; }
};debug!("coerce_from_inference_variable(a={:?}, b={:?})", a, b);
318if true {
if !(a.is_ty_var() && self.shallow_resolve(a) == a) {
::core::panicking::panic("assertion failed: a.is_ty_var() && self.shallow_resolve(a) == a")
};
};debug_assert!(a.is_ty_var() && self.shallow_resolve(a) == a);
319if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};debug_assert!(self.shallow_resolve(b) == b);
320321if b.is_ty_var() {
322let mut obligations = PredicateObligations::with_capacity(2);
323let mut push_coerce_obligation = |a, b| {
324obligations.push(Obligation::new(
325self.tcx(),
326self.cause.clone(),
327self.param_env,
328 ty::Binder::dummy(ty::PredicateKind::Coerce(ty::CoercePredicate { a, b })),
329 ));
330 };
331332let target_ty = if self.use_lub {
333// When computing the lub, we create a new target
334 // and coerce both `a` and `b` to it.
335let target_ty = self.next_ty_var(self.cause.span);
336push_coerce_obligation(a, target_ty);
337push_coerce_obligation(b, target_ty);
338target_ty339 } else {
340// When subtyping, we don't need to create a new target
341 // as we only coerce `a` to `b`.
342push_coerce_obligation(a, b);
343b344 };
345346{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:346",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(346u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_from_inference_variable: two inference variables, target_ty={0:?}, obligations={1:?}",
target_ty, obligations) as &dyn Value))])
});
} else { ; }
};debug!(
347"coerce_from_inference_variable: two inference variables, target_ty={:?}, obligations={:?}",
348 target_ty, obligations
349 );
350success(::alloc::vec::Vec::new()vec![], target_ty, obligations)
351 } else {
352// One unresolved type variable: just apply subtyping, we may be able
353 // to do something useful.
354self.unify(a, b, ForceLeakCheck::No)
355 }
356 }
357358/// Handles coercing some arbitrary type `a` to some reference (`b`). This
359 /// handles a few cases:
360 /// - Introducing reborrows to give more flexible lifetimes
361 /// - Deref coercions to allow `&T` to coerce to `&T::Target`
362 /// - Coercing mutable references to immutable references
363 /// These coercions can be freely intermixed, for example we are able to
364 /// coerce `&mut T` to `&mut T::Target`.
365fn coerce_to_ref(
366&self,
367 a: Ty<'tcx>,
368 b: Ty<'tcx>,
369 r_b: ty::Region<'tcx>,
370 mutbl_b: hir::Mutability,
371 ) -> CoerceResult<'tcx> {
372{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:372",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(372u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_to_ref(a={0:?}, b={1:?})",
a, b) as &dyn Value))])
});
} else { ; }
};debug!("coerce_to_ref(a={:?}, b={:?})", a, b);
373if true {
if !(self.shallow_resolve(a) == a) {
::core::panicking::panic("assertion failed: self.shallow_resolve(a) == a")
};
};debug_assert!(self.shallow_resolve(a) == a);
374if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};debug_assert!(self.shallow_resolve(b) == b);
375376let (r_a, mt_a) = match *a.kind() {
377 ty::Ref(r_a, ty, mutbl) => {
378coerce_mutbls(mutbl, mutbl_b)?;
379 (r_a, ty::TypeAndMut { ty, mutbl })
380 }
381_ => return self.unify(a, b, ForceLeakCheck::No),
382 };
383384// Look at each step in the `Deref` chain and check if
385 // any of the autoref'd `Target` types unify with the
386 // coercion target.
387 //
388 // For example when coercing from `&mut Vec<T>` to `&M [T]` we
389 // have three deref steps:
390 // 1. `&mut Vec<T>`, skip autoref
391 // 2. `Vec<T>`, autoref'd ty: `&M Vec<T>`
392 // - `&M Vec<T>` does not unify with `&M [T]`
393 // 3. `[T]`, autoref'd ty: `&M [T]`
394 // - `&M [T]` does unify with `&M [T]`
395let mut first_error = None;
396let mut r_borrow_var = None;
397let mut autoderef = self.autoderef(self.cause.span, a);
398let found = autoderef.by_ref().find_map(|(deref_ty, autoderefs)| {
399if autoderefs == 0 {
400// Don't autoref the first step as otherwise we'd allow
401 // coercing `&T` to `&&T`.
402return None;
403 }
404405// The logic here really shouldn't exist. We don't care about free
406 // lifetimes during HIR typeck. Unfortunately later parts of this
407 // function rely on structural identity of the autoref'd deref'd ty.
408 //
409 // This means that what region we use here actually impacts whether
410 // we emit a reborrow coercion or not which can affect diagnostics
411 // and capture analysis (which in turn affects borrowck).
412let r = if !self.use_lub {
413r_b414 } else if autoderefs == 1 {
415r_a416 } else {
417if r_borrow_var.is_none() {
418// create var lazily, at most once
419let coercion = RegionVariableOrigin::Coercion(self.cause.span);
420let r = self.next_region_var(coercion);
421r_borrow_var = Some(r);
422 }
423r_borrow_var.unwrap()
424 };
425426let autorefd_deref_ty = Ty::new_ref(self.tcx, r, deref_ty, mutbl_b);
427428// Note that we unify the autoref'd `Target` type with `b` rather than
429 // the `Target` type with the pointee of `b`. This is necessary
430 // to properly account for the differing variances of the pointees
431 // of `&` vs `&mut` references.
432match self.unify_raw(autorefd_deref_ty, b, ForceLeakCheck::No) {
433Ok(ok) => Some(ok),
434Err(err) => {
435if first_error.is_none() {
436first_error = Some(err);
437 }
438None439 }
440 }
441 });
442443// Extract type or return an error. We return the first error
444 // we got, which should be from relating the "base" type
445 // (e.g., in example above, the failure from relating `Vec<T>`
446 // to the target type), since that should be the least
447 // confusing.
448let Some(InferOk { value: coerced_a, mut obligations }) = foundelse {
449if let Some(first_error) = first_error {
450{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:450",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(450u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_to_ref: failed with err = {0:?}",
first_error) as &dyn Value))])
});
} else { ; }
};debug!("coerce_to_ref: failed with err = {:?}", first_error);
451return Err(first_error);
452 } else {
453// This may happen in the new trait solver since autoderef requires
454 // the pointee to be structurally normalizable, or else it'll just bail.
455 // So when we have a type like `&<not well formed>`, then we get no
456 // autoderef steps (even though there should be at least one). That means
457 // we get no type mismatches, since the loop above just exits early.
458return Err(TypeError::Mismatch);
459 }
460 };
461462if coerced_a == a && mt_a.mutbl.is_not() && autoderef.step_count() == 1 {
463// As a special case, if we would produce `&'a *x`, that's
464 // a total no-op. We end up with the type `&'a T` just as
465 // we started with. In that case, just skip it altogether.
466 //
467 // Unfortunately, this can actually effect capture analysis
468 // which in turn means this effects borrow checking. This can
469 // also effect diagnostics.
470 // FIXME(BoxyUwU): we should always emit reborrow coercions
471 //
472 // Note that for `&mut`, we DO want to reborrow --
473 // otherwise, this would be a move, which might be an
474 // error. For example `foo(self.x)` where `self` and
475 // `self.x` both have `&mut `type would be a move of
476 // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
477 // which is a borrow.
478if !mutbl_b.is_not() {
::core::panicking::panic("assertion failed: mutbl_b.is_not()")
};assert!(mutbl_b.is_not()); // can only coerce &T -> &U
479return success(::alloc::vec::Vec::new()vec![], coerced_a, obligations);
480 }
481482let InferOk { value: mut adjustments, obligations: o } =
483self.adjust_steps_as_infer_ok(&autoderef);
484obligations.extend(o);
485obligations.extend(autoderef.into_obligations());
486487if !#[allow(non_exhaustive_omitted_patterns)] match coerced_a.kind() {
ty::Ref(..) => true,
_ => false,
} {
{
::core::panicking::panic_fmt(format_args!("expected a ref type, got {0:?}",
coerced_a));
}
};assert!(
488matches!(coerced_a.kind(), ty::Ref(..)),
489"expected a ref type, got {:?}",
490 coerced_a
491 );
492493// Now apply the autoref
494let mutbl = AutoBorrowMutability::new(mutbl_b, self.allow_two_phase);
495adjustments496 .push(Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)), target: coerced_a });
497498{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:498",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(498u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_to_ref: succeeded coerced_a={0:?} adjustments={1:?}",
coerced_a, adjustments) as &dyn Value))])
});
} else { ; }
};debug!("coerce_to_ref: succeeded coerced_a={:?} adjustments={:?}", coerced_a, adjustments);
499500success(adjustments, coerced_a, obligations)
501 }
502503/// Performs [unsized coercion] by emulating a fulfillment loop on a
504 /// `CoerceUnsized` goal until all `CoerceUnsized` and `Unsize` goals
505 /// are successfully selected.
506 ///
507 /// [unsized coercion](https://doc.rust-lang.org/reference/type-coercions.html#unsized-coercions)
508#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("coerce_unsized",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(508u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["source", "target"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&target)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: CoerceResult<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:510",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(510u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["source", "target"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&source) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&target) as
&dyn Value))])
});
} else { ; }
};
if true {
if !(self.shallow_resolve(source) == source) {
::core::panicking::panic("assertion failed: self.shallow_resolve(source) == source")
};
};
if true {
if !(self.shallow_resolve(target) == target) {
::core::panicking::panic("assertion failed: self.shallow_resolve(target) == target")
};
};
if source.is_ty_var() {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:518",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(518u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: source is a TyVar, bailing out")
as &dyn Value))])
});
} else { ; }
};
return Err(TypeError::Mismatch);
}
if target.is_ty_var() {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:522",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(522u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: target is a TyVar, bailing out")
as &dyn Value))])
});
} else { ; }
};
return Err(TypeError::Mismatch);
}
match target.kind() {
ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_)
| ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) | ty::Str |
ty::Array(_, _) | ty::Slice(_) | ty::FnDef(_, _) |
ty::FnPtr(_, _) | ty::Dynamic(_, _) | ty::Closure(_, _) |
ty::CoroutineClosure(_, _) | ty::Coroutine(_, _) |
ty::CoroutineWitness(_, _) | ty::Never | ty::Tuple(_) =>
return Err(TypeError::Mismatch),
_ => {}
}
if let ty::Ref(_, source_pointee, ty::Mutability::Not) =
*source.kind() && source_pointee.is_str() &&
let ty::Ref(_, target_pointee, ty::Mutability::Not) =
*target.kind() && target_pointee.is_str() {
return Err(TypeError::Mismatch);
}
let traits =
(self.tcx.lang_items().unsize_trait(),
self.tcx.lang_items().coerce_unsized_trait());
let (Some(unsize_did), Some(coerce_unsized_did)) =
traits else {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:576",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(576u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("missing Unsize or CoerceUnsized traits")
as &dyn Value))])
});
} else { ; }
};
return Err(TypeError::Mismatch);
};
let reborrow =
match (source.kind(), target.kind()) {
(&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => {
coerce_mutbls(mutbl_a, mutbl_b)?;
let coercion =
RegionVariableOrigin::Coercion(self.cause.span);
let r_borrow = self.next_region_var(coercion);
let mutbl =
AutoBorrowMutability::new(mutbl_b, AllowTwoPhase::No);
Some((Adjustment {
kind: Adjust::Deref(DerefAdjustKind::Builtin),
target: ty_a,
},
Adjustment {
kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)),
target: Ty::new_ref(self.tcx, r_borrow, ty_a, mutbl_b),
}))
}
(&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(_, mt_b)) => {
coerce_mutbls(mt_a, mt_b)?;
Some((Adjustment {
kind: Adjust::Deref(DerefAdjustKind::Builtin),
target: ty_a,
},
Adjustment {
kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
target: Ty::new_ptr(self.tcx, ty_a, mt_b),
}))
}
_ => None,
};
let coerce_source =
reborrow.as_ref().map_or(source, |(_, r)| r.target);
let coerce_target = self.next_ty_var(self.cause.span);
let mut coercion =
self.unify_and(coerce_target, target,
reborrow.into_iter().flat_map(|(deref, autoref)|
[deref, autoref]), Adjust::Pointer(PointerCoercion::Unsize),
ForceLeakCheck::No)?;
let cause =
self.cause(self.cause.span,
ObligationCauseCode::Coercion { source, target });
let pred =
ty::TraitRef::new(self.tcx, coerce_unsized_did,
[coerce_source, coerce_target]);
let obligation =
Obligation::new(self.tcx, cause, self.fcx.param_env, pred);
if self.next_trait_solver() {
coercion.obligations.push(obligation);
if self.infcx.visit_proof_tree(Goal::new(self.tcx,
self.param_env, pred),
&mut CoerceVisitor {
fcx: self.fcx,
span: self.cause.span,
}).is_break() {
return Err(TypeError::Mismatch);
}
} else {
self.coerce_unsized_old_solver(obligation, &mut coercion,
coerce_unsized_did, unsize_did)?;
}
Ok(coercion)
}
}
}#[instrument(skip(self), level = "debug")]509fn coerce_unsized(&self, source: Ty<'tcx>, target: Ty<'tcx>) -> CoerceResult<'tcx> {
510debug!(?source, ?target);
511debug_assert!(self.shallow_resolve(source) == source);
512debug_assert!(self.shallow_resolve(target) == target);
513514// We don't apply any coercions incase either the source or target
515 // aren't sufficiently well known but tend to instead just equate
516 // them both.
517if source.is_ty_var() {
518debug!("coerce_unsized: source is a TyVar, bailing out");
519return Err(TypeError::Mismatch);
520 }
521if target.is_ty_var() {
522debug!("coerce_unsized: target is a TyVar, bailing out");
523return Err(TypeError::Mismatch);
524 }
525526// This is an optimization because coercion is one of the most common
527 // operations that we do in typeck, since it happens at every assignment
528 // and call arg (among other positions).
529 //
530 // These targets are known to never be RHS in `LHS: CoerceUnsized<RHS>`.
531 // That's because these are built-in types for which a core-provided impl
532 // doesn't exist, and for which a user-written impl is invalid.
533 //
534 // This is technically incomplete when users write impossible bounds like
535 // `where T: CoerceUnsized<usize>`, for example, but that trait is unstable
536 // and coercion is allowed to be incomplete. The only case where this matters
537 // is impossible bounds.
538 //
539 // Note that some of these types implement `LHS: Unsize<RHS>`, but they
540 // do not implement *`CoerceUnsized`* which is the root obligation of the
541 // check below.
542match target.kind() {
543 ty::Bool
544 | ty::Char
545 | ty::Int(_)
546 | ty::Uint(_)
547 | ty::Float(_)
548 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
549 | ty::Str
550 | ty::Array(_, _)
551 | ty::Slice(_)
552 | ty::FnDef(_, _)
553 | ty::FnPtr(_, _)
554 | ty::Dynamic(_, _)
555 | ty::Closure(_, _)
556 | ty::CoroutineClosure(_, _)
557 | ty::Coroutine(_, _)
558 | ty::CoroutineWitness(_, _)
559 | ty::Never
560 | ty::Tuple(_) => return Err(TypeError::Mismatch),
561_ => {}
562 }
563// `&str: CoerceUnsized<&str>` does not hold but is encountered frequently
564 // so we fast path bail out here
565if let ty::Ref(_, source_pointee, ty::Mutability::Not) = *source.kind()
566 && source_pointee.is_str()
567 && let ty::Ref(_, target_pointee, ty::Mutability::Not) = *target.kind()
568 && target_pointee.is_str()
569 {
570return Err(TypeError::Mismatch);
571 }
572573let traits =
574 (self.tcx.lang_items().unsize_trait(), self.tcx.lang_items().coerce_unsized_trait());
575let (Some(unsize_did), Some(coerce_unsized_did)) = traits else {
576debug!("missing Unsize or CoerceUnsized traits");
577return Err(TypeError::Mismatch);
578 };
579580// Note, we want to avoid unnecessary unsizing. We don't want to coerce to
581 // a DST unless we have to. This currently comes out in the wash since
582 // we can't unify [T] with U. But to properly support DST, we need to allow
583 // that, at which point we will need extra checks on the target here.
584585 // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
586let reborrow = match (source.kind(), target.kind()) {
587 (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => {
588 coerce_mutbls(mutbl_a, mutbl_b)?;
589590let coercion = RegionVariableOrigin::Coercion(self.cause.span);
591let r_borrow = self.next_region_var(coercion);
592593// We don't allow two-phase borrows here, at least for initial
594 // implementation. If it happens that this coercion is a function argument,
595 // the reborrow in coerce_borrowed_ptr will pick it up.
596let mutbl = AutoBorrowMutability::new(mutbl_b, AllowTwoPhase::No);
597598Some((
599 Adjustment { kind: Adjust::Deref(DerefAdjustKind::Builtin), target: ty_a },
600 Adjustment {
601 kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)),
602 target: Ty::new_ref(self.tcx, r_borrow, ty_a, mutbl_b),
603 },
604 ))
605 }
606 (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(_, mt_b)) => {
607 coerce_mutbls(mt_a, mt_b)?;
608609Some((
610 Adjustment { kind: Adjust::Deref(DerefAdjustKind::Builtin), target: ty_a },
611 Adjustment {
612 kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
613 target: Ty::new_ptr(self.tcx, ty_a, mt_b),
614 },
615 ))
616 }
617_ => None,
618 };
619let coerce_source = reborrow.as_ref().map_or(source, |(_, r)| r.target);
620621// Setup either a subtyping or a LUB relationship between
622 // the `CoerceUnsized` target type and the expected type.
623 // We only have the latter, so we use an inference variable
624 // for the former and let type inference do the rest.
625let coerce_target = self.next_ty_var(self.cause.span);
626627let mut coercion = self.unify_and(
628 coerce_target,
629 target,
630 reborrow.into_iter().flat_map(|(deref, autoref)| [deref, autoref]),
631 Adjust::Pointer(PointerCoercion::Unsize),
632 ForceLeakCheck::No,
633 )?;
634635// Create an obligation for `Source: CoerceUnsized<Target>`.
636let cause = self.cause(self.cause.span, ObligationCauseCode::Coercion { source, target });
637let pred = ty::TraitRef::new(self.tcx, coerce_unsized_did, [coerce_source, coerce_target]);
638let obligation = Obligation::new(self.tcx, cause, self.fcx.param_env, pred);
639640if self.next_trait_solver() {
641 coercion.obligations.push(obligation);
642643if self
644.infcx
645 .visit_proof_tree(
646 Goal::new(self.tcx, self.param_env, pred),
647&mut CoerceVisitor { fcx: self.fcx, span: self.cause.span },
648 )
649 .is_break()
650 {
651return Err(TypeError::Mismatch);
652 }
653 } else {
654self.coerce_unsized_old_solver(
655 obligation,
656&mut coercion,
657 coerce_unsized_did,
658 unsize_did,
659 )?;
660 }
661662Ok(coercion)
663 }
664665fn coerce_unsized_old_solver(
666&self,
667 obligation: Obligation<'tcx, ty::Predicate<'tcx>>,
668 coercion: &mut InferOk<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>,
669 coerce_unsized_did: DefId,
670 unsize_did: DefId,
671 ) -> Result<(), TypeError<'tcx>> {
672let mut selcx = traits::SelectionContext::new(self);
673// Use a FIFO queue for this custom fulfillment procedure.
674 //
675 // A Vec (or SmallVec) is not a natural choice for a queue. However,
676 // this code path is hot, and this queue usually has a max length of 1
677 // and almost never more than 3. By using a SmallVec we avoid an
678 // allocation, at the (very small) cost of (occasionally) having to
679 // shift subsequent elements down when removing the front element.
680let mut queue: SmallVec<[PredicateObligation<'tcx>; 4]> = {
let count = 0usize + 1usize;
let mut vec = ::smallvec::SmallVec::new();
if count <= vec.inline_size() {
vec.push(obligation);
vec
} else {
::smallvec::SmallVec::from_vec(<[_]>::into_vec(::alloc::boxed::box_new([obligation])))
}
}smallvec![obligation];
681682// Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
683 // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
684 // inference might unify those two inner type variables later.
685let traits = [coerce_unsized_did, unsize_did];
686while !queue.is_empty() {
687let obligation = queue.remove(0);
688let trait_pred = match obligation.predicate.kind().no_bound_vars() {
689Some(ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)))
690if traits.contains(&trait_pred.def_id()) =>
691 {
692self.resolve_vars_if_possible(trait_pred)
693 }
694// Eagerly process alias-relate obligations in new trait solver,
695 // since these can be emitted in the process of solving trait goals,
696 // but we need to constrain vars before processing goals mentioning
697 // them.
698Some(ty::PredicateKind::AliasRelate(..)) => {
699let ocx = ObligationCtxt::new(self);
700 ocx.register_obligation(obligation);
701if !ocx.try_evaluate_obligations().is_empty() {
702return Err(TypeError::Mismatch);
703 }
704 coercion.obligations.extend(ocx.into_pending_obligations());
705continue;
706 }
707_ => {
708 coercion.obligations.push(obligation);
709continue;
710 }
711 };
712{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:712",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(712u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized resolve step: {0:?}",
trait_pred) as &dyn Value))])
});
} else { ; }
};debug!("coerce_unsized resolve step: {:?}", trait_pred);
713match selcx.select(&obligation.with(selcx.tcx(), trait_pred)) {
714// Uncertain or unimplemented.
715Ok(None) => {
716if trait_pred.def_id() == unsize_did {
717let self_ty = trait_pred.self_ty();
718let unsize_ty = trait_pred.trait_ref.args[1].expect_ty();
719{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:719",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(719u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: ambiguous unsize case for {0:?}",
trait_pred) as &dyn Value))])
});
} else { ; }
};debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_pred);
720match (self_ty.kind(), unsize_ty.kind()) {
721 (&ty::Infer(ty::TyVar(v)), ty::Dynamic(..))
722if self.type_var_is_sized(v) =>
723 {
724{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:724",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(724u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: have sized infer {0:?}",
v) as &dyn Value))])
});
} else { ; }
};debug!("coerce_unsized: have sized infer {:?}", v);
725 coercion.obligations.push(obligation);
726// `$0: Unsize<dyn Trait>` where we know that `$0: Sized`, try going
727 // for unsizing.
728}
729_ => {
730// Some other case for `$0: Unsize<Something>`. Note that we
731 // hit this case even if `Something` is a sized type, so just
732 // don't do the coercion.
733{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:733",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(733u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: ambiguous unsize")
as &dyn Value))])
});
} else { ; }
};debug!("coerce_unsized: ambiguous unsize");
734return Err(TypeError::Mismatch);
735 }
736 }
737 } else {
738{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:738",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(738u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: early return - ambiguous")
as &dyn Value))])
});
} else { ; }
};debug!("coerce_unsized: early return - ambiguous");
739return Err(TypeError::Mismatch);
740 }
741 }
742Err(SelectionError::Unimplemented) => {
743{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:743",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(743u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: early return - can\'t prove obligation")
as &dyn Value))])
});
} else { ; }
};debug!("coerce_unsized: early return - can't prove obligation");
744return Err(TypeError::Mismatch);
745 }
746747Err(SelectionError::TraitDynIncompatible(_)) => {
748// Dyn compatibility errors in coercion will *always* be due to the
749 // fact that the RHS of the coercion is a non-dyn compatible `dyn Trait`
750 // written in source somewhere (otherwise we will never have lowered
751 // the dyn trait from HIR to middle).
752 //
753 // There's no reason to emit yet another dyn compatibility error,
754 // especially since the span will differ slightly and thus not be
755 // deduplicated at all!
756self.fcx.set_tainted_by_errors(
757self.fcx
758 .dcx()
759 .span_delayed_bug(self.cause.span, "dyn compatibility during coercion"),
760 );
761 }
762Err(err) => {
763let guar = self.err_ctxt().report_selection_error(
764 obligation.clone(),
765&obligation,
766&err,
767 );
768self.fcx.set_tainted_by_errors(guar);
769// Treat this like an obligation and follow through
770 // with the unsizing - the lack of a coercion should
771 // be silent, as it causes a type mismatch later.
772}
773Ok(Some(ImplSource::UserDefined(impl_source))) => {
774 queue.extend(impl_source.nested);
775// Certain incoherent `CoerceUnsized` implementations may cause ICEs,
776 // so check the impl's validity. Taint the body so that we don't try
777 // to evaluate these invalid coercions in CTFE. We only need to do this
778 // for local impls, since upstream impls should be valid.
779if impl_source.impl_def_id.is_local()
780 && let Err(guar) =
781self.tcx.ensure_ok().coerce_unsized_info(impl_source.impl_def_id)
782 {
783self.fcx.set_tainted_by_errors(guar);
784 }
785 }
786Ok(Some(impl_source)) => queue.extend(impl_source.nested_obligations()),
787 }
788 }
789790Ok(())
791 }
792793/// Applies reborrowing for `Pin`
794 ///
795 /// We currently only support reborrowing `Pin<&mut T>` as `Pin<&mut T>`. This is accomplished
796 /// by inserting a call to `Pin::as_mut` during MIR building.
797 ///
798 /// In the future we might want to support other reborrowing coercions, such as:
799 /// - `Pin<&mut T>` as `Pin<&T>`
800 /// - `Pin<&T>` as `Pin<&T>`
801 /// - `Pin<Box<T>>` as `Pin<&T>`
802 /// - `Pin<Box<T>>` as `Pin<&mut T>`
803#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("coerce_to_pin_ref",
"rustc_hir_typeck::coercion", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(803u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["a", "b"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: CoerceResult<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
if true {
if !(self.shallow_resolve(a) == a) {
::core::panicking::panic("assertion failed: self.shallow_resolve(a) == a")
};
};
if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};
let extract_pin_mut =
|ty: Ty<'tcx>|
{
let (pin, ty) =
match ty.kind() {
ty::Adt(pin, args) if
self.tcx.is_lang_item(pin.did(), hir::LangItem::Pin) => {
(*pin, args[0].expect_ty())
}
_ => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:819",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(819u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("can\'t reborrow {0:?} as pinned",
ty) as &dyn Value))])
});
} else { ; }
};
return Err(TypeError::Mismatch);
}
};
match ty.kind() {
ty::Ref(region, ty, mutbl) =>
Ok((pin, *region, *ty, *mutbl)),
_ => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:827",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(827u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("can\'t reborrow pin of inner type {0:?}",
ty) as &dyn Value))])
});
} else { ; }
};
Err(TypeError::Mismatch)
}
}
};
let (pin, a_region, a_ty, mut_a) = extract_pin_mut(a)?;
let (_, _, _b_ty, mut_b) = extract_pin_mut(b)?;
coerce_mutbls(mut_a, mut_b)?;
let a =
Ty::new_adt(self.tcx, pin,
self.tcx.mk_args(&[Ty::new_ref(self.tcx, a_region, a_ty,
mut_b).into()]));
self.unify_and(a, b, [], Adjust::ReborrowPin(mut_b),
ForceLeakCheck::No)
}
}
}#[instrument(skip(self), level = "trace")]804fn coerce_to_pin_ref(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
805debug_assert!(self.shallow_resolve(a) == a);
806debug_assert!(self.shallow_resolve(b) == b);
807808// We need to make sure the two types are compatible for coercion.
809 // Then we will build a ReborrowPin adjustment and return that as an InferOk.
810811 // Right now we can only reborrow if this is a `Pin<&mut T>`.
812let extract_pin_mut = |ty: Ty<'tcx>| {
813// Get the T out of Pin<T>
814let (pin, ty) = match ty.kind() {
815 ty::Adt(pin, args) if self.tcx.is_lang_item(pin.did(), hir::LangItem::Pin) => {
816 (*pin, args[0].expect_ty())
817 }
818_ => {
819debug!("can't reborrow {:?} as pinned", ty);
820return Err(TypeError::Mismatch);
821 }
822 };
823// Make sure the T is something we understand (just `&mut U` for now)
824match ty.kind() {
825 ty::Ref(region, ty, mutbl) => Ok((pin, *region, *ty, *mutbl)),
826_ => {
827debug!("can't reborrow pin of inner type {:?}", ty);
828Err(TypeError::Mismatch)
829 }
830 }
831 };
832833let (pin, a_region, a_ty, mut_a) = extract_pin_mut(a)?;
834let (_, _, _b_ty, mut_b) = extract_pin_mut(b)?;
835836 coerce_mutbls(mut_a, mut_b)?;
837838// update a with b's mutability since we'll be coercing mutability
839let a = Ty::new_adt(
840self.tcx,
841 pin,
842self.tcx.mk_args(&[Ty::new_ref(self.tcx, a_region, a_ty, mut_b).into()]),
843 );
844845// To complete the reborrow, we need to make sure we can unify the inner types, and if so we
846 // add the adjustments.
847self.unify_and(a, b, [], Adjust::ReborrowPin(mut_b), ForceLeakCheck::No)
848 }
849850fn coerce_from_fn_pointer(
851&self,
852 a: Ty<'tcx>,
853 a_sig: ty::PolyFnSig<'tcx>,
854 b: Ty<'tcx>,
855 ) -> CoerceResult<'tcx> {
856{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:856",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(856u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message", "a_sig",
"b"], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_from_fn_pointer")
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&a_sig) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&b) as
&dyn Value))])
});
} else { ; }
};debug!(?a_sig, ?b, "coerce_from_fn_pointer");
857if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};debug_assert!(self.shallow_resolve(b) == b);
858859match b.kind() {
860 ty::FnPtr(_, b_hdr) if a_sig.safety().is_safe() && b_hdr.safety.is_unsafe() => {
861let a = self.tcx.safe_to_unsafe_fn_ty(a_sig);
862let adjust = Adjust::Pointer(PointerCoercion::UnsafeFnPointer);
863self.unify_and(a, b, [], adjust, ForceLeakCheck::Yes)
864 }
865_ => self.unify(a, b, ForceLeakCheck::Yes),
866 }
867 }
868869fn coerce_from_fn_item(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
870{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:870",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(870u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_from_fn_item(a={0:?}, b={1:?})",
a, b) as &dyn Value))])
});
} else { ; }
};debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
871if true {
if !(self.shallow_resolve(a) == a) {
::core::panicking::panic("assertion failed: self.shallow_resolve(a) == a")
};
};debug_assert!(self.shallow_resolve(a) == a);
872if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};debug_assert!(self.shallow_resolve(b) == b);
873874match b.kind() {
875 ty::FnPtr(_, b_hdr) => {
876let a_sig = self.sig_for_fn_def_coercion(a, Some(b_hdr.safety))?;
877878let InferOk { value: a_sig, mut obligations } =
879self.at(&self.cause, self.param_env).normalize(a_sig);
880let a = Ty::new_fn_ptr(self.tcx, a_sig);
881882let adjust = Adjust::Pointer(PointerCoercion::ReifyFnPointer(b_hdr.safety));
883let InferOk { value, obligations: o2 } =
884self.unify_and(a, b, [], adjust, ForceLeakCheck::Yes)?;
885886obligations.extend(o2);
887Ok(InferOk { value, obligations })
888 }
889_ => self.unify(a, b, ForceLeakCheck::No),
890 }
891 }
892893/// Attempts to coerce from a closure to a function pointer. Fails
894 /// if the closure has any upvars.
895fn coerce_closure_to_fn(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
896if true {
if !(self.shallow_resolve(a) == a) {
::core::panicking::panic("assertion failed: self.shallow_resolve(a) == a")
};
};debug_assert!(self.shallow_resolve(a) == a);
897if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};debug_assert!(self.shallow_resolve(b) == b);
898899match b.kind() {
900 ty::FnPtr(_, hdr) => {
901let safety = hdr.safety;
902let terr = TypeError::Sorts(ty::error::ExpectedFound::new(a, b));
903let closure_sig = self.sig_for_closure_coercion(a, Some(hdr.safety), terr)?;
904let pointer_ty = Ty::new_fn_ptr(self.tcx, closure_sig);
905{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:905",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(905u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_closure_to_fn(a={0:?}, b={1:?}, pty={2:?})",
a, b, pointer_ty) as &dyn Value))])
});
} else { ; }
};debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})", a, b, pointer_ty);
906907let adjust = Adjust::Pointer(PointerCoercion::ClosureFnPointer(safety));
908self.unify_and(pointer_ty, b, [], adjust, ForceLeakCheck::No)
909 }
910_ => self.unify(a, b, ForceLeakCheck::No),
911 }
912 }
913914fn coerce_to_raw_ptr(
915&self,
916 a: Ty<'tcx>,
917 b: Ty<'tcx>,
918 mutbl_b: hir::Mutability,
919 ) -> CoerceResult<'tcx> {
920{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:920",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(920u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_to_raw_ptr(a={0:?}, b={1:?})",
a, b) as &dyn Value))])
});
} else { ; }
};debug!("coerce_to_raw_ptr(a={:?}, b={:?})", a, b);
921if true {
if !(self.shallow_resolve(a) == a) {
::core::panicking::panic("assertion failed: self.shallow_resolve(a) == a")
};
};debug_assert!(self.shallow_resolve(a) == a);
922if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};debug_assert!(self.shallow_resolve(b) == b);
923924let (is_ref, mt_a) = match *a.kind() {
925 ty::Ref(_, ty, mutbl) => (true, ty::TypeAndMut { ty, mutbl }),
926 ty::RawPtr(ty, mutbl) => (false, ty::TypeAndMut { ty, mutbl }),
927_ => return self.unify(a, b, ForceLeakCheck::No),
928 };
929coerce_mutbls(mt_a.mutbl, mutbl_b)?;
930931// Check that the types which they point at are compatible.
932let a_raw = Ty::new_ptr(self.tcx, mt_a.ty, mutbl_b);
933// Although references and raw ptrs have the same
934 // representation, we still register an Adjust::DerefRef so that
935 // regionck knows that the region for `a` must be valid here.
936if is_ref {
937self.unify_and(
938a_raw,
939b,
940 [Adjustment { kind: Adjust::Deref(DerefAdjustKind::Builtin), target: mt_a.ty }],
941 Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)),
942 ForceLeakCheck::No,
943 )
944 } else if mt_a.mutbl != mutbl_b {
945self.unify_and(
946a_raw,
947b,
948 [],
949 Adjust::Pointer(PointerCoercion::MutToConstPointer),
950 ForceLeakCheck::No,
951 )
952 } else {
953self.unify(a_raw, b, ForceLeakCheck::No)
954 }
955 }
956}
957958impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
959/// Attempt to coerce an expression to a type, and return the
960 /// adjusted type of the expression, if successful.
961 /// Adjustments are only recorded if the coercion succeeded.
962 /// The expressions *must not* have any preexisting adjustments.
963pub(crate) fn coerce(
964&self,
965 expr: &'tcx hir::Expr<'tcx>,
966 expr_ty: Ty<'tcx>,
967mut target: Ty<'tcx>,
968 allow_two_phase: AllowTwoPhase,
969 cause: Option<ObligationCause<'tcx>>,
970 ) -> RelateResult<'tcx, Ty<'tcx>> {
971let source = self.try_structurally_resolve_type(expr.span, expr_ty);
972if self.next_trait_solver() {
973target = self.try_structurally_resolve_type(
974cause.as_ref().map_or(expr.span, |cause| cause.span),
975target,
976 );
977 }
978{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:978",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(978u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coercion::try({0:?}: {1:?} -> {2:?})",
expr, source, target) as &dyn Value))])
});
} else { ; }
};debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
979980let cause =
981cause.unwrap_or_else(|| self.cause(expr.span, ObligationCauseCode::ExprAssignable));
982let coerce = Coerce::new(
983self,
984cause,
985allow_two_phase,
986self.tcx.expr_guaranteed_to_constitute_read_for_never(expr),
987 );
988let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?;
989990let (adjustments, _) = self.register_infer_ok_obligations(ok);
991self.apply_adjustments(expr, adjustments);
992Ok(if let Err(guar) = expr_ty.error_reported() {
993Ty::new_error(self.tcx, guar)
994 } else {
995target996 })
997 }
998999/// Probe whether `expr_ty` can be coerced to `target_ty`. This has no side-effects,
1000 /// and may return false positives if types are not yet fully constrained by inference.
1001 ///
1002 /// Returns false if the coercion is not possible, or if the coercion creates any
1003 /// sub-obligations that result in errors.
1004 ///
1005 /// This should only be used for diagnostics.
1006pub(crate) fn may_coerce(&self, expr_ty: Ty<'tcx>, target_ty: Ty<'tcx>) -> bool {
1007let cause = self.cause(DUMMY_SP, ObligationCauseCode::ExprAssignable);
1008// We don't ever need two-phase here since we throw out the result of the coercion.
1009 // We also just always set `coerce_never` to true, since this is a heuristic.
1010let coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No, true);
1011self.probe(|_| {
1012// Make sure to structurally resolve the types, since we use
1013 // the `TyKind`s heavily in coercion.
1014let ocx = ObligationCtxt::new(self);
1015let structurally_resolve = |ty| {
1016let ty = self.shallow_resolve(ty);
1017if self.next_trait_solver()
1018 && let ty::Alias(..) = ty.kind()
1019 {
1020ocx.structurally_normalize_ty(&cause, self.param_env, ty)
1021 } else {
1022Ok(ty)
1023 }
1024 };
1025let Ok(expr_ty) = structurally_resolve(expr_ty) else {
1026return false;
1027 };
1028let Ok(target_ty) = structurally_resolve(target_ty) else {
1029return false;
1030 };
10311032let Ok(ok) = coerce.coerce(expr_ty, target_ty) else {
1033return false;
1034 };
1035ocx.register_obligations(ok.obligations);
1036ocx.try_evaluate_obligations().is_empty()
1037 })
1038 }
10391040/// Given a type and a target type, this function will calculate and return
1041 /// how many dereference steps needed to coerce `expr_ty` to `target`. If
1042 /// it's not possible, return `None`.
1043pub(crate) fn deref_steps_for_suggestion(
1044&self,
1045 expr_ty: Ty<'tcx>,
1046 target: Ty<'tcx>,
1047 ) -> Option<usize> {
1048let cause = self.cause(DUMMY_SP, ObligationCauseCode::ExprAssignable);
1049// We don't ever need two-phase here since we throw out the result of the coercion.
1050let coerce = Coerce::new(self, cause, AllowTwoPhase::No, true);
1051coerce.autoderef(DUMMY_SP, expr_ty).find_map(|(ty, steps)| {
1052self.probe(|_| coerce.unify_raw(ty, target, ForceLeakCheck::No)).ok().map(|_| steps)
1053 })
1054 }
10551056/// Given a type, this function will calculate and return the type given
1057 /// for `<Ty as Deref>::Target` only if `Ty` also implements `DerefMut`.
1058 ///
1059 /// This function is for diagnostics only, since it does not register
1060 /// trait or region sub-obligations. (presumably we could, but it's not
1061 /// particularly important for diagnostics...)
1062pub(crate) fn deref_once_mutably_for_diagnostic(&self, expr_ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
1063self.autoderef(DUMMY_SP, expr_ty).silence_errors().nth(1).and_then(|(deref_ty, _)| {
1064self.infcx
1065 .type_implements_trait(
1066self.tcx.lang_items().deref_mut_trait()?,
1067 [expr_ty],
1068self.param_env,
1069 )
1070 .may_apply()
1071 .then_some(deref_ty)
1072 })
1073 }
10741075x;#[instrument(level = "debug", skip(self), ret)]1076fn sig_for_coerce_lub(
1077&self,
1078 ty: Ty<'tcx>,
1079 closure_upvars_terr: TypeError<'tcx>,
1080 ) -> Result<ty::PolyFnSig<'tcx>, TypeError<'tcx>> {
1081match ty.kind() {
1082 ty::FnDef(..) => self.sig_for_fn_def_coercion(ty, None),
1083 ty::Closure(..) => self.sig_for_closure_coercion(ty, None, closure_upvars_terr),
1084_ => unreachable!("`sig_for_fn_def_closure_coerce_lub` called with wrong ty: {:?}", ty),
1085 }
1086 }
10871088fn sig_for_fn_def_coercion(
1089&self,
1090 fndef: Ty<'tcx>,
1091 expected_safety: Option<hir::Safety>,
1092 ) -> Result<ty::PolyFnSig<'tcx>, TypeError<'tcx>> {
1093let tcx = self.tcx;
10941095let &ty::FnDef(def_id, _) = fndef.kind() else {
1096{
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("`sig_for_fn_def_coercion` called with non-fndef: {0:?}",
fndef)));
};unreachable!("`sig_for_fn_def_coercion` called with non-fndef: {:?}", fndef);
1097 };
10981099// Intrinsics are not coercible to function pointers
1100if tcx.intrinsic(def_id).is_some() {
1101return Err(TypeError::IntrinsicCast);
1102 }
11031104let fn_attrs = tcx.codegen_fn_attrs(def_id);
1105if #[allow(non_exhaustive_omitted_patterns)] match fn_attrs.inline {
InlineAttr::Force { .. } => true,
_ => false,
}matches!(fn_attrs.inline, InlineAttr::Force { .. }) {
1106return Err(TypeError::ForceInlineCast);
1107 }
11081109let sig = fndef.fn_sig(tcx);
1110let sig = if fn_attrs.safe_target_features {
1111// Allow the coercion if the current function has all the features that would be
1112 // needed to call the coercee safely.
1113match tcx.adjust_target_feature_sig(def_id, sig, self.body_id.into()) {
1114Some(adjusted_sig) => adjusted_sig,
1115Noneif #[allow(non_exhaustive_omitted_patterns)] match expected_safety {
Some(hir::Safety::Safe) => true,
_ => false,
}matches!(expected_safety, Some(hir::Safety::Safe)) => {
1116return Err(TypeError::TargetFeatureCast(def_id));
1117 }
1118None => sig,
1119 }
1120 } else {
1121sig1122 };
11231124if sig.safety().is_safe() && #[allow(non_exhaustive_omitted_patterns)] match expected_safety {
Some(hir::Safety::Unsafe) => true,
_ => false,
}matches!(expected_safety, Some(hir::Safety::Unsafe)) {
1125Ok(tcx.safe_to_unsafe_sig(sig))
1126 } else {
1127Ok(sig)
1128 }
1129 }
11301131fn sig_for_closure_coercion(
1132&self,
1133 closure: Ty<'tcx>,
1134 expected_safety: Option<hir::Safety>,
1135 closure_upvars_terr: TypeError<'tcx>,
1136 ) -> Result<ty::PolyFnSig<'tcx>, TypeError<'tcx>> {
1137let tcx = self.tcx;
11381139let ty::Closure(closure_def, closure_args) = closure.kind() else {
1140{
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("`sig_for_closure_coercion` called with non closure ty: {0:?}",
closure)));
};unreachable!("`sig_for_closure_coercion` called with non closure ty: {:?}", closure);
1141 };
11421143// At this point we haven't done capture analysis, which means
1144 // that the ClosureArgs just contains an inference variable instead
1145 // of tuple of captured types.
1146 //
1147 // All we care here is if any variable is being captured and not the exact paths,
1148 // so we check `upvars_mentioned` for root variables being captured.
1149if !tcx.upvars_mentioned(closure_def.expect_local()).is_none_or(|u| u.is_empty()) {
1150return Err(closure_upvars_terr);
1151 }
11521153// We coerce the closure, which has fn type
1154 // `extern "rust-call" fn((arg0,arg1,...)) -> _`
1155 // to
1156 // `fn(arg0,arg1,...) -> _`
1157 // or
1158 // `unsafe fn(arg0,arg1,...) -> _`
1159let closure_sig = closure_args.as_closure().sig();
1160Ok(tcx.signature_unclosure(closure_sig, expected_safety.unwrap_or(hir::Safety::Safe)))
1161 }
11621163/// Given some expressions, their known unified type and another expression,
1164 /// tries to unify the types, potentially inserting coercions on any of the
1165 /// provided expressions and returns their LUB (aka "common supertype").
1166 ///
1167 /// This is really an internal helper. From outside the coercion
1168 /// module, you should instantiate a `CoerceMany` instance.
1169fn try_find_coercion_lub(
1170&self,
1171 cause: &ObligationCause<'tcx>,
1172 exprs: &[&'tcx hir::Expr<'tcx>],
1173 prev_ty: Ty<'tcx>,
1174 new: &hir::Expr<'_>,
1175 new_ty: Ty<'tcx>,
1176 ) -> RelateResult<'tcx, Ty<'tcx>> {
1177let prev_ty = self.try_structurally_resolve_type(cause.span, prev_ty);
1178let new_ty = self.try_structurally_resolve_type(new.span, new_ty);
1179{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:1179",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(1179u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coercion::try_find_coercion_lub({0:?}, {1:?}, exprs={2:?} exprs)",
prev_ty, new_ty, exprs.len()) as &dyn Value))])
});
} else { ; }
};debug!(
1180"coercion::try_find_coercion_lub({:?}, {:?}, exprs={:?} exprs)",
1181 prev_ty,
1182 new_ty,
1183 exprs.len()
1184 );
11851186// Fast Path: don't go through the coercion logic if we're coercing
1187 // a type to itself. This is unfortunately quite perf relevant so
1188 // we do it even though it may mask bugs in the coercion logic.
1189if prev_ty == new_ty {
1190return Ok(prev_ty);
1191 }
11921193let terr = TypeError::Sorts(ty::error::ExpectedFound::new(prev_ty, new_ty));
1194let opt_sigs = match (prev_ty.kind(), new_ty.kind()) {
1195// Don't coerce pairs of fndefs or pairs of closures to fn ptrs
1196 // if they can just be lubbed.
1197 //
1198 // See #88097 or `lub_closures_before_fnptr_coercion.rs` for where
1199 // we would erroneously coerce closures to fnptrs when attempting to
1200 // coerce a closure to itself.
1201(ty::FnDef(..), ty::FnDef(..)) | (ty::Closure(..), ty::Closure(..)) => {
1202let lubbed_ty = self.commit_if_ok(|snapshot| {
1203let outer_universe = self.infcx.universe();
12041205// We need to eagerly handle nested obligations due to lazy norm.
1206let result = if self.next_trait_solver() {
1207let ocx = ObligationCtxt::new(self);
1208let value = ocx.lub(cause, self.param_env, prev_ty, new_ty)?;
1209if ocx.try_evaluate_obligations().is_empty() {
1210Ok(InferOk { value, obligations: ocx.into_pending_obligations() })
1211 } else {
1212Err(TypeError::Mismatch)
1213 }
1214 } else {
1215self.at(cause, self.param_env).lub(prev_ty, new_ty)
1216 };
12171218self.leak_check(outer_universe, Some(snapshot))?;
1219result1220 });
12211222match lubbed_ty {
1223Ok(ok) => return Ok(self.register_infer_ok_obligations(ok)),
1224Err(_) => {
1225let a_sig = self.sig_for_coerce_lub(prev_ty, terr)?;
1226let b_sig = self.sig_for_coerce_lub(new_ty, terr)?;
1227Some((a_sig, b_sig))
1228 }
1229 }
1230 }
12311232 (ty::Closure(..), ty::FnDef(..)) | (ty::FnDef(..), ty::Closure(..)) => {
1233let a_sig = self.sig_for_coerce_lub(prev_ty, terr)?;
1234let b_sig = self.sig_for_coerce_lub(new_ty, terr)?;
1235Some((a_sig, b_sig))
1236 }
1237// ty::FnPtr x ty::FnPtr is fine to just be handled through a normal `unify`
1238 // call using `lub` which is what will happen on the normal path.
1239(ty::FnPtr(..), ty::FnPtr(..)) => None,
1240_ => None,
1241 };
12421243if let Some((mut a_sig, mut b_sig)) = opt_sigs {
1244// Allow coercing safe sigs to unsafe sigs
1245if a_sig.safety().is_safe() && b_sig.safety().is_unsafe() {
1246a_sig = self.tcx.safe_to_unsafe_sig(a_sig);
1247 } else if b_sig.safety().is_safe() && a_sig.safety().is_unsafe() {
1248b_sig = self.tcx.safe_to_unsafe_sig(b_sig);
1249 };
12501251// The signature must match.
1252let (a_sig, b_sig) = self.normalize(new.span, (a_sig, b_sig));
1253let sig = self1254 .at(cause, self.param_env)
1255 .lub(a_sig, b_sig)
1256 .map(|ok| self.register_infer_ok_obligations(ok))?;
12571258// Reify both sides and return the reified fn pointer type.
1259let fn_ptr = Ty::new_fn_ptr(self.tcx, sig);
1260let prev_adjustment = match prev_ty.kind() {
1261 ty::Closure(..) => Adjust::Pointer(PointerCoercion::ClosureFnPointer(sig.safety())),
1262 ty::FnDef(..) => Adjust::Pointer(PointerCoercion::ReifyFnPointer(sig.safety())),
1263_ => ::rustc_middle::util::bug::span_bug_fmt(cause.span,
format_args!("should not try to coerce a {0} to a fn pointer", prev_ty))span_bug!(cause.span, "should not try to coerce a {prev_ty} to a fn pointer"),
1264 };
1265let next_adjustment = match new_ty.kind() {
1266 ty::Closure(..) => Adjust::Pointer(PointerCoercion::ClosureFnPointer(sig.safety())),
1267 ty::FnDef(..) => Adjust::Pointer(PointerCoercion::ReifyFnPointer(sig.safety())),
1268_ => ::rustc_middle::util::bug::span_bug_fmt(new.span,
format_args!("should not try to coerce a {0} to a fn pointer", new_ty))span_bug!(new.span, "should not try to coerce a {new_ty} to a fn pointer"),
1269 };
1270for expr in exprs.iter() {
1271self.apply_adjustments(
1272 expr,
1273<[_]>::into_vec(::alloc::boxed::box_new([Adjustment {
kind: prev_adjustment.clone(),
target: fn_ptr,
}]))vec![Adjustment { kind: prev_adjustment.clone(), target: fn_ptr }],
1274 );
1275 }
1276self.apply_adjustments(new, <[_]>::into_vec(::alloc::boxed::box_new([Adjustment {
kind: next_adjustment,
target: fn_ptr,
}]))vec![Adjustment { kind: next_adjustment, target: fn_ptr }]);
1277return Ok(fn_ptr);
1278 }
12791280// Configure a Coerce instance to compute the LUB.
1281 // We don't allow two-phase borrows on any autorefs this creates since we
1282 // probably aren't processing function arguments here and even if we were,
1283 // they're going to get autorefed again anyway and we can apply 2-phase borrows
1284 // at that time.
1285 //
1286 // NOTE: we set `coerce_never` to `true` here because coercion LUBs only
1287 // operate on values and not places, so a never coercion is valid.
1288let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No, true);
1289coerce.use_lub = true;
12901291// First try to coerce the new expression to the type of the previous ones,
1292 // but only if the new expression has no coercion already applied to it.
1293let mut first_error = None;
1294if !self.typeck_results.borrow().adjustments().contains_key(new.hir_id) {
1295let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
1296match result {
1297Ok(ok) => {
1298let (adjustments, target) = self.register_infer_ok_obligations(ok);
1299self.apply_adjustments(new, adjustments);
1300{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:1300",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(1300u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coercion::try_find_coercion_lub: was able to coerce from new type {0:?} to previous type {1:?} ({2:?})",
new_ty, prev_ty, target) as &dyn Value))])
});
} else { ; }
};debug!(
1301"coercion::try_find_coercion_lub: was able to coerce from new type {:?} to previous type {:?} ({:?})",
1302 new_ty, prev_ty, target
1303 );
1304return Ok(target);
1305 }
1306Err(e) => first_error = Some(e),
1307 }
1308 }
13091310let ok = self1311 .commit_if_ok(|_| coerce.coerce(prev_ty, new_ty))
1312// Avoid giving strange errors on failed attempts.
1313.map_err(|e| first_error.unwrap_or(e))?;
13141315let (adjustments, target) = self.register_infer_ok_obligations(ok);
1316for expr in exprs {
1317self.apply_adjustments(expr, adjustments.clone());
1318 }
1319{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:1319",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(1319u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coercion::try_find_coercion_lub: was able to coerce previous type {0:?} to new type {1:?} ({2:?})",
prev_ty, new_ty, target) as &dyn Value))])
});
} else { ; }
};debug!(
1320"coercion::try_find_coercion_lub: was able to coerce previous type {:?} to new type {:?} ({:?})",
1321 prev_ty, new_ty, target
1322 );
1323Ok(target)
1324 }
1325}
13261327/// Check whether `ty` can be coerced to `output_ty`.
1328/// Used from clippy.
1329pub fn can_coerce<'tcx>(
1330 tcx: TyCtxt<'tcx>,
1331 param_env: ty::ParamEnv<'tcx>,
1332 body_id: LocalDefId,
1333 ty: Ty<'tcx>,
1334 output_ty: Ty<'tcx>,
1335) -> bool {
1336let root_ctxt = crate::typeck_root_ctxt::TypeckRootCtxt::new(tcx, body_id);
1337let fn_ctxt = FnCtxt::new(&root_ctxt, param_env, body_id);
1338fn_ctxt.may_coerce(ty, output_ty)
1339}
13401341/// CoerceMany encapsulates the pattern you should use when you have
1342/// many expressions that are all getting coerced to a common
1343/// type. This arises, for example, when you have a match (the result
1344/// of each arm is coerced to a common type). It also arises in less
1345/// obvious places, such as when you have many `break foo` expressions
1346/// that target the same loop, or the various `return` expressions in
1347/// a function.
1348///
1349/// The basic protocol is as follows:
1350///
1351/// - Instantiate the `CoerceMany` with an initial `expected_ty`.
1352/// This will also serve as the "starting LUB". The expectation is
1353/// that this type is something which all of the expressions *must*
1354/// be coercible to. Use a fresh type variable if needed.
1355/// - For each expression whose result is to be coerced, invoke `coerce()` with.
1356/// - In some cases we wish to coerce "non-expressions" whose types are implicitly
1357/// unit. This happens for example if you have a `break` with no expression,
1358/// or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
1359/// - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
1360/// from you so that you don't have to worry your pretty head about it.
1361/// But if an error is reported, the final type will be `err`.
1362/// - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
1363/// previously coerced expressions.
1364/// - When all done, invoke `complete()`. This will return the LUB of
1365/// all your expressions.
1366/// - WARNING: I don't believe this final type is guaranteed to be
1367/// related to your initial `expected_ty` in any particular way,
1368/// although it will typically be a subtype, so you should check it.
1369/// Check the note below for more details.
1370/// - Invoking `complete()` may cause us to go and adjust the "adjustments" on
1371/// previously coerced expressions.
1372///
1373/// Example:
1374///
1375/// ```ignore (illustrative)
1376/// let mut coerce = CoerceMany::new(expected_ty);
1377/// for expr in exprs {
1378/// let expr_ty = fcx.check_expr_with_expectation(expr, expected);
1379/// coerce.coerce(fcx, &cause, expr, expr_ty);
1380/// }
1381/// let final_ty = coerce.complete(fcx);
1382/// ```
1383///
1384/// NOTE: Why does the `expected_ty` participate in the LUB?
1385/// When coercing, each branch should use the following expectations for type inference:
1386/// - The branch can be coerced to the expected type of the match/if/whatever.
1387/// - The branch can be coercion lub'd with the types of the previous branches.
1388/// Ideally we'd have some sort of `Expectation::ParticipatesInCoerceLub(ongoing_lub_ty, final_ty)`,
1389/// but adding and using this feels very challenging.
1390/// What we instead do is to use the expected type of the match/if/whatever as
1391/// the initial coercion lub. This allows us to use the lub of "expected type of match" with
1392/// "types from previous branches" as the coercion target, which can contains both expectations.
1393///
1394/// Two concerns with this approach:
1395/// - We may have incompatible `final_ty` if that lub is different from the expected
1396/// type of the match. However, in this case coercing the final type of the
1397/// `CoerceMany` to its expected type would have error'd anyways, so we don't care.
1398/// - We may constrain the `expected_ty` too early. For some branches with
1399/// type `a` and `b`, we end up with `(a lub expected_ty) lub b` instead of
1400/// `(a lub b) lub expected_ty`. They should be the same type. However,
1401/// `a lub expected_ty` may constrain inference variables in `expected_ty`.
1402/// In this case the difference does matter and we get actually incorrect results.
1403/// FIXME: Ideally we'd compute the final type without unnecessarily constraining
1404/// the expected type of the match when computing the types of its branches.
1405pub(crate) struct CoerceMany<'tcx> {
1406 expected_ty: Ty<'tcx>,
1407 final_ty: Option<Ty<'tcx>>,
1408 expressions: Vec<&'tcx hir::Expr<'tcx>>,
1409}
14101411impl<'tcx> CoerceMany<'tcx> {
1412/// Creates a `CoerceMany` with a default capacity of 1. If the full set of
1413 /// coercion sites is known before hand, consider `with_capacity()` instead
1414 /// to avoid allocation.
1415pub(crate) fn new(expected_ty: Ty<'tcx>) -> Self {
1416Self::with_capacity(expected_ty, 1)
1417 }
14181419/// Creates a `CoerceMany` with a given capacity.
1420pub(crate) fn with_capacity(expected_ty: Ty<'tcx>, capacity: usize) -> Self {
1421CoerceMany { expected_ty, final_ty: None, expressions: Vec::with_capacity(capacity) }
1422 }
14231424/// Returns the "expected type" with which this coercion was
1425 /// constructed. This represents the "downward propagated" type
1426 /// that was given to us at the start of typing whatever construct
1427 /// we are typing (e.g., the match expression).
1428 ///
1429 /// Typically, this is used as the expected type when
1430 /// type-checking each of the alternative expressions whose types
1431 /// we are trying to merge.
1432pub(crate) fn expected_ty(&self) -> Ty<'tcx> {
1433self.expected_ty
1434 }
14351436/// Returns the current "merged type", representing our best-guess
1437 /// at the LUB of the expressions we've seen so far (if any). This
1438 /// isn't *final* until you call `self.complete()`, which will return
1439 /// the merged type.
1440pub(crate) fn merged_ty(&self) -> Ty<'tcx> {
1441self.final_ty.unwrap_or(self.expected_ty)
1442 }
14431444/// Indicates that the value generated by `expression`, which is
1445 /// of type `expression_ty`, is one of the possibilities that we
1446 /// could coerce from. This will record `expression`, and later
1447 /// calls to `coerce` may come back and add adjustments and things
1448 /// if necessary.
1449pub(crate) fn coerce<'a>(
1450&mut self,
1451 fcx: &FnCtxt<'a, 'tcx>,
1452 cause: &ObligationCause<'tcx>,
1453 expression: &'tcx hir::Expr<'tcx>,
1454 expression_ty: Ty<'tcx>,
1455 ) {
1456self.coerce_inner(fcx, cause, Some(expression), expression_ty, |_| {}, false)
1457 }
14581459/// Indicates that one of the inputs is a "forced unit". This
1460 /// occurs in a case like `if foo { ... };`, where the missing else
1461 /// generates a "forced unit". Another example is a `loop { break;
1462 /// }`, where the `break` has no argument expression. We treat
1463 /// these cases slightly differently for error-reporting
1464 /// purposes. Note that these tend to correspond to cases where
1465 /// the `()` expression is implicit in the source, and hence we do
1466 /// not take an expression argument.
1467 ///
1468 /// The `augment_error` gives you a chance to extend the error
1469 /// message, in case any results (e.g., we use this to suggest
1470 /// removing a `;`).
1471pub(crate) fn coerce_forced_unit<'a>(
1472&mut self,
1473 fcx: &FnCtxt<'a, 'tcx>,
1474 cause: &ObligationCause<'tcx>,
1475 augment_error: impl FnOnce(&mut Diag<'_>),
1476 label_unit_as_expected: bool,
1477 ) {
1478self.coerce_inner(
1479fcx,
1480cause,
1481None,
1482fcx.tcx.types.unit,
1483augment_error,
1484label_unit_as_expected,
1485 )
1486 }
14871488/// The inner coercion "engine". If `expression` is `None`, this
1489 /// is a forced-unit case, and hence `expression_ty` must be
1490 /// `Nil`.
1491#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("coerce_inner",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(1491u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["cause",
"expression", "expression_ty"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expression)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expression_ty)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
if expression_ty.is_ty_var() {
expression_ty = fcx.infcx.shallow_resolve(expression_ty);
}
if let Err(guar) =
(expression_ty, self.merged_ty()).error_reported() {
self.final_ty = Some(Ty::new_error(fcx.tcx, guar));
return;
}
let (expected, found) =
if label_expression_as_expected {
(expression_ty, self.merged_ty())
} else { (self.merged_ty(), expression_ty) };
let result =
if let Some(expression) = expression {
if self.expressions.is_empty() {
fcx.coerce(expression, expression_ty, self.expected_ty,
AllowTwoPhase::No, Some(cause.clone()))
} else {
fcx.try_find_coercion_lub(cause, &self.expressions,
self.merged_ty(), expression, expression_ty)
}
} else {
if !expression_ty.is_unit() {
{
::core::panicking::panic_fmt(format_args!("if let hack without unit type"));
}
};
fcx.at(cause,
fcx.param_env).eq(DefineOpaqueTypes::Yes, expected,
found).map(|infer_ok|
{
fcx.register_infer_ok_obligations(infer_ok);
expression_ty
})
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:1582",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(1582u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["result"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&result) as
&dyn Value))])
});
} else { ; }
};
match result {
Ok(v) => {
self.final_ty = Some(v);
if let Some(e) = expression { self.expressions.push(e); }
}
Err(coercion_error) => {
fcx.set_tainted_by_errors(fcx.dcx().span_delayed_bug(cause.span,
"coercion error but no error emitted"));
let (expected, found) =
fcx.resolve_vars_if_possible((expected, found));
let mut err;
let mut unsized_return = false;
match *cause.code() {
ObligationCauseCode::ReturnNoExpression => {
err =
{
fcx.dcx().struct_span_err(cause.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`return;` in a function whose return type is not `()`"))
})).with_code(E0069)
};
if let Some(value) =
fcx.err_ctxt().ty_kind_suggestion(fcx.param_env, found) {
err.span_suggestion_verbose(cause.span.shrink_to_hi(),
"give the `return` a value of the expected type",
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {0}", value))
}), Applicability::HasPlaceholders);
}
err.span_label(cause.span, "return type is not `()`");
}
ObligationCauseCode::BlockTailExpression(blk_id, ..) => {
err =
self.report_return_mismatched_types(cause, expected, found,
coercion_error, fcx, blk_id, expression);
unsized_return = self.is_return_ty_definitely_unsized(fcx);
}
ObligationCauseCode::ReturnValue(return_expr_id) => {
err =
self.report_return_mismatched_types(cause, expected, found,
coercion_error, fcx, return_expr_id, expression);
unsized_return = self.is_return_ty_definitely_unsized(fcx);
}
ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
arm_span,
arm_ty,
prior_arm_ty,
ref prior_non_diverging_arms,
tail_defines_return_position_impl_trait: Some(rpit_def_id),
.. }) => {
err =
fcx.err_ctxt().report_mismatched_types(cause, fcx.param_env,
expected, found, coercion_error);
if prior_non_diverging_arms.len() > 0 {
self.suggest_boxing_tail_for_return_position_impl_trait(fcx,
&mut err, rpit_def_id, arm_ty, prior_arm_ty,
prior_non_diverging_arms.iter().chain(std::iter::once(&arm_span)).copied());
}
}
ObligationCauseCode::IfExpression {
expr_id,
tail_defines_return_position_impl_trait: Some(rpit_def_id) }
=> {
let hir::Node::Expr(hir::Expr {
kind: hir::ExprKind::If(_, then_expr, Some(else_expr)), ..
}) =
fcx.tcx.hir_node(expr_id) else {
::core::panicking::panic("internal error: entered unreachable code");
};
err =
fcx.err_ctxt().report_mismatched_types(cause, fcx.param_env,
expected, found, coercion_error);
let then_span =
fcx.find_block_span_from_hir_id(then_expr.hir_id);
let else_span =
fcx.find_block_span_from_hir_id(else_expr.hir_id);
if then_span != then_expr.span &&
else_span != else_expr.span {
let then_ty =
fcx.typeck_results.borrow().expr_ty(then_expr);
let else_ty =
fcx.typeck_results.borrow().expr_ty(else_expr);
self.suggest_boxing_tail_for_return_position_impl_trait(fcx,
&mut err, rpit_def_id, then_ty, else_ty,
[then_span, else_span].into_iter());
}
}
_ => {
err =
fcx.err_ctxt().report_mismatched_types(cause, fcx.param_env,
expected, found, coercion_error);
}
}
augment_error(&mut err);
if let Some(expr) = expression {
if let hir::ExprKind::Loop(_, _, loop_src @
(hir::LoopSource::While | hir::LoopSource::ForLoop), _) =
expr.kind {
let loop_type =
if loop_src == hir::LoopSource::While {
"`while` loops"
} else { "`for` loops" };
err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} evaluate to unit type `()`",
loop_type))
}));
}
fcx.emit_coerce_suggestions(&mut err, expr, found, expected,
None, Some(coercion_error));
}
let reported = err.emit_unless_delay(unsized_return);
self.final_ty = Some(Ty::new_error(fcx.tcx, reported));
}
}
}
}
}#[instrument(skip(self, fcx, augment_error, label_expression_as_expected), level = "debug")]1492pub(crate) fn coerce_inner<'a>(
1493&mut self,
1494 fcx: &FnCtxt<'a, 'tcx>,
1495 cause: &ObligationCause<'tcx>,
1496 expression: Option<&'tcx hir::Expr<'tcx>>,
1497mut expression_ty: Ty<'tcx>,
1498 augment_error: impl FnOnce(&mut Diag<'_>),
1499 label_expression_as_expected: bool,
1500 ) {
1501// Incorporate whatever type inference information we have
1502 // until now; in principle we might also want to process
1503 // pending obligations, but doing so should only improve
1504 // compatibility (hopefully that is true) by helping us
1505 // uncover never types better.
1506if expression_ty.is_ty_var() {
1507 expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1508 }
15091510// If we see any error types, just propagate that error
1511 // upwards.
1512if let Err(guar) = (expression_ty, self.merged_ty()).error_reported() {
1513self.final_ty = Some(Ty::new_error(fcx.tcx, guar));
1514return;
1515 }
15161517let (expected, found) = if label_expression_as_expected {
1518// In the case where this is a "forced unit", like
1519 // `break`, we want to call the `()` "expected"
1520 // since it is implied by the syntax.
1521 // (Note: not all force-units work this way.)"
1522(expression_ty, self.merged_ty())
1523 } else {
1524// Otherwise, the "expected" type for error
1525 // reporting is the current unification type,
1526 // which is basically the LUB of the expressions
1527 // we've seen so far (combined with the expected
1528 // type)
1529(self.merged_ty(), expression_ty)
1530 };
15311532// Handle the actual type unification etc.
1533let result = if let Some(expression) = expression {
1534if self.expressions.is_empty() {
1535// Special-case the first expression we are coercing.
1536 // To be honest, I'm not entirely sure why we do this.
1537 // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
1538fcx.coerce(
1539 expression,
1540 expression_ty,
1541self.expected_ty,
1542 AllowTwoPhase::No,
1543Some(cause.clone()),
1544 )
1545 } else {
1546 fcx.try_find_coercion_lub(
1547 cause,
1548&self.expressions,
1549self.merged_ty(),
1550 expression,
1551 expression_ty,
1552 )
1553 }
1554 } else {
1555// this is a hack for cases where we default to `()` because
1556 // the expression etc has been omitted from the source. An
1557 // example is an `if let` without an else:
1558 //
1559 // if let Some(x) = ... { }
1560 //
1561 // we wind up with a second match arm that is like `_ =>
1562 // ()`. That is the case we are considering here. We take
1563 // a different path to get the right "expected, found"
1564 // message and so forth (and because we know that
1565 // `expression_ty` will be unit).
1566 //
1567 // Another example is `break` with no argument expression.
1568assert!(expression_ty.is_unit(), "if let hack without unit type");
1569 fcx.at(cause, fcx.param_env)
1570 .eq(
1571// needed for tests/ui/type-alias-impl-trait/issue-65679-inst-opaque-ty-from-val-twice.rs
1572DefineOpaqueTypes::Yes,
1573 expected,
1574 found,
1575 )
1576 .map(|infer_ok| {
1577 fcx.register_infer_ok_obligations(infer_ok);
1578 expression_ty
1579 })
1580 };
15811582debug!(?result);
1583match result {
1584Ok(v) => {
1585self.final_ty = Some(v);
1586if let Some(e) = expression {
1587self.expressions.push(e);
1588 }
1589 }
1590Err(coercion_error) => {
1591// Mark that we've failed to coerce the types here to suppress
1592 // any superfluous errors we might encounter while trying to
1593 // emit or provide suggestions on how to fix the initial error.
1594fcx.set_tainted_by_errors(
1595 fcx.dcx().span_delayed_bug(cause.span, "coercion error but no error emitted"),
1596 );
1597let (expected, found) = fcx.resolve_vars_if_possible((expected, found));
15981599let mut err;
1600let mut unsized_return = false;
1601match *cause.code() {
1602 ObligationCauseCode::ReturnNoExpression => {
1603 err = struct_span_code_err!(
1604 fcx.dcx(),
1605 cause.span,
1606 E0069,
1607"`return;` in a function whose return type is not `()`"
1608);
1609if let Some(value) = fcx.err_ctxt().ty_kind_suggestion(fcx.param_env, found)
1610 {
1611 err.span_suggestion_verbose(
1612 cause.span.shrink_to_hi(),
1613"give the `return` a value of the expected type",
1614format!(" {value}"),
1615 Applicability::HasPlaceholders,
1616 );
1617 }
1618 err.span_label(cause.span, "return type is not `()`");
1619 }
1620 ObligationCauseCode::BlockTailExpression(blk_id, ..) => {
1621 err = self.report_return_mismatched_types(
1622 cause,
1623 expected,
1624 found,
1625 coercion_error,
1626 fcx,
1627 blk_id,
1628 expression,
1629 );
1630 unsized_return = self.is_return_ty_definitely_unsized(fcx);
1631 }
1632 ObligationCauseCode::ReturnValue(return_expr_id) => {
1633 err = self.report_return_mismatched_types(
1634 cause,
1635 expected,
1636 found,
1637 coercion_error,
1638 fcx,
1639 return_expr_id,
1640 expression,
1641 );
1642 unsized_return = self.is_return_ty_definitely_unsized(fcx);
1643 }
1644 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
1645 arm_span,
1646 arm_ty,
1647 prior_arm_ty,
1648ref prior_non_diverging_arms,
1649 tail_defines_return_position_impl_trait: Some(rpit_def_id),
1650 ..
1651 }) => {
1652 err = fcx.err_ctxt().report_mismatched_types(
1653 cause,
1654 fcx.param_env,
1655 expected,
1656 found,
1657 coercion_error,
1658 );
1659// Check that we're actually in the second or later arm
1660if prior_non_diverging_arms.len() > 0 {
1661self.suggest_boxing_tail_for_return_position_impl_trait(
1662 fcx,
1663&mut err,
1664 rpit_def_id,
1665 arm_ty,
1666 prior_arm_ty,
1667 prior_non_diverging_arms
1668 .iter()
1669 .chain(std::iter::once(&arm_span))
1670 .copied(),
1671 );
1672 }
1673 }
1674 ObligationCauseCode::IfExpression {
1675 expr_id,
1676 tail_defines_return_position_impl_trait: Some(rpit_def_id),
1677 } => {
1678let hir::Node::Expr(hir::Expr {
1679 kind: hir::ExprKind::If(_, then_expr, Some(else_expr)),
1680 ..
1681 }) = fcx.tcx.hir_node(expr_id)
1682else {
1683unreachable!();
1684 };
1685 err = fcx.err_ctxt().report_mismatched_types(
1686 cause,
1687 fcx.param_env,
1688 expected,
1689 found,
1690 coercion_error,
1691 );
1692let then_span = fcx.find_block_span_from_hir_id(then_expr.hir_id);
1693let else_span = fcx.find_block_span_from_hir_id(else_expr.hir_id);
1694// Don't suggest wrapping whole block in `Box::new`.
1695if then_span != then_expr.span && else_span != else_expr.span {
1696let then_ty = fcx.typeck_results.borrow().expr_ty(then_expr);
1697let else_ty = fcx.typeck_results.borrow().expr_ty(else_expr);
1698self.suggest_boxing_tail_for_return_position_impl_trait(
1699 fcx,
1700&mut err,
1701 rpit_def_id,
1702 then_ty,
1703 else_ty,
1704 [then_span, else_span].into_iter(),
1705 );
1706 }
1707 }
1708_ => {
1709 err = fcx.err_ctxt().report_mismatched_types(
1710 cause,
1711 fcx.param_env,
1712 expected,
1713 found,
1714 coercion_error,
1715 );
1716 }
1717 }
17181719 augment_error(&mut err);
17201721if let Some(expr) = expression {
1722if let hir::ExprKind::Loop(
1723_,
1724_,
1725 loop_src @ (hir::LoopSource::While | hir::LoopSource::ForLoop),
1726_,
1727 ) = expr.kind
1728 {
1729let loop_type = if loop_src == hir::LoopSource::While {
1730"`while` loops"
1731} else {
1732"`for` loops"
1733};
17341735 err.note(format!("{loop_type} evaluate to unit type `()`"));
1736 }
17371738 fcx.emit_coerce_suggestions(
1739&mut err,
1740 expr,
1741 found,
1742 expected,
1743None,
1744Some(coercion_error),
1745 );
1746 }
17471748let reported = err.emit_unless_delay(unsized_return);
17491750self.final_ty = Some(Ty::new_error(fcx.tcx, reported));
1751 }
1752 }
1753 }
17541755fn suggest_boxing_tail_for_return_position_impl_trait(
1756&self,
1757 fcx: &FnCtxt<'_, 'tcx>,
1758 err: &mut Diag<'_>,
1759 rpit_def_id: LocalDefId,
1760 a_ty: Ty<'tcx>,
1761 b_ty: Ty<'tcx>,
1762 arm_spans: impl Iterator<Item = Span>,
1763 ) {
1764let compatible = |ty: Ty<'tcx>| {
1765fcx.probe(|_| {
1766let ocx = ObligationCtxt::new(fcx);
1767ocx.register_obligations(
1768fcx.tcx.item_self_bounds(rpit_def_id).iter_identity().filter_map(|clause| {
1769let predicate = clause1770 .kind()
1771 .map_bound(|clause| match clause {
1772 ty::ClauseKind::Trait(trait_pred) => Some(ty::ClauseKind::Trait(
1773trait_pred.with_replaced_self_ty(fcx.tcx, ty),
1774 )),
1775 ty::ClauseKind::Projection(proj_pred) => {
1776Some(ty::ClauseKind::Projection(
1777proj_pred.with_replaced_self_ty(fcx.tcx, ty),
1778 ))
1779 }
1780_ => None,
1781 })
1782 .transpose()?;
1783Some(Obligation::new(
1784fcx.tcx,
1785ObligationCause::dummy(),
1786fcx.param_env,
1787predicate,
1788 ))
1789 }),
1790 );
1791ocx.try_evaluate_obligations().is_empty()
1792 })
1793 };
17941795if !compatible(a_ty) || !compatible(b_ty) {
1796return;
1797 }
17981799let rpid_def_span = fcx.tcx.def_span(rpit_def_id);
1800err.subdiagnostic(SuggestBoxingForReturnImplTrait::ChangeReturnType {
1801 start_sp: rpid_def_span.with_hi(rpid_def_span.lo() + BytePos(4)),
1802 end_sp: rpid_def_span.shrink_to_hi(),
1803 });
18041805let (starts, ends) =
1806arm_spans.map(|span| (span.shrink_to_lo(), span.shrink_to_hi())).unzip();
1807err.subdiagnostic(SuggestBoxingForReturnImplTrait::BoxReturnExpr { starts, ends });
1808 }
18091810fn report_return_mismatched_types<'infcx>(
1811&self,
1812 cause: &ObligationCause<'tcx>,
1813 expected: Ty<'tcx>,
1814 found: Ty<'tcx>,
1815 ty_err: TypeError<'tcx>,
1816 fcx: &'infcx FnCtxt<'_, 'tcx>,
1817 block_or_return_id: hir::HirId,
1818 expression: Option<&'tcx hir::Expr<'tcx>>,
1819 ) -> Diag<'infcx> {
1820let mut err =
1821fcx.err_ctxt().report_mismatched_types(cause, fcx.param_env, expected, found, ty_err);
18221823let due_to_block = #[allow(non_exhaustive_omitted_patterns)] match fcx.tcx.hir_node(block_or_return_id)
{
hir::Node::Block(..) => true,
_ => false,
}matches!(fcx.tcx.hir_node(block_or_return_id), hir::Node::Block(..));
1824let parent = fcx.tcx.parent_hir_node(block_or_return_id);
1825if let Some(expr) = expression1826 && let hir::Node::Expr(&hir::Expr {
1827 kind: hir::ExprKind::Closure(&hir::Closure { body, .. }),
1828 ..
1829 }) = parent1830 {
1831let needs_block =
1832 !#[allow(non_exhaustive_omitted_patterns)] match fcx.tcx.hir_body(body).value.kind
{
hir::ExprKind::Block(..) => true,
_ => false,
}matches!(fcx.tcx.hir_body(body).value.kind, hir::ExprKind::Block(..));
1833fcx.suggest_missing_semicolon(&mut err, expr, expected, needs_block, true);
1834 }
1835// Verify that this is a tail expression of a function, otherwise the
1836 // label pointing out the cause for the type coercion will be wrong
1837 // as prior return coercions would not be relevant (#57664).
1838if let Some(expr) = expression1839 && due_to_block1840 {
1841fcx.suggest_missing_semicolon(&mut err, expr, expected, false, false);
1842let pointing_at_return_type = fcx.suggest_mismatched_types_on_tail(
1843&mut err,
1844expr,
1845expected,
1846found,
1847block_or_return_id,
1848 );
1849if let Some(cond_expr) = fcx.tcx.hir_get_if_cause(expr.hir_id)
1850 && expected.is_unit()
1851 && !pointing_at_return_type1852// If the block is from an external macro or try (`?`) desugaring, then
1853 // do not suggest adding a semicolon, because there's nowhere to put it.
1854 // See issues #81943 and #87051.
1855 // Similarly, if the block is from a loop desugaring, then also do not
1856 // suggest adding a semicolon. See issue #150850.
1857&& cond_expr.span.desugaring_kind().is_none()
1858 && !cond_expr.span.in_external_macro(fcx.tcx.sess.source_map())
1859 && !#[allow(non_exhaustive_omitted_patterns)] match cond_expr.kind {
hir::ExprKind::Match(.., hir::MatchSource::TryDesugar(_)) => true,
_ => false,
}matches!(
1860 cond_expr.kind,
1861 hir::ExprKind::Match(.., hir::MatchSource::TryDesugar(_))
1862 )1863 {
1864if let ObligationCauseCode::BlockTailExpression(hir_id, hir::MatchSource::Normal) =
1865cause.code()
1866 && let hir::Node::Block(block) = fcx.tcx.hir_node(*hir_id)
1867 && let hir::Node::Expr(expr) = fcx.tcx.parent_hir_node(block.hir_id)
1868 && let hir::Node::Expr(if_expr) = fcx.tcx.parent_hir_node(expr.hir_id)
1869 && let hir::ExprKind::If(_cond, _then, None) = if_expr.kind
1870 {
1871err.span_label(
1872cond_expr.span,
1873"`if` expressions without `else` arms expect their inner expression to be `()`",
1874 );
1875 } else {
1876err.span_label(cond_expr.span, "expected this to be `()`");
1877 }
1878if expr.can_have_side_effects() {
1879fcx.suggest_semicolon_at_end(cond_expr.span, &mut err);
1880 }
1881 }
1882 }
18831884// If this is due to an explicit `return`, suggest adding a return type.
1885if let Some((fn_id, fn_decl)) = fcx.get_fn_decl(block_or_return_id)
1886 && !due_to_block1887 {
1888fcx.suggest_missing_return_type(&mut err, fn_decl, expected, found, fn_id);
1889 }
18901891// If this is due to a block, then maybe we forgot a `return`/`break`.
1892if due_to_block1893 && let Some(expr) = expression1894 && let Some(parent_fn_decl) =
1895fcx.tcx.hir_fn_decl_by_hir_id(fcx.tcx.local_def_id_to_hir_id(fcx.body_id))
1896 {
1897fcx.suggest_missing_break_or_return_expr(
1898&mut err,
1899expr,
1900parent_fn_decl,
1901expected,
1902found,
1903block_or_return_id,
1904fcx.body_id,
1905 );
1906 }
19071908let ret_coercion_span = fcx.ret_coercion_span.get();
19091910if let Some(sp) = ret_coercion_span1911// If the closure has an explicit return type annotation, or if
1912 // the closure's return type has been inferred from outside
1913 // requirements (such as an Fn* trait bound), then a type error
1914 // may occur at the first return expression we see in the closure
1915 // (if it conflicts with the declared return type). Skip adding a
1916 // note in this case, since it would be incorrect.
1917&& let Some(fn_sig) = fcx.body_fn_sig()
1918 && fn_sig.output().is_ty_var()
1919 {
1920err.span_note(sp, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("return type inferred to be `{0}` here",
expected))
})format!("return type inferred to be `{expected}` here"));
1921 }
19221923err1924 }
19251926/// Checks whether the return type is unsized via an obligation, which makes
1927 /// sure we consider `dyn Trait: Sized` where clauses, which are trivially
1928 /// false but technically valid for typeck.
1929fn is_return_ty_definitely_unsized(&self, fcx: &FnCtxt<'_, 'tcx>) -> bool {
1930if let Some(sig) = fcx.body_fn_sig() {
1931 !fcx.predicate_may_hold(&Obligation::new(
1932fcx.tcx,
1933ObligationCause::dummy(),
1934fcx.param_env,
1935 ty::TraitRef::new(
1936fcx.tcx,
1937fcx.tcx.require_lang_item(hir::LangItem::Sized, DUMMY_SP),
1938 [sig.output()],
1939 ),
1940 ))
1941 } else {
1942false
1943}
1944 }
19451946pub(crate) fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> {
1947if let Some(final_ty) = self.final_ty {
1948final_ty1949 } else {
1950// If we only had inputs that were of type `!` (or no
1951 // inputs at all), then the final type is `!`.
1952if !self.expressions.is_empty() {
::core::panicking::panic("assertion failed: self.expressions.is_empty()")
};assert!(self.expressions.is_empty());
1953fcx.tcx.types.never
1954 }
1955 }
1956}
19571958/// Recursively visit goals to decide whether an unsizing is possible.
1959/// `Break`s when it isn't, and an error should be raised.
1960/// `Continue`s when an unsizing ok based on an implementation of the `Unsize` trait / lang item.
1961struct CoerceVisitor<'a, 'tcx> {
1962 fcx: &'a FnCtxt<'a, 'tcx>,
1963 span: Span,
1964}
19651966impl<'tcx> ProofTreeVisitor<'tcx> for CoerceVisitor<'_, 'tcx> {
1967type Result = ControlFlow<()>;
19681969fn span(&self) -> Span {
1970self.span
1971 }
19721973fn visit_goal(&mut self, goal: &inspect::InspectGoal<'_, 'tcx>) -> Self::Result {
1974let Some(pred) = goal.goal().predicate.as_trait_clause() else {
1975return ControlFlow::Continue(());
1976 };
19771978// Make sure this predicate is referring to either an `Unsize` or `CoerceUnsized` trait,
1979 // Otherwise there's nothing to do.
1980if !self.fcx.tcx.is_lang_item(pred.def_id(), LangItem::Unsize)
1981 && !self.fcx.tcx.is_lang_item(pred.def_id(), LangItem::CoerceUnsized)
1982 {
1983return ControlFlow::Continue(());
1984 }
19851986match goal.result() {
1987// If we prove the `Unsize` or `CoerceUnsized` goal, continue recursing.
1988Ok(Certainty::Yes) => ControlFlow::Continue(()),
1989Err(NoSolution) => {
1990// Even if we find no solution, continue recursing if we find a single candidate
1991 // for which we're shallowly certain it holds to get the right error source.
1992if let [only_candidate] = &goal.candidates()[..]
1993 && only_candidate.shallow_certainty() == Certainty::Yes1994 {
1995only_candidate.visit_nested_no_probe(self)
1996 } else {
1997 ControlFlow::Break(())
1998 }
1999 }
2000Ok(Certainty::Maybe { .. }) => {
2001// FIXME: structurally normalize?
2002if self.fcx.tcx.is_lang_item(pred.def_id(), LangItem::Unsize)
2003 && let ty::Dynamic(..) = pred.skip_binder().trait_ref.args.type_at(1).kind()
2004 && let ty::Infer(ty::TyVar(vid)) = *pred.self_ty().skip_binder().kind()
2005 && self.fcx.type_var_is_sized(vid)
2006 {
2007// We get here when trying to unsize a type variable to a `dyn Trait`,
2008 // knowing that that variable is sized. Unsizing definitely has to happen in that case.
2009 // If the variable weren't sized, we may not need an unsizing coercion.
2010 // In general, we don't want to add coercions too eagerly since it makes error messages much worse.
2011ControlFlow::Continue(())
2012 } else if let Some(cand) = goal.unique_applicable_candidate()
2013 && cand.shallow_certainty() == Certainty::Yes2014 {
2015cand.visit_nested_no_probe(self)
2016 } else {
2017 ControlFlow::Break(())
2018 }
2019 }
2020 }
2021 }
2022}