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_hiras hir;
43use rustc_hir::attrs::InlineAttr;
44use rustc_hir::attrs::lang_items::LangItem;
45use rustc_hir::def_id::{DefId, LocalDefId};
46use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer;
47use rustc_infer::infer::relate::RelateResult;
48use rustc_infer::infer::{DefineOpaqueTypes, InferOk, InferResult, RegionVariableOrigin};
49use rustc_infer::traits::{
50MatchExpressionArmCause, Obligation, PredicateObligation, PredicateObligations, SelectionError,
51};
52use rustc_middle::span_bug;
53use rustc_middle::ty::adjustment::{
54Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, DerefAdjustKind,
55PointerCoercion,
56};
57use rustc_middle::ty::error::TypeError;
58use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt, Unnormalized};
59use rustc_span::{BytePos, DUMMY_SP, Span};
60use rustc_trait_selection::infer::InferCtxtExt as _;
61use rustc_trait_selection::solve::inspect::{self, InferCtxtProofTreeExt, ProofTreeVisitor};
62use rustc_trait_selection::solve::{Certainty, Goal, NoSolution};
63use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
64use rustc_trait_selection::traits::{
65self, ImplSource, NormalizeExt, ObligationCause, ObligationCauseCode, ObligationCtxt,
66};
67use smallvec::{SmallVec, smallvec};
68use tracing::{debug, instrument};
6970use crate::FnCtxt;
71use crate::diagnostics::SuggestBoxingForReturnImplTrait;
7273struct Coerce<'a, 'tcx> {
74 fcx: &'a FnCtxt<'a, 'tcx>,
75 cause: ObligationCause<'tcx>,
76 use_lub: bool,
77/// Determines whether or not allow_two_phase_borrow is set on any
78 /// autoref adjustments we create while coercing. We don't want to
79 /// allow deref coercions to create two-phase borrows, at least initially,
80 /// but we do need two-phase borrows for function argument reborrows.
81 /// See #47489 and #48598
82 /// See docs on the "AllowTwoPhase" type for a more detailed discussion
83allow_two_phase: AllowTwoPhase,
84/// Whether we allow `NeverToAny` coercions. This is unsound if we're
85 /// coercing a place expression without it counting as a read in the MIR.
86 /// This is a side-effect of HIR not really having a great distinction
87 /// between places and values.
88coerce_never: bool,
89}
9091impl<'a, 'tcx> Dereffor Coerce<'a, 'tcx> {
92type Target = FnCtxt<'a, 'tcx>;
93fn deref(&self) -> &Self::Target {
94self.fcx
95 }
96}
9798type CoerceResult<'tcx> = InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>;
99100/// Coercing a mutable reference to an immutable works, while
101/// coercing `&T` to `&mut T` should be forbidden.
102fn coerce_mutbls<'tcx>(
103 from_mutbl: hir::Mutability,
104 to_mutbl: hir::Mutability,
105) -> RelateResult<'tcx, ()> {
106if from_mutbl >= to_mutbl { Ok(()) } else { Err(TypeError::Mutability) }
107}
108109/// This always returns `Ok(...)`.
110fn success<'tcx>(
111 adj: Vec<Adjustment<'tcx>>,
112 target: Ty<'tcx>,
113 obligations: PredicateObligations<'tcx>,
114) -> CoerceResult<'tcx> {
115Ok(InferOk { value: (adj, target), obligations })
116}
117118/// Data extracted from a reference (pinned or not) for coercion to a reference (pinned or not).
119struct CoerceMaybePinnedRef<'tcx> {
120/// coercion source, must be a pinned (i.e. `Pin<&T>` or `Pin<&mut T>`) or normal reference (`&T` or `&mut T`)
121a: Ty<'tcx>,
122/// coercion target, must be a pinned (i.e. `Pin<&T>` or `Pin<&mut T>`) or normal reference (`&T` or `&mut T`)
123b: Ty<'tcx>,
124/// referent type of the source
125a_ty: Ty<'tcx>,
126/// pinnedness of the source
127a_pin: ty::Pinnedness,
128/// mutability of the source
129a_mut: ty::Mutability,
130/// region of the source
131a_r: ty::Region<'tcx>,
132/// pinnedness of the target
133b_pin: ty::Pinnedness,
134/// mutability of the target
135b_mut: ty::Mutability,
136}
137138/// Whether to force a leak check to occur in `Coerce::unify_raw`.
139/// Note that leak checks may still occur evn with `ForceLeakCheck::No`.
140///
141/// FIXME: We may want to change type relations to always leak-check
142/// after exiting a binder, at which point we will always do so and
143/// no longer need to handle this explicitly
144enum ForceLeakCheck {
145 Yes,
146 No,
147}
148149impl<'f, 'tcx> Coerce<'f, 'tcx> {
150fn new(
151 fcx: &'f FnCtxt<'f, 'tcx>,
152 cause: ObligationCause<'tcx>,
153 allow_two_phase: AllowTwoPhase,
154 coerce_never: bool,
155 ) -> Self {
156Coerce { fcx, cause, allow_two_phase, use_lub: false, coerce_never }
157 }
158159fn unify_raw(
160&self,
161 a: Ty<'tcx>,
162 b: Ty<'tcx>,
163 leak_check: ForceLeakCheck,
164 ) -> InferResult<'tcx, Ty<'tcx>> {
165{
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:165",
"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(165u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("unify(a: {0:?}, b: {1:?}, use_lub: {2})",
a, b, self.use_lub) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("unify(a: {:?}, b: {:?}, use_lub: {})", a, b, self.use_lub);
166self.commit_if_ok(|snapshot| {
167let outer_universe = self.infcx.universe();
168169let at = self.at(&self.cause, self.fcx.param_env);
170171let res = if self.use_lub {
172at.lub(b, a)
173 } else {
174at.sup(DefineOpaqueTypes::Yes, b, a)
175 .map(|InferOk { value: (), obligations }| InferOk { value: b, obligations })
176 };
177178// In the new solver, lazy norm may allow us to shallowly equate
179 // more types, but we emit possibly impossible-to-satisfy obligations.
180 // Filter these cases out to make sure our coercion is more accurate.
181let res = match res {
182Ok(InferOk { value, obligations }) if self.next_trait_solver() => {
183let ocx = ObligationCtxt::new(self);
184ocx.register_obligations(obligations);
185if ocx.try_evaluate_obligations().no_errors() {
186Ok(InferOk { value, obligations: ocx.into_pending_obligations() })
187 } else {
188Err(TypeError::Mismatch)
189 }
190 }
191 res => res,
192 };
193194// We leak check here mostly because lub operations are
195 // kind of scuffed around binders. Instead of computing an actual
196 // lub'd binder we instead:
197 // - Equate the binders
198 // - Return the lhs of the lub operation
199 //
200 // This may lead to incomplete type inference for the resulting type
201 // of a `match` or `if .. else`, etc. This is a backwards compat
202 // hazard for if/when we start handling `lub` more correctly.
203 //
204 // In order to actually ensure that equating the binders *does*
205 // result in equal binders, and that the lhs is actually a supertype
206 // of the rhs, we must perform a leak check here.
207if #[allow(non_exhaustive_omitted_patterns)] match leak_check {
ForceLeakCheck::Yes => true,
_ => false,
}matches!(leak_check, ForceLeakCheck::Yes) {
208self.leak_check(outer_universe, Some(snapshot))?;
209 }
210211res212 })
213 }
214215/// Unify two types (using sub or lub).
216fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>, leak_check: ForceLeakCheck) -> CoerceResult<'tcx> {
217self.unify_raw(a, b, leak_check)
218 .and_then(|InferOk { value: ty, obligations }| success(::alloc::vec::Vec::new()vec![], ty, obligations))
219 }
220221/// Unify two types (using sub or lub) and produce a specific coercion.
222fn unify_and(
223&self,
224 a: Ty<'tcx>,
225 b: Ty<'tcx>,
226 adjustments: impl IntoIterator<Item = Adjustment<'tcx>>,
227 final_adjustment: Adjust,
228 leak_check: ForceLeakCheck,
229 ) -> CoerceResult<'tcx> {
230self.unify_raw(a, b, leak_check).and_then(|InferOk { value: ty, obligations }| {
231success(
232adjustments233 .into_iter()
234 .chain(std::iter::once(Adjustment { target: ty, kind: final_adjustment }))
235 .collect(),
236ty,
237obligations,
238 )
239 })
240 }
241242x;#[instrument(skip(self), ret)]243fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
244// First, remove any resolved type variables (at the top level, at least):
245let a = self.shallow_resolve(a);
246let b = self.shallow_resolve(b);
247debug!("Coerce.tys({:?} => {:?})", a, b);
248249// Coercing from `!` to any type is allowed:
250if a.is_never() {
251if self.coerce_never {
252return success(
253vec![Adjustment { kind: Adjust::NeverToAny, target: b }],
254 b,
255 PredicateObligations::new(),
256 );
257 } else {
258// Otherwise the only coercion we can do is unification.
259return self.unify(a, b, ForceLeakCheck::No);
260 }
261 }
262263// Coercing *from* an unresolved inference variable means that
264 // we have no information about the source type. This will always
265 // ultimately fall back to some form of subtyping.
266if a.is_ty_var() {
267return self.coerce_from_inference_variable(a, b);
268 }
269270// Consider coercing the subtype to a DST
271 //
272 // NOTE: this is wrapped in a `commit_if_ok` because it creates
273 // a "spurious" type variable, and we don't want to have that
274 // type variable in memory if the coercion fails.
275let unsize = self.commit_if_ok(|_| self.coerce_unsized(a, b));
276match unsize {
277Ok(_) => {
278debug!("coerce: unsize successful");
279return unsize;
280 }
281Err(error) => {
282debug!(?error, "coerce: unsize failed");
283 }
284 }
285286// Examine the target type and consider type-specific coercions, such
287 // as auto-borrowing, coercing pointer mutability, pin-ergonomics, or
288 // generic reborrow.
289match *b.kind() {
290 ty::RawPtr(_, b_mutbl) => {
291return self.coerce_to_raw_ptr(a, b, b_mutbl);
292 }
293 ty::Ref(r_b, _, mutbl_b) => {
294if let Some(pin_ref_to_ref) = self.maybe_pin_ref_to_ref(a, b) {
295return self.coerce_pin_ref_to_ref(pin_ref_to_ref);
296 }
297return self.coerce_to_ref(a, b, r_b, mutbl_b);
298 }
299_ if let Some(to_pin_ref) = self.maybe_to_pin_ref(a, b) => {
300return self.coerce_to_pin_ref(to_pin_ref);
301 }
302 ty::Adt(_, _)
303if self.tcx.features().reborrow()
304 && self
305.fcx
306 .infcx
307 .type_implements_trait(
308self.tcx
309 .lang_items()
310 .reborrow()
311 .expect("Unexpectedly using core/std without reborrow"),
312 [b],
313self.fcx.param_env,
314 )
315 .must_apply_modulo_regions() =>
316 {
317let reborrow_coerce = self.commit_if_ok(|_| self.coerce_reborrow(a, b));
318if reborrow_coerce.is_ok() {
319return reborrow_coerce;
320 }
321 }
322_ => {}
323 }
324325match *a.kind() {
326 ty::FnDef(..) => {
327// Function items are coercible to any closure
328 // type; function pointers are not (that would
329 // require double indirection).
330 // Additionally, we permit coercion of function
331 // items to drop the unsafe qualifier.
332self.coerce_from_fn_item(a, b)
333 }
334 ty::FnPtr(a_sig_tys, a_hdr) => {
335// We permit coercion of fn pointers to drop the
336 // unsafe qualifier.
337self.coerce_from_fn_pointer(a, a_sig_tys.with(a_hdr), b)
338 }
339 ty::Closure(..) => {
340// Non-capturing closures are coercible to
341 // function pointers or unsafe function pointers.
342 // It cannot convert closures that require unsafe.
343self.coerce_closure_to_fn(a, b)
344 }
345 ty::Adt(_, _) if self.tcx.features().reborrow() => {
346let reborrow_coerce = self.commit_if_ok(|_| self.coerce_shared_reborrow(a, b));
347if reborrow_coerce.is_ok() {
348 reborrow_coerce
349 } else {
350self.unify(a, b, ForceLeakCheck::No)
351 }
352 }
353_ => {
354// Otherwise, just use unification rules.
355self.unify(a, b, ForceLeakCheck::No)
356 }
357 }
358 }
359360/// Coercing *from* an inference variable. In this case, we have no information
361 /// about the source type, so we can't really do a true coercion and we always
362 /// fall back to subtyping (`unify_and`).
363fn coerce_from_inference_variable(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
364{
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:364",
"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(364u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_from_inference_variable(a={0:?}, b={1:?})",
a, b) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("coerce_from_inference_variable(a={:?}, b={:?})", a, b);
365if 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);
366if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};debug_assert!(self.shallow_resolve(b) == b);
367368if b.is_ty_var() {
369let mut obligations = PredicateObligations::with_capacity(2);
370let mut push_coerce_obligation = |a, b| {
371obligations.push(Obligation::new(
372self.tcx(),
373self.cause.clone(),
374self.param_env,
375 ty::Binder::dummy(ty::PredicateKind::Coerce(ty::CoercePredicate { a, b })),
376 ));
377 };
378379let target_ty = if self.use_lub {
380// When computing the lub, we create a new target
381 // and coerce both `a` and `b` to it.
382let target_ty = self.next_ty_var(self.cause.span);
383push_coerce_obligation(a, target_ty);
384push_coerce_obligation(b, target_ty);
385target_ty386 } else {
387// When subtyping, we don't need to create a new target
388 // as we only coerce `a` to `b`.
389push_coerce_obligation(a, b);
390b391 };
392393{
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:393",
"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(393u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_from_inference_variable: two inference variables, target_ty={0:?}, obligations={1:?}",
target_ty, obligations) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
394"coerce_from_inference_variable: two inference variables, target_ty={:?}, obligations={:?}",
395 target_ty, obligations
396 );
397success(::alloc::vec::Vec::new()vec![], target_ty, obligations)
398 } else {
399// One unresolved type variable: just apply subtyping, we may be able
400 // to do something useful.
401self.unify(a, b, ForceLeakCheck::No)
402 }
403 }
404405/// Handles coercing some arbitrary type `a` to some reference (`b`). This
406 /// handles a few cases:
407 /// - Introducing reborrows to give more flexible lifetimes
408 /// - Deref coercions to allow `&T` to coerce to `&T::Target`
409 /// - Coercing mutable references to immutable references
410 /// These coercions can be freely intermixed, for example we are able to
411 /// coerce `&mut T` to `&mut T::Target`.
412fn coerce_to_ref(
413&self,
414 a: Ty<'tcx>,
415 b: Ty<'tcx>,
416 r_b: ty::Region<'tcx>,
417 mutbl_b: hir::Mutability,
418 ) -> CoerceResult<'tcx> {
419{
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:419",
"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(419u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_to_ref(a={0:?}, b={1:?})",
a, b) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("coerce_to_ref(a={:?}, b={:?})", a, b);
420if true {
if !(self.shallow_resolve(a) == a) {
::core::panicking::panic("assertion failed: self.shallow_resolve(a) == a")
};
};debug_assert!(self.shallow_resolve(a) == a);
421if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};debug_assert!(self.shallow_resolve(b) == b);
422423let (r_a, mt_a) = match *a.kind() {
424 ty::Ref(r_a, ty, mutbl) => {
425 coerce_mutbls(mutbl, mutbl_b)?;
426 (r_a, ty::TypeAndMut { ty, mutbl })
427 }
428_ => return self.unify(a, b, ForceLeakCheck::No),
429 };
430431// Look at each step in the `Deref` chain and check if
432 // any of the autoref'd `Target` types unify with the
433 // coercion target.
434 //
435 // For example when coercing from `&mut Vec<T>` to `&M [T]` we
436 // have three deref steps:
437 // 1. `&mut Vec<T>`, skip autoref
438 // 2. `Vec<T>`, autoref'd ty: `&M Vec<T>`
439 // - `&M Vec<T>` does not unify with `&M [T]`
440 // 3. `[T]`, autoref'd ty: `&M [T]`
441 // - `&M [T]` does unify with `&M [T]`
442let mut first_error = None;
443let mut r_borrow_var = None;
444let mut autoderef = self.autoderef(self.cause.span, a);
445let found = autoderef.by_ref().find_map(|(deref_ty, autoderefs)| {
446if autoderefs == 0 {
447// Don't autoref the first step as otherwise we'd allow
448 // coercing `&T` to `&&T`.
449return None;
450 }
451452// The logic here really shouldn't exist. We don't care about free
453 // lifetimes during HIR typeck. Unfortunately later parts of this
454 // function rely on structural identity of the autoref'd deref'd ty.
455 //
456 // This means that what region we use here actually impacts whether
457 // we emit a reborrow coercion or not which can affect diagnostics
458 // and capture analysis (which in turn affects borrowck).
459let r = if !self.use_lub {
460r_b461 } else if autoderefs == 1 {
462r_a463 } else {
464if r_borrow_var.is_none() {
465// create var lazily, at most once
466let coercion = RegionVariableOrigin::Coercion(self.cause.span);
467let r = self.next_region_var(coercion);
468r_borrow_var = Some(r);
469 }
470r_borrow_var.unwrap()
471 };
472473let autorefd_deref_ty = Ty::new_ref(self.tcx, r, deref_ty, mutbl_b);
474475// Note that we unify the autoref'd `Target` type with `b` rather than
476 // the `Target` type with the pointee of `b`. This is necessary
477 // to properly account for the differing variances of the pointees
478 // of `&` vs `&mut` references.
479match self.unify_raw(autorefd_deref_ty, b, ForceLeakCheck::No) {
480Ok(ok) => Some(ok),
481Err(err) => {
482if first_error.is_none() {
483first_error = Some(err);
484 }
485None486 }
487 }
488 });
489490// Extract type or return an error. We return the first error
491 // we got, which should be from relating the "base" type
492 // (e.g., in example above, the failure from relating `Vec<T>`
493 // to the target type), since that should be the least
494 // confusing.
495let Some(InferOk { value: coerced_a, mut obligations }) = foundelse {
496if let Some(first_error) = first_error {
497{
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:497",
"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(497u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_to_ref: failed with err = {0:?}",
first_error) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("coerce_to_ref: failed with err = {:?}", first_error);
498return Err(first_error);
499 } else {
500// This may happen in the new trait solver since autoderef requires
501 // the pointee to be structurally normalizable, or else it'll just bail.
502 // So when we have a type like `&<not well formed>`, then we get no
503 // autoderef steps (even though there should be at least one). That means
504 // we get no type mismatches, since the loop above just exits early.
505return Err(TypeError::Mismatch);
506 }
507 };
508509if coerced_a == a && mt_a.mutbl.is_not() && autoderef.step_count() == 1 {
510// As a special case, if we would produce `&'a *x`, that's
511 // a total no-op. We end up with the type `&'a T` just as
512 // we started with. In that case, just skip it altogether.
513 //
514 // Unfortunately, this can actually effect capture analysis
515 // which in turn means this effects borrow checking. This can
516 // also effect diagnostics.
517 // FIXME(BoxyUwU): we should always emit reborrow coercions
518 //
519 // Note that for `&mut`, we DO want to reborrow --
520 // otherwise, this would be a move, which might be an
521 // error. For example `foo(self.x)` where `self` and
522 // `self.x` both have `&mut `type would be a move of
523 // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
524 // which is a borrow.
525if !mutbl_b.is_not() {
::core::panicking::panic("assertion failed: mutbl_b.is_not()")
};assert!(mutbl_b.is_not()); // can only coerce &T -> &U
526return success(::alloc::vec::Vec::new()vec![], coerced_a, obligations);
527 }
528529let InferOk { value: mut adjustments, obligations: o } =
530self.adjust_steps_as_infer_ok(&autoderef);
531obligations.extend(o);
532obligations.extend(autoderef.into_obligations());
533534if !#[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!(
535matches!(coerced_a.kind(), ty::Ref(..)),
536"expected a ref type, got {:?}",
537 coerced_a
538 );
539540// Now apply the autoref
541let mutbl = AutoBorrowMutability::new(mutbl_b, self.allow_two_phase);
542adjustments543 .push(Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)), target: coerced_a });
544545{
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:545",
"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(545u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_to_ref: succeeded coerced_a={0:?} adjustments={1:?}",
coerced_a, adjustments) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("coerce_to_ref: succeeded coerced_a={:?} adjustments={:?}", coerced_a, adjustments);
546547success(adjustments, coerced_a, obligations)
548 }
549550/// Performs [unsized coercion] by emulating a fulfillment loop on a
551 /// `CoerceUnsized` goal until all `CoerceUnsized` and `Unsize` goals
552 /// are successfully selected.
553 ///
554 /// [unsized coercion](https://doc.rust-lang.org/reference/type-coercions.html#unsized-coercions)
555#[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(555u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("source")
}> =
::tracing::__macro_support::FieldName::new("source");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("target")
}> =
::tracing::__macro_support::FieldName::new("target");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&target)
as &dyn ::tracing::field::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:557",
"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(557u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("source")
}> =
::tracing::__macro_support::FieldName::new("source");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("target")
}> =
::tracing::__macro_support::FieldName::new("target");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&target)
as &dyn ::tracing::field::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:565",
"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(565u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: source is a TyVar, bailing out")
as &dyn ::tracing::field::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:569",
"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(569u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: target is a TyVar, bailing out")
as &dyn ::tracing::field::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:623",
"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(623u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("missing Unsize or CoerceUnsized traits")
as &dyn ::tracing::field::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.map(|(deref, autoref)|
[deref, autoref]).into_flat_iter(),
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,
errored: false,
}).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")]556fn coerce_unsized(&self, source: Ty<'tcx>, target: Ty<'tcx>) -> CoerceResult<'tcx> {
557debug!(?source, ?target);
558debug_assert!(self.shallow_resolve(source) == source);
559debug_assert!(self.shallow_resolve(target) == target);
560561// We don't apply any coercions incase either the source or target
562 // aren't sufficiently well known but tend to instead just equate
563 // them both.
564if source.is_ty_var() {
565debug!("coerce_unsized: source is a TyVar, bailing out");
566return Err(TypeError::Mismatch);
567 }
568if target.is_ty_var() {
569debug!("coerce_unsized: target is a TyVar, bailing out");
570return Err(TypeError::Mismatch);
571 }
572573// This is an optimization because coercion is one of the most common
574 // operations that we do in typeck, since it happens at every assignment
575 // and call arg (among other positions).
576 //
577 // These targets are known to never be RHS in `LHS: CoerceUnsized<RHS>`.
578 // That's because these are built-in types for which a core-provided impl
579 // doesn't exist, and for which a user-written impl is invalid.
580 //
581 // This is technically incomplete when users write impossible bounds like
582 // `where T: CoerceUnsized<usize>`, for example, but that trait is unstable
583 // and coercion is allowed to be incomplete. The only case where this matters
584 // is impossible bounds.
585 //
586 // Note that some of these types implement `LHS: Unsize<RHS>`, but they
587 // do not implement *`CoerceUnsized`* which is the root obligation of the
588 // check below.
589match target.kind() {
590 ty::Bool
591 | ty::Char
592 | ty::Int(_)
593 | ty::Uint(_)
594 | ty::Float(_)
595 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
596 | ty::Str
597 | ty::Array(_, _)
598 | ty::Slice(_)
599 | ty::FnDef(_, _)
600 | ty::FnPtr(_, _)
601 | ty::Dynamic(_, _)
602 | ty::Closure(_, _)
603 | ty::CoroutineClosure(_, _)
604 | ty::Coroutine(_, _)
605 | ty::CoroutineWitness(_, _)
606 | ty::Never
607 | ty::Tuple(_) => return Err(TypeError::Mismatch),
608_ => {}
609 }
610// `&str: CoerceUnsized<&str>` does not hold but is encountered frequently
611 // so we fast path bail out here
612if let ty::Ref(_, source_pointee, ty::Mutability::Not) = *source.kind()
613 && source_pointee.is_str()
614 && let ty::Ref(_, target_pointee, ty::Mutability::Not) = *target.kind()
615 && target_pointee.is_str()
616 {
617return Err(TypeError::Mismatch);
618 }
619620let traits =
621 (self.tcx.lang_items().unsize_trait(), self.tcx.lang_items().coerce_unsized_trait());
622let (Some(unsize_did), Some(coerce_unsized_did)) = traits else {
623debug!("missing Unsize or CoerceUnsized traits");
624return Err(TypeError::Mismatch);
625 };
626627// Note, we want to avoid unnecessary unsizing. We don't want to coerce to
628 // a DST unless we have to. This currently comes out in the wash since
629 // we can't unify [T] with U. But to properly support DST, we need to allow
630 // that, at which point we will need extra checks on the target here.
631632 // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
633let reborrow = match (source.kind(), target.kind()) {
634 (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => {
635 coerce_mutbls(mutbl_a, mutbl_b)?;
636637let coercion = RegionVariableOrigin::Coercion(self.cause.span);
638let r_borrow = self.next_region_var(coercion);
639640// We don't allow two-phase borrows here, at least for initial
641 // implementation. If it happens that this coercion is a function argument,
642 // the reborrow in coerce_borrowed_ptr will pick it up.
643let mutbl = AutoBorrowMutability::new(mutbl_b, AllowTwoPhase::No);
644645Some((
646 Adjustment { kind: Adjust::Deref(DerefAdjustKind::Builtin), target: ty_a },
647 Adjustment {
648 kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)),
649 target: Ty::new_ref(self.tcx, r_borrow, ty_a, mutbl_b),
650 },
651 ))
652 }
653 (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(_, mt_b)) => {
654 coerce_mutbls(mt_a, mt_b)?;
655656Some((
657 Adjustment { kind: Adjust::Deref(DerefAdjustKind::Builtin), target: ty_a },
658 Adjustment {
659 kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
660 target: Ty::new_ptr(self.tcx, ty_a, mt_b),
661 },
662 ))
663 }
664_ => None,
665 };
666let coerce_source = reborrow.as_ref().map_or(source, |(_, r)| r.target);
667668// Setup either a subtyping or a LUB relationship between
669 // the `CoerceUnsized` target type and the expected type.
670 // We only have the latter, so we use an inference variable
671 // for the former and let type inference do the rest.
672let coerce_target = self.next_ty_var(self.cause.span);
673674let mut coercion = self.unify_and(
675 coerce_target,
676 target,
677 reborrow.map(|(deref, autoref)| [deref, autoref]).into_flat_iter(),
678 Adjust::Pointer(PointerCoercion::Unsize),
679 ForceLeakCheck::No,
680 )?;
681682// Create an obligation for `Source: CoerceUnsized<Target>`.
683let cause = self.cause(self.cause.span, ObligationCauseCode::Coercion { source, target });
684let pred = ty::TraitRef::new(self.tcx, coerce_unsized_did, [coerce_source, coerce_target]);
685let obligation = Obligation::new(self.tcx, cause, self.fcx.param_env, pred);
686687if self.next_trait_solver() {
688 coercion.obligations.push(obligation);
689690if self
691.infcx
692 .visit_proof_tree(
693 Goal::new(self.tcx, self.param_env, pred),
694&mut CoerceVisitor { fcx: self.fcx, span: self.cause.span, errored: false },
695 )
696 .is_break()
697 {
698return Err(TypeError::Mismatch);
699 }
700 } else {
701self.coerce_unsized_old_solver(
702 obligation,
703&mut coercion,
704 coerce_unsized_did,
705 unsize_did,
706 )?;
707 }
708709Ok(coercion)
710 }
711712fn coerce_unsized_old_solver(
713&self,
714 obligation: Obligation<'tcx, ty::Predicate<'tcx>>,
715 coercion: &mut InferOk<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>,
716 coerce_unsized_did: DefId,
717 unsize_did: DefId,
718 ) -> Result<(), TypeError<'tcx>> {
719let mut selcx = traits::SelectionContext::new(self);
720// Use a FIFO queue for this custom fulfillment procedure.
721 //
722 // A Vec (or SmallVec) is not a natural choice for a queue. However,
723 // this code path is hot, and this queue usually has a max length of 1
724 // and almost never more than 3. By using a SmallVec we avoid an
725 // allocation, at the (very small) cost of (occasionally) having to
726 // shift subsequent elements down when removing the front element.
727let 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(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[obligation])))
}
}smallvec![obligation];
728729// Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
730 // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
731 // inference might unify those two inner type variables later.
732let traits = [coerce_unsized_did, unsize_did];
733while !queue.is_empty() {
734let obligation = queue.remove(0);
735let trait_pred = match obligation.predicate.kind().no_bound_vars() {
736Some(ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)))
737if traits.contains(&trait_pred.def_id()) =>
738 {
739self.resolve_vars_if_possible(trait_pred)
740 }
741_ => {
742 coercion.obligations.push(obligation);
743continue;
744 }
745 };
746{
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:746",
"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(746u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized resolve step: {0:?}",
trait_pred) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("coerce_unsized resolve step: {:?}", trait_pred);
747match selcx.select(&obligation.with(selcx.tcx(), trait_pred)) {
748// Uncertain or unimplemented.
749Ok(None) => {
750if trait_pred.def_id() == unsize_did {
751let self_ty = trait_pred.self_ty();
752let unsize_ty = trait_pred.trait_ref.args[1].expect_ty();
753{
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:753",
"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(753u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: ambiguous unsize case for {0:?}",
trait_pred) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_pred);
754match (self_ty.kind(), unsize_ty.kind()) {
755 (&ty::Infer(ty::TyVar(v)), ty::Dynamic(..))
756if self.type_var_is_sized(v) =>
757 {
758{
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:758",
"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(758u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: have sized infer {0:?}",
v) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("coerce_unsized: have sized infer {:?}", v);
759 coercion.obligations.push(obligation);
760// `$0: Unsize<dyn Trait>` where we know that `$0: Sized`, try going
761 // for unsizing.
762}
763_ => {
764// Some other case for `$0: Unsize<Something>`. Note that we
765 // hit this case even if `Something` is a sized type, so just
766 // don't do the coercion.
767{
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:767",
"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(767u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: ambiguous unsize")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("coerce_unsized: ambiguous unsize");
768return Err(TypeError::Mismatch);
769 }
770 }
771 } else {
772{
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:772",
"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(772u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: early return - ambiguous")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("coerce_unsized: early return - ambiguous");
773return Err(TypeError::Mismatch);
774 }
775 }
776Err(SelectionError::Unimplemented) => {
777{
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:777",
"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(777u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: early return - can\'t prove obligation")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("coerce_unsized: early return - can't prove obligation");
778return Err(TypeError::Mismatch);
779 }
780781Err(SelectionError::TraitDynIncompatible(_)) => {
782// Dyn compatibility errors in coercion will *always* be due to the
783 // fact that the RHS of the coercion is a non-dyn compatible `dyn Trait`
784 // written in source somewhere (otherwise we will never have lowered
785 // the dyn trait from HIR to middle).
786 //
787 // There's no reason to emit yet another dyn compatibility error,
788 // especially since the span will differ slightly and thus not be
789 // deduplicated at all!
790self.fcx.set_tainted_by_errors(
791self.fcx
792 .dcx()
793 .span_delayed_bug(self.cause.span, "dyn compatibility during coercion"),
794 );
795 }
796Err(err) => {
797let guar = self.err_ctxt().report_selection_error(
798 obligation.clone(),
799&obligation,
800&err,
801 );
802self.fcx.set_tainted_by_errors(guar);
803// Treat this like an obligation and follow through
804 // with the unsizing - the lack of a coercion should
805 // be silent, as it causes a type mismatch later.
806}
807Ok(Some(ImplSource::UserDefined(impl_source))) => {
808 queue.extend(impl_source.nested);
809// Certain incoherent `CoerceUnsized` implementations may cause ICEs,
810 // so check the impl's validity. Taint the body so that we don't try
811 // to evaluate these invalid coercions in CTFE. We only need to do this
812 // for local impls, since upstream impls should be valid.
813if impl_source.impl_def_id.is_local()
814 && let Err(guar) =
815self.tcx.ensure_result().coerce_unsized_info(impl_source.impl_def_id)
816 {
817self.fcx.set_tainted_by_errors(guar);
818 }
819 }
820Ok(Some(impl_source)) => queue.extend(impl_source.nested_obligations()),
821 }
822 }
823824Ok(())
825 }
826827/// Create an obligation for `ty: Unpin`, where .
828fn unpin_obligation(
829&self,
830 source: Ty<'tcx>,
831 target: Ty<'tcx>,
832 ty: Ty<'tcx>,
833 ) -> PredicateObligation<'tcx> {
834let pred = ty::TraitRef::new(
835self.tcx,
836self.tcx.require_lang_item(LangItem::Unpin, self.cause.span),
837 [ty],
838 );
839let cause = self.cause(self.cause.span, ObligationCauseCode::Coercion { source, target });
840PredicateObligation::new(self.tcx, cause, self.param_env, pred)
841 }
842843/// Checks if the given types are compatible for coercion from a pinned reference to a normal reference.
844fn maybe_pin_ref_to_ref(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> Option<CoerceMaybePinnedRef<'tcx>> {
845if !self.tcx.features().pin_ergonomics() {
846return None;
847 }
848if let Some((a_ty, a_pin @ ty::Pinnedness::Pinned, a_mut, a_r)) = a.maybe_pinned_ref()
849 && let Some((_, b_pin @ ty::Pinnedness::Not, b_mut, _)) = b.maybe_pinned_ref()
850 {
851return Some(CoerceMaybePinnedRef { a, b, a_ty, a_pin, a_mut, a_r, b_pin, b_mut });
852 }
853{
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:853",
"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(853u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("not fitting pinned ref to ref coercion (`{0:?}` -> `{1:?}`)",
a, b) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("not fitting pinned ref to ref coercion (`{:?}` -> `{:?}`)", a, b);
854None855 }
856857/// Coerces from a pinned reference to a normal reference.
858#[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_pin_ref_to_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(858u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a")
}> =
::tracing::__macro_support::FieldName::new("a");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("b")
}> =
::tracing::__macro_support::FieldName::new("b");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a_ty")
}> =
::tracing::__macro_support::FieldName::new("a_ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a_pin")
}> =
::tracing::__macro_support::FieldName::new("a_pin");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a_mut")
}> =
::tracing::__macro_support::FieldName::new("a_mut");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a_r")
}> =
::tracing::__macro_support::FieldName::new("a_r");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("b_pin")
}> =
::tracing::__macro_support::FieldName::new("b_pin");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("b_mut")
}> =
::tracing::__macro_support::FieldName::new("b_mut");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_pin)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_mut)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_r)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b_pin)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b_mut)
as &dyn ::tracing::field::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")
};
};
if true {
if !self.tcx.features().pin_ergonomics() {
::core::panicking::panic("assertion failed: self.tcx.features().pin_ergonomics()")
};
};
if true {
{
match (&a_pin, &ty::Pinnedness::Pinned) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};
if true {
{
match (&b_pin, &ty::Pinnedness::Not) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};
coerce_mutbls(a_mut, b_mut)?;
let unpin_obligation = self.unpin_obligation(a, b, a_ty);
let a = Ty::new_ref(self.tcx, a_r, a_ty, b_mut);
let mut coerce =
self.unify_and(a, b,
[Adjustment {
kind: Adjust::Deref(DerefAdjustKind::Pin),
target: a_ty,
}],
Adjust::Borrow(AutoBorrow::Ref(AutoBorrowMutability::new(b_mut,
self.allow_two_phase))), ForceLeakCheck::No)?;
coerce.obligations.push(unpin_obligation);
Ok(coerce)
}
}
}#[instrument(skip(self), level = "trace")]859fn coerce_pin_ref_to_ref(
860&self,
861CoerceMaybePinnedRef { a, b, a_ty, a_pin, a_mut, a_r, b_pin, b_mut }: CoerceMaybePinnedRef<
862'tcx,
863 >,
864 ) -> CoerceResult<'tcx> {
865debug_assert!(self.shallow_resolve(a) == a);
866debug_assert!(self.shallow_resolve(b) == b);
867debug_assert!(self.tcx.features().pin_ergonomics());
868debug_assert_eq!(a_pin, ty::Pinnedness::Pinned);
869debug_assert_eq!(b_pin, ty::Pinnedness::Not);
870871 coerce_mutbls(a_mut, b_mut)?;
872873let unpin_obligation = self.unpin_obligation(a, b, a_ty);
874875let a = Ty::new_ref(self.tcx, a_r, a_ty, b_mut);
876let mut coerce = self.unify_and(
877 a,
878 b,
879 [Adjustment { kind: Adjust::Deref(DerefAdjustKind::Pin), target: a_ty }],
880 Adjust::Borrow(AutoBorrow::Ref(AutoBorrowMutability::new(b_mut, self.allow_two_phase))),
881 ForceLeakCheck::No,
882 )?;
883 coerce.obligations.push(unpin_obligation);
884Ok(coerce)
885 }
886887/// Checks if the given types are compatible for coercion to a pinned reference.
888fn maybe_to_pin_ref(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> Option<CoerceMaybePinnedRef<'tcx>> {
889if !self.tcx.features().pin_ergonomics() {
890return None;
891 }
892if let Some((a_ty, a_pin, a_mut, a_r)) = a.maybe_pinned_ref()
893 && let Some((_, b_pin @ ty::Pinnedness::Pinned, b_mut, _)) = b.maybe_pinned_ref()
894 {
895return Some(CoerceMaybePinnedRef { a, b, a_ty, a_pin, a_mut, a_r, b_pin, b_mut });
896 }
897{
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:897",
"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(897u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("not fitting ref to pinned ref coercion (`{0:?}` -> `{1:?}`)",
a, b) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("not fitting ref to pinned ref coercion (`{:?}` -> `{:?}`)", a, b);
898None899 }
900901/// Applies reborrowing and auto-borrowing that results to `Pin<&T>` or `Pin<&mut T>`:
902 ///
903 /// Currently we only support the following coercions:
904 /// - Reborrowing `Pin<&mut T>` -> `Pin<&mut T>`
905 /// - Reborrowing `Pin<&T>` -> `Pin<&T>`
906 /// - Auto-borrowing `&mut T` -> `Pin<&mut T>` where `T: Unpin`
907 /// - Auto-borrowing `&mut T` -> `Pin<&T>` where `T: Unpin`
908 /// - Auto-borrowing `&T` -> `Pin<&T>` where `T: Unpin`
909 ///
910 /// In the future we might want to support other reborrowing coercions, such as:
911 /// - `Pin<Box<T>>` as `Pin<&T>`
912 /// - `Pin<Box<T>>` as `Pin<&mut T>`
913#[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(913u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a")
}> =
::tracing::__macro_support::FieldName::new("a");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("b")
}> =
::tracing::__macro_support::FieldName::new("b");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a_ty")
}> =
::tracing::__macro_support::FieldName::new("a_ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a_pin")
}> =
::tracing::__macro_support::FieldName::new("a_pin");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a_mut")
}> =
::tracing::__macro_support::FieldName::new("a_mut");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a_r")
}> =
::tracing::__macro_support::FieldName::new("a_r");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("b_pin")
}> =
::tracing::__macro_support::FieldName::new("b_pin");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("b_mut")
}> =
::tracing::__macro_support::FieldName::new("b_mut");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_pin)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_mut)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_r)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b_pin)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b_mut)
as &dyn ::tracing::field::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")
};
};
if true {
if !self.tcx.features().pin_ergonomics() {
::core::panicking::panic("assertion failed: self.tcx.features().pin_ergonomics()")
};
};
if true {
{
match (&b_pin, &ty::Pinnedness::Pinned) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};
let (deref, unpin_obligation) =
match a_pin {
ty::Pinnedness::Pinned => (DerefAdjustKind::Pin, None),
ty::Pinnedness::Not => {
(DerefAdjustKind::Builtin,
Some(self.unpin_obligation(a, b, a_ty)))
}
};
coerce_mutbls(a_mut, b_mut)?;
let a = Ty::new_pinned_ref(self.tcx, a_r, a_ty, b_mut);
let mut coerce =
self.unify_and(a, b,
[Adjustment { kind: Adjust::Deref(deref), target: a_ty }],
Adjust::Borrow(AutoBorrow::Pin(b_mut)),
ForceLeakCheck::No)?;
coerce.obligations.extend(unpin_obligation);
Ok(coerce)
}
}
}#[instrument(skip(self), level = "trace")]914fn coerce_to_pin_ref(
915&self,
916CoerceMaybePinnedRef { a, b, a_ty, a_pin, a_mut, a_r, b_pin, b_mut }: CoerceMaybePinnedRef<
917'tcx,
918 >,
919 ) -> CoerceResult<'tcx> {
920debug_assert!(self.shallow_resolve(a) == a);
921debug_assert!(self.shallow_resolve(b) == b);
922debug_assert!(self.tcx.features().pin_ergonomics());
923debug_assert_eq!(b_pin, ty::Pinnedness::Pinned);
924925// We need to deref the reference first before we reborrow it to a pinned reference.
926let (deref, unpin_obligation) = match a_pin {
927// no `Unpin` required when reborrowing a pinned reference to a pinned reference
928ty::Pinnedness::Pinned => (DerefAdjustKind::Pin, None),
929// `Unpin` required when reborrowing a non-pinned reference to a pinned reference
930ty::Pinnedness::Not => {
931 (DerefAdjustKind::Builtin, Some(self.unpin_obligation(a, b, a_ty)))
932 }
933 };
934935 coerce_mutbls(a_mut, b_mut)?;
936937// update a with b's mutability since we'll be coercing mutability
938let a = Ty::new_pinned_ref(self.tcx, a_r, a_ty, b_mut);
939940// To complete the reborrow, we need to make sure we can unify the inner types, and if so we
941 // add the adjustments.
942let mut coerce = self.unify_and(
943 a,
944 b,
945 [Adjustment { kind: Adjust::Deref(deref), target: a_ty }],
946 Adjust::Borrow(AutoBorrow::Pin(b_mut)),
947 ForceLeakCheck::No,
948 )?;
949950 coerce.obligations.extend(unpin_obligation);
951Ok(coerce)
952 }
953954/// Applies generic exclusive reborrowing on type implementing `Reborrow`.
955#[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_reborrow",
"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(955u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a")
}> =
::tracing::__macro_support::FieldName::new("a");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("b")
}> =
::tracing::__macro_support::FieldName::new("b");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
as &dyn ::tracing::field::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 (ty::Adt(a_def, _), ty::Adt(b_def, _)) =
(a.kind(),
b.kind()) else { return Err(TypeError::Mismatch); };
if a_def.did() == b_def.did() {
self.unify_and(a, b, [],
Adjust::GenericReborrow(ty::Mutability::Mut),
ForceLeakCheck::No)
} else { Err(TypeError::Mismatch) }
}
}
}#[instrument(skip(self), level = "trace")]956fn coerce_reborrow(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
957debug_assert!(self.shallow_resolve(a) == a);
958debug_assert!(self.shallow_resolve(b) == b);
959960// We need to make sure the two types are compatible for reborrow.
961let (ty::Adt(a_def, _), ty::Adt(b_def, _)) = (a.kind(), b.kind()) else {
962return Err(TypeError::Mismatch);
963 };
964if a_def.did() == b_def.did() {
965// Reborrow is applicable here
966self.unify_and(
967 a,
968 b,
969 [],
970 Adjust::GenericReborrow(ty::Mutability::Mut),
971 ForceLeakCheck::No,
972 )
973 } else {
974// FIXME: CoerceShared check goes here, error for now
975Err(TypeError::Mismatch)
976 }
977 }
978979/// Applies generic exclusive reborrowing on type implementing `Reborrow`.
980#[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_shared_reborrow",
"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(980u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a")
}> =
::tracing::__macro_support::FieldName::new("a");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("b")
}> =
::tracing::__macro_support::FieldName::new("b");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
as &dyn ::tracing::field::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 (ty::Adt(a_def, _), ty::Adt(b_def, _)) =
(a.kind(),
b.kind()) else { return Err(TypeError::Mismatch); };
if a_def.did() == b_def.did() { return Err(TypeError::Mismatch); }
let Some(coerce_shared_trait_did) =
self.tcx.lang_items().coerce_shared() else {
return Err(TypeError::Mismatch);
};
let coerce_shared_trait_ref =
ty::TraitRef::new(self.tcx, coerce_shared_trait_did, [a, b]);
let obligation =
traits::Obligation::new(self.tcx, ObligationCause::dummy(),
self.param_env, ty::Binder::dummy(coerce_shared_trait_ref));
let ocx = ObligationCtxt::new(&self.infcx);
ocx.register_obligation(obligation);
let errs = ocx.evaluate_obligations_error_on_ambiguity();
if errs.no_errors() {
Ok(InferOk {
value: (::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[Adjustment {
kind: Adjust::GenericReborrow(ty::Mutability::Not),
target: b,
}])), b),
obligations: ocx.into_pending_obligations(),
})
} else { Err(TypeError::Mismatch) }
}
}
}#[instrument(skip(self), level = "trace")]981fn coerce_shared_reborrow(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
982debug_assert!(self.shallow_resolve(a) == a);
983debug_assert!(self.shallow_resolve(b) == b);
984985// We need to make sure the two types are compatible for reborrow.
986let (ty::Adt(a_def, _), ty::Adt(b_def, _)) = (a.kind(), b.kind()) else {
987return Err(TypeError::Mismatch);
988 };
989if a_def.did() == b_def.did() {
990// CoerceShared cannot be T -> T.
991return Err(TypeError::Mismatch);
992 }
993let Some(coerce_shared_trait_did) = self.tcx.lang_items().coerce_shared() else {
994return Err(TypeError::Mismatch);
995 };
996let coerce_shared_trait_ref = ty::TraitRef::new(self.tcx, coerce_shared_trait_did, [a, b]);
997let obligation = traits::Obligation::new(
998self.tcx,
999 ObligationCause::dummy(),
1000self.param_env,
1001 ty::Binder::dummy(coerce_shared_trait_ref),
1002 );
1003let ocx = ObligationCtxt::new(&self.infcx);
1004 ocx.register_obligation(obligation);
1005let errs = ocx.evaluate_obligations_error_on_ambiguity();
1006if errs.no_errors() {
1007Ok(InferOk {
1008 value: (
1009vec![Adjustment {
1010 kind: Adjust::GenericReborrow(ty::Mutability::Not),
1011 target: b,
1012 }],
1013 b,
1014 ),
1015 obligations: ocx.into_pending_obligations(),
1016 })
1017 } else {
1018Err(TypeError::Mismatch)
1019 }
1020 }
10211022fn coerce_from_fn_pointer(
1023&self,
1024 a: Ty<'tcx>,
1025 a_sig: ty::PolyFnSig<'tcx>,
1026 b: Ty<'tcx>,
1027 ) -> CoerceResult<'tcx> {
1028{
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:1028",
"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(1028u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message",
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a_sig")
}> =
::tracing::__macro_support::FieldName::new("a_sig");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("b")
}> =
::tracing::__macro_support::FieldName::new("b");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_from_fn_pointer")
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_sig)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?a_sig, ?b, "coerce_from_fn_pointer");
1029if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};debug_assert!(self.shallow_resolve(b) == b);
10301031match b.kind() {
1032 ty::FnPtr(_, b_hdr) if a_sig.safety().is_safe() && b_hdr.safety().is_unsafe() => {
1033let a = self.tcx.safe_to_unsafe_fn_ty(a_sig);
1034let adjust = Adjust::Pointer(PointerCoercion::UnsafeFnPointer);
1035self.unify_and(a, b, [], adjust, ForceLeakCheck::Yes)
1036 }
1037_ => self.unify(a, b, ForceLeakCheck::Yes),
1038 }
1039 }
10401041fn coerce_from_fn_item(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
1042{
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:1042",
"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(1042u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_from_fn_item(a={0:?}, b={1:?})",
a, b) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
1043if true {
if !(self.shallow_resolve(a) == a) {
::core::panicking::panic("assertion failed: self.shallow_resolve(a) == a")
};
};debug_assert!(self.shallow_resolve(a) == a);
1044if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};debug_assert!(self.shallow_resolve(b) == b);
10451046match b.kind() {
1047 ty::FnPtr(_, b_hdr) => {
1048let a_sig = self.sig_for_fn_def_coercion(a, Some(b_hdr.safety()))?;
10491050let InferOk { value: a_sig, mut obligations } =
1051self.at(&self.cause, self.param_env).normalize(Unnormalized::new_wip(a_sig));
1052let a = Ty::new_fn_ptr(self.tcx, a_sig);
10531054let adjust = Adjust::Pointer(PointerCoercion::ReifyFnPointer(b_hdr.safety()));
1055let InferOk { value, obligations: o2 } =
1056self.unify_and(a, b, [], adjust, ForceLeakCheck::Yes)?;
10571058obligations.extend(o2);
1059Ok(InferOk { value, obligations })
1060 }
1061_ => self.unify(a, b, ForceLeakCheck::No),
1062 }
1063 }
10641065/// Attempts to coerce from a closure to a function pointer. Fails
1066 /// if the closure has any upvars.
1067fn coerce_closure_to_fn(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
1068if true {
if !(self.shallow_resolve(a) == a) {
::core::panicking::panic("assertion failed: self.shallow_resolve(a) == a")
};
};debug_assert!(self.shallow_resolve(a) == a);
1069if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};debug_assert!(self.shallow_resolve(b) == b);
10701071match b.kind() {
1072 ty::FnPtr(_, hdr) => {
1073let safety = hdr.safety();
1074let terr = TypeError::Sorts(ty::error::ExpectedFound::new(a, b));
1075let closure_sig = self.sig_for_closure_coercion(a, Some(hdr.safety()), terr)?;
1076let pointer_ty = Ty::new_fn_ptr(self.tcx, closure_sig);
1077{
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:1077",
"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(1077u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_closure_to_fn(a={0:?}, b={1:?}, pty={2:?})",
a, b, pointer_ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})", a, b, pointer_ty);
10781079let adjust = Adjust::Pointer(PointerCoercion::ClosureFnPointer(safety));
1080self.unify_and(pointer_ty, b, [], adjust, ForceLeakCheck::No)
1081 }
1082_ => self.unify(a, b, ForceLeakCheck::No),
1083 }
1084 }
10851086fn coerce_to_raw_ptr(
1087&self,
1088 a: Ty<'tcx>,
1089 b: Ty<'tcx>,
1090 mutbl_b: hir::Mutability,
1091 ) -> CoerceResult<'tcx> {
1092{
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:1092",
"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(1092u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_to_raw_ptr(a={0:?}, b={1:?})",
a, b) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("coerce_to_raw_ptr(a={:?}, b={:?})", a, b);
1093if true {
if !(self.shallow_resolve(a) == a) {
::core::panicking::panic("assertion failed: self.shallow_resolve(a) == a")
};
};debug_assert!(self.shallow_resolve(a) == a);
1094if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};debug_assert!(self.shallow_resolve(b) == b);
10951096let (is_ref, mt_a) = match *a.kind() {
1097 ty::Ref(_, ty, mutbl) => (true, ty::TypeAndMut { ty, mutbl }),
1098 ty::RawPtr(ty, mutbl) => (false, ty::TypeAndMut { ty, mutbl }),
1099_ => return self.unify(a, b, ForceLeakCheck::No),
1100 };
1101 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
11021103// Check that the types which they point at are compatible.
1104let a_raw = Ty::new_ptr(self.tcx, mt_a.ty, mutbl_b);
1105// Although references and raw ptrs have the same
1106 // representation, we still register an Adjust::DerefRef so that
1107 // regionck knows that the region for `a` must be valid here.
1108if is_ref {
1109self.unify_and(
1110a_raw,
1111b,
1112 [Adjustment { kind: Adjust::Deref(DerefAdjustKind::Builtin), target: mt_a.ty }],
1113 Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)),
1114 ForceLeakCheck::No,
1115 )
1116 } else if mt_a.mutbl != mutbl_b {
1117self.unify_and(
1118a_raw,
1119b,
1120 [],
1121 Adjust::Pointer(PointerCoercion::MutToConstPointer),
1122 ForceLeakCheck::No,
1123 )
1124 } else {
1125self.unify(a_raw, b, ForceLeakCheck::No)
1126 }
1127 }
1128}
11291130impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
1131/// Attempt to coerce an expression to a type, and return the
1132 /// adjusted type of the expression, if successful.
1133 /// Adjustments are only recorded if the coercion succeeded.
1134 /// The expressions *must not* have any preexisting adjustments.
1135pub(crate) fn coerce(
1136&self,
1137 expr: &'tcx hir::Expr<'tcx>,
1138 expr_ty: Ty<'tcx>,
1139 target: Ty<'tcx>,
1140 allow_two_phase: AllowTwoPhase,
1141 cause: Option<ObligationCause<'tcx>>,
1142 ) -> RelateResult<'tcx, Ty<'tcx>> {
1143let source = self.resolve_vars_with_obligations(expr_ty);
1144{
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:1144",
"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(1144u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coercion::try({0:?}: {1:?} -> {2:?})",
expr, source, target) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
11451146let cause =
1147cause.unwrap_or_else(|| self.cause(expr.span, ObligationCauseCode::ExprAssignable));
1148let coerce = Coerce::new(
1149self,
1150cause,
1151allow_two_phase,
1152self.tcx.expr_guaranteed_to_constitute_read_for_never(expr),
1153 );
1154let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?;
11551156let (adjustments, _) = self.register_infer_ok_obligations(ok);
1157self.apply_adjustments(expr, adjustments);
1158Ok(if let Err(guar) = expr_ty.error_reported() {
1159Ty::new_error(self.tcx, guar)
1160 } else {
1161target1162 })
1163 }
11641165/// Probe whether `expr_ty` can be coerced to `target_ty`. This has no side-effects,
1166 /// and may return false positives if types are not yet fully constrained by inference.
1167 ///
1168 /// Returns false if the coercion is not possible, or if the coercion creates any
1169 /// sub-obligations that result in errors.
1170 ///
1171 /// This should only be used for diagnostics.
1172pub(crate) fn may_coerce(&self, expr_ty: Ty<'tcx>, target_ty: Ty<'tcx>) -> bool {
1173let cause = self.cause(DUMMY_SP, ObligationCauseCode::ExprAssignable);
1174// We don't ever need two-phase here since we throw out the result of the coercion.
1175 // We also just always set `coerce_never` to true, since this is a heuristic.
1176let coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No, true);
1177self.probe(|_| {
1178// Make sure to structurally resolve the types, since we use
1179 // the `TyKind`s heavily in coercion.
1180let ocx = ObligationCtxt::new(self);
1181let Ok(ok) = coerce.coerce(expr_ty, target_ty) else {
1182return false;
1183 };
1184ocx.register_obligations(ok.obligations);
1185ocx.try_evaluate_obligations().no_errors()
1186 })
1187 }
11881189/// Given a type and a target type, this function will calculate and return
1190 /// how many dereference steps needed to coerce `expr_ty` to `target`. If
1191 /// it's not possible, return `None`.
1192pub(crate) fn deref_steps_for_suggestion(
1193&self,
1194 expr_ty: Ty<'tcx>,
1195 target: Ty<'tcx>,
1196 ) -> Option<usize> {
1197let cause = self.cause(DUMMY_SP, ObligationCauseCode::ExprAssignable);
1198// We don't ever need two-phase here since we throw out the result of the coercion.
1199let coerce = Coerce::new(self, cause, AllowTwoPhase::No, true);
1200coerce.autoderef(DUMMY_SP, expr_ty).find_map(|(ty, steps)| {
1201self.probe(|_| coerce.unify_raw(ty, target, ForceLeakCheck::No)).ok().map(|_| steps)
1202 })
1203 }
12041205/// Given a type, this function will calculate and return the type given
1206 /// for `<Ty as Deref>::Target` only if `Ty` also implements `DerefMut`.
1207 ///
1208 /// This function is for diagnostics only, since it does not register
1209 /// trait or region sub-obligations. (presumably we could, but it's not
1210 /// particularly important for diagnostics...)
1211pub(crate) fn deref_once_mutably_for_diagnostic(&self, expr_ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
1212self.autoderef(DUMMY_SP, expr_ty).silence_errors().nth(1).and_then(|(deref_ty, _)| {
1213self.infcx
1214 .type_implements_trait(
1215self.tcx.lang_items().deref_mut_trait()?,
1216 [expr_ty],
1217self.param_env,
1218 )
1219 .may_apply()
1220 .then_some(deref_ty)
1221 })
1222 }
12231224x;#[instrument(level = "debug", skip(self), ret)]1225fn sig_for_coerce_lub(
1226&self,
1227 ty: Ty<'tcx>,
1228 closure_upvars_terr: TypeError<'tcx>,
1229 ) -> Result<ty::PolyFnSig<'tcx>, TypeError<'tcx>> {
1230match ty.kind() {
1231 ty::FnDef(..) => self.sig_for_fn_def_coercion(ty, None),
1232 ty::Closure(..) => self.sig_for_closure_coercion(ty, None, closure_upvars_terr),
1233_ => unreachable!("`sig_for_fn_def_closure_coerce_lub` called with wrong ty: {:?}", ty),
1234 }
1235 }
12361237fn sig_for_fn_def_coercion(
1238&self,
1239 fndef: Ty<'tcx>,
1240 expected_safety: Option<hir::Safety>,
1241 ) -> Result<ty::PolyFnSig<'tcx>, TypeError<'tcx>> {
1242let tcx = self.tcx;
12431244let &ty::FnDef(def_id, _) = fndef.kind() else {
1245{
::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);
1246 };
12471248// Intrinsics are not coercible to function pointers
1249if tcx.intrinsic(def_id).is_some() {
1250return Err(TypeError::IntrinsicCast);
1251 }
12521253let fn_attrs = tcx.codegen_fn_attrs(def_id);
1254if #[allow(non_exhaustive_omitted_patterns)] match fn_attrs.inline {
InlineAttr::Force { .. } => true,
_ => false,
}matches!(fn_attrs.inline, InlineAttr::Force { .. }) {
1255return Err(TypeError::ForceInlineCast);
1256 }
12571258let sig = fndef.fn_sig(tcx);
1259let sig = if fn_attrs.safe_target_features {
1260// Allow the coercion if the current function has all the features that would be
1261 // needed to call the coercee safely.
1262match tcx.adjust_target_feature_sig(def_id, sig, self.body_def_id.into()) {
1263Some(adjusted_sig) => adjusted_sig,
1264Noneif #[allow(non_exhaustive_omitted_patterns)] match expected_safety {
Some(hir::Safety::Safe) => true,
_ => false,
}matches!(expected_safety, Some(hir::Safety::Safe)) => {
1265return Err(TypeError::TargetFeatureCast(def_id));
1266 }
1267None => sig,
1268 }
1269 } else {
1270sig1271 };
12721273if 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)) {
1274Ok(tcx.safe_to_unsafe_sig(sig))
1275 } else {
1276Ok(sig)
1277 }
1278 }
12791280fn sig_for_closure_coercion(
1281&self,
1282 closure: Ty<'tcx>,
1283 expected_safety: Option<hir::Safety>,
1284 closure_upvars_terr: TypeError<'tcx>,
1285 ) -> Result<ty::PolyFnSig<'tcx>, TypeError<'tcx>> {
1286let tcx = self.tcx;
12871288let ty::Closure(closure_def, closure_args) = closure.kind() else {
1289{
::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);
1290 };
12911292// At this point we haven't done capture analysis, which means
1293 // that the ClosureArgs just contains an inference variable instead
1294 // of tuple of captured types.
1295 //
1296 // All we care here is if any variable is being captured and not the exact paths,
1297 // so we check `upvars_mentioned` for root variables being captured.
1298if !tcx.upvars_mentioned(closure_def.expect_local()).is_none_or(|u| u.is_empty()) {
1299return Err(closure_upvars_terr);
1300 }
13011302// We coerce the closure, which has fn type
1303 // `extern "rust-call" fn((arg0,arg1,...)) -> _`
1304 // to
1305 // `fn(arg0,arg1,...) -> _`
1306 // or
1307 // `unsafe fn(arg0,arg1,...) -> _`
1308let closure_sig = closure_args.as_closure().sig();
1309Ok(tcx.signature_unclosure(closure_sig, expected_safety.unwrap_or(hir::Safety::Safe)))
1310 }
13111312/// Given some expressions, their known unified type and another expression,
1313 /// tries to unify the types, potentially inserting coercions on any of the
1314 /// provided expressions and returns their LUB (aka "common supertype").
1315 ///
1316 /// This is really an internal helper. From outside the coercion
1317 /// module, you should instantiate a `CoerceMany` instance.
1318fn try_find_coercion_lub(
1319&self,
1320 cause: &ObligationCause<'tcx>,
1321 exprs: &[&'tcx hir::Expr<'tcx>],
1322 prev_ty: Ty<'tcx>,
1323 new: &hir::Expr<'_>,
1324 new_ty: Ty<'tcx>,
1325 ) -> RelateResult<'tcx, Ty<'tcx>> {
1326let prev_ty = self.resolve_vars_with_obligations(prev_ty);
1327let new_ty = self.resolve_vars_with_obligations(new_ty);
1328{
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:1328",
"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(1328u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::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 ::tracing::field::Value))])
});
} else { ; }
};debug!(
1329"coercion::try_find_coercion_lub({:?}, {:?}, exprs={:?} exprs)",
1330 prev_ty,
1331 new_ty,
1332 exprs.len()
1333 );
13341335// Fast Path: don't go through the coercion logic if we're coercing
1336 // a type to itself. This is unfortunately quite perf relevant so
1337 // we do it even though it may mask bugs in the coercion logic.
1338if prev_ty == new_ty {
1339return Ok(prev_ty);
1340 }
13411342let terr = TypeError::Sorts(ty::error::ExpectedFound::new(prev_ty, new_ty));
1343let opt_sigs = match (prev_ty.kind(), new_ty.kind()) {
1344// Don't coerce pairs of fndefs or pairs of closures to fn ptrs
1345 // if they can just be lubbed.
1346 //
1347 // See #88097 or `lub_closures_before_fnptr_coercion.rs` for where
1348 // we would erroneously coerce closures to fnptrs when attempting to
1349 // coerce a closure to itself.
1350(ty::FnDef(..), ty::FnDef(..)) | (ty::Closure(..), ty::Closure(..)) => {
1351let lubbed_ty = self.commit_if_ok(|snapshot| {
1352let outer_universe = self.infcx.universe();
13531354// We need to eagerly handle nested obligations due to lazy norm.
1355let result = if self.next_trait_solver() {
1356let ocx = ObligationCtxt::new(self);
1357let value = ocx.lub(cause, self.param_env, prev_ty, new_ty)?;
1358if ocx.try_evaluate_obligations().no_errors() {
1359Ok(InferOk { value, obligations: ocx.into_pending_obligations() })
1360 } else {
1361Err(TypeError::Mismatch)
1362 }
1363 } else {
1364self.at(cause, self.param_env).lub(prev_ty, new_ty)
1365 };
13661367self.leak_check(outer_universe, Some(snapshot))?;
1368result1369 });
13701371match lubbed_ty {
1372Ok(ok) => return Ok(self.register_infer_ok_obligations(ok)),
1373Err(_) => {
1374let a_sig = self.sig_for_coerce_lub(prev_ty, terr)?;
1375let b_sig = self.sig_for_coerce_lub(new_ty, terr)?;
1376Some((a_sig, b_sig))
1377 }
1378 }
1379 }
13801381 (ty::Closure(..), ty::FnDef(..)) | (ty::FnDef(..), ty::Closure(..)) => {
1382let a_sig = self.sig_for_coerce_lub(prev_ty, terr)?;
1383let b_sig = self.sig_for_coerce_lub(new_ty, terr)?;
1384Some((a_sig, b_sig))
1385 }
1386// ty::FnPtr x ty::FnPtr is fine to just be handled through a normal `unify`
1387 // call using `lub` which is what will happen on the normal path.
1388(ty::FnPtr(..), ty::FnPtr(..)) => None,
1389_ => None,
1390 };
13911392if let Some((mut a_sig, mut b_sig)) = opt_sigs {
1393// Allow coercing safe sigs to unsafe sigs
1394if a_sig.safety().is_safe() && b_sig.safety().is_unsafe() {
1395a_sig = self.tcx.safe_to_unsafe_sig(a_sig);
1396 } else if b_sig.safety().is_safe() && a_sig.safety().is_unsafe() {
1397b_sig = self.tcx.safe_to_unsafe_sig(b_sig);
1398 };
13991400// The signature must match.
1401let (a_sig, b_sig) = self.normalize(new.span, Unnormalized::new_wip((a_sig, b_sig)));
1402let sig = self
1403.at(cause, self.param_env)
1404 .lub(a_sig, b_sig)
1405 .map(|ok| self.register_infer_ok_obligations(ok))?;
14061407// Reify both sides and return the reified fn pointer type.
1408let fn_ptr = Ty::new_fn_ptr(self.tcx, sig);
1409let prev_adjustment = match prev_ty.kind() {
1410 ty::Closure(..) => Adjust::Pointer(PointerCoercion::ClosureFnPointer(sig.safety())),
1411 ty::FnDef(..) => Adjust::Pointer(PointerCoercion::ReifyFnPointer(sig.safety())),
1412_ => ::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"),
1413 };
1414let next_adjustment = match new_ty.kind() {
1415 ty::Closure(..) => Adjust::Pointer(PointerCoercion::ClosureFnPointer(sig.safety())),
1416 ty::FnDef(..) => Adjust::Pointer(PointerCoercion::ReifyFnPointer(sig.safety())),
1417_ => ::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"),
1418 };
1419for expr in exprs.iter() {
1420self.apply_adjustments(
1421 expr,
1422::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[Adjustment { kind: prev_adjustment.clone(), target: fn_ptr }]))vec![Adjustment { kind: prev_adjustment.clone(), target: fn_ptr }],
1423 );
1424 }
1425self.apply_adjustments(new, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[Adjustment { kind: next_adjustment, target: fn_ptr }]))vec![Adjustment { kind: next_adjustment, target: fn_ptr }]);
1426return Ok(fn_ptr);
1427 }
14281429// Configure a Coerce instance to compute the LUB.
1430 // We don't allow two-phase borrows on any autorefs this creates since we
1431 // probably aren't processing function arguments here and even if we were,
1432 // they're going to get autorefed again anyway and we can apply 2-phase borrows
1433 // at that time.
1434 //
1435 // NOTE: we set `coerce_never` to `true` here because coercion LUBs only
1436 // operate on values and not places, so a never coercion is valid.
1437let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No, true);
1438coerce.use_lub = true;
14391440// First try to coerce the new expression to the type of the previous ones,
1441 // but only if the new expression has no coercion already applied to it.
1442let mut first_error = None;
1443if !self.typeck_results.borrow().adjustments().contains_key(new.hir_id) {
1444let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
1445match result {
1446Ok(ok) => {
1447let (adjustments, target) = self.register_infer_ok_obligations(ok);
1448self.apply_adjustments(new, adjustments);
1449{
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:1449",
"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(1449u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::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 ::tracing::field::Value))])
});
} else { ; }
};debug!(
1450"coercion::try_find_coercion_lub: was able to coerce from new type {:?} to previous type {:?} ({:?})",
1451 new_ty, prev_ty, target
1452 );
1453return Ok(target);
1454 }
1455Err(e) => first_error = Some(e),
1456 }
1457 }
14581459let ok = self
1460.commit_if_ok(|_| coerce.coerce(prev_ty, new_ty))
1461// Avoid giving strange errors on failed attempts.
1462.map_err(|e| first_error.unwrap_or(e))?;
14631464let (adjustments, target) = self.register_infer_ok_obligations(ok);
1465for expr in exprs {
1466self.apply_adjustments(expr, adjustments.clone());
1467 }
1468{
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:1468",
"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(1468u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::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 ::tracing::field::Value))])
});
} else { ; }
};debug!(
1469"coercion::try_find_coercion_lub: was able to coerce previous type {:?} to new type {:?} ({:?})",
1470 prev_ty, new_ty, target
1471 );
1472Ok(target)
1473 }
1474}
14751476/// Check whether `ty` can be coerced to `output_ty`.
1477/// Used from clippy.
1478pub fn can_coerce<'tcx>(
1479 tcx: TyCtxt<'tcx>,
1480 param_env: ty::ParamEnv<'tcx>,
1481 body_def_id: LocalDefId,
1482 ty: Ty<'tcx>,
1483 output_ty: Ty<'tcx>,
1484) -> bool {
1485let root_ctxt = crate::typeck_root_ctxt::TypeckRootCtxt::new(tcx, body_def_id);
1486let fn_ctxt = FnCtxt::new(&root_ctxt, param_env, body_def_id);
1487fn_ctxt.may_coerce(ty, output_ty)
1488}
14891490/// CoerceMany encapsulates the pattern you should use when you have
1491/// many expressions that are all getting coerced to a common
1492/// type. This arises, for example, when you have a match (the result
1493/// of each arm is coerced to a common type). It also arises in less
1494/// obvious places, such as when you have many `break foo` expressions
1495/// that target the same loop, or the various `return` expressions in
1496/// a function.
1497///
1498/// The basic protocol is as follows:
1499///
1500/// - Instantiate the `CoerceMany` with an initial `expected_ty`.
1501/// This will also serve as the "starting LUB". The expectation is
1502/// that this type is something which all of the expressions *must*
1503/// be coercible to. Use a fresh type variable if needed.
1504/// - For each expression whose result is to be coerced, invoke `coerce()` with.
1505/// - In some cases we wish to coerce "non-expressions" whose types are implicitly
1506/// unit. This happens for example if you have a `break` with no expression,
1507/// or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
1508/// - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
1509/// from you so that you don't have to worry your pretty head about it.
1510/// But if an error is reported, the final type will be `err`.
1511/// - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
1512/// previously coerced expressions.
1513/// - When all done, invoke `complete()`. This will return the LUB of
1514/// all your expressions.
1515/// - WARNING: I don't believe this final type is guaranteed to be
1516/// related to your initial `expected_ty` in any particular way,
1517/// although it will typically be a subtype, so you should check it.
1518/// Check the note below for more details.
1519/// - Invoking `complete()` may cause us to go and adjust the "adjustments" on
1520/// previously coerced expressions.
1521///
1522/// Example:
1523///
1524/// ```ignore (illustrative)
1525/// let mut coerce = CoerceMany::new(expected_ty);
1526/// for expr in exprs {
1527/// let expr_ty = fcx.check_expr_with_expectation(expr, expected);
1528/// coerce.coerce(fcx, &cause, expr, expr_ty);
1529/// }
1530/// let final_ty = coerce.complete(fcx);
1531/// ```
1532///
1533/// NOTE: Why does the `expected_ty` participate in the LUB?
1534/// When coercing, each branch should use the following expectations for type inference:
1535/// - The branch can be coerced to the expected type of the match/if/whatever.
1536/// - The branch can be coercion lub'd with the types of the previous branches.
1537/// Ideally we'd have some sort of `Expectation::ParticipatesInCoerceLub(ongoing_lub_ty, final_ty)`,
1538/// but adding and using this feels very challenging.
1539/// What we instead do is to use the expected type of the match/if/whatever as
1540/// the initial coercion lub. This allows us to use the lub of "expected type of match" with
1541/// "types from previous branches" as the coercion target, which can contains both expectations.
1542///
1543/// Two concerns with this approach:
1544/// - We may have incompatible `final_ty` if that lub is different from the expected
1545/// type of the match. However, in this case coercing the final type of the
1546/// `CoerceMany` to its expected type would have error'd anyways, so we don't care.
1547/// - We may constrain the `expected_ty` too early. For some branches with
1548/// type `a` and `b`, we end up with `(a lub expected_ty) lub b` instead of
1549/// `(a lub b) lub expected_ty`. They should be the same type. However,
1550/// `a lub expected_ty` may constrain inference variables in `expected_ty`.
1551/// In this case the difference does matter and we get actually incorrect results.
1552/// FIXME: Ideally we'd compute the final type without unnecessarily constraining
1553/// the expected type of the match when computing the types of its branches.
1554pub(crate) struct CoerceMany<'tcx> {
1555 expected_ty: Ty<'tcx>,
1556 final_ty: Option<Ty<'tcx>>,
1557 expressions: Vec<&'tcx hir::Expr<'tcx>>,
1558}
15591560impl<'tcx> CoerceMany<'tcx> {
1561/// Creates a `CoerceMany` with a default capacity of 1. If the full set of
1562 /// coercion sites is known before hand, consider `with_capacity()` instead
1563 /// to avoid allocation.
1564pub(crate) fn new(expected_ty: Ty<'tcx>) -> Self {
1565Self::with_capacity(expected_ty, 1)
1566 }
15671568/// Creates a `CoerceMany` with a given capacity.
1569pub(crate) fn with_capacity(expected_ty: Ty<'tcx>, capacity: usize) -> Self {
1570CoerceMany { expected_ty, final_ty: None, expressions: Vec::with_capacity(capacity) }
1571 }
15721573/// Returns the "expected type" with which this coercion was
1574 /// constructed. This represents the "downward propagated" type
1575 /// that was given to us at the start of typing whatever construct
1576 /// we are typing (e.g., the match expression).
1577 ///
1578 /// Typically, this is used as the expected type when
1579 /// type-checking each of the alternative expressions whose types
1580 /// we are trying to merge.
1581pub(crate) fn expected_ty(&self) -> Ty<'tcx> {
1582self.expected_ty
1583 }
15841585/// Returns the current "merged type", representing our best-guess
1586 /// at the LUB of the expressions we've seen so far (if any). This
1587 /// isn't *final* until you call `self.complete()`, which will return
1588 /// the merged type.
1589pub(crate) fn merged_ty(&self) -> Ty<'tcx> {
1590self.final_ty.unwrap_or(self.expected_ty)
1591 }
15921593/// Indicates that the value generated by `expression`, which is
1594 /// of type `expression_ty`, is one of the possibilities that we
1595 /// could coerce from. This will record `expression`, and later
1596 /// calls to `coerce` may come back and add adjustments and things
1597 /// if necessary.
1598pub(crate) fn coerce<'a>(
1599&mut self,
1600 fcx: &FnCtxt<'a, 'tcx>,
1601 cause: &ObligationCause<'tcx>,
1602 expression: &'tcx hir::Expr<'tcx>,
1603 expression_ty: Ty<'tcx>,
1604 ) {
1605self.coerce_inner(fcx, cause, Some(expression), expression_ty, |_| {}, false)
1606 }
16071608/// Indicates that one of the inputs is a "forced unit". This
1609 /// occurs in a case like `if foo { ... };`, where the missing else
1610 /// generates a "forced unit". Another example is a `loop { break;
1611 /// }`, where the `break` has no argument expression. We treat
1612 /// these cases slightly differently for error-reporting
1613 /// purposes. Note that these tend to correspond to cases where
1614 /// the `()` expression is implicit in the source, and hence we do
1615 /// not take an expression argument.
1616 ///
1617 /// The `augment_error` gives you a chance to extend the error
1618 /// message, in case any results (e.g., we use this to suggest
1619 /// removing a `;`).
1620pub(crate) fn coerce_forced_unit<'a>(
1621&mut self,
1622 fcx: &FnCtxt<'a, 'tcx>,
1623 cause: &ObligationCause<'tcx>,
1624 augment_error: impl FnOnce(&mut Diag<'_>),
1625 label_unit_as_expected: bool,
1626 ) {
1627self.coerce_inner(
1628fcx,
1629cause,
1630None,
1631fcx.tcx.types.unit,
1632augment_error,
1633label_unit_as_expected,
1634 )
1635 }
16361637/// The inner coercion "engine". If `expression` is `None`, this
1638 /// is a forced-unit case, and hence `expression_ty` must be
1639 /// `Nil`.
1640#[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(1640u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("cause")
}> =
::tracing::__macro_support::FieldName::new("cause");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("expression")
}> =
::tracing::__macro_support::FieldName::new("expression");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("expression_ty")
}> =
::tracing::__macro_support::FieldName::new("expression_ty");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expression)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expression_ty)
as &dyn ::tracing::field::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:1731",
"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(1731u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("result")
}> =
::tracing::__macro_support::FieldName::new("result");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&result)
as &dyn ::tracing::field::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(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(block, _, 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))
}));
if loop_src == hir::LoopSource::While &&
let Some(pat) = irrefutable_if_let_expr(block) {
err.span_label(pat.span,
"this pattern always matches, consider using `loop` instead");
}
}
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")]1641pub(crate) fn coerce_inner<'a>(
1642&mut self,
1643 fcx: &FnCtxt<'a, 'tcx>,
1644 cause: &ObligationCause<'tcx>,
1645 expression: Option<&'tcx hir::Expr<'tcx>>,
1646mut expression_ty: Ty<'tcx>,
1647 augment_error: impl FnOnce(&mut Diag<'_>),
1648 label_expression_as_expected: bool,
1649 ) {
1650// Incorporate whatever type inference information we have
1651 // until now; in principle we might also want to process
1652 // pending obligations, but doing so should only improve
1653 // compatibility (hopefully that is true) by helping us
1654 // uncover never types better.
1655if expression_ty.is_ty_var() {
1656 expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1657 }
16581659// If we see any error types, just propagate that error
1660 // upwards.
1661if let Err(guar) = (expression_ty, self.merged_ty()).error_reported() {
1662self.final_ty = Some(Ty::new_error(fcx.tcx, guar));
1663return;
1664 }
16651666let (expected, found) = if label_expression_as_expected {
1667// In the case where this is a "forced unit", like
1668 // `break`, we want to call the `()` "expected"
1669 // since it is implied by the syntax.
1670 // (Note: not all force-units work this way.)"
1671(expression_ty, self.merged_ty())
1672 } else {
1673// Otherwise, the "expected" type for error
1674 // reporting is the current unification type,
1675 // which is basically the LUB of the expressions
1676 // we've seen so far (combined with the expected
1677 // type)
1678(self.merged_ty(), expression_ty)
1679 };
16801681// Handle the actual type unification etc.
1682let result = if let Some(expression) = expression {
1683if self.expressions.is_empty() {
1684// Special-case the first expression we are coercing.
1685 // To be honest, I'm not entirely sure why we do this.
1686 // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
1687fcx.coerce(
1688 expression,
1689 expression_ty,
1690self.expected_ty,
1691 AllowTwoPhase::No,
1692Some(cause.clone()),
1693 )
1694 } else {
1695 fcx.try_find_coercion_lub(
1696 cause,
1697&self.expressions,
1698self.merged_ty(),
1699 expression,
1700 expression_ty,
1701 )
1702 }
1703 } else {
1704// this is a hack for cases where we default to `()` because
1705 // the expression etc has been omitted from the source. An
1706 // example is an `if let` without an else:
1707 //
1708 // if let Some(x) = ... { }
1709 //
1710 // we wind up with a second match arm that is like `_ =>
1711 // ()`. That is the case we are considering here. We take
1712 // a different path to get the right "expected, found"
1713 // message and so forth (and because we know that
1714 // `expression_ty` will be unit).
1715 //
1716 // Another example is `break` with no argument expression.
1717assert!(expression_ty.is_unit(), "if let hack without unit type");
1718 fcx.at(cause, fcx.param_env)
1719 .eq(
1720// needed for tests/ui/type-alias-impl-trait/issue-65679-inst-opaque-ty-from-val-twice.rs
1721DefineOpaqueTypes::Yes,
1722 expected,
1723 found,
1724 )
1725 .map(|infer_ok| {
1726 fcx.register_infer_ok_obligations(infer_ok);
1727 expression_ty
1728 })
1729 };
17301731debug!(?result);
1732match result {
1733Ok(v) => {
1734self.final_ty = Some(v);
1735if let Some(e) = expression {
1736self.expressions.push(e);
1737 }
1738 }
1739Err(coercion_error) => {
1740// Mark that we've failed to coerce the types here to suppress
1741 // any superfluous errors we might encounter while trying to
1742 // emit or provide suggestions on how to fix the initial error.
1743fcx.set_tainted_by_errors(
1744 fcx.dcx().span_delayed_bug(cause.span, "coercion error but no error emitted"),
1745 );
1746let (expected, found) = fcx.resolve_vars_if_possible((expected, found));
17471748let mut err;
1749let mut unsized_return = false;
1750match *cause.code() {
1751 ObligationCauseCode::ReturnNoExpression => {
1752 err = struct_span_code_err!(
1753 fcx.dcx(),
1754 cause.span,
1755 E0069,
1756"`return;` in a function whose return type is not `()`"
1757);
1758if let Some(value) = fcx.err_ctxt().ty_kind_suggestion(fcx.param_env, found)
1759 {
1760 err.span_suggestion_verbose(
1761 cause.span.shrink_to_hi(),
1762"give the `return` a value of the expected type",
1763format!(" {value}"),
1764 Applicability::HasPlaceholders,
1765 );
1766 }
1767 err.span_label(cause.span, "return type is not `()`");
1768 }
1769 ObligationCauseCode::BlockTailExpression(blk_id, ..) => {
1770 err = self.report_return_mismatched_types(
1771 cause,
1772 expected,
1773 found,
1774 coercion_error,
1775 fcx,
1776 blk_id,
1777 expression,
1778 );
1779 unsized_return = self.is_return_ty_definitely_unsized(fcx);
1780 }
1781 ObligationCauseCode::ReturnValue(return_expr_id) => {
1782 err = self.report_return_mismatched_types(
1783 cause,
1784 expected,
1785 found,
1786 coercion_error,
1787 fcx,
1788 return_expr_id,
1789 expression,
1790 );
1791 unsized_return = self.is_return_ty_definitely_unsized(fcx);
1792 }
1793 ObligationCauseCode::MatchExpressionArm(MatchExpressionArmCause {
1794 arm_span,
1795 arm_ty,
1796 prior_arm_ty,
1797ref prior_non_diverging_arms,
1798 tail_defines_return_position_impl_trait: Some(rpit_def_id),
1799 ..
1800 }) => {
1801 err = fcx.err_ctxt().report_mismatched_types(
1802 cause,
1803 fcx.param_env,
1804 expected,
1805 found,
1806 coercion_error,
1807 );
1808// Check that we're actually in the second or later arm
1809if prior_non_diverging_arms.len() > 0 {
1810self.suggest_boxing_tail_for_return_position_impl_trait(
1811 fcx,
1812&mut err,
1813 rpit_def_id,
1814 arm_ty,
1815 prior_arm_ty,
1816 prior_non_diverging_arms
1817 .iter()
1818 .chain(std::iter::once(&arm_span))
1819 .copied(),
1820 );
1821 }
1822 }
1823 ObligationCauseCode::IfExpression {
1824 expr_id,
1825 tail_defines_return_position_impl_trait: Some(rpit_def_id),
1826 } => {
1827let hir::Node::Expr(hir::Expr {
1828 kind: hir::ExprKind::If(_, then_expr, Some(else_expr)),
1829 ..
1830 }) = fcx.tcx.hir_node(expr_id)
1831else {
1832unreachable!();
1833 };
1834 err = fcx.err_ctxt().report_mismatched_types(
1835 cause,
1836 fcx.param_env,
1837 expected,
1838 found,
1839 coercion_error,
1840 );
1841let then_span = fcx.find_block_span_from_hir_id(then_expr.hir_id);
1842let else_span = fcx.find_block_span_from_hir_id(else_expr.hir_id);
1843// Don't suggest wrapping whole block in `Box::new`.
1844if then_span != then_expr.span && else_span != else_expr.span {
1845let then_ty = fcx.typeck_results.borrow().expr_ty(then_expr);
1846let else_ty = fcx.typeck_results.borrow().expr_ty(else_expr);
1847self.suggest_boxing_tail_for_return_position_impl_trait(
1848 fcx,
1849&mut err,
1850 rpit_def_id,
1851 then_ty,
1852 else_ty,
1853 [then_span, else_span].into_iter(),
1854 );
1855 }
1856 }
1857_ => {
1858 err = fcx.err_ctxt().report_mismatched_types(
1859 cause,
1860 fcx.param_env,
1861 expected,
1862 found,
1863 coercion_error,
1864 );
1865 }
1866 }
18671868 augment_error(&mut err);
18691870if let Some(expr) = expression {
1871if let hir::ExprKind::Loop(
1872 block,
1873_,
1874 loop_src @ (hir::LoopSource::While | hir::LoopSource::ForLoop),
1875_,
1876 ) = expr.kind
1877 {
1878let loop_type = if loop_src == hir::LoopSource::While {
1879"`while` loops"
1880} else {
1881"`for` loops"
1882};
18831884 err.note(format!("{loop_type} evaluate to unit type `()`"));
1885if loop_src == hir::LoopSource::While
1886 && let Some(pat) = irrefutable_if_let_expr(block)
1887 {
1888 err.span_label(
1889 pat.span,
1890"this pattern always matches, consider using `loop` instead",
1891 );
1892 }
1893 }
18941895 fcx.emit_coerce_suggestions(
1896&mut err,
1897 expr,
1898 found,
1899 expected,
1900None,
1901Some(coercion_error),
1902 );
1903 }
19041905let reported = err.emit_unless_delay(unsized_return);
19061907self.final_ty = Some(Ty::new_error(fcx.tcx, reported));
1908 }
1909 }
1910 }
19111912fn suggest_boxing_tail_for_return_position_impl_trait(
1913&self,
1914 fcx: &FnCtxt<'_, 'tcx>,
1915 err: &mut Diag<'_>,
1916 rpit_def_id: LocalDefId,
1917 a_ty: Ty<'tcx>,
1918 b_ty: Ty<'tcx>,
1919 arm_spans: impl Iterator<Item = Span>,
1920 ) {
1921let compatible = |ty: Ty<'tcx>| {
1922fcx.probe(|_| {
1923let ocx = ObligationCtxt::new(fcx);
1924ocx.register_obligations(
1925fcx.tcx
1926 .item_self_bounds(rpit_def_id)
1927 .iter_identity()
1928 .map(Unnormalized::skip_norm_wip)
1929 .filter_map(|clause| {
1930let predicate = clause
1931 .kind()
1932 .map_bound(|clause| match clause {
1933 ty::ClauseKind::Trait(trait_pred) => {
1934Some(ty::ClauseKind::Trait(
1935 trait_pred.with_replaced_self_ty(fcx.tcx, ty),
1936 ))
1937 }
1938 ty::ClauseKind::Projection(proj_pred) => {
1939Some(ty::ClauseKind::Projection(
1940 proj_pred.with_replaced_self_ty(fcx.tcx, ty),
1941 ))
1942 }
1943_ => None,
1944 })
1945 .transpose()?;
1946Some(Obligation::new(
1947fcx.tcx,
1948ObligationCause::dummy(),
1949fcx.param_env,
1950predicate,
1951 ))
1952 }),
1953 );
1954ocx.try_evaluate_obligations().no_errors()
1955 })
1956 };
19571958if !compatible(a_ty) || !compatible(b_ty) {
1959return;
1960 }
19611962let rpid_def_span = fcx.tcx.def_span(rpit_def_id);
1963err.subdiagnostic(SuggestBoxingForReturnImplTrait::ChangeReturnType {
1964 start_sp: rpid_def_span.with_hi(rpid_def_span.lo() + BytePos(4)),
1965 end_sp: rpid_def_span.shrink_to_hi(),
1966 });
19671968let (starts, ends) =
1969arm_spans.map(|span| (span.shrink_to_lo(), span.shrink_to_hi())).unzip();
1970err.subdiagnostic(SuggestBoxingForReturnImplTrait::BoxReturnExpr { starts, ends });
1971 }
19721973fn report_return_mismatched_types<'infcx>(
1974&self,
1975 cause: &ObligationCause<'tcx>,
1976 expected: Ty<'tcx>,
1977 found: Ty<'tcx>,
1978 ty_err: TypeError<'tcx>,
1979 fcx: &'infcx FnCtxt<'_, 'tcx>,
1980 block_or_return_id: hir::HirId,
1981 expression: Option<&'tcx hir::Expr<'tcx>>,
1982 ) -> Diag<'infcx> {
1983let mut err =
1984fcx.err_ctxt().report_mismatched_types(cause, fcx.param_env, expected, found, ty_err);
19851986let 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(..));
1987let parent = fcx.tcx.parent_hir_node(block_or_return_id);
1988if let Some(expr) = expression1989 && let hir::Node::Expr(&hir::Expr {
1990 kind: hir::ExprKind::Closure(&hir::Closure { body, .. }),
1991 ..
1992 }) = parent1993 {
1994let needs_block =
1995 !#[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(..));
1996fcx.suggest_missing_semicolon(&mut err, expr, expected, needs_block, true);
1997 }
1998// Verify that this is a tail expression of a function, otherwise the
1999 // label pointing out the cause for the type coercion will be wrong
2000 // as prior return coercions would not be relevant (#57664).
2001if let Some(expr) = expression2002 && due_to_block2003 {
2004fcx.suggest_missing_semicolon(&mut err, expr, expected, false, false);
2005let pointing_at_return_type = fcx.suggest_mismatched_types_on_tail(
2006&mut err,
2007expr,
2008expected,
2009found,
2010block_or_return_id,
2011 );
2012if let Some(cond_expr) = fcx.tcx.hir_get_if_cause(expr.hir_id)
2013 && expected.is_unit()
2014 && !pointing_at_return_type2015// If the block is from an external macro or try (`?`) desugaring, then
2016 // do not suggest adding a semicolon, because there's nowhere to put it.
2017 // See issues #81943 and #87051.
2018 // Similarly, if the block is from a loop desugaring, then also do not
2019 // suggest adding a semicolon. See issue #150850.
2020&& cond_expr.span.desugaring_kind().is_none()
2021 && !cond_expr.span.in_external_macro(fcx.tcx.sess.source_map())
2022 && !#[allow(non_exhaustive_omitted_patterns)] match cond_expr.kind {
hir::ExprKind::Match(.., hir::MatchSource::TryDesugar(_)) => true,
_ => false,
}matches!(
2023 cond_expr.kind,
2024 hir::ExprKind::Match(.., hir::MatchSource::TryDesugar(_))
2025 )2026 {
2027if let ObligationCauseCode::BlockTailExpression(hir_id, hir::MatchSource::Normal) =
2028cause.code()
2029 && let hir::Node::Block(block) = fcx.tcx.hir_node(*hir_id)
2030 && let hir::Node::Expr(expr) = fcx.tcx.parent_hir_node(block.hir_id)
2031 && let hir::Node::Expr(if_expr) = fcx.tcx.parent_hir_node(expr.hir_id)
2032 && let hir::ExprKind::If(_cond, _then, None) = if_expr.kind
2033 {
2034err.span_label(
2035cond_expr.span,
2036"`if` expressions without `else` arms expect their inner expression to be `()`",
2037 );
2038 } else {
2039err.span_label(cond_expr.span, "expected this to be `()`");
2040 }
2041if expr.can_have_side_effects() {
2042// Don't suggest semicolon after if expressions as it does not fix the issue
2043if !#[allow(non_exhaustive_omitted_patterns)] match cond_expr.kind {
hir::ExprKind::If(..) => true,
_ => false,
}matches!(cond_expr.kind, hir::ExprKind::If(..)) {
2044fcx.suggest_semicolon_at_end(cond_expr.span, &mut err);
2045 }
2046 }
2047 }
2048 }
20492050// If this is due to an explicit `return`, suggest adding a return type.
2051if let Some((fn_id, fn_decl)) = fcx.get_fn_decl(block_or_return_id)
2052 && !due_to_block2053 {
2054fcx.suggest_missing_return_type(&mut err, fn_decl, expected, found, fn_id);
2055 }
20562057// If this is due to a block, then maybe we forgot a `return`/`break`.
2058if due_to_block2059 && let Some(expr) = expression2060 && let Some(parent_fn_decl) =
2061fcx.tcx.hir_fn_decl_by_hir_id(fcx.tcx.local_def_id_to_hir_id(fcx.body_def_id))
2062 {
2063fcx.suggest_missing_break_or_return_expr(
2064&mut err,
2065expr,
2066parent_fn_decl,
2067expected,
2068found,
2069block_or_return_id,
2070fcx.body_def_id,
2071 );
2072 }
20732074let is_return_position = fcx2075 .tcx
2076 .hir_get_fn_id_for_return_block(block_or_return_id)
2077 .is_some_and(|fn_id| fn_id == fcx.tcx.local_def_id_to_hir_id(fcx.body_def_id));
20782079if is_return_position2080 && let Some(sp) = fcx.ret_coercion_span.get()
2081// If the closure has an explicit return type annotation, or if
2082 // the closure's return type has been inferred from outside
2083 // requirements (such as an Fn* trait bound), then a type error
2084 // may occur at the first return expression we see in the closure
2085 // (if it conflicts with the declared return type). Skip adding a
2086 // note in this case, since it would be incorrect.
2087&& let Some(fn_sig) = fcx.fn_sig()
2088 && fn_sig.output().is_ty_var()
2089 {
2090err.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"));
2091 }
20922093err2094 }
20952096/// Checks whether the return type is unsized via an obligation, which makes
2097 /// sure we consider `dyn Trait: Sized` where clauses, which are trivially
2098 /// false but technically valid for typeck.
2099fn is_return_ty_definitely_unsized(&self, fcx: &FnCtxt<'_, 'tcx>) -> bool {
2100if let Some(sig) = fcx.fn_sig() {
2101 !fcx.predicate_may_hold(&Obligation::new(
2102fcx.tcx,
2103ObligationCause::dummy(),
2104fcx.param_env,
2105 ty::TraitRef::new(
2106fcx.tcx,
2107fcx.tcx.require_lang_item(LangItem::Sized, DUMMY_SP),
2108 [sig.output()],
2109 ),
2110 ))
2111 } else {
2112false
2113}
2114 }
21152116pub(crate) fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> {
2117if let Some(final_ty) = self.final_ty {
2118final_ty2119 } else {
2120// If we only had inputs that were of type `!` (or no
2121 // inputs at all), then the final type is `!`.
2122if !self.expressions.is_empty() {
::core::panicking::panic("assertion failed: self.expressions.is_empty()")
};assert!(self.expressions.is_empty());
2123fcx.tcx.types.never
2124 }
2125 }
2126}
21272128fn irrefutable_if_let_expr<'hir>(block: &hir::Block<'hir>) -> Option<&'hir hir::Pat<'hir>> {
2129let hir::ExprKind::If(cond, _, _) = block.expr?.kind else {
2130return None;
2131 };
2132let hir::ExprKind::Let(let_expr) = cond.kind else {
2133return None;
2134 };
2135simple_irrefutable_pattern(let_expr.pat).then_some(let_expr.pat)
2136}
21372138fn simple_irrefutable_pattern(pat: &hir::Pat<'_>) -> bool {
2139match pat.kind {
2140 hir::PatKind::Wild | hir::PatKind::Binding(_, _, _, None) => true,
2141 hir::PatKind::Tuple(pats, _) => pats.iter().all(simple_irrefutable_pattern),
2142_ => false,
2143 }
2144}
21452146/// Recursively visit goals to decide whether an unsizing is possible.
2147/// `Break`s when it isn't, and an error should be raised.
2148/// `Continue`s when an unsizing ok based on an implementation of the `Unsize` trait / lang item.
2149struct CoerceVisitor<'a, 'tcx> {
2150 fcx: &'a FnCtxt<'a, 'tcx>,
2151 span: Span,
2152/// Whether the coercion is impossible. If so we sometimes still try to
2153 /// coerce in these cases to emit better errors. This changes the behavior
2154 /// when hitting the recursion limit.
2155errored: bool,
2156}
21572158impl<'tcx> ProofTreeVisitor<'tcx> for CoerceVisitor<'_, 'tcx> {
2159type Result = ControlFlow<()>;
21602161fn span(&self) -> Span {
2162self.span
2163 }
21642165fn visit_goal(&mut self, goal: &inspect::InspectGoal<'_, 'tcx>) -> Self::Result {
2166let Some(pred) = goal.goal().predicate.as_trait_clause() else {
2167return ControlFlow::Continue(());
2168 };
21692170// Make sure this predicate is referring to either an `Unsize` or `CoerceUnsized` trait,
2171 // Otherwise there's nothing to do.
2172if !self.fcx.tcx.is_lang_item(pred.def_id(), LangItem::Unsize)
2173 && !self.fcx.tcx.is_lang_item(pred.def_id(), LangItem::CoerceUnsized)
2174 {
2175return ControlFlow::Continue(());
2176 }
21772178match goal.result() {
2179// If we prove the `Unsize` or `CoerceUnsized` goal, continue recursing.
2180Ok(Certainty::Yes) => ControlFlow::Continue(()),
2181Err(NoSolution) => {
2182self.errored = true;
2183// Even if we find no solution, continue recursing if we find a single candidate
2184 // for which we're shallowly certain it holds to get the right error source.
2185if let [only_candidate] = &goal.candidates()[..]
2186 && only_candidate.shallow_certainty() == Certainty::Yes2187 {
2188only_candidate.visit_nested_no_probe(self)
2189 } else {
2190 ControlFlow::Break(())
2191 }
2192 }
2193Ok(Certainty::Maybe(_)) => {
2194// FIXME: structurally normalize?
2195if self.fcx.tcx.is_lang_item(pred.def_id(), LangItem::Unsize)
2196 && let ty::Dynamic(..) = pred.skip_binder().trait_ref.args.type_at(1).kind()
2197 && let ty::Infer(ty::TyVar(vid)) = *pred.self_ty().skip_binder().kind()
2198 && self.fcx.type_var_is_sized(vid)
2199 {
2200// We get here when trying to unsize a type variable to a `dyn Trait`,
2201 // knowing that that variable is sized. Unsizing definitely has to happen in that case.
2202 // If the variable weren't sized, we may not need an unsizing coercion.
2203 // In general, we don't want to add coercions too eagerly since it makes error messages much worse.
2204ControlFlow::Continue(())
2205 } else if let Some(cand) = goal.unique_applicable_candidate()
2206 && cand.shallow_certainty() == Certainty::Yes2207 {
2208cand.visit_nested_no_probe(self)
2209 } else {
2210 ControlFlow::Break(())
2211 }
2212 }
2213 }
2214 }
22152216fn on_recursion_limit(&mut self) -> Self::Result {
2217if self.errored {
2218// This prevents accidentally committing unfulfilled unsized coercions while trying to
2219 // find the error source for diagnostics.
2220 // See https://github.com/rust-lang/trait-system-refactor-initiative/issues/266.
2221ControlFlow::Break(())
2222 } else {
2223 ControlFlow::Continue(())
2224 }
2225 }
2226}