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::lang_items::LangItem;
10use rustc_infer::traits::{ObligationCauseCode, PredicateObligations};
11use rustc_middle::bug;
12use rustc_middle::ty::{
13self, GenericArgsRef, Term, TermKind, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable,
14TypeVisitableExt, TypeVisitor,
15};
16use rustc_session::errors::feature_err;
17use rustc_span::def_id::{DefId, LocalDefId};
18use rustc_span::{Span, sym};
19use tracing::{debug, instrument, trace};
2021use crate::infer::InferCtxt;
22use crate::traits;
2324/// Returns the set of obligations needed to make `term` well-formed.
25/// If `term` contains unresolved inference variables, this may include
26/// further WF obligations. However, if `term` IS an unresolved
27/// inference variable, returns `None`, because we are not able to
28/// make any progress at all. This is to prevent cycles where we
29/// say "?0 is WF if ?0 is WF".
30pub fn obligations<'tcx>(
31 infcx: &InferCtxt<'tcx>,
32 param_env: ty::ParamEnv<'tcx>,
33 body_id: LocalDefId,
34 recursion_depth: usize,
35 term: Term<'tcx>,
36 span: Span,
37) -> Option<PredicateObligations<'tcx>> {
38// Handle the "cycle" case (see comment above) by bailing out if necessary.
39let term = match term.kind() {
40TermKind::Ty(ty) => {
41match ty.kind() {
42 ty::Infer(ty::TyVar(_)) => {
43let resolved_ty = infcx.shallow_resolve(ty);
44if resolved_ty == ty {
45// No progress, bail out to prevent cycles.
46return None;
47 } else {
48resolved_ty49 }
50 }
51_ => ty,
52 }
53 .into()
54 }
55TermKind::Const(ct) => {
56match ct.kind() {
57 ty::ConstKind::Infer(_) => {
58let resolved = infcx.shallow_resolve_const(ct);
59if resolved == ct {
60// No progress, bail out to prevent cycles.
61return None;
62 } else {
63resolved64 }
65 }
66_ => ct,
67 }
68 .into()
69 }
70 };
7172let mut wf = WfPredicates {
73infcx,
74param_env,
75body_id,
76span,
77 out: PredicateObligations::new(),
78recursion_depth,
79 item: None,
80 };
81wf.add_wf_preds_for_term(term);
82{
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:82",
"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(82u32),
::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);
8384let result = wf.normalize(infcx);
85{
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:85",
"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(85u32),
::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);
86Some(result)
87}
8889/// Compute the predicates that are required for a type to be well-formed.
90///
91/// This is only intended to be used in the new solver, since it does not
92/// take into account recursion depth or proper error-reporting spans.
93pub fn unnormalized_obligations<'tcx>(
94 infcx: &InferCtxt<'tcx>,
95 param_env: ty::ParamEnv<'tcx>,
96 term: Term<'tcx>,
97 span: Span,
98 body_id: LocalDefId,
99) -> Option<PredicateObligations<'tcx>> {
100if 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));
101102// However, if `term` IS an unresolved inference variable, returns `None`,
103 // because we are not able to make any progress at all. This is to prevent
104 // cycles where we say "?0 is WF if ?0 is WF".
105if term.is_infer() {
106return None;
107 }
108109let mut wf = WfPredicates {
110infcx,
111param_env,
112body_id,
113span,
114 out: PredicateObligations::new(),
115 recursion_depth: 0,
116 item: None,
117 };
118wf.add_wf_preds_for_term(term);
119Some(wf.out)
120}
121122/// Returns the obligations that make this trait reference
123/// well-formed. For example, if there is a trait `Set` defined like
124/// `trait Set<K: Eq>`, then the trait bound `Foo: Set<Bar>` is WF
125/// if `Bar: Eq`.
126pub fn trait_obligations<'tcx>(
127 infcx: &InferCtxt<'tcx>,
128 param_env: ty::ParamEnv<'tcx>,
129 body_id: LocalDefId,
130 trait_pred: ty::TraitPredicate<'tcx>,
131 span: Span,
132 item: &'tcx hir::Item<'tcx>,
133) -> PredicateObligations<'tcx> {
134let mut wf = WfPredicates {
135infcx,
136param_env,
137body_id,
138span,
139 out: PredicateObligations::new(),
140 recursion_depth: 0,
141 item: Some(item),
142 };
143wf.add_wf_preds_for_trait_pred(trait_pred, Elaborate::All);
144{
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:144",
"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(144u32),
::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);
145wf.normalize(infcx)
146}
147148/// Returns the requirements for `clause` to be well-formed.
149///
150/// For example, if there is a trait `Set` defined like
151/// `trait Set<K: Eq>`, then the trait bound `Foo: Set<Bar>` is WF
152/// if `Bar: Eq`.
153x;#[instrument(skip(infcx), ret)]154pub fn clause_obligations<'tcx>(
155 infcx: &InferCtxt<'tcx>,
156 param_env: ty::ParamEnv<'tcx>,
157 body_id: LocalDefId,
158 clause: ty::Clause<'tcx>,
159 span: Span,
160) -> PredicateObligations<'tcx> {
161let mut wf = WfPredicates {
162 infcx,
163 param_env,
164 body_id,
165 span,
166 out: PredicateObligations::new(),
167 recursion_depth: 0,
168 item: None,
169 };
170171// It's ok to skip the binder here because wf code is prepared for it
172match clause.kind().skip_binder() {
173 ty::ClauseKind::Trait(t) => {
174 wf.add_wf_preds_for_trait_pred(t, Elaborate::None);
175 }
176 ty::ClauseKind::HostEffect(..) => {
177// Technically the well-formedness of this predicate is implied by
178 // the corresponding trait predicate it should've been generated beside.
179}
180 ty::ClauseKind::RegionOutlives(..) => {}
181 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
182 wf.add_wf_preds_for_term(ty.into());
183 }
184 ty::ClauseKind::Projection(t) => {
185 wf.add_wf_preds_for_projection_term(t.projection_term);
186 wf.add_wf_preds_for_term(t.term);
187 }
188 ty::ClauseKind::ConstArgHasType(ct, ty) => {
189 wf.add_wf_preds_for_term(ct.into());
190 wf.add_wf_preds_for_term(ty.into());
191 }
192 ty::ClauseKind::WellFormed(term) => {
193 wf.add_wf_preds_for_term(term);
194 }
195196 ty::ClauseKind::ConstEvaluatable(ct) => {
197 wf.add_wf_preds_for_term(ct.into());
198 }
199 ty::ClauseKind::UnstableFeature(_) => {}
200 }
201202 wf.normalize(infcx)
203}
204205struct WfPredicates<'a, 'tcx> {
206 infcx: &'a InferCtxt<'tcx>,
207 param_env: ty::ParamEnv<'tcx>,
208 body_id: LocalDefId,
209 span: Span,
210 out: PredicateObligations<'tcx>,
211 recursion_depth: usize,
212 item: Option<&'tcx hir::Item<'tcx>>,
213}
214215/// Controls whether we "elaborate" supertraits and so forth on the WF
216/// predicates. This is a kind of hack to address #43784. The
217/// underlying problem in that issue was a trait structure like:
218///
219/// ```ignore (illustrative)
220/// trait Foo: Copy { }
221/// trait Bar: Foo { }
222/// impl<T: Bar> Foo for T { }
223/// impl<T> Bar for T { }
224/// ```
225///
226/// Here, in the `Foo` impl, we will check that `T: Copy` holds -- but
227/// we decide that this is true because `T: Bar` is in the
228/// where-clauses (and we can elaborate that to include `T:
229/// Copy`). This wouldn't be a problem, except that when we check the
230/// `Bar` impl, we decide that `T: Foo` must hold because of the `Foo`
231/// impl. And so nowhere did we check that `T: Copy` holds!
232///
233/// To resolve this, we elaborate the WF requirements that must be
234/// proven when checking impls. This means that (e.g.) the `impl Bar
235/// for T` will be forced to prove not only that `T: Foo` but also `T:
236/// Copy` (which it won't be able to do, because there is no `Copy`
237/// impl for `T`).
238#[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)]
239enum Elaborate {
240 All,
241None,
242}
243244/// Points the cause span of a super predicate at the relevant associated type.
245///
246/// Given a trait impl item:
247///
248/// ```ignore (incomplete)
249/// impl TargetTrait for TargetType {
250/// type Assoc = SomeType;
251/// }
252/// ```
253///
254/// And a super predicate of `TargetTrait` that has any of the following forms:
255///
256/// 1. `<OtherType as OtherTrait>::Assoc == <TargetType as TargetTrait>::Assoc`
257/// 2. `<<TargetType as TargetTrait>::Assoc as OtherTrait>::Assoc == OtherType`
258/// 3. `<TargetType as TargetTrait>::Assoc: OtherTrait`
259///
260/// Replace the span of the cause with the span of the associated item:
261///
262/// ```ignore (incomplete)
263/// impl TargetTrait for TargetType {
264/// type Assoc = SomeType;
265/// // ^^^^^^^^ this span
266/// }
267/// ```
268///
269/// Note that bounds that can be expressed as associated item bounds are **not**
270/// super predicates. This means that form 2 and 3 from above are only relevant if
271/// the [`GenericArgsRef`] of the projection type are not its identity arguments.
272fn extend_cause_with_original_assoc_item_obligation<'tcx>(
273 tcx: TyCtxt<'tcx>,
274 item: Option<&hir::Item<'tcx>>,
275 cause: &mut traits::ObligationCause<'tcx>,
276 pred: ty::Predicate<'tcx>,
277) {
278{
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:278",
"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(278u32),
::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");
279let (items, impl_def_id) = match item {
280Some(hir::Item { kind: hir::ItemKind::Impl(impl_), owner_id, .. }) => {
281 (impl_.items, *owner_id)
282 }
283_ => return,
284 };
285286let ty_to_impl_span = |ty: Ty<'_>| {
287if let ty::Alias(ty::AliasTy { kind: ty::Projection { def_id }, .. }) = ty.kind()
288 && let Some(&impl_item_id) = tcx.impl_item_implementor_ids(impl_def_id).get(def_id)
289 && let Some(impl_item) =
290items.iter().find(|item| item.owner_id.to_def_id() == impl_item_id)
291 {
292Some(tcx.hir_impl_item(*impl_item).expect_type().span)
293 } else {
294None295 }
296 };
297298// It is fine to skip the binder as we don't care about regions here.
299match pred.kind().skip_binder() {
300 ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)) => {
301// Form 1: The obligation comes not from the current `impl` nor the `trait` being
302 // implemented, but rather from a "second order" obligation, where an associated
303 // type has a projection coming from another associated type.
304 // See `tests/ui/traits/assoc-type-in-superbad.rs` for an example.
305if let Some(term_ty) = proj.term.as_type()
306 && let Some(impl_item_span) = ty_to_impl_span(term_ty)
307 {
308cause.span = impl_item_span;
309 }
310311// Form 2: A projection obligation for an associated item failed to be met.
312 // We overwrite the span from above to ensure that a bound like
313 // `Self::Assoc1: Trait<OtherAssoc = Self::Assoc2>` gets the same
314 // span for both obligations that it is lowered to.
315if let Some(impl_item_span) = ty_to_impl_span(proj.self_ty()) {
316cause.span = impl_item_span;
317 }
318 }
319320 ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
321// Form 3: A trait obligation for an associated item failed to be met.
322{
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:322",
"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(322u32),
::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);
323if let Some(impl_item_span) = ty_to_impl_span(pred.self_ty()) {
324cause.span = impl_item_span;
325 }
326 }
327_ => {}
328 }
329}
330331impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
332fn tcx(&self) -> TyCtxt<'tcx> {
333self.infcx.tcx
334 }
335336fn cause(&self, code: traits::ObligationCauseCode<'tcx>) -> traits::ObligationCause<'tcx> {
337 traits::ObligationCause::new(self.span, self.body_id, code)
338 }
339340fn normalize(self, infcx: &InferCtxt<'tcx>) -> PredicateObligations<'tcx> {
341// Do not normalize `wf` obligations with the new solver.
342 //
343 // The current deep normalization routine with the new solver does not
344 // handle ambiguity and the new solver correctly deals with unnnormalized goals.
345 // If the user relies on normalized types, e.g. for `fn implied_outlives_bounds`,
346 // it is their responsibility to normalize while avoiding ambiguity.
347if infcx.next_trait_solver() {
348return self.out;
349 }
350351let cause = self.cause(ObligationCauseCode::WellFormed(None));
352let param_env = self.param_env;
353let mut obligations = PredicateObligations::with_capacity(self.out.len());
354for mut obligation in self.out {
355if !!obligation.has_escaping_bound_vars() {
::core::panicking::panic("assertion failed: !obligation.has_escaping_bound_vars()")
};assert!(!obligation.has_escaping_bound_vars());
356let mut selcx = traits::SelectionContext::new(infcx);
357// Don't normalize the whole obligation, the param env is either
358 // already normalized, or we're currently normalizing the
359 // param_env. Either way we should only normalize the predicate.
360let normalized_predicate = traits::normalize::normalize_with_depth_to(
361&mut selcx,
362 param_env,
363 cause.clone(),
364self.recursion_depth,
365 obligation.predicate,
366&mut obligations,
367 );
368 obligation.predicate = normalized_predicate;
369 obligations.push(obligation);
370 }
371obligations372 }
373374/// Pushes the obligations required for `trait_ref` to be WF into `self.out`.
375fn add_wf_preds_for_trait_pred(
376&mut self,
377 trait_pred: ty::TraitPredicate<'tcx>,
378 elaborate: Elaborate,
379 ) {
380let tcx = self.tcx();
381let trait_ref = trait_pred.trait_ref;
382383// Negative trait predicates don't require supertraits to hold, just
384 // that their args are WF.
385if trait_pred.polarity == ty::PredicatePolarity::Negative {
386self.add_wf_preds_for_negative_trait_pred(trait_ref);
387return;
388 }
389390// if the trait predicate is not const, the wf obligations should not be const as well.
391let obligations = self.nominal_obligations(trait_ref.def_id, trait_ref.args);
392393{
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:393",
"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(393u32),
::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);
394let param_env = self.param_env;
395let depth = self.recursion_depth;
396397let item = self.item;
398399let extend = |traits::PredicateObligation { predicate, mut cause, .. }| {
400if let Some(parent_trait_pred) = predicate.as_trait_clause() {
401cause = cause.derived_cause(
402parent_trait_pred,
403 traits::ObligationCauseCode::WellFormedDerived,
404 );
405 }
406extend_cause_with_original_assoc_item_obligation(tcx, item, &mut cause, predicate);
407 traits::Obligation::with_depth(tcx, cause, depth, param_env, predicate)
408 };
409410if let Elaborate::All = elaborate {
411let implied_obligations = traits::util::elaborate(tcx, obligations);
412let implied_obligations = implied_obligations.map(extend);
413self.out.extend(implied_obligations);
414 } else {
415self.out.extend(obligations);
416 }
417418self.out.extend(
419trait_ref420 .args
421 .iter()
422 .enumerate()
423 .filter_map(|(i, arg)| arg.as_term().map(|t| (i, t)))
424 .filter(|(_, term)| !term.has_escaping_bound_vars())
425 .map(|(i, term)| {
426let mut cause = traits::ObligationCause::misc(self.span, self.body_id);
427// The first arg is the self ty - use the correct span for it.
428if i == 0 {
429if let Some(hir::ItemKind::Impl(hir::Impl { self_ty, .. })) =
430item.map(|i| &i.kind)
431 {
432cause.span = self_ty.span;
433 }
434 }
435 traits::Obligation::with_depth(
436tcx,
437cause,
438depth,
439param_env,
440 ty::ClauseKind::WellFormed(term),
441 )
442 }),
443 );
444 }
445446// Compute the obligations that are required for `trait_ref` to be WF,
447 // given that it is a *negative* trait predicate.
448fn add_wf_preds_for_negative_trait_pred(&mut self, trait_ref: ty::TraitRef<'tcx>) {
449for arg in trait_ref.args {
450if let Some(term) = arg.as_term() {
451self.add_wf_preds_for_term(term);
452 }
453 }
454 }
455456/// Pushes the obligations required for a projection to be WF into `self.out`.
457fn add_wf_preds_for_projection_term(&mut self, data: ty::AliasTerm<'tcx>) {
458// A projection is well-formed if
459 //
460 // (a) its predicates hold (*)
461 // (b) its args are wf
462 //
463 // (*) The predicates of an associated type include the predicates of
464 // the trait that it's contained in. For example, given
465 //
466 // trait A<T>: Clone {
467 // type X where T: Copy;
468 // }
469 //
470 // The predicates of `<() as A<i32>>::X` are:
471 // [
472 // `(): Sized`
473 // `(): Clone`
474 // `(): A<i32>`
475 // `i32: Sized`
476 // `i32: Clone`
477 // `i32: Copy`
478 // ]
479let obligations = self.nominal_obligations(data.expect_projection_def_id(), data.args);
480self.out.extend(obligations);
481482self.add_wf_preds_for_projection_args(data.args);
483 }
484485/// Pushes the obligations required for an inherent alias to be WF
486 /// into `self.out`.
487// FIXME(inherent_associated_types): Merge this function with `fn compute_alias`.
488fn add_wf_preds_for_inherent_projection(&mut self, data: ty::AliasTerm<'tcx>) {
489// An inherent projection is well-formed if
490 //
491 // (a) its predicates hold (*)
492 // (b) its args are wf
493 //
494 // (*) The predicates of an inherent associated type include the
495 // predicates of the impl that it's contained in.
496497if !data.self_ty().has_escaping_bound_vars() {
498// FIXME(inherent_associated_types): Should this happen inside of a snapshot?
499 // FIXME(inherent_associated_types): This is incompatible with the new solver and lazy norm!
500let args = traits::project::compute_inherent_assoc_term_args(
501&mut traits::SelectionContext::new(self.infcx),
502self.param_env,
503data,
504self.cause(ObligationCauseCode::WellFormed(None)),
505self.recursion_depth,
506&mut self.out,
507 );
508let def_id = data.expect_inherent_def_id();
509let obligations = self.nominal_obligations(def_id, args);
510self.out.extend(obligations);
511 }
512513data.args.visit_with(self);
514 }
515516fn add_wf_preds_for_projection_args(&mut self, args: GenericArgsRef<'tcx>) {
517let tcx = self.tcx();
518let cause = self.cause(ObligationCauseCode::WellFormed(None));
519let param_env = self.param_env;
520let depth = self.recursion_depth;
521522self.out.extend(
523args.iter()
524 .filter_map(|arg| arg.as_term())
525 .filter(|term| !term.has_escaping_bound_vars())
526 .map(|term| {
527 traits::Obligation::with_depth(
528tcx,
529cause.clone(),
530depth,
531param_env,
532 ty::ClauseKind::WellFormed(term),
533 )
534 }),
535 );
536 }
537538fn require_sized(&mut self, subty: Ty<'tcx>, cause: traits::ObligationCauseCode<'tcx>) {
539if !subty.has_escaping_bound_vars() {
540let cause = self.cause(cause);
541let trait_ref = ty::TraitRef::new(
542self.tcx(),
543self.tcx().require_lang_item(LangItem::Sized, cause.span),
544 [subty],
545 );
546self.out.push(traits::Obligation::with_depth(
547self.tcx(),
548cause,
549self.recursion_depth,
550self.param_env,
551 ty::Binder::dummy(trait_ref),
552 ));
553 }
554 }
555556/// Pushes all the predicates needed to validate that `term` is WF into `out`.
557#[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(557u32),
::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:560",
"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(560u32),
::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))]558fn add_wf_preds_for_term(&mut self, term: Term<'tcx>) {
559 term.visit_with(self);
560debug!(?self.out);
561 }
562563#[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(563u32),
::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();
}
if self.tcx().is_lang_item(def_id, LangItem::ConstParamTy) &&
self.tcx().features().const_param_ty_unchecked() {
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:591",
"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(591u32),
::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.skip_norm_wip())
}).filter(|pred| !pred.has_escaping_bound_vars()).collect()
}
}
}#[instrument(level = "debug", skip(self))]564fn nominal_obligations(
565&mut self,
566 def_id: DefId,
567 args: GenericArgsRef<'tcx>,
568 ) -> PredicateObligations<'tcx> {
569// PERF: `Sized`'s predicates include `MetaSized`, but both are compiler implemented marker
570 // traits, so `MetaSized` will always be WF if `Sized` is WF and vice-versa. Determining
571 // the nominal obligations of `Sized` would in-effect just elaborate `MetaSized` and make
572 // the compiler do a bunch of work needlessly.
573if self.tcx().is_lang_item(def_id, LangItem::Sized) {
574return Default::default();
575 }
576if self.tcx().is_lang_item(def_id, LangItem::ConstParamTy)
577 && self.tcx().features().const_param_ty_unchecked()
578 {
579return Default::default();
580 }
581582let predicates = self.tcx().predicates_of(def_id);
583let mut origins = vec![def_id; predicates.predicates.len()];
584let mut head = predicates;
585while let Some(parent) = head.parent {
586 head = self.tcx().predicates_of(parent);
587 origins.extend(iter::repeat(parent).take(head.predicates.len()));
588 }
589590let predicates = predicates.instantiate(self.tcx(), args);
591trace!("{:#?}", predicates);
592debug_assert_eq!(predicates.predicates.len(), origins.len());
593594 iter::zip(predicates, origins.into_iter().rev())
595 .map(|((pred, span), origin_def_id)| {
596let code = ObligationCauseCode::WhereClause(origin_def_id, span);
597let cause = self.cause(code);
598 traits::Obligation::with_depth(
599self.tcx(),
600 cause,
601self.recursion_depth,
602self.param_env,
603 pred.skip_norm_wip(),
604 )
605 })
606 .filter(|pred| !pred.has_escaping_bound_vars())
607 .collect()
608 }
609610fn add_wf_preds_for_dyn_ty(
611&mut self,
612 ty: Ty<'tcx>,
613 data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
614 region: ty::Region<'tcx>,
615 ) {
616// Imagine a type like this:
617 //
618 // trait Foo { }
619 // trait Bar<'c> : 'c { }
620 //
621 // &'b (Foo+'c+Bar<'d>)
622 // ^
623 //
624 // In this case, the following relationships must hold:
625 //
626 // 'b <= 'c
627 // 'd <= 'c
628 //
629 // The first conditions is due to the normal region pointer
630 // rules, which say that a reference cannot outlive its
631 // referent.
632 //
633 // The final condition may be a bit surprising. In particular,
634 // you may expect that it would have been `'c <= 'd`, since
635 // usually lifetimes of outer things are conservative
636 // approximations for inner things. However, it works somewhat
637 // differently with trait objects: here the idea is that if the
638 // user specifies a region bound (`'c`, in this case) it is the
639 // "master bound" that *implies* that bounds from other traits are
640 // all met. (Remember that *all bounds* in a type like
641 // `Foo+Bar+Zed` must be met, not just one, hence if we write
642 // `Foo<'x>+Bar<'y>`, we know that the type outlives *both* 'x and
643 // 'y.)
644 //
645 // Note: in fact we only permit builtin traits, not `Bar<'d>`, I
646 // am looking forward to the future here.
647if !data.has_escaping_bound_vars() && !region.has_escaping_bound_vars() {
648let implicit_bounds = object_region_bounds(self.tcx(), data);
649650let explicit_bound = region;
651652self.out.reserve(implicit_bounds.len());
653for implicit_bound in implicit_bounds {
654let cause = self.cause(ObligationCauseCode::ObjectTypeBound(ty, explicit_bound));
655let outlives =
656 ty::Binder::dummy(ty::OutlivesPredicate(explicit_bound, implicit_bound));
657self.out.push(traits::Obligation::with_depth(
658self.tcx(),
659 cause,
660self.recursion_depth,
661self.param_env,
662 outlives,
663 ));
664 }
665666// We don't add any wf predicates corresponding to the trait ref's generic arguments
667 // which allows code like this to compile:
668 // ```rust
669 // trait Trait<T: Sized> {}
670 // fn foo(_: &dyn Trait<[u32]>) {}
671 // ```
672}
673 }
674675fn add_wf_preds_for_pat_ty(&mut self, base_ty: Ty<'tcx>, pat: ty::Pattern<'tcx>) {
676let tcx = self.tcx();
677match *pat {
678 ty::PatternKind::Range { start, end } => {
679let mut check = |c| {
680let cause = self.cause(ObligationCauseCode::Misc);
681self.out.push(traits::Obligation::with_depth(
682tcx,
683cause.clone(),
684self.recursion_depth,
685self.param_env,
686 ty::Binder::dummy(ty::PredicateKind::Clause(
687 ty::ClauseKind::ConstArgHasType(c, base_ty),
688 )),
689 ));
690if !tcx.features().generic_pattern_types() {
691if c.has_param() {
692if self.span.is_dummy() {
693self.tcx()
694 .dcx()
695 .delayed_bug("feature error should be reported elsewhere, too");
696 } else {
697feature_err(
698&self.tcx().sess,
699 sym::generic_pattern_types,
700self.span,
701"wraparound pattern type ranges cause monomorphization time errors",
702 )
703 .emit();
704 }
705 }
706 }
707 };
708check(start);
709check(end);
710 }
711 ty::PatternKind::NotNull => {}
712 ty::PatternKind::Or(patterns) => {
713for pat in patterns {
714self.add_wf_preds_for_pat_ty(base_ty, pat)
715 }
716 }
717 }
718 }
719}
720721impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for WfPredicates<'a, 'tcx> {
722fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
723{
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:723",
"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(723u32),
::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());
724725let tcx = self.tcx();
726727match *t.kind() {
728 ty::Bool729 | ty::Char730 | ty::Int(..)
731 | ty::Uint(..)
732 | ty::Float(..)
733 | ty::Error(_)
734 | ty::Str735 | ty::CoroutineWitness(..)
736 | ty::Never737 | ty::Param(_)
738 | ty::Bound(..)
739 | ty::Placeholder(..)
740 | ty::Foreign(..) => {
741// WfScalar, WfParameter, etc
742}
743744// Can only infer to `ty::Int(_) | ty::Uint(_)`.
745ty::Infer(ty::IntVar(_)) => {}
746747// Can only infer to `ty::Float(_)`.
748ty::Infer(ty::FloatVar(_)) => {}
749750 ty::Slice(subty) => {
751self.require_sized(subty, ObligationCauseCode::SliceOrArrayElem);
752 }
753754 ty::Array(subty, len) => {
755self.require_sized(subty, ObligationCauseCode::SliceOrArrayElem);
756// Note that the len being WF is implicitly checked while visiting.
757 // Here we just check that it's of type usize.
758let cause = self.cause(ObligationCauseCode::ArrayLen(t));
759self.out.push(traits::Obligation::with_depth(
760tcx,
761cause,
762self.recursion_depth,
763self.param_env,
764 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(
765len,
766tcx.types.usize,
767 ))),
768 ));
769 }
770771 ty::Pat(base_ty, pat) => {
772self.require_sized(base_ty, ObligationCauseCode::Misc);
773self.add_wf_preds_for_pat_ty(base_ty, pat);
774 }
775776 ty::Tuple(tys) => {
777if let Some((last, rest)) = tys.split_last() {
778for &elem in rest {
779self.require_sized(elem, ObligationCauseCode::TupleElem);
780if elem.is_scalable_vector() && !self.span.is_dummy() {
781self.tcx()
782 .dcx()
783 .struct_span_err(
784self.span,
785"scalable vectors cannot be tuple fields",
786 )
787 .emit();
788 }
789 }
790791if last.is_scalable_vector() && !self.span.is_dummy() {
792self.tcx()
793 .dcx()
794 .struct_span_err(self.span, "scalable vectors cannot be tuple fields")
795 .emit();
796 }
797 }
798 }
799800 ty::RawPtr(_, _) => {
801// Simple cases that are WF if their type args are WF.
802}
803804 ty::Alias(ty::AliasTy {
805 kind: ty::Projection { def_id } | ty::Opaque { def_id } | ty::Free { def_id },
806 args,
807 ..
808 }) => {
809let obligations = self.nominal_obligations(def_id, args);
810self.out.extend(obligations);
811 }
812 ty::Alias(data @ ty::AliasTy { kind: ty::Inherent { .. }, .. }) => {
813self.add_wf_preds_for_inherent_projection(data.into());
814return; // Subtree handled by compute_inherent_projection.
815}
816817 ty::Adt(def, args) => {
818// WfNominalType
819let obligations = self.nominal_obligations(def.did(), args);
820self.out.extend(obligations);
821 }
822823 ty::FnDef(did, args) => {
824// HACK: Check the return type of function definitions for
825 // well-formedness to mostly fix #84533. This is still not
826 // perfect and there may be ways to abuse the fact that we
827 // ignore requirements with escaping bound vars. That's a
828 // more general issue however.
829let fn_sig = tcx.fn_sig(did).instantiate(tcx, args).skip_norm_wip();
830fn_sig.output().skip_binder().visit_with(self);
831832let obligations = self.nominal_obligations(did, args);
833self.out.extend(obligations);
834 }
835836 ty::Ref(r, rty, _) => {
837// WfReference
838if !r.has_escaping_bound_vars() && !rty.has_escaping_bound_vars() {
839let cause = self.cause(ObligationCauseCode::ReferenceOutlivesReferent(t));
840self.out.push(traits::Obligation::with_depth(
841tcx,
842cause,
843self.recursion_depth,
844self.param_env,
845 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(
846 ty::OutlivesPredicate(rty, r),
847 ))),
848 ));
849 }
850 }
851852 ty::Coroutine(did, args, ..) => {
853// Walk ALL the types in the coroutine: this will
854 // include the upvar types as well as the yield
855 // type. Note that this is mildly distinct from
856 // the closure case, where we have to be careful
857 // about the signature of the closure. We don't
858 // have the problem of implied bounds here since
859 // coroutines don't take arguments.
860let obligations = self.nominal_obligations(did, args);
861self.out.extend(obligations);
862 }
863864 ty::Closure(did, args) => {
865// Note that we cannot skip the generic types
866 // types. Normally, within the fn
867 // body where they are created, the generics will
868 // always be WF, and outside of that fn body we
869 // are not directly inspecting closure types
870 // anyway, except via auto trait matching (which
871 // only inspects the upvar types).
872 // But when a closure is part of a type-alias-impl-trait
873 // then the function that created the defining site may
874 // have had more bounds available than the type alias
875 // specifies. This may cause us to have a closure in the
876 // hidden type that is not actually well formed and
877 // can cause compiler crashes when the user abuses unsafe
878 // code to procure such a closure.
879 // See tests/ui/type-alias-impl-trait/wf_check_closures.rs
880let obligations = self.nominal_obligations(did, args);
881self.out.extend(obligations);
882// Only check the upvar types for WF, not the rest
883 // of the types within. This is needed because we
884 // capture the signature and it may not be WF
885 // without the implied bounds. Consider a closure
886 // like `|x: &'a T|` -- it may be that `T: 'a` is
887 // not known to hold in the creator's context (and
888 // indeed the closure may not be invoked by its
889 // creator, but rather turned to someone who *can*
890 // verify that).
891 //
892 // The special treatment of closures here really
893 // ought not to be necessary either; the problem
894 // is related to #25860 -- there is no way for us
895 // to express a fn type complete with the implied
896 // bounds that it is assuming. I think in reality
897 // the WF rules around fn are a bit messed up, and
898 // that is the rot problem: `fn(&'a T)` should
899 // probably always be WF, because it should be
900 // shorthand for something like `where(T: 'a) {
901 // fn(&'a T) }`, as discussed in #25860.
902let upvars = args.as_closure().tupled_upvars_ty();
903return upvars.visit_with(self);
904 }
905906 ty::CoroutineClosure(did, args) => {
907// See the above comments. The same apply to coroutine-closures.
908let obligations = self.nominal_obligations(did, args);
909self.out.extend(obligations);
910let upvars = args.as_coroutine_closure().tupled_upvars_ty();
911return upvars.visit_with(self);
912 }
913914 ty::FnPtr(..) => {
915// Let the visitor iterate into the argument/return
916 // types appearing in the fn signature.
917}
918 ty::UnsafeBinder(ty) => {
919// FIXME(unsafe_binders): For now, we have no way to express
920 // that a type must be `ManuallyDrop` OR `Copy` (or a pointer).
921if !ty.has_escaping_bound_vars() {
922self.out.push(traits::Obligation::new(
923self.tcx(),
924self.cause(ObligationCauseCode::Misc),
925self.param_env,
926ty.map_bound(|ty| {
927 ty::TraitRef::new(
928self.tcx(),
929self.tcx().require_lang_item(
930 LangItem::BikeshedGuaranteedNoDrop,
931self.span,
932 ),
933 [ty],
934 )
935 }),
936 ));
937 }
938939// We recurse into the binder below.
940}
941942 ty::Dynamic(data, r) => {
943// WfObject
944 //
945 // Here, we defer WF checking due to higher-ranked
946 // regions. This is perhaps not ideal.
947self.add_wf_preds_for_dyn_ty(t, data, r);
948949// FIXME(#27579) RFC also considers adding trait
950 // obligations that don't refer to Self and
951 // checking those
952if let Some(principal) = data.principal() {
953let principal_def_id = principal.skip_binder().def_id;
954self.out.push(traits::Obligation::with_depth(
955tcx,
956self.cause(ObligationCauseCode::WellFormed(None)),
957self.recursion_depth,
958self.param_env,
959 ty::Binder::dummy(ty::PredicateKind::DynCompatible(principal_def_id)),
960 ));
961962// For the most part we don't add wf predicates corresponding to
963 // the trait ref's generic arguments which allows code like this
964 // to compile:
965 // ```rust
966 // trait Trait<T: Sized> {}
967 // fn foo(_: &dyn Trait<[u32]>) {}
968 // ```
969 //
970 // However, we sometimes incidentally check that const arguments
971 // have the correct type as a side effect of the anon const
972 // desugaring. To make this "consistent" for users we explicitly
973 // check `ConstArgHasType` clauses so that const args that don't
974 // go through an anon const still have their types checked.
975 //
976 // See also: https://rustc-dev-guide.rust-lang.org/const-generics.html
977let args = principal.skip_binder().with_self_ty(self.tcx(), t).args;
978let obligations =
979self.nominal_obligations(principal_def_id, args).into_iter().filter(|o| {
980let kind = o.predicate.kind().skip_binder();
981match kind {
982 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(
983 ct,
984_,
985 )) if #[allow(non_exhaustive_omitted_patterns)] match ct.kind() {
ty::ConstKind::Param(..) => true,
_ => false,
}matches!(ct.kind(), ty::ConstKind::Param(..)) => {
986// ConstArgHasType clauses are not higher kinded. Assert as
987 // such so we can fix this up if that ever changes.
988if !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());
989// In stable rust, variables from the trait object binder
990 // cannot be referenced by a ConstArgHasType clause. However,
991 // under `generic_const_parameter_types`, it can. Ignore those
992 // predicates for now, to not have HKT-ConstArgHasTypes.
993!kind.has_escaping_bound_vars()
994 }
995_ => false,
996 }
997 });
998self.out.extend(obligations);
999 }
10001001if !t.has_escaping_bound_vars() {
1002for projection in data.projection_bounds() {
1003let pred_binder = projection
1004 .with_self_ty(tcx, t)
1005 .map_bound(|p| {
1006 p.term.as_const().map(|ct| {
1007let assoc_const_ty = tcx
1008 .type_of(p.def_id())
1009 .instantiate(tcx, p.projection_term.args)
1010 .skip_norm_wip();
1011 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(
1012 ct,
1013 assoc_const_ty,
1014 ))
1015 })
1016 })
1017 .transpose();
1018if let Some(pred_binder) = pred_binder {
1019self.out.push(traits::Obligation::with_depth(
1020 tcx,
1021self.cause(ObligationCauseCode::WellFormed(None)),
1022self.recursion_depth,
1023self.param_env,
1024 pred_binder,
1025 ));
1026 }
1027 }
1028 }
1029 }
10301031// Inference variables are the complicated case, since we don't
1032 // know what type they are. We do two things:
1033 //
1034 // 1. Check if they have been resolved, and if so proceed with
1035 // THAT type.
1036 // 2. If not, we've at least simplified things (e.g., we went
1037 // from `Vec?0>: WF` to `?0: WF`), so we can
1038 // register a pending obligation and keep
1039 // moving. (Goal is that an "inductive hypothesis"
1040 // is satisfied to ensure termination.)
1041 // See also the comment on `fn obligations`, describing cycle
1042 // prevention, which happens before this can be reached.
1043ty::Infer(_) => {
1044let cause = self.cause(ObligationCauseCode::WellFormed(None));
1045self.out.push(traits::Obligation::with_depth(
1046tcx,
1047cause,
1048self.recursion_depth,
1049self.param_env,
1050 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(
1051t.into(),
1052 ))),
1053 ));
1054 }
1055 }
10561057t.super_visit_with(self)
1058 }
10591060fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1061let tcx = self.tcx();
10621063match c.kind() {
1064 ty::ConstKind::Unevaluated(uv) => {
1065if !c.has_escaping_bound_vars() {
1066// Skip type consts as mGCA doesn't support evaluatable clauses
1067if !uv.kind.is_type_const(tcx) && !tcx.features().generic_const_args() {
1068let predicate = ty::Binder::dummy(ty::PredicateKind::Clause(
1069 ty::ClauseKind::ConstEvaluatable(c),
1070 ));
1071let cause = self.cause(ObligationCauseCode::WellFormed(None));
1072self.out.push(traits::Obligation::with_depth(
1073tcx,
1074cause,
1075self.recursion_depth,
1076self.param_env,
1077predicate,
1078 ));
1079 }
10801081match uv.kind {
1082 ty::UnevaluatedConstKind::Inherent { .. } => {
1083self.add_wf_preds_for_inherent_projection(uv.into());
1084return; // Subtree is handled by above function
1085}
1086 ty::UnevaluatedConstKind::Projection { def_id }
1087 | ty::UnevaluatedConstKind::Free { def_id }
1088 | ty::UnevaluatedConstKind::Anon { def_id } => {
1089let obligations = self.nominal_obligations(def_id, uv.args);
1090self.out.extend(obligations);
1091 }
1092 }
1093 }
1094 }
1095 ty::ConstKind::Infer(_) => {
1096let cause = self.cause(ObligationCauseCode::WellFormed(None));
10971098self.out.push(traits::Obligation::with_depth(
1099tcx,
1100cause,
1101self.recursion_depth,
1102self.param_env,
1103 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(
1104c.into(),
1105 ))),
1106 ));
1107 }
1108 ty::ConstKind::Expr(_) => {
1109// FIXME(generic_const_exprs): this doesn't verify that given `Expr(N + 1)` the
1110 // trait bound `typeof(N): Add<typeof(1)>` holds. This is currently unnecessary
1111 // as `ConstKind::Expr` is only produced via normalization of `ConstKind::Unevaluated`
1112 // which means that the `DefId` would have been typeck'd elsewhere. However in
1113 // the future we may allow directly lowering to `ConstKind::Expr` in which case
1114 // we would not be proving bounds we should.
11151116let predicate = ty::Binder::dummy(ty::PredicateKind::Clause(
1117 ty::ClauseKind::ConstEvaluatable(c),
1118 ));
1119let cause = self.cause(ObligationCauseCode::WellFormed(None));
1120self.out.push(traits::Obligation::with_depth(
1121tcx,
1122cause,
1123self.recursion_depth,
1124self.param_env,
1125predicate,
1126 ));
1127 }
11281129 ty::ConstKind::Error(_)
1130 | ty::ConstKind::Param(_)
1131 | ty::ConstKind::Bound(..)
1132 | ty::ConstKind::Placeholder(..) => {
1133// These variants are trivially WF, so nothing to do here.
1134}
1135 ty::ConstKind::Value(val) => {
1136// FIXME(mgca): no need to feature-gate once valtree lifetimes are not erased
1137if tcx.features().min_generic_const_args() {
1138match val.ty.kind() {
1139 ty::Adt(adt_def, args) => {
1140let adt_val = val.destructure_adt_const();
1141let variant_def = adt_def.variant(adt_val.variant);
1142let cause = self.cause(ObligationCauseCode::WellFormed(None));
1143self.out.extend(variant_def.fields.iter().zip(adt_val.fields).map(
1144 |(field_def, &field_val)| {
1145let field_ty = tcx1146 .type_of(field_def.did)
1147 .instantiate(tcx, args)
1148 .skip_norm_wip();
1149let predicate = ty::PredicateKind::Clause(
1150 ty::ClauseKind::ConstArgHasType(field_val, field_ty),
1151 );
1152 traits::Obligation::with_depth(
1153tcx,
1154cause.clone(),
1155self.recursion_depth,
1156self.param_env,
1157predicate,
1158 )
1159 },
1160 ));
1161 }
1162 ty::Tuple(field_tys) => {
1163let field_vals = val.to_branch();
1164let cause = self.cause(ObligationCauseCode::WellFormed(None));
1165self.out.extend(field_tys.iter().zip(field_vals).map(
1166 |(field_ty, &field_val)| {
1167let predicate = ty::PredicateKind::Clause(
1168 ty::ClauseKind::ConstArgHasType(field_val, field_ty),
1169 );
1170 traits::Obligation::with_depth(
1171tcx,
1172cause.clone(),
1173self.recursion_depth,
1174self.param_env,
1175predicate,
1176 )
1177 },
1178 ));
1179 }
1180 ty::Array(elem_ty, _len) => {
1181let elem_vals = val.to_branch();
1182let cause = self.cause(ObligationCauseCode::WellFormed(None));
11831184self.out.extend(elem_vals.iter().map(|&elem_val| {
1185let predicate = ty::PredicateKind::Clause(
1186 ty::ClauseKind::ConstArgHasType(elem_val, *elem_ty),
1187 );
1188 traits::Obligation::with_depth(
1189tcx,
1190cause.clone(),
1191self.recursion_depth,
1192self.param_env,
1193predicate,
1194 )
1195 }));
1196 }
1197_ => {}
1198 }
1199 }
12001201// FIXME: Enforce that values are structurally-matchable.
1202}
1203 }
12041205c.super_visit_with(self)
1206 }
12071208fn visit_predicate(&mut self, _p: ty::Predicate<'tcx>) -> Self::Result {
1209::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");
1210 }
1211}
12121213/// Given an object type like `SomeTrait + Send`, computes the lifetime
1214/// bounds that must hold on the elided self type. These are derived
1215/// from the declarations of `SomeTrait`, `Send`, and friends -- if
1216/// they declare `trait SomeTrait : 'static`, for example, then
1217/// `'static` would appear in the list.
1218///
1219/// N.B., in some cases, particularly around higher-ranked bounds,
1220/// this function returns a kind of conservative approximation.
1221/// That is, all regions returned by this function are definitely
1222/// required, but there may be other region bounds that are not
1223/// returned, as well as requirements like `for<'a> T: 'a`.
1224///
1225/// Requires that trait definitions have been processed so that we can
1226/// elaborate predicates and walk supertraits.
1227pub fn object_region_bounds<'tcx>(
1228 tcx: TyCtxt<'tcx>,
1229 existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1230) -> Vec<ty::Region<'tcx>> {
1231let erased_self_ty = tcx.types.trait_object_dummy_self;
12321233let predicates =
1234existential_predicates.iter().map(|predicate| predicate.with_self_ty(tcx, erased_self_ty));
12351236 traits::elaborate(tcx, predicates)
1237 .filter_map(|pred| {
1238{
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:1238",
"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(1238u32),
::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);
1239match pred.kind().skip_binder() {
1240 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ref t, ref r)) => {
1241// Search for a bound of the form `erased_self_ty
1242 // : 'a`, but be wary of something like `for<'a>
1243 // erased_self_ty : 'a` (we interpret a
1244 // higher-ranked bound like that as 'static,
1245 // though at present the code in `fulfill.rs`
1246 // considers such bounds to be unsatisfiable, so
1247 // it's kind of a moot point since you could never
1248 // construct such an object, but this seems
1249 // correct even if that code changes).
1250if t == &erased_self_ty && !r.has_escaping_bound_vars() {
1251Some(*r)
1252 } else {
1253None1254 }
1255 }
1256 ty::ClauseKind::Trait(_)
1257 | ty::ClauseKind::HostEffect(..)
1258 | ty::ClauseKind::RegionOutlives(_)
1259 | ty::ClauseKind::Projection(_)
1260 | ty::ClauseKind::ConstArgHasType(_, _)
1261 | ty::ClauseKind::WellFormed(_)
1262 | ty::ClauseKind::UnstableFeature(_)
1263 | ty::ClauseKind::ConstEvaluatable(_) => None,
1264 }
1265 })
1266 .collect()
1267}