1use std::iter;
2
3use tracing::debug;
4
5use super::{
6 ExpectedFound, RelateResult, TypeRelation, structurally_relate_consts, structurally_relate_tys,
7};
8use crate::error::TypeError;
9use crate::inherent::*;
10use crate::relate::VarianceDiagInfo;
11use crate::solve::Goal;
12use crate::visit::TypeVisitableExt as _;
13use crate::{self as ty, InferCtxtLike, Interner, TypingMode, Upcast};
14
15pub trait PredicateEmittingRelation<Infcx, I = <Infcx as InferCtxtLike>::Interner>:
16 TypeRelation<I>
17where
18 Infcx: InferCtxtLike<Interner = I>,
19 I: Interner,
20{
21 fn span(&self) -> I::Span;
22
23 fn param_env(&self) -> I::ParamEnv;
24
25 fn register_goals(&mut self, obligations: impl IntoIterator<Item = Goal<I, I::Predicate>>);
27
28 fn register_predicates(
31 &mut self,
32 obligations: impl IntoIterator<Item: Upcast<I, I::Predicate>>,
33 );
34
35 fn ambient_variance(&self) -> ty::Variance;
36}
37
38pub fn super_combine_tys<Infcx, I, R>(
39 infcx: &Infcx,
40 relation: &mut R,
41 a: I::Ty,
42 b: I::Ty,
43) -> RelateResult<I, I::Ty>
44where
45 Infcx: InferCtxtLike<Interner = I>,
46 I: Interner,
47 R: PredicateEmittingRelation<Infcx>,
48{
49 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_type_ir/src/relate/combine.rs:49",
"rustc_type_ir::relate::combine", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_type_ir/src/relate/combine.rs"),
::tracing_core::__macro_support::Option::Some(49u32),
::tracing_core::__macro_support::Option::Some("rustc_type_ir::relate::combine"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("super_combine_tys::<{0}>({1:?}, {2:?})",
std::any::type_name::<R>(), a, b) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("super_combine_tys::<{}>({:?}, {:?})", std::any::type_name::<R>(), a, b);
50 if true {
if !!a.has_escaping_bound_vars() {
::core::panicking::panic("assertion failed: !a.has_escaping_bound_vars()")
};
};debug_assert!(!a.has_escaping_bound_vars());
51 if true {
if !!b.has_escaping_bound_vars() {
::core::panicking::panic("assertion failed: !b.has_escaping_bound_vars()")
};
};debug_assert!(!b.has_escaping_bound_vars());
52
53 match (a.kind(), b.kind()) {
54 (ty::Error(e), _) | (_, ty::Error(e)) => {
55 infcx.set_tainted_by_errors(e);
56 return Ok(Ty::new_error(infcx.cx(), e));
57 }
58
59 (ty::Infer(ty::IntVar(a_id)), ty::Infer(ty::IntVar(b_id))) => {
61 infcx.equate_int_vids_raw(a_id, b_id);
62 Ok(a)
63 }
64 (ty::Infer(ty::IntVar(v_id)), ty::Int(v)) => {
65 infcx.instantiate_int_var_raw(v_id, ty::IntVarValue::IntType(v));
66 Ok(b)
67 }
68 (ty::Int(v), ty::Infer(ty::IntVar(v_id))) => {
69 infcx.instantiate_int_var_raw(v_id, ty::IntVarValue::IntType(v));
70 Ok(a)
71 }
72 (ty::Infer(ty::IntVar(v_id)), ty::Uint(v)) => {
73 infcx.instantiate_int_var_raw(v_id, ty::IntVarValue::UintType(v));
74 Ok(b)
75 }
76 (ty::Uint(v), ty::Infer(ty::IntVar(v_id))) => {
77 infcx.instantiate_int_var_raw(v_id, ty::IntVarValue::UintType(v));
78 Ok(a)
79 }
80
81 (ty::Infer(ty::FloatVar(a_id)), ty::Infer(ty::FloatVar(b_id))) => {
83 infcx.equate_float_vids_raw(a_id, b_id);
84 Ok(a)
85 }
86 (ty::Infer(ty::FloatVar(v_id)), ty::Float(v)) => {
87 infcx.instantiate_float_var_raw(v_id, ty::FloatVarValue::Known(v));
88 Ok(b)
89 }
90 (ty::Float(v), ty::Infer(ty::FloatVar(v_id))) => {
91 infcx.instantiate_float_var_raw(v_id, ty::FloatVarValue::Known(v));
92 Ok(a)
93 }
94
95 (ty::Alias(..), ty::Infer(ty::TyVar(_))) | (ty::Infer(ty::TyVar(_)), ty::Alias(..))
97 if infcx.next_trait_solver() =>
98 {
99 {
::core::panicking::panic_fmt(format_args!("We do not expect to encounter `TyVar` this late in combine -- they should have been handled earlier"));
}panic!(
100 "We do not expect to encounter `TyVar` this late in combine \
101 -- they should have been handled earlier"
102 )
103 }
104 (_, ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)))
105 | (ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)), _)
106 if infcx.next_trait_solver() =>
107 {
108 {
::core::panicking::panic_fmt(format_args!("We do not expect to encounter `Fresh` variables in the new solver"));
}panic!("We do not expect to encounter `Fresh` variables in the new solver")
109 }
110
111 (ty::Alias(ty::IsRigid::No, alias), _) | (_, ty::Alias(ty::IsRigid::No, alias))
112 if infcx.next_trait_solver() =>
113 {
114 let terms_are_inverted = !#[allow(non_exhaustive_omitted_patterns)] match a.kind() {
ty::Alias(ty::IsRigid::No, _) => true,
_ => false,
}matches!(a.kind(), ty::Alias(ty::IsRigid::No, _));
116 let other = if terms_are_inverted { a } else { b };
117 match (relation.ambient_variance(), terms_are_inverted) {
118 (ty::Invariant, _) => relation.register_predicates([ty::ProjectionPredicate {
119 projection_term: alias.into(),
120 term: other.into(),
121 }]),
122 (ty::Covariant, false) | (ty::Contravariant, true) => {
123 let new_var = infcx.next_ty_infer();
126 relation.register_predicates([
127 ty::PredicateKind::Clause(ty::ClauseKind::Projection(
128 ty::ProjectionPredicate {
129 projection_term: alias.into(),
130 term: new_var.into(),
131 },
132 )),
133 ty::PredicateKind::Subtype(ty::SubtypePredicate {
134 a_is_expected: !terms_are_inverted,
135 a: new_var,
136 b: other,
137 }),
138 ]);
139 }
140 (ty::Contravariant, false) | (ty::Covariant, true) => {
141 let new_var = infcx.next_ty_infer();
143 relation.register_predicates([
144 ty::PredicateKind::Clause(ty::ClauseKind::Projection(
145 ty::ProjectionPredicate {
146 projection_term: alias.into(),
147 term: new_var.into(),
148 },
149 )),
150 ty::PredicateKind::Subtype(ty::SubtypePredicate {
151 a_is_expected: terms_are_inverted,
152 a: other,
153 b: new_var,
154 }),
155 ]);
156 }
157 (ty::Bivariant, _) => {
158 {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("cannot handle bivariant aliases in register_projection_with_variance")));
}unreachable!(
159 "cannot handle bivariant aliases in register_projection_with_variance"
160 )
161 }
162 }
163 Ok(a)
164 }
165
166 (ty::Infer(_), _) | (_, ty::Infer(_)) => Err(TypeError::Sorts(ExpectedFound::new(a, b))),
168
169 (ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }), _)
170 | (_, ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }))
171 if !infcx.next_trait_solver() =>
172 {
173 match infcx.typing_mode_raw().assert_not_erased() {
174 TypingMode::Coherence => {
179 relation.register_predicates([ty::Binder::dummy(ty::PredicateKind::Ambiguous)]);
180 Ok(a)
181 }
182 TypingMode::Typeck { .. }
183 | TypingMode::PostTypeckUntilBorrowck { .. }
184 | TypingMode::PostBorrowck { .. }
185 | TypingMode::PostAnalysis
186 | TypingMode::Codegen => structurally_relate_tys(relation, a, b),
187 }
188 }
189
190 _ => structurally_relate_tys(relation, a, b),
191 }
192}
193
194pub fn super_combine_consts<Infcx, I, R>(
195 infcx: &Infcx,
196 relation: &mut R,
197 a: I::Const,
198 b: I::Const,
199) -> RelateResult<I, I::Const>
200where
201 Infcx: InferCtxtLike<Interner = I>,
202 I: Interner,
203 R: PredicateEmittingRelation<Infcx>,
204{
205 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_type_ir/src/relate/combine.rs:205",
"rustc_type_ir::relate::combine", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_type_ir/src/relate/combine.rs"),
::tracing_core::__macro_support::Option::Some(205u32),
::tracing_core::__macro_support::Option::Some("rustc_type_ir::relate::combine"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("super_combine_consts::<{0}>({1:?}, {2:?})",
std::any::type_name::<R>(), a, b) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("super_combine_consts::<{}>({:?}, {:?})", std::any::type_name::<R>(), a, b);
206 if true {
if !!a.has_escaping_bound_vars() {
::core::panicking::panic("assertion failed: !a.has_escaping_bound_vars()")
};
};debug_assert!(!a.has_escaping_bound_vars());
207 if true {
if !!b.has_escaping_bound_vars() {
::core::panicking::panic("assertion failed: !b.has_escaping_bound_vars()")
};
};debug_assert!(!b.has_escaping_bound_vars());
208
209 if a == b {
210 return Ok(a);
211 }
212
213 let a = infcx.shallow_resolve_const(a);
214 let b = infcx.shallow_resolve_const(b);
215
216 match (a.kind(), b.kind()) {
217 (
218 ty::ConstKind::Infer(ty::InferConst::Var(a_vid)),
219 ty::ConstKind::Infer(ty::InferConst::Var(b_vid)),
220 ) => {
221 infcx.equate_const_vids_raw(a_vid, b_vid);
222 Ok(a)
223 }
224
225 (ty::ConstKind::Infer(ty::InferConst::Var(_)), ty::ConstKind::Infer(_))
227 | (ty::ConstKind::Infer(_), ty::ConstKind::Infer(ty::InferConst::Var(_))) => {
228 {
::core::panicking::panic_fmt(format_args!("tried to combine ConstKind::Infer/ConstKind::Infer(InferConst::Var): {0:?} and {1:?}",
a, b));
}panic!(
229 "tried to combine ConstKind::Infer/ConstKind::Infer(InferConst::Var): {a:?} and {b:?}"
230 )
231 }
232
233 (ty::ConstKind::Infer(ty::InferConst::Var(vid)), _) => {
234 infcx.instantiate_const_var(relation, true, vid, b)?;
235 Ok(b)
236 }
237
238 (_, ty::ConstKind::Infer(ty::InferConst::Var(vid))) => {
239 infcx.instantiate_const_var(relation, false, vid, a)?;
240 Ok(a)
241 }
242
243 (ty::ConstKind::Alias(ty::IsRigid::No, alias), _)
244 | (_, ty::ConstKind::Alias(ty::IsRigid::No, alias))
245 if (infcx.cx().features().generic_const_exprs() || infcx.next_trait_solver()) =>
246 {
247 if infcx.next_trait_solver() {
248 let other = if #[allow(non_exhaustive_omitted_patterns)] match a.kind() {
ty::ConstKind::Alias(..) => true,
_ => false,
}matches!(a.kind(), ty::ConstKind::Alias(..)) { b } else { a };
249 relation.register_predicates([ty::ProjectionPredicate {
250 projection_term: alias.into(),
251 term: other.into(),
252 }])
253 } else {
254 relation.register_predicates([ty::PredicateKind::ConstEquate(a, b)]);
255 }
256
257 Ok(b)
258 }
259
260 _ => structurally_relate_consts(relation, a, b),
261 }
262}
263
264pub fn combine_ty_args<Infcx, I, R>(
265 infcx: &Infcx,
266 relation: &mut R,
267 a_ty: I::Ty,
268 b_ty: I::Ty,
269 variances: I::VariancesOf,
270 a_args: I::GenericArgs,
271 b_args: I::GenericArgs,
272 mk: impl FnOnce(I::GenericArgs) -> I::Ty,
273) -> RelateResult<I, I::Ty>
274where
275 Infcx: InferCtxtLike<Interner = I>,
276 I: Interner,
277 R: PredicateEmittingRelation<Infcx>,
278{
279 let cx = infcx.cx();
280 let mut has_unconstrained_bivariant_arg = false;
281 let args = iter::zip(a_args.iter(), b_args.iter()).enumerate().map(|(i, (a, b))| {
282 let variance = variances.get(i).unwrap();
283 let variance_info = match variance {
284 ty::Invariant => {
285 VarianceDiagInfo::Invariant { ty: a_ty, param_index: i.try_into().unwrap() }
286 }
287 ty::Covariant | ty::Contravariant => VarianceDiagInfo::default(),
288 ty::Bivariant => {
289 let has_non_region_infer = |arg: I::GenericArg| {
290 arg.has_non_region_infer()
291 && infcx.resolve_vars_if_possible(arg).has_non_region_infer()
292 };
293 if has_non_region_infer(a) || has_non_region_infer(b) {
294 has_unconstrained_bivariant_arg = true;
295 }
296 VarianceDiagInfo::default()
297 }
298 };
299 relation.relate_with_variance(variance, variance_info, a, b)
300 });
301 let args = cx.mk_args_from_iter(args)?;
302
303 if has_unconstrained_bivariant_arg {
327 relation.register_predicates([
328 ty::ClauseKind::WellFormed(a_ty.into()),
329 ty::ClauseKind::WellFormed(b_ty.into()),
330 ]);
331 }
332
333 if a_args == args { Ok(a_ty) } else { Ok(mk(args)) }
334}