1use std::collections::hash_map::Entry;
2use std::slice;
3
4use rustc_abi::FieldIdx;
5use rustc_data_structures::fx::FxHashSet;
6use rustc_errors::{
7 Applicability, Diag, DiagCtxtHandle, Diagnostic, ErrorGuaranteed, Level, MultiSpan,
8};
9use rustc_hir::def::{CtorOf, DefKind, Res};
10use rustc_hir::def_id::DefId;
11use rustc_hir::intravisit::VisitorExt;
12use rustc_hir::lang_items::LangItem;
13use rustc_hir::{self as hir, AmbigArg, ExprKind, GenericArg, HirId, Node, QPath, intravisit};
14use rustc_hir_analysis::hir_ty_lowering::errors::GenericsArgsErrExtend;
15use rustc_hir_analysis::hir_ty_lowering::generics::{
16 check_generic_arg_count_for_value_path, lower_generic_args,
17};
18use rustc_hir_analysis::hir_ty_lowering::{
19 ExplicitLateBound, GenericArgCountMismatch, GenericArgCountResult, GenericArgsLowerer,
20 GenericPathSegment, HirTyLowerer, IsMethodCall, RegionInferReason,
21};
22use rustc_infer::infer::canonical::{Canonical, OriginalQueryValues, QueryResponse};
23use rustc_infer::infer::{DefineOpaqueTypes, InferResult};
24use rustc_lint::builtin::SELF_CONSTRUCTOR_FROM_OUTER_ITEM;
25use rustc_middle::ty::adjustment::{
26 Adjust, Adjustment, AutoBorrow, AutoBorrowMutability, DerefAdjustKind,
27};
28use rustc_middle::ty::{
29 self, AdtKind, CanonicalUserType, GenericArgsRef, GenericParamDefKind, IsIdentity,
30 SizedTraitKind, Ty, TyCtxt, TypeFoldable, TypeVisitable, TypeVisitableExt, Unnormalized,
31 UserArgs, UserSelfTy,
32};
33use rustc_middle::{bug, span_bug};
34use rustc_session::lint;
35use rustc_span::Span;
36use rustc_span::def_id::LocalDefId;
37use rustc_span::hygiene::DesugaringKind;
38use rustc_trait_selection::error_reporting::infer::need_type_info::TypeAnnotationNeeded;
39use rustc_trait_selection::traits::{
40 self, NormalizeExt, ObligationCauseCode, StructurallyNormalizeExt,
41};
42use tracing::{debug, instrument};
43
44use crate::callee::{self, DeferredCallResolution};
45use crate::errors::{self, CtorIsPrivate};
46use crate::method::{self, MethodCallee};
47use crate::{BreakableCtxt, Diverges, Expectation, FnCtxt, LoweredTy};
48
49impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
50 pub(crate) fn transform_args_for_inherent_type_const(
56 &self,
57 def_id: DefId,
58 args: GenericArgsRef<'tcx>,
59 ) -> GenericArgsRef<'tcx> {
60 let tcx = self.tcx;
61 if !tcx.is_type_const(def_id) {
62 return args;
63 }
64 let Some(assoc_item) = tcx.opt_associated_item(def_id) else {
65 return args;
66 };
67 if !#[allow(non_exhaustive_omitted_patterns)] match assoc_item.container {
ty::AssocContainer::InherentImpl => true,
_ => false,
}matches!(assoc_item.container, ty::AssocContainer::InherentImpl) {
68 return args;
69 }
70
71 let impl_def_id = assoc_item.container_id(tcx);
72 let generics = tcx.generics_of(def_id);
73 let impl_args = &args[..generics.parent_count];
74 let self_ty = tcx.type_of(impl_def_id).instantiate(tcx, impl_args).skip_norm_wip();
75 let own_args = &args[generics.parent_count..];
77 tcx.mk_args_from_iter(
78 std::iter::once(ty::GenericArg::from(self_ty)).chain(own_args.iter().copied()),
79 )
80 }
81
82 pub(crate) fn warn_if_unreachable(&self, id: HirId, span: Span, kind: &str) {
85 struct UnreachableItem<'a, 'b> {
86 kind: &'a str,
87 span: Span,
88 orig_span: Span,
89 custom_note: Option<&'b str>,
90 }
91
92 impl<'a, 'b, 'c> Diagnostic<'a, ()> for UnreachableItem<'b, 'c> {
93 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
94 let Self { kind, span, orig_span, custom_note } = self;
95 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unreachable {0}", kind))
})format!("unreachable {kind}");
96 Diag::new(dcx, level, msg.clone()).with_span_label(span, msg).with_span_label(
97 orig_span,
98 custom_note.map(|c| c.to_owned()).unwrap_or_else(|| {
99 "any code following this expression is unreachable".to_owned()
100 }),
101 )
102 }
103 }
104
105 let Diverges::Always { span: orig_span, custom_note } = self.diverges.get() else {
106 return;
107 };
108
109 match span.desugaring_kind() {
110 Some(DesugaringKind::Async) => return,
113
114 Some(DesugaringKind::Await) => return,
118
119 _ => {}
120 }
121
122 if self.tcx.is_automatically_derived(self.tcx.parent(id.owner.def_id.into())) {
125 return;
126 }
127
128 self.diverges.set(Diverges::WarnedAlways);
130
131 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs:131",
"rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
::tracing_core::__macro_support::Option::Some(131u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("warn_if_unreachable: id={0:?} span={1:?} kind={2}",
id, span, kind) as &dyn Value))])
});
} else { ; }
};debug!("warn_if_unreachable: id={:?} span={:?} kind={}", id, span, kind);
132
133 self.tcx().emit_node_span_lint(
134 lint::builtin::UNREACHABLE_CODE,
135 id,
136 span,
137 UnreachableItem { kind, span, orig_span, custom_note },
138 );
139 }
140
141 x;#[instrument(skip(self), level = "debug", ret)]
148 pub(crate) fn resolve_vars_with_obligations<T: TypeFoldable<TyCtxt<'tcx>>>(
149 &self,
150 mut t: T,
151 ) -> T {
152 if !t.has_non_region_infer() {
154 debug!("no inference var, nothing needs doing");
155 return t;
156 }
157
158 t = self.resolve_vars_if_possible(t);
160 if !t.has_non_region_infer() {
161 debug!(?t);
162 return t;
163 }
164
165 self.select_obligations_where_possible(|_| {});
170 self.resolve_vars_if_possible(t)
171 }
172
173 pub(crate) fn record_deferred_call_resolution(
174 &self,
175 closure_def_id: LocalDefId,
176 r: DeferredCallResolution<'tcx>,
177 ) {
178 let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
179 deferred_call_resolutions.entry(closure_def_id).or_default().push(r);
180 }
181
182 pub(crate) fn remove_deferred_call_resolutions(
183 &self,
184 closure_def_id: LocalDefId,
185 ) -> Vec<DeferredCallResolution<'tcx>> {
186 let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
187 deferred_call_resolutions.remove(&closure_def_id).unwrap_or_default()
188 }
189
190 fn tag(&self) -> String {
191 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:p}", self))
})format!("{self:p}")
192 }
193
194 pub(crate) fn local_ty(&self, span: Span, nid: HirId) -> Ty<'tcx> {
195 self.locals.borrow().get(&nid).cloned().unwrap_or_else(|| {
196 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("no type for local variable {0}",
self.tcx.hir_id_to_string(nid)))span_bug!(span, "no type for local variable {}", self.tcx.hir_id_to_string(nid))
197 })
198 }
199
200 #[inline]
201 pub(crate) fn write_ty(&self, id: HirId, ty: Ty<'tcx>) {
202 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs:202",
"rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
::tracing_core::__macro_support::Option::Some(202u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("write_ty({0:?}, {1:?}) in fcx {2}",
id, self.resolve_vars_if_possible(ty), self.tag()) as
&dyn Value))])
});
} else { ; }
};debug!("write_ty({:?}, {:?}) in fcx {}", id, self.resolve_vars_if_possible(ty), self.tag());
203 let mut typeck = self.typeck_results.borrow_mut();
204 let mut node_ty = typeck.node_types_mut();
205
206 if let Some(prev) = node_ty.insert(id, ty) {
207 if prev.references_error() {
208 node_ty.insert(id, prev);
209 } else if !ty.references_error() {
210 self.dcx().span_delayed_bug(
215 self.tcx.hir_span(id),
216 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{1}` overridden by `{2}` for {3:?} in {0:?}",
self.body_id, prev, ty, id))
})format!("`{prev}` overridden by `{ty}` for {id:?} in {:?}", self.body_id),
217 );
218 }
219 }
220
221 if let Err(e) = ty.error_reported() {
222 self.set_tainted_by_errors(e);
223 }
224 }
225
226 pub(crate) fn write_field_index(&self, hir_id: HirId, index: FieldIdx) {
227 self.typeck_results.borrow_mut().field_indices_mut().insert(hir_id, index);
228 }
229
230 #[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("write_resolution",
"rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
::tracing_core::__macro_support::Option::Some(230u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
::tracing_core::field::FieldSet::new(&["hir_id", "r"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hir_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&r)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
self.typeck_results.borrow_mut().type_dependent_defs_mut().insert(hir_id,
r);
}
}
}#[instrument(level = "debug", skip(self))]
231 pub(crate) fn write_resolution(
232 &self,
233 hir_id: HirId,
234 r: Result<(DefKind, DefId), ErrorGuaranteed>,
235 ) {
236 self.typeck_results.borrow_mut().type_dependent_defs_mut().insert(hir_id, r);
237 }
238
239 #[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("write_method_call_and_enforce_effects",
"rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
::tracing_core::__macro_support::Option::Some(239u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
::tracing_core::field::FieldSet::new(&["hir_id", "span",
"method"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hir_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&method)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
self.enforce_context_effects(Some(hir_id), span, method.def_id,
method.args);
self.write_resolution(hir_id,
Ok((DefKind::AssocFn, method.def_id)));
self.write_args(hir_id, method.args);
}
}
}#[instrument(level = "debug", skip(self))]
240 pub(crate) fn write_method_call_and_enforce_effects(
241 &self,
242 hir_id: HirId,
243 span: Span,
244 method: MethodCallee<'tcx>,
245 ) {
246 self.enforce_context_effects(Some(hir_id), span, method.def_id, method.args);
247 self.write_resolution(hir_id, Ok((DefKind::AssocFn, method.def_id)));
248 self.write_args(hir_id, method.args);
249 }
250
251 fn write_args(&self, node_id: HirId, args: GenericArgsRef<'tcx>) {
252 if !args.is_empty() {
253 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs:253",
"rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
::tracing_core::__macro_support::Option::Some(253u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("write_args({0:?}, {1:?}) in fcx {2}",
node_id, args, self.tag()) as &dyn Value))])
});
} else { ; }
};debug!("write_args({:?}, {:?}) in fcx {}", node_id, args, self.tag());
254
255 self.typeck_results.borrow_mut().node_args_mut().insert(node_id, args);
256 }
257 }
258
259 #[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("write_user_type_annotation_from_args",
"rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
::tracing_core::__macro_support::Option::Some(266u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
::tracing_core::field::FieldSet::new(&["hir_id", "def_id",
"args", "user_self_ty"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hir_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&user_self_ty)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs:274",
"rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
::tracing_core::__macro_support::Option::Some(274u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("fcx {0}",
self.tag()) as &dyn Value))])
});
} else { ; }
};
if self.tcx.def_kind(def_id) == DefKind::ConstParam { return; }
if Self::can_contain_user_lifetime_bounds((args, user_self_ty)) {
let canonicalized =
self.canonicalize_user_type_annotation(ty::UserType::new(ty::UserTypeKind::TypeOf(def_id,
UserArgs { args, user_self_ty })));
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs:287",
"rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
::tracing_core::__macro_support::Option::Some(287u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
::tracing_core::field::FieldSet::new(&["canonicalized"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&canonicalized)
as &dyn Value))])
});
} else { ; }
};
self.write_user_type_annotation(hir_id, canonicalized);
}
}
}
}#[instrument(skip(self), level = "debug")]
267 pub(crate) fn write_user_type_annotation_from_args(
268 &self,
269 hir_id: HirId,
270 def_id: DefId,
271 args: GenericArgsRef<'tcx>,
272 user_self_ty: Option<UserSelfTy<'tcx>>,
273 ) {
274 debug!("fcx {}", self.tag());
275
276 if self.tcx.def_kind(def_id) == DefKind::ConstParam {
280 return;
281 }
282
283 if Self::can_contain_user_lifetime_bounds((args, user_self_ty)) {
284 let canonicalized = self.canonicalize_user_type_annotation(ty::UserType::new(
285 ty::UserTypeKind::TypeOf(def_id, UserArgs { args, user_self_ty }),
286 ));
287 debug!(?canonicalized);
288 self.write_user_type_annotation(hir_id, canonicalized);
289 }
290 }
291
292 #[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("write_user_type_annotation",
"rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
::tracing_core::__macro_support::Option::Some(292u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
::tracing_core::field::FieldSet::new(&["hir_id",
"canonical_user_type_annotation"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hir_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&canonical_user_type_annotation)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs:298",
"rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
::tracing_core::__macro_support::Option::Some(298u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("fcx {0}",
self.tag()) as &dyn Value))])
});
} else { ; }
};
if !canonical_user_type_annotation.is_identity() {
self.typeck_results.borrow_mut().user_provided_types_mut().insert(hir_id,
canonical_user_type_annotation);
} else {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs:307",
"rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
::tracing_core::__macro_support::Option::Some(307u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("skipping identity args")
as &dyn Value))])
});
} else { ; }
};
}
}
}
}#[instrument(skip(self), level = "debug")]
293 pub(crate) fn write_user_type_annotation(
294 &self,
295 hir_id: HirId,
296 canonical_user_type_annotation: CanonicalUserType<'tcx>,
297 ) {
298 debug!("fcx {}", self.tag());
299
300 if !canonical_user_type_annotation.is_identity() {
302 self.typeck_results
303 .borrow_mut()
304 .user_provided_types_mut()
305 .insert(hir_id, canonical_user_type_annotation);
306 } else {
307 debug!("skipping identity args");
308 }
309 }
310
311 #[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("apply_adjustments",
"rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
::tracing_core::__macro_support::Option::Some(311u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
::tracing_core::field::FieldSet::new(&["adj"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&adj)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs:313",
"rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
::tracing_core::__macro_support::Option::Some(313u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("expr = {0:#?}",
expr) as &dyn Value))])
});
} else { ; }
};
if adj.is_empty() { return; }
let mut expr_ty =
self.typeck_results.borrow().expr_ty_adjusted(expr);
for a in &adj {
match a.kind {
Adjust::NeverToAny => {
if let ty::Infer(ty::TyVar(a_id)) = a.target.kind() {
self.diverging_type_vars.borrow_mut().push(*a_id);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs:326",
"rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
::tracing_core::__macro_support::Option::Some(326u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("apply_adjustments: adding `{0:?}` as diverging type var",
a.target) as &dyn Value))])
});
} else { ; }
};
}
}
Adjust::Deref(DerefAdjustKind::Overloaded(overloaded_deref))
=> {
self.enforce_context_effects(None, expr.span,
overloaded_deref.method_call(self.tcx),
self.tcx.mk_args(&[expr_ty.into()]));
}
Adjust::Deref(DerefAdjustKind::Builtin) => {}
Adjust::Deref(DerefAdjustKind::Pin) => {}
Adjust::Pointer(_pointer_coercion) => {}
Adjust::GenericReborrow(_) => {}
Adjust::Borrow(_) => {}
}
expr_ty = a.target;
}
let autoborrow_mut =
adj.iter().any(|adj|
{
#[allow(non_exhaustive_omitted_patterns)]
match adj {
&Adjustment {
kind: Adjust::Borrow(AutoBorrow::Ref(AutoBorrowMutability::Mut {
.. })), .. } => true,
_ => false,
}
});
match self.typeck_results.borrow_mut().adjustments_mut().entry(expr.hir_id)
{
Entry::Vacant(entry) => { entry.insert(adj); }
Entry::Occupied(mut entry) => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs:372",
"rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
::tracing_core::__macro_support::Option::Some(372u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!(" - composing on top of {0:?}",
entry.get()) as &dyn Value))])
});
} else { ; }
};
match (&mut entry.get_mut()[..], &adj[..]) {
([Adjustment { kind: Adjust::NeverToAny, target }],
&[.., Adjustment { target: new_target, .. }]) => {
*target = new_target;
}
(&mut [Adjustment { kind: Adjust::Deref(_), .. },
Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(..)), ..
}], &[Adjustment { kind: Adjust::Deref(_), .. }, ..]) => {
*entry.get_mut() = adj;
}
_ => {
self.dcx().span_delayed_bug(expr.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("while adjusting {0:?}, can\'t compose {1:?} and {2:?}",
expr, entry.get(), adj))
}));
*entry.get_mut() = adj;
}
}
}
}
if autoborrow_mut { self.convert_place_derefs_to_mutable(expr); }
}
}
}#[instrument(skip(self, expr), level = "debug")]
312 pub(crate) fn apply_adjustments(&self, expr: &hir::Expr<'_>, adj: Vec<Adjustment<'tcx>>) {
313 debug!("expr = {:#?}", expr);
314
315 if adj.is_empty() {
316 return;
317 }
318
319 let mut expr_ty = self.typeck_results.borrow().expr_ty_adjusted(expr);
320
321 for a in &adj {
322 match a.kind {
323 Adjust::NeverToAny => {
324 if let ty::Infer(ty::TyVar(a_id)) = a.target.kind() {
325 self.diverging_type_vars.borrow_mut().push(*a_id);
326 debug!("apply_adjustments: adding `{:?}` as diverging type var", a.target);
327 }
328 }
329 Adjust::Deref(DerefAdjustKind::Overloaded(overloaded_deref)) => {
330 self.enforce_context_effects(
331 None,
332 expr.span,
333 overloaded_deref.method_call(self.tcx),
334 self.tcx.mk_args(&[expr_ty.into()]),
335 );
336 }
337 Adjust::Deref(DerefAdjustKind::Builtin) => {
338 }
340 Adjust::Deref(DerefAdjustKind::Pin) => {
341 }
343 Adjust::Pointer(_pointer_coercion) => {
344 }
346 Adjust::GenericReborrow(_) => {
347 }
349 Adjust::Borrow(_) => {
350 }
352 }
353
354 expr_ty = a.target;
355 }
356
357 let autoborrow_mut = adj.iter().any(|adj| {
358 matches!(
359 adj,
360 &Adjustment {
361 kind: Adjust::Borrow(AutoBorrow::Ref(AutoBorrowMutability::Mut { .. })),
362 ..
363 }
364 )
365 });
366
367 match self.typeck_results.borrow_mut().adjustments_mut().entry(expr.hir_id) {
368 Entry::Vacant(entry) => {
369 entry.insert(adj);
370 }
371 Entry::Occupied(mut entry) => {
372 debug!(" - composing on top of {:?}", entry.get());
373 match (&mut entry.get_mut()[..], &adj[..]) {
374 (
375 [Adjustment { kind: Adjust::NeverToAny, target }],
376 &[.., Adjustment { target: new_target, .. }],
377 ) => {
378 *target = new_target;
386 }
387
388 (
389 &mut [
390 Adjustment { kind: Adjust::Deref(_), .. },
391 Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(..)), .. },
392 ],
393 &[
394 Adjustment { kind: Adjust::Deref(_), .. },
395 .., ],
397 ) => {
398 *entry.get_mut() = adj;
400 }
401
402 _ => {
403 self.dcx().span_delayed_bug(
406 expr.span,
407 format!(
408 "while adjusting {:?}, can't compose {:?} and {:?}",
409 expr,
410 entry.get(),
411 adj
412 ),
413 );
414
415 *entry.get_mut() = adj;
416 }
417 }
418 }
419 }
420
421 if autoborrow_mut {
425 self.convert_place_derefs_to_mutable(expr);
426 }
427 }
428
429 pub(crate) fn normalize<T>(&self, span: Span, value: Unnormalized<'tcx, T>) -> T
430 where
431 T: TypeFoldable<TyCtxt<'tcx>>,
432 {
433 self.register_infer_ok_obligations(
434 self.at(&self.misc(span), self.param_env).normalize(value),
435 )
436 }
437
438 pub(crate) fn require_type_meets(
439 &self,
440 ty: Ty<'tcx>,
441 span: Span,
442 code: traits::ObligationCauseCode<'tcx>,
443 def_id: DefId,
444 ) {
445 self.register_bound(ty, def_id, self.cause(span, code));
446 }
447
448 pub(crate) fn require_type_is_sized(
449 &self,
450 ty: Ty<'tcx>,
451 span: Span,
452 code: traits::ObligationCauseCode<'tcx>,
453 ) {
454 if !ty.references_error() {
455 let lang_item = self.tcx.require_lang_item(LangItem::Sized, span);
456 self.require_type_meets(ty, span, code, lang_item);
457 }
458 }
459
460 pub(crate) fn require_type_is_sized_deferred(
461 &self,
462 ty: Ty<'tcx>,
463 span: Span,
464 code: traits::ObligationCauseCode<'tcx>,
465 ) {
466 if !ty.references_error() {
467 self.deferred_sized_obligations.borrow_mut().push((ty, span, code));
468 }
469 }
470
471 pub(crate) fn require_type_has_static_alignment(&self, ty: Ty<'tcx>, span: Span) {
472 if !ty.references_error() {
473 let tail = self.tcx.struct_tail_raw(
474 ty,
475 &self.misc(span),
476 |ty| self.normalize(span, ty),
477 || {},
478 );
479 if tail.has_trivial_sizedness(self.tcx, SizedTraitKind::Sized)
481 || #[allow(non_exhaustive_omitted_patterns)] match tail.kind() {
ty::Slice(..) => true,
_ => false,
}matches!(tail.kind(), ty::Slice(..))
482 {
483 } else {
485 let lang_item = self.tcx.require_lang_item(LangItem::Sized, span);
487 self.require_type_meets(ty, span, ObligationCauseCode::Misc, lang_item);
488 }
489 }
490 }
491
492 pub(crate) fn register_bound(
493 &self,
494 ty: Ty<'tcx>,
495 def_id: DefId,
496 cause: traits::ObligationCause<'tcx>,
497 ) {
498 if !ty.references_error() {
499 self.fulfillment_cx.borrow_mut().register_bound(
500 self,
501 self.param_env,
502 ty,
503 def_id,
504 cause,
505 );
506 }
507 }
508
509 pub(crate) fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> LoweredTy<'tcx> {
510 let ty = self.lowerer().lower_ty(hir_ty);
511 self.register_wf_obligation(ty.into(), hir_ty.span, ObligationCauseCode::WellFormed(None));
512 LoweredTy::from_raw(self, hir_ty.span, ty)
513 }
514
515 pub(crate) fn collect_impl_trait_clauses_from_hir_ty(
519 &self,
520 hir_ty: &'tcx hir::Ty<'tcx>,
521 ) -> ty::Clauses<'tcx> {
522 struct CollectClauses<'a, 'tcx> {
523 clauses: Vec<ty::Clause<'tcx>>,
524 fcx: &'a FnCtxt<'a, 'tcx>,
525 }
526
527 impl<'tcx> intravisit::Visitor<'tcx> for CollectClauses<'_, 'tcx> {
528 fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx, AmbigArg>) {
529 if let Some(clauses) = self.fcx.trait_ascriptions.borrow().get(&ty.hir_id.local_id)
530 {
531 self.clauses.extend(clauses.iter().cloned());
532 }
533 intravisit::walk_ty(self, ty)
534 }
535 }
536
537 let mut clauses = CollectClauses { clauses: ::alloc::vec::Vec::new()vec![], fcx: self };
538 clauses.visit_ty_unambig(hir_ty);
539 self.tcx.mk_clauses(&clauses.clauses)
540 }
541
542 #[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("lower_ty_saving_user_provided_ty",
"rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
::tracing_core::__macro_support::Option::Some(542u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
::tracing_core::field::FieldSet::new(&[],
::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,
&{ meta.fields().value_set(&[]) })
} 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: Ty<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
let ty = self.lower_ty(hir_ty);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs:545",
"rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
::tracing_core::__macro_support::Option::Some(545u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
::tracing_core::field::FieldSet::new(&["ty"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&ty) as
&dyn Value))])
});
} else { ; }
};
if Self::can_contain_user_lifetime_bounds(ty.raw) {
let c_ty =
self.canonicalize_response(ty::UserType::new(ty::UserTypeKind::Ty(ty.raw)));
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs:549",
"rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
::tracing_core::__macro_support::Option::Some(549u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
::tracing_core::field::FieldSet::new(&["c_ty"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&c_ty) as
&dyn Value))])
});
} else { ; }
};
self.typeck_results.borrow_mut().user_provided_types_mut().insert(hir_ty.hir_id,
c_ty);
}
ty.normalized
}
}
}#[instrument(level = "debug", skip_all)]
543 pub(crate) fn lower_ty_saving_user_provided_ty(&self, hir_ty: &'tcx hir::Ty<'tcx>) -> Ty<'tcx> {
544 let ty = self.lower_ty(hir_ty);
545 debug!(?ty);
546
547 if Self::can_contain_user_lifetime_bounds(ty.raw) {
548 let c_ty = self.canonicalize_response(ty::UserType::new(ty::UserTypeKind::Ty(ty.raw)));
549 debug!(?c_ty);
550 self.typeck_results.borrow_mut().user_provided_types_mut().insert(hir_ty.hir_id, c_ty);
551 }
552
553 ty.normalized
554 }
555
556 pub(super) fn user_args_for_adt(ty: LoweredTy<'tcx>) -> UserArgs<'tcx> {
557 match (ty.raw.kind(), ty.normalized.kind()) {
558 (ty::Adt(_, args), _) => UserArgs { args, user_self_ty: None },
559 (_, ty::Adt(adt, args)) => UserArgs {
560 args,
561 user_self_ty: Some(UserSelfTy { impl_def_id: adt.did(), self_ty: ty.raw }),
562 },
563 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("non-adt type {0:?}", ty))bug!("non-adt type {:?}", ty),
564 }
565 }
566
567 pub(crate) fn lower_const_arg(
568 &self,
569 const_arg: &'tcx hir::ConstArg<'tcx>,
570 ty: Ty<'tcx>,
571 ) -> ty::Const<'tcx> {
572 let ct = self.lowerer().lower_const_arg(const_arg, ty);
573 self.register_wf_obligation(
574 ct.into(),
575 self.tcx.hir_span(const_arg.hir_id),
576 ObligationCauseCode::WellFormed(None),
577 );
578 ct
579 }
580
581 fn can_contain_user_lifetime_bounds<T>(t: T) -> bool
589 where
590 T: TypeVisitable<TyCtxt<'tcx>>,
591 {
592 t.has_free_regions() || t.has_aliases() || t.has_infer_types() || t.has_param()
594 }
595
596 pub(crate) fn node_ty(&self, id: HirId) -> Ty<'tcx> {
597 match self.typeck_results.borrow().node_types().get(id) {
598 Some(&t) => t,
599 None if let Some(e) = self.tainted_by_errors() => Ty::new_error(self.tcx, e),
600 None => {
601 ::rustc_middle::util::bug::bug_fmt(format_args!("no type for node {0} in fcx {1}",
self.tcx.hir_id_to_string(id), self.tag()));bug!("no type for node {} in fcx {}", self.tcx.hir_id_to_string(id), self.tag());
602 }
603 }
604 }
605
606 pub(crate) fn node_ty_opt(&self, id: HirId) -> Option<Ty<'tcx>> {
607 match self.typeck_results.borrow().node_types().get(id) {
608 Some(&t) => Some(t),
609 None if let Some(e) = self.tainted_by_errors() => Some(Ty::new_error(self.tcx, e)),
610 None => None,
611 }
612 }
613
614 pub(crate) fn register_wf_obligation(
616 &self,
617 term: ty::Term<'tcx>,
618 span: Span,
619 code: traits::ObligationCauseCode<'tcx>,
620 ) {
621 let cause = self.cause(span, code);
623 self.register_predicate(traits::Obligation::new(
624 self.tcx,
625 cause,
626 self.param_env,
627 ty::ClauseKind::WellFormed(term),
628 ));
629 }
630
631 pub(crate) fn add_wf_bounds(&self, args: GenericArgsRef<'tcx>, span: Span) {
633 for term in args.iter().filter_map(ty::GenericArg::as_term) {
634 self.register_wf_obligation(term, span, ObligationCauseCode::WellFormed(None));
635 }
636 }
637
638 pub(crate) fn field_ty(
642 &self,
643 span: Span,
644 field: &'tcx ty::FieldDef,
645 args: GenericArgsRef<'tcx>,
646 ) -> Ty<'tcx> {
647 self.normalize(span, field.ty(self.tcx, args))
648 }
649
650 #[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("drain_stalled_coroutine_obligations",
"rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
::tracing_core::__macro_support::Option::Some(651u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
::tracing_core::field::FieldSet::new(&[],
::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,
&{ meta.fields().value_set(&[]) })
} 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;
}
{
self.select_obligations_where_possible(|_| {});
let defining_opaque_types_and_generators =
match self.typing_mode() {
ty::TypingMode::Analysis {
defining_opaque_types_and_generators } => {
defining_opaque_types_and_generators
}
ty::TypingMode::Coherence | ty::TypingMode::Borrowck { .. }
| ty::TypingMode::PostBorrowckAnalysis { .. } |
ty::TypingMode::PostAnalysis => {
::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
}
};
if defining_opaque_types_and_generators.iter().any(|def_id|
self.tcx.is_coroutine(def_id.to_def_id())) {
self.typeck_results.borrow_mut().coroutine_stalled_predicates.extend(self.fulfillment_cx.borrow_mut().drain_stalled_obligations_for_coroutines(&self.infcx).into_iter().map(|o|
(o.predicate, o.cause)));
}
}
}
}#[instrument(level = "debug", skip(self))]
652 pub(crate) fn drain_stalled_coroutine_obligations(&self) {
653 self.select_obligations_where_possible(|_| {});
658
659 let defining_opaque_types_and_generators = match self.typing_mode() {
660 ty::TypingMode::Analysis { defining_opaque_types_and_generators } => {
661 defining_opaque_types_and_generators
662 }
663 ty::TypingMode::Coherence
664 | ty::TypingMode::Borrowck { .. }
665 | ty::TypingMode::PostBorrowckAnalysis { .. }
666 | ty::TypingMode::PostAnalysis => {
667 bug!()
668 }
669 };
670
671 if defining_opaque_types_and_generators
672 .iter()
673 .any(|def_id| self.tcx.is_coroutine(def_id.to_def_id()))
674 {
675 self.typeck_results.borrow_mut().coroutine_stalled_predicates.extend(
676 self.fulfillment_cx
677 .borrow_mut()
678 .drain_stalled_obligations_for_coroutines(&self.infcx)
679 .into_iter()
680 .map(|o| (o.predicate, o.cause)),
681 );
682 }
683 }
684
685 #[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("report_ambiguity_errors",
"rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
::tracing_core::__macro_support::Option::Some(685u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
::tracing_core::field::FieldSet::new(&[],
::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,
&{ meta.fields().value_set(&[]) })
} 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;
}
{
let mut errors =
self.fulfillment_cx.borrow_mut().collect_remaining_errors(self);
if !errors.is_empty() {
self.adjust_fulfillment_errors_for_expr_obligation(&mut errors);
self.err_ctxt().report_fulfillment_errors(errors);
}
}
}
}#[instrument(skip(self), level = "debug")]
686 pub(crate) fn report_ambiguity_errors(&self) {
687 let mut errors = self.fulfillment_cx.borrow_mut().collect_remaining_errors(self);
688
689 if !errors.is_empty() {
690 self.adjust_fulfillment_errors_for_expr_obligation(&mut errors);
691 self.err_ctxt().report_fulfillment_errors(errors);
692 }
693 }
694
695 pub(crate) fn select_obligations_where_possible(
697 &self,
698 mutate_fulfillment_errors: impl Fn(&mut Vec<traits::FulfillmentError<'tcx>>),
699 ) {
700 let mut result = self.fulfillment_cx.borrow_mut().try_evaluate_obligations(self);
701 if !result.is_empty() {
702 mutate_fulfillment_errors(&mut result);
703 self.adjust_fulfillment_errors_for_expr_obligation(&mut result);
704 self.err_ctxt().report_fulfillment_errors(result);
705 }
706 }
707
708 pub(crate) fn make_overloaded_place_return_type(&self, method: MethodCallee<'tcx>) -> Ty<'tcx> {
713 let ret_ty = method.sig.output();
715
716 ret_ty.builtin_deref(true).unwrap()
718 }
719
720 pub(crate) fn type_var_is_sized(&self, self_ty: ty::TyVid) -> bool {
721 let sized_did = self.tcx.lang_items().sized_trait();
722 self.obligations_for_self_ty(self_ty).into_iter().any(|obligation| {
723 match obligation.predicate.kind().skip_binder() {
724 ty::PredicateKind::Clause(ty::ClauseKind::Trait(data)) => {
725 Some(data.def_id()) == sized_did
726 }
727 _ => false,
728 }
729 })
730 }
731
732 pub(crate) fn err_args(&self, len: usize, guar: ErrorGuaranteed) -> Vec<Ty<'tcx>> {
733 let ty_error = Ty::new_error(self.tcx, guar);
734 ::alloc::vec::from_elem(ty_error, len)vec![ty_error; len]
735 }
736
737 x;#[instrument(level = "trace", skip(self), ret)]
740 pub(crate) fn resolve_ty_and_res_fully_qualified_call(
741 &self,
742 qpath: &'tcx QPath<'tcx>,
743 hir_id: HirId,
744 span: Span,
745 ) -> (Res, Option<LoweredTy<'tcx>>, &'tcx [hir::PathSegment<'tcx>]) {
746 let (ty, qself, item_segment) = match *qpath {
747 QPath::Resolved(ref opt_qself, path) => {
748 return (
749 path.res,
750 opt_qself.as_ref().map(|qself| self.lower_ty(qself)),
751 path.segments,
752 );
753 }
754 QPath::TypeRelative(ref qself, ref segment) => {
755 let ty = self.lowerer().lower_ty(qself);
765 (LoweredTy::from_raw(self, span, ty), qself, segment)
766 }
767 };
768
769 self.register_wf_obligation(
770 ty.raw.into(),
771 qself.span,
772 ObligationCauseCode::WellFormed(None),
773 );
774 self.select_obligations_where_possible(|_| {});
775
776 if let Some(&cached_result) = self.typeck_results.borrow().type_dependent_defs().get(hir_id)
777 {
778 let def = cached_result.map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id));
781 return (def, Some(ty), slice::from_ref(&**item_segment));
782 }
783 let item_name = item_segment.ident;
784 let result = self
785 .resolve_fully_qualified_call(span, item_name, ty.normalized, qself.span, hir_id)
786 .or_else(|error| {
787 let guar = self
788 .dcx()
789 .span_delayed_bug(span, "method resolution should've emitted an error");
790 let result = match error {
791 method::MethodError::PrivateMatch(kind, def_id, _) => Ok((kind, def_id)),
792 _ => Err(guar),
793 };
794
795 let trait_missing_method =
796 matches!(error, method::MethodError::NoMatch(_)) && ty.normalized.is_trait();
797 self.report_method_error(
798 hir_id,
799 ty.normalized,
800 error,
801 Expectation::NoExpectation,
802 trait_missing_method && span.edition().at_least_rust_2021(), );
804
805 result
806 });
807
808 self.write_resolution(hir_id, result);
810 (
811 result.map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)),
812 Some(ty),
813 slice::from_ref(&**item_segment),
814 )
815 }
816
817 pub(crate) fn get_fn_decl(
819 &self,
820 blk_id: HirId,
821 ) -> Option<(LocalDefId, &'tcx hir::FnDecl<'tcx>)> {
822 self.tcx.hir_get_fn_id_for_return_block(blk_id).and_then(|item_id| {
825 match self.tcx.hir_node(item_id) {
826 Node::Item(&hir::Item {
827 kind: hir::ItemKind::Fn { sig, .. }, owner_id, ..
828 }) => Some((owner_id.def_id, sig.decl)),
829 Node::TraitItem(&hir::TraitItem {
830 kind: hir::TraitItemKind::Fn(ref sig, ..),
831 owner_id,
832 ..
833 }) => Some((owner_id.def_id, sig.decl)),
834 Node::ImplItem(&hir::ImplItem {
835 kind: hir::ImplItemKind::Fn(ref sig, ..),
836 owner_id,
837 ..
838 }) => Some((owner_id.def_id, sig.decl)),
839 Node::Expr(&hir::Expr {
840 hir_id,
841 kind: hir::ExprKind::Closure(&hir::Closure { def_id, kind, fn_decl, .. }),
842 ..
843 }) => {
844 match kind {
845 hir::ClosureKind::CoroutineClosure(_) => {
846 return None;
848 }
849 hir::ClosureKind::Closure => Some((def_id, fn_decl)),
850 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
851 _,
852 hir::CoroutineSource::Fn,
853 )) => {
854 let (sig, owner_id) = match self.tcx.parent_hir_node(hir_id) {
855 Node::Item(&hir::Item {
856 kind: hir::ItemKind::Fn { ref sig, .. },
857 owner_id,
858 ..
859 }) => (sig, owner_id),
860 Node::TraitItem(&hir::TraitItem {
861 kind: hir::TraitItemKind::Fn(ref sig, ..),
862 owner_id,
863 ..
864 }) => (sig, owner_id),
865 Node::ImplItem(&hir::ImplItem {
866 kind: hir::ImplItemKind::Fn(ref sig, ..),
867 owner_id,
868 ..
869 }) => (sig, owner_id),
870 _ => return None,
871 };
872 Some((owner_id.def_id, sig.decl))
873 }
874 _ => None,
875 }
876 }
877 _ => None,
878 }
879 })
880 }
881
882 pub(crate) fn note_internal_mutation_in_method(
883 &self,
884 err: &mut Diag<'_>,
885 expr: &hir::Expr<'_>,
886 expected: Option<Ty<'tcx>>,
887 found: Ty<'tcx>,
888 ) {
889 if found != self.tcx.types.unit {
890 return;
891 }
892
893 let ExprKind::MethodCall(path_segment, rcvr, ..) = expr.kind else {
894 return;
895 };
896
897 let rcvr_has_the_expected_type = self
898 .typeck_results
899 .borrow()
900 .expr_ty_adjusted_opt(rcvr)
901 .zip(expected)
902 .is_some_and(|(ty, expected_ty)| expected_ty.peel_refs() == ty.peel_refs());
903
904 let prev_call_mutates_and_returns_unit = || {
905 self.typeck_results
906 .borrow()
907 .type_dependent_def_id(expr.hir_id)
908 .map(|def_id| self.tcx.fn_sig(def_id).skip_binder().skip_binder())
909 .and_then(|sig| sig.inputs_and_output.split_last())
910 .is_some_and(|(output, inputs)| {
911 output.is_unit()
912 && inputs
913 .get(0)
914 .and_then(|self_ty| self_ty.ref_mutability())
915 .is_some_and(rustc_ast::Mutability::is_mut)
916 })
917 };
918
919 if !(rcvr_has_the_expected_type || prev_call_mutates_and_returns_unit()) {
920 return;
921 }
922
923 let mut sp = MultiSpan::from_span(path_segment.ident.span);
924 sp.push_span_label(
925 path_segment.ident.span,
926 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this call modifies {0} in-place",
match rcvr.kind {
ExprKind::Path(QPath::Resolved(None, hir::Path {
segments: [segment], .. })) =>
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", segment.ident))
}),
_ => "its receiver".to_string(),
}))
})format!(
927 "this call modifies {} in-place",
928 match rcvr.kind {
929 ExprKind::Path(QPath::Resolved(
930 None,
931 hir::Path { segments: [segment], .. },
932 )) => format!("`{}`", segment.ident),
933 _ => "its receiver".to_string(),
934 }
935 ),
936 );
937
938 let modifies_rcvr_note =
939 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("method `{0}` modifies its receiver in-place",
path_segment.ident))
})format!("method `{}` modifies its receiver in-place", path_segment.ident);
940 if rcvr_has_the_expected_type {
941 sp.push_span_label(
942 rcvr.span,
943 "you probably want to use this value after calling the method...",
944 );
945 err.span_note(sp, modifies_rcvr_note);
946 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("...instead of the `()` output of method `{0}`",
path_segment.ident))
})format!("...instead of the `()` output of method `{}`", path_segment.ident));
947 } else if let ExprKind::MethodCall(..) = rcvr.kind {
948 err.span_note(
949 sp,
950 modifies_rcvr_note + ", it is not meant to be used in method chains.",
951 );
952 } else {
953 err.span_note(sp, modifies_rcvr_note);
954 }
955 }
956
957 #[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("instantiate_value_path",
"rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
::tracing_core::__macro_support::Option::Some(959u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
::tracing_core::field::FieldSet::new(&["segments",
"self_ty", "res", "path_span", "hir_id"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&segments)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&res)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path_span)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hir_id)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: (Ty<'tcx>, Res) = loop {};
return __tracing_attr_fake_return;
}
{
let tcx = self.tcx;
let generic_segments =
match res {
Res::Local(_) | Res::SelfCtor(_) =>
::alloc::vec::Vec::new(),
Res::Def(kind, def_id) =>
self.lowerer().probe_generic_path_segments(segments,
self_ty.map(|ty| ty.raw), kind, def_id, span),
Res::Err => {
return (Ty::new_error(tcx,
tcx.dcx().span_delayed_bug(span,
"could not resolve path {:?}")), res);
}
_ =>
::rustc_middle::util::bug::bug_fmt(format_args!("instantiate_value_path on {0:?}",
res)),
};
let mut user_self_ty = None;
let mut is_alias_variant_ctor = false;
let mut err_extend = GenericsArgsErrExtend::None;
match res {
Res::Def(DefKind::Ctor(CtorOf::Variant, _), _) if
let Some(self_ty) = self_ty => {
let adt_def = self_ty.normalized.ty_adt_def().unwrap();
user_self_ty =
Some(UserSelfTy {
impl_def_id: adt_def.did(),
self_ty: self_ty.raw,
});
is_alias_variant_ctor = true;
err_extend = GenericsArgsErrExtend::DefVariant(segments);
}
Res::Def(DefKind::Ctor(CtorOf::Variant, _), _) => {
err_extend = GenericsArgsErrExtend::DefVariant(segments);
}
Res::Def(DefKind::AssocFn | DefKind::AssocConst { .. },
def_id) => {
let assoc_item = tcx.associated_item(def_id);
let container = assoc_item.container;
let container_id = assoc_item.container_id(tcx);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs:1010",
"rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
::tracing_core::__macro_support::Option::Some(1010u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
::tracing_core::field::FieldSet::new(&["def_id",
"container", "container_id"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&def_id) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&container)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&container_id)
as &dyn Value))])
});
} else { ; }
};
match container {
ty::AssocContainer::Trait => {
let arg_span =
if let hir::Node::Expr(call_expr) =
self.tcx.parent_hir_node(hir_id) &&
let hir::ExprKind::Call(_, args) = call_expr.kind &&
let Some(first_arg) = args.first() {
let mut arg = first_arg;
while let hir::ExprKind::AddrOf(_, _, inner) = arg.kind {
arg = inner;
}
Some(arg.span)
} else { None };
if let Err(e) =
callee::check_legal_trait_for_method_call(tcx, path_span,
arg_span, span, container_id, self.body_id.to_def_id()) {
self.set_tainted_by_errors(e);
}
}
ty::AssocContainer::InherentImpl |
ty::AssocContainer::TraitImpl(_) => {
if segments.len() == 1 {
user_self_ty =
self_ty.map(|self_ty|
UserSelfTy {
impl_def_id: container_id,
self_ty: self_ty.raw,
});
}
}
}
}
_ => {}
}
let indices: FxHashSet<_> =
generic_segments.iter().map(|GenericPathSegment(_, index)|
index).collect();
let generics_err =
self.lowerer().prohibit_generic_args(segments.iter().enumerate().filter_map(|(index,
seg)|
{
if !indices.contains(&index) || is_alias_variant_ctor {
Some(seg)
} else { None }
}), err_extend);
if let Err(e) =
self.lowerer().check_param_res_if_mcg_for_instantiate_value_path(res,
span) {
return (Ty::new_error(self.tcx, e), res);
}
if let Res::Local(hid) = res {
let ty = self.local_ty(span, hid);
let ty = self.normalize(span, Unnormalized::new_wip(ty));
return (ty, res);
}
if let Err(_) = generics_err { user_self_ty = None; }
let mut infer_args_for_err = None;
let mut explicit_late_bound = ExplicitLateBound::No;
for &GenericPathSegment(def_id, index) in &generic_segments {
let seg = &segments[index];
let generics = tcx.generics_of(def_id);
let arg_count =
check_generic_arg_count_for_value_path(self, def_id,
generics, seg, IsMethodCall::No);
if let ExplicitLateBound::Yes = arg_count.explicit_late_bound
{
explicit_late_bound = ExplicitLateBound::Yes;
}
if let Err(GenericArgCountMismatch { reported, .. }) =
arg_count.correct {
infer_args_for_err.get_or_insert_with(||
(reported, FxHashSet::default())).1.insert(index);
self.set_tainted_by_errors(reported);
}
}
let has_self =
generic_segments.last().is_some_and(|GenericPathSegment(def_id,
_)| tcx.generics_of(*def_id).has_self);
let (res, implicit_args) =
if let Res::Def(DefKind::ConstParam, def) = res {
(res,
Some(ty::GenericArgs::identity_for_item(tcx,
tcx.parent(def))))
} else if let Res::SelfCtor(impl_def_id) = res {
let ty =
LoweredTy::from_raw(self, span,
tcx.at(span).type_of(impl_def_id).instantiate_identity().skip_norm_wip());
if std::iter::successors(Some(self.body_id.to_def_id()),
|&def_id|
{
self.tcx.generics_of(def_id).parent
}).all(|def_id| def_id != impl_def_id) {
let sugg =
ty.normalized.ty_adt_def().map(|def|
errors::ReplaceWithName {
span: path_span,
name: self.tcx.item_name(def.did()).to_ident_string(),
});
let item =
match self.tcx.hir_node_by_def_id(self.tcx.hir_get_parent_item(hir_id).def_id)
{
hir::Node::Item(item) =>
Some(errors::InnerItem {
span: item.kind.ident().map(|i| i.span).unwrap_or(item.span),
}),
_ => None,
};
if ty.raw.has_param() {
let guar =
self.dcx().emit_err(errors::SelfCtorFromOuterItem {
span: path_span,
impl_span: tcx.def_span(impl_def_id),
sugg,
item,
});
return (Ty::new_error(self.tcx, guar), res);
} else {
self.tcx.emit_node_span_lint(SELF_CONSTRUCTOR_FROM_OUTER_ITEM,
hir_id, path_span,
errors::SelfCtorFromOuterItemLint {
impl_span: tcx.def_span(impl_def_id),
sugg,
item,
});
}
}
match ty.normalized.ty_adt_def() {
Some(adt_def) if adt_def.has_ctor() => {
let (ctor_kind, ctor_def_id) =
adt_def.non_enum_variant().ctor.unwrap();
let vis = tcx.visibility(ctor_def_id);
if !vis.is_accessible_from(tcx.parent_module(hir_id).to_def_id(),
tcx) {
self.dcx().emit_err(CtorIsPrivate {
span,
def: tcx.def_path_str(adt_def.did()),
});
}
let new_res =
Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind),
ctor_def_id);
let user_args = Self::user_args_for_adt(ty);
user_self_ty = user_args.user_self_ty;
(new_res, Some(user_args.args))
}
_ => {
let mut err =
self.dcx().struct_span_err(span,
"the `Self` constructor can only be used with tuple or unit structs");
if let Some(adt_def) = ty.normalized.ty_adt_def() {
match adt_def.adt_kind() {
AdtKind::Enum => {
err.help("did you mean to use one of the enum's variants?");
}
AdtKind::Struct | AdtKind::Union => {
err.span_suggestion(span, "use curly brackets",
"Self { /* fields */ }", Applicability::HasPlaceholders);
}
}
}
let reported = err.emit();
return (Ty::new_error(tcx, reported), res);
}
}
} else { (res, None) };
let def_id = res.def_id();
let (correct, infer_args_for_err) =
match infer_args_for_err {
Some((reported, args)) => {
(Err(GenericArgCountMismatch {
reported,
invalid_args: ::alloc::vec::Vec::new(),
}), args)
}
None => (Ok(()), Default::default()),
};
let arg_count =
GenericArgCountResult { explicit_late_bound, correct };
struct CtorGenericArgsCtxt<'a, 'tcx> {
fcx: &'a FnCtxt<'a, 'tcx>,
span: Span,
generic_segments: &'a [GenericPathSegment],
infer_args_for_err: &'a FxHashSet<usize>,
segments: &'tcx [hir::PathSegment<'tcx>],
}
impl<'a, 'tcx> GenericArgsLowerer<'a, 'tcx> for
CtorGenericArgsCtxt<'a, 'tcx> {
fn args_for_def_id(&mut self, def_id: DefId)
-> (Option<&'a hir::GenericArgs<'tcx>>, bool) {
if let Some(&GenericPathSegment(_, index)) =
self.generic_segments.iter().find(|&GenericPathSegment(did,
_)| *did == def_id) {
if !self.infer_args_for_err.contains(&index) {
if let Some(data) = self.segments[index].args {
return (Some(data), self.segments[index].infer_args);
}
}
return (None, self.segments[index].infer_args);
}
(None, true)
}
fn provided_kind(&mut self,
preceding_args: &[ty::GenericArg<'tcx>],
param: &ty::GenericParamDef, arg: &GenericArg<'tcx>)
-> ty::GenericArg<'tcx> {
match (¶m.kind, arg) {
(GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) =>
self.fcx.lowerer().lower_lifetime(lt,
RegionInferReason::Param(param)).into(),
(GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) =>
{
self.fcx.lower_ty(ty.as_unambig_ty()).raw.into()
}
(GenericParamDefKind::Type { .. }, GenericArg::Infer(inf))
=> {
self.fcx.lower_ty(&inf.to_ty()).raw.into()
}
(GenericParamDefKind::Const { .. }, GenericArg::Const(ct))
=>
self.fcx.lower_const_arg(ct.as_unambig_ct(),
self.fcx.tcx.type_of(param.def_id).instantiate(self.fcx.tcx,
preceding_args).skip_norm_wip()).into(),
(&GenericParamDefKind::Const { .. }, GenericArg::Infer(inf))
=> {
self.fcx.ct_infer(Some(param), inf.span).into()
}
_ =>
::core::panicking::panic("internal error: entered unreachable code"),
}
}
fn inferred_kind(&mut self,
preceding_args: &[ty::GenericArg<'tcx>],
param: &ty::GenericParamDef, infer_args: bool)
-> ty::GenericArg<'tcx> {
let tcx = self.fcx.tcx();
if !infer_args &&
let Some(default) = param.default_value(tcx) {
return default.instantiate(tcx,
preceding_args).skip_norm_wip();
}
self.fcx.var_for_def(self.span, param)
}
}
let args_raw =
implicit_args.unwrap_or_else(||
{
lower_generic_args(self, def_id, &[], has_self,
self_ty.map(|s| s.raw), &arg_count,
&mut CtorGenericArgsCtxt {
fcx: self,
span,
generic_segments: &generic_segments,
infer_args_for_err: &infer_args_for_err,
segments,
})
});
let args_for_user_type =
if let Res::Def(DefKind::AssocConst { .. }, def_id) = res {
self.transform_args_for_inherent_type_const(def_id,
args_raw)
} else { args_raw };
self.write_user_type_annotation_from_args(hir_id, def_id,
args_for_user_type, user_self_ty);
let args = self.normalize(span, Unnormalized::new_wip(args_raw));
self.add_required_obligations_for_hir(span, def_id, args, hir_id);
let ty = tcx.type_of(def_id);
if !!args.has_escaping_bound_vars() {
::core::panicking::panic("assertion failed: !args.has_escaping_bound_vars()")
};
if !!ty.skip_binder().has_escaping_bound_vars() {
::core::panicking::panic("assertion failed: !ty.skip_binder().has_escaping_bound_vars()")
};
let ty_instantiated =
self.normalize(span, ty.instantiate(tcx, args));
if let Some(UserSelfTy { impl_def_id, self_ty }) = user_self_ty {
let impl_ty =
self.normalize(span,
tcx.type_of(impl_def_id).instantiate(tcx, args));
let self_ty =
self.normalize(span, Unnormalized::new_wip(self_ty));
match self.at(&self.misc(span),
self.param_env).eq(DefineOpaqueTypes::Yes, impl_ty, self_ty)
{
Ok(ok) => self.register_infer_ok_obligations(ok),
Err(_) => {
self.dcx().span_bug(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("instantiate_value_path: (UFCS) {0:?} was a subtype of {1:?} but now is not?",
self_ty, impl_ty))
}));
}
}
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs:1398",
"rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
::tracing_core::__macro_support::Option::Some(1398u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("instantiate_value_path: type of {0:?} is {1:?}",
hir_id, ty_instantiated) as &dyn Value))])
});
} else { ; }
};
let args =
if let Res::Def(DefKind::AssocConst { .. }, def_id) = res {
self.transform_args_for_inherent_type_const(def_id, args)
} else { args };
self.write_args(hir_id, args);
(ty_instantiated, res)
}
}
}#[instrument(skip(self, span), level = "debug")]
960 pub(crate) fn instantiate_value_path(
961 &self,
962 segments: &'tcx [hir::PathSegment<'tcx>],
963 self_ty: Option<LoweredTy<'tcx>>,
964 res: Res,
965 span: Span,
966 path_span: Span,
967 hir_id: HirId,
968 ) -> (Ty<'tcx>, Res) {
969 let tcx = self.tcx;
970
971 let generic_segments = match res {
972 Res::Local(_) | Res::SelfCtor(_) => vec![],
973 Res::Def(kind, def_id) => self.lowerer().probe_generic_path_segments(
974 segments,
975 self_ty.map(|ty| ty.raw),
976 kind,
977 def_id,
978 span,
979 ),
980 Res::Err => {
981 return (
982 Ty::new_error(
983 tcx,
984 tcx.dcx().span_delayed_bug(span, "could not resolve path {:?}"),
985 ),
986 res,
987 );
988 }
989 _ => bug!("instantiate_value_path on {:?}", res),
990 };
991
992 let mut user_self_ty = None;
993 let mut is_alias_variant_ctor = false;
994 let mut err_extend = GenericsArgsErrExtend::None;
995 match res {
996 Res::Def(DefKind::Ctor(CtorOf::Variant, _), _) if let Some(self_ty) = self_ty => {
997 let adt_def = self_ty.normalized.ty_adt_def().unwrap();
998 user_self_ty =
999 Some(UserSelfTy { impl_def_id: adt_def.did(), self_ty: self_ty.raw });
1000 is_alias_variant_ctor = true;
1001 err_extend = GenericsArgsErrExtend::DefVariant(segments);
1002 }
1003 Res::Def(DefKind::Ctor(CtorOf::Variant, _), _) => {
1004 err_extend = GenericsArgsErrExtend::DefVariant(segments);
1005 }
1006 Res::Def(DefKind::AssocFn | DefKind::AssocConst { .. }, def_id) => {
1007 let assoc_item = tcx.associated_item(def_id);
1008 let container = assoc_item.container;
1009 let container_id = assoc_item.container_id(tcx);
1010 debug!(?def_id, ?container, ?container_id);
1011 match container {
1012 ty::AssocContainer::Trait => {
1013 let arg_span = if let hir::Node::Expr(call_expr) =
1014 self.tcx.parent_hir_node(hir_id)
1015 && let hir::ExprKind::Call(_, args) = call_expr.kind
1016 && let Some(first_arg) = args.first()
1017 {
1018 let mut arg = first_arg;
1019 while let hir::ExprKind::AddrOf(_, _, inner) = arg.kind {
1020 arg = inner;
1021 }
1022 Some(arg.span)
1023 } else {
1024 None
1025 };
1026
1027 if let Err(e) = callee::check_legal_trait_for_method_call(
1028 tcx,
1029 path_span,
1030 arg_span,
1031 span,
1032 container_id,
1033 self.body_id.to_def_id(),
1034 ) {
1035 self.set_tainted_by_errors(e);
1036 }
1037 }
1038 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
1039 if segments.len() == 1 {
1040 user_self_ty = self_ty.map(|self_ty| UserSelfTy {
1047 impl_def_id: container_id,
1048 self_ty: self_ty.raw,
1049 });
1050 }
1051 }
1052 }
1053 }
1054 _ => {}
1055 }
1056
1057 let indices: FxHashSet<_> =
1063 generic_segments.iter().map(|GenericPathSegment(_, index)| index).collect();
1064 let generics_err = self.lowerer().prohibit_generic_args(
1065 segments.iter().enumerate().filter_map(|(index, seg)| {
1066 if !indices.contains(&index) || is_alias_variant_ctor { Some(seg) } else { None }
1067 }),
1068 err_extend,
1069 );
1070
1071 if let Err(e) = self.lowerer().check_param_res_if_mcg_for_instantiate_value_path(res, span)
1072 {
1073 return (Ty::new_error(self.tcx, e), res);
1074 }
1075
1076 if let Res::Local(hid) = res {
1077 let ty = self.local_ty(span, hid);
1078 let ty = self.normalize(span, Unnormalized::new_wip(ty));
1079 return (ty, res);
1080 }
1081
1082 if let Err(_) = generics_err {
1083 user_self_ty = None;
1085 }
1086
1087 let mut infer_args_for_err = None;
1095
1096 let mut explicit_late_bound = ExplicitLateBound::No;
1097 for &GenericPathSegment(def_id, index) in &generic_segments {
1098 let seg = &segments[index];
1099 let generics = tcx.generics_of(def_id);
1100
1101 let arg_count = check_generic_arg_count_for_value_path(
1106 self,
1107 def_id,
1108 generics,
1109 seg,
1110 IsMethodCall::No,
1111 );
1112
1113 if let ExplicitLateBound::Yes = arg_count.explicit_late_bound {
1114 explicit_late_bound = ExplicitLateBound::Yes;
1115 }
1116
1117 if let Err(GenericArgCountMismatch { reported, .. }) = arg_count.correct {
1118 infer_args_for_err
1119 .get_or_insert_with(|| (reported, FxHashSet::default()))
1120 .1
1121 .insert(index);
1122 self.set_tainted_by_errors(reported); }
1124 }
1125
1126 let has_self = generic_segments
1127 .last()
1128 .is_some_and(|GenericPathSegment(def_id, _)| tcx.generics_of(*def_id).has_self);
1129
1130 let (res, implicit_args) = if let Res::Def(DefKind::ConstParam, def) = res {
1131 (res, Some(ty::GenericArgs::identity_for_item(tcx, tcx.parent(def))))
1141 } else if let Res::SelfCtor(impl_def_id) = res {
1142 let ty = LoweredTy::from_raw(
1143 self,
1144 span,
1145 tcx.at(span).type_of(impl_def_id).instantiate_identity().skip_norm_wip(),
1146 );
1147
1148 if std::iter::successors(Some(self.body_id.to_def_id()), |&def_id| {
1156 self.tcx.generics_of(def_id).parent
1157 })
1158 .all(|def_id| def_id != impl_def_id)
1159 {
1160 let sugg = ty.normalized.ty_adt_def().map(|def| errors::ReplaceWithName {
1161 span: path_span,
1162 name: self.tcx.item_name(def.did()).to_ident_string(),
1163 });
1164 let item = match self
1165 .tcx
1166 .hir_node_by_def_id(self.tcx.hir_get_parent_item(hir_id).def_id)
1167 {
1168 hir::Node::Item(item) => Some(errors::InnerItem {
1169 span: item.kind.ident().map(|i| i.span).unwrap_or(item.span),
1170 }),
1171 _ => None,
1172 };
1173 if ty.raw.has_param() {
1174 let guar = self.dcx().emit_err(errors::SelfCtorFromOuterItem {
1175 span: path_span,
1176 impl_span: tcx.def_span(impl_def_id),
1177 sugg,
1178 item,
1179 });
1180 return (Ty::new_error(self.tcx, guar), res);
1181 } else {
1182 self.tcx.emit_node_span_lint(
1183 SELF_CONSTRUCTOR_FROM_OUTER_ITEM,
1184 hir_id,
1185 path_span,
1186 errors::SelfCtorFromOuterItemLint {
1187 impl_span: tcx.def_span(impl_def_id),
1188 sugg,
1189 item,
1190 },
1191 );
1192 }
1193 }
1194
1195 match ty.normalized.ty_adt_def() {
1196 Some(adt_def) if adt_def.has_ctor() => {
1197 let (ctor_kind, ctor_def_id) = adt_def.non_enum_variant().ctor.unwrap();
1198 let vis = tcx.visibility(ctor_def_id);
1200 if !vis.is_accessible_from(tcx.parent_module(hir_id).to_def_id(), tcx) {
1201 self.dcx()
1202 .emit_err(CtorIsPrivate { span, def: tcx.def_path_str(adt_def.did()) });
1203 }
1204 let new_res = Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id);
1205 let user_args = Self::user_args_for_adt(ty);
1206 user_self_ty = user_args.user_self_ty;
1207 (new_res, Some(user_args.args))
1208 }
1209 _ => {
1210 let mut err = self.dcx().struct_span_err(
1211 span,
1212 "the `Self` constructor can only be used with tuple or unit structs",
1213 );
1214 if let Some(adt_def) = ty.normalized.ty_adt_def() {
1215 match adt_def.adt_kind() {
1216 AdtKind::Enum => {
1217 err.help("did you mean to use one of the enum's variants?");
1218 }
1219 AdtKind::Struct | AdtKind::Union => {
1220 err.span_suggestion(
1221 span,
1222 "use curly brackets",
1223 "Self { /* fields */ }",
1224 Applicability::HasPlaceholders,
1225 );
1226 }
1227 }
1228 }
1229 let reported = err.emit();
1230 return (Ty::new_error(tcx, reported), res);
1231 }
1232 }
1233 } else {
1234 (res, None)
1235 };
1236 let def_id = res.def_id();
1237
1238 let (correct, infer_args_for_err) = match infer_args_for_err {
1239 Some((reported, args)) => {
1240 (Err(GenericArgCountMismatch { reported, invalid_args: vec![] }), args)
1241 }
1242 None => (Ok(()), Default::default()),
1243 };
1244
1245 let arg_count = GenericArgCountResult { explicit_late_bound, correct };
1246
1247 struct CtorGenericArgsCtxt<'a, 'tcx> {
1248 fcx: &'a FnCtxt<'a, 'tcx>,
1249 span: Span,
1250 generic_segments: &'a [GenericPathSegment],
1251 infer_args_for_err: &'a FxHashSet<usize>,
1252 segments: &'tcx [hir::PathSegment<'tcx>],
1253 }
1254 impl<'a, 'tcx> GenericArgsLowerer<'a, 'tcx> for CtorGenericArgsCtxt<'a, 'tcx> {
1255 fn args_for_def_id(
1256 &mut self,
1257 def_id: DefId,
1258 ) -> (Option<&'a hir::GenericArgs<'tcx>>, bool) {
1259 if let Some(&GenericPathSegment(_, index)) =
1260 self.generic_segments.iter().find(|&GenericPathSegment(did, _)| *did == def_id)
1261 {
1262 if !self.infer_args_for_err.contains(&index) {
1265 if let Some(data) = self.segments[index].args {
1267 return (Some(data), self.segments[index].infer_args);
1268 }
1269 }
1270 return (None, self.segments[index].infer_args);
1271 }
1272
1273 (None, true)
1274 }
1275
1276 fn provided_kind(
1277 &mut self,
1278 preceding_args: &[ty::GenericArg<'tcx>],
1279 param: &ty::GenericParamDef,
1280 arg: &GenericArg<'tcx>,
1281 ) -> ty::GenericArg<'tcx> {
1282 match (¶m.kind, arg) {
1283 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => self
1284 .fcx
1285 .lowerer()
1286 .lower_lifetime(lt, RegionInferReason::Param(param))
1287 .into(),
1288 (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
1289 self.fcx.lower_ty(ty.as_unambig_ty()).raw.into()
1291 }
1292 (GenericParamDefKind::Type { .. }, GenericArg::Infer(inf)) => {
1293 self.fcx.lower_ty(&inf.to_ty()).raw.into()
1294 }
1295 (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => self
1296 .fcx
1297 .lower_const_arg(
1299 ct.as_unambig_ct(),
1300 self.fcx
1301 .tcx
1302 .type_of(param.def_id)
1303 .instantiate(self.fcx.tcx, preceding_args)
1304 .skip_norm_wip(),
1305 )
1306 .into(),
1307 (&GenericParamDefKind::Const { .. }, GenericArg::Infer(inf)) => {
1308 self.fcx.ct_infer(Some(param), inf.span).into()
1309 }
1310 _ => unreachable!(),
1311 }
1312 }
1313
1314 fn inferred_kind(
1315 &mut self,
1316 preceding_args: &[ty::GenericArg<'tcx>],
1317 param: &ty::GenericParamDef,
1318 infer_args: bool,
1319 ) -> ty::GenericArg<'tcx> {
1320 let tcx = self.fcx.tcx();
1321 if !infer_args && let Some(default) = param.default_value(tcx) {
1322 return default.instantiate(tcx, preceding_args).skip_norm_wip();
1325 }
1326 self.fcx.var_for_def(self.span, param)
1331 }
1332 }
1333
1334 let args_raw = implicit_args.unwrap_or_else(|| {
1335 lower_generic_args(
1336 self,
1337 def_id,
1338 &[],
1339 has_self,
1340 self_ty.map(|s| s.raw),
1341 &arg_count,
1342 &mut CtorGenericArgsCtxt {
1343 fcx: self,
1344 span,
1345 generic_segments: &generic_segments,
1346 infer_args_for_err: &infer_args_for_err,
1347 segments,
1348 },
1349 )
1350 });
1351
1352 let args_for_user_type = if let Res::Def(DefKind::AssocConst { .. }, def_id) = res {
1353 self.transform_args_for_inherent_type_const(def_id, args_raw)
1354 } else {
1355 args_raw
1356 };
1357
1358 self.write_user_type_annotation_from_args(hir_id, def_id, args_for_user_type, user_self_ty);
1360
1361 let args = self.normalize(span, Unnormalized::new_wip(args_raw));
1363
1364 self.add_required_obligations_for_hir(span, def_id, args, hir_id);
1365
1366 let ty = tcx.type_of(def_id);
1369 assert!(!args.has_escaping_bound_vars());
1370 assert!(!ty.skip_binder().has_escaping_bound_vars());
1371 let ty_instantiated = self.normalize(span, ty.instantiate(tcx, args));
1372
1373 if let Some(UserSelfTy { impl_def_id, self_ty }) = user_self_ty {
1374 let impl_ty = self.normalize(span, tcx.type_of(impl_def_id).instantiate(tcx, args));
1380 let self_ty = self.normalize(span, Unnormalized::new_wip(self_ty));
1381 match self.at(&self.misc(span), self.param_env).eq(
1382 DefineOpaqueTypes::Yes,
1383 impl_ty,
1384 self_ty,
1385 ) {
1386 Ok(ok) => self.register_infer_ok_obligations(ok),
1387 Err(_) => {
1388 self.dcx().span_bug(
1389 span,
1390 format!(
1391 "instantiate_value_path: (UFCS) {self_ty:?} was a subtype of {impl_ty:?} but now is not?",
1392 ),
1393 );
1394 }
1395 }
1396 }
1397
1398 debug!("instantiate_value_path: type of {:?} is {:?}", hir_id, ty_instantiated);
1399
1400 let args = if let Res::Def(DefKind::AssocConst { .. }, def_id) = res {
1401 self.transform_args_for_inherent_type_const(def_id, args)
1402 } else {
1403 args
1404 };
1405
1406 self.write_args(hir_id, args);
1407
1408 (ty_instantiated, res)
1409 }
1410
1411 pub(crate) fn add_required_obligations_for_hir(
1413 &self,
1414 span: Span,
1415 def_id: DefId,
1416 args: GenericArgsRef<'tcx>,
1417 hir_id: HirId,
1418 ) {
1419 self.add_required_obligations_with_code(span, def_id, args, |idx, span| {
1420 ObligationCauseCode::WhereClauseInExpr(def_id, span, hir_id, idx)
1421 })
1422 }
1423
1424 #[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("add_required_obligations_with_code",
"rustc_hir_typeck::fn_ctxt::_impl", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs"),
::tracing_core::__macro_support::Option::Some(1424u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::fn_ctxt::_impl"),
::tracing_core::field::FieldSet::new(&["def_id"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let param_env = self.param_env;
let bounds =
self.tcx.predicates_of(def_id).instantiate(self.tcx, args);
for obligation in
traits::predicates_for_generics(|idx, predicate_span|
self.cause(span, code(idx, predicate_span)),
|pred| self.normalize(span, pred), param_env, bounds) {
self.register_predicate(obligation);
}
}
}
}#[instrument(level = "debug", skip(self, code, span, args))]
1425 pub(crate) fn add_required_obligations_with_code(
1426 &self,
1427 span: Span,
1428 def_id: DefId,
1429 args: GenericArgsRef<'tcx>,
1430 code: impl Fn(usize, Span) -> ObligationCauseCode<'tcx>,
1431 ) {
1432 let param_env = self.param_env;
1433
1434 let bounds = self.tcx.predicates_of(def_id).instantiate(self.tcx, args);
1435
1436 for obligation in traits::predicates_for_generics(
1437 |idx, predicate_span| self.cause(span, code(idx, predicate_span)),
1438 |pred| self.normalize(span, pred),
1439 param_env,
1440 bounds,
1441 ) {
1442 self.register_predicate(obligation);
1443 }
1444 }
1445
1446 x;#[instrument(level = "debug", skip(self, sp), ret)]
1447 pub(crate) fn try_structurally_resolve_const(
1448 &self,
1449 sp: Span,
1450 ct: ty::Const<'tcx>,
1451 ) -> ty::Const<'tcx> {
1452 let ct = self.resolve_vars_with_obligations(ct);
1453
1454 if self.next_trait_solver()
1455 && let ty::ConstKind::Unevaluated(..) = ct.kind()
1456 {
1457 let result = self.at(&self.misc(sp), self.param_env).structurally_normalize_const(
1461 Unnormalized::new_wip(ct),
1462 &mut **self.fulfillment_cx.borrow_mut(),
1463 );
1464 match result {
1465 Ok(normalized_ct) => normalized_ct,
1466 Err(errors) => {
1467 let guar = self.err_ctxt().report_fulfillment_errors(errors);
1468 return ty::Const::new_error(self.tcx, guar);
1469 }
1470 }
1471 } else if self.tcx.features().generic_const_exprs() {
1472 rustc_trait_selection::traits::evaluate_const(&self.infcx, ct, self.param_env)
1473 } else {
1474 ct
1475 }
1476 }
1477
1478 pub(crate) fn structurally_resolve_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
1487 let ty = self.resolve_vars_with_obligations(ty);
1488
1489 if !ty.is_ty_var() { ty } else { self.type_must_be_known_at_this_point(sp, ty) }
1490 }
1491
1492 #[cold]
1493 pub(crate) fn type_must_be_known_at_this_point(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
1494 let guar = self.tainted_by_errors().unwrap_or_else(|| {
1495 self.err_ctxt()
1496 .emit_inference_failure_err(
1497 self.body_id,
1498 sp,
1499 ty.into(),
1500 TypeAnnotationNeeded::E0282,
1501 true,
1502 )
1503 .emit()
1504 });
1505 let err = Ty::new_error(self.tcx, guar);
1506 self.demand_suptype(sp, err, ty);
1507 err
1508 }
1509
1510 pub(crate) fn structurally_resolve_const(
1511 &self,
1512 sp: Span,
1513 ct: ty::Const<'tcx>,
1514 ) -> ty::Const<'tcx> {
1515 let ct = self.try_structurally_resolve_const(sp, ct);
1516
1517 if !ct.is_ct_infer() {
1518 ct
1519 } else {
1520 let e = self.tainted_by_errors().unwrap_or_else(|| {
1521 self.err_ctxt()
1522 .emit_inference_failure_err(
1523 self.body_id,
1524 sp,
1525 ct.into(),
1526 TypeAnnotationNeeded::E0282,
1527 true,
1528 )
1529 .emit()
1530 });
1531 ty::Const::new_error(self.tcx, e)
1533 }
1534 }
1535
1536 pub(crate) fn with_breakable_ctxt<F: FnOnce() -> R, R>(
1537 &self,
1538 id: HirId,
1539 ctxt: BreakableCtxt<'tcx>,
1540 f: F,
1541 ) -> (BreakableCtxt<'tcx>, R) {
1542 let index;
1543 {
1544 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
1545 index = enclosing_breakables.stack.len();
1546 enclosing_breakables.by_id.insert(id, index);
1547 enclosing_breakables.stack.push(ctxt);
1548 }
1549 let result = f();
1550 let ctxt = {
1551 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
1552 if true {
if !(enclosing_breakables.stack.len() == index + 1) {
::core::panicking::panic("assertion failed: enclosing_breakables.stack.len() == index + 1")
};
};debug_assert!(enclosing_breakables.stack.len() == index + 1);
1553 enclosing_breakables.by_id.swap_remove(&id).expect("missing breakable context");
1555 enclosing_breakables.stack.pop().expect("missing breakable context")
1556 };
1557 (ctxt, result)
1558 }
1559
1560 pub(crate) fn probe_instantiate_query_response(
1563 &self,
1564 span: Span,
1565 original_values: &OriginalQueryValues<'tcx>,
1566 query_result: &Canonical<'tcx, QueryResponse<'tcx, Ty<'tcx>>>,
1567 ) -> InferResult<'tcx, Ty<'tcx>> {
1568 self.instantiate_query_response_and_region_obligations(
1569 &self.misc(span),
1570 self.param_env,
1571 original_values,
1572 query_result,
1573 )
1574 }
1575
1576 pub(crate) fn expr_in_place(&self, mut expr_id: HirId) -> bool {
1578 let mut contained_in_place = false;
1579
1580 while let hir::Node::Expr(parent_expr) = self.tcx.parent_hir_node(expr_id) {
1581 match &parent_expr.kind {
1582 hir::ExprKind::Assign(lhs, ..) | hir::ExprKind::AssignOp(_, lhs, ..) => {
1583 if lhs.hir_id == expr_id {
1584 contained_in_place = true;
1585 break;
1586 }
1587 }
1588 _ => (),
1589 }
1590 expr_id = parent_expr.hir_id;
1591 }
1592
1593 contained_in_place
1594 }
1595}