1use hir::def_id::{DefId, LocalDefId};
2use rustc_hir as hir;
3use rustc_middle::bug;
4use rustc_middle::traits::ObligationCause;
5use rustc_middle::traits::solve::Goal;
6use rustc_middle::ty::error::{ExpectedFound, TypeError};
7use rustc_middle::ty::{
8 self, BottomUpFolder, OpaqueTypeKey, ProvisionalHiddenType, Ty, TyCtxt, TypeFoldable,
9 TypeVisitableExt,
10};
11use rustc_span::Span;
12use tracing::{debug, instrument};
13
14use super::{DefineOpaqueTypes, RegionVariableOrigin};
15use crate::errors::OpaqueHiddenTypeDiag;
16use crate::infer::{InferCtxt, InferOk};
17use crate::traits::{self, Obligation, PredicateObligations};
18
19mod table;
20
21pub use table::{OpaqueTypeStorage, OpaqueTypeStorageEntries, OpaqueTypeTable};
22
23impl<'tcx> InferCtxt<'tcx> {
24 pub fn replace_opaque_types_with_inference_vars<T: TypeFoldable<TyCtxt<'tcx>>>(
27 &self,
28 value: T,
29 body_id: LocalDefId,
30 span: Span,
31 param_env: ty::ParamEnv<'tcx>,
32 ) -> InferOk<'tcx, T> {
33 if self.next_trait_solver() {
35 return InferOk { value, obligations: PredicateObligations::new() };
36 }
37
38 if !value.has_opaque_types() {
39 return InferOk { value, obligations: PredicateObligations::new() };
40 }
41
42 let mut obligations = PredicateObligations::new();
43 let value = value.fold_with(&mut BottomUpFolder {
44 tcx: self.tcx,
45 lt_op: |lt| lt,
46 ct_op: |ct| ct,
47 ty_op: |ty| match *ty.kind() {
48 ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. })
49 if self.can_define_opaque_ty(def_id) && !ty.has_escaping_bound_vars() =>
50 {
51 let def_span = self.tcx.def_span(def_id);
52 let span = if span.contains(def_span) { def_span } else { span };
53 let ty_var = self.next_ty_var(span);
54 obligations.extend(
55 self.handle_opaque_type(ty, ty_var, span, param_env)
56 .unwrap()
57 .into_iter()
58 .map(|goal| {
59 Obligation::new(
60 self.tcx,
61 ObligationCause::new(
62 span,
63 body_id,
64 traits::ObligationCauseCode::OpaqueReturnType(None),
65 ),
66 goal.param_env,
67 goal.predicate,
68 )
69 }),
70 );
71 ty_var
72 }
73 _ => ty,
74 },
75 });
76 InferOk { value, obligations }
77 }
78
79 pub fn handle_opaque_type(
80 &self,
81 a: Ty<'tcx>,
82 b: Ty<'tcx>,
83 span: Span,
84 param_env: ty::ParamEnv<'tcx>,
85 ) -> Result<Vec<Goal<'tcx, ty::Predicate<'tcx>>>, TypeError<'tcx>> {
86 if true {
if !!self.next_trait_solver() {
::core::panicking::panic("assertion failed: !self.next_trait_solver()")
};
};debug_assert!(!self.next_trait_solver());
87 let process = |a: Ty<'tcx>, b: Ty<'tcx>| match *a.kind() {
88 ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) if def_id.is_local() => {
89 let def_id = def_id.expect_local();
90 if let ty::TypingMode::Coherence = self.typing_mode() {
91 return Some(self.register_hidden_type(
93 OpaqueTypeKey { def_id, args },
94 span,
95 param_env,
96 b,
97 ));
98 }
99 if !self.can_define_opaque_ty(def_id) {
134 return None;
135 }
136
137 if let ty::Alias(ty::Opaque, ty::AliasTy { def_id: b_def_id, .. }) = *b.kind() {
138 if self.can_define_opaque_ty(b_def_id)
144 && #[allow(non_exhaustive_omitted_patterns)] match self.tcx.opaque_ty_origin(b_def_id)
{
hir::OpaqueTyOrigin::TyAlias { .. } => true,
_ => false,
}matches!(
145 self.tcx.opaque_ty_origin(b_def_id),
146 hir::OpaqueTyOrigin::TyAlias { .. }
147 )
148 {
149 self.dcx().emit_err(OpaqueHiddenTypeDiag {
150 span,
151 hidden_type: self.tcx.def_span(b_def_id),
152 opaque_type: self.tcx.def_span(def_id),
153 });
154 }
155 }
156 Some(self.register_hidden_type(OpaqueTypeKey { def_id, args }, span, param_env, b))
157 }
158 _ => None,
159 };
160 if let Some(res) = process(a, b) {
161 res
162 } else if let Some(res) = process(b, a) {
163 res
164 } else {
165 let (a, b) = self.resolve_vars_if_possible((a, b));
166 Err(TypeError::Sorts(ExpectedFound::new(a, b)))
167 }
168 }
169}
170
171impl<'tcx> InferCtxt<'tcx> {
172 #[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("register_hidden_type",
"rustc_infer::infer::opaque_types", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_infer/src/infer/opaque_types/mod.rs"),
::tracing_core::__macro_support::Option::Some(172u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer::opaque_types"),
::tracing_core::field::FieldSet::new(&["opaque_type_key",
"span", "param_env", "hidden_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(&opaque_type_key)
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(¶m_env)
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(&hidden_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:
Result<Vec<Goal<'tcx, ty::Predicate<'tcx>>>,
TypeError<'tcx>> = loop {};
return __tracing_attr_fake_return;
}
{
let mut goals = Vec::new();
self.insert_hidden_type(opaque_type_key, span, param_env,
hidden_ty, &mut goals)?;
self.add_item_bounds_for_hidden_type(opaque_type_key.def_id.to_def_id(),
opaque_type_key.args, param_env, hidden_ty, &mut goals);
Ok(goals)
}
}
}#[instrument(skip(self), level = "debug")]
173 fn register_hidden_type(
174 &self,
175 opaque_type_key: OpaqueTypeKey<'tcx>,
176 span: Span,
177 param_env: ty::ParamEnv<'tcx>,
178 hidden_ty: Ty<'tcx>,
179 ) -> Result<Vec<Goal<'tcx, ty::Predicate<'tcx>>>, TypeError<'tcx>> {
180 let mut goals = Vec::new();
181
182 self.insert_hidden_type(opaque_type_key, span, param_env, hidden_ty, &mut goals)?;
183
184 self.add_item_bounds_for_hidden_type(
185 opaque_type_key.def_id.to_def_id(),
186 opaque_type_key.args,
187 param_env,
188 hidden_ty,
189 &mut goals,
190 );
191
192 Ok(goals)
193 }
194
195 pub fn register_hidden_type_in_storage(
200 &self,
201 opaque_type_key: OpaqueTypeKey<'tcx>,
202 hidden_ty: ProvisionalHiddenType<'tcx>,
203 ) -> Option<Ty<'tcx>> {
204 self.inner.borrow_mut().opaque_types().register(opaque_type_key, hidden_ty)
205 }
206
207 pub fn insert_hidden_type(
215 &self,
216 opaque_type_key: OpaqueTypeKey<'tcx>,
217 span: Span,
218 param_env: ty::ParamEnv<'tcx>,
219 hidden_ty: Ty<'tcx>,
220 goals: &mut Vec<Goal<'tcx, ty::Predicate<'tcx>>>,
221 ) -> Result<(), TypeError<'tcx>> {
222 let tcx = self.tcx;
223 match self.typing_mode() {
229 ty::TypingMode::Coherence => {
230 goals.push(Goal::new(tcx, param_env, ty::PredicateKind::Ambiguous));
234 }
235 ty::TypingMode::Analysis { .. } => {
236 let prev = self
237 .inner
238 .borrow_mut()
239 .opaque_types()
240 .register(opaque_type_key, ProvisionalHiddenType { ty: hidden_ty, span });
241 if let Some(prev) = prev {
242 goals.extend(
243 self.at(&ObligationCause::dummy_with_span(span), param_env)
244 .eq(DefineOpaqueTypes::Yes, prev, hidden_ty)?
245 .obligations
246 .into_iter()
247 .map(|obligation| obligation.as_goal()),
248 );
249 }
250 }
251 ty::TypingMode::Borrowck { .. } => {
252 let prev = self
253 .inner
254 .borrow_mut()
255 .opaque_types()
256 .register(opaque_type_key, ProvisionalHiddenType { ty: hidden_ty, span });
257
258 let actual = prev.unwrap_or_else(|| {
261 let actual = tcx
262 .type_of_opaque_hir_typeck(opaque_type_key.def_id)
263 .instantiate(self.tcx, opaque_type_key.args);
264 let actual = ty::fold_regions(tcx, actual, |re, _dbi| match re.kind() {
265 ty::ReErased => self.next_region_var(RegionVariableOrigin::Misc(span)),
266 _ => re,
267 });
268 actual
269 });
270
271 goals.extend(
272 self.at(&ObligationCause::dummy_with_span(span), param_env)
273 .eq(DefineOpaqueTypes::Yes, hidden_ty, actual)?
274 .obligations
275 .into_iter()
276 .map(|obligation| obligation.as_goal()),
277 );
278 }
279 mode @ (ty::TypingMode::PostBorrowckAnalysis { .. } | ty::TypingMode::PostAnalysis) => {
280 ::rustc_middle::util::bug::bug_fmt(format_args!("insert hidden type in {0:?}",
mode))bug!("insert hidden type in {mode:?}")
281 }
282 }
283
284 Ok(())
285 }
286
287 pub fn add_item_bounds_for_hidden_type(
288 &self,
289 def_id: DefId,
290 args: ty::GenericArgsRef<'tcx>,
291 param_env: ty::ParamEnv<'tcx>,
292 hidden_ty: Ty<'tcx>,
293 goals: &mut Vec<Goal<'tcx, ty::Predicate<'tcx>>>,
294 ) {
295 let tcx = self.tcx;
296 goals.push(Goal::new(tcx, param_env, ty::ClauseKind::WellFormed(hidden_ty.into())));
308
309 let replace_opaques_in = |clause: ty::Clause<'tcx>, goals: &mut Vec<_>| {
310 clause.fold_with(&mut BottomUpFolder {
311 tcx,
312 ty_op: |ty| match *ty.kind() {
313 ty::Alias(ty::Projection, projection_ty)
318 if !projection_ty.has_escaping_bound_vars()
319 && !tcx.is_impl_trait_in_trait(projection_ty.def_id)
320 && !self.next_trait_solver() =>
321 {
322 let ty_var = self.next_ty_var(self.tcx.def_span(projection_ty.def_id));
323 goals.push(Goal::new(
324 self.tcx,
325 param_env,
326 ty::PredicateKind::Clause(ty::ClauseKind::Projection(
327 ty::ProjectionPredicate {
328 projection_term: projection_ty.into(),
329 term: ty_var.into(),
330 },
331 )),
332 ));
333 ty_var
334 }
335 ty::Alias(ty::Opaque, ty::AliasTy { def_id: def_id2, args: args2, .. })
338 if def_id == def_id2 && args == args2 =>
339 {
340 hidden_ty
341 }
342 _ => ty,
343 },
344 lt_op: |lt| lt,
345 ct_op: |ct| ct,
346 })
347 };
348
349 let item_bounds = tcx.explicit_item_bounds(def_id);
350 for (predicate, _) in item_bounds.iter_instantiated_copied(tcx, args) {
351 let predicate = replace_opaques_in(predicate, goals);
352
353 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_infer/src/infer/opaque_types/mod.rs:354",
"rustc_infer::infer::opaque_types", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_infer/src/infer/opaque_types/mod.rs"),
::tracing_core::__macro_support::Option::Some(354u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer::opaque_types"),
::tracing_core::field::FieldSet::new(&["predicate"],
::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(&predicate)
as &dyn Value))])
});
} else { ; }
};debug!(?predicate);
355 goals.push(Goal::new(self.tcx, param_env, predicate));
356 }
357
358 if self.tcx.is_conditionally_const(def_id) {
360 let item_bounds = tcx.explicit_implied_const_bounds(def_id);
361 for (predicate, _) in item_bounds.iter_instantiated_copied(tcx, args) {
362 let predicate = replace_opaques_in(
363 predicate.to_host_effect_clause(self.tcx, ty::BoundConstness::Maybe),
364 goals,
365 );
366
367 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_infer/src/infer/opaque_types/mod.rs:368",
"rustc_infer::infer::opaque_types", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_infer/src/infer/opaque_types/mod.rs"),
::tracing_core::__macro_support::Option::Some(368u32),
::tracing_core::__macro_support::Option::Some("rustc_infer::infer::opaque_types"),
::tracing_core::field::FieldSet::new(&["predicate"],
::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(&predicate)
as &dyn Value))])
});
} else { ; }
};debug!(?predicate);
369 goals.push(Goal::new(self.tcx, param_env, predicate));
370 }
371 }
372 }
373}