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() {
41TermKind::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 }
56TermKind::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_fields_are_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::AliasTy { kind: ty::Projection { def_id }, .. }) = ty.kind()
289 && let Some(&impl_item_id) = tcx.impl_item_implementor_ids(impl_def_id).get(def_id)
290 && let Some(impl_item) =
291items.iter().find(|item| item.owner_id.to_def_id() == impl_item_id)
292 {
293Some(tcx.hir_impl_item(*impl_item).expect_type().span)
294 } else {
295None296 }
297 };
298299// It is fine to skip the binder as we don't care about regions here.
300match pred.kind().skip_binder() {
301 ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)) => {
302// Form 1: The obligation comes not from the current `impl` nor the `trait` being
303 // implemented, but rather from a "second order" obligation, where an associated
304 // type has a projection coming from another associated type.
305 // See `tests/ui/traits/assoc-type-in-superbad.rs` for an example.
306if let Some(term_ty) = proj.term.as_type()
307 && let Some(impl_item_span) = ty_to_impl_span(term_ty)
308 {
309cause.span = impl_item_span;
310 }
311312// Form 2: A projection obligation for an associated item failed to be met.
313 // We overwrite the span from above to ensure that a bound like
314 // `Self::Assoc1: Trait<OtherAssoc = Self::Assoc2>` gets the same
315 // span for both obligations that it is lowered to.
316if let Some(impl_item_span) = ty_to_impl_span(proj.self_ty()) {
317cause.span = impl_item_span;
318 }
319 }
320321 ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
322// Form 3: A trait obligation for an associated item failed to be met.
323{
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:323",
"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(323u32),
::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);
324if let Some(impl_item_span) = ty_to_impl_span(pred.self_ty()) {
325cause.span = impl_item_span;
326 }
327 }
328_ => {}
329 }
330}
331332impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
333fn tcx(&self) -> TyCtxt<'tcx> {
334self.infcx.tcx
335 }
336337fn cause(&self, code: traits::ObligationCauseCode<'tcx>) -> traits::ObligationCause<'tcx> {
338 traits::ObligationCause::new(self.span, self.body_id, code)
339 }
340341fn normalize(self, infcx: &InferCtxt<'tcx>) -> PredicateObligations<'tcx> {
342// Do not normalize `wf` obligations with the new solver.
343 //
344 // The current deep normalization routine with the new solver does not
345 // handle ambiguity and the new solver correctly deals with unnnormalized goals.
346 // If the user relies on normalized types, e.g. for `fn implied_outlives_bounds`,
347 // it is their responsibility to normalize while avoiding ambiguity.
348if infcx.next_trait_solver() {
349return self.out;
350 }
351352let cause = self.cause(ObligationCauseCode::WellFormed(None));
353let param_env = self.param_env;
354let mut obligations = PredicateObligations::with_capacity(self.out.len());
355for mut obligation in self.out {
356if !!obligation.has_escaping_bound_vars() {
::core::panicking::panic("assertion failed: !obligation.has_escaping_bound_vars()")
};assert!(!obligation.has_escaping_bound_vars());
357let mut selcx = traits::SelectionContext::new(infcx);
358// Don't normalize the whole obligation, the param env is either
359 // already normalized, or we're currently normalizing the
360 // param_env. Either way we should only normalize the predicate.
361let normalized_predicate = traits::normalize::normalize_with_depth_to(
362&mut selcx,
363 param_env,
364 cause.clone(),
365self.recursion_depth,
366 obligation.predicate,
367&mut obligations,
368 );
369 obligation.predicate = normalized_predicate;
370 obligations.push(obligation);
371 }
372obligations373 }
374375/// Pushes the obligations required for `trait_ref` to be WF into `self.out`.
376fn add_wf_preds_for_trait_pred(
377&mut self,
378 trait_pred: ty::TraitPredicate<'tcx>,
379 elaborate: Elaborate,
380 ) {
381let tcx = self.tcx();
382let trait_ref = trait_pred.trait_ref;
383384// Negative trait predicates don't require supertraits to hold, just
385 // that their args are WF.
386if trait_pred.polarity == ty::PredicatePolarity::Negative {
387self.add_wf_preds_for_negative_trait_pred(trait_ref);
388return;
389 }
390391// if the trait predicate is not const, the wf obligations should not be const as well.
392let obligations = self.nominal_obligations(trait_ref.def_id, trait_ref.args);
393394{
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:394",
"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(394u32),
::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);
395let param_env = self.param_env;
396let depth = self.recursion_depth;
397398let item = self.item;
399400let extend = |traits::PredicateObligation { predicate, mut cause, .. }| {
401if let Some(parent_trait_pred) = predicate.as_trait_clause() {
402cause = cause.derived_cause(
403parent_trait_pred,
404 traits::ObligationCauseCode::WellFormedDerived,
405 );
406 }
407extend_cause_with_original_assoc_item_obligation(tcx, item, &mut cause, predicate);
408 traits::Obligation::with_depth(tcx, cause, depth, param_env, predicate)
409 };
410411if let Elaborate::All = elaborate {
412let implied_obligations = traits::util::elaborate(tcx, obligations);
413let implied_obligations = implied_obligations.map(extend);
414self.out.extend(implied_obligations);
415 } else {
416self.out.extend(obligations);
417 }
418419self.out.extend(
420trait_ref421 .args
422 .iter()
423 .enumerate()
424 .filter_map(|(i, arg)| arg.as_term().map(|t| (i, t)))
425 .filter(|(_, term)| !term.has_escaping_bound_vars())
426 .map(|(i, term)| {
427let mut cause = traits::ObligationCause::misc(self.span, self.body_id);
428// The first arg is the self ty - use the correct span for it.
429if i == 0 {
430if let Some(hir::ItemKind::Impl(hir::Impl { self_ty, .. })) =
431item.map(|i| &i.kind)
432 {
433cause.span = self_ty.span;
434 }
435 }
436 traits::Obligation::with_depth(
437tcx,
438cause,
439depth,
440param_env,
441 ty::ClauseKind::WellFormed(term),
442 )
443 }),
444 );
445 }
446447// Compute the obligations that are required for `trait_ref` to be WF,
448 // given that it is a *negative* trait predicate.
449fn add_wf_preds_for_negative_trait_pred(&mut self, trait_ref: ty::TraitRef<'tcx>) {
450for arg in trait_ref.args {
451if let Some(term) = arg.as_term() {
452self.add_wf_preds_for_term(term);
453 }
454 }
455 }
456457/// Pushes the obligations required for an alias (except inherent) to be WF
458 /// into `self.out`.
459fn add_wf_preds_for_alias_term(&mut self, data: ty::AliasTerm<'tcx>) {
460// A projection is well-formed if
461 //
462 // (a) its predicates hold (*)
463 // (b) its args are wf
464 //
465 // (*) The predicates of an associated type include the predicates of
466 // the trait that it's contained in. For example, given
467 //
468 // trait A<T>: Clone {
469 // type X where T: Copy;
470 // }
471 //
472 // The predicates of `<() as A<i32>>::X` are:
473 // [
474 // `(): Sized`
475 // `(): Clone`
476 // `(): A<i32>`
477 // `i32: Sized`
478 // `i32: Clone`
479 // `i32: Copy`
480 // ]
481let obligations = self.nominal_obligations(data.def_id, data.args);
482self.out.extend(obligations);
483484self.add_wf_preds_for_projection_args(data.args);
485 }
486487/// Pushes the obligations required for an inherent alias to be WF
488 /// into `self.out`.
489// FIXME(inherent_associated_types): Merge this function with `fn compute_alias`.
490fn add_wf_preds_for_inherent_projection(&mut self, data: ty::AliasTerm<'tcx>) {
491// An inherent projection is well-formed if
492 //
493 // (a) its predicates hold (*)
494 // (b) its args are wf
495 //
496 // (*) The predicates of an inherent associated type include the
497 // predicates of the impl that it's contained in.
498499if !data.self_ty().has_escaping_bound_vars() {
500// FIXME(inherent_associated_types): Should this happen inside of a snapshot?
501 // FIXME(inherent_associated_types): This is incompatible with the new solver and lazy norm!
502let args = traits::project::compute_inherent_assoc_term_args(
503&mut traits::SelectionContext::new(self.infcx),
504self.param_env,
505data,
506self.cause(ObligationCauseCode::WellFormed(None)),
507self.recursion_depth,
508&mut self.out,
509 );
510let obligations = self.nominal_obligations(data.def_id, args);
511self.out.extend(obligations);
512 }
513514data.args.visit_with(self);
515 }
516517fn add_wf_preds_for_projection_args(&mut self, args: GenericArgsRef<'tcx>) {
518let tcx = self.tcx();
519let cause = self.cause(ObligationCauseCode::WellFormed(None));
520let param_env = self.param_env;
521let depth = self.recursion_depth;
522523self.out.extend(
524args.iter()
525 .filter_map(|arg| arg.as_term())
526 .filter(|term| !term.has_escaping_bound_vars())
527 .map(|term| {
528 traits::Obligation::with_depth(
529tcx,
530cause.clone(),
531depth,
532param_env,
533 ty::ClauseKind::WellFormed(term),
534 )
535 }),
536 );
537 }
538539fn require_sized(&mut self, subty: Ty<'tcx>, cause: traits::ObligationCauseCode<'tcx>) {
540if !subty.has_escaping_bound_vars() {
541let cause = self.cause(cause);
542let trait_ref = ty::TraitRef::new(
543self.tcx(),
544self.tcx().require_lang_item(LangItem::Sized, cause.span),
545 [subty],
546 );
547self.out.push(traits::Obligation::with_depth(
548self.tcx(),
549cause,
550self.recursion_depth,
551self.param_env,
552 ty::Binder::dummy(trait_ref),
553 ));
554 }
555 }
556557/// Pushes all the predicates needed to validate that `term` is WF into `out`.
558#[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(558u32),
::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:561",
"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(561u32),
::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))]559fn add_wf_preds_for_term(&mut self, term: Term<'tcx>) {
560 term.visit_with(self);
561debug!(?self.out);
562 }
563564#[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(564u32),
::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:587",
"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(587u32),
::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))]565fn nominal_obligations(
566&mut self,
567 def_id: DefId,
568 args: GenericArgsRef<'tcx>,
569 ) -> PredicateObligations<'tcx> {
570// PERF: `Sized`'s predicates include `MetaSized`, but both are compiler implemented marker
571 // traits, so `MetaSized` will always be WF if `Sized` is WF and vice-versa. Determining
572 // the nominal obligations of `Sized` would in-effect just elaborate `MetaSized` and make
573 // the compiler do a bunch of work needlessly.
574if self.tcx().is_lang_item(def_id, LangItem::Sized) {
575return Default::default();
576 }
577578let predicates = self.tcx().predicates_of(def_id);
579let mut origins = vec![def_id; predicates.predicates.len()];
580let mut head = predicates;
581while let Some(parent) = head.parent {
582 head = self.tcx().predicates_of(parent);
583 origins.extend(iter::repeat(parent).take(head.predicates.len()));
584 }
585586let predicates = predicates.instantiate(self.tcx(), args);
587trace!("{:#?}", predicates);
588debug_assert_eq!(predicates.predicates.len(), origins.len());
589590 iter::zip(predicates, origins.into_iter().rev())
591 .map(|((pred, span), origin_def_id)| {
592let code = ObligationCauseCode::WhereClause(origin_def_id, span);
593let cause = self.cause(code);
594 traits::Obligation::with_depth(
595self.tcx(),
596 cause,
597self.recursion_depth,
598self.param_env,
599 pred,
600 )
601 })
602 .filter(|pred| !pred.has_escaping_bound_vars())
603 .collect()
604 }
605606fn add_wf_preds_for_dyn_ty(
607&mut self,
608 ty: Ty<'tcx>,
609 data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
610 region: ty::Region<'tcx>,
611 ) {
612// Imagine a type like this:
613 //
614 // trait Foo { }
615 // trait Bar<'c> : 'c { }
616 //
617 // &'b (Foo+'c+Bar<'d>)
618 // ^
619 //
620 // In this case, the following relationships must hold:
621 //
622 // 'b <= 'c
623 // 'd <= 'c
624 //
625 // The first conditions is due to the normal region pointer
626 // rules, which say that a reference cannot outlive its
627 // referent.
628 //
629 // The final condition may be a bit surprising. In particular,
630 // you may expect that it would have been `'c <= 'd`, since
631 // usually lifetimes of outer things are conservative
632 // approximations for inner things. However, it works somewhat
633 // differently with trait objects: here the idea is that if the
634 // user specifies a region bound (`'c`, in this case) it is the
635 // "master bound" that *implies* that bounds from other traits are
636 // all met. (Remember that *all bounds* in a type like
637 // `Foo+Bar+Zed` must be met, not just one, hence if we write
638 // `Foo<'x>+Bar<'y>`, we know that the type outlives *both* 'x and
639 // 'y.)
640 //
641 // Note: in fact we only permit builtin traits, not `Bar<'d>`, I
642 // am looking forward to the future here.
643if !data.has_escaping_bound_vars() && !region.has_escaping_bound_vars() {
644let implicit_bounds = object_region_bounds(self.tcx(), data);
645646let explicit_bound = region;
647648self.out.reserve(implicit_bounds.len());
649for implicit_bound in implicit_bounds {
650let cause = self.cause(ObligationCauseCode::ObjectTypeBound(ty, explicit_bound));
651let outlives =
652 ty::Binder::dummy(ty::OutlivesPredicate(explicit_bound, implicit_bound));
653self.out.push(traits::Obligation::with_depth(
654self.tcx(),
655 cause,
656self.recursion_depth,
657self.param_env,
658 outlives,
659 ));
660 }
661662// We don't add any wf predicates corresponding to the trait ref's generic arguments
663 // which allows code like this to compile:
664 // ```rust
665 // trait Trait<T: Sized> {}
666 // fn foo(_: &dyn Trait<[u32]>) {}
667 // ```
668}
669 }
670671fn add_wf_preds_for_pat_ty(&mut self, base_ty: Ty<'tcx>, pat: ty::Pattern<'tcx>) {
672let tcx = self.tcx();
673match *pat {
674 ty::PatternKind::Range { start, end } => {
675let mut check = |c| {
676let cause = self.cause(ObligationCauseCode::Misc);
677self.out.push(traits::Obligation::with_depth(
678tcx,
679cause.clone(),
680self.recursion_depth,
681self.param_env,
682 ty::Binder::dummy(ty::PredicateKind::Clause(
683 ty::ClauseKind::ConstArgHasType(c, base_ty),
684 )),
685 ));
686if !tcx.features().generic_pattern_types() {
687if c.has_param() {
688if self.span.is_dummy() {
689self.tcx()
690 .dcx()
691 .delayed_bug("feature error should be reported elsewhere, too");
692 } else {
693feature_err(
694&self.tcx().sess,
695 sym::generic_pattern_types,
696self.span,
697"wraparound pattern type ranges cause monomorphization time errors",
698 )
699 .emit();
700 }
701 }
702 }
703 };
704check(start);
705check(end);
706 }
707 ty::PatternKind::NotNull => {}
708 ty::PatternKind::Or(patterns) => {
709for pat in patterns {
710self.add_wf_preds_for_pat_ty(base_ty, pat)
711 }
712 }
713 }
714 }
715}
716717impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for WfPredicates<'a, 'tcx> {
718fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
719{
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:719",
"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(719u32),
::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());
720721let tcx = self.tcx();
722723match *t.kind() {
724 ty::Bool725 | ty::Char726 | ty::Int(..)
727 | ty::Uint(..)
728 | ty::Float(..)
729 | ty::Error(_)
730 | ty::Str731 | ty::CoroutineWitness(..)
732 | ty::Never733 | ty::Param(_)
734 | ty::Bound(..)
735 | ty::Placeholder(..)
736 | ty::Foreign(..) => {
737// WfScalar, WfParameter, etc
738}
739740// Can only infer to `ty::Int(_) | ty::Uint(_)`.
741ty::Infer(ty::IntVar(_)) => {}
742743// Can only infer to `ty::Float(_)`.
744ty::Infer(ty::FloatVar(_)) => {}
745746 ty::Slice(subty) => {
747self.require_sized(subty, ObligationCauseCode::SliceOrArrayElem);
748 }
749750 ty::Array(subty, len) => {
751self.require_sized(subty, ObligationCauseCode::SliceOrArrayElem);
752// Note that the len being WF is implicitly checked while visiting.
753 // Here we just check that it's of type usize.
754let cause = self.cause(ObligationCauseCode::ArrayLen(t));
755self.out.push(traits::Obligation::with_depth(
756tcx,
757cause,
758self.recursion_depth,
759self.param_env,
760 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(
761len,
762tcx.types.usize,
763 ))),
764 ));
765 }
766767 ty::Pat(base_ty, pat) => {
768self.require_sized(base_ty, ObligationCauseCode::Misc);
769self.add_wf_preds_for_pat_ty(base_ty, pat);
770 }
771772 ty::Tuple(tys) => {
773if let Some((last, rest)) = tys.split_last() {
774for &elem in rest {
775self.require_sized(elem, ObligationCauseCode::TupleElem);
776if elem.is_scalable_vector() && !self.span.is_dummy() {
777self.tcx()
778 .dcx()
779 .struct_span_err(
780self.span,
781"scalable vectors cannot be tuple fields",
782 )
783 .emit();
784 }
785 }
786787if last.is_scalable_vector() && !self.span.is_dummy() {
788self.tcx()
789 .dcx()
790 .struct_span_err(self.span, "scalable vectors cannot be tuple fields")
791 .emit();
792 }
793 }
794 }
795796 ty::RawPtr(_, _) => {
797// Simple cases that are WF if their type args are WF.
798}
799800 ty::Alias(ty::AliasTy {
801 kind: ty::Projection { def_id } | ty::Opaque { def_id } | ty::Free { def_id },
802 args,
803 ..
804 }) => {
805let obligations = self.nominal_obligations(def_id, args);
806self.out.extend(obligations);
807 }
808 ty::Alias(data @ ty::AliasTy { kind: ty::Inherent { .. }, .. }) => {
809self.add_wf_preds_for_inherent_projection(data.into());
810return; // Subtree handled by compute_inherent_projection.
811}
812813 ty::Adt(def, args) => {
814// WfNominalType
815let obligations = self.nominal_obligations(def.did(), args);
816self.out.extend(obligations);
817 }
818819 ty::FnDef(did, args) => {
820// HACK: Check the return type of function definitions for
821 // well-formedness to mostly fix #84533. This is still not
822 // perfect and there may be ways to abuse the fact that we
823 // ignore requirements with escaping bound vars. That's a
824 // more general issue however.
825let fn_sig = tcx.fn_sig(did).instantiate(tcx, args);
826fn_sig.output().skip_binder().visit_with(self);
827828let obligations = self.nominal_obligations(did, args);
829self.out.extend(obligations);
830 }
831832 ty::Ref(r, rty, _) => {
833// WfReference
834if !r.has_escaping_bound_vars() && !rty.has_escaping_bound_vars() {
835let cause = self.cause(ObligationCauseCode::ReferenceOutlivesReferent(t));
836self.out.push(traits::Obligation::with_depth(
837tcx,
838cause,
839self.recursion_depth,
840self.param_env,
841 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(
842 ty::OutlivesPredicate(rty, r),
843 ))),
844 ));
845 }
846 }
847848 ty::Coroutine(did, args, ..) => {
849// Walk ALL the types in the coroutine: this will
850 // include the upvar types as well as the yield
851 // type. Note that this is mildly distinct from
852 // the closure case, where we have to be careful
853 // about the signature of the closure. We don't
854 // have the problem of implied bounds here since
855 // coroutines don't take arguments.
856let obligations = self.nominal_obligations(did, args);
857self.out.extend(obligations);
858 }
859860 ty::Closure(did, args) => {
861// Note that we cannot skip the generic types
862 // types. Normally, within the fn
863 // body where they are created, the generics will
864 // always be WF, and outside of that fn body we
865 // are not directly inspecting closure types
866 // anyway, except via auto trait matching (which
867 // only inspects the upvar types).
868 // But when a closure is part of a type-alias-impl-trait
869 // then the function that created the defining site may
870 // have had more bounds available than the type alias
871 // specifies. This may cause us to have a closure in the
872 // hidden type that is not actually well formed and
873 // can cause compiler crashes when the user abuses unsafe
874 // code to procure such a closure.
875 // See tests/ui/type-alias-impl-trait/wf_check_closures.rs
876let obligations = self.nominal_obligations(did, args);
877self.out.extend(obligations);
878// Only check the upvar types for WF, not the rest
879 // of the types within. This is needed because we
880 // capture the signature and it may not be WF
881 // without the implied bounds. Consider a closure
882 // like `|x: &'a T|` -- it may be that `T: 'a` is
883 // not known to hold in the creator's context (and
884 // indeed the closure may not be invoked by its
885 // creator, but rather turned to someone who *can*
886 // verify that).
887 //
888 // The special treatment of closures here really
889 // ought not to be necessary either; the problem
890 // is related to #25860 -- there is no way for us
891 // to express a fn type complete with the implied
892 // bounds that it is assuming. I think in reality
893 // the WF rules around fn are a bit messed up, and
894 // that is the rot problem: `fn(&'a T)` should
895 // probably always be WF, because it should be
896 // shorthand for something like `where(T: 'a) {
897 // fn(&'a T) }`, as discussed in #25860.
898let upvars = args.as_closure().tupled_upvars_ty();
899return upvars.visit_with(self);
900 }
901902 ty::CoroutineClosure(did, args) => {
903// See the above comments. The same apply to coroutine-closures.
904let obligations = self.nominal_obligations(did, args);
905self.out.extend(obligations);
906let upvars = args.as_coroutine_closure().tupled_upvars_ty();
907return upvars.visit_with(self);
908 }
909910 ty::FnPtr(..) => {
911// Let the visitor iterate into the argument/return
912 // types appearing in the fn signature.
913}
914 ty::UnsafeBinder(ty) => {
915// FIXME(unsafe_binders): For now, we have no way to express
916 // that a type must be `ManuallyDrop` OR `Copy` (or a pointer).
917if !ty.has_escaping_bound_vars() {
918self.out.push(traits::Obligation::new(
919self.tcx(),
920self.cause(ObligationCauseCode::Misc),
921self.param_env,
922ty.map_bound(|ty| {
923 ty::TraitRef::new(
924self.tcx(),
925self.tcx().require_lang_item(
926 LangItem::BikeshedGuaranteedNoDrop,
927self.span,
928 ),
929 [ty],
930 )
931 }),
932 ));
933 }
934935// We recurse into the binder below.
936}
937938 ty::Dynamic(data, r) => {
939// WfObject
940 //
941 // Here, we defer WF checking due to higher-ranked
942 // regions. This is perhaps not ideal.
943self.add_wf_preds_for_dyn_ty(t, data, r);
944945// FIXME(#27579) RFC also considers adding trait
946 // obligations that don't refer to Self and
947 // checking those
948if let Some(principal) = data.principal() {
949let principal_def_id = principal.skip_binder().def_id;
950self.out.push(traits::Obligation::with_depth(
951tcx,
952self.cause(ObligationCauseCode::WellFormed(None)),
953self.recursion_depth,
954self.param_env,
955 ty::Binder::dummy(ty::PredicateKind::DynCompatible(principal_def_id)),
956 ));
957958// For the most part we don't add wf predicates corresponding to
959 // the trait ref's generic arguments which allows code like this
960 // to compile:
961 // ```rust
962 // trait Trait<T: Sized> {}
963 // fn foo(_: &dyn Trait<[u32]>) {}
964 // ```
965 //
966 // However, we sometimes incidentally check that const arguments
967 // have the correct type as a side effect of the anon const
968 // desugaring. To make this "consistent" for users we explicitly
969 // check `ConstArgHasType` clauses so that const args that don't
970 // go through an anon const still have their types checked.
971 //
972 // See also: https://rustc-dev-guide.rust-lang.org/const-generics.html
973let args = principal.skip_binder().with_self_ty(self.tcx(), t).args;
974let obligations =
975self.nominal_obligations(principal_def_id, args).into_iter().filter(|o| {
976let kind = o.predicate.kind().skip_binder();
977match kind {
978 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(
979 ct,
980_,
981 )) if #[allow(non_exhaustive_omitted_patterns)] match ct.kind() {
ty::ConstKind::Param(..) => true,
_ => false,
}matches!(ct.kind(), ty::ConstKind::Param(..)) => {
982// ConstArgHasType clauses are not higher kinded. Assert as
983 // such so we can fix this up if that ever changes.
984if !o.predicate.kind().bound_vars().is_empty() {
::core::panicking::panic("assertion failed: o.predicate.kind().bound_vars().is_empty()")
};assert!(o.predicate.kind().bound_vars().is_empty());
985// In stable rust, variables from the trait object binder
986 // cannot be referenced by a ConstArgHasType clause. However,
987 // under `generic_const_parameter_types`, it can. Ignore those
988 // predicates for now, to not have HKT-ConstArgHasTypes.
989!kind.has_escaping_bound_vars()
990 }
991_ => false,
992 }
993 });
994self.out.extend(obligations);
995 }
996997if !t.has_escaping_bound_vars() {
998for projection in data.projection_bounds() {
999let pred_binder = projection
1000 .with_self_ty(tcx, t)
1001 .map_bound(|p| {
1002 p.term.as_const().map(|ct| {
1003let assoc_const_ty = tcx
1004 .type_of(p.projection_term.def_id)
1005 .instantiate(tcx, p.projection_term.args);
1006 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(
1007 ct,
1008 assoc_const_ty,
1009 ))
1010 })
1011 })
1012 .transpose();
1013if let Some(pred_binder) = pred_binder {
1014self.out.push(traits::Obligation::with_depth(
1015 tcx,
1016self.cause(ObligationCauseCode::WellFormed(None)),
1017self.recursion_depth,
1018self.param_env,
1019 pred_binder,
1020 ));
1021 }
1022 }
1023 }
1024 }
10251026// Inference variables are the complicated case, since we don't
1027 // know what type they are. We do two things:
1028 //
1029 // 1. Check if they have been resolved, and if so proceed with
1030 // THAT type.
1031 // 2. If not, we've at least simplified things (e.g., we went
1032 // from `Vec?0>: WF` to `?0: WF`), so we can
1033 // register a pending obligation and keep
1034 // moving. (Goal is that an "inductive hypothesis"
1035 // is satisfied to ensure termination.)
1036 // See also the comment on `fn obligations`, describing cycle
1037 // prevention, which happens before this can be reached.
1038ty::Infer(_) => {
1039let cause = self.cause(ObligationCauseCode::WellFormed(None));
1040self.out.push(traits::Obligation::with_depth(
1041tcx,
1042cause,
1043self.recursion_depth,
1044self.param_env,
1045 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(
1046t.into(),
1047 ))),
1048 ));
1049 }
1050 }
10511052t.super_visit_with(self)
1053 }
10541055fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1056let tcx = self.tcx();
10571058match c.kind() {
1059 ty::ConstKind::Unevaluated(uv) => {
1060if !c.has_escaping_bound_vars() {
1061// Skip type consts as mGCA doesn't support evaluatable clauses
1062if !tcx.is_type_const(uv.def) {
1063let predicate = ty::Binder::dummy(ty::PredicateKind::Clause(
1064 ty::ClauseKind::ConstEvaluatable(c),
1065 ));
1066let cause = self.cause(ObligationCauseCode::WellFormed(None));
1067self.out.push(traits::Obligation::with_depth(
1068tcx,
1069cause,
1070self.recursion_depth,
1071self.param_env,
1072predicate,
1073 ));
1074 }
10751076if #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(uv.def) {
DefKind::AssocConst { .. } => true,
_ => false,
}matches!(tcx.def_kind(uv.def), DefKind::AssocConst { .. })1077 && tcx.def_kind(tcx.parent(uv.def)) == (DefKind::Impl { of_trait: false })
1078 {
1079self.add_wf_preds_for_inherent_projection(uv.into());
1080return; // Subtree is handled by above function
1081} else {
1082let obligations = self.nominal_obligations(uv.def, uv.args);
1083self.out.extend(obligations);
1084 }
1085 }
1086 }
1087 ty::ConstKind::Infer(_) => {
1088let cause = self.cause(ObligationCauseCode::WellFormed(None));
10891090self.out.push(traits::Obligation::with_depth(
1091tcx,
1092cause,
1093self.recursion_depth,
1094self.param_env,
1095 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(
1096c.into(),
1097 ))),
1098 ));
1099 }
1100 ty::ConstKind::Expr(_) => {
1101// FIXME(generic_const_exprs): this doesn't verify that given `Expr(N + 1)` the
1102 // trait bound `typeof(N): Add<typeof(1)>` holds. This is currently unnecessary
1103 // as `ConstKind::Expr` is only produced via normalization of `ConstKind::Unevaluated`
1104 // which means that the `DefId` would have been typeck'd elsewhere. However in
1105 // the future we may allow directly lowering to `ConstKind::Expr` in which case
1106 // we would not be proving bounds we should.
11071108let predicate = ty::Binder::dummy(ty::PredicateKind::Clause(
1109 ty::ClauseKind::ConstEvaluatable(c),
1110 ));
1111let cause = self.cause(ObligationCauseCode::WellFormed(None));
1112self.out.push(traits::Obligation::with_depth(
1113tcx,
1114cause,
1115self.recursion_depth,
1116self.param_env,
1117predicate,
1118 ));
1119 }
11201121 ty::ConstKind::Error(_)
1122 | ty::ConstKind::Param(_)
1123 | ty::ConstKind::Bound(..)
1124 | ty::ConstKind::Placeholder(..) => {
1125// These variants are trivially WF, so nothing to do here.
1126}
1127 ty::ConstKind::Value(val) => {
1128// FIXME(mgca): no need to feature-gate once valtree lifetimes are not erased
1129if tcx.features().min_generic_const_args() {
1130match val.ty.kind() {
1131 ty::Adt(adt_def, args) => {
1132let adt_val = val.destructure_adt_const();
1133let variant_def = adt_def.variant(adt_val.variant);
1134let cause = self.cause(ObligationCauseCode::WellFormed(None));
1135self.out.extend(variant_def.fields.iter().zip(adt_val.fields).map(
1136 |(field_def, &field_val)| {
1137let field_ty =
1138tcx.type_of(field_def.did).instantiate(tcx, args);
1139let predicate = ty::PredicateKind::Clause(
1140 ty::ClauseKind::ConstArgHasType(field_val, field_ty),
1141 );
1142 traits::Obligation::with_depth(
1143tcx,
1144cause.clone(),
1145self.recursion_depth,
1146self.param_env,
1147predicate,
1148 )
1149 },
1150 ));
1151 }
1152 ty::Tuple(field_tys) => {
1153let field_vals = val.to_branch();
1154let cause = self.cause(ObligationCauseCode::WellFormed(None));
1155self.out.extend(field_tys.iter().zip(field_vals).map(
1156 |(field_ty, &field_val)| {
1157let predicate = ty::PredicateKind::Clause(
1158 ty::ClauseKind::ConstArgHasType(field_val, field_ty),
1159 );
1160 traits::Obligation::with_depth(
1161tcx,
1162cause.clone(),
1163self.recursion_depth,
1164self.param_env,
1165predicate,
1166 )
1167 },
1168 ));
1169 }
1170 ty::Array(elem_ty, _len) => {
1171let elem_vals = val.to_branch();
1172let cause = self.cause(ObligationCauseCode::WellFormed(None));
11731174self.out.extend(elem_vals.iter().map(|&elem_val| {
1175let predicate = ty::PredicateKind::Clause(
1176 ty::ClauseKind::ConstArgHasType(elem_val, *elem_ty),
1177 );
1178 traits::Obligation::with_depth(
1179tcx,
1180cause.clone(),
1181self.recursion_depth,
1182self.param_env,
1183predicate,
1184 )
1185 }));
1186 }
1187_ => {}
1188 }
1189 }
11901191// FIXME: Enforce that values are structurally-matchable.
1192}
1193 }
11941195c.super_visit_with(self)
1196 }
11971198fn visit_predicate(&mut self, _p: ty::Predicate<'tcx>) -> Self::Result {
1199::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");
1200 }
1201}
12021203/// Given an object type like `SomeTrait + Send`, computes the lifetime
1204/// bounds that must hold on the elided self type. These are derived
1205/// from the declarations of `SomeTrait`, `Send`, and friends -- if
1206/// they declare `trait SomeTrait : 'static`, for example, then
1207/// `'static` would appear in the list.
1208///
1209/// N.B., in some cases, particularly around higher-ranked bounds,
1210/// this function returns a kind of conservative approximation.
1211/// That is, all regions returned by this function are definitely
1212/// required, but there may be other region bounds that are not
1213/// returned, as well as requirements like `for<'a> T: 'a`.
1214///
1215/// Requires that trait definitions have been processed so that we can
1216/// elaborate predicates and walk supertraits.
1217pub fn object_region_bounds<'tcx>(
1218 tcx: TyCtxt<'tcx>,
1219 existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1220) -> Vec<ty::Region<'tcx>> {
1221let erased_self_ty = tcx.types.trait_object_dummy_self;
12221223let predicates =
1224existential_predicates.iter().map(|predicate| predicate.with_self_ty(tcx, erased_self_ty));
12251226 traits::elaborate(tcx, predicates)
1227 .filter_map(|pred| {
1228{
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:1228",
"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(1228u32),
::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);
1229match pred.kind().skip_binder() {
1230 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ref t, ref r)) => {
1231// Search for a bound of the form `erased_self_ty
1232 // : 'a`, but be wary of something like `for<'a>
1233 // erased_self_ty : 'a` (we interpret a
1234 // higher-ranked bound like that as 'static,
1235 // though at present the code in `fulfill.rs`
1236 // considers such bounds to be unsatisfiable, so
1237 // it's kind of a moot point since you could never
1238 // construct such an object, but this seems
1239 // correct even if that code changes).
1240if t == &erased_self_ty && !r.has_escaping_bound_vars() {
1241Some(*r)
1242 } else {
1243None1244 }
1245 }
1246 ty::ClauseKind::Trait(_)
1247 | ty::ClauseKind::HostEffect(..)
1248 | ty::ClauseKind::RegionOutlives(_)
1249 | ty::ClauseKind::Projection(_)
1250 | ty::ClauseKind::ConstArgHasType(_, _)
1251 | ty::ClauseKind::WellFormed(_)
1252 | ty::ClauseKind::UnstableFeature(_)
1253 | ty::ClauseKind::ConstEvaluatable(_) => None,
1254 }
1255 })
1256 .collect()
1257}