rustc_trait_selection/traits/
util.rs1use std::collections::VecDeque;
2
3use rustc_attr_ir::lang_items::LangItem;
4use rustc_data_structures::fx::FxHashSet;
5use rustc_hir::def_id::DefId;
6use rustc_infer::infer::InferCtxt;
7pub use rustc_infer::traits::util::*;
8use rustc_middle::ty::{
9 self, CallerBoundsIterator, SizedTraitKind, Ty, TyCtxt, TypeFoldable, TypeVisitableExt,
10 Unnormalized,
11};
12pub use rustc_next_trait_solver::placeholder::{BoundVarReplacer, PlaceholderReplacer};
13use rustc_span::Span;
14use smallvec::{SmallVec, smallvec};
15use tracing::debug;
16
17pub fn expand_trait_aliases<'tcx>(
33 tcx: TyCtxt<'tcx>,
34 clauses: impl IntoIterator<Item = (ty::Clause<'tcx>, Span)>,
35) -> (
36 Vec<(ty::PolyTraitClause<'tcx>, SmallVec<[Span; 1]>)>,
37 Vec<(ty::PolyProjectionClause<'tcx>, Span)>,
38) {
39 let mut trait_preds = ::alloc::vec::Vec::new()vec![];
40 let mut projection_preds = ::alloc::vec::Vec::new()vec![];
41 let mut seen_projection_preds = FxHashSet::default();
42
43 let mut queue: VecDeque<_> = clauses.into_iter().map(|(p, s)| (p, {
let count = 0usize + 1usize;
let mut vec = ::smallvec::SmallVec::new();
if count <= vec.inline_size() {
vec.push(s);
vec
} else {
::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[s])))
}
}smallvec![s])).collect();
44
45 while let Some((clause, spans)) = queue.pop_front() {
46 match clause.kind().skip_binder() {
47 ty::ClauseKind::Trait(trait_pred) => {
48 if tcx.is_trait_alias(trait_pred.def_id()) {
49 queue.extend(
50 tcx.explicit_super_clauses_of(trait_pred.def_id())
51 .iter_identity_copied()
52 .map(Unnormalized::skip_norm_wip)
53 .map(|(super_clause, span)| {
54 let mut spans = spans.clone();
55 spans.push(span);
56 (
57 super_clause.instantiate_supertrait(
58 tcx,
59 clause.kind().rebind(trait_pred.trait_ref),
60 ),
61 spans,
62 )
63 }),
64 );
65 } else {
66 trait_preds.push((clause.kind().rebind(trait_pred), spans));
67 }
68 }
69 ty::ClauseKind::Projection(projection_pred) => {
70 let projection_pred = clause.kind().rebind(projection_pred);
71 if !seen_projection_preds.insert(tcx.anonymize_bound_vars(projection_pred)) {
72 continue;
73 }
74 projection_preds.push((projection_pred, *spans.last().unwrap()));
75 }
76 ty::ClauseKind::RegionOutlives(..)
77 | ty::ClauseKind::TypeOutlives(..)
78 | ty::ClauseKind::ConstArgHasType(_, _)
79 | ty::ClauseKind::WellFormed(_)
80 | ty::ClauseKind::ConstEvaluatable(_)
81 | ty::ClauseKind::UnstableFeature(_)
82 | ty::ClauseKind::HostEffect(..) => {}
83 ty::ClauseKind::CompressedTrait(..) => ::core::panicking::unreachable_default_msg()unreachable!(),
84 }
85 }
86
87 (trait_preds, projection_preds)
88}
89
90pub fn upcast_choices<'tcx>(
98 tcx: TyCtxt<'tcx>,
99 source_trait_ref: ty::PolyTraitRef<'tcx>,
100 target_trait_def_id: DefId,
101) -> Vec<ty::PolyTraitRef<'tcx>> {
102 if source_trait_ref.def_id() == target_trait_def_id {
103 return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[source_trait_ref]))vec![source_trait_ref]; }
105
106 supertraits(tcx, source_trait_ref)
107 .filter(|r| r.def_id() == target_trait_def_id)
108 .map(Unnormalized::skip_norm_wip)
109 .collect()
110}
111
112pub(crate) fn closure_trait_ref_and_return_type<'tcx>(
113 tcx: TyCtxt<'tcx>,
114 fn_trait_def_id: DefId,
115 self_ty: Ty<'tcx>,
116 sig: ty::PolyFnSig<'tcx>,
117 tuple_arguments: TupleArgumentsFlag,
118) -> ty::Binder<'tcx, (ty::TraitRef<'tcx>, Ty<'tcx>)> {
119 if !!self_ty.has_escaping_bound_vars() {
::core::panicking::panic("assertion failed: !self_ty.has_escaping_bound_vars()")
};assert!(!self_ty.has_escaping_bound_vars());
120 let arguments_tuple = match tuple_arguments {
121 TupleArgumentsFlag::No => sig.skip_binder().inputs()[0],
122 TupleArgumentsFlag::Yes => Ty::new_tup(tcx, sig.skip_binder().inputs()),
123 };
124 let trait_ref = ty::TraitRef::new(tcx, fn_trait_def_id, [self_ty, arguments_tuple]);
125 sig.map_bound(|sig| (trait_ref, sig.output()))
126}
127
128pub(crate) fn coroutine_trait_ref_and_outputs<'tcx>(
129 tcx: TyCtxt<'tcx>,
130 fn_trait_def_id: DefId,
131 self_ty: Ty<'tcx>,
132 sig: ty::GenSig<TyCtxt<'tcx>>,
133) -> (ty::TraitRef<'tcx>, Ty<'tcx>, Ty<'tcx>) {
134 if !!self_ty.has_escaping_bound_vars() {
::core::panicking::panic("assertion failed: !self_ty.has_escaping_bound_vars()")
};assert!(!self_ty.has_escaping_bound_vars());
135 let trait_ref = ty::TraitRef::new(tcx, fn_trait_def_id, [self_ty, sig.resume_ty]);
136 (trait_ref, sig.yield_ty, sig.return_ty)
137}
138
139pub(crate) fn future_trait_ref_and_outputs<'tcx>(
140 tcx: TyCtxt<'tcx>,
141 fn_trait_def_id: DefId,
142 self_ty: Ty<'tcx>,
143 sig: ty::GenSig<TyCtxt<'tcx>>,
144) -> (ty::TraitRef<'tcx>, Ty<'tcx>) {
145 if !!self_ty.has_escaping_bound_vars() {
::core::panicking::panic("assertion failed: !self_ty.has_escaping_bound_vars()")
};assert!(!self_ty.has_escaping_bound_vars());
146 let trait_ref = ty::TraitRef::new(tcx, fn_trait_def_id, [self_ty]);
147 (trait_ref, sig.return_ty)
148}
149
150pub(crate) fn iterator_trait_ref_and_outputs<'tcx>(
151 tcx: TyCtxt<'tcx>,
152 iterator_def_id: DefId,
153 self_ty: Ty<'tcx>,
154 sig: ty::GenSig<TyCtxt<'tcx>>,
155) -> (ty::TraitRef<'tcx>, Ty<'tcx>) {
156 if !!self_ty.has_escaping_bound_vars() {
::core::panicking::panic("assertion failed: !self_ty.has_escaping_bound_vars()")
};assert!(!self_ty.has_escaping_bound_vars());
157 let trait_ref = ty::TraitRef::new(tcx, iterator_def_id, [self_ty]);
158 (trait_ref, sig.yield_ty)
159}
160
161pub(crate) fn async_iterator_trait_ref_and_outputs<'tcx>(
162 tcx: TyCtxt<'tcx>,
163 async_iterator_def_id: DefId,
164 self_ty: Ty<'tcx>,
165 sig: ty::GenSig<TyCtxt<'tcx>>,
166) -> (ty::TraitRef<'tcx>, Ty<'tcx>) {
167 if !!self_ty.has_escaping_bound_vars() {
::core::panicking::panic("assertion failed: !self_ty.has_escaping_bound_vars()")
};assert!(!self_ty.has_escaping_bound_vars());
168 let trait_ref = ty::TraitRef::new(tcx, async_iterator_def_id, [self_ty]);
169 (trait_ref, sig.yield_ty)
170}
171
172pub fn impl_item_is_final(tcx: TyCtxt<'_>, assoc_item: &ty::AssocItem) -> bool {
173 assoc_item.defaultness(tcx).is_final()
174 && tcx.defaultness(assoc_item.container_id(tcx)).is_final()
175}
176
177pub(crate) enum TupleArgumentsFlag {
178 Yes,
179 No,
180}
181
182pub fn with_replaced_escaping_bound_vars<
195 'a,
196 'tcx,
197 T: TypeFoldable<TyCtxt<'tcx>>,
198 R: TypeFoldable<TyCtxt<'tcx>>,
199>(
200 infcx: &'a InferCtxt<'tcx>,
201 universe_indices: &'a mut Vec<Option<ty::UniverseIndex>>,
202 value: T,
203 f: impl FnOnce(T) -> R,
204) -> R {
205 if value.has_escaping_bound_vars() {
206 let (value, mapped_regions, mapped_types, mapped_consts) =
207 BoundVarReplacer::replace_bound_vars(infcx, universe_indices, value);
208 let result = f(value);
209 PlaceholderReplacer::replace_placeholders(
210 infcx,
211 mapped_regions,
212 mapped_types,
213 mapped_consts,
214 universe_indices,
215 result,
216 )
217 } else {
218 f(value)
219 }
220}
221
222pub fn implicit_fast_path<'tcx>(
223 tcx: TyCtxt<'tcx>,
224 predicate: ty::Predicate<'tcx>,
225 param_env: ty::ParamEnv<'tcx>,
226) -> bool {
227 if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)) =
231 predicate.kind().skip_binder()
232 && trait_pred.polarity == ty::ClausePolarity::Positive
233 {
234 let sizedness = match tcx.as_lang_item(trait_pred.def_id()) {
235 Some(LangItem::Sized) => SizedTraitKind::Sized,
236 Some(LangItem::MetaSized) => SizedTraitKind::MetaSized,
237 _ => return false,
238 };
239
240 if trait_pred.self_ty().has_trivial_sizedness(tcx, sizedness) {
241 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/util.rs:241",
"rustc_trait_selection::traits::util",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/util.rs"),
::tracing_core::__macro_support::Option::Some(241u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::util"),
::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!("fast path -- trivial sizedness")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("fast path -- trivial sizedness");
242 return true;
243 }
244
245 if #[allow(non_exhaustive_omitted_patterns)] match trait_pred.self_ty().kind() {
ty::Param(_) | ty::Placeholder(_) => true,
_ => false,
}matches!(trait_pred.self_ty().kind(), ty::Param(_) | ty::Placeholder(_)) {
246 for clause_pred in param_env
247 .caller_bounds()
248 .trait_clauses(tcx)
249 .with_polarity(ty::ClausePolarity::Positive)
250 .with_self_ty(trait_pred.self_ty())
251 .iter()
252 {
253 let clause_pred = clause_pred.skip_binder();
254 if clause_pred.def_id() == trait_pred.def_id() {
255 return true;
256 }
257 }
258 }
259 }
260
261 false
262}