1//! # Type Coercion
2//!
3//! Under certain circumstances we will coerce from one type to another,
4//! for example by auto-borrowing. This occurs in situations where the
5//! compiler has a firm 'expected type' that was supplied from the user,
6//! and where the actual type is similar to that expected type in purpose
7//! but not in representation (so actual subtyping is inappropriate).
8//!
9//! ## Reborrowing
10//!
11//! Note that if we are expecting a reference, we will *reborrow*
12//! even if the argument provided was already a reference. This is
13//! useful for freezing mut things (that is, when the expected type is &T
14//! but you have &mut T) and also for avoiding the linearity
15//! of mut things (when the expected is &mut T and you have &mut T). See
16//! the various `tests/ui/coerce/*.rs` tests for
17//! examples of where this is useful.
18//!
19//! ## Subtle note
20//!
21//! When inferring the generic arguments of functions, the argument
22//! order is relevant, which can lead to the following edge case:
23//!
24//! ```ignore (illustrative)
25//! fn foo<T>(a: T, b: T) {
26//! // ...
27//! }
28//!
29//! foo(&7i32, &mut 7i32);
30//! // This compiles, as we first infer `T` to be `&i32`,
31//! // and then coerce `&mut 7i32` to `&7i32`.
32//!
33//! foo(&mut 7i32, &7i32);
34//! // This does not compile, as we first infer `T` to be `&mut i32`
35//! // and are then unable to coerce `&7i32` to `&mut i32`.
36//! ```
3738use std::ops::{ControlFlow, Deref};
3940use rustc_errors::codes::*;
41use rustc_errors::{Applicability, Diag, struct_span_code_err};
42use rustc_hir::attrs::InlineAttr;
43use rustc_hir::def_id::{DefId, LocalDefId};
44use rustc_hir::{selfas hir, LangItem};
45use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer;
46use rustc_infer::infer::relate::RelateResult;
47use rustc_infer::infer::{DefineOpaqueTypes, InferOk, InferResult, RegionVariableOrigin};
48use rustc_infer::traits::{
49MatchExpressionArmCause, Obligation, PredicateObligation, PredicateObligations, SelectionError,
50};
51use rustc_middle::span_bug;
52use rustc_middle::ty::adjustment::{
53Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, DerefAdjustKind,
54PointerCoercion,
55};
56use rustc_middle::ty::error::TypeError;
57use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt};
58use rustc_span::{BytePos, DUMMY_SP, Span};
59use rustc_trait_selection::infer::InferCtxtExt as _;
60use rustc_trait_selection::solve::inspect::{self, InferCtxtProofTreeExt, ProofTreeVisitor};
61use rustc_trait_selection::solve::{Certainty, Goal, NoSolution};
62use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
63use rustc_trait_selection::traits::{
64self, ImplSource, NormalizeExt, ObligationCause, ObligationCauseCode, ObligationCtxt,
65};
66use smallvec::{SmallVec, smallvec};
67use tracing::{debug, instrument};
6869use crate::FnCtxt;
70use crate::errors::SuggestBoxingForReturnImplTrait;
7172struct Coerce<'a, 'tcx> {
73 fcx: &'a FnCtxt<'a, 'tcx>,
74 cause: ObligationCause<'tcx>,
75 use_lub: bool,
76/// Determines whether or not allow_two_phase_borrow is set on any
77 /// autoref adjustments we create while coercing. We don't want to
78 /// allow deref coercions to create two-phase borrows, at least initially,
79 /// but we do need two-phase borrows for function argument reborrows.
80 /// See #47489 and #48598
81 /// See docs on the "AllowTwoPhase" type for a more detailed discussion
82allow_two_phase: AllowTwoPhase,
83/// Whether we allow `NeverToAny` coercions. This is unsound if we're
84 /// coercing a place expression without it counting as a read in the MIR.
85 /// This is a side-effect of HIR not really having a great distinction
86 /// between places and values.
87coerce_never: bool,
88}
8990impl<'a, 'tcx> Dereffor Coerce<'a, 'tcx> {
91type Target = FnCtxt<'a, 'tcx>;
92fn deref(&self) -> &Self::Target {
93self.fcx
94 }
95}
9697type CoerceResult<'tcx> = InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>;
9899/// Coercing a mutable reference to an immutable works, while
100/// coercing `&T` to `&mut T` should be forbidden.
101fn coerce_mutbls<'tcx>(
102 from_mutbl: hir::Mutability,
103 to_mutbl: hir::Mutability,
104) -> RelateResult<'tcx, ()> {
105if from_mutbl >= to_mutbl { Ok(()) } else { Err(TypeError::Mutability) }
106}
107108/// This always returns `Ok(...)`.
109fn success<'tcx>(
110 adj: Vec<Adjustment<'tcx>>,
111 target: Ty<'tcx>,
112 obligations: PredicateObligations<'tcx>,
113) -> CoerceResult<'tcx> {
114Ok(InferOk { value: (adj, target), obligations })
115}
116117/// Data extracted from a reference (pinned or not) for coercion to a reference (pinned or not).
118struct CoerceMaybePinnedRef<'tcx> {
119/// coercion source, must be a pinned (i.e. `Pin<&T>` or `Pin<&mut T>`) or normal reference (`&T` or `&mut T`)
120a: Ty<'tcx>,
121/// coercion target, must be a pinned (i.e. `Pin<&T>` or `Pin<&mut T>`) or normal reference (`&T` or `&mut T`)
122b: Ty<'tcx>,
123/// referent type of the source
124a_ty: Ty<'tcx>,
125/// pinnedness of the source
126a_pin: ty::Pinnedness,
127/// mutability of the source
128a_mut: ty::Mutability,
129/// region of the source
130a_r: ty::Region<'tcx>,
131/// pinnedness of the target
132b_pin: ty::Pinnedness,
133/// mutability of the target
134b_mut: ty::Mutability,
135}
136137/// Whether to force a leak check to occur in `Coerce::unify_raw`.
138/// Note that leak checks may still occur evn with `ForceLeakCheck::No`.
139///
140/// FIXME: We may want to change type relations to always leak-check
141/// after exiting a binder, at which point we will always do so and
142/// no longer need to handle this explicitly
143enum ForceLeakCheck {
144 Yes,
145 No,
146}
147148impl<'f, 'tcx> Coerce<'f, 'tcx> {
149fn new(
150 fcx: &'f FnCtxt<'f, 'tcx>,
151 cause: ObligationCause<'tcx>,
152 allow_two_phase: AllowTwoPhase,
153 coerce_never: bool,
154 ) -> Self {
155Coerce { fcx, cause, allow_two_phase, use_lub: false, coerce_never }
156 }
157158fn unify_raw(
159&self,
160 a: Ty<'tcx>,
161 b: Ty<'tcx>,
162 leak_check: ForceLeakCheck,
163 ) -> InferResult<'tcx, Ty<'tcx>> {
164{
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:164",
"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(164u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("unify(a: {0:?}, b: {1:?}, use_lub: {2})",
a, b, self.use_lub) as &dyn Value))])
});
} else { ; }
};debug!("unify(a: {:?}, b: {:?}, use_lub: {})", a, b, self.use_lub);
165self.commit_if_ok(|snapshot| {
166let outer_universe = self.infcx.universe();
167168let at = self.at(&self.cause, self.fcx.param_env);
169170let res = if self.use_lub {
171at.lub(b, a)
172 } else {
173at.sup(DefineOpaqueTypes::Yes, b, a)
174 .map(|InferOk { value: (), obligations }| InferOk { value: b, obligations })
175 };
176177// In the new solver, lazy norm may allow us to shallowly equate
178 // more types, but we emit possibly impossible-to-satisfy obligations.
179 // Filter these cases out to make sure our coercion is more accurate.
180let res = match res {
181Ok(InferOk { value, obligations }) if self.next_trait_solver() => {
182let ocx = ObligationCtxt::new(self);
183ocx.register_obligations(obligations);
184if ocx.try_evaluate_obligations().is_empty() {
185Ok(InferOk { value, obligations: ocx.into_pending_obligations() })
186 } else {
187Err(TypeError::Mismatch)
188 }
189 }
190 res => res,
191 };
192193// We leak check here mostly because lub operations are
194 // kind of scuffed around binders. Instead of computing an actual
195 // lub'd binder we instead:
196 // - Equate the binders
197 // - Return the lhs of the lub operation
198 //
199 // This may lead to incomplete type inference for the resulting type
200 // of a `match` or `if .. else`, etc. This is a backwards compat
201 // hazard for if/when we start handling `lub` more correctly.
202 //
203 // In order to actually ensure that equating the binders *does*
204 // result in equal binders, and that the lhs is actually a supertype
205 // of the rhs, we must perform a leak check here.
206if #[allow(non_exhaustive_omitted_patterns)] match leak_check {
ForceLeakCheck::Yes => true,
_ => false,
}matches!(leak_check, ForceLeakCheck::Yes) {
207self.leak_check(outer_universe, Some(snapshot))?;
208 }
209210res211 })
212 }
213214/// Unify two types (using sub or lub).
215fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>, leak_check: ForceLeakCheck) -> CoerceResult<'tcx> {
216self.unify_raw(a, b, leak_check)
217 .and_then(|InferOk { value: ty, obligations }| success(::alloc::vec::Vec::new()vec![], ty, obligations))
218 }
219220/// Unify two types (using sub or lub) and produce a specific coercion.
221fn unify_and(
222&self,
223 a: Ty<'tcx>,
224 b: Ty<'tcx>,
225 adjustments: impl IntoIterator<Item = Adjustment<'tcx>>,
226 final_adjustment: Adjust,
227 leak_check: ForceLeakCheck,
228 ) -> CoerceResult<'tcx> {
229self.unify_raw(a, b, leak_check).and_then(|InferOk { value: ty, obligations }| {
230success(
231adjustments232 .into_iter()
233 .chain(std::iter::once(Adjustment { target: ty, kind: final_adjustment }))
234 .collect(),
235ty,
236obligations,
237 )
238 })
239 }
240241x;#[instrument(skip(self), ret)]242fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
243// First, remove any resolved type variables (at the top level, at least):
244let a = self.shallow_resolve(a);
245let b = self.shallow_resolve(b);
246debug!("Coerce.tys({:?} => {:?})", a, b);
247248// Coercing from `!` to any type is allowed:
249if a.is_never() {
250if self.coerce_never {
251return success(
252vec![Adjustment { kind: Adjust::NeverToAny, target: b }],
253 b,
254 PredicateObligations::new(),
255 );
256 } else {
257// Otherwise the only coercion we can do is unification.
258return self.unify(a, b, ForceLeakCheck::No);
259 }
260 }
261262// Coercing *from* an unresolved inference variable means that
263 // we have no information about the source type. This will always
264 // ultimately fall back to some form of subtyping.
265if a.is_ty_var() {
266return self.coerce_from_inference_variable(a, b);
267 }
268269// Consider coercing the subtype to a DST
270 //
271 // NOTE: this is wrapped in a `commit_if_ok` because it creates
272 // a "spurious" type variable, and we don't want to have that
273 // type variable in memory if the coercion fails.
274let unsize = self.commit_if_ok(|_| self.coerce_unsized(a, b));
275match unsize {
276Ok(_) => {
277debug!("coerce: unsize successful");
278return unsize;
279 }
280Err(error) => {
281debug!(?error, "coerce: unsize failed");
282 }
283 }
284285// Examine the target type and consider type-specific coercions, such
286 // as auto-borrowing, coercing pointer mutability, or pin-ergonomics.
287match *b.kind() {
288 ty::RawPtr(_, b_mutbl) => {
289return self.coerce_to_raw_ptr(a, b, b_mutbl);
290 }
291 ty::Ref(r_b, _, mutbl_b) => {
292if let Some(pin_ref_to_ref) = self.maybe_pin_ref_to_ref(a, b) {
293return self.coerce_pin_ref_to_ref(pin_ref_to_ref);
294 }
295return self.coerce_to_ref(a, b, r_b, mutbl_b);
296 }
297_ if let Some(to_pin_ref) = self.maybe_to_pin_ref(a, b) => {
298return self.coerce_to_pin_ref(to_pin_ref);
299 }
300_ => {}
301 }
302303match *a.kind() {
304 ty::FnDef(..) => {
305// Function items are coercible to any closure
306 // type; function pointers are not (that would
307 // require double indirection).
308 // Additionally, we permit coercion of function
309 // items to drop the unsafe qualifier.
310self.coerce_from_fn_item(a, b)
311 }
312 ty::FnPtr(a_sig_tys, a_hdr) => {
313// We permit coercion of fn pointers to drop the
314 // unsafe qualifier.
315self.coerce_from_fn_pointer(a, a_sig_tys.with(a_hdr), b)
316 }
317 ty::Closure(..) => {
318// Non-capturing closures are coercible to
319 // function pointers or unsafe function pointers.
320 // It cannot convert closures that require unsafe.
321self.coerce_closure_to_fn(a, b)
322 }
323_ => {
324// Otherwise, just use unification rules.
325self.unify(a, b, ForceLeakCheck::No)
326 }
327 }
328 }
329330/// Coercing *from* an inference variable. In this case, we have no information
331 /// about the source type, so we can't really do a true coercion and we always
332 /// fall back to subtyping (`unify_and`).
333fn coerce_from_inference_variable(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
334{
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:334",
"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(334u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_from_inference_variable(a={0:?}, b={1:?})",
a, b) as &dyn Value))])
});
} else { ; }
};debug!("coerce_from_inference_variable(a={:?}, b={:?})", a, b);
335if 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);
336if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};debug_assert!(self.shallow_resolve(b) == b);
337338if b.is_ty_var() {
339let mut obligations = PredicateObligations::with_capacity(2);
340let mut push_coerce_obligation = |a, b| {
341obligations.push(Obligation::new(
342self.tcx(),
343self.cause.clone(),
344self.param_env,
345 ty::Binder::dummy(ty::PredicateKind::Coerce(ty::CoercePredicate { a, b })),
346 ));
347 };
348349let target_ty = if self.use_lub {
350// When computing the lub, we create a new target
351 // and coerce both `a` and `b` to it.
352let target_ty = self.next_ty_var(self.cause.span);
353push_coerce_obligation(a, target_ty);
354push_coerce_obligation(b, target_ty);
355target_ty356 } else {
357// When subtyping, we don't need to create a new target
358 // as we only coerce `a` to `b`.
359push_coerce_obligation(a, b);
360b361 };
362363{
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:363",
"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(363u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_from_inference_variable: two inference variables, target_ty={0:?}, obligations={1:?}",
target_ty, obligations) as &dyn Value))])
});
} else { ; }
};debug!(
364"coerce_from_inference_variable: two inference variables, target_ty={:?}, obligations={:?}",
365 target_ty, obligations
366 );
367success(::alloc::vec::Vec::new()vec![], target_ty, obligations)
368 } else {
369// One unresolved type variable: just apply subtyping, we may be able
370 // to do something useful.
371self.unify(a, b, ForceLeakCheck::No)
372 }
373 }
374375/// Handles coercing some arbitrary type `a` to some reference (`b`). This
376 /// handles a few cases:
377 /// - Introducing reborrows to give more flexible lifetimes
378 /// - Deref coercions to allow `&T` to coerce to `&T::Target`
379 /// - Coercing mutable references to immutable references
380 /// These coercions can be freely intermixed, for example we are able to
381 /// coerce `&mut T` to `&mut T::Target`.
382fn coerce_to_ref(
383&self,
384 a: Ty<'tcx>,
385 b: Ty<'tcx>,
386 r_b: ty::Region<'tcx>,
387 mutbl_b: hir::Mutability,
388 ) -> CoerceResult<'tcx> {
389{
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:389",
"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(389u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_to_ref(a={0:?}, b={1:?})",
a, b) as &dyn Value))])
});
} else { ; }
};debug!("coerce_to_ref(a={:?}, b={:?})", a, b);
390if true {
if !(self.shallow_resolve(a) == a) {
::core::panicking::panic("assertion failed: self.shallow_resolve(a) == a")
};
};debug_assert!(self.shallow_resolve(a) == a);
391if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};debug_assert!(self.shallow_resolve(b) == b);
392393let (r_a, mt_a) = match *a.kind() {
394 ty::Ref(r_a, ty, mutbl) => {
395coerce_mutbls(mutbl, mutbl_b)?;
396 (r_a, ty::TypeAndMut { ty, mutbl })
397 }
398_ => return self.unify(a, b, ForceLeakCheck::No),
399 };
400401// Look at each step in the `Deref` chain and check if
402 // any of the autoref'd `Target` types unify with the
403 // coercion target.
404 //
405 // For example when coercing from `&mut Vec<T>` to `&M [T]` we
406 // have three deref steps:
407 // 1. `&mut Vec<T>`, skip autoref
408 // 2. `Vec<T>`, autoref'd ty: `&M Vec<T>`
409 // - `&M Vec<T>` does not unify with `&M [T]`
410 // 3. `[T]`, autoref'd ty: `&M [T]`
411 // - `&M [T]` does unify with `&M [T]`
412let mut first_error = None;
413let mut r_borrow_var = None;
414let mut autoderef = self.autoderef(self.cause.span, a);
415let found = autoderef.by_ref().find_map(|(deref_ty, autoderefs)| {
416if autoderefs == 0 {
417// Don't autoref the first step as otherwise we'd allow
418 // coercing `&T` to `&&T`.
419return None;
420 }
421422// The logic here really shouldn't exist. We don't care about free
423 // lifetimes during HIR typeck. Unfortunately later parts of this
424 // function rely on structural identity of the autoref'd deref'd ty.
425 //
426 // This means that what region we use here actually impacts whether
427 // we emit a reborrow coercion or not which can affect diagnostics
428 // and capture analysis (which in turn affects borrowck).
429let r = if !self.use_lub {
430r_b431 } else if autoderefs == 1 {
432r_a433 } else {
434if r_borrow_var.is_none() {
435// create var lazily, at most once
436let coercion = RegionVariableOrigin::Coercion(self.cause.span);
437let r = self.next_region_var(coercion);
438r_borrow_var = Some(r);
439 }
440r_borrow_var.unwrap()
441 };
442443let autorefd_deref_ty = Ty::new_ref(self.tcx, r, deref_ty, mutbl_b);
444445// Note that we unify the autoref'd `Target` type with `b` rather than
446 // the `Target` type with the pointee of `b`. This is necessary
447 // to properly account for the differing variances of the pointees
448 // of `&` vs `&mut` references.
449match self.unify_raw(autorefd_deref_ty, b, ForceLeakCheck::No) {
450Ok(ok) => Some(ok),
451Err(err) => {
452if first_error.is_none() {
453first_error = Some(err);
454 }
455None456 }
457 }
458 });
459460// Extract type or return an error. We return the first error
461 // we got, which should be from relating the "base" type
462 // (e.g., in example above, the failure from relating `Vec<T>`
463 // to the target type), since that should be the least
464 // confusing.
465let Some(InferOk { value: coerced_a, mut obligations }) = foundelse {
466if let Some(first_error) = first_error {
467{
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:467",
"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(467u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_to_ref: failed with err = {0:?}",
first_error) as &dyn Value))])
});
} else { ; }
};debug!("coerce_to_ref: failed with err = {:?}", first_error);
468return Err(first_error);
469 } else {
470// This may happen in the new trait solver since autoderef requires
471 // the pointee to be structurally normalizable, or else it'll just bail.
472 // So when we have a type like `&<not well formed>`, then we get no
473 // autoderef steps (even though there should be at least one). That means
474 // we get no type mismatches, since the loop above just exits early.
475return Err(TypeError::Mismatch);
476 }
477 };
478479if coerced_a == a && mt_a.mutbl.is_not() && autoderef.step_count() == 1 {
480// As a special case, if we would produce `&'a *x`, that's
481 // a total no-op. We end up with the type `&'a T` just as
482 // we started with. In that case, just skip it altogether.
483 //
484 // Unfortunately, this can actually effect capture analysis
485 // which in turn means this effects borrow checking. This can
486 // also effect diagnostics.
487 // FIXME(BoxyUwU): we should always emit reborrow coercions
488 //
489 // Note that for `&mut`, we DO want to reborrow --
490 // otherwise, this would be a move, which might be an
491 // error. For example `foo(self.x)` where `self` and
492 // `self.x` both have `&mut `type would be a move of
493 // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
494 // which is a borrow.
495if !mutbl_b.is_not() {
::core::panicking::panic("assertion failed: mutbl_b.is_not()")
};assert!(mutbl_b.is_not()); // can only coerce &T -> &U
496return success(::alloc::vec::Vec::new()vec![], coerced_a, obligations);
497 }
498499let InferOk { value: mut adjustments, obligations: o } =
500self.adjust_steps_as_infer_ok(&autoderef);
501obligations.extend(o);
502obligations.extend(autoderef.into_obligations());
503504if !#[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!(
505matches!(coerced_a.kind(), ty::Ref(..)),
506"expected a ref type, got {:?}",
507 coerced_a
508 );
509510// Now apply the autoref
511let mutbl = AutoBorrowMutability::new(mutbl_b, self.allow_two_phase);
512adjustments513 .push(Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)), target: coerced_a });
514515{
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:515",
"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(515u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_to_ref: succeeded coerced_a={0:?} adjustments={1:?}",
coerced_a, adjustments) as &dyn Value))])
});
} else { ; }
};debug!("coerce_to_ref: succeeded coerced_a={:?} adjustments={:?}", coerced_a, adjustments);
516517success(adjustments, coerced_a, obligations)
518 }
519520/// Performs [unsized coercion] by emulating a fulfillment loop on a
521 /// `CoerceUnsized` goal until all `CoerceUnsized` and `Unsize` goals
522 /// are successfully selected.
523 ///
524 /// [unsized coercion](https://doc.rust-lang.org/reference/type-coercions.html#unsized-coercions)
525#[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(525u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["source", "target"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&target)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: CoerceResult<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:527",
"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(527u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["source", "target"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&source) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&target) as
&dyn Value))])
});
} else { ; }
};
if true {
if !(self.shallow_resolve(source) == source) {
::core::panicking::panic("assertion failed: self.shallow_resolve(source) == source")
};
};
if true {
if !(self.shallow_resolve(target) == target) {
::core::panicking::panic("assertion failed: self.shallow_resolve(target) == target")
};
};
if source.is_ty_var() {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:535",
"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(535u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: source is a TyVar, bailing out")
as &dyn Value))])
});
} else { ; }
};
return Err(TypeError::Mismatch);
}
if target.is_ty_var() {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:539",
"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(539u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: target is a TyVar, bailing out")
as &dyn Value))])
});
} else { ; }
};
return Err(TypeError::Mismatch);
}
match target.kind() {
ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_)
| ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) | ty::Str |
ty::Array(_, _) | ty::Slice(_) | ty::FnDef(_, _) |
ty::FnPtr(_, _) | ty::Dynamic(_, _) | ty::Closure(_, _) |
ty::CoroutineClosure(_, _) | ty::Coroutine(_, _) |
ty::CoroutineWitness(_, _) | ty::Never | ty::Tuple(_) =>
return Err(TypeError::Mismatch),
_ => {}
}
if let ty::Ref(_, source_pointee, ty::Mutability::Not) =
*source.kind() && source_pointee.is_str() &&
let ty::Ref(_, target_pointee, ty::Mutability::Not) =
*target.kind() && target_pointee.is_str() {
return Err(TypeError::Mismatch);
}
let traits =
(self.tcx.lang_items().unsize_trait(),
self.tcx.lang_items().coerce_unsized_trait());
let (Some(unsize_did), Some(coerce_unsized_did)) =
traits else {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:593",
"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(593u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("missing Unsize or CoerceUnsized traits")
as &dyn Value))])
});
} else { ; }
};
return Err(TypeError::Mismatch);
};
let reborrow =
match (source.kind(), target.kind()) {
(&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => {
coerce_mutbls(mutbl_a, mutbl_b)?;
let coercion =
RegionVariableOrigin::Coercion(self.cause.span);
let r_borrow = self.next_region_var(coercion);
let mutbl =
AutoBorrowMutability::new(mutbl_b, AllowTwoPhase::No);
Some((Adjustment {
kind: Adjust::Deref(DerefAdjustKind::Builtin),
target: ty_a,
},
Adjustment {
kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)),
target: Ty::new_ref(self.tcx, r_borrow, ty_a, mutbl_b),
}))
}
(&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(_, mt_b)) => {
coerce_mutbls(mt_a, mt_b)?;
Some((Adjustment {
kind: Adjust::Deref(DerefAdjustKind::Builtin),
target: ty_a,
},
Adjustment {
kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
target: Ty::new_ptr(self.tcx, ty_a, mt_b),
}))
}
_ => None,
};
let coerce_source =
reborrow.as_ref().map_or(source, |(_, r)| r.target);
let coerce_target = self.next_ty_var(self.cause.span);
let mut coercion =
self.unify_and(coerce_target, target,
reborrow.into_iter().flat_map(|(deref, autoref)|
[deref, autoref]), Adjust::Pointer(PointerCoercion::Unsize),
ForceLeakCheck::No)?;
let cause =
self.cause(self.cause.span,
ObligationCauseCode::Coercion { source, target });
let pred =
ty::TraitRef::new(self.tcx, coerce_unsized_did,
[coerce_source, coerce_target]);
let obligation =
Obligation::new(self.tcx, cause, self.fcx.param_env, pred);
if self.next_trait_solver() {
coercion.obligations.push(obligation);
if self.infcx.visit_proof_tree(Goal::new(self.tcx,
self.param_env, pred),
&mut CoerceVisitor {
fcx: self.fcx,
span: self.cause.span,
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")]526fn coerce_unsized(&self, source: Ty<'tcx>, target: Ty<'tcx>) -> CoerceResult<'tcx> {
527debug!(?source, ?target);
528debug_assert!(self.shallow_resolve(source) == source);
529debug_assert!(self.shallow_resolve(target) == target);
530531// We don't apply any coercions incase either the source or target
532 // aren't sufficiently well known but tend to instead just equate
533 // them both.
534if source.is_ty_var() {
535debug!("coerce_unsized: source is a TyVar, bailing out");
536return Err(TypeError::Mismatch);
537 }
538if target.is_ty_var() {
539debug!("coerce_unsized: target is a TyVar, bailing out");
540return Err(TypeError::Mismatch);
541 }
542543// This is an optimization because coercion is one of the most common
544 // operations that we do in typeck, since it happens at every assignment
545 // and call arg (among other positions).
546 //
547 // These targets are known to never be RHS in `LHS: CoerceUnsized<RHS>`.
548 // That's because these are built-in types for which a core-provided impl
549 // doesn't exist, and for which a user-written impl is invalid.
550 //
551 // This is technically incomplete when users write impossible bounds like
552 // `where T: CoerceUnsized<usize>`, for example, but that trait is unstable
553 // and coercion is allowed to be incomplete. The only case where this matters
554 // is impossible bounds.
555 //
556 // Note that some of these types implement `LHS: Unsize<RHS>`, but they
557 // do not implement *`CoerceUnsized`* which is the root obligation of the
558 // check below.
559match target.kind() {
560 ty::Bool
561 | ty::Char
562 | ty::Int(_)
563 | ty::Uint(_)
564 | ty::Float(_)
565 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
566 | ty::Str
567 | ty::Array(_, _)
568 | ty::Slice(_)
569 | ty::FnDef(_, _)
570 | ty::FnPtr(_, _)
571 | ty::Dynamic(_, _)
572 | ty::Closure(_, _)
573 | ty::CoroutineClosure(_, _)
574 | ty::Coroutine(_, _)
575 | ty::CoroutineWitness(_, _)
576 | ty::Never
577 | ty::Tuple(_) => return Err(TypeError::Mismatch),
578_ => {}
579 }
580// `&str: CoerceUnsized<&str>` does not hold but is encountered frequently
581 // so we fast path bail out here
582if let ty::Ref(_, source_pointee, ty::Mutability::Not) = *source.kind()
583 && source_pointee.is_str()
584 && let ty::Ref(_, target_pointee, ty::Mutability::Not) = *target.kind()
585 && target_pointee.is_str()
586 {
587return Err(TypeError::Mismatch);
588 }
589590let traits =
591 (self.tcx.lang_items().unsize_trait(), self.tcx.lang_items().coerce_unsized_trait());
592let (Some(unsize_did), Some(coerce_unsized_did)) = traits else {
593debug!("missing Unsize or CoerceUnsized traits");
594return Err(TypeError::Mismatch);
595 };
596597// Note, we want to avoid unnecessary unsizing. We don't want to coerce to
598 // a DST unless we have to. This currently comes out in the wash since
599 // we can't unify [T] with U. But to properly support DST, we need to allow
600 // that, at which point we will need extra checks on the target here.
601602 // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
603let reborrow = match (source.kind(), target.kind()) {
604 (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => {
605 coerce_mutbls(mutbl_a, mutbl_b)?;
606607let coercion = RegionVariableOrigin::Coercion(self.cause.span);
608let r_borrow = self.next_region_var(coercion);
609610// We don't allow two-phase borrows here, at least for initial
611 // implementation. If it happens that this coercion is a function argument,
612 // the reborrow in coerce_borrowed_ptr will pick it up.
613let mutbl = AutoBorrowMutability::new(mutbl_b, AllowTwoPhase::No);
614615Some((
616 Adjustment { kind: Adjust::Deref(DerefAdjustKind::Builtin), target: ty_a },
617 Adjustment {
618 kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)),
619 target: Ty::new_ref(self.tcx, r_borrow, ty_a, mutbl_b),
620 },
621 ))
622 }
623 (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(_, mt_b)) => {
624 coerce_mutbls(mt_a, mt_b)?;
625626Some((
627 Adjustment { kind: Adjust::Deref(DerefAdjustKind::Builtin), target: ty_a },
628 Adjustment {
629 kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
630 target: Ty::new_ptr(self.tcx, ty_a, mt_b),
631 },
632 ))
633 }
634_ => None,
635 };
636let coerce_source = reborrow.as_ref().map_or(source, |(_, r)| r.target);
637638// Setup either a subtyping or a LUB relationship between
639 // the `CoerceUnsized` target type and the expected type.
640 // We only have the latter, so we use an inference variable
641 // for the former and let type inference do the rest.
642let coerce_target = self.next_ty_var(self.cause.span);
643644let mut coercion = self.unify_and(
645 coerce_target,
646 target,
647 reborrow.into_iter().flat_map(|(deref, autoref)| [deref, autoref]),
648 Adjust::Pointer(PointerCoercion::Unsize),
649 ForceLeakCheck::No,
650 )?;
651652// Create an obligation for `Source: CoerceUnsized<Target>`.
653let cause = self.cause(self.cause.span, ObligationCauseCode::Coercion { source, target });
654let pred = ty::TraitRef::new(self.tcx, coerce_unsized_did, [coerce_source, coerce_target]);
655let obligation = Obligation::new(self.tcx, cause, self.fcx.param_env, pred);
656657if self.next_trait_solver() {
658 coercion.obligations.push(obligation);
659660if self
661.infcx
662 .visit_proof_tree(
663 Goal::new(self.tcx, self.param_env, pred),
664&mut CoerceVisitor { fcx: self.fcx, span: self.cause.span, errored: false },
665 )
666 .is_break()
667 {
668return Err(TypeError::Mismatch);
669 }
670 } else {
671self.coerce_unsized_old_solver(
672 obligation,
673&mut coercion,
674 coerce_unsized_did,
675 unsize_did,
676 )?;
677 }
678679Ok(coercion)
680 }
681682fn coerce_unsized_old_solver(
683&self,
684 obligation: Obligation<'tcx, ty::Predicate<'tcx>>,
685 coercion: &mut InferOk<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>,
686 coerce_unsized_did: DefId,
687 unsize_did: DefId,
688 ) -> Result<(), TypeError<'tcx>> {
689let mut selcx = traits::SelectionContext::new(self);
690// Use a FIFO queue for this custom fulfillment procedure.
691 //
692 // A Vec (or SmallVec) is not a natural choice for a queue. However,
693 // this code path is hot, and this queue usually has a max length of 1
694 // and almost never more than 3. By using a SmallVec we avoid an
695 // allocation, at the (very small) cost of (occasionally) having to
696 // shift subsequent elements down when removing the front element.
697let 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];
698699// Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
700 // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
701 // inference might unify those two inner type variables later.
702let traits = [coerce_unsized_did, unsize_did];
703while !queue.is_empty() {
704let obligation = queue.remove(0);
705let trait_pred = match obligation.predicate.kind().no_bound_vars() {
706Some(ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)))
707if traits.contains(&trait_pred.def_id()) =>
708 {
709self.resolve_vars_if_possible(trait_pred)
710 }
711// Eagerly process alias-relate obligations in new trait solver,
712 // since these can be emitted in the process of solving trait goals,
713 // but we need to constrain vars before processing goals mentioning
714 // them.
715Some(ty::PredicateKind::AliasRelate(..)) => {
716let ocx = ObligationCtxt::new(self);
717 ocx.register_obligation(obligation);
718if !ocx.try_evaluate_obligations().is_empty() {
719return Err(TypeError::Mismatch);
720 }
721 coercion.obligations.extend(ocx.into_pending_obligations());
722continue;
723 }
724_ => {
725 coercion.obligations.push(obligation);
726continue;
727 }
728 };
729{
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:729",
"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(729u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized resolve step: {0:?}",
trait_pred) as &dyn Value))])
});
} else { ; }
};debug!("coerce_unsized resolve step: {:?}", trait_pred);
730match selcx.select(&obligation.with(selcx.tcx(), trait_pred)) {
731// Uncertain or unimplemented.
732Ok(None) => {
733if trait_pred.def_id() == unsize_did {
734let self_ty = trait_pred.self_ty();
735let unsize_ty = trait_pred.trait_ref.args[1].expect_ty();
736{
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:736",
"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(736u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: ambiguous unsize case for {0:?}",
trait_pred) as &dyn Value))])
});
} else { ; }
};debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_pred);
737match (self_ty.kind(), unsize_ty.kind()) {
738 (&ty::Infer(ty::TyVar(v)), ty::Dynamic(..))
739if self.type_var_is_sized(v) =>
740 {
741{
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:741",
"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(741u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: have sized infer {0:?}",
v) as &dyn Value))])
});
} else { ; }
};debug!("coerce_unsized: have sized infer {:?}", v);
742 coercion.obligations.push(obligation);
743// `$0: Unsize<dyn Trait>` where we know that `$0: Sized`, try going
744 // for unsizing.
745}
746_ => {
747// Some other case for `$0: Unsize<Something>`. Note that we
748 // hit this case even if `Something` is a sized type, so just
749 // don't do the coercion.
750{
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:750",
"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(750u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: ambiguous unsize")
as &dyn Value))])
});
} else { ; }
};debug!("coerce_unsized: ambiguous unsize");
751return Err(TypeError::Mismatch);
752 }
753 }
754 } else {
755{
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:755",
"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(755u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: early return - ambiguous")
as &dyn Value))])
});
} else { ; }
};debug!("coerce_unsized: early return - ambiguous");
756return Err(TypeError::Mismatch);
757 }
758 }
759Err(SelectionError::Unimplemented) => {
760{
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:760",
"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(760u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: early return - can\'t prove obligation")
as &dyn Value))])
});
} else { ; }
};debug!("coerce_unsized: early return - can't prove obligation");
761return Err(TypeError::Mismatch);
762 }
763764Err(SelectionError::TraitDynIncompatible(_)) => {
765// Dyn compatibility errors in coercion will *always* be due to the
766 // fact that the RHS of the coercion is a non-dyn compatible `dyn Trait`
767 // written in source somewhere (otherwise we will never have lowered
768 // the dyn trait from HIR to middle).
769 //
770 // There's no reason to emit yet another dyn compatibility error,
771 // especially since the span will differ slightly and thus not be
772 // deduplicated at all!
773self.fcx.set_tainted_by_errors(
774self.fcx
775 .dcx()
776 .span_delayed_bug(self.cause.span, "dyn compatibility during coercion"),
777 );
778 }
779Err(err) => {
780let guar = self.err_ctxt().report_selection_error(
781 obligation.clone(),
782&obligation,
783&err,
784 );
785self.fcx.set_tainted_by_errors(guar);
786// Treat this like an obligation and follow through
787 // with the unsizing - the lack of a coercion should
788 // be silent, as it causes a type mismatch later.
789}
790Ok(Some(ImplSource::UserDefined(impl_source))) => {
791 queue.extend(impl_source.nested);
792// Certain incoherent `CoerceUnsized` implementations may cause ICEs,
793 // so check the impl's validity. Taint the body so that we don't try
794 // to evaluate these invalid coercions in CTFE. We only need to do this
795 // for local impls, since upstream impls should be valid.
796if impl_source.impl_def_id.is_local()
797 && let Err(guar) =
798self.tcx.ensure_result().coerce_unsized_info(impl_source.impl_def_id)
799 {
800self.fcx.set_tainted_by_errors(guar);
801 }
802 }
803Ok(Some(impl_source)) => queue.extend(impl_source.nested_obligations()),
804 }
805 }
806807Ok(())
808 }
809810/// Create an obligation for `ty: Unpin`, where .
811fn unpin_obligation(
812&self,
813 source: Ty<'tcx>,
814 target: Ty<'tcx>,
815 ty: Ty<'tcx>,
816 ) -> PredicateObligation<'tcx> {
817let pred = ty::TraitRef::new(
818self.tcx,
819self.tcx.require_lang_item(hir::LangItem::Unpin, self.cause.span),
820 [ty],
821 );
822let cause = self.cause(self.cause.span, ObligationCauseCode::Coercion { source, target });
823 PredicateObligation::new(self.tcx, cause, self.param_env, pred)
824 }
825826/// Checks if the given types are compatible for coercion from a pinned reference to a normal reference.
827fn maybe_pin_ref_to_ref(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> Option<CoerceMaybePinnedRef<'tcx>> {
828if !self.tcx.features().pin_ergonomics() {
829return None;
830 }
831if let Some((a_ty, a_pin @ ty::Pinnedness::Pinned, a_mut, a_r)) = a.maybe_pinned_ref()
832 && let Some((_, b_pin @ ty::Pinnedness::Not, b_mut, _)) = b.maybe_pinned_ref()
833 {
834return Some(CoerceMaybePinnedRef { a, b, a_ty, a_pin, a_mut, a_r, b_pin, b_mut });
835 }
836{
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:836",
"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(836u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("not fitting pinned ref to ref coercion (`{0:?}` -> `{1:?}`)",
a, b) as &dyn Value))])
});
} else { ; }
};debug!("not fitting pinned ref to ref coercion (`{:?}` -> `{:?}`)", a, b);
837None838 }
839840/// Coerces from a pinned reference to a normal reference.
841#[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(841u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["a", "b", "a_ty",
"a_pin", "a_mut", "a_r", "b_pin", "b_mut"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_ty)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_pin)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_mut)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_r)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b_pin)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b_mut)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: CoerceResult<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
if true {
if !(self.shallow_resolve(a) == a) {
::core::panicking::panic("assertion failed: self.shallow_resolve(a) == a")
};
};
if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};
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")]842fn coerce_pin_ref_to_ref(
843&self,
844CoerceMaybePinnedRef { a, b, a_ty, a_pin, a_mut, a_r, b_pin, b_mut }: CoerceMaybePinnedRef<
845'tcx,
846 >,
847 ) -> CoerceResult<'tcx> {
848debug_assert!(self.shallow_resolve(a) == a);
849debug_assert!(self.shallow_resolve(b) == b);
850debug_assert!(self.tcx.features().pin_ergonomics());
851debug_assert_eq!(a_pin, ty::Pinnedness::Pinned);
852debug_assert_eq!(b_pin, ty::Pinnedness::Not);
853854 coerce_mutbls(a_mut, b_mut)?;
855856let unpin_obligation = self.unpin_obligation(a, b, a_ty);
857858let a = Ty::new_ref(self.tcx, a_r, a_ty, b_mut);
859let mut coerce = self.unify_and(
860 a,
861 b,
862 [Adjustment { kind: Adjust::Deref(DerefAdjustKind::Pin), target: a_ty }],
863 Adjust::Borrow(AutoBorrow::Ref(AutoBorrowMutability::new(b_mut, self.allow_two_phase))),
864 ForceLeakCheck::No,
865 )?;
866 coerce.obligations.push(unpin_obligation);
867Ok(coerce)
868 }
869870/// Checks if the given types are compatible for coercion to a pinned reference.
871fn maybe_to_pin_ref(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> Option<CoerceMaybePinnedRef<'tcx>> {
872if !self.tcx.features().pin_ergonomics() {
873return None;
874 }
875if let Some((a_ty, a_pin, a_mut, a_r)) = a.maybe_pinned_ref()
876 && let Some((_, b_pin @ ty::Pinnedness::Pinned, b_mut, _)) = b.maybe_pinned_ref()
877 {
878return Some(CoerceMaybePinnedRef { a, b, a_ty, a_pin, a_mut, a_r, b_pin, b_mut });
879 }
880{
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:880",
"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(880u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("not fitting ref to pinned ref coercion (`{0:?}` -> `{1:?}`)",
a, b) as &dyn Value))])
});
} else { ; }
};debug!("not fitting ref to pinned ref coercion (`{:?}` -> `{:?}`)", a, b);
881None882 }
883884/// Applies reborrowing and auto-borrowing that results to `Pin<&T>` or `Pin<&mut T>`:
885 ///
886 /// Currently we only support the following coercions:
887 /// - Reborrowing `Pin<&mut T>` -> `Pin<&mut T>`
888 /// - Reborrowing `Pin<&T>` -> `Pin<&T>`
889 /// - Auto-borrowing `&mut T` -> `Pin<&mut T>` where `T: Unpin`
890 /// - Auto-borrowing `&mut T` -> `Pin<&T>` where `T: Unpin`
891 /// - Auto-borrowing `&T` -> `Pin<&T>` where `T: Unpin`
892 ///
893 /// In the future we might want to support other reborrowing coercions, such as:
894 /// - `Pin<Box<T>>` as `Pin<&T>`
895 /// - `Pin<Box<T>>` as `Pin<&mut T>`
896#[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(896u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["a", "b", "a_ty",
"a_pin", "a_mut", "a_r", "b_pin", "b_mut"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_ty)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_pin)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_mut)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_r)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b_pin)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b_mut)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: CoerceResult<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
if true {
if !(self.shallow_resolve(a) == a) {
::core::panicking::panic("assertion failed: self.shallow_resolve(a) == a")
};
};
if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};
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")]897fn coerce_to_pin_ref(
898&self,
899CoerceMaybePinnedRef { a, b, a_ty, a_pin, a_mut, a_r, b_pin, b_mut }: CoerceMaybePinnedRef<
900'tcx,
901 >,
902 ) -> CoerceResult<'tcx> {
903debug_assert!(self.shallow_resolve(a) == a);
904debug_assert!(self.shallow_resolve(b) == b);
905debug_assert!(self.tcx.features().pin_ergonomics());
906debug_assert_eq!(b_pin, ty::Pinnedness::Pinned);
907908// We need to deref the reference first before we reborrow it to a pinned reference.
909let (deref, unpin_obligation) = match a_pin {
910// no `Unpin` required when reborrowing a pinned reference to a pinned reference
911ty::Pinnedness::Pinned => (DerefAdjustKind::Pin, None),
912// `Unpin` required when reborrowing a non-pinned reference to a pinned reference
913ty::Pinnedness::Not => {
914 (DerefAdjustKind::Builtin, Some(self.unpin_obligation(a, b, a_ty)))
915 }
916 };
917918 coerce_mutbls(a_mut, b_mut)?;
919920// update a with b's mutability since we'll be coercing mutability
921let a = Ty::new_pinned_ref(self.tcx, a_r, a_ty, b_mut);
922923// To complete the reborrow, we need to make sure we can unify the inner types, and if so we
924 // add the adjustments.
925let mut coerce = self.unify_and(
926 a,
927 b,
928 [Adjustment { kind: Adjust::Deref(deref), target: a_ty }],
929 Adjust::Borrow(AutoBorrow::Pin(b_mut)),
930 ForceLeakCheck::No,
931 )?;
932933 coerce.obligations.extend(unpin_obligation);
934Ok(coerce)
935 }
936937fn coerce_from_fn_pointer(
938&self,
939 a: Ty<'tcx>,
940 a_sig: ty::PolyFnSig<'tcx>,
941 b: Ty<'tcx>,
942 ) -> CoerceResult<'tcx> {
943{
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:943",
"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(943u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message", "a_sig",
"b"], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_from_fn_pointer")
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&a_sig) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&b) as
&dyn Value))])
});
} else { ; }
};debug!(?a_sig, ?b, "coerce_from_fn_pointer");
944if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};debug_assert!(self.shallow_resolve(b) == b);
945946match b.kind() {
947 ty::FnPtr(_, b_hdr) if a_sig.safety().is_safe() && b_hdr.safety.is_unsafe() => {
948let a = self.tcx.safe_to_unsafe_fn_ty(a_sig);
949let adjust = Adjust::Pointer(PointerCoercion::UnsafeFnPointer);
950self.unify_and(a, b, [], adjust, ForceLeakCheck::Yes)
951 }
952_ => self.unify(a, b, ForceLeakCheck::Yes),
953 }
954 }
955956fn coerce_from_fn_item(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
957{
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:957",
"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(957u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_from_fn_item(a={0:?}, b={1:?})",
a, b) as &dyn Value))])
});
} else { ; }
};debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
958if true {
if !(self.shallow_resolve(a) == a) {
::core::panicking::panic("assertion failed: self.shallow_resolve(a) == a")
};
};debug_assert!(self.shallow_resolve(a) == a);
959if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};debug_assert!(self.shallow_resolve(b) == b);
960961match b.kind() {
962 ty::FnPtr(_, b_hdr) => {
963let a_sig = self.sig_for_fn_def_coercion(a, Some(b_hdr.safety))?;
964965let InferOk { value: a_sig, mut obligations } =
966self.at(&self.cause, self.param_env).normalize(a_sig);
967let a = Ty::new_fn_ptr(self.tcx, a_sig);
968969let adjust = Adjust::Pointer(PointerCoercion::ReifyFnPointer(b_hdr.safety));
970let InferOk { value, obligations: o2 } =
971self.unify_and(a, b, [], adjust, ForceLeakCheck::Yes)?;
972973obligations.extend(o2);
974Ok(InferOk { value, obligations })
975 }
976_ => self.unify(a, b, ForceLeakCheck::No),
977 }
978 }
979980/// Attempts to coerce from a closure to a function pointer. Fails
981 /// if the closure has any upvars.
982fn coerce_closure_to_fn(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
983if true {
if !(self.shallow_resolve(a) == a) {
::core::panicking::panic("assertion failed: self.shallow_resolve(a) == a")
};
};debug_assert!(self.shallow_resolve(a) == a);
984if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};debug_assert!(self.shallow_resolve(b) == b);
985986match b.kind() {
987 ty::FnPtr(_, hdr) => {
988let safety = hdr.safety;
989let terr = TypeError::Sorts(ty::error::ExpectedFound::new(a, b));
990let closure_sig = self.sig_for_closure_coercion(a, Some(hdr.safety), terr)?;
991let pointer_ty = Ty::new_fn_ptr(self.tcx, closure_sig);
992{
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:992",
"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(992u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_closure_to_fn(a={0:?}, b={1:?}, pty={2:?})",
a, b, pointer_ty) as &dyn Value))])
});
} else { ; }
};debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})", a, b, pointer_ty);
993994let adjust = Adjust::Pointer(PointerCoercion::ClosureFnPointer(safety));
995self.unify_and(pointer_ty, b, [], adjust, ForceLeakCheck::No)
996 }
997_ => self.unify(a, b, ForceLeakCheck::No),
998 }
999 }
10001001fn coerce_to_raw_ptr(
1002&self,
1003 a: Ty<'tcx>,
1004 b: Ty<'tcx>,
1005 mutbl_b: hir::Mutability,
1006 ) -> CoerceResult<'tcx> {
1007{
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:1007",
"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(1007u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coerce_to_raw_ptr(a={0:?}, b={1:?})",
a, b) as &dyn Value))])
});
} else { ; }
};debug!("coerce_to_raw_ptr(a={:?}, b={:?})", a, b);
1008if true {
if !(self.shallow_resolve(a) == a) {
::core::panicking::panic("assertion failed: self.shallow_resolve(a) == a")
};
};debug_assert!(self.shallow_resolve(a) == a);
1009if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};debug_assert!(self.shallow_resolve(b) == b);
10101011let (is_ref, mt_a) = match *a.kind() {
1012 ty::Ref(_, ty, mutbl) => (true, ty::TypeAndMut { ty, mutbl }),
1013 ty::RawPtr(ty, mutbl) => (false, ty::TypeAndMut { ty, mutbl }),
1014_ => return self.unify(a, b, ForceLeakCheck::No),
1015 };
1016coerce_mutbls(mt_a.mutbl, mutbl_b)?;
10171018// Check that the types which they point at are compatible.
1019let a_raw = Ty::new_ptr(self.tcx, mt_a.ty, mutbl_b);
1020// Although references and raw ptrs have the same
1021 // representation, we still register an Adjust::DerefRef so that
1022 // regionck knows that the region for `a` must be valid here.
1023if is_ref {
1024self.unify_and(
1025a_raw,
1026b,
1027 [Adjustment { kind: Adjust::Deref(DerefAdjustKind::Builtin), target: mt_a.ty }],
1028 Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)),
1029 ForceLeakCheck::No,
1030 )
1031 } else if mt_a.mutbl != mutbl_b {
1032self.unify_and(
1033a_raw,
1034b,
1035 [],
1036 Adjust::Pointer(PointerCoercion::MutToConstPointer),
1037 ForceLeakCheck::No,
1038 )
1039 } else {
1040self.unify(a_raw, b, ForceLeakCheck::No)
1041 }
1042 }
1043}
10441045impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
1046/// Attempt to coerce an expression to a type, and return the
1047 /// adjusted type of the expression, if successful.
1048 /// Adjustments are only recorded if the coercion succeeded.
1049 /// The expressions *must not* have any preexisting adjustments.
1050pub(crate) fn coerce(
1051&self,
1052 expr: &'tcx hir::Expr<'tcx>,
1053 expr_ty: Ty<'tcx>,
1054mut target: Ty<'tcx>,
1055 allow_two_phase: AllowTwoPhase,
1056 cause: Option<ObligationCause<'tcx>>,
1057 ) -> RelateResult<'tcx, Ty<'tcx>> {
1058let source = self.try_structurally_resolve_type(expr.span, expr_ty);
1059if self.next_trait_solver() {
1060target = self.try_structurally_resolve_type(
1061cause.as_ref().map_or(expr.span, |cause| cause.span),
1062target,
1063 );
1064 }
1065{
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:1065",
"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(1065u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coercion::try({0:?}: {1:?} -> {2:?})",
expr, source, target) as &dyn Value))])
});
} else { ; }
};debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
10661067let cause =
1068cause.unwrap_or_else(|| self.cause(expr.span, ObligationCauseCode::ExprAssignable));
1069let coerce = Coerce::new(
1070self,
1071cause,
1072allow_two_phase,
1073self.tcx.expr_guaranteed_to_constitute_read_for_never(expr),
1074 );
1075let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?;
10761077let (adjustments, _) = self.register_infer_ok_obligations(ok);
1078self.apply_adjustments(expr, adjustments);
1079Ok(if let Err(guar) = expr_ty.error_reported() {
1080Ty::new_error(self.tcx, guar)
1081 } else {
1082target1083 })
1084 }
10851086/// Probe whether `expr_ty` can be coerced to `target_ty`. This has no side-effects,
1087 /// and may return false positives if types are not yet fully constrained by inference.
1088 ///
1089 /// Returns false if the coercion is not possible, or if the coercion creates any
1090 /// sub-obligations that result in errors.
1091 ///
1092 /// This should only be used for diagnostics.
1093pub(crate) fn may_coerce(&self, expr_ty: Ty<'tcx>, target_ty: Ty<'tcx>) -> bool {
1094let cause = self.cause(DUMMY_SP, ObligationCauseCode::ExprAssignable);
1095// We don't ever need two-phase here since we throw out the result of the coercion.
1096 // We also just always set `coerce_never` to true, since this is a heuristic.
1097let coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No, true);
1098self.probe(|_| {
1099// Make sure to structurally resolve the types, since we use
1100 // the `TyKind`s heavily in coercion.
1101let ocx = ObligationCtxt::new(self);
1102let structurally_resolve = |ty| {
1103let ty = self.shallow_resolve(ty);
1104if self.next_trait_solver()
1105 && let ty::Alias(..) = ty.kind()
1106 {
1107ocx.structurally_normalize_ty(&cause, self.param_env, ty)
1108 } else {
1109Ok(ty)
1110 }
1111 };
1112let Ok(expr_ty) = structurally_resolve(expr_ty) else {
1113return false;
1114 };
1115let Ok(target_ty) = structurally_resolve(target_ty) else {
1116return false;
1117 };
11181119let Ok(ok) = coerce.coerce(expr_ty, target_ty) else {
1120return false;
1121 };
1122ocx.register_obligations(ok.obligations);
1123ocx.try_evaluate_obligations().is_empty()
1124 })
1125 }
11261127/// Given a type and a target type, this function will calculate and return
1128 /// how many dereference steps needed to coerce `expr_ty` to `target`. If
1129 /// it's not possible, return `None`.
1130pub(crate) fn deref_steps_for_suggestion(
1131&self,
1132 expr_ty: Ty<'tcx>,
1133 target: Ty<'tcx>,
1134 ) -> Option<usize> {
1135let cause = self.cause(DUMMY_SP, ObligationCauseCode::ExprAssignable);
1136// We don't ever need two-phase here since we throw out the result of the coercion.
1137let coerce = Coerce::new(self, cause, AllowTwoPhase::No, true);
1138coerce.autoderef(DUMMY_SP, expr_ty).find_map(|(ty, steps)| {
1139self.probe(|_| coerce.unify_raw(ty, target, ForceLeakCheck::No)).ok().map(|_| steps)
1140 })
1141 }
11421143/// Given a type, this function will calculate and return the type given
1144 /// for `<Ty as Deref>::Target` only if `Ty` also implements `DerefMut`.
1145 ///
1146 /// This function is for diagnostics only, since it does not register
1147 /// trait or region sub-obligations. (presumably we could, but it's not
1148 /// particularly important for diagnostics...)
1149pub(crate) fn deref_once_mutably_for_diagnostic(&self, expr_ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
1150self.autoderef(DUMMY_SP, expr_ty).silence_errors().nth(1).and_then(|(deref_ty, _)| {
1151self.infcx
1152 .type_implements_trait(
1153self.tcx.lang_items().deref_mut_trait()?,
1154 [expr_ty],
1155self.param_env,
1156 )
1157 .may_apply()
1158 .then_some(deref_ty)
1159 })
1160 }
11611162x;#[instrument(level = "debug", skip(self), ret)]1163fn sig_for_coerce_lub(
1164&self,
1165 ty: Ty<'tcx>,
1166 closure_upvars_terr: TypeError<'tcx>,
1167 ) -> Result<ty::PolyFnSig<'tcx>, TypeError<'tcx>> {
1168match ty.kind() {
1169 ty::FnDef(..) => self.sig_for_fn_def_coercion(ty, None),
1170 ty::Closure(..) => self.sig_for_closure_coercion(ty, None, closure_upvars_terr),
1171_ => unreachable!("`sig_for_fn_def_closure_coerce_lub` called with wrong ty: {:?}", ty),
1172 }
1173 }
11741175fn sig_for_fn_def_coercion(
1176&self,
1177 fndef: Ty<'tcx>,
1178 expected_safety: Option<hir::Safety>,
1179 ) -> Result<ty::PolyFnSig<'tcx>, TypeError<'tcx>> {
1180let tcx = self.tcx;
11811182let &ty::FnDef(def_id, _) = fndef.kind() else {
1183{
::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);
1184 };
11851186// Intrinsics are not coercible to function pointers
1187if tcx.intrinsic(def_id).is_some() {
1188return Err(TypeError::IntrinsicCast);
1189 }
11901191let fn_attrs = tcx.codegen_fn_attrs(def_id);
1192if #[allow(non_exhaustive_omitted_patterns)] match fn_attrs.inline {
InlineAttr::Force { .. } => true,
_ => false,
}matches!(fn_attrs.inline, InlineAttr::Force { .. }) {
1193return Err(TypeError::ForceInlineCast);
1194 }
11951196let sig = fndef.fn_sig(tcx);
1197let sig = if fn_attrs.safe_target_features {
1198// Allow the coercion if the current function has all the features that would be
1199 // needed to call the coercee safely.
1200match tcx.adjust_target_feature_sig(def_id, sig, self.body_id.into()) {
1201Some(adjusted_sig) => adjusted_sig,
1202Noneif #[allow(non_exhaustive_omitted_patterns)] match expected_safety {
Some(hir::Safety::Safe) => true,
_ => false,
}matches!(expected_safety, Some(hir::Safety::Safe)) => {
1203return Err(TypeError::TargetFeatureCast(def_id));
1204 }
1205None => sig,
1206 }
1207 } else {
1208sig1209 };
12101211if 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)) {
1212Ok(tcx.safe_to_unsafe_sig(sig))
1213 } else {
1214Ok(sig)
1215 }
1216 }
12171218fn sig_for_closure_coercion(
1219&self,
1220 closure: Ty<'tcx>,
1221 expected_safety: Option<hir::Safety>,
1222 closure_upvars_terr: TypeError<'tcx>,
1223 ) -> Result<ty::PolyFnSig<'tcx>, TypeError<'tcx>> {
1224let tcx = self.tcx;
12251226let ty::Closure(closure_def, closure_args) = closure.kind() else {
1227{
::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);
1228 };
12291230// At this point we haven't done capture analysis, which means
1231 // that the ClosureArgs just contains an inference variable instead
1232 // of tuple of captured types.
1233 //
1234 // All we care here is if any variable is being captured and not the exact paths,
1235 // so we check `upvars_mentioned` for root variables being captured.
1236if !tcx.upvars_mentioned(closure_def.expect_local()).is_none_or(|u| u.is_empty()) {
1237return Err(closure_upvars_terr);
1238 }
12391240// We coerce the closure, which has fn type
1241 // `extern "rust-call" fn((arg0,arg1,...)) -> _`
1242 // to
1243 // `fn(arg0,arg1,...) -> _`
1244 // or
1245 // `unsafe fn(arg0,arg1,...) -> _`
1246let closure_sig = closure_args.as_closure().sig();
1247Ok(tcx.signature_unclosure(closure_sig, expected_safety.unwrap_or(hir::Safety::Safe)))
1248 }
12491250/// Given some expressions, their known unified type and another expression,
1251 /// tries to unify the types, potentially inserting coercions on any of the
1252 /// provided expressions and returns their LUB (aka "common supertype").
1253 ///
1254 /// This is really an internal helper. From outside the coercion
1255 /// module, you should instantiate a `CoerceMany` instance.
1256fn try_find_coercion_lub(
1257&self,
1258 cause: &ObligationCause<'tcx>,
1259 exprs: &[&'tcx hir::Expr<'tcx>],
1260 prev_ty: Ty<'tcx>,
1261 new: &hir::Expr<'_>,
1262 new_ty: Ty<'tcx>,
1263 ) -> RelateResult<'tcx, Ty<'tcx>> {
1264let prev_ty = self.try_structurally_resolve_type(cause.span, prev_ty);
1265let new_ty = self.try_structurally_resolve_type(new.span, new_ty);
1266{
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:1266",
"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(1266u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coercion::try_find_coercion_lub({0:?}, {1:?}, exprs={2:?} exprs)",
prev_ty, new_ty, exprs.len()) as &dyn Value))])
});
} else { ; }
};debug!(
1267"coercion::try_find_coercion_lub({:?}, {:?}, exprs={:?} exprs)",
1268 prev_ty,
1269 new_ty,
1270 exprs.len()
1271 );
12721273// Fast Path: don't go through the coercion logic if we're coercing
1274 // a type to itself. This is unfortunately quite perf relevant so
1275 // we do it even though it may mask bugs in the coercion logic.
1276if prev_ty == new_ty {
1277return Ok(prev_ty);
1278 }
12791280let terr = TypeError::Sorts(ty::error::ExpectedFound::new(prev_ty, new_ty));
1281let opt_sigs = match (prev_ty.kind(), new_ty.kind()) {
1282// Don't coerce pairs of fndefs or pairs of closures to fn ptrs
1283 // if they can just be lubbed.
1284 //
1285 // See #88097 or `lub_closures_before_fnptr_coercion.rs` for where
1286 // we would erroneously coerce closures to fnptrs when attempting to
1287 // coerce a closure to itself.
1288(ty::FnDef(..), ty::FnDef(..)) | (ty::Closure(..), ty::Closure(..)) => {
1289let lubbed_ty = self.commit_if_ok(|snapshot| {
1290let outer_universe = self.infcx.universe();
12911292// We need to eagerly handle nested obligations due to lazy norm.
1293let result = if self.next_trait_solver() {
1294let ocx = ObligationCtxt::new(self);
1295let value = ocx.lub(cause, self.param_env, prev_ty, new_ty)?;
1296if ocx.try_evaluate_obligations().is_empty() {
1297Ok(InferOk { value, obligations: ocx.into_pending_obligations() })
1298 } else {
1299Err(TypeError::Mismatch)
1300 }
1301 } else {
1302self.at(cause, self.param_env).lub(prev_ty, new_ty)
1303 };
13041305self.leak_check(outer_universe, Some(snapshot))?;
1306result1307 });
13081309match lubbed_ty {
1310Ok(ok) => return Ok(self.register_infer_ok_obligations(ok)),
1311Err(_) => {
1312let a_sig = self.sig_for_coerce_lub(prev_ty, terr)?;
1313let b_sig = self.sig_for_coerce_lub(new_ty, terr)?;
1314Some((a_sig, b_sig))
1315 }
1316 }
1317 }
13181319 (ty::Closure(..), ty::FnDef(..)) | (ty::FnDef(..), ty::Closure(..)) => {
1320let a_sig = self.sig_for_coerce_lub(prev_ty, terr)?;
1321let b_sig = self.sig_for_coerce_lub(new_ty, terr)?;
1322Some((a_sig, b_sig))
1323 }
1324// ty::FnPtr x ty::FnPtr is fine to just be handled through a normal `unify`
1325 // call using `lub` which is what will happen on the normal path.
1326(ty::FnPtr(..), ty::FnPtr(..)) => None,
1327_ => None,
1328 };
13291330if let Some((mut a_sig, mut b_sig)) = opt_sigs {
1331// Allow coercing safe sigs to unsafe sigs
1332if a_sig.safety().is_safe() && b_sig.safety().is_unsafe() {
1333a_sig = self.tcx.safe_to_unsafe_sig(a_sig);
1334 } else if b_sig.safety().is_safe() && a_sig.safety().is_unsafe() {
1335b_sig = self.tcx.safe_to_unsafe_sig(b_sig);
1336 };
13371338// The signature must match.
1339let (a_sig, b_sig) = self.normalize(new.span, (a_sig, b_sig));
1340let sig = self1341 .at(cause, self.param_env)
1342 .lub(a_sig, b_sig)
1343 .map(|ok| self.register_infer_ok_obligations(ok))?;
13441345// Reify both sides and return the reified fn pointer type.
1346let fn_ptr = Ty::new_fn_ptr(self.tcx, sig);
1347let prev_adjustment = match prev_ty.kind() {
1348 ty::Closure(..) => Adjust::Pointer(PointerCoercion::ClosureFnPointer(sig.safety())),
1349 ty::FnDef(..) => Adjust::Pointer(PointerCoercion::ReifyFnPointer(sig.safety())),
1350_ => ::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"),
1351 };
1352let next_adjustment = match new_ty.kind() {
1353 ty::Closure(..) => Adjust::Pointer(PointerCoercion::ClosureFnPointer(sig.safety())),
1354 ty::FnDef(..) => Adjust::Pointer(PointerCoercion::ReifyFnPointer(sig.safety())),
1355_ => ::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"),
1356 };
1357for expr in exprs.iter() {
1358self.apply_adjustments(
1359 expr,
1360::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 }],
1361 );
1362 }
1363self.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 }]);
1364return Ok(fn_ptr);
1365 }
13661367// Configure a Coerce instance to compute the LUB.
1368 // We don't allow two-phase borrows on any autorefs this creates since we
1369 // probably aren't processing function arguments here and even if we were,
1370 // they're going to get autorefed again anyway and we can apply 2-phase borrows
1371 // at that time.
1372 //
1373 // NOTE: we set `coerce_never` to `true` here because coercion LUBs only
1374 // operate on values and not places, so a never coercion is valid.
1375let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No, true);
1376coerce.use_lub = true;
13771378// First try to coerce the new expression to the type of the previous ones,
1379 // but only if the new expression has no coercion already applied to it.
1380let mut first_error = None;
1381if !self.typeck_results.borrow().adjustments().contains_key(new.hir_id) {
1382let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
1383match result {
1384Ok(ok) => {
1385let (adjustments, target) = self.register_infer_ok_obligations(ok);
1386self.apply_adjustments(new, adjustments);
1387{
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:1387",
"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(1387u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coercion::try_find_coercion_lub: was able to coerce from new type {0:?} to previous type {1:?} ({2:?})",
new_ty, prev_ty, target) as &dyn Value))])
});
} else { ; }
};debug!(
1388"coercion::try_find_coercion_lub: was able to coerce from new type {:?} to previous type {:?} ({:?})",
1389 new_ty, prev_ty, target
1390 );
1391return Ok(target);
1392 }
1393Err(e) => first_error = Some(e),
1394 }
1395 }
13961397let ok = self1398 .commit_if_ok(|_| coerce.coerce(prev_ty, new_ty))
1399// Avoid giving strange errors on failed attempts.
1400.map_err(|e| first_error.unwrap_or(e))?;
14011402let (adjustments, target) = self.register_infer_ok_obligations(ok);
1403for expr in exprs {
1404self.apply_adjustments(expr, adjustments.clone());
1405 }
1406{
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:1406",
"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(1406u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("coercion::try_find_coercion_lub: was able to coerce previous type {0:?} to new type {1:?} ({2:?})",
prev_ty, new_ty, target) as &dyn Value))])
});
} else { ; }
};debug!(
1407"coercion::try_find_coercion_lub: was able to coerce previous type {:?} to new type {:?} ({:?})",
1408 prev_ty, new_ty, target
1409 );
1410Ok(target)
1411 }
1412}
14131414/// Check whether `ty` can be coerced to `output_ty`.
1415/// Used from clippy.
1416pub fn can_coerce<'tcx>(
1417 tcx: TyCtxt<'tcx>,
1418 param_env: ty::ParamEnv<'tcx>,
1419 body_id: LocalDefId,
1420 ty: Ty<'tcx>,
1421 output_ty: Ty<'tcx>,
1422) -> bool {
1423let root_ctxt = crate::typeck_root_ctxt::TypeckRootCtxt::new(tcx, body_id);
1424let fn_ctxt = FnCtxt::new(&root_ctxt, param_env, body_id);
1425fn_ctxt.may_coerce(ty, output_ty)
1426}
14271428/// CoerceMany encapsulates the pattern you should use when you have
1429/// many expressions that are all getting coerced to a common
1430/// type. This arises, for example, when you have a match (the result
1431/// of each arm is coerced to a common type). It also arises in less
1432/// obvious places, such as when you have many `break foo` expressions
1433/// that target the same loop, or the various `return` expressions in
1434/// a function.
1435///
1436/// The basic protocol is as follows:
1437///
1438/// - Instantiate the `CoerceMany` with an initial `expected_ty`.
1439/// This will also serve as the "starting LUB". The expectation is
1440/// that this type is something which all of the expressions *must*
1441/// be coercible to. Use a fresh type variable if needed.
1442/// - For each expression whose result is to be coerced, invoke `coerce()` with.
1443/// - In some cases we wish to coerce "non-expressions" whose types are implicitly
1444/// unit. This happens for example if you have a `break` with no expression,
1445/// or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
1446/// - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
1447/// from you so that you don't have to worry your pretty head about it.
1448/// But if an error is reported, the final type will be `err`.
1449/// - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
1450/// previously coerced expressions.
1451/// - When all done, invoke `complete()`. This will return the LUB of
1452/// all your expressions.
1453/// - WARNING: I don't believe this final type is guaranteed to be
1454/// related to your initial `expected_ty` in any particular way,
1455/// although it will typically be a subtype, so you should check it.
1456/// Check the note below for more details.
1457/// - Invoking `complete()` may cause us to go and adjust the "adjustments" on
1458/// previously coerced expressions.
1459///
1460/// Example:
1461///
1462/// ```ignore (illustrative)
1463/// let mut coerce = CoerceMany::new(expected_ty);
1464/// for expr in exprs {
1465/// let expr_ty = fcx.check_expr_with_expectation(expr, expected);
1466/// coerce.coerce(fcx, &cause, expr, expr_ty);
1467/// }
1468/// let final_ty = coerce.complete(fcx);
1469/// ```
1470///
1471/// NOTE: Why does the `expected_ty` participate in the LUB?
1472/// When coercing, each branch should use the following expectations for type inference:
1473/// - The branch can be coerced to the expected type of the match/if/whatever.
1474/// - The branch can be coercion lub'd with the types of the previous branches.
1475/// Ideally we'd have some sort of `Expectation::ParticipatesInCoerceLub(ongoing_lub_ty, final_ty)`,
1476/// but adding and using this feels very challenging.
1477/// What we instead do is to use the expected type of the match/if/whatever as
1478/// the initial coercion lub. This allows us to use the lub of "expected type of match" with
1479/// "types from previous branches" as the coercion target, which can contains both expectations.
1480///
1481/// Two concerns with this approach:
1482/// - We may have incompatible `final_ty` if that lub is different from the expected
1483/// type of the match. However, in this case coercing the final type of the
1484/// `CoerceMany` to its expected type would have error'd anyways, so we don't care.
1485/// - We may constrain the `expected_ty` too early. For some branches with
1486/// type `a` and `b`, we end up with `(a lub expected_ty) lub b` instead of
1487/// `(a lub b) lub expected_ty`. They should be the same type. However,
1488/// `a lub expected_ty` may constrain inference variables in `expected_ty`.
1489/// In this case the difference does matter and we get actually incorrect results.
1490/// FIXME: Ideally we'd compute the final type without unnecessarily constraining
1491/// the expected type of the match when computing the types of its branches.
1492pub(crate) struct CoerceMany<'tcx> {
1493 expected_ty: Ty<'tcx>,
1494 final_ty: Option<Ty<'tcx>>,
1495 expressions: Vec<&'tcx hir::Expr<'tcx>>,
1496}
14971498impl<'tcx> CoerceMany<'tcx> {
1499/// Creates a `CoerceMany` with a default capacity of 1. If the full set of
1500 /// coercion sites is known before hand, consider `with_capacity()` instead
1501 /// to avoid allocation.
1502pub(crate) fn new(expected_ty: Ty<'tcx>) -> Self {
1503Self::with_capacity(expected_ty, 1)
1504 }
15051506/// Creates a `CoerceMany` with a given capacity.
1507pub(crate) fn with_capacity(expected_ty: Ty<'tcx>, capacity: usize) -> Self {
1508CoerceMany { expected_ty, final_ty: None, expressions: Vec::with_capacity(capacity) }
1509 }
15101511/// Returns the "expected type" with which this coercion was
1512 /// constructed. This represents the "downward propagated" type
1513 /// that was given to us at the start of typing whatever construct
1514 /// we are typing (e.g., the match expression).
1515 ///
1516 /// Typically, this is used as the expected type when
1517 /// type-checking each of the alternative expressions whose types
1518 /// we are trying to merge.
1519pub(crate) fn expected_ty(&self) -> Ty<'tcx> {
1520self.expected_ty
1521 }
15221523/// Returns the current "merged type", representing our best-guess
1524 /// at the LUB of the expressions we've seen so far (if any). This
1525 /// isn't *final* until you call `self.complete()`, which will return
1526 /// the merged type.
1527pub(crate) fn merged_ty(&self) -> Ty<'tcx> {
1528self.final_ty.unwrap_or(self.expected_ty)
1529 }
15301531/// Indicates that the value generated by `expression`, which is
1532 /// of type `expression_ty`, is one of the possibilities that we
1533 /// could coerce from. This will record `expression`, and later
1534 /// calls to `coerce` may come back and add adjustments and things
1535 /// if necessary.
1536pub(crate) fn coerce<'a>(
1537&mut self,
1538 fcx: &FnCtxt<'a, 'tcx>,
1539 cause: &ObligationCause<'tcx>,
1540 expression: &'tcx hir::Expr<'tcx>,
1541 expression_ty: Ty<'tcx>,
1542 ) {
1543self.coerce_inner(fcx, cause, Some(expression), expression_ty, |_| {}, false)
1544 }
15451546/// Indicates that one of the inputs is a "forced unit". This
1547 /// occurs in a case like `if foo { ... };`, where the missing else
1548 /// generates a "forced unit". Another example is a `loop { break;
1549 /// }`, where the `break` has no argument expression. We treat
1550 /// these cases slightly differently for error-reporting
1551 /// purposes. Note that these tend to correspond to cases where
1552 /// the `()` expression is implicit in the source, and hence we do
1553 /// not take an expression argument.
1554 ///
1555 /// The `augment_error` gives you a chance to extend the error
1556 /// message, in case any results (e.g., we use this to suggest
1557 /// removing a `;`).
1558pub(crate) fn coerce_forced_unit<'a>(
1559&mut self,
1560 fcx: &FnCtxt<'a, 'tcx>,
1561 cause: &ObligationCause<'tcx>,
1562 augment_error: impl FnOnce(&mut Diag<'_>),
1563 label_unit_as_expected: bool,
1564 ) {
1565self.coerce_inner(
1566fcx,
1567cause,
1568None,
1569fcx.tcx.types.unit,
1570augment_error,
1571label_unit_as_expected,
1572 )
1573 }
15741575/// The inner coercion "engine". If `expression` is `None`, this
1576 /// is a forced-unit case, and hence `expression_ty` must be
1577 /// `Nil`.
1578#[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(1578u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["cause",
"expression", "expression_ty"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expression)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expression_ty)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
if expression_ty.is_ty_var() {
expression_ty = fcx.infcx.shallow_resolve(expression_ty);
}
if let Err(guar) =
(expression_ty, self.merged_ty()).error_reported() {
self.final_ty = Some(Ty::new_error(fcx.tcx, guar));
return;
}
let (expected, found) =
if label_expression_as_expected {
(expression_ty, self.merged_ty())
} else { (self.merged_ty(), expression_ty) };
let result =
if let Some(expression) = expression {
if self.expressions.is_empty() {
fcx.coerce(expression, expression_ty, self.expected_ty,
AllowTwoPhase::No, Some(cause.clone()))
} else {
fcx.try_find_coercion_lub(cause, &self.expressions,
self.merged_ty(), expression, expression_ty)
}
} else {
if !expression_ty.is_unit() {
{
::core::panicking::panic_fmt(format_args!("if let hack without unit type"));
}
};
fcx.at(cause,
fcx.param_env).eq(DefineOpaqueTypes::Yes, expected,
found).map(|infer_ok|
{
fcx.register_infer_ok_obligations(infer_ok);
expression_ty
})
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/coercion.rs:1669",
"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(1669u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["result"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&result) as
&dyn Value))])
});
} else { ; }
};
match result {
Ok(v) => {
self.final_ty = Some(v);
if let Some(e) = expression { self.expressions.push(e); }
}
Err(coercion_error) => {
fcx.set_tainted_by_errors(fcx.dcx().span_delayed_bug(cause.span,
"coercion error but no error emitted"));
let (expected, found) =
fcx.resolve_vars_if_possible((expected, found));
let mut err;
let mut unsized_return = false;
match *cause.code() {
ObligationCauseCode::ReturnNoExpression => {
err =
{
fcx.dcx().struct_span_err(cause.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`return;` in a function whose return type is not `()`"))
})).with_code(E0069)
};
if let Some(value) =
fcx.err_ctxt().ty_kind_suggestion(fcx.param_env, found) {
err.span_suggestion_verbose(cause.span.shrink_to_hi(),
"give the `return` a value of the expected type",
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {0}", value))
}), Applicability::HasPlaceholders);
}
err.span_label(cause.span, "return type is not `()`");
}
ObligationCauseCode::BlockTailExpression(blk_id, ..) => {
err =
self.report_return_mismatched_types(cause, expected, found,
coercion_error, fcx, blk_id, expression);
unsized_return = self.is_return_ty_definitely_unsized(fcx);
}
ObligationCauseCode::ReturnValue(return_expr_id) => {
err =
self.report_return_mismatched_types(cause, expected, found,
coercion_error, fcx, return_expr_id, expression);
unsized_return = self.is_return_ty_definitely_unsized(fcx);
}
ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
arm_span,
arm_ty,
prior_arm_ty,
ref prior_non_diverging_arms,
tail_defines_return_position_impl_trait: Some(rpit_def_id),
.. }) => {
err =
fcx.err_ctxt().report_mismatched_types(cause, fcx.param_env,
expected, found, coercion_error);
if prior_non_diverging_arms.len() > 0 {
self.suggest_boxing_tail_for_return_position_impl_trait(fcx,
&mut err, rpit_def_id, arm_ty, prior_arm_ty,
prior_non_diverging_arms.iter().chain(std::iter::once(&arm_span)).copied());
}
}
ObligationCauseCode::IfExpression {
expr_id,
tail_defines_return_position_impl_trait: Some(rpit_def_id) }
=> {
let hir::Node::Expr(hir::Expr {
kind: hir::ExprKind::If(_, then_expr, Some(else_expr)), ..
}) =
fcx.tcx.hir_node(expr_id) else {
::core::panicking::panic("internal error: entered unreachable code");
};
err =
fcx.err_ctxt().report_mismatched_types(cause, fcx.param_env,
expected, found, coercion_error);
let then_span =
fcx.find_block_span_from_hir_id(then_expr.hir_id);
let else_span =
fcx.find_block_span_from_hir_id(else_expr.hir_id);
if then_span != then_expr.span &&
else_span != else_expr.span {
let then_ty =
fcx.typeck_results.borrow().expr_ty(then_expr);
let else_ty =
fcx.typeck_results.borrow().expr_ty(else_expr);
self.suggest_boxing_tail_for_return_position_impl_trait(fcx,
&mut err, rpit_def_id, then_ty, else_ty,
[then_span, else_span].into_iter());
}
}
_ => {
err =
fcx.err_ctxt().report_mismatched_types(cause, fcx.param_env,
expected, found, coercion_error);
}
}
augment_error(&mut err);
if let Some(expr) = expression {
if let hir::ExprKind::Loop(_, _, loop_src @
(hir::LoopSource::While | hir::LoopSource::ForLoop), _) =
expr.kind {
let loop_type =
if loop_src == hir::LoopSource::While {
"`while` loops"
} else { "`for` loops" };
err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} evaluate to unit type `()`",
loop_type))
}));
}
fcx.emit_coerce_suggestions(&mut err, expr, found, expected,
None, Some(coercion_error));
}
let reported = err.emit_unless_delay(unsized_return);
self.final_ty = Some(Ty::new_error(fcx.tcx, reported));
}
}
}
}
}#[instrument(skip(self, fcx, augment_error, label_expression_as_expected), level = "debug")]1579pub(crate) fn coerce_inner<'a>(
1580&mut self,
1581 fcx: &FnCtxt<'a, 'tcx>,
1582 cause: &ObligationCause<'tcx>,
1583 expression: Option<&'tcx hir::Expr<'tcx>>,
1584mut expression_ty: Ty<'tcx>,
1585 augment_error: impl FnOnce(&mut Diag<'_>),
1586 label_expression_as_expected: bool,
1587 ) {
1588// Incorporate whatever type inference information we have
1589 // until now; in principle we might also want to process
1590 // pending obligations, but doing so should only improve
1591 // compatibility (hopefully that is true) by helping us
1592 // uncover never types better.
1593if expression_ty.is_ty_var() {
1594 expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1595 }
15961597// If we see any error types, just propagate that error
1598 // upwards.
1599if let Err(guar) = (expression_ty, self.merged_ty()).error_reported() {
1600self.final_ty = Some(Ty::new_error(fcx.tcx, guar));
1601return;
1602 }
16031604let (expected, found) = if label_expression_as_expected {
1605// In the case where this is a "forced unit", like
1606 // `break`, we want to call the `()` "expected"
1607 // since it is implied by the syntax.
1608 // (Note: not all force-units work this way.)"
1609(expression_ty, self.merged_ty())
1610 } else {
1611// Otherwise, the "expected" type for error
1612 // reporting is the current unification type,
1613 // which is basically the LUB of the expressions
1614 // we've seen so far (combined with the expected
1615 // type)
1616(self.merged_ty(), expression_ty)
1617 };
16181619// Handle the actual type unification etc.
1620let result = if let Some(expression) = expression {
1621if self.expressions.is_empty() {
1622// Special-case the first expression we are coercing.
1623 // To be honest, I'm not entirely sure why we do this.
1624 // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
1625fcx.coerce(
1626 expression,
1627 expression_ty,
1628self.expected_ty,
1629 AllowTwoPhase::No,
1630Some(cause.clone()),
1631 )
1632 } else {
1633 fcx.try_find_coercion_lub(
1634 cause,
1635&self.expressions,
1636self.merged_ty(),
1637 expression,
1638 expression_ty,
1639 )
1640 }
1641 } else {
1642// this is a hack for cases where we default to `()` because
1643 // the expression etc has been omitted from the source. An
1644 // example is an `if let` without an else:
1645 //
1646 // if let Some(x) = ... { }
1647 //
1648 // we wind up with a second match arm that is like `_ =>
1649 // ()`. That is the case we are considering here. We take
1650 // a different path to get the right "expected, found"
1651 // message and so forth (and because we know that
1652 // `expression_ty` will be unit).
1653 //
1654 // Another example is `break` with no argument expression.
1655assert!(expression_ty.is_unit(), "if let hack without unit type");
1656 fcx.at(cause, fcx.param_env)
1657 .eq(
1658// needed for tests/ui/type-alias-impl-trait/issue-65679-inst-opaque-ty-from-val-twice.rs
1659DefineOpaqueTypes::Yes,
1660 expected,
1661 found,
1662 )
1663 .map(|infer_ok| {
1664 fcx.register_infer_ok_obligations(infer_ok);
1665 expression_ty
1666 })
1667 };
16681669debug!(?result);
1670match result {
1671Ok(v) => {
1672self.final_ty = Some(v);
1673if let Some(e) = expression {
1674self.expressions.push(e);
1675 }
1676 }
1677Err(coercion_error) => {
1678// Mark that we've failed to coerce the types here to suppress
1679 // any superfluous errors we might encounter while trying to
1680 // emit or provide suggestions on how to fix the initial error.
1681fcx.set_tainted_by_errors(
1682 fcx.dcx().span_delayed_bug(cause.span, "coercion error but no error emitted"),
1683 );
1684let (expected, found) = fcx.resolve_vars_if_possible((expected, found));
16851686let mut err;
1687let mut unsized_return = false;
1688match *cause.code() {
1689 ObligationCauseCode::ReturnNoExpression => {
1690 err = struct_span_code_err!(
1691 fcx.dcx(),
1692 cause.span,
1693 E0069,
1694"`return;` in a function whose return type is not `()`"
1695);
1696if let Some(value) = fcx.err_ctxt().ty_kind_suggestion(fcx.param_env, found)
1697 {
1698 err.span_suggestion_verbose(
1699 cause.span.shrink_to_hi(),
1700"give the `return` a value of the expected type",
1701format!(" {value}"),
1702 Applicability::HasPlaceholders,
1703 );
1704 }
1705 err.span_label(cause.span, "return type is not `()`");
1706 }
1707 ObligationCauseCode::BlockTailExpression(blk_id, ..) => {
1708 err = self.report_return_mismatched_types(
1709 cause,
1710 expected,
1711 found,
1712 coercion_error,
1713 fcx,
1714 blk_id,
1715 expression,
1716 );
1717 unsized_return = self.is_return_ty_definitely_unsized(fcx);
1718 }
1719 ObligationCauseCode::ReturnValue(return_expr_id) => {
1720 err = self.report_return_mismatched_types(
1721 cause,
1722 expected,
1723 found,
1724 coercion_error,
1725 fcx,
1726 return_expr_id,
1727 expression,
1728 );
1729 unsized_return = self.is_return_ty_definitely_unsized(fcx);
1730 }
1731 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
1732 arm_span,
1733 arm_ty,
1734 prior_arm_ty,
1735ref prior_non_diverging_arms,
1736 tail_defines_return_position_impl_trait: Some(rpit_def_id),
1737 ..
1738 }) => {
1739 err = fcx.err_ctxt().report_mismatched_types(
1740 cause,
1741 fcx.param_env,
1742 expected,
1743 found,
1744 coercion_error,
1745 );
1746// Check that we're actually in the second or later arm
1747if prior_non_diverging_arms.len() > 0 {
1748self.suggest_boxing_tail_for_return_position_impl_trait(
1749 fcx,
1750&mut err,
1751 rpit_def_id,
1752 arm_ty,
1753 prior_arm_ty,
1754 prior_non_diverging_arms
1755 .iter()
1756 .chain(std::iter::once(&arm_span))
1757 .copied(),
1758 );
1759 }
1760 }
1761 ObligationCauseCode::IfExpression {
1762 expr_id,
1763 tail_defines_return_position_impl_trait: Some(rpit_def_id),
1764 } => {
1765let hir::Node::Expr(hir::Expr {
1766 kind: hir::ExprKind::If(_, then_expr, Some(else_expr)),
1767 ..
1768 }) = fcx.tcx.hir_node(expr_id)
1769else {
1770unreachable!();
1771 };
1772 err = fcx.err_ctxt().report_mismatched_types(
1773 cause,
1774 fcx.param_env,
1775 expected,
1776 found,
1777 coercion_error,
1778 );
1779let then_span = fcx.find_block_span_from_hir_id(then_expr.hir_id);
1780let else_span = fcx.find_block_span_from_hir_id(else_expr.hir_id);
1781// Don't suggest wrapping whole block in `Box::new`.
1782if then_span != then_expr.span && else_span != else_expr.span {
1783let then_ty = fcx.typeck_results.borrow().expr_ty(then_expr);
1784let else_ty = fcx.typeck_results.borrow().expr_ty(else_expr);
1785self.suggest_boxing_tail_for_return_position_impl_trait(
1786 fcx,
1787&mut err,
1788 rpit_def_id,
1789 then_ty,
1790 else_ty,
1791 [then_span, else_span].into_iter(),
1792 );
1793 }
1794 }
1795_ => {
1796 err = fcx.err_ctxt().report_mismatched_types(
1797 cause,
1798 fcx.param_env,
1799 expected,
1800 found,
1801 coercion_error,
1802 );
1803 }
1804 }
18051806 augment_error(&mut err);
18071808if let Some(expr) = expression {
1809if let hir::ExprKind::Loop(
1810_,
1811_,
1812 loop_src @ (hir::LoopSource::While | hir::LoopSource::ForLoop),
1813_,
1814 ) = expr.kind
1815 {
1816let loop_type = if loop_src == hir::LoopSource::While {
1817"`while` loops"
1818} else {
1819"`for` loops"
1820};
18211822 err.note(format!("{loop_type} evaluate to unit type `()`"));
1823 }
18241825 fcx.emit_coerce_suggestions(
1826&mut err,
1827 expr,
1828 found,
1829 expected,
1830None,
1831Some(coercion_error),
1832 );
1833 }
18341835let reported = err.emit_unless_delay(unsized_return);
18361837self.final_ty = Some(Ty::new_error(fcx.tcx, reported));
1838 }
1839 }
1840 }
18411842fn suggest_boxing_tail_for_return_position_impl_trait(
1843&self,
1844 fcx: &FnCtxt<'_, 'tcx>,
1845 err: &mut Diag<'_>,
1846 rpit_def_id: LocalDefId,
1847 a_ty: Ty<'tcx>,
1848 b_ty: Ty<'tcx>,
1849 arm_spans: impl Iterator<Item = Span>,
1850 ) {
1851let compatible = |ty: Ty<'tcx>| {
1852fcx.probe(|_| {
1853let ocx = ObligationCtxt::new(fcx);
1854ocx.register_obligations(
1855fcx.tcx.item_self_bounds(rpit_def_id).iter_identity().filter_map(|clause| {
1856let predicate = clause1857 .kind()
1858 .map_bound(|clause| match clause {
1859 ty::ClauseKind::Trait(trait_pred) => Some(ty::ClauseKind::Trait(
1860trait_pred.with_replaced_self_ty(fcx.tcx, ty),
1861 )),
1862 ty::ClauseKind::Projection(proj_pred) => {
1863Some(ty::ClauseKind::Projection(
1864proj_pred.with_replaced_self_ty(fcx.tcx, ty),
1865 ))
1866 }
1867_ => None,
1868 })
1869 .transpose()?;
1870Some(Obligation::new(
1871fcx.tcx,
1872ObligationCause::dummy(),
1873fcx.param_env,
1874predicate,
1875 ))
1876 }),
1877 );
1878ocx.try_evaluate_obligations().is_empty()
1879 })
1880 };
18811882if !compatible(a_ty) || !compatible(b_ty) {
1883return;
1884 }
18851886let rpid_def_span = fcx.tcx.def_span(rpit_def_id);
1887err.subdiagnostic(SuggestBoxingForReturnImplTrait::ChangeReturnType {
1888 start_sp: rpid_def_span.with_hi(rpid_def_span.lo() + BytePos(4)),
1889 end_sp: rpid_def_span.shrink_to_hi(),
1890 });
18911892let (starts, ends) =
1893arm_spans.map(|span| (span.shrink_to_lo(), span.shrink_to_hi())).unzip();
1894err.subdiagnostic(SuggestBoxingForReturnImplTrait::BoxReturnExpr { starts, ends });
1895 }
18961897fn report_return_mismatched_types<'infcx>(
1898&self,
1899 cause: &ObligationCause<'tcx>,
1900 expected: Ty<'tcx>,
1901 found: Ty<'tcx>,
1902 ty_err: TypeError<'tcx>,
1903 fcx: &'infcx FnCtxt<'_, 'tcx>,
1904 block_or_return_id: hir::HirId,
1905 expression: Option<&'tcx hir::Expr<'tcx>>,
1906 ) -> Diag<'infcx> {
1907let mut err =
1908fcx.err_ctxt().report_mismatched_types(cause, fcx.param_env, expected, found, ty_err);
19091910let 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(..));
1911let parent = fcx.tcx.parent_hir_node(block_or_return_id);
1912if let Some(expr) = expression1913 && let hir::Node::Expr(&hir::Expr {
1914 kind: hir::ExprKind::Closure(&hir::Closure { body, .. }),
1915 ..
1916 }) = parent1917 {
1918let needs_block =
1919 !#[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(..));
1920fcx.suggest_missing_semicolon(&mut err, expr, expected, needs_block, true);
1921 }
1922// Verify that this is a tail expression of a function, otherwise the
1923 // label pointing out the cause for the type coercion will be wrong
1924 // as prior return coercions would not be relevant (#57664).
1925if let Some(expr) = expression1926 && due_to_block1927 {
1928fcx.suggest_missing_semicolon(&mut err, expr, expected, false, false);
1929let pointing_at_return_type = fcx.suggest_mismatched_types_on_tail(
1930&mut err,
1931expr,
1932expected,
1933found,
1934block_or_return_id,
1935 );
1936if let Some(cond_expr) = fcx.tcx.hir_get_if_cause(expr.hir_id)
1937 && expected.is_unit()
1938 && !pointing_at_return_type1939// If the block is from an external macro or try (`?`) desugaring, then
1940 // do not suggest adding a semicolon, because there's nowhere to put it.
1941 // See issues #81943 and #87051.
1942 // Similarly, if the block is from a loop desugaring, then also do not
1943 // suggest adding a semicolon. See issue #150850.
1944&& cond_expr.span.desugaring_kind().is_none()
1945 && !cond_expr.span.in_external_macro(fcx.tcx.sess.source_map())
1946 && !#[allow(non_exhaustive_omitted_patterns)] match cond_expr.kind {
hir::ExprKind::Match(.., hir::MatchSource::TryDesugar(_)) => true,
_ => false,
}matches!(
1947 cond_expr.kind,
1948 hir::ExprKind::Match(.., hir::MatchSource::TryDesugar(_))
1949 )1950 {
1951if let ObligationCauseCode::BlockTailExpression(hir_id, hir::MatchSource::Normal) =
1952cause.code()
1953 && let hir::Node::Block(block) = fcx.tcx.hir_node(*hir_id)
1954 && let hir::Node::Expr(expr) = fcx.tcx.parent_hir_node(block.hir_id)
1955 && let hir::Node::Expr(if_expr) = fcx.tcx.parent_hir_node(expr.hir_id)
1956 && let hir::ExprKind::If(_cond, _then, None) = if_expr.kind
1957 {
1958err.span_label(
1959cond_expr.span,
1960"`if` expressions without `else` arms expect their inner expression to be `()`",
1961 );
1962 } else {
1963err.span_label(cond_expr.span, "expected this to be `()`");
1964 }
1965if expr.can_have_side_effects() {
1966fcx.suggest_semicolon_at_end(cond_expr.span, &mut err);
1967 }
1968 }
1969 }
19701971// If this is due to an explicit `return`, suggest adding a return type.
1972if let Some((fn_id, fn_decl)) = fcx.get_fn_decl(block_or_return_id)
1973 && !due_to_block1974 {
1975fcx.suggest_missing_return_type(&mut err, fn_decl, expected, found, fn_id);
1976 }
19771978// If this is due to a block, then maybe we forgot a `return`/`break`.
1979if due_to_block1980 && let Some(expr) = expression1981 && let Some(parent_fn_decl) =
1982fcx.tcx.hir_fn_decl_by_hir_id(fcx.tcx.local_def_id_to_hir_id(fcx.body_id))
1983 {
1984fcx.suggest_missing_break_or_return_expr(
1985&mut err,
1986expr,
1987parent_fn_decl,
1988expected,
1989found,
1990block_or_return_id,
1991fcx.body_id,
1992 );
1993 }
19941995let ret_coercion_span = fcx.ret_coercion_span.get();
19961997if let Some(sp) = ret_coercion_span1998// If the closure has an explicit return type annotation, or if
1999 // the closure's return type has been inferred from outside
2000 // requirements (such as an Fn* trait bound), then a type error
2001 // may occur at the first return expression we see in the closure
2002 // (if it conflicts with the declared return type). Skip adding a
2003 // note in this case, since it would be incorrect.
2004&& let Some(fn_sig) = fcx.body_fn_sig()
2005 && fn_sig.output().is_ty_var()
2006 {
2007err.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"));
2008 }
20092010err2011 }
20122013/// Checks whether the return type is unsized via an obligation, which makes
2014 /// sure we consider `dyn Trait: Sized` where clauses, which are trivially
2015 /// false but technically valid for typeck.
2016fn is_return_ty_definitely_unsized(&self, fcx: &FnCtxt<'_, 'tcx>) -> bool {
2017if let Some(sig) = fcx.body_fn_sig() {
2018 !fcx.predicate_may_hold(&Obligation::new(
2019fcx.tcx,
2020ObligationCause::dummy(),
2021fcx.param_env,
2022 ty::TraitRef::new(
2023fcx.tcx,
2024fcx.tcx.require_lang_item(hir::LangItem::Sized, DUMMY_SP),
2025 [sig.output()],
2026 ),
2027 ))
2028 } else {
2029false
2030}
2031 }
20322033pub(crate) fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> {
2034if let Some(final_ty) = self.final_ty {
2035final_ty2036 } else {
2037// If we only had inputs that were of type `!` (or no
2038 // inputs at all), then the final type is `!`.
2039if !self.expressions.is_empty() {
::core::panicking::panic("assertion failed: self.expressions.is_empty()")
};assert!(self.expressions.is_empty());
2040fcx.tcx.types.never
2041 }
2042 }
2043}
20442045/// Recursively visit goals to decide whether an unsizing is possible.
2046/// `Break`s when it isn't, and an error should be raised.
2047/// `Continue`s when an unsizing ok based on an implementation of the `Unsize` trait / lang item.
2048struct CoerceVisitor<'a, 'tcx> {
2049 fcx: &'a FnCtxt<'a, 'tcx>,
2050 span: Span,
2051/// Whether the coercion is impossible. If so we sometimes still try to
2052 /// coerce in these cases to emit better errors. This changes the behavior
2053 /// when hitting the recursion limit.
2054errored: bool,
2055}
20562057impl<'tcx> ProofTreeVisitor<'tcx> for CoerceVisitor<'_, 'tcx> {
2058type Result = ControlFlow<()>;
20592060fn span(&self) -> Span {
2061self.span
2062 }
20632064fn visit_goal(&mut self, goal: &inspect::InspectGoal<'_, 'tcx>) -> Self::Result {
2065let Some(pred) = goal.goal().predicate.as_trait_clause() else {
2066return ControlFlow::Continue(());
2067 };
20682069// Make sure this predicate is referring to either an `Unsize` or `CoerceUnsized` trait,
2070 // Otherwise there's nothing to do.
2071if !self.fcx.tcx.is_lang_item(pred.def_id(), LangItem::Unsize)
2072 && !self.fcx.tcx.is_lang_item(pred.def_id(), LangItem::CoerceUnsized)
2073 {
2074return ControlFlow::Continue(());
2075 }
20762077match goal.result() {
2078// If we prove the `Unsize` or `CoerceUnsized` goal, continue recursing.
2079Ok(Certainty::Yes) => ControlFlow::Continue(()),
2080Err(NoSolution) => {
2081self.errored = true;
2082// Even if we find no solution, continue recursing if we find a single candidate
2083 // for which we're shallowly certain it holds to get the right error source.
2084if let [only_candidate] = &goal.candidates()[..]
2085 && only_candidate.shallow_certainty() == Certainty::Yes2086 {
2087only_candidate.visit_nested_no_probe(self)
2088 } else {
2089 ControlFlow::Break(())
2090 }
2091 }
2092Ok(Certainty::Maybe { .. }) => {
2093// FIXME: structurally normalize?
2094if self.fcx.tcx.is_lang_item(pred.def_id(), LangItem::Unsize)
2095 && let ty::Dynamic(..) = pred.skip_binder().trait_ref.args.type_at(1).kind()
2096 && let ty::Infer(ty::TyVar(vid)) = *pred.self_ty().skip_binder().kind()
2097 && self.fcx.type_var_is_sized(vid)
2098 {
2099// We get here when trying to unsize a type variable to a `dyn Trait`,
2100 // knowing that that variable is sized. Unsizing definitely has to happen in that case.
2101 // If the variable weren't sized, we may not need an unsizing coercion.
2102 // In general, we don't want to add coercions too eagerly since it makes error messages much worse.
2103ControlFlow::Continue(())
2104 } else if let Some(cand) = goal.unique_applicable_candidate()
2105 && cand.shallow_certainty() == Certainty::Yes2106 {
2107cand.visit_nested_no_probe(self)
2108 } else {
2109 ControlFlow::Break(())
2110 }
2111 }
2112 }
2113 }
21142115fn on_recursion_limit(&mut self) -> Self::Result {
2116if self.errored {
2117// This prevents accidentally committing unfulfilled unsized coercions while trying to
2118 // find the error source for diagnostics.
2119 // See https://github.com/rust-lang/trait-system-refactor-initiative/issues/266.
2120ControlFlow::Break(())
2121 } else {
2122 ControlFlow::Continue(())
2123 }
2124 }
2125}