1//! Core logic responsible for determining what it means for various type system
2//! primitives to be "well formed". Actually checking whether these primitives are
3//! well formed is performed elsewhere (e.g. during type checking or item well formedness
4//! checking).
56use std::iter;
78use rustc_hiras hir;
9use rustc_hir::def::DefKind;
10use rustc_hir::lang_items::LangItem;
11use rustc_infer::traits::{ObligationCauseCode, PredicateObligations};
12use rustc_middle::bug;
13use rustc_middle::ty::{
14self, GenericArgsRef, Term, TermKind, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable,
15TypeVisitableExt, TypeVisitor,
16};
17use rustc_session::parse::feature_err;
18use rustc_span::def_id::{DefId, LocalDefId};
19use rustc_span::{Span, sym};
20use tracing::{debug, instrument, trace};
2122use crate::infer::InferCtxt;
23use crate::traits;
2425/// Returns the set of obligations needed to make `arg` well-formed.
26/// If `arg` contains unresolved inference variables, this may include
27/// further WF obligations. However, if `arg` IS an unresolved
28/// inference variable, returns `None`, because we are not able to
29/// make any progress at all. This is to prevent cycles where we
30/// say "?0 is WF if ?0 is WF".
31pub fn obligations<'tcx>(
32 infcx: &InferCtxt<'tcx>,
33 param_env: ty::ParamEnv<'tcx>,
34 body_id: LocalDefId,
35 recursion_depth: usize,
36 term: Term<'tcx>,
37 span: Span,
38) -> Option<PredicateObligations<'tcx>> {
39// Handle the "cycle" case (see comment above) by bailing out if necessary.
40let term = match term.kind() {
41 TermKind::Ty(ty) => {
42match ty.kind() {
43 ty::Infer(ty::TyVar(_)) => {
44let resolved_ty = infcx.shallow_resolve(ty);
45if resolved_ty == ty {
46// No progress, bail out to prevent cycles.
47return None;
48 } else {
49resolved_ty50 }
51 }
52_ => ty,
53 }
54 .into()
55 }
56 TermKind::Const(ct) => {
57match ct.kind() {
58 ty::ConstKind::Infer(_) => {
59let resolved = infcx.shallow_resolve_const(ct);
60if resolved == ct {
61// No progress, bail out to prevent cycles.
62return None;
63 } else {
64resolved65 }
66 }
67_ => ct,
68 }
69 .into()
70 }
71 };
7273let mut wf = WfPredicates {
74infcx,
75param_env,
76body_id,
77span,
78 out: PredicateObligations::new(),
79recursion_depth,
80 item: None,
81 };
82wf.add_wf_preds_for_term(term);
83{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/wf.rs:83",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(83u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
::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!("wf::obligations({0:?}, body_id={1:?}) = {2:?}",
term, body_id, wf.out) as &dyn Value))])
});
} else { ; }
};debug!("wf::obligations({:?}, body_id={:?}) = {:?}", term, body_id, wf.out);
8485let result = wf.normalize(infcx);
86{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/wf.rs:86",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(86u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
::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!("wf::obligations({0:?}, body_id={1:?}) ~~> {2:?}",
term, body_id, result) as &dyn Value))])
});
} else { ; }
};debug!("wf::obligations({:?}, body_id={:?}) ~~> {:?}", term, body_id, result);
87Some(result)
88}
8990/// Compute the predicates that are required for a type to be well-formed.
91///
92/// This is only intended to be used in the new solver, since it does not
93/// take into account recursion depth or proper error-reporting spans.
94pub fn unnormalized_obligations<'tcx>(
95 infcx: &InferCtxt<'tcx>,
96 param_env: ty::ParamEnv<'tcx>,
97 term: Term<'tcx>,
98 span: Span,
99 body_id: LocalDefId,
100) -> Option<PredicateObligations<'tcx>> {
101if true {
match (&term, &infcx.resolve_vars_if_possible(term)) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
};debug_assert_eq!(term, infcx.resolve_vars_if_possible(term));
102103// However, if `arg` IS an unresolved inference variable, returns `None`,
104 // because we are not able to make any progress at all. This is to prevent
105 // cycles where we say "?0 is WF if ?0 is WF".
106if term.is_infer() {
107return None;
108 }
109110let mut wf = WfPredicates {
111infcx,
112param_env,
113body_id,
114span,
115 out: PredicateObligations::new(),
116 recursion_depth: 0,
117 item: None,
118 };
119wf.add_wf_preds_for_term(term);
120Some(wf.out)
121}
122123/// Returns the obligations that make this trait reference
124/// well-formed. For example, if there is a trait `Set` defined like
125/// `trait Set<K: Eq>`, then the trait bound `Foo: Set<Bar>` is WF
126/// if `Bar: Eq`.
127pub fn trait_obligations<'tcx>(
128 infcx: &InferCtxt<'tcx>,
129 param_env: ty::ParamEnv<'tcx>,
130 body_id: LocalDefId,
131 trait_pred: ty::TraitPredicate<'tcx>,
132 span: Span,
133 item: &'tcx hir::Item<'tcx>,
134) -> PredicateObligations<'tcx> {
135let mut wf = WfPredicates {
136infcx,
137param_env,
138body_id,
139span,
140 out: PredicateObligations::new(),
141 recursion_depth: 0,
142 item: Some(item),
143 };
144wf.add_wf_preds_for_trait_pred(trait_pred, Elaborate::All);
145{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/wf.rs:145",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(145u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
::tracing_core::field::FieldSet::new(&["obligations"],
::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(&wf.out) as
&dyn Value))])
});
} else { ; }
};debug!(obligations = ?wf.out);
146wf.normalize(infcx)
147}
148149/// Returns the requirements for `clause` to be well-formed.
150///
151/// For example, if there is a trait `Set` defined like
152/// `trait Set<K: Eq>`, then the trait bound `Foo: Set<Bar>` is WF
153/// if `Bar: Eq`.
154x;#[instrument(skip(infcx), ret)]155pub fn clause_obligations<'tcx>(
156 infcx: &InferCtxt<'tcx>,
157 param_env: ty::ParamEnv<'tcx>,
158 body_id: LocalDefId,
159 clause: ty::Clause<'tcx>,
160 span: Span,
161) -> PredicateObligations<'tcx> {
162let mut wf = WfPredicates {
163 infcx,
164 param_env,
165 body_id,
166 span,
167 out: PredicateObligations::new(),
168 recursion_depth: 0,
169 item: None,
170 };
171172// It's ok to skip the binder here because wf code is prepared for it
173match clause.kind().skip_binder() {
174 ty::ClauseKind::Trait(t) => {
175 wf.add_wf_preds_for_trait_pred(t, Elaborate::None);
176 }
177 ty::ClauseKind::HostEffect(..) => {
178// Technically the well-formedness of this predicate is implied by
179 // the corresponding trait predicate it should've been generated beside.
180}
181 ty::ClauseKind::RegionOutlives(..) => {}
182 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
183 wf.add_wf_preds_for_term(ty.into());
184 }
185 ty::ClauseKind::Projection(t) => {
186 wf.add_wf_preds_for_alias_term(t.projection_term);
187 wf.add_wf_preds_for_term(t.term);
188 }
189 ty::ClauseKind::ConstArgHasType(ct, ty) => {
190 wf.add_wf_preds_for_term(ct.into());
191 wf.add_wf_preds_for_term(ty.into());
192 }
193 ty::ClauseKind::WellFormed(term) => {
194 wf.add_wf_preds_for_term(term);
195 }
196197 ty::ClauseKind::ConstEvaluatable(ct) => {
198 wf.add_wf_preds_for_term(ct.into());
199 }
200 ty::ClauseKind::UnstableFeature(_) => {}
201 }
202203 wf.normalize(infcx)
204}
205206struct WfPredicates<'a, 'tcx> {
207 infcx: &'a InferCtxt<'tcx>,
208 param_env: ty::ParamEnv<'tcx>,
209 body_id: LocalDefId,
210 span: Span,
211 out: PredicateObligations<'tcx>,
212 recursion_depth: usize,
213 item: Option<&'tcx hir::Item<'tcx>>,
214}
215216/// Controls whether we "elaborate" supertraits and so forth on the WF
217/// predicates. This is a kind of hack to address #43784. The
218/// underlying problem in that issue was a trait structure like:
219///
220/// ```ignore (illustrative)
221/// trait Foo: Copy { }
222/// trait Bar: Foo { }
223/// impl<T: Bar> Foo for T { }
224/// impl<T> Bar for T { }
225/// ```
226///
227/// Here, in the `Foo` impl, we will check that `T: Copy` holds -- but
228/// we decide that this is true because `T: Bar` is in the
229/// where-clauses (and we can elaborate that to include `T:
230/// Copy`). This wouldn't be a problem, except that when we check the
231/// `Bar` impl, we decide that `T: Foo` must hold because of the `Foo`
232/// impl. And so nowhere did we check that `T: Copy` holds!
233///
234/// To resolve this, we elaborate the WF requirements that must be
235/// proven when checking impls. This means that (e.g.) the `impl Bar
236/// for T` will be forced to prove not only that `T: Foo` but also `T:
237/// Copy` (which it won't be able to do, because there is no `Copy`
238/// impl for `T`).
239#[derive(#[automatically_derived]
impl ::core::fmt::Debug for Elaborate {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
Elaborate::All => "All",
Elaborate::None => "None",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for Elaborate {
#[inline]
fn eq(&self, other: &Elaborate) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Elaborate {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::marker::Copy for Elaborate { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Elaborate {
#[inline]
fn clone(&self) -> Elaborate { *self }
}Clone)]
240enum Elaborate {
241 All,
242None,
243}
244245/// Points the cause span of a super predicate at the relevant associated type.
246///
247/// Given a trait impl item:
248///
249/// ```ignore (incomplete)
250/// impl TargetTrait for TargetType {
251/// type Assoc = SomeType;
252/// }
253/// ```
254///
255/// And a super predicate of `TargetTrait` that has any of the following forms:
256///
257/// 1. `<OtherType as OtherTrait>::Assoc == <TargetType as TargetTrait>::Assoc`
258/// 2. `<<TargetType as TargetTrait>::Assoc as OtherTrait>::Assoc == OtherType`
259/// 3. `<TargetType as TargetTrait>::Assoc: OtherTrait`
260///
261/// Replace the span of the cause with the span of the associated item:
262///
263/// ```ignore (incomplete)
264/// impl TargetTrait for TargetType {
265/// type Assoc = SomeType;
266/// // ^^^^^^^^ this span
267/// }
268/// ```
269///
270/// Note that bounds that can be expressed as associated item bounds are **not**
271/// super predicates. This means that form 2 and 3 from above are only relevant if
272/// the [`GenericArgsRef`] of the projection type are not its identity arguments.
273fn extend_cause_with_original_assoc_item_obligation<'tcx>(
274 tcx: TyCtxt<'tcx>,
275 item: Option<&hir::Item<'tcx>>,
276 cause: &mut traits::ObligationCause<'tcx>,
277 pred: ty::Predicate<'tcx>,
278) {
279{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/wf.rs:279",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(279u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
::tracing_core::field::FieldSet::new(&["message", "item",
"cause", "pred"],
::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!("extended_cause_with_original_assoc_item_obligation")
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&item) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&cause) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&pred) as
&dyn Value))])
});
} else { ; }
};debug!(?item, ?cause, ?pred, "extended_cause_with_original_assoc_item_obligation");
280let (items, impl_def_id) = match item {
281Some(hir::Item { kind: hir::ItemKind::Impl(impl_), owner_id, .. }) => {
282 (impl_.items, *owner_id)
283 }
284_ => return,
285 };
286287let ty_to_impl_span = |ty: Ty<'_>| {
288if let ty::Alias(ty::Projection, projection_ty) = ty.kind()
289 && let Some(&impl_item_id) =
290tcx.impl_item_implementor_ids(impl_def_id).get(&projection_ty.def_id)
291 && let Some(impl_item) =
292items.iter().find(|item| item.owner_id.to_def_id() == impl_item_id)
293 {
294Some(tcx.hir_impl_item(*impl_item).expect_type().span)
295 } else {
296None297 }
298 };
299300// It is fine to skip the binder as we don't care about regions here.
301match pred.kind().skip_binder() {
302 ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)) => {
303// Form 1: The obligation comes not from the current `impl` nor the `trait` being
304 // implemented, but rather from a "second order" obligation, where an associated
305 // type has a projection coming from another associated type.
306 // See `tests/ui/traits/assoc-type-in-superbad.rs` for an example.
307if let Some(term_ty) = proj.term.as_type()
308 && let Some(impl_item_span) = ty_to_impl_span(term_ty)
309 {
310cause.span = impl_item_span;
311 }
312313// Form 2: A projection obligation for an associated item failed to be met.
314 // We overwrite the span from above to ensure that a bound like
315 // `Self::Assoc1: Trait<OtherAssoc = Self::Assoc2>` gets the same
316 // span for both obligations that it is lowered to.
317if let Some(impl_item_span) = ty_to_impl_span(proj.self_ty()) {
318cause.span = impl_item_span;
319 }
320 }
321322 ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
323// Form 3: A trait obligation for an associated item failed to be met.
324{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/wf.rs:324",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(324u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
::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!("extended_cause_with_original_assoc_item_obligation trait proj {0:?}",
pred) as &dyn Value))])
});
} else { ; }
};debug!("extended_cause_with_original_assoc_item_obligation trait proj {:?}", pred);
325if let Some(impl_item_span) = ty_to_impl_span(pred.self_ty()) {
326cause.span = impl_item_span;
327 }
328 }
329_ => {}
330 }
331}
332333impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
334fn tcx(&self) -> TyCtxt<'tcx> {
335self.infcx.tcx
336 }
337338fn cause(&self, code: traits::ObligationCauseCode<'tcx>) -> traits::ObligationCause<'tcx> {
339 traits::ObligationCause::new(self.span, self.body_id, code)
340 }
341342fn normalize(self, infcx: &InferCtxt<'tcx>) -> PredicateObligations<'tcx> {
343// Do not normalize `wf` obligations with the new solver.
344 //
345 // The current deep normalization routine with the new solver does not
346 // handle ambiguity and the new solver correctly deals with unnnormalized goals.
347 // If the user relies on normalized types, e.g. for `fn implied_outlives_bounds`,
348 // it is their responsibility to normalize while avoiding ambiguity.
349if infcx.next_trait_solver() {
350return self.out;
351 }
352353let cause = self.cause(ObligationCauseCode::WellFormed(None));
354let param_env = self.param_env;
355let mut obligations = PredicateObligations::with_capacity(self.out.len());
356for mut obligation in self.out {
357if !!obligation.has_escaping_bound_vars() {
::core::panicking::panic("assertion failed: !obligation.has_escaping_bound_vars()")
};assert!(!obligation.has_escaping_bound_vars());
358let mut selcx = traits::SelectionContext::new(infcx);
359// Don't normalize the whole obligation, the param env is either
360 // already normalized, or we're currently normalizing the
361 // param_env. Either way we should only normalize the predicate.
362let normalized_predicate = traits::normalize::normalize_with_depth_to(
363&mut selcx,
364 param_env,
365 cause.clone(),
366self.recursion_depth,
367 obligation.predicate,
368&mut obligations,
369 );
370 obligation.predicate = normalized_predicate;
371 obligations.push(obligation);
372 }
373obligations374 }
375376/// Pushes the obligations required for `trait_ref` to be WF into `self.out`.
377fn add_wf_preds_for_trait_pred(
378&mut self,
379 trait_pred: ty::TraitPredicate<'tcx>,
380 elaborate: Elaborate,
381 ) {
382let tcx = self.tcx();
383let trait_ref = trait_pred.trait_ref;
384385// Negative trait predicates don't require supertraits to hold, just
386 // that their args are WF.
387if trait_pred.polarity == ty::PredicatePolarity::Negative {
388self.add_wf_preds_for_negative_trait_pred(trait_ref);
389return;
390 }
391392// if the trait predicate is not const, the wf obligations should not be const as well.
393let obligations = self.nominal_obligations(trait_ref.def_id, trait_ref.args);
394395{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/wf.rs:395",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(395u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
::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!("compute_trait_pred obligations {0:?}",
obligations) as &dyn Value))])
});
} else { ; }
};debug!("compute_trait_pred obligations {:?}", obligations);
396let param_env = self.param_env;
397let depth = self.recursion_depth;
398399let item = self.item;
400401let extend = |traits::PredicateObligation { predicate, mut cause, .. }| {
402if let Some(parent_trait_pred) = predicate.as_trait_clause() {
403cause = cause.derived_cause(
404parent_trait_pred,
405 traits::ObligationCauseCode::WellFormedDerived,
406 );
407 }
408extend_cause_with_original_assoc_item_obligation(tcx, item, &mut cause, predicate);
409 traits::Obligation::with_depth(tcx, cause, depth, param_env, predicate)
410 };
411412if let Elaborate::All = elaborate {
413let implied_obligations = traits::util::elaborate(tcx, obligations);
414let implied_obligations = implied_obligations.map(extend);
415self.out.extend(implied_obligations);
416 } else {
417self.out.extend(obligations);
418 }
419420self.out.extend(
421trait_ref422 .args
423 .iter()
424 .enumerate()
425 .filter_map(|(i, arg)| arg.as_term().map(|t| (i, t)))
426 .filter(|(_, term)| !term.has_escaping_bound_vars())
427 .map(|(i, term)| {
428let mut cause = traits::ObligationCause::misc(self.span, self.body_id);
429// The first arg is the self ty - use the correct span for it.
430if i == 0 {
431if let Some(hir::ItemKind::Impl(hir::Impl { self_ty, .. })) =
432item.map(|i| &i.kind)
433 {
434cause.span = self_ty.span;
435 }
436 }
437 traits::Obligation::with_depth(
438tcx,
439cause,
440depth,
441param_env,
442 ty::ClauseKind::WellFormed(term),
443 )
444 }),
445 );
446 }
447448// Compute the obligations that are required for `trait_ref` to be WF,
449 // given that it is a *negative* trait predicate.
450fn add_wf_preds_for_negative_trait_pred(&mut self, trait_ref: ty::TraitRef<'tcx>) {
451for arg in trait_ref.args {
452if let Some(term) = arg.as_term() {
453self.add_wf_preds_for_term(term);
454 }
455 }
456 }
457458/// Pushes the obligations required for an alias (except inherent) to be WF
459 /// into `self.out`.
460fn add_wf_preds_for_alias_term(&mut self, data: ty::AliasTerm<'tcx>) {
461// A projection is well-formed if
462 //
463 // (a) its predicates hold (*)
464 // (b) its args are wf
465 //
466 // (*) The predicates of an associated type include the predicates of
467 // the trait that it's contained in. For example, given
468 //
469 // trait A<T>: Clone {
470 // type X where T: Copy;
471 // }
472 //
473 // The predicates of `<() as A<i32>>::X` are:
474 // [
475 // `(): Sized`
476 // `(): Clone`
477 // `(): A<i32>`
478 // `i32: Sized`
479 // `i32: Clone`
480 // `i32: Copy`
481 // ]
482let obligations = self.nominal_obligations(data.def_id, data.args);
483self.out.extend(obligations);
484485self.add_wf_preds_for_projection_args(data.args);
486 }
487488/// Pushes the obligations required for an inherent alias to be WF
489 /// into `self.out`.
490// FIXME(inherent_associated_types): Merge this function with `fn compute_alias`.
491fn add_wf_preds_for_inherent_projection(&mut self, data: ty::AliasTerm<'tcx>) {
492// An inherent projection is well-formed if
493 //
494 // (a) its predicates hold (*)
495 // (b) its args are wf
496 //
497 // (*) The predicates of an inherent associated type include the
498 // predicates of the impl that it's contained in.
499500if !data.self_ty().has_escaping_bound_vars() {
501// FIXME(inherent_associated_types): Should this happen inside of a snapshot?
502 // FIXME(inherent_associated_types): This is incompatible with the new solver and lazy norm!
503let args = traits::project::compute_inherent_assoc_term_args(
504&mut traits::SelectionContext::new(self.infcx),
505self.param_env,
506data,
507self.cause(ObligationCauseCode::WellFormed(None)),
508self.recursion_depth,
509&mut self.out,
510 );
511let obligations = self.nominal_obligations(data.def_id, args);
512self.out.extend(obligations);
513 }
514515data.args.visit_with(self);
516 }
517518fn add_wf_preds_for_projection_args(&mut self, args: GenericArgsRef<'tcx>) {
519let tcx = self.tcx();
520let cause = self.cause(ObligationCauseCode::WellFormed(None));
521let param_env = self.param_env;
522let depth = self.recursion_depth;
523524self.out.extend(
525args.iter()
526 .filter_map(|arg| arg.as_term())
527 .filter(|term| !term.has_escaping_bound_vars())
528 .map(|term| {
529 traits::Obligation::with_depth(
530tcx,
531cause.clone(),
532depth,
533param_env,
534 ty::ClauseKind::WellFormed(term),
535 )
536 }),
537 );
538 }
539540fn require_sized(&mut self, subty: Ty<'tcx>, cause: traits::ObligationCauseCode<'tcx>) {
541if !subty.has_escaping_bound_vars() {
542let cause = self.cause(cause);
543let trait_ref = ty::TraitRef::new(
544self.tcx(),
545self.tcx().require_lang_item(LangItem::Sized, cause.span),
546 [subty],
547 );
548self.out.push(traits::Obligation::with_depth(
549self.tcx(),
550cause,
551self.recursion_depth,
552self.param_env,
553 ty::Binder::dummy(trait_ref),
554 ));
555 }
556 }
557558/// Pushes all the predicates needed to validate that `term` is WF into `out`.
559#[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_wf_preds_for_term",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(559u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
::tracing_core::field::FieldSet::new(&["term"],
::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(&term)
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;
}
{
term.visit_with(self);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/wf.rs:562",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(562u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
::tracing_core::field::FieldSet::new(&["self.out"],
::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(&self.out)
as &dyn Value))])
});
} else { ; }
};
}
}
}#[instrument(level = "debug", skip(self))]560fn add_wf_preds_for_term(&mut self, term: Term<'tcx>) {
561 term.visit_with(self);
562debug!(?self.out);
563 }
564565#[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("nominal_obligations",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(565u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
::tracing_core::field::FieldSet::new(&["def_id", "args"],
::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)),
(&::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))])
})
} 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: PredicateObligations<'tcx> =
loop {};
return __tracing_attr_fake_return;
}
{
if self.tcx().is_lang_item(def_id, LangItem::Sized) {
return Default::default();
}
let predicates = self.tcx().predicates_of(def_id);
let mut origins =
::alloc::vec::from_elem(def_id, predicates.predicates.len());
let mut head = predicates;
while let Some(parent) = head.parent {
head = self.tcx().predicates_of(parent);
origins.extend(iter::repeat(parent).take(head.predicates.len()));
}
let predicates = predicates.instantiate(self.tcx(), args);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/wf.rs:588",
"rustc_trait_selection::traits::wf",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(588u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::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!("{0:#?}",
predicates) as &dyn Value))])
});
} else { ; }
};
if true {
match (&predicates.predicates.len(), &origins.len()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
};
iter::zip(predicates,
origins.into_iter().rev()).map(|((pred, span),
origin_def_id)|
{
let code =
ObligationCauseCode::WhereClause(origin_def_id, span);
let cause = self.cause(code);
traits::Obligation::with_depth(self.tcx(), cause,
self.recursion_depth, self.param_env, pred)
}).filter(|pred| !pred.has_escaping_bound_vars()).collect()
}
}
}#[instrument(level = "debug", skip(self))]566fn nominal_obligations(
567&mut self,
568 def_id: DefId,
569 args: GenericArgsRef<'tcx>,
570 ) -> PredicateObligations<'tcx> {
571// PERF: `Sized`'s predicates include `MetaSized`, but both are compiler implemented marker
572 // traits, so `MetaSized` will always be WF if `Sized` is WF and vice-versa. Determining
573 // the nominal obligations of `Sized` would in-effect just elaborate `MetaSized` and make
574 // the compiler do a bunch of work needlessly.
575if self.tcx().is_lang_item(def_id, LangItem::Sized) {
576return Default::default();
577 }
578579let predicates = self.tcx().predicates_of(def_id);
580let mut origins = vec![def_id; predicates.predicates.len()];
581let mut head = predicates;
582while let Some(parent) = head.parent {
583 head = self.tcx().predicates_of(parent);
584 origins.extend(iter::repeat(parent).take(head.predicates.len()));
585 }
586587let predicates = predicates.instantiate(self.tcx(), args);
588trace!("{:#?}", predicates);
589debug_assert_eq!(predicates.predicates.len(), origins.len());
590591 iter::zip(predicates, origins.into_iter().rev())
592 .map(|((pred, span), origin_def_id)| {
593let code = ObligationCauseCode::WhereClause(origin_def_id, span);
594let cause = self.cause(code);
595 traits::Obligation::with_depth(
596self.tcx(),
597 cause,
598self.recursion_depth,
599self.param_env,
600 pred,
601 )
602 })
603 .filter(|pred| !pred.has_escaping_bound_vars())
604 .collect()
605 }
606607fn add_wf_preds_for_dyn_ty(
608&mut self,
609 ty: Ty<'tcx>,
610 data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
611 region: ty::Region<'tcx>,
612 ) {
613// Imagine a type like this:
614 //
615 // trait Foo { }
616 // trait Bar<'c> : 'c { }
617 //
618 // &'b (Foo+'c+Bar<'d>)
619 // ^
620 //
621 // In this case, the following relationships must hold:
622 //
623 // 'b <= 'c
624 // 'd <= 'c
625 //
626 // The first conditions is due to the normal region pointer
627 // rules, which say that a reference cannot outlive its
628 // referent.
629 //
630 // The final condition may be a bit surprising. In particular,
631 // you may expect that it would have been `'c <= 'd`, since
632 // usually lifetimes of outer things are conservative
633 // approximations for inner things. However, it works somewhat
634 // differently with trait objects: here the idea is that if the
635 // user specifies a region bound (`'c`, in this case) it is the
636 // "master bound" that *implies* that bounds from other traits are
637 // all met. (Remember that *all bounds* in a type like
638 // `Foo+Bar+Zed` must be met, not just one, hence if we write
639 // `Foo<'x>+Bar<'y>`, we know that the type outlives *both* 'x and
640 // 'y.)
641 //
642 // Note: in fact we only permit builtin traits, not `Bar<'d>`, I
643 // am looking forward to the future here.
644if !data.has_escaping_bound_vars() && !region.has_escaping_bound_vars() {
645let implicit_bounds = object_region_bounds(self.tcx(), data);
646647let explicit_bound = region;
648649self.out.reserve(implicit_bounds.len());
650for implicit_bound in implicit_bounds {
651let cause = self.cause(ObligationCauseCode::ObjectTypeBound(ty, explicit_bound));
652let outlives =
653 ty::Binder::dummy(ty::OutlivesPredicate(explicit_bound, implicit_bound));
654self.out.push(traits::Obligation::with_depth(
655self.tcx(),
656 cause,
657self.recursion_depth,
658self.param_env,
659 outlives,
660 ));
661 }
662663// We don't add any wf predicates corresponding to the trait ref's generic arguments
664 // which allows code like this to compile:
665 // ```rust
666 // trait Trait<T: Sized> {}
667 // fn foo(_: &dyn Trait<[u32]>) {}
668 // ```
669}
670 }
671672fn add_wf_preds_for_pat_ty(&mut self, base_ty: Ty<'tcx>, pat: ty::Pattern<'tcx>) {
673let tcx = self.tcx();
674match *pat {
675 ty::PatternKind::Range { start, end } => {
676let mut check = |c| {
677let cause = self.cause(ObligationCauseCode::Misc);
678self.out.push(traits::Obligation::with_depth(
679tcx,
680cause.clone(),
681self.recursion_depth,
682self.param_env,
683 ty::Binder::dummy(ty::PredicateKind::Clause(
684 ty::ClauseKind::ConstArgHasType(c, base_ty),
685 )),
686 ));
687if !tcx.features().generic_pattern_types() {
688if c.has_param() {
689if self.span.is_dummy() {
690self.tcx()
691 .dcx()
692 .delayed_bug("feature error should be reported elsewhere, too");
693 } else {
694feature_err(
695&self.tcx().sess,
696 sym::generic_pattern_types,
697self.span,
698"wraparound pattern type ranges cause monomorphization time errors",
699 )
700 .emit();
701 }
702 }
703 }
704 };
705check(start);
706check(end);
707 }
708 ty::PatternKind::NotNull => {}
709 ty::PatternKind::Or(patterns) => {
710for pat in patterns {
711self.add_wf_preds_for_pat_ty(base_ty, pat)
712 }
713 }
714 }
715 }
716}
717718impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for WfPredicates<'a, 'tcx> {
719fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
720{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/wf.rs:720",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(720u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
::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!("wf bounds for t={0:?} t.kind={1:#?}",
t, t.kind()) as &dyn Value))])
});
} else { ; }
};debug!("wf bounds for t={:?} t.kind={:#?}", t, t.kind());
721722let tcx = self.tcx();
723724match *t.kind() {
725 ty::Bool726 | ty::Char727 | ty::Int(..)
728 | ty::Uint(..)
729 | ty::Float(..)
730 | ty::Error(_)
731 | ty::Str732 | ty::CoroutineWitness(..)
733 | ty::Never734 | ty::Param(_)
735 | ty::Bound(..)
736 | ty::Placeholder(..)
737 | ty::Foreign(..) => {
738// WfScalar, WfParameter, etc
739}
740741// Can only infer to `ty::Int(_) | ty::Uint(_)`.
742ty::Infer(ty::IntVar(_)) => {}
743744// Can only infer to `ty::Float(_)`.
745ty::Infer(ty::FloatVar(_)) => {}
746747 ty::Slice(subty) => {
748self.require_sized(subty, ObligationCauseCode::SliceOrArrayElem);
749 }
750751 ty::Array(subty, len) => {
752self.require_sized(subty, ObligationCauseCode::SliceOrArrayElem);
753// Note that the len being WF is implicitly checked while visiting.
754 // Here we just check that it's of type usize.
755let cause = self.cause(ObligationCauseCode::ArrayLen(t));
756self.out.push(traits::Obligation::with_depth(
757tcx,
758cause,
759self.recursion_depth,
760self.param_env,
761 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(
762len,
763tcx.types.usize,
764 ))),
765 ));
766 }
767768 ty::Pat(base_ty, pat) => {
769self.require_sized(base_ty, ObligationCauseCode::Misc);
770self.add_wf_preds_for_pat_ty(base_ty, pat);
771 }
772773 ty::Tuple(tys) => {
774if let Some((last, rest)) = tys.split_last() {
775for &elem in rest {
776self.require_sized(elem, ObligationCauseCode::TupleElem);
777if elem.is_scalable_vector() && !self.span.is_dummy() {
778self.tcx()
779 .dcx()
780 .struct_span_err(
781self.span,
782"scalable vectors cannot be tuple fields",
783 )
784 .emit();
785 }
786 }
787788if last.is_scalable_vector() && !self.span.is_dummy() {
789self.tcx()
790 .dcx()
791 .struct_span_err(self.span, "scalable vectors cannot be tuple fields")
792 .emit();
793 }
794 }
795 }
796797 ty::RawPtr(_, _) => {
798// Simple cases that are WF if their type args are WF.
799}
800801 ty::Alias(ty::Projection | ty::Opaque | ty::Free, data) => {
802let obligations = self.nominal_obligations(data.def_id, data.args);
803self.out.extend(obligations);
804 }
805 ty::Alias(ty::Inherent, data) => {
806self.add_wf_preds_for_inherent_projection(data.into());
807return; // Subtree handled by compute_inherent_projection.
808}
809810 ty::Adt(def, args) => {
811// WfNominalType
812let obligations = self.nominal_obligations(def.did(), args);
813self.out.extend(obligations);
814 }
815816 ty::FnDef(did, args) => {
817// HACK: Check the return type of function definitions for
818 // well-formedness to mostly fix #84533. This is still not
819 // perfect and there may be ways to abuse the fact that we
820 // ignore requirements with escaping bound vars. That's a
821 // more general issue however.
822let fn_sig = tcx.fn_sig(did).instantiate(tcx, args);
823fn_sig.output().skip_binder().visit_with(self);
824825let obligations = self.nominal_obligations(did, args);
826self.out.extend(obligations);
827 }
828829 ty::Ref(r, rty, _) => {
830// WfReference
831if !r.has_escaping_bound_vars() && !rty.has_escaping_bound_vars() {
832let cause = self.cause(ObligationCauseCode::ReferenceOutlivesReferent(t));
833self.out.push(traits::Obligation::with_depth(
834tcx,
835cause,
836self.recursion_depth,
837self.param_env,
838 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(
839 ty::OutlivesPredicate(rty, r),
840 ))),
841 ));
842 }
843 }
844845 ty::Coroutine(did, args, ..) => {
846// Walk ALL the types in the coroutine: this will
847 // include the upvar types as well as the yield
848 // type. Note that this is mildly distinct from
849 // the closure case, where we have to be careful
850 // about the signature of the closure. We don't
851 // have the problem of implied bounds here since
852 // coroutines don't take arguments.
853let obligations = self.nominal_obligations(did, args);
854self.out.extend(obligations);
855 }
856857 ty::Closure(did, args) => {
858// Note that we cannot skip the generic types
859 // types. Normally, within the fn
860 // body where they are created, the generics will
861 // always be WF, and outside of that fn body we
862 // are not directly inspecting closure types
863 // anyway, except via auto trait matching (which
864 // only inspects the upvar types).
865 // But when a closure is part of a type-alias-impl-trait
866 // then the function that created the defining site may
867 // have had more bounds available than the type alias
868 // specifies. This may cause us to have a closure in the
869 // hidden type that is not actually well formed and
870 // can cause compiler crashes when the user abuses unsafe
871 // code to procure such a closure.
872 // See tests/ui/type-alias-impl-trait/wf_check_closures.rs
873let obligations = self.nominal_obligations(did, args);
874self.out.extend(obligations);
875// Only check the upvar types for WF, not the rest
876 // of the types within. This is needed because we
877 // capture the signature and it may not be WF
878 // without the implied bounds. Consider a closure
879 // like `|x: &'a T|` -- it may be that `T: 'a` is
880 // not known to hold in the creator's context (and
881 // indeed the closure may not be invoked by its
882 // creator, but rather turned to someone who *can*
883 // verify that).
884 //
885 // The special treatment of closures here really
886 // ought not to be necessary either; the problem
887 // is related to #25860 -- there is no way for us
888 // to express a fn type complete with the implied
889 // bounds that it is assuming. I think in reality
890 // the WF rules around fn are a bit messed up, and
891 // that is the rot problem: `fn(&'a T)` should
892 // probably always be WF, because it should be
893 // shorthand for something like `where(T: 'a) {
894 // fn(&'a T) }`, as discussed in #25860.
895let upvars = args.as_closure().tupled_upvars_ty();
896return upvars.visit_with(self);
897 }
898899 ty::CoroutineClosure(did, args) => {
900// See the above comments. The same apply to coroutine-closures.
901let obligations = self.nominal_obligations(did, args);
902self.out.extend(obligations);
903let upvars = args.as_coroutine_closure().tupled_upvars_ty();
904return upvars.visit_with(self);
905 }
906907 ty::FnPtr(..) => {
908// Let the visitor iterate into the argument/return
909 // types appearing in the fn signature.
910}
911 ty::UnsafeBinder(ty) => {
912// FIXME(unsafe_binders): For now, we have no way to express
913 // that a type must be `ManuallyDrop` OR `Copy` (or a pointer).
914if !ty.has_escaping_bound_vars() {
915self.out.push(traits::Obligation::new(
916self.tcx(),
917self.cause(ObligationCauseCode::Misc),
918self.param_env,
919ty.map_bound(|ty| {
920 ty::TraitRef::new(
921self.tcx(),
922self.tcx().require_lang_item(
923 LangItem::BikeshedGuaranteedNoDrop,
924self.span,
925 ),
926 [ty],
927 )
928 }),
929 ));
930 }
931932// We recurse into the binder below.
933}
934935 ty::Dynamic(data, r) => {
936// WfObject
937 //
938 // Here, we defer WF checking due to higher-ranked
939 // regions. This is perhaps not ideal.
940self.add_wf_preds_for_dyn_ty(t, data, r);
941942// FIXME(#27579) RFC also considers adding trait
943 // obligations that don't refer to Self and
944 // checking those
945if let Some(principal) = data.principal_def_id() {
946self.out.push(traits::Obligation::with_depth(
947tcx,
948self.cause(ObligationCauseCode::WellFormed(None)),
949self.recursion_depth,
950self.param_env,
951 ty::Binder::dummy(ty::PredicateKind::DynCompatible(principal)),
952 ));
953 }
954 }
955956// Inference variables are the complicated case, since we don't
957 // know what type they are. We do two things:
958 //
959 // 1. Check if they have been resolved, and if so proceed with
960 // THAT type.
961 // 2. If not, we've at least simplified things (e.g., we went
962 // from `Vec?0>: WF` to `?0: WF`), so we can
963 // register a pending obligation and keep
964 // moving. (Goal is that an "inductive hypothesis"
965 // is satisfied to ensure termination.)
966 // See also the comment on `fn obligations`, describing cycle
967 // prevention, which happens before this can be reached.
968ty::Infer(_) => {
969let cause = self.cause(ObligationCauseCode::WellFormed(None));
970self.out.push(traits::Obligation::with_depth(
971tcx,
972cause,
973self.recursion_depth,
974self.param_env,
975 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(
976t.into(),
977 ))),
978 ));
979 }
980 }
981982t.super_visit_with(self)
983 }
984985fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
986let tcx = self.tcx();
987988match c.kind() {
989 ty::ConstKind::Unevaluated(uv) => {
990if !c.has_escaping_bound_vars() {
991let predicate = ty::Binder::dummy(ty::PredicateKind::Clause(
992 ty::ClauseKind::ConstEvaluatable(c),
993 ));
994let cause = self.cause(ObligationCauseCode::WellFormed(None));
995self.out.push(traits::Obligation::with_depth(
996tcx,
997cause,
998self.recursion_depth,
999self.param_env,
1000predicate,
1001 ));
10021003if tcx.def_kind(uv.def) == DefKind::AssocConst1004 && tcx.def_kind(tcx.parent(uv.def)) == (DefKind::Impl { of_trait: false })
1005 {
1006self.add_wf_preds_for_inherent_projection(uv.into());
1007return; // Subtree is handled by above function
1008} else {
1009let obligations = self.nominal_obligations(uv.def, uv.args);
1010self.out.extend(obligations);
1011 }
1012 }
1013 }
1014 ty::ConstKind::Infer(_) => {
1015let cause = self.cause(ObligationCauseCode::WellFormed(None));
10161017self.out.push(traits::Obligation::with_depth(
1018tcx,
1019cause,
1020self.recursion_depth,
1021self.param_env,
1022 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(
1023c.into(),
1024 ))),
1025 ));
1026 }
1027 ty::ConstKind::Expr(_) => {
1028// FIXME(generic_const_exprs): this doesn't verify that given `Expr(N + 1)` the
1029 // trait bound `typeof(N): Add<typeof(1)>` holds. This is currently unnecessary
1030 // as `ConstKind::Expr` is only produced via normalization of `ConstKind::Unevaluated`
1031 // which means that the `DefId` would have been typeck'd elsewhere. However in
1032 // the future we may allow directly lowering to `ConstKind::Expr` in which case
1033 // we would not be proving bounds we should.
10341035let predicate = ty::Binder::dummy(ty::PredicateKind::Clause(
1036 ty::ClauseKind::ConstEvaluatable(c),
1037 ));
1038let cause = self.cause(ObligationCauseCode::WellFormed(None));
1039self.out.push(traits::Obligation::with_depth(
1040tcx,
1041cause,
1042self.recursion_depth,
1043self.param_env,
1044predicate,
1045 ));
1046 }
10471048 ty::ConstKind::Error(_)
1049 | ty::ConstKind::Param(_)
1050 | ty::ConstKind::Bound(..)
1051 | ty::ConstKind::Placeholder(..) => {
1052// These variants are trivially WF, so nothing to do here.
1053}
1054 ty::ConstKind::Value(val) => {
1055// FIXME(mgca): no need to feature-gate once valtree lifetimes are not erased
1056if tcx.features().min_generic_const_args() {
1057match val.ty.kind() {
1058 ty::Adt(adt_def, args) => {
1059let adt_val = val.destructure_adt_const();
1060let variant_def = adt_def.variant(adt_val.variant);
1061let cause = self.cause(ObligationCauseCode::WellFormed(None));
1062self.out.extend(variant_def.fields.iter().zip(adt_val.fields).map(
1063 |(field_def, &field_val)| {
1064let field_ty =
1065tcx.type_of(field_def.did).instantiate(tcx, args);
1066let predicate = ty::PredicateKind::Clause(
1067 ty::ClauseKind::ConstArgHasType(field_val, field_ty),
1068 );
1069 traits::Obligation::with_depth(
1070tcx,
1071cause.clone(),
1072self.recursion_depth,
1073self.param_env,
1074predicate,
1075 )
1076 },
1077 ));
1078 }
1079 ty::Tuple(field_tys) => {
1080let field_vals = val.to_branch();
1081let cause = self.cause(ObligationCauseCode::WellFormed(None));
1082self.out.extend(field_tys.iter().zip(field_vals).map(
1083 |(field_ty, &field_val)| {
1084let predicate = ty::PredicateKind::Clause(
1085 ty::ClauseKind::ConstArgHasType(field_val, field_ty),
1086 );
1087 traits::Obligation::with_depth(
1088tcx,
1089cause.clone(),
1090self.recursion_depth,
1091self.param_env,
1092predicate,
1093 )
1094 },
1095 ));
1096 }
1097_ => {}
1098 }
1099 }
11001101// FIXME: Enforce that values are structurally-matchable.
1102}
1103 }
11041105c.super_visit_with(self)
1106 }
11071108fn visit_predicate(&mut self, _p: ty::Predicate<'tcx>) -> Self::Result {
1109::rustc_middle::util::bug::bug_fmt(format_args!("predicate should not be checked for well-formedness"));bug!("predicate should not be checked for well-formedness");
1110 }
1111}
11121113/// Given an object type like `SomeTrait + Send`, computes the lifetime
1114/// bounds that must hold on the elided self type. These are derived
1115/// from the declarations of `SomeTrait`, `Send`, and friends -- if
1116/// they declare `trait SomeTrait : 'static`, for example, then
1117/// `'static` would appear in the list.
1118///
1119/// N.B., in some cases, particularly around higher-ranked bounds,
1120/// this function returns a kind of conservative approximation.
1121/// That is, all regions returned by this function are definitely
1122/// required, but there may be other region bounds that are not
1123/// returned, as well as requirements like `for<'a> T: 'a`.
1124///
1125/// Requires that trait definitions have been processed so that we can
1126/// elaborate predicates and walk supertraits.
1127pub fn object_region_bounds<'tcx>(
1128 tcx: TyCtxt<'tcx>,
1129 existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1130) -> Vec<ty::Region<'tcx>> {
1131let erased_self_ty = tcx.types.trait_object_dummy_self;
11321133let predicates =
1134existential_predicates.iter().map(|predicate| predicate.with_self_ty(tcx, erased_self_ty));
11351136 traits::elaborate(tcx, predicates)
1137 .filter_map(|pred| {
1138{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/wf.rs:1138",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(1138u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
::tracing_core::field::FieldSet::new(&["pred"],
::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(&pred) as
&dyn Value))])
});
} else { ; }
};debug!(?pred);
1139match pred.kind().skip_binder() {
1140 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ref t, ref r)) => {
1141// Search for a bound of the form `erased_self_ty
1142 // : 'a`, but be wary of something like `for<'a>
1143 // erased_self_ty : 'a` (we interpret a
1144 // higher-ranked bound like that as 'static,
1145 // though at present the code in `fulfill.rs`
1146 // considers such bounds to be unsatisfiable, so
1147 // it's kind of a moot point since you could never
1148 // construct such an object, but this seems
1149 // correct even if that code changes).
1150if t == &erased_self_ty && !r.has_escaping_bound_vars() {
1151Some(*r)
1152 } else {
1153None1154 }
1155 }
1156 ty::ClauseKind::Trait(_)
1157 | ty::ClauseKind::HostEffect(..)
1158 | ty::ClauseKind::RegionOutlives(_)
1159 | ty::ClauseKind::Projection(_)
1160 | ty::ClauseKind::ConstArgHasType(_, _)
1161 | ty::ClauseKind::WellFormed(_)
1162 | ty::ClauseKind::UnstableFeature(_)
1163 | ty::ClauseKind::ConstEvaluatable(_) => None,
1164 }
1165 })
1166 .collect()
1167}