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_attr_ir::InlineAttr;
41use rustc_attr_ir::lang_items::LangItem;
42use rustc_errors::codes::*;
43use rustc_errors::{Applicability, Diag, struct_span_code_err};
44use rustc_hiras hir;
45use rustc_hir::def_id::{DefId, LocalDefId};
46use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer;
47use rustc_infer::infer::relate::RelateResult;
48use rustc_infer::infer::{DefineOpaqueTypes, InferOk, InferResult, RegionVariableOrigin};
49use rustc_infer::traits::{
50MatchExpressionArmCause, Obligation, PredicateObligation, PredicateObligations, SelectionError,
51};
52use rustc_middle::ty::adjustment::{
53Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, DerefAdjustKind,
54PointerCoercion,
55};
56use rustc_middle::ty::error::TypeError;
57use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt, Unnormalized};
58use rustc_span::{BytePos, DUMMY_SP, Span, span_bug};
59use rustc_trait_selection::infer::InferCtxtExtas _;
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::diagnostics::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 /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:164",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("unify(a: {0:?}, b: {1:?}, use_lub: {2})",
a, b, self.use_lub) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("unify(a: {:?}, b: {:?}, use_lub: {})", a, b, self.use_lub);
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 {
173self.sup_raw(&self.cause, self.param_env, 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().no_errors() {
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 }
240241{}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::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",
"rustc_hir_typeck::coercion", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(241u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a")
}> =
::tracing::__macro_support::FieldName::new("a");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("b")
}> =
::tracing::__macro_support::FieldName::new("b");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[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;
}
{
let a = self.shallow_resolve(a);
let b = self.shallow_resolve(b);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:246",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(246u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Coerce.tys({0:?} => {1:?})",
a, b) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
if a.is_never() {
if self.coerce_never {
return success(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[Adjustment { kind: Adjust::NeverToAny, target: b }])), b,
PredicateObligations::new());
} else { return self.unify(a, b, ForceLeakCheck::No); }
}
if a.is_ty_var() {
return self.coerce_from_inference_variable(a, b);
}
let unsize =
self.commit_if_ok(|_| self.coerce_unsized(a, b));
match unsize {
Ok(_) => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:277",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(277u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce: unsize successful")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
return unsize;
}
Err(error) => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:281",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(281u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message",
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("error")
}> =
::tracing::__macro_support::FieldName::new("error");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce: unsize failed")
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&error)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
}
}
match *b.kind() {
ty::RawPtr(_, b_mutbl) => {
return self.coerce_to_raw_ptr(a, b, b_mutbl);
}
ty::Ref(r_b, _, mutbl_b) => {
if let Some(pin_ref_to_ref) =
self.maybe_pin_ref_to_ref(a, b) {
return self.coerce_pin_ref_to_ref(pin_ref_to_ref);
}
return self.coerce_to_ref(a, b, r_b, mutbl_b);
}
_ if let Some(to_pin_ref) = self.maybe_to_pin_ref(a, b) => {
return self.coerce_to_pin_ref(to_pin_ref);
}
ty::Adt(_, _) if
self.tcx.features().reborrow() &&
self.fcx.infcx.type_implements_trait(self.tcx.lang_items().reborrow().expect("Unexpectedly using core/std without reborrow"),
[b], self.fcx.param_env).must_apply_modulo_regions() => {
let reborrow_coerce =
self.commit_if_ok(|_| self.coerce_reborrow(a, b));
if reborrow_coerce.is_ok() { return reborrow_coerce; }
}
ty::Int(_) | ty::Uint(_) | ty::Float(_) |
ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) => {}
_ => {}
}
match *a.kind() {
ty::FnDef(..) => { self.coerce_from_fn_item(a, b) }
ty::FnPtr(a_sig_tys, a_hdr) => {
self.coerce_from_fn_pointer(a, a_sig_tys.with(a_hdr), b)
}
ty::Closure(..) => { self.coerce_closure_to_fn(a, b) }
ty::Adt(_, _) if self.tcx.features().reborrow() => {
let reborrow_coerce =
self.commit_if_ok(|_| self.coerce_shared_reborrow(a, b));
if reborrow_coerce.is_ok() {
reborrow_coerce
} else { self.unify(a, b, ForceLeakCheck::No) }
}
ty::Int(_) | ty::Uint(_) | ty::Float(_) |
ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) => {
self.unify(a, b, ForceLeakCheck::No)
}
_ => { self.unify(a, b, ForceLeakCheck::No) }
}
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:241",
"rustc_hir_typeck::coercion", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(241u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[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, pin-ergonomics, or
287 // generic reborrow.
288match *b.kind() {
289 ty::RawPtr(_, b_mutbl) => {
290return self.coerce_to_raw_ptr(a, b, b_mutbl);
291 }
292 ty::Ref(r_b, _, mutbl_b) => {
293if let Some(pin_ref_to_ref) = self.maybe_pin_ref_to_ref(a, b) {
294return self.coerce_pin_ref_to_ref(pin_ref_to_ref);
295 }
296return self.coerce_to_ref(a, b, r_b, mutbl_b);
297 }
298_ if let Some(to_pin_ref) = self.maybe_to_pin_ref(a, b) => {
299return self.coerce_to_pin_ref(to_pin_ref);
300 }
301 ty::Adt(_, _)
302if self.tcx.features().reborrow()
303 && self
304.fcx
305 .infcx
306 .type_implements_trait(
307self.tcx
308 .lang_items()
309 .reborrow()
310 .expect("Unexpectedly using core/std without reborrow"),
311 [b],
312self.fcx.param_env,
313 )
314 .must_apply_modulo_regions() =>
315 {
316let reborrow_coerce = self.commit_if_ok(|_| self.coerce_reborrow(a, b));
317if reborrow_coerce.is_ok() {
318return reborrow_coerce;
319 }
320 }
321 ty::Int(_)
322 | ty::Uint(_)
323 | ty::Float(_)
324 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) => {
325// For now, do nothing. If coercions are ever added for ints/floats then the arms
326 // handling these types in `check_expr_lit` will need re-evaluation.
327}
328_ => {}
329 }
330331match *a.kind() {
332 ty::FnDef(..) => {
333// Function items are coercible to any closure
334 // type; function pointers are not (that would
335 // require double indirection).
336 // Additionally, we permit coercion of function
337 // items to drop the unsafe qualifier.
338self.coerce_from_fn_item(a, b)
339 }
340 ty::FnPtr(a_sig_tys, a_hdr) => {
341// We permit coercion of fn pointers to drop the
342 // unsafe qualifier.
343self.coerce_from_fn_pointer(a, a_sig_tys.with(a_hdr), b)
344 }
345 ty::Closure(..) => {
346// Non-capturing closures are coercible to
347 // function pointers or unsafe function pointers.
348 // It cannot convert closures that require unsafe.
349self.coerce_closure_to_fn(a, b)
350 }
351 ty::Adt(_, _) if self.tcx.features().reborrow() => {
352let reborrow_coerce = self.commit_if_ok(|_| self.coerce_shared_reborrow(a, b));
353if reborrow_coerce.is_ok() {
354 reborrow_coerce
355 } else {
356self.unify(a, b, ForceLeakCheck::No)
357 }
358 }
359 ty::Int(_)
360 | ty::Uint(_)
361 | ty::Float(_)
362 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) => {
363// For now, just use unification rules. If coercions are ever added for ints/floats
364 // then the arms handling these types in `check_expr_lit` will need re-evaluation.
365self.unify(a, b, ForceLeakCheck::No)
366 }
367_ => {
368// Otherwise, just use unification rules.
369self.unify(a, b, ForceLeakCheck::No)
370 }
371 }
372 }
373374/// Coercing *from* an inference variable. In this case, we have no information
375 /// about the source type, so we can't really do a true coercion and we always
376 /// fall back to subtyping (`unify_and`).
377fn coerce_from_inference_variable(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
378{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:378",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(378u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_from_inference_variable(a={0:?}, b={1:?})",
a, b) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("coerce_from_inference_variable(a={:?}, b={:?})", a, b);
379if 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);
380if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};debug_assert!(self.shallow_resolve(b) == b);
381382if b.is_ty_var() {
383let mut obligations = PredicateObligations::with_capacity(2);
384let mut push_coerce_obligation = |a, b| {
385obligations.push(Obligation::new(
386self.tcx(),
387self.cause.clone(),
388self.param_env,
389 ty::Binder::dummy(ty::PredicateKind::Coerce(ty::CoercePredicate { a, b })),
390 ));
391 };
392393let target_ty = if self.use_lub {
394// When computing the lub, we create a new target
395 // and coerce both `a` and `b` to it.
396let target_ty = self.next_ty_var(self.cause.span);
397push_coerce_obligation(a, target_ty);
398push_coerce_obligation(b, target_ty);
399target_ty400 } else {
401// When subtyping, we don't need to create a new target
402 // as we only coerce `a` to `b`.
403push_coerce_obligation(a, b);
404b405 };
406407{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:407",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(407u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_from_inference_variable: two inference variables, target_ty={0:?}, obligations={1:?}",
target_ty, obligations) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
408"coerce_from_inference_variable: two inference variables, target_ty={:?}, obligations={:?}",
409 target_ty, obligations
410 );
411success(::alloc::vec::Vec::new()vec![], target_ty, obligations)
412 } else {
413// One unresolved type variable: just apply subtyping, we may be able
414 // to do something useful.
415self.unify(a, b, ForceLeakCheck::No)
416 }
417 }
418419/// Handles coercing some arbitrary type `a` to some reference (`b`). This
420 /// handles a few cases:
421 /// - Introducing reborrows to give more flexible lifetimes
422 /// - Deref coercions to allow `&T` to coerce to `&T::Target`
423 /// - Coercing mutable references to immutable references
424 /// These coercions can be freely intermixed, for example we are able to
425 /// coerce `&mut T` to `&mut T::Target`.
426fn coerce_to_ref(
427&self,
428 a: Ty<'tcx>,
429 b: Ty<'tcx>,
430 r_b: ty::Region<'tcx>,
431 mutbl_b: hir::Mutability,
432 ) -> CoerceResult<'tcx> {
433{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:433",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(433u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_to_ref(a={0:?}, b={1:?})",
a, b) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("coerce_to_ref(a={:?}, b={:?})", a, b);
434if true {
if !(self.shallow_resolve(a) == a) {
::core::panicking::panic("assertion failed: self.shallow_resolve(a) == a")
};
};debug_assert!(self.shallow_resolve(a) == a);
435if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};debug_assert!(self.shallow_resolve(b) == b);
436437let (r_a, mt_a) = match *a.kind() {
438 ty::Ref(r_a, ty, mutbl) => {
439 coerce_mutbls(mutbl, mutbl_b)?;
440 (r_a, ty::TypeAndMut { ty, mutbl })
441 }
442_ => return self.unify(a, b, ForceLeakCheck::No),
443 };
444445// Look at each step in the `Deref` chain and check if
446 // any of the autoref'd `Target` types unify with the
447 // coercion target.
448 //
449 // For example when coercing from `&mut Vec<T>` to `&M [T]` we
450 // have three deref steps:
451 // 1. `&mut Vec<T>`, skip autoref
452 // 2. `Vec<T>`, autoref'd ty: `&M Vec<T>`
453 // - `&M Vec<T>` does not unify with `&M [T]`
454 // 3. `[T]`, autoref'd ty: `&M [T]`
455 // - `&M [T]` does unify with `&M [T]`
456let mut first_error = None;
457let mut r_borrow_var = None;
458let mut autoderef = self.autoderef(self.cause.span, a);
459let found = autoderef.by_ref().find_map(|(deref_ty, autoderefs)| {
460if autoderefs == 0 {
461// Don't autoref the first step as otherwise we'd allow
462 // coercing `&T` to `&&T`.
463return None;
464 }
465466// The logic here really shouldn't exist. We don't care about free
467 // lifetimes during HIR typeck. Unfortunately later parts of this
468 // function rely on structural identity of the autoref'd deref'd ty.
469 //
470 // This means that what region we use here actually impacts whether
471 // we emit a reborrow coercion or not which can affect diagnostics
472 // and capture analysis (which in turn affects borrowck).
473let r = if !self.use_lub {
474r_b475 } else if autoderefs == 1 {
476r_a477 } else {
478if r_borrow_var.is_none() {
479// create var lazily, at most once
480let coercion = RegionVariableOrigin::Coercion(self.cause.span);
481let r = self.next_region_var(coercion);
482r_borrow_var = Some(r);
483 }
484r_borrow_var.unwrap()
485 };
486487let autorefd_deref_ty = Ty::new_ref(self.tcx, r, deref_ty, mutbl_b);
488489// Note that we unify the autoref'd `Target` type with `b` rather than
490 // the `Target` type with the pointee of `b`. This is necessary
491 // to properly account for the differing variances of the pointees
492 // of `&` vs `&mut` references.
493match self.unify_raw(autorefd_deref_ty, b, ForceLeakCheck::No) {
494Ok(ok) => Some(ok),
495Err(err) => {
496if first_error.is_none() {
497first_error = Some(err);
498 }
499None500 }
501 }
502 });
503504// Extract type or return an error. We return the first error
505 // we got, which should be from relating the "base" type
506 // (e.g., in example above, the failure from relating `Vec<T>`
507 // to the target type), since that should be the least
508 // confusing.
509let Some(InferOk { value: coerced_a, mut obligations }) = foundelse {
510if let Some(first_error) = first_error {
511{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:511",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(511u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_to_ref: failed with err = {0:?}",
first_error) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("coerce_to_ref: failed with err = {:?}", first_error);
512return Err(first_error);
513 } else {
514// This may happen in the new trait solver since autoderef requires
515 // the pointee to be structurally normalizable, or else it'll just bail.
516 // So when we have a type like `&<not well formed>`, then we get no
517 // autoderef steps (even though there should be at least one). That means
518 // we get no type mismatches, since the loop above just exits early.
519return Err(TypeError::Mismatch);
520 }
521 };
522523if coerced_a == a && mt_a.mutbl.is_not() && autoderef.step_count() == 1 {
524// As a special case, if we would produce `&'a *x`, that's
525 // a total no-op. We end up with the type `&'a T` just as
526 // we started with. In that case, just skip it altogether.
527 //
528 // Unfortunately, this can actually effect capture analysis
529 // which in turn means this effects borrow checking. This can
530 // also effect diagnostics.
531 // FIXME(BoxyUwU): we should always emit reborrow coercions
532 //
533 // Note that for `&mut`, we DO want to reborrow --
534 // otherwise, this would be a move, which might be an
535 // error. For example `foo(self.x)` where `self` and
536 // `self.x` both have `&mut `type would be a move of
537 // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`,
538 // which is a borrow.
539if !mutbl_b.is_not() {
::core::panicking::panic("assertion failed: mutbl_b.is_not()")
};assert!(mutbl_b.is_not()); // can only coerce &T -> &U
540return success(::alloc::vec::Vec::new()vec![], coerced_a, obligations);
541 }
542543let InferOk { value: mut adjustments, obligations: o } =
544self.adjust_steps_as_infer_ok(&autoderef);
545obligations.extend(o);
546obligations.extend(autoderef.into_obligations());
547548if !#[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!(
549matches!(coerced_a.kind(), ty::Ref(..)),
550"expected a ref type, got {:?}",
551 coerced_a
552 );
553554// Now apply the autoref
555let mutbl = AutoBorrowMutability::new(mutbl_b, self.allow_two_phase);
556adjustments557 .push(Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)), target: coerced_a });
558559{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:559",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(559u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_to_ref: succeeded coerced_a={0:?} adjustments={1:?}",
coerced_a, adjustments) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("coerce_to_ref: succeeded coerced_a={:?} adjustments={:?}", coerced_a, adjustments);
560561success(adjustments, coerced_a, obligations)
562 }
563564/// Performs [unsized coercion] by emulating a fulfillment loop on a
565 /// `CoerceUnsized` goal until all `CoerceUnsized` and `Unsize` goals
566 /// are successfully selected.
567 ///
568 /// [unsized coercion](https://doc.rust-lang.org/reference/type-coercions.html#unsized-coercions)
569{}
#[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("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(569u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("source")
}> =
::tracing::__macro_support::FieldName::new("source");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("target")
}> =
::tracing::__macro_support::FieldName::new("target");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&target)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: CoerceResult<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:571",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(571u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("source")
}> =
::tracing::__macro_support::FieldName::new("source");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("target")
}> =
::tracing::__macro_support::FieldName::new("target");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&target)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
if true {
if !(self.shallow_resolve(source) == source) {
::core::panicking::panic("assertion failed: self.shallow_resolve(source) == source")
};
};
if true {
if !(self.shallow_resolve(target) == target) {
::core::panicking::panic("assertion failed: self.shallow_resolve(target) == target")
};
};
if source.is_ty_var() {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:579",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(579u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: source is a TyVar, bailing out")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
return Err(TypeError::Mismatch);
}
if target.is_ty_var() {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:583",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(583u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: target is a TyVar, bailing out")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
return Err(TypeError::Mismatch);
}
match target.kind() {
ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_)
| ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) | ty::Str |
ty::Array(_, _) | ty::Slice(_) | ty::FnDef(_, _) |
ty::FnPtr(_, _) | ty::Dynamic(_, _) | ty::Closure(_, _) |
ty::CoroutineClosure(_, _) | ty::Coroutine(_, _) |
ty::CoroutineWitness(_, _) | ty::Never | ty::Tuple(_) =>
return Err(TypeError::Mismatch),
_ => {}
}
if let ty::Ref(_, source_pointee, ty::Mutability::Not) =
*source.kind() && source_pointee.is_str() &&
let ty::Ref(_, target_pointee, ty::Mutability::Not) =
*target.kind() && target_pointee.is_str() {
return Err(TypeError::Mismatch);
}
let traits =
(self.tcx.lang_items().unsize_trait(),
self.tcx.lang_items().coerce_unsized_trait());
let (Some(unsize_did), Some(coerce_unsized_did)) =
traits else {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:637",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(637u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("missing Unsize or CoerceUnsized traits")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
return Err(TypeError::Mismatch);
};
let reborrow =
match (source.kind(), target.kind()) {
(&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => {
coerce_mutbls(mutbl_a, mutbl_b)?;
let coercion =
RegionVariableOrigin::Coercion(self.cause.span);
let r_borrow = self.next_region_var(coercion);
let mutbl =
AutoBorrowMutability::new(mutbl_b, AllowTwoPhase::No);
Some((Adjustment {
kind: Adjust::Deref(DerefAdjustKind::Builtin),
target: ty_a,
},
Adjustment {
kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)),
target: Ty::new_ref(self.tcx, r_borrow, ty_a, mutbl_b),
}))
}
(&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(_, mt_b)) => {
coerce_mutbls(mt_a, mt_b)?;
Some((Adjustment {
kind: Adjust::Deref(DerefAdjustKind::Builtin),
target: ty_a,
},
Adjustment {
kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
target: Ty::new_ptr(self.tcx, ty_a, mt_b),
}))
}
_ => None,
};
let coerce_source =
reborrow.as_ref().map_or(source, |(_, r)| r.target);
let coerce_target = self.next_ty_var(self.cause.span);
let mut coercion =
self.unify_and(coerce_target, target,
reborrow.map(|(deref, autoref)|
[deref, autoref]).into_flat_iter(),
Adjust::Pointer(PointerCoercion::Unsize),
ForceLeakCheck::No)?;
let cause =
self.cause(self.cause.span,
ObligationCauseCode::Coercion { source, target });
let pred =
ty::TraitRef::new(self.tcx, coerce_unsized_did,
[coerce_source, coerce_target]);
let obligation =
Obligation::new(self.tcx, cause, self.fcx.param_env, pred);
if self.next_trait_solver() {
coercion.obligations.push(obligation);
if self.infcx.visit_proof_tree(Goal::new(self.tcx,
self.param_env, pred),
&mut CoerceVisitor {
fcx: self.fcx,
span: self.cause.span,
errored: false,
}).is_break() {
return Err(TypeError::Mismatch);
}
} else {
self.coerce_unsized_old_solver(obligation, &mut coercion,
coerce_unsized_did, unsize_did)?;
}
Ok(coercion)
}
}
}#[instrument(skip(self), level = "debug")]570fn coerce_unsized(&self, source: Ty<'tcx>, target: Ty<'tcx>) -> CoerceResult<'tcx> {
571debug!(?source, ?target);
572debug_assert!(self.shallow_resolve(source) == source);
573debug_assert!(self.shallow_resolve(target) == target);
574575// We don't apply any coercions incase either the source or target
576 // aren't sufficiently well known but tend to instead just equate
577 // them both.
578if source.is_ty_var() {
579debug!("coerce_unsized: source is a TyVar, bailing out");
580return Err(TypeError::Mismatch);
581 }
582if target.is_ty_var() {
583debug!("coerce_unsized: target is a TyVar, bailing out");
584return Err(TypeError::Mismatch);
585 }
586587// This is an optimization because coercion is one of the most common
588 // operations that we do in typeck, since it happens at every assignment
589 // and call arg (among other positions).
590 //
591 // These targets are known to never be RHS in `LHS: CoerceUnsized<RHS>`.
592 // That's because these are built-in types for which a core-provided impl
593 // doesn't exist, and for which a user-written impl is invalid.
594 //
595 // This is technically incomplete when users write impossible bounds like
596 // `where T: CoerceUnsized<usize>`, for example, but that trait is unstable
597 // and coercion is allowed to be incomplete. The only case where this matters
598 // is impossible bounds.
599 //
600 // Note that some of these types implement `LHS: Unsize<RHS>`, but they
601 // do not implement *`CoerceUnsized`* which is the root obligation of the
602 // check below.
603match target.kind() {
604 ty::Bool
605 | ty::Char
606 | ty::Int(_)
607 | ty::Uint(_)
608 | ty::Float(_)
609 | ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
610 | ty::Str
611 | ty::Array(_, _)
612 | ty::Slice(_)
613 | ty::FnDef(_, _)
614 | ty::FnPtr(_, _)
615 | ty::Dynamic(_, _)
616 | ty::Closure(_, _)
617 | ty::CoroutineClosure(_, _)
618 | ty::Coroutine(_, _)
619 | ty::CoroutineWitness(_, _)
620 | ty::Never
621 | ty::Tuple(_) => return Err(TypeError::Mismatch),
622_ => {}
623 }
624// `&str: CoerceUnsized<&str>` does not hold but is encountered frequently
625 // so we fast path bail out here
626if let ty::Ref(_, source_pointee, ty::Mutability::Not) = *source.kind()
627 && source_pointee.is_str()
628 && let ty::Ref(_, target_pointee, ty::Mutability::Not) = *target.kind()
629 && target_pointee.is_str()
630 {
631return Err(TypeError::Mismatch);
632 }
633634let traits =
635 (self.tcx.lang_items().unsize_trait(), self.tcx.lang_items().coerce_unsized_trait());
636let (Some(unsize_did), Some(coerce_unsized_did)) = traits else {
637debug!("missing Unsize or CoerceUnsized traits");
638return Err(TypeError::Mismatch);
639 };
640641// Note, we want to avoid unnecessary unsizing. We don't want to coerce to
642 // a DST unless we have to. This currently comes out in the wash since
643 // we can't unify [T] with U. But to properly support DST, we need to allow
644 // that, at which point we will need extra checks on the target here.
645646 // Handle reborrows before selecting `Source: CoerceUnsized<Target>`.
647let reborrow = match (source.kind(), target.kind()) {
648 (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => {
649 coerce_mutbls(mutbl_a, mutbl_b)?;
650651let coercion = RegionVariableOrigin::Coercion(self.cause.span);
652let r_borrow = self.next_region_var(coercion);
653654// We don't allow two-phase borrows here, at least for initial
655 // implementation. If it happens that this coercion is a function argument,
656 // the reborrow in coerce_borrowed_ptr will pick it up.
657let mutbl = AutoBorrowMutability::new(mutbl_b, AllowTwoPhase::No);
658659Some((
660 Adjustment { kind: Adjust::Deref(DerefAdjustKind::Builtin), target: ty_a },
661 Adjustment {
662 kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)),
663 target: Ty::new_ref(self.tcx, r_borrow, ty_a, mutbl_b),
664 },
665 ))
666 }
667 (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(_, mt_b)) => {
668 coerce_mutbls(mt_a, mt_b)?;
669670Some((
671 Adjustment { kind: Adjust::Deref(DerefAdjustKind::Builtin), target: ty_a },
672 Adjustment {
673 kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)),
674 target: Ty::new_ptr(self.tcx, ty_a, mt_b),
675 },
676 ))
677 }
678_ => None,
679 };
680let coerce_source = reborrow.as_ref().map_or(source, |(_, r)| r.target);
681682// Setup either a subtyping or a LUB relationship between
683 // the `CoerceUnsized` target type and the expected type.
684 // We only have the latter, so we use an inference variable
685 // for the former and let type inference do the rest.
686let coerce_target = self.next_ty_var(self.cause.span);
687688let mut coercion = self.unify_and(
689 coerce_target,
690 target,
691 reborrow.map(|(deref, autoref)| [deref, autoref]).into_flat_iter(),
692 Adjust::Pointer(PointerCoercion::Unsize),
693 ForceLeakCheck::No,
694 )?;
695696// Create an obligation for `Source: CoerceUnsized<Target>`.
697let cause = self.cause(self.cause.span, ObligationCauseCode::Coercion { source, target });
698let pred = ty::TraitRef::new(self.tcx, coerce_unsized_did, [coerce_source, coerce_target]);
699let obligation = Obligation::new(self.tcx, cause, self.fcx.param_env, pred);
700701if self.next_trait_solver() {
702 coercion.obligations.push(obligation);
703704if self
705.infcx
706 .visit_proof_tree(
707 Goal::new(self.tcx, self.param_env, pred),
708&mut CoerceVisitor { fcx: self.fcx, span: self.cause.span, errored: false },
709 )
710 .is_break()
711 {
712return Err(TypeError::Mismatch);
713 }
714 } else {
715self.coerce_unsized_old_solver(
716 obligation,
717&mut coercion,
718 coerce_unsized_did,
719 unsize_did,
720 )?;
721 }
722723Ok(coercion)
724 }
725726fn coerce_unsized_old_solver(
727&self,
728 obligation: Obligation<'tcx, ty::Predicate<'tcx>>,
729 coercion: &mut InferOk<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>,
730 coerce_unsized_did: DefId,
731 unsize_did: DefId,
732 ) -> Result<(), TypeError<'tcx>> {
733let mut selcx = traits::SelectionContext::new(self);
734// Use a FIFO queue for this custom fulfillment procedure.
735 //
736 // A Vec (or SmallVec) is not a natural choice for a queue. However,
737 // this code path is hot, and this queue usually has a max length of 1
738 // and almost never more than 3. By using a SmallVec we avoid an
739 // allocation, at the (very small) cost of (occasionally) having to
740 // shift subsequent elements down when removing the front element.
741let 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];
742743// Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid
744 // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where
745 // inference might unify those two inner type variables later.
746let traits = [coerce_unsized_did, unsize_did];
747while !queue.is_empty() {
748let obligation = queue.remove(0);
749let trait_pred = match obligation.predicate.kind().no_bound_vars() {
750Some(ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)))
751if traits.contains(&trait_pred.def_id()) =>
752 {
753self.deeply_resolve_ignoring_regions(trait_pred)
754 }
755_ => {
756 coercion.obligations.push(obligation);
757continue;
758 }
759 };
760{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:760",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized resolve step: {0:?}",
trait_pred) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("coerce_unsized resolve step: {:?}", trait_pred);
761match selcx.select(&obligation.with(selcx.tcx(), trait_pred)) {
762// Uncertain or unimplemented.
763Ok(None) => {
764if trait_pred.def_id() == unsize_did {
765let self_ty = trait_pred.self_ty();
766let unsize_ty = trait_pred.trait_ref.args[1].expect_ty();
767{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:767",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(767u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: ambiguous unsize case for {0:?}",
trait_pred) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_pred);
768match (self_ty.kind(), unsize_ty.kind()) {
769 (&ty::Infer(ty::TyVar(v)), ty::Dynamic(..))
770if self.type_var_is_sized(v) =>
771 {
772{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:772",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(772u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: have sized infer {0:?}",
v) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("coerce_unsized: have sized infer {:?}", v);
773 coercion.obligations.push(obligation);
774// `$0: Unsize<dyn Trait>` where we know that `$0: Sized`, try going
775 // for unsizing.
776}
777_ => {
778// Some other case for `$0: Unsize<Something>`. Note that we
779 // hit this case even if `Something` is a sized type, so just
780 // don't do the coercion.
781{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:781",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(781u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: ambiguous unsize")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("coerce_unsized: ambiguous unsize");
782return Err(TypeError::Mismatch);
783 }
784 }
785 } else {
786{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:786",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(786u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: early return - ambiguous")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("coerce_unsized: early return - ambiguous");
787return Err(TypeError::Mismatch);
788 }
789 }
790Err(SelectionError::Unimplemented) => {
791{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:791",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(791u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_unsized: early return - can\'t prove obligation")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("coerce_unsized: early return - can't prove obligation");
792return Err(TypeError::Mismatch);
793 }
794795Err(SelectionError::TraitDynIncompatible(_)) => {
796// Dyn compatibility errors in coercion will *always* be due to the
797 // fact that the RHS of the coercion is a non-dyn compatible `dyn Trait`
798 // written in source somewhere (otherwise we will never have lowered
799 // the dyn trait from HIR to middle).
800 //
801 // There's no reason to emit yet another dyn compatibility error,
802 // especially since the span will differ slightly and thus not be
803 // deduplicated at all!
804self.fcx.set_tainted_by_errors(
805self.fcx
806 .dcx()
807 .span_delayed_bug(self.cause.span, "dyn compatibility during coercion"),
808 );
809 }
810Err(err) => {
811let guar = self.err_ctxt().report_selection_error(
812 obligation.clone(),
813&obligation,
814&err,
815 );
816self.fcx.set_tainted_by_errors(guar);
817// Treat this like an obligation and follow through
818 // with the unsizing - the lack of a coercion should
819 // be silent, as it causes a type mismatch later.
820}
821Ok(Some(ImplSource::UserDefined(impl_source))) => {
822 queue.extend(impl_source.nested);
823// Certain incoherent `CoerceUnsized` implementations may cause ICEs,
824 // so check the impl's validity. Taint the body so that we don't try
825 // to evaluate these invalid coercions in CTFE. We only need to do this
826 // for local impls, since upstream impls should be valid.
827if impl_source.impl_def_id.is_local()
828 && let Err(guar) =
829self.tcx.ensure_result().coerce_unsized_info(impl_source.impl_def_id)
830 {
831self.fcx.set_tainted_by_errors(guar);
832 }
833 }
834Ok(Some(impl_source)) => queue.extend(impl_source.nested_obligations()),
835 }
836 }
837838Ok(())
839 }
840841/// Create an obligation for `ty: Unpin`, where .
842fn unpin_obligation(
843&self,
844 source: Ty<'tcx>,
845 target: Ty<'tcx>,
846 ty: Ty<'tcx>,
847 ) -> PredicateObligation<'tcx> {
848let pred = ty::TraitRef::new(
849self.tcx,
850self.tcx.require_lang_item(LangItem::Unpin, self.cause.span),
851 [ty],
852 );
853let cause = self.cause(self.cause.span, ObligationCauseCode::Coercion { source, target });
854PredicateObligation::new(self.tcx, cause, self.param_env, pred)
855 }
856857/// Checks if the given types are compatible for coercion from a pinned reference to a normal reference.
858fn maybe_pin_ref_to_ref(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> Option<CoerceMaybePinnedRef<'tcx>> {
859if !self.tcx.features().pin_ergonomics() {
860return None;
861 }
862if let Some((a_ty, a_pin @ ty::Pinnedness::Pinned, a_mut, a_r)) = a.maybe_pinned_ref()
863 && let Some((_, b_pin @ ty::Pinnedness::Not, b_mut, _)) = b.maybe_pinned_ref()
864 {
865return Some(CoerceMaybePinnedRef { a, b, a_ty, a_pin, a_mut, a_r, b_pin, b_mut });
866 }
867{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:867",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(867u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("not fitting pinned ref to ref coercion (`{0:?}` -> `{1:?}`)",
a, b) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("not fitting pinned ref to ref coercion (`{:?}` -> `{:?}`)", a, b);
868None869 }
870871/// Coerces from a pinned reference to a normal reference.
872{}
#[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("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(872u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a")
}> =
::tracing::__macro_support::FieldName::new("a");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("b")
}> =
::tracing::__macro_support::FieldName::new("b");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a_ty")
}> =
::tracing::__macro_support::FieldName::new("a_ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a_pin")
}> =
::tracing::__macro_support::FieldName::new("a_pin");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a_mut")
}> =
::tracing::__macro_support::FieldName::new("a_mut");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a_r")
}> =
::tracing::__macro_support::FieldName::new("a_r");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("b_pin")
}> =
::tracing::__macro_support::FieldName::new("b_pin");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("b_mut")
}> =
::tracing::__macro_support::FieldName::new("b_mut");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_pin)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_mut)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_r)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b_pin)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b_mut)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: CoerceResult<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
if true {
if !(self.shallow_resolve(a) == a) {
::core::panicking::panic("assertion failed: self.shallow_resolve(a) == a")
};
};
if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};
if true {
if !self.tcx.features().pin_ergonomics() {
::core::panicking::panic("assertion failed: self.tcx.features().pin_ergonomics()")
};
};
if true {
{
match (&a_pin, &ty::Pinnedness::Pinned) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};
if true {
{
match (&b_pin, &ty::Pinnedness::Not) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};
coerce_mutbls(a_mut, b_mut)?;
let unpin_obligation = self.unpin_obligation(a, b, a_ty);
let a = Ty::new_ref(self.tcx, a_r, a_ty, b_mut);
let mut coerce =
self.unify_and(a, b,
[Adjustment {
kind: Adjust::Deref(DerefAdjustKind::Pin),
target: a_ty,
}],
Adjust::Borrow(AutoBorrow::Ref(AutoBorrowMutability::new(b_mut,
self.allow_two_phase))), ForceLeakCheck::No)?;
coerce.obligations.push(unpin_obligation);
Ok(coerce)
}
}
}#[instrument(skip(self), level = "trace")]873fn coerce_pin_ref_to_ref(
874&self,
875CoerceMaybePinnedRef { a, b, a_ty, a_pin, a_mut, a_r, b_pin, b_mut }: CoerceMaybePinnedRef<
876'tcx,
877 >,
878 ) -> CoerceResult<'tcx> {
879debug_assert!(self.shallow_resolve(a) == a);
880debug_assert!(self.shallow_resolve(b) == b);
881debug_assert!(self.tcx.features().pin_ergonomics());
882debug_assert_eq!(a_pin, ty::Pinnedness::Pinned);
883debug_assert_eq!(b_pin, ty::Pinnedness::Not);
884885 coerce_mutbls(a_mut, b_mut)?;
886887let unpin_obligation = self.unpin_obligation(a, b, a_ty);
888889let a = Ty::new_ref(self.tcx, a_r, a_ty, b_mut);
890let mut coerce = self.unify_and(
891 a,
892 b,
893 [Adjustment { kind: Adjust::Deref(DerefAdjustKind::Pin), target: a_ty }],
894 Adjust::Borrow(AutoBorrow::Ref(AutoBorrowMutability::new(b_mut, self.allow_two_phase))),
895 ForceLeakCheck::No,
896 )?;
897 coerce.obligations.push(unpin_obligation);
898Ok(coerce)
899 }
900901/// Checks if the given types are compatible for coercion to a pinned reference.
902fn maybe_to_pin_ref(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> Option<CoerceMaybePinnedRef<'tcx>> {
903if !self.tcx.features().pin_ergonomics() {
904return None;
905 }
906if let Some((a_ty, a_pin, a_mut, a_r)) = a.maybe_pinned_ref()
907 && let Some((_, b_pin @ ty::Pinnedness::Pinned, b_mut, _)) = b.maybe_pinned_ref()
908 {
909return Some(CoerceMaybePinnedRef { a, b, a_ty, a_pin, a_mut, a_r, b_pin, b_mut });
910 }
911{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:911",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(911u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("not fitting ref to pinned ref coercion (`{0:?}` -> `{1:?}`)",
a, b) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("not fitting ref to pinned ref coercion (`{:?}` -> `{:?}`)", a, b);
912None913 }
914915/// Applies reborrowing and auto-borrowing that results to `Pin<&T>` or `Pin<&mut T>`:
916 ///
917 /// Currently we only support the following coercions:
918 /// - Reborrowing `Pin<&mut T>` -> `Pin<&mut T>`
919 /// - Reborrowing `Pin<&T>` -> `Pin<&T>`
920 /// - Auto-borrowing `&mut T` -> `Pin<&mut T>` where `T: Unpin`
921 /// - Auto-borrowing `&mut T` -> `Pin<&T>` where `T: Unpin`
922 /// - Auto-borrowing `&T` -> `Pin<&T>` where `T: Unpin`
923 ///
924 /// In the future we might want to support other reborrowing coercions, such as:
925 /// - `Pin<Box<T>>` as `Pin<&T>`
926 /// - `Pin<Box<T>>` as `Pin<&mut T>`
927{}
#[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("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(927u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a")
}> =
::tracing::__macro_support::FieldName::new("a");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("b")
}> =
::tracing::__macro_support::FieldName::new("b");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a_ty")
}> =
::tracing::__macro_support::FieldName::new("a_ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a_pin")
}> =
::tracing::__macro_support::FieldName::new("a_pin");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a_mut")
}> =
::tracing::__macro_support::FieldName::new("a_mut");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a_r")
}> =
::tracing::__macro_support::FieldName::new("a_r");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("b_pin")
}> =
::tracing::__macro_support::FieldName::new("b_pin");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("b_mut")
}> =
::tracing::__macro_support::FieldName::new("b_mut");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_pin)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_mut)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_r)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b_pin)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b_mut)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: CoerceResult<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
if true {
if !(self.shallow_resolve(a) == a) {
::core::panicking::panic("assertion failed: self.shallow_resolve(a) == a")
};
};
if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};
if true {
if !self.tcx.features().pin_ergonomics() {
::core::panicking::panic("assertion failed: self.tcx.features().pin_ergonomics()")
};
};
if true {
{
match (&b_pin, &ty::Pinnedness::Pinned) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};
let (deref, unpin_obligation) =
match a_pin {
ty::Pinnedness::Pinned => (DerefAdjustKind::Pin, None),
ty::Pinnedness::Not => {
(DerefAdjustKind::Builtin,
Some(self.unpin_obligation(a, b, a_ty)))
}
};
coerce_mutbls(a_mut, b_mut)?;
let a = Ty::new_pinned_ref(self.tcx, a_r, a_ty, b_mut);
let mut coerce =
self.unify_and(a, b,
[Adjustment { kind: Adjust::Deref(deref), target: a_ty }],
Adjust::Borrow(AutoBorrow::Pin(b_mut)),
ForceLeakCheck::No)?;
coerce.obligations.extend(unpin_obligation);
Ok(coerce)
}
}
}#[instrument(skip(self), level = "trace")]928fn coerce_to_pin_ref(
929&self,
930CoerceMaybePinnedRef { a, b, a_ty, a_pin, a_mut, a_r, b_pin, b_mut }: CoerceMaybePinnedRef<
931'tcx,
932 >,
933 ) -> CoerceResult<'tcx> {
934debug_assert!(self.shallow_resolve(a) == a);
935debug_assert!(self.shallow_resolve(b) == b);
936debug_assert!(self.tcx.features().pin_ergonomics());
937debug_assert_eq!(b_pin, ty::Pinnedness::Pinned);
938939// We need to deref the reference first before we reborrow it to a pinned reference.
940let (deref, unpin_obligation) = match a_pin {
941// no `Unpin` required when reborrowing a pinned reference to a pinned reference
942ty::Pinnedness::Pinned => (DerefAdjustKind::Pin, None),
943// `Unpin` required when reborrowing a non-pinned reference to a pinned reference
944ty::Pinnedness::Not => {
945 (DerefAdjustKind::Builtin, Some(self.unpin_obligation(a, b, a_ty)))
946 }
947 };
948949 coerce_mutbls(a_mut, b_mut)?;
950951// update a with b's mutability since we'll be coercing mutability
952let a = Ty::new_pinned_ref(self.tcx, a_r, a_ty, b_mut);
953954// To complete the reborrow, we need to make sure we can unify the inner types, and if so we
955 // add the adjustments.
956let mut coerce = self.unify_and(
957 a,
958 b,
959 [Adjustment { kind: Adjust::Deref(deref), target: a_ty }],
960 Adjust::Borrow(AutoBorrow::Pin(b_mut)),
961 ForceLeakCheck::No,
962 )?;
963964 coerce.obligations.extend(unpin_obligation);
965Ok(coerce)
966 }
967968/// Applies generic exclusive reborrowing on type implementing `Reborrow`.
969{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("coerce_reborrow",
"rustc_hir_typeck::coercion", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(969u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a")
}> =
::tracing::__macro_support::FieldName::new("a");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("b")
}> =
::tracing::__macro_support::FieldName::new("b");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: CoerceResult<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
if true {
if !(self.shallow_resolve(a) == a) {
::core::panicking::panic("assertion failed: self.shallow_resolve(a) == a")
};
};
if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};
let (ty::Adt(a_def, _), ty::Adt(b_def, _)) =
(a.kind(),
b.kind()) else { return Err(TypeError::Mismatch); };
if a_def.did() == b_def.did() {
let coerce =
self.unify_and(a, b, [],
Adjust::GenericReborrow(ty::Mutability::Mut),
ForceLeakCheck::No)?;
self.taint_if_reborrow_impls_are_invalid(ty::Mutability::Mut);
Ok(coerce)
} else { Err(TypeError::Mismatch) }
}
}
}#[instrument(skip(self), level = "trace")]970fn coerce_reborrow(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
971debug_assert!(self.shallow_resolve(a) == a);
972debug_assert!(self.shallow_resolve(b) == b);
973974// We need to make sure the two types are compatible for reborrow.
975let (ty::Adt(a_def, _), ty::Adt(b_def, _)) = (a.kind(), b.kind()) else {
976return Err(TypeError::Mismatch);
977 };
978if a_def.did() == b_def.did() {
979// Reborrow is applicable here
980let coerce = self.unify_and(
981 a,
982 b,
983 [],
984 Adjust::GenericReborrow(ty::Mutability::Mut),
985 ForceLeakCheck::No,
986 )?;
987self.taint_if_reborrow_impls_are_invalid(ty::Mutability::Mut);
988Ok(coerce)
989 } else {
990// FIXME: CoerceShared check goes here, error for now
991Err(TypeError::Mismatch)
992 }
993 }
994995/// Applies generic exclusive reborrowing on type implementing `Reborrow`.
996{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("coerce_shared_reborrow",
"rustc_hir_typeck::coercion", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(996u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a")
}> =
::tracing::__macro_support::FieldName::new("a");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("b")
}> =
::tracing::__macro_support::FieldName::new("b");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: CoerceResult<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
if true {
if !(self.shallow_resolve(a) == a) {
::core::panicking::panic("assertion failed: self.shallow_resolve(a) == a")
};
};
if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};
let (ty::Adt(a_def, _), ty::Adt(b_def, _)) =
(a.kind(),
b.kind()) else { return Err(TypeError::Mismatch); };
if a_def.did() == b_def.did() { return Err(TypeError::Mismatch); }
let Some(coerce_shared_trait_did) =
self.tcx.lang_items().coerce_shared() else {
return Err(TypeError::Mismatch);
};
let coerce_shared_trait_ref =
ty::TraitRef::new(self.tcx, coerce_shared_trait_did, [a, b]);
let obligation =
traits::Obligation::new(self.tcx, ObligationCause::dummy(),
self.param_env, ty::Binder::dummy(coerce_shared_trait_ref));
let ocx = ObligationCtxt::new(&self.infcx);
ocx.register_obligation(obligation);
let errs = ocx.evaluate_obligations_error_on_ambiguity();
if errs.no_errors() {
self.taint_if_reborrow_impls_are_invalid(ty::Mutability::Not);
Ok(InferOk {
value: (::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[Adjustment {
kind: Adjust::GenericReborrow(ty::Mutability::Not),
target: b,
}])), b),
obligations: ocx.into_pending_obligations(),
})
} else { Err(TypeError::Mismatch) }
}
}
}#[instrument(skip(self), level = "trace")]997fn coerce_shared_reborrow(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
998debug_assert!(self.shallow_resolve(a) == a);
999debug_assert!(self.shallow_resolve(b) == b);
10001001// We need to make sure the two types are compatible for reborrow.
1002let (ty::Adt(a_def, _), ty::Adt(b_def, _)) = (a.kind(), b.kind()) else {
1003return Err(TypeError::Mismatch);
1004 };
1005if a_def.did() == b_def.did() {
1006// CoerceShared cannot be T -> T.
1007return Err(TypeError::Mismatch);
1008 }
1009let Some(coerce_shared_trait_did) = self.tcx.lang_items().coerce_shared() else {
1010return Err(TypeError::Mismatch);
1011 };
1012let coerce_shared_trait_ref = ty::TraitRef::new(self.tcx, coerce_shared_trait_did, [a, b]);
1013let obligation = traits::Obligation::new(
1014self.tcx,
1015 ObligationCause::dummy(),
1016self.param_env,
1017 ty::Binder::dummy(coerce_shared_trait_ref),
1018 );
1019let ocx = ObligationCtxt::new(&self.infcx);
1020 ocx.register_obligation(obligation);
1021let errs = ocx.evaluate_obligations_error_on_ambiguity();
1022if errs.no_errors() {
1023self.taint_if_reborrow_impls_are_invalid(ty::Mutability::Not);
1024Ok(InferOk {
1025 value: (
1026vec![Adjustment {
1027 kind: Adjust::GenericReborrow(ty::Mutability::Not),
1028 target: b,
1029 }],
1030 b,
1031 ),
1032 obligations: ocx.into_pending_obligations(),
1033 })
1034 } else {
1035Err(TypeError::Mismatch)
1036 }
1037 }
10381039/// Borrowck and const eval lower a generic reborrow by walking the fields of the source and
1040 /// target types, trusting that coherence has validated the `Reborrow` and `CoerceShared` impls
1041 /// that permit it. If coherence rejected any of those impls, that walk can hit shapes it does
1042 /// not expect, so we taint the body to keep it away from them.
1043fn taint_if_reborrow_impls_are_invalid(&self, mutability: ty::Mutability) {
1044let lang_items = self.tcx.lang_items();
1045let trait_def_ids = match mutability {
1046 ty::Mutability::Mut => [lang_items.reborrow(), None],
1047// A shared reborrow also reborrows any fields of the source that implement `Reborrow`.
1048ty::Mutability::Not => [lang_items.coerce_shared(), lang_items.reborrow()],
1049 };
1050for trait_def_id in trait_def_ids.into_iter().flatten() {
1051if let Err(guar) = self.tcx.ensure_result().coherent_trait(trait_def_id) {
1052self.set_tainted_by_errors(guar);
1053 }
1054 }
1055 }
10561057fn coerce_from_fn_pointer(
1058&self,
1059 a: Ty<'tcx>,
1060 a_sig: ty::PolyFnSig<'tcx>,
1061 b: Ty<'tcx>,
1062 ) -> CoerceResult<'tcx> {
1063{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:1063",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(1063u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message",
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("a_sig")
}> =
::tracing::__macro_support::FieldName::new("a_sig");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("b")
}> =
::tracing::__macro_support::FieldName::new("b");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_from_fn_pointer")
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a_sig)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&b)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?a_sig, ?b, "coerce_from_fn_pointer");
1064if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};debug_assert!(self.shallow_resolve(b) == b);
10651066match b.kind() {
1067 ty::FnPtr(_, b_hdr) if a_sig.safety().is_safe() && b_hdr.safety().is_unsafe() => {
1068let a = self.tcx.safe_to_unsafe_fn_ty(a_sig);
1069let adjust = Adjust::Pointer(PointerCoercion::UnsafeFnPointer);
1070self.unify_and(a, b, [], adjust, ForceLeakCheck::Yes)
1071 }
1072_ => self.unify(a, b, ForceLeakCheck::Yes),
1073 }
1074 }
10751076fn coerce_from_fn_item(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
1077{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:1077",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(1077u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_from_fn_item(a={0:?}, b={1:?})",
a, b) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b);
1078if true {
if !(self.shallow_resolve(a) == a) {
::core::panicking::panic("assertion failed: self.shallow_resolve(a) == a")
};
};debug_assert!(self.shallow_resolve(a) == a);
1079if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};debug_assert!(self.shallow_resolve(b) == b);
10801081match b.kind() {
1082 ty::FnPtr(_, b_hdr) => {
1083let a_sig = self.sig_for_fn_def_coercion(a, Some(b_hdr.safety()))?;
10841085let InferOk { value: a_sig, mut obligations } =
1086self.at(&self.cause, self.param_env).normalize(Unnormalized::new_wip(a_sig));
1087let a = Ty::new_fn_ptr(self.tcx, a_sig);
10881089let adjust = Adjust::Pointer(PointerCoercion::ReifyFnPointer(b_hdr.safety()));
1090let InferOk { value, obligations: o2 } =
1091self.unify_and(a, b, [], adjust, ForceLeakCheck::Yes)?;
10921093obligations.extend(o2);
1094Ok(InferOk { value, obligations })
1095 }
1096_ => self.unify(a, b, ForceLeakCheck::No),
1097 }
1098 }
10991100/// Attempts to coerce from a closure to a function pointer. Fails
1101 /// if the closure has any upvars.
1102fn coerce_closure_to_fn(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> {
1103if true {
if !(self.shallow_resolve(a) == a) {
::core::panicking::panic("assertion failed: self.shallow_resolve(a) == a")
};
};debug_assert!(self.shallow_resolve(a) == a);
1104if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};debug_assert!(self.shallow_resolve(b) == b);
11051106match b.kind() {
1107 ty::FnPtr(_, hdr) => {
1108let safety = hdr.safety();
1109let terr = TypeError::Sorts(ty::error::ExpectedFound::new(a, b));
1110let closure_sig = self.sig_for_closure_coercion(a, Some(hdr.safety()), terr)?;
1111let pointer_ty = Ty::new_fn_ptr(self.tcx, closure_sig);
1112{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:1112",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(1112u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_closure_to_fn(a={0:?}, b={1:?}, pty={2:?})",
a, b, pointer_ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})", a, b, pointer_ty);
11131114let adjust = Adjust::Pointer(PointerCoercion::ClosureFnPointer(safety));
1115self.unify_and(pointer_ty, b, [], adjust, ForceLeakCheck::No)
1116 }
1117_ => self.unify(a, b, ForceLeakCheck::No),
1118 }
1119 }
11201121fn coerce_to_raw_ptr(
1122&self,
1123 a: Ty<'tcx>,
1124 b: Ty<'tcx>,
1125 mutbl_b: hir::Mutability,
1126 ) -> CoerceResult<'tcx> {
1127{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:1127",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(1127u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coerce_to_raw_ptr(a={0:?}, b={1:?})",
a, b) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("coerce_to_raw_ptr(a={:?}, b={:?})", a, b);
1128if true {
if !(self.shallow_resolve(a) == a) {
::core::panicking::panic("assertion failed: self.shallow_resolve(a) == a")
};
};debug_assert!(self.shallow_resolve(a) == a);
1129if true {
if !(self.shallow_resolve(b) == b) {
::core::panicking::panic("assertion failed: self.shallow_resolve(b) == b")
};
};debug_assert!(self.shallow_resolve(b) == b);
11301131let (is_ref, mt_a) = match *a.kind() {
1132 ty::Ref(_, ty, mutbl) => (true, ty::TypeAndMut { ty, mutbl }),
1133 ty::RawPtr(ty, mutbl) => (false, ty::TypeAndMut { ty, mutbl }),
1134_ => return self.unify(a, b, ForceLeakCheck::No),
1135 };
1136 coerce_mutbls(mt_a.mutbl, mutbl_b)?;
11371138// Check that the types which they point at are compatible.
1139let a_raw = Ty::new_ptr(self.tcx, mt_a.ty, mutbl_b);
1140// Although references and raw ptrs have the same
1141 // representation, we still register an Adjust::DerefRef so that
1142 // regionck knows that the region for `a` must be valid here.
1143if is_ref {
1144self.unify_and(
1145a_raw,
1146b,
1147 [Adjustment { kind: Adjust::Deref(DerefAdjustKind::Builtin), target: mt_a.ty }],
1148 Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)),
1149 ForceLeakCheck::No,
1150 )
1151 } else if mt_a.mutbl != mutbl_b {
1152self.unify_and(
1153a_raw,
1154b,
1155 [],
1156 Adjust::Pointer(PointerCoercion::MutToConstPointer),
1157 ForceLeakCheck::No,
1158 )
1159 } else {
1160self.unify(a_raw, b, ForceLeakCheck::No)
1161 }
1162 }
1163}
11641165impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
1166/// Attempt to coerce an expression to a type, and return the
1167 /// adjusted type of the expression, if successful.
1168 /// Adjustments are only recorded if the coercion succeeded.
1169 /// The expressions *must not* have any preexisting adjustments.
1170pub(crate) fn coerce(
1171&self,
1172 expr: &'tcx hir::Expr<'tcx>,
1173 expr_ty: Ty<'tcx>,
1174 target: Ty<'tcx>,
1175 allow_two_phase: AllowTwoPhase,
1176 cause: Option<ObligationCause<'tcx>>,
1177 ) -> RelateResult<'tcx, Ty<'tcx>> {
1178let source = self.deeply_resolve_ignoring_regions_with_obligations(expr_ty);
1179{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:1179",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(1179u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coercion::try({0:?}: {1:?} -> {2:?})",
expr, source, target) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target);
11801181let cause =
1182cause.unwrap_or_else(|| self.cause(expr.span, ObligationCauseCode::ExprAssignable));
1183let coerce = Coerce::new(
1184self,
1185cause,
1186allow_two_phase,
1187self.tcx.expr_guaranteed_to_constitute_read_for_never(expr),
1188 );
1189let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?;
11901191let (adjustments, _) = self.register_infer_ok_obligations(ok);
1192self.apply_adjustments(expr, adjustments);
1193Ok(if let Err(guar) = expr_ty.error_reported() {
1194Ty::new_error(self.tcx, guar)
1195 } else {
1196target1197 })
1198 }
11991200/// Probe whether `expr_ty` can be coerced to `target_ty`. This has no side-effects,
1201 /// and may return false positives if types are not yet fully constrained by inference.
1202 ///
1203 /// Returns false if the coercion is not possible, or if the coercion creates any
1204 /// sub-obligations that result in errors.
1205 ///
1206 /// This should only be used for diagnostics.
1207pub(crate) fn may_coerce(&self, expr_ty: Ty<'tcx>, target_ty: Ty<'tcx>) -> bool {
1208let cause = self.cause(DUMMY_SP, ObligationCauseCode::ExprAssignable);
1209// We don't ever need two-phase here since we throw out the result of the coercion.
1210 // We also just always set `coerce_never` to true, since this is a heuristic.
1211let coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No, true);
1212self.probe(|_| {
1213// Make sure to structurally resolve the types, since we use
1214 // the `TyKind`s heavily in coercion.
1215let ocx = ObligationCtxt::new(self);
1216let Ok(ok) = coerce.coerce(expr_ty, target_ty) else {
1217return false;
1218 };
1219ocx.register_obligations(ok.obligations);
1220ocx.try_evaluate_obligations().no_errors()
1221 })
1222 }
12231224/// Like [`Self::may_coerce`], but for suggestions whose replacement must complete with a
1225 /// value of the target type. A coercion from `!` to another type does not provide such a
1226 /// value, so it should not by itself justify these suggestions.
1227 ///
1228 /// This should only be used for suggestions.
1229pub(crate) fn may_coerce_except_never(&self, expr_ty: Ty<'tcx>, target_ty: Ty<'tcx>) -> bool {
1230if expr_ty.is_never() && !target_ty.is_never() {
1231return false;
1232 }
1233self.may_coerce(expr_ty, target_ty)
1234 }
12351236/// Given a type and a target type, this function will calculate and return
1237 /// how many dereference steps needed to coerce `expr_ty` to `target`. If
1238 /// it's not possible, return `None`.
1239pub(crate) fn deref_steps_for_suggestion(
1240&self,
1241 expr_ty: Ty<'tcx>,
1242 target: Ty<'tcx>,
1243 ) -> Option<usize> {
1244let cause = self.cause(DUMMY_SP, ObligationCauseCode::ExprAssignable);
1245// We don't ever need two-phase here since we throw out the result of the coercion.
1246let coerce = Coerce::new(self, cause, AllowTwoPhase::No, true);
1247coerce.autoderef(DUMMY_SP, expr_ty).find_map(|(ty, steps)| {
1248self.probe(|_| coerce.unify_raw(ty, target, ForceLeakCheck::No)).ok().map(|_| steps)
1249 })
1250 }
12511252/// Given a type, this function will calculate and return the type given
1253 /// for `<Ty as Deref>::Target` only if `Ty` also implements `DerefMut`.
1254 ///
1255 /// This function is for diagnostics only, since it does not register
1256 /// trait or region sub-obligations. (presumably we could, but it's not
1257 /// particularly important for diagnostics...)
1258pub(crate) fn deref_once_mutably_for_diagnostic(&self, expr_ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
1259self.autoderef(DUMMY_SP, expr_ty).silence_errors().nth(1).and_then(|(deref_ty, _)| {
1260self.infcx
1261 .type_implements_trait(
1262self.tcx.lang_items().deref_mut_trait()?,
1263 [expr_ty],
1264self.param_env,
1265 )
1266 .may_apply()
1267 .then_some(deref_ty)
1268 })
1269 }
12701271{}
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("sig_for_coerce_lub",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(1271u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ty")
}> =
::tracing::__macro_support::FieldName::new("ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("closure_upvars_terr")
}> =
::tracing::__macro_support::FieldName::new("closure_upvars_terr");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&closure_upvars_terr)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[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:
Result<ty::PolyFnSig<'tcx>, TypeError<'tcx>> = loop {};
return __tracing_attr_fake_return;
}
{
match ty.kind() {
ty::FnDef(..) => self.sig_for_fn_def_coercion(ty, None),
ty::Closure(..) =>
self.sig_for_closure_coercion(ty, None,
closure_upvars_terr),
_ => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("`sig_for_fn_def_closure_coerce_lub` called with wrong ty: {0:?}",
ty)));
}
}
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:1271",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(1271u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(level = "debug", skip(self), ret)]1272fn sig_for_coerce_lub(
1273&self,
1274 ty: Ty<'tcx>,
1275 closure_upvars_terr: TypeError<'tcx>,
1276 ) -> Result<ty::PolyFnSig<'tcx>, TypeError<'tcx>> {
1277match ty.kind() {
1278 ty::FnDef(..) => self.sig_for_fn_def_coercion(ty, None),
1279 ty::Closure(..) => self.sig_for_closure_coercion(ty, None, closure_upvars_terr),
1280_ => unreachable!("`sig_for_fn_def_closure_coerce_lub` called with wrong ty: {:?}", ty),
1281 }
1282 }
12831284fn sig_for_fn_def_coercion(
1285&self,
1286 fndef: Ty<'tcx>,
1287 expected_safety: Option<hir::Safety>,
1288 ) -> Result<ty::PolyFnSig<'tcx>, TypeError<'tcx>> {
1289let tcx = self.tcx;
12901291let &ty::FnDef(def_id, _) = fndef.kind() else {
1292{
::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);
1293 };
12941295// Intrinsics are not coercible to function pointers
1296if tcx.intrinsic(def_id).is_some() {
1297return Err(TypeError::IntrinsicCast);
1298 }
12991300let fn_attrs = tcx.codegen_fn_attrs(def_id);
1301if #[allow(non_exhaustive_omitted_patterns)] match fn_attrs.inline {
InlineAttr::Force { .. } => true,
_ => false,
}matches!(fn_attrs.inline, InlineAttr::Force { .. }) {
1302return Err(TypeError::ForceInlineCast);
1303 }
13041305let sig = fndef.fn_sig(tcx);
1306let sig = if fn_attrs.safe_target_features {
1307// Allow the coercion if the current function has all the features that would be
1308 // needed to call the coercee safely.
1309match tcx.adjust_target_feature_sig(def_id, sig, self.body_def_id.into()) {
1310Some(adjusted_sig) => adjusted_sig,
1311Noneif #[allow(non_exhaustive_omitted_patterns)] match expected_safety {
Some(hir::Safety::Safe) => true,
_ => false,
}matches!(expected_safety, Some(hir::Safety::Safe)) => {
1312return Err(TypeError::TargetFeatureCast(def_id));
1313 }
1314None => sig,
1315 }
1316 } else {
1317sig1318 };
13191320if 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)) {
1321Ok(tcx.safe_to_unsafe_sig(sig))
1322 } else {
1323Ok(sig)
1324 }
1325 }
13261327fn sig_for_closure_coercion(
1328&self,
1329 closure: Ty<'tcx>,
1330 expected_safety: Option<hir::Safety>,
1331 closure_upvars_terr: TypeError<'tcx>,
1332 ) -> Result<ty::PolyFnSig<'tcx>, TypeError<'tcx>> {
1333let tcx = self.tcx;
13341335let ty::Closure(closure_def, closure_args) = closure.kind() else {
1336{
::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);
1337 };
13381339// At this point we haven't done capture analysis, which means
1340 // that the ClosureArgs just contains an inference variable instead
1341 // of tuple of captured types.
1342 //
1343 // All we care here is if any variable is being captured and not the exact paths,
1344 // so we check `upvars_mentioned` for root variables being captured.
1345if !tcx.upvars_mentioned(closure_def.expect_local()).is_none_or(|u| u.is_empty()) {
1346return Err(closure_upvars_terr);
1347 }
13481349// We coerce the closure, which has fn type
1350 // `extern "rust-call" fn((arg0,arg1,...)) -> _`
1351 // to
1352 // `fn(arg0,arg1,...) -> _`
1353 // or
1354 // `unsafe fn(arg0,arg1,...) -> _`
1355let closure_sig = closure_args.as_closure().sig();
1356Ok(tcx.signature_unclosure(closure_sig, expected_safety.unwrap_or(hir::Safety::Safe)))
1357 }
13581359/// Given some expressions, their known unified type and another expression,
1360 /// tries to unify the types, potentially inserting coercions on any of the
1361 /// provided expressions and returns their LUB (aka "common supertype").
1362 ///
1363 /// This is really an internal helper. From outside the coercion
1364 /// module, you should instantiate a `CoerceMany` instance.
1365fn try_find_coercion_lub(
1366&self,
1367 cause: &ObligationCause<'tcx>,
1368 exprs: &[&'tcx hir::Expr<'tcx>],
1369 prev_ty: Ty<'tcx>,
1370 new: &hir::Expr<'_>,
1371 new_ty: Ty<'tcx>,
1372 ) -> RelateResult<'tcx, Ty<'tcx>> {
1373let prev_ty = self.deeply_resolve_ignoring_regions_with_obligations(prev_ty);
1374let new_ty = self.deeply_resolve_ignoring_regions_with_obligations(new_ty);
1375{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:1375",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(1375u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coercion::try_find_coercion_lub({0:?}, {1:?}, exprs={2:?} exprs)",
prev_ty, new_ty, exprs.len()) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
1376"coercion::try_find_coercion_lub({:?}, {:?}, exprs={:?} exprs)",
1377 prev_ty,
1378 new_ty,
1379 exprs.len()
1380 );
13811382// Fast Path: don't go through the coercion logic if we're coercing
1383 // a type to itself. This is unfortunately quite perf relevant so
1384 // we do it even though it may mask bugs in the coercion logic.
1385if prev_ty == new_ty {
1386return Ok(prev_ty);
1387 }
13881389let terr = TypeError::Sorts(ty::error::ExpectedFound::new(prev_ty, new_ty));
1390let opt_sigs = match (prev_ty.kind(), new_ty.kind()) {
1391// Don't coerce pairs of fndefs or pairs of closures to fn ptrs
1392 // if they can just be lubbed.
1393 //
1394 // See #88097 or `lub_closures_before_fnptr_coercion.rs` for where
1395 // we would erroneously coerce closures to fnptrs when attempting to
1396 // coerce a closure to itself.
1397(ty::FnDef(..), ty::FnDef(..)) | (ty::Closure(..), ty::Closure(..)) => {
1398let lubbed_ty = self.commit_if_ok(|snapshot| {
1399let outer_universe = self.infcx.universe();
14001401// We need to eagerly handle nested obligations due to lazy norm.
1402let result = if self.next_trait_solver() {
1403let ocx = ObligationCtxt::new(self);
1404let value = ocx.lub(cause, self.param_env, prev_ty, new_ty)?;
1405if ocx.try_evaluate_obligations().no_errors() {
1406Ok(InferOk { value, obligations: ocx.into_pending_obligations() })
1407 } else {
1408Err(TypeError::Mismatch)
1409 }
1410 } else {
1411self.at(cause, self.param_env).lub(prev_ty, new_ty)
1412 };
14131414self.leak_check(outer_universe, Some(snapshot))?;
1415result1416 });
14171418match lubbed_ty {
1419Ok(ok) => return Ok(self.register_infer_ok_obligations(ok)),
1420Err(_) => {
1421let a_sig = self.sig_for_coerce_lub(prev_ty, terr)?;
1422let b_sig = self.sig_for_coerce_lub(new_ty, terr)?;
1423Some((a_sig, b_sig))
1424 }
1425 }
1426 }
14271428 (ty::Closure(..), ty::FnDef(..)) | (ty::FnDef(..), ty::Closure(..)) => {
1429let a_sig = self.sig_for_coerce_lub(prev_ty, terr)?;
1430let b_sig = self.sig_for_coerce_lub(new_ty, terr)?;
1431Some((a_sig, b_sig))
1432 }
1433// ty::FnPtr x ty::FnPtr is fine to just be handled through a normal `unify`
1434 // call using `lub` which is what will happen on the normal path.
1435(ty::FnPtr(..), ty::FnPtr(..)) => None,
1436_ => None,
1437 };
14381439if let Some((mut a_sig, mut b_sig)) = opt_sigs {
1440// Allow coercing safe sigs to unsafe sigs
1441if a_sig.safety().is_safe() && b_sig.safety().is_unsafe() {
1442a_sig = self.tcx.safe_to_unsafe_sig(a_sig);
1443 } else if b_sig.safety().is_safe() && a_sig.safety().is_unsafe() {
1444b_sig = self.tcx.safe_to_unsafe_sig(b_sig);
1445 };
14461447// The signature must match.
1448let (a_sig, b_sig) = self.normalize(new.span, Unnormalized::new_wip((a_sig, b_sig)));
1449let sig = self
1450.at(cause, self.param_env)
1451 .lub(a_sig, b_sig)
1452 .map(|ok| self.register_infer_ok_obligations(ok))?;
14531454// Reify both sides and return the reified fn pointer type.
1455let fn_ptr = Ty::new_fn_ptr(self.tcx, sig);
1456let prev_adjustment = match prev_ty.kind() {
1457 ty::Closure(..) => Adjust::Pointer(PointerCoercion::ClosureFnPointer(sig.safety())),
1458 ty::FnDef(..) => Adjust::Pointer(PointerCoercion::ReifyFnPointer(sig.safety())),
1459_ => ::rustc_span::macros::bug_impl(Some(cause.span),
format_args!("should not try to coerce a {0} to a fn pointer", prev_ty),
Location::caller())span_bug!(cause.span, "should not try to coerce a {prev_ty} to a fn pointer"),
1460 };
1461let next_adjustment = match new_ty.kind() {
1462 ty::Closure(..) => Adjust::Pointer(PointerCoercion::ClosureFnPointer(sig.safety())),
1463 ty::FnDef(..) => Adjust::Pointer(PointerCoercion::ReifyFnPointer(sig.safety())),
1464_ => ::rustc_span::macros::bug_impl(Some(new.span),
format_args!("should not try to coerce a {0} to a fn pointer", new_ty),
Location::caller())span_bug!(new.span, "should not try to coerce a {new_ty} to a fn pointer"),
1465 };
1466for expr in exprs.iter() {
1467self.apply_adjustments(
1468 expr,
1469::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 }],
1470 );
1471 }
1472self.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 }]);
1473return Ok(fn_ptr);
1474 }
14751476// Configure a Coerce instance to compute the LUB.
1477 // We don't allow two-phase borrows on any autorefs this creates since we
1478 // probably aren't processing function arguments here and even if we were,
1479 // they're going to get autorefed again anyway and we can apply 2-phase borrows
1480 // at that time.
1481 //
1482 // NOTE: we set `coerce_never` to `true` here because coercion LUBs only
1483 // operate on values and not places, so a never coercion is valid.
1484let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No, true);
1485coerce.use_lub = true;
14861487// First try to coerce the new expression to the type of the previous ones,
1488 // but only if the new expression has no coercion already applied to it.
1489let mut first_error = None;
1490if !self.typeck_results.borrow().adjustments().contains_key(new.hir_id) {
1491let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty));
1492match result {
1493Ok(ok) => {
1494let (adjustments, target) = self.register_infer_ok_obligations(ok);
1495self.apply_adjustments(new, adjustments);
1496{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:1496",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(1496u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coercion::try_find_coercion_lub: was able to coerce from new type {0:?} to previous type {1:?} ({2:?})",
new_ty, prev_ty, target) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
1497"coercion::try_find_coercion_lub: was able to coerce from new type {:?} to previous type {:?} ({:?})",
1498 new_ty, prev_ty, target
1499 );
1500return Ok(target);
1501 }
1502Err(e) => first_error = Some(e),
1503 }
1504 }
15051506let ok = self
1507.commit_if_ok(|_| coerce.coerce(prev_ty, new_ty))
1508// Avoid giving strange errors on failed attempts.
1509.map_err(|e| first_error.unwrap_or(e))?;
15101511let (adjustments, target) = self.register_infer_ok_obligations(ok);
1512for expr in exprs {
1513self.apply_adjustments(expr, adjustments.clone());
1514 }
1515{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:1515",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(1515u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("coercion::try_find_coercion_lub: was able to coerce previous type {0:?} to new type {1:?} ({2:?})",
prev_ty, new_ty, target) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
1516"coercion::try_find_coercion_lub: was able to coerce previous type {:?} to new type {:?} ({:?})",
1517 prev_ty, new_ty, target
1518 );
1519Ok(target)
1520 }
1521}
15221523/// Check whether `ty` can be coerced to `output_ty`.
1524/// Used from clippy.
1525pub fn can_coerce<'tcx>(
1526 tcx: TyCtxt<'tcx>,
1527 param_env: ty::ParamEnv<'tcx>,
1528 body_def_id: LocalDefId,
1529 ty: Ty<'tcx>,
1530 output_ty: Ty<'tcx>,
1531) -> bool {
1532let root_ctxt = crate::typeck_root_ctxt::TypeckRootCtxt::new(tcx, body_def_id);
1533let fn_ctxt = FnCtxt::new(&root_ctxt, param_env, body_def_id);
1534fn_ctxt.may_coerce(ty, output_ty)
1535}
15361537/// CoerceMany encapsulates the pattern you should use when you have
1538/// many expressions that are all getting coerced to a common
1539/// type. This arises, for example, when you have a match (the result
1540/// of each arm is coerced to a common type). It also arises in less
1541/// obvious places, such as when you have many `break foo` expressions
1542/// that target the same loop, or the various `return` expressions in
1543/// a function.
1544///
1545/// The basic protocol is as follows:
1546///
1547/// - Instantiate the `CoerceMany` with an initial `expected_ty`.
1548/// This will also serve as the "starting LUB". The expectation is
1549/// that this type is something which all of the expressions *must*
1550/// be coercible to. Use a fresh type variable if needed.
1551/// - For each expression whose result is to be coerced, invoke `coerce()` with.
1552/// - In some cases we wish to coerce "non-expressions" whose types are implicitly
1553/// unit. This happens for example if you have a `break` with no expression,
1554/// or an `if` with no `else`. In that case, invoke `coerce_forced_unit()`.
1555/// - `coerce()` and `coerce_forced_unit()` may report errors. They hide this
1556/// from you so that you don't have to worry your pretty head about it.
1557/// But if an error is reported, the final type will be `err`.
1558/// - Invoking `coerce()` may cause us to go and adjust the "adjustments" on
1559/// previously coerced expressions.
1560/// - When all done, invoke `complete()`. This will return the LUB of
1561/// all your expressions.
1562/// - WARNING: I don't believe this final type is guaranteed to be
1563/// related to your initial `expected_ty` in any particular way,
1564/// although it will typically be a subtype, so you should check it.
1565/// Check the note below for more details.
1566/// - Invoking `complete()` may cause us to go and adjust the "adjustments" on
1567/// previously coerced expressions.
1568///
1569/// Example:
1570///
1571/// ```ignore (illustrative)
1572/// let mut coerce = CoerceMany::new(expected_ty);
1573/// for expr in exprs {
1574/// let expr_ty = fcx.check_expr_with_expectation(expr, expected);
1575/// coerce.coerce(fcx, &cause, expr, expr_ty);
1576/// }
1577/// let final_ty = coerce.complete(fcx);
1578/// ```
1579///
1580/// NOTE: Why does the `expected_ty` participate in the LUB?
1581/// When coercing, each branch should use the following expectations for type inference:
1582/// - The branch can be coerced to the expected type of the match/if/whatever.
1583/// - The branch can be coercion lub'd with the types of the previous branches.
1584/// Ideally we'd have some sort of `Expectation::ParticipatesInCoerceLub(ongoing_lub_ty, final_ty)`,
1585/// but adding and using this feels very challenging.
1586/// What we instead do is to use the expected type of the match/if/whatever as
1587/// the initial coercion lub. This allows us to use the lub of "expected type of match" with
1588/// "types from previous branches" as the coercion target, which can contains both expectations.
1589///
1590/// Two concerns with this approach:
1591/// - We may have incompatible `final_ty` if that lub is different from the expected
1592/// type of the match. However, in this case coercing the final type of the
1593/// `CoerceMany` to its expected type would have error'd anyways, so we don't care.
1594/// - We may constrain the `expected_ty` too early. For some branches with
1595/// type `a` and `b`, we end up with `(a lub expected_ty) lub b` instead of
1596/// `(a lub b) lub expected_ty`. They should be the same type. However,
1597/// `a lub expected_ty` may constrain inference variables in `expected_ty`.
1598/// In this case the difference does matter and we get actually incorrect results.
1599/// FIXME: Ideally we'd compute the final type without unnecessarily constraining
1600/// the expected type of the match when computing the types of its branches.
1601pub(crate) struct CoerceMany<'tcx> {
1602 expected_ty: Ty<'tcx>,
1603 final_ty: Option<Ty<'tcx>>,
1604 expressions: Vec<&'tcx hir::Expr<'tcx>>,
1605}
16061607impl<'tcx> CoerceMany<'tcx> {
1608/// Creates a `CoerceMany` with a default capacity of 1. If the full set of
1609 /// coercion sites is known before hand, consider `with_capacity()` instead
1610 /// to avoid allocation.
1611pub(crate) fn new(expected_ty: Ty<'tcx>) -> Self {
1612Self::with_capacity(expected_ty, 1)
1613 }
16141615/// Creates a `CoerceMany` with a given capacity.
1616pub(crate) fn with_capacity(expected_ty: Ty<'tcx>, capacity: usize) -> Self {
1617CoerceMany { expected_ty, final_ty: None, expressions: Vec::with_capacity(capacity) }
1618 }
16191620/// Returns the "expected type" with which this coercion was
1621 /// constructed. This represents the "downward propagated" type
1622 /// that was given to us at the start of typing whatever construct
1623 /// we are typing (e.g., the match expression).
1624 ///
1625 /// Typically, this is used as the expected type when
1626 /// type-checking each of the alternative expressions whose types
1627 /// we are trying to merge.
1628pub(crate) fn expected_ty(&self) -> Ty<'tcx> {
1629self.expected_ty
1630 }
16311632/// Returns the current "merged type", representing our best-guess
1633 /// at the LUB of the expressions we've seen so far (if any). This
1634 /// isn't *final* until you call `self.complete()`, which will return
1635 /// the merged type.
1636pub(crate) fn merged_ty(&self) -> Ty<'tcx> {
1637self.final_ty.unwrap_or(self.expected_ty)
1638 }
16391640/// Indicates that the value generated by `expression`, which is
1641 /// of type `expression_ty`, is one of the possibilities that we
1642 /// could coerce from. This will record `expression`, and later
1643 /// calls to `coerce` may come back and add adjustments and things
1644 /// if necessary.
1645pub(crate) fn coerce<'a>(
1646&mut self,
1647 fcx: &FnCtxt<'a, 'tcx>,
1648 cause: &ObligationCause<'tcx>,
1649 expression: &'tcx hir::Expr<'tcx>,
1650 expression_ty: Ty<'tcx>,
1651 ) {
1652self.coerce_inner(fcx, cause, Some(expression), expression_ty, |_| {}, false)
1653 }
16541655/// Indicates that one of the inputs is a "forced unit". This
1656 /// occurs in a case like `if foo { ... };`, where the missing else
1657 /// generates a "forced unit". Another example is a `loop { break;
1658 /// }`, where the `break` has no argument expression. We treat
1659 /// these cases slightly differently for error-reporting
1660 /// purposes. Note that these tend to correspond to cases where
1661 /// the `()` expression is implicit in the source, and hence we do
1662 /// not take an expression argument.
1663 ///
1664 /// The `augment_error` gives you a chance to extend the error
1665 /// message, in case any results (e.g., we use this to suggest
1666 /// removing a `;`).
1667pub(crate) fn coerce_forced_unit<'a>(
1668&mut self,
1669 fcx: &FnCtxt<'a, 'tcx>,
1670 cause: &ObligationCause<'tcx>,
1671 augment_error: impl FnOnce(&mut Diag<'_>),
1672 label_unit_as_expected: bool,
1673 ) {
1674self.coerce_inner(
1675fcx,
1676cause,
1677None,
1678fcx.tcx.types.unit,
1679augment_error,
1680label_unit_as_expected,
1681 )
1682 }
16831684/// The inner coercion "engine". If `expression` is `None`, this
1685 /// is a forced-unit case, and hence `expression_ty` must be
1686 /// `Nil`.
1687{}
#[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("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(1687u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("cause")
}> =
::tracing::__macro_support::FieldName::new("cause");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("expression")
}> =
::tracing::__macro_support::FieldName::new("expression");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("expression_ty")
}> =
::tracing::__macro_support::FieldName::new("expression_ty");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expression)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expression_ty)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
if expression_ty.is_ty_var() {
expression_ty = fcx.infcx.shallow_resolve(expression_ty);
}
if let Err(guar) =
(expression_ty, self.merged_ty()).error_reported() {
self.final_ty = Some(Ty::new_error(fcx.tcx, guar));
return;
}
let (expected, found) =
if label_expression_as_expected {
(expression_ty, self.merged_ty())
} else { (self.merged_ty(), expression_ty) };
let result =
if let Some(expression) = expression {
if self.expressions.is_empty() {
fcx.coerce(expression, expression_ty, self.expected_ty,
AllowTwoPhase::No, Some(cause.clone()))
} else {
fcx.try_find_coercion_lub(cause, &self.expressions,
self.merged_ty(), expression, expression_ty)
}
} else {
if !expression_ty.is_unit() {
{
::core::panicking::panic_fmt(format_args!("if let hack without unit type"));
}
};
fcx.at(cause,
fcx.param_env).eq(DefineOpaqueTypes::Yes, expected,
found).map(|infer_ok|
{
fcx.register_infer_ok_obligations(infer_ok);
expression_ty
})
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs:1778",
"rustc_hir_typeck::coercion", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/92b5b8c87c61b20adc9001b41baf587634a74734/compiler/rustc_hir_typeck/src/coercion.rs"),
::tracing_core::__macro_support::Option::Some(1778u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::coercion"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("result")
}> =
::tracing::__macro_support::FieldName::new("result");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&result)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
match result {
Ok(v) => {
self.final_ty = Some(v);
if let Some(e) = expression { self.expressions.push(e); }
}
Err(coercion_error) => {
fcx.set_tainted_by_errors(fcx.dcx().span_delayed_bug(cause.span,
"coercion error but no error emitted"));
let (expected, found) =
fcx.deeply_resolve_ignoring_regions((expected, found));
let mut err;
let mut unsized_return = false;
match *cause.code() {
ObligationCauseCode::ReturnNoExpression => {
err =
{
fcx.dcx().struct_span_err(cause.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`return;` in a function whose return type is not `()`"))
})).with_code(E0069)
};
if let Some(value) =
fcx.err_ctxt().ty_kind_suggestion(fcx.param_env, found) {
err.span_suggestion_verbose(cause.span.shrink_to_hi(),
"give the `return` a value of the expected type",
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {0}", value))
}), Applicability::HasPlaceholders);
}
err.span_label(cause.span, "return type is not `()`");
}
ObligationCauseCode::BlockTailExpression(blk_id, ..) => {
err =
self.report_return_mismatched_types(cause, expected, found,
coercion_error, fcx, blk_id, expression);
unsized_return = self.is_return_ty_definitely_unsized(fcx);
}
ObligationCauseCode::ReturnValue(return_expr_id) => {
err =
self.report_return_mismatched_types(cause, expected, found,
coercion_error, fcx, return_expr_id, expression);
unsized_return = self.is_return_ty_definitely_unsized(fcx);
}
ObligationCauseCode::MatchExpressionArm(MatchExpressionArmCause {
arm_span,
arm_ty,
prior_arm_ty,
ref prior_non_diverging_arms,
tail_defines_return_position_impl_trait: Some(rpit_def_id),
.. }) => {
err =
fcx.err_ctxt().report_mismatched_types(cause, fcx.param_env,
expected, found, coercion_error);
if prior_non_diverging_arms.len() > 0 {
self.suggest_boxing_tail_for_return_position_impl_trait(fcx,
&mut err, rpit_def_id, arm_ty, prior_arm_ty,
prior_non_diverging_arms.iter().chain(std::iter::once(&arm_span)).copied());
}
}
ObligationCauseCode::IfExpression {
expr_id,
tail_defines_return_position_impl_trait: Some(rpit_def_id) }
=> {
let hir::Node::Expr(hir::Expr {
kind: hir::ExprKind::If(_, then_expr, Some(else_expr)), ..
}) =
fcx.tcx.hir_node(expr_id) else {
::core::panicking::unreachable_default_msg();
};
err =
fcx.err_ctxt().report_mismatched_types(cause, fcx.param_env,
expected, found, coercion_error);
let then_span =
fcx.find_block_span_from_hir_id(then_expr.hir_id);
let else_span =
fcx.find_block_span_from_hir_id(else_expr.hir_id);
if then_span != then_expr.span &&
else_span != else_expr.span {
let then_ty =
fcx.typeck_results.borrow().expr_ty(then_expr);
let else_ty =
fcx.typeck_results.borrow().expr_ty(else_expr);
self.suggest_boxing_tail_for_return_position_impl_trait(fcx,
&mut err, rpit_def_id, then_ty, else_ty,
[then_span, else_span].into_iter());
}
}
_ => {
err =
fcx.err_ctxt().report_mismatched_types(cause, fcx.param_env,
expected, found, coercion_error);
}
}
augment_error(&mut err);
if let Some(expr) = expression {
if let hir::ExprKind::Loop(block, _, loop_src @
(hir::LoopSource::While | hir::LoopSource::ForLoop), _) =
expr.kind {
let loop_type =
if loop_src == hir::LoopSource::While {
"`while` loops"
} else { "`for` loops" };
err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} evaluate to unit type `()`",
loop_type))
}));
if loop_src == hir::LoopSource::While &&
let Some(pat) = irrefutable_if_let_expr(block) {
err.span_label(pat.span,
"this pattern always matches, consider using `loop` instead");
}
}
fcx.emit_coerce_suggestions(&mut err, expr, found, expected,
None, Some(coercion_error));
}
let guar = err.emit_err_unless_delay(unsized_return);
self.final_ty = Some(Ty::new_error(fcx.tcx, guar));
}
}
}
}
}#[instrument(skip(self, fcx, augment_error, label_expression_as_expected), level = "debug")]1688pub(crate) fn coerce_inner<'a>(
1689&mut self,
1690 fcx: &FnCtxt<'a, 'tcx>,
1691 cause: &ObligationCause<'tcx>,
1692 expression: Option<&'tcx hir::Expr<'tcx>>,
1693mut expression_ty: Ty<'tcx>,
1694 augment_error: impl FnOnce(&mut Diag<'_>),
1695 label_expression_as_expected: bool,
1696 ) {
1697// Incorporate whatever type inference information we have
1698 // until now; in principle we might also want to process
1699 // pending obligations, but doing so should only improve
1700 // compatibility (hopefully that is true) by helping us
1701 // uncover never types better.
1702if expression_ty.is_ty_var() {
1703 expression_ty = fcx.infcx.shallow_resolve(expression_ty);
1704 }
17051706// If we see any error types, just propagate that error
1707 // upwards.
1708if let Err(guar) = (expression_ty, self.merged_ty()).error_reported() {
1709self.final_ty = Some(Ty::new_error(fcx.tcx, guar));
1710return;
1711 }
17121713let (expected, found) = if label_expression_as_expected {
1714// In the case where this is a "forced unit", like
1715 // `break`, we want to call the `()` "expected"
1716 // since it is implied by the syntax.
1717 // (Note: not all force-units work this way.)"
1718(expression_ty, self.merged_ty())
1719 } else {
1720// Otherwise, the "expected" type for error
1721 // reporting is the current unification type,
1722 // which is basically the LUB of the expressions
1723 // we've seen so far (combined with the expected
1724 // type)
1725(self.merged_ty(), expression_ty)
1726 };
17271728// Handle the actual type unification etc.
1729let result = if let Some(expression) = expression {
1730if self.expressions.is_empty() {
1731// Special-case the first expression we are coercing.
1732 // To be honest, I'm not entirely sure why we do this.
1733 // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why
1734fcx.coerce(
1735 expression,
1736 expression_ty,
1737self.expected_ty,
1738 AllowTwoPhase::No,
1739Some(cause.clone()),
1740 )
1741 } else {
1742 fcx.try_find_coercion_lub(
1743 cause,
1744&self.expressions,
1745self.merged_ty(),
1746 expression,
1747 expression_ty,
1748 )
1749 }
1750 } else {
1751// this is a hack for cases where we default to `()` because
1752 // the expression etc has been omitted from the source. An
1753 // example is an `if let` without an else:
1754 //
1755 // if let Some(x) = ... { }
1756 //
1757 // we wind up with a second match arm that is like `_ =>
1758 // ()`. That is the case we are considering here. We take
1759 // a different path to get the right "expected, found"
1760 // message and so forth (and because we know that
1761 // `expression_ty` will be unit).
1762 //
1763 // Another example is `break` with no argument expression.
1764assert!(expression_ty.is_unit(), "if let hack without unit type");
1765 fcx.at(cause, fcx.param_env)
1766 .eq(
1767// needed for tests/ui/type-alias-impl-trait/issue-65679-inst-opaque-ty-from-val-twice.rs
1768DefineOpaqueTypes::Yes,
1769 expected,
1770 found,
1771 )
1772 .map(|infer_ok| {
1773 fcx.register_infer_ok_obligations(infer_ok);
1774 expression_ty
1775 })
1776 };
17771778debug!(?result);
1779match result {
1780Ok(v) => {
1781self.final_ty = Some(v);
1782if let Some(e) = expression {
1783self.expressions.push(e);
1784 }
1785 }
1786Err(coercion_error) => {
1787// Mark that we've failed to coerce the types here to suppress
1788 // any superfluous errors we might encounter while trying to
1789 // emit or provide suggestions on how to fix the initial error.
1790fcx.set_tainted_by_errors(
1791 fcx.dcx().span_delayed_bug(cause.span, "coercion error but no error emitted"),
1792 );
1793let (expected, found) = fcx.deeply_resolve_ignoring_regions((expected, found));
17941795let mut err;
1796let mut unsized_return = false;
1797match *cause.code() {
1798 ObligationCauseCode::ReturnNoExpression => {
1799 err = struct_span_code_err!(
1800 fcx.dcx(),
1801 cause.span,
1802 E0069,
1803"`return;` in a function whose return type is not `()`"
1804);
1805if let Some(value) = fcx.err_ctxt().ty_kind_suggestion(fcx.param_env, found)
1806 {
1807 err.span_suggestion_verbose(
1808 cause.span.shrink_to_hi(),
1809"give the `return` a value of the expected type",
1810format!(" {value}"),
1811 Applicability::HasPlaceholders,
1812 );
1813 }
1814 err.span_label(cause.span, "return type is not `()`");
1815 }
1816 ObligationCauseCode::BlockTailExpression(blk_id, ..) => {
1817 err = self.report_return_mismatched_types(
1818 cause,
1819 expected,
1820 found,
1821 coercion_error,
1822 fcx,
1823 blk_id,
1824 expression,
1825 );
1826 unsized_return = self.is_return_ty_definitely_unsized(fcx);
1827 }
1828 ObligationCauseCode::ReturnValue(return_expr_id) => {
1829 err = self.report_return_mismatched_types(
1830 cause,
1831 expected,
1832 found,
1833 coercion_error,
1834 fcx,
1835 return_expr_id,
1836 expression,
1837 );
1838 unsized_return = self.is_return_ty_definitely_unsized(fcx);
1839 }
1840 ObligationCauseCode::MatchExpressionArm(MatchExpressionArmCause {
1841 arm_span,
1842 arm_ty,
1843 prior_arm_ty,
1844ref prior_non_diverging_arms,
1845 tail_defines_return_position_impl_trait: Some(rpit_def_id),
1846 ..
1847 }) => {
1848 err = fcx.err_ctxt().report_mismatched_types(
1849 cause,
1850 fcx.param_env,
1851 expected,
1852 found,
1853 coercion_error,
1854 );
1855// Check that we're actually in the second or later arm
1856if prior_non_diverging_arms.len() > 0 {
1857self.suggest_boxing_tail_for_return_position_impl_trait(
1858 fcx,
1859&mut err,
1860 rpit_def_id,
1861 arm_ty,
1862 prior_arm_ty,
1863 prior_non_diverging_arms
1864 .iter()
1865 .chain(std::iter::once(&arm_span))
1866 .copied(),
1867 );
1868 }
1869 }
1870 ObligationCauseCode::IfExpression {
1871 expr_id,
1872 tail_defines_return_position_impl_trait: Some(rpit_def_id),
1873 } => {
1874let hir::Node::Expr(hir::Expr {
1875 kind: hir::ExprKind::If(_, then_expr, Some(else_expr)),
1876 ..
1877 }) = fcx.tcx.hir_node(expr_id)
1878else {
1879unreachable!();
1880 };
1881 err = fcx.err_ctxt().report_mismatched_types(
1882 cause,
1883 fcx.param_env,
1884 expected,
1885 found,
1886 coercion_error,
1887 );
1888let then_span = fcx.find_block_span_from_hir_id(then_expr.hir_id);
1889let else_span = fcx.find_block_span_from_hir_id(else_expr.hir_id);
1890// Don't suggest wrapping whole block in `Box::new`.
1891if then_span != then_expr.span && else_span != else_expr.span {
1892let then_ty = fcx.typeck_results.borrow().expr_ty(then_expr);
1893let else_ty = fcx.typeck_results.borrow().expr_ty(else_expr);
1894self.suggest_boxing_tail_for_return_position_impl_trait(
1895 fcx,
1896&mut err,
1897 rpit_def_id,
1898 then_ty,
1899 else_ty,
1900 [then_span, else_span].into_iter(),
1901 );
1902 }
1903 }
1904_ => {
1905 err = fcx.err_ctxt().report_mismatched_types(
1906 cause,
1907 fcx.param_env,
1908 expected,
1909 found,
1910 coercion_error,
1911 );
1912 }
1913 }
19141915 augment_error(&mut err);
19161917if let Some(expr) = expression {
1918if let hir::ExprKind::Loop(
1919 block,
1920_,
1921 loop_src @ (hir::LoopSource::While | hir::LoopSource::ForLoop),
1922_,
1923 ) = expr.kind
1924 {
1925let loop_type = if loop_src == hir::LoopSource::While {
1926"`while` loops"
1927} else {
1928"`for` loops"
1929};
19301931 err.note(format!("{loop_type} evaluate to unit type `()`"));
1932if loop_src == hir::LoopSource::While
1933 && let Some(pat) = irrefutable_if_let_expr(block)
1934 {
1935 err.span_label(
1936 pat.span,
1937"this pattern always matches, consider using `loop` instead",
1938 );
1939 }
1940 }
19411942 fcx.emit_coerce_suggestions(
1943&mut err,
1944 expr,
1945 found,
1946 expected,
1947None,
1948Some(coercion_error),
1949 );
1950 }
19511952let guar = err.emit_err_unless_delay(unsized_return);
19531954self.final_ty = Some(Ty::new_error(fcx.tcx, guar));
1955 }
1956 }
1957 }
19581959fn suggest_boxing_tail_for_return_position_impl_trait(
1960&self,
1961 fcx: &FnCtxt<'_, 'tcx>,
1962 err: &mut Diag<'_>,
1963 rpit_def_id: LocalDefId,
1964 a_ty: Ty<'tcx>,
1965 b_ty: Ty<'tcx>,
1966 arm_spans: impl Iterator<Item = Span>,
1967 ) {
1968let compatible = |ty: Ty<'tcx>| {
1969fcx.probe(|_| {
1970let ocx = ObligationCtxt::new(fcx);
1971ocx.register_obligations(
1972fcx.tcx
1973 .item_self_bounds(rpit_def_id)
1974 .iter_identity()
1975 .map(Unnormalized::skip_norm_wip)
1976 .filter_map(|clause| {
1977let predicate = clause
1978 .kind()
1979 .map_bound(|clause| match clause {
1980 ty::ClauseKind::Trait(trait_pred) => {
1981Some(ty::ClauseKind::Trait(
1982 trait_pred.with_replaced_self_ty(fcx.tcx, ty),
1983 ))
1984 }
1985 ty::ClauseKind::Projection(proj_pred) => {
1986Some(ty::ClauseKind::Projection(
1987 proj_pred.with_replaced_self_ty(fcx.tcx, ty),
1988 ))
1989 }
1990_ => None,
1991 })
1992 .transpose()?;
1993Some(Obligation::new(
1994fcx.tcx,
1995ObligationCause::dummy(),
1996fcx.param_env,
1997predicate,
1998 ))
1999 }),
2000 );
2001ocx.try_evaluate_obligations().no_errors()
2002 })
2003 };
20042005if !compatible(a_ty) || !compatible(b_ty) {
2006return;
2007 }
20082009let rpid_def_span = fcx.tcx.def_span(rpit_def_id);
2010err.subdiagnostic(SuggestBoxingForReturnImplTrait::ChangeReturnType {
2011 start_sp: rpid_def_span.with_hi(rpid_def_span.lo() + BytePos(4)),
2012 end_sp: rpid_def_span.shrink_to_hi(),
2013 });
20142015let (starts, ends) =
2016arm_spans.map(|span| (span.shrink_to_lo(), span.shrink_to_hi())).unzip();
2017err.subdiagnostic(SuggestBoxingForReturnImplTrait::BoxReturnExpr { starts, ends });
2018 }
20192020fn report_return_mismatched_types<'infcx>(
2021&self,
2022 cause: &ObligationCause<'tcx>,
2023 expected: Ty<'tcx>,
2024 found: Ty<'tcx>,
2025 ty_err: TypeError<'tcx>,
2026 fcx: &'infcx FnCtxt<'_, 'tcx>,
2027 block_or_return_id: hir::HirId,
2028 expression: Option<&'tcx hir::Expr<'tcx>>,
2029 ) -> Diag<'infcx> {
2030let mut err =
2031fcx.err_ctxt().report_mismatched_types(cause, fcx.param_env, expected, found, ty_err);
20322033let 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(..));
2034let parent = fcx.tcx.parent_hir_node(block_or_return_id);
2035if let Some(expr) = expression2036 && let hir::Node::Expr(&hir::Expr {
2037 kind: hir::ExprKind::Closure(&hir::Closure { body, .. }),
2038 ..
2039 }) = parent2040 {
2041let needs_block =
2042 !#[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(..));
2043fcx.suggest_missing_semicolon(&mut err, expr, expected, needs_block, true);
2044 }
2045// Verify that this is a tail expression of a function, otherwise the
2046 // label pointing out the cause for the type coercion will be wrong
2047 // as prior return coercions would not be relevant (#57664).
2048if let Some(expr) = expression2049 && due_to_block2050 {
2051fcx.suggest_missing_semicolon(&mut err, expr, expected, false, false);
2052let pointing_at_return_type = fcx.suggest_mismatched_types_on_tail(
2053&mut err,
2054expr,
2055expected,
2056found,
2057block_or_return_id,
2058 );
2059if let Some(cond_expr) = fcx.tcx.hir_get_if_cause(expr.hir_id)
2060 && expected.is_unit()
2061 && !pointing_at_return_type2062// If the block is from an external macro or try (`?`) desugaring, then
2063 // do not suggest adding a semicolon, because there's nowhere to put it.
2064 // See issues #81943 and #87051.
2065 // Similarly, if the block is from a loop desugaring, then also do not
2066 // suggest adding a semicolon. See issue #150850.
2067&& cond_expr.span.desugaring_kind().is_none()
2068 && !cond_expr.span.in_external_macro(fcx.tcx.sess.source_map())
2069 && !#[allow(non_exhaustive_omitted_patterns)] match cond_expr.kind {
hir::ExprKind::Match(.., hir::MatchSource::TryDesugar(_)) => true,
_ => false,
}matches!(
2070 cond_expr.kind,
2071 hir::ExprKind::Match(.., hir::MatchSource::TryDesugar(_))
2072 )2073 {
2074if let ObligationCauseCode::BlockTailExpression(hir_id, hir::MatchSource::Normal) =
2075cause.code()
2076 && let hir::Node::Block(block) = fcx.tcx.hir_node(*hir_id)
2077 && let hir::Node::Expr(expr) = fcx.tcx.parent_hir_node(block.hir_id)
2078 && let hir::Node::Expr(if_expr) = fcx.tcx.parent_hir_node(expr.hir_id)
2079 && let hir::ExprKind::If(_cond, _then, None) = if_expr.kind
2080 {
2081err.span_label(
2082cond_expr.span,
2083"`if` expressions without `else` arms expect their inner expression to be `()`",
2084 );
2085 } else {
2086err.span_label(cond_expr.span, "expected this to be `()`");
2087 }
2088if expr.can_have_side_effects() {
2089// Don't suggest semicolon after if expressions as it does not fix the issue
2090if !#[allow(non_exhaustive_omitted_patterns)] match cond_expr.kind {
hir::ExprKind::If(..) => true,
_ => false,
}matches!(cond_expr.kind, hir::ExprKind::If(..)) {
2091fcx.suggest_semicolon_at_end(cond_expr.span, &mut err);
2092 }
2093 }
2094 }
2095 }
20962097// If this is due to an explicit `return`, suggest adding a return type.
2098if let Some((fn_id, fn_decl)) = fcx.get_fn_decl(block_or_return_id)
2099 && !due_to_block2100 {
2101fcx.suggest_missing_return_type(&mut err, fn_decl, expected, found, fn_id);
2102 }
21032104let is_return_position = fcx2105 .tcx
2106 .hir_get_fn_id_for_return_block(block_or_return_id)
2107 .is_some_and(|fn_id| fn_id == fcx.tcx.local_def_id_to_hir_id(fcx.body_def_id));
21082109// If this is due to a block, then maybe we forgot a `return`/`break`.
2110if due_to_block2111 && let Some(expr) = expression2112 && let Some(parent_fn_decl) =
2113fcx.tcx.hir_fn_decl_by_hir_id(fcx.tcx.local_def_id_to_hir_id(fcx.body_def_id))
2114 && !is_return_position2115 {
2116fcx.suggest_missing_break_or_return_expr(
2117&mut err,
2118expr,
2119parent_fn_decl,
2120expected,
2121found,
2122block_or_return_id,
2123fcx.body_def_id,
2124 );
2125 }
21262127if is_return_position2128 && let Some(sp) = fcx.ret_coercion_span.get()
2129// If the closure has an explicit return type annotation, or if
2130 // the closure's return type has been inferred from outside
2131 // requirements (such as an Fn* trait bound), then a type error
2132 // may occur at the first return expression we see in the closure
2133 // (if it conflicts with the declared return type). Skip adding a
2134 // note in this case, since it would be incorrect.
2135&& let Some(fn_sig) = fcx.fn_sig()
2136 && fn_sig.output().is_ty_var()
2137 {
2138err.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"));
2139 }
21402141err2142 }
21432144/// Checks whether the return type is unsized via an obligation, which makes
2145 /// sure we consider `dyn Trait: Sized` where clauses, which are trivially
2146 /// false but technically valid for typeck.
2147fn is_return_ty_definitely_unsized(&self, fcx: &FnCtxt<'_, 'tcx>) -> bool {
2148if let Some(sig) = fcx.fn_sig() {
2149 !fcx.predicate_may_hold(&Obligation::new(
2150fcx.tcx,
2151ObligationCause::dummy(),
2152fcx.param_env,
2153 ty::TraitRef::new(
2154fcx.tcx,
2155fcx.tcx.require_lang_item(LangItem::Sized, DUMMY_SP),
2156 [sig.output()],
2157 ),
2158 ))
2159 } else {
2160false
2161}
2162 }
21632164pub(crate) fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> {
2165if let Some(final_ty) = self.final_ty {
2166final_ty2167 } else {
2168// If we only had inputs that were of type `!` (or no
2169 // inputs at all), then the final type is `!`.
2170if !self.expressions.is_empty() {
::core::panicking::panic("assertion failed: self.expressions.is_empty()")
};assert!(self.expressions.is_empty());
2171fcx.tcx.types.never
2172 }
2173 }
2174}
21752176fn irrefutable_if_let_expr<'hir>(block: &hir::Block<'hir>) -> Option<&'hir hir::Pat<'hir>> {
2177let hir::ExprKind::If(cond, _, _) = block.expr?.kind else {
2178return None;
2179 };
2180let hir::ExprKind::Let(let_expr) = cond.kind else {
2181return None;
2182 };
2183simple_irrefutable_pattern(let_expr.pat).then_some(let_expr.pat)
2184}
21852186fn simple_irrefutable_pattern(pat: &hir::Pat<'_>) -> bool {
2187match pat.kind {
2188 hir::PatKind::Wild | hir::PatKind::Binding(_, _, _, None) => true,
2189 hir::PatKind::Tuple(pats, _) => pats.iter().all(simple_irrefutable_pattern),
2190_ => false,
2191 }
2192}
21932194/// Recursively visit goals to decide whether an unsizing is possible.
2195/// `Break`s when it isn't, and an error should be raised.
2196/// `Continue`s when an unsizing ok based on an implementation of the `Unsize` trait / lang item.
2197struct CoerceVisitor<'a, 'tcx> {
2198 fcx: &'a FnCtxt<'a, 'tcx>,
2199 span: Span,
2200/// Whether the coercion is impossible. If so we sometimes still try to
2201 /// coerce in these cases to emit better errors. This changes the behavior
2202 /// when hitting the recursion limit.
2203errored: bool,
2204}
22052206impl<'tcx> ProofTreeVisitor<'tcx> for CoerceVisitor<'_, 'tcx> {
2207type Result = ControlFlow<()>;
22082209fn span(&self) -> Span {
2210self.span
2211 }
22122213fn visit_goal(&mut self, goal: &inspect::InspectGoal<'_, 'tcx>) -> Self::Result {
2214let Some(pred) = goal.goal().predicate.as_trait_clause() else {
2215return ControlFlow::Continue(());
2216 };
22172218// Make sure this predicate is referring to either an `Unsize` or `CoerceUnsized` trait,
2219 // Otherwise there's nothing to do.
2220if !self.fcx.tcx.is_lang_item(pred.def_id(), LangItem::Unsize)
2221 && !self.fcx.tcx.is_lang_item(pred.def_id(), LangItem::CoerceUnsized)
2222 {
2223return ControlFlow::Continue(());
2224 }
22252226match goal.result() {
2227// If we prove the `Unsize` or `CoerceUnsized` goal, continue recursing.
2228Ok(Certainty::Yes) => ControlFlow::Continue(()),
2229Err(NoSolution) => {
2230self.errored = true;
2231// Even if we find no solution, continue recursing if we find a single candidate
2232 // for which we're shallowly certain it holds to get the right error source.
2233if let [only_candidate] = &goal.candidates()[..]
2234 && only_candidate.shallow_certainty() == Certainty::Yes2235 {
2236only_candidate.visit_nested_no_probe(self)
2237 } else {
2238 ControlFlow::Break(())
2239 }
2240 }
2241Ok(Certainty::Maybe(_)) => {
2242// FIXME: structurally normalize?
2243if self.fcx.tcx.is_lang_item(pred.def_id(), LangItem::Unsize)
2244 && let ty::Dynamic(..) = pred.skip_binder().trait_ref.args.type_at(1).kind()
2245 && let ty::Infer(ty::TyVar(vid)) = *pred.self_ty().skip_binder().kind()
2246 && self.fcx.type_var_is_sized(vid)
2247 {
2248// We get here when trying to unsize a type variable to a `dyn Trait`,
2249 // knowing that that variable is sized. Unsizing definitely has to happen in that case.
2250 // If the variable weren't sized, we may not need an unsizing coercion.
2251 // In general, we don't want to add coercions too eagerly since it makes error messages much worse.
2252ControlFlow::Continue(())
2253 } else if let Some(cand) = goal.unique_applicable_candidate()
2254 && cand.shallow_certainty() == Certainty::Yes2255 {
2256cand.visit_nested_no_probe(self)
2257 } else {
2258 ControlFlow::Break(())
2259 }
2260 }
2261 }
2262 }
22632264fn on_recursion_limit(&mut self) -> Self::Result {
2265if self.errored {
2266// This prevents accidentally committing unfulfilled unsized coercions while trying to
2267 // find the error source for diagnostics.
2268 // See https://github.com/rust-lang/trait-system-refactor-initiative/issues/266.
2269ControlFlow::Break(())
2270 } else {
2271 ControlFlow::Continue(())
2272 }
2273 }
2274}