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_attr_ir::lang_items::LangItem;
9use rustc_hiras hir;
10use rustc_infer::traits::{
11ObligationCauseCode, PredicateObligation, PredicateObligations, WellFormedLoc,
12};
13use rustc_middle::ty::{
14self, DelayedSet, GenericArgsRef, PredicateProxy, Term, TermKind, Ty, TyCtxt,
15TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor,
16};
17use rustc_session::diagnostics::feature_err;
18use rustc_span::def_id::{DefId, LocalDefId};
19use rustc_span::{Span, bug, sym};
20use tracing::{debug, instrument};
2122use crate::infer::InferCtxt;
23use crate::traits;
2425/// Returns the set of obligations needed to make `term` well-formed.
26/// If `term` contains unresolved inference variables, this may include
27/// further WF obligations. However, if `term` 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_def_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_def_id,
77span,
78 out: PredicateObligations::new(),
79recursion_depth,
80 item: None,
81 visited_tys: Default::default(),
82 };
83wf.add_wf_preds_for_term(term);
84{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/traits/wf.rs:84",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(84u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("wf::obligations({0:?}, body_def_id={1:?}) = {2:?}",
term, body_def_id, wf.out) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("wf::obligations({:?}, body_def_id={:?}) = {:?}", term, body_def_id, wf.out);
8586let result = wf.normalize(infcx);
87{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/traits/wf.rs:87",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(87u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("wf::obligations({0:?}, body_def_id={1:?}) ~~> {2:?}",
term, body_def_id, result) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("wf::obligations({:?}, body_def_id={:?}) ~~> {:?}", term, body_def_id, result);
88Some(result)
89}
9091/// Compute the predicates that are required for a type to be well-formed.
92///
93/// This is only intended to be used in the new solver, since it does not
94/// take into account recursion depth or proper error-reporting spans.
95pub fn unnormalized_obligations<'tcx>(
96 infcx: &InferCtxt<'tcx>,
97 param_env: ty::ParamEnv<'tcx>,
98 term: Term<'tcx>,
99 span: Span,
100 body_def_id: LocalDefId,
101) -> Option<PredicateObligations<'tcx>> {
102if true {
{
match (&term, &infcx.deeply_resolve_ignoring_regions(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.deeply_resolve_ignoring_regions(term));
103104// However, if `term` IS an unresolved inference variable, returns `None`,
105 // because we are not able to make any progress at all. This is to prevent
106 // cycles where we say "?0 is WF if ?0 is WF".
107if term.is_infer() {
108return None;
109 }
110111let mut wf = WfPredicates {
112infcx,
113param_env,
114body_def_id,
115span,
116 out: PredicateObligations::new(),
117 recursion_depth: 0,
118 item: None,
119 visited_tys: Default::default(),
120 };
121wf.add_wf_preds_for_term(term);
122Some(wf.out)
123}
124125/// Returns the obligations that make this trait reference
126/// well-formed. For example, if there is a trait `Set` defined like
127/// `trait Set<K: Eq>`, then the trait bound `Foo: Set<Bar>` is WF
128/// if `Bar: Eq`.
129pub fn trait_obligations<'tcx>(
130 infcx: &InferCtxt<'tcx>,
131 param_env: ty::ParamEnv<'tcx>,
132 body_def_id: LocalDefId,
133 trait_pred: ty::TraitClause<'tcx>,
134 span: Span,
135 item: &'tcx hir::Item<'tcx>,
136) -> PredicateObligations<'tcx> {
137let mut wf = WfPredicates {
138infcx,
139param_env,
140body_def_id,
141span,
142 out: PredicateObligations::new(),
143 recursion_depth: 0,
144 item: Some(item),
145 visited_tys: Default::default(),
146 };
147wf.add_wf_preds_for_trait_pred(trait_pred, Elaborate::All);
148{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/traits/wf.rs:148",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(148u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("obligations")
}> =
::tracing::__macro_support::FieldName::new("obligations");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&wf.out)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(obligations = ?wf.out);
149wf.normalize(infcx)
150}
151152/// Returns the requirements for `clause` to be well-formed.
153///
154/// For example, if there is a trait `Set` defined like
155/// `trait Set<K: Eq>`, then the trait bound `Foo: Set<Bar>` is WF
156/// if `Bar: Eq`.
157{}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::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("clause_obligations",
"rustc_trait_selection::traits::wf", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(157u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("param_env")
}> =
::tracing::__macro_support::FieldName::new("param_env");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("body_def_id")
}> =
::tracing::__macro_support::FieldName::new("body_def_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("clause")
}> =
::tracing::__macro_support::FieldName::new("clause");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("span")
}> =
::tracing::__macro_support::FieldName::new("span");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(¶m_env)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&body_def_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&clause)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[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;
}
{
let mut wf =
WfPredicates {
infcx,
param_env,
body_def_id,
span,
out: PredicateObligations::new(),
recursion_depth: 0,
item: None,
visited_tys: Default::default(),
};
match clause.kind().skip_binder() {
ty::ClauseKind::Trait(t) => {
wf.add_wf_preds_for_trait_pred(t, Elaborate::None);
}
ty::ClauseKind::HostEffect(..) => {}
ty::ClauseKind::RegionOutlives(..) => {}
ty::ClauseKind::TypeOutlives(ty::OutlivesClause(ty, _reg))
=> {
wf.add_wf_preds_for_term(ty.into());
}
ty::ClauseKind::Projection(t) => {
wf.add_wf_preds_for_projection_term(t.projection_term);
wf.add_wf_preds_for_term(t.term);
}
ty::ClauseKind::ConstArgHasType(ct, ty) => {
wf.add_wf_preds_for_term(ct.into());
wf.add_wf_preds_for_term(ty.into());
}
ty::ClauseKind::WellFormed(term) => {
wf.add_wf_preds_for_term(term);
}
ty::ClauseKind::ConstEvaluatable(ct) => {
wf.add_wf_preds_for_term(ct.into());
}
ty::ClauseKind::UnstableFeature(_) => {}
}
wf.normalize(infcx)
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/traits/wf.rs:157",
"rustc_trait_selection::traits::wf", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(157u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(skip(infcx), ret)]158pub fn clause_obligations<'tcx>(
159 infcx: &InferCtxt<'tcx>,
160 param_env: ty::ParamEnv<'tcx>,
161 body_def_id: LocalDefId,
162 clause: ty::Clause<'tcx>,
163 span: Span,
164) -> PredicateObligations<'tcx> {
165let mut wf = WfPredicates {
166 infcx,
167 param_env,
168 body_def_id,
169 span,
170 out: PredicateObligations::new(),
171 recursion_depth: 0,
172 item: None,
173 visited_tys: Default::default(),
174 };
175176// It's ok to skip the binder here because wf code is prepared for it
177match clause.kind().skip_binder() {
178 ty::ClauseKind::Trait(t) => {
179 wf.add_wf_preds_for_trait_pred(t, Elaborate::None);
180 }
181 ty::ClauseKind::HostEffect(..) => {
182// Technically the well-formedness of this clause is implied by
183 // the corresponding trait clause it should've been generated beside.
184}
185 ty::ClauseKind::RegionOutlives(..) => {}
186 ty::ClauseKind::TypeOutlives(ty::OutlivesClause(ty, _reg)) => {
187 wf.add_wf_preds_for_term(ty.into());
188 }
189 ty::ClauseKind::Projection(t) => {
190 wf.add_wf_preds_for_projection_term(t.projection_term);
191 wf.add_wf_preds_for_term(t.term);
192 }
193 ty::ClauseKind::ConstArgHasType(ct, ty) => {
194 wf.add_wf_preds_for_term(ct.into());
195 wf.add_wf_preds_for_term(ty.into());
196 }
197 ty::ClauseKind::WellFormed(term) => {
198 wf.add_wf_preds_for_term(term);
199 }
200201 ty::ClauseKind::ConstEvaluatable(ct) => {
202 wf.add_wf_preds_for_term(ct.into());
203 }
204 ty::ClauseKind::UnstableFeature(_) => {}
205 }
206207 wf.normalize(infcx)
208}
209210struct WfPredicates<'a, 'tcx> {
211 infcx: &'a InferCtxt<'tcx>,
212 param_env: ty::ParamEnv<'tcx>,
213 body_def_id: LocalDefId,
214 span: Span,
215 out: PredicateObligations<'tcx>,
216 recursion_depth: usize,
217 item: Option<&'tcx hir::Item<'tcx>>,
218 visited_tys: DelayedSet<Ty<'tcx>>,
219}
220221/// Controls whether we "elaborate" supertraits and so forth on the WF
222/// predicates. This is a kind of hack to address #43784. The
223/// underlying problem in that issue was a trait structure like:
224///
225/// ```ignore (illustrative)
226/// trait Foo: Copy { }
227/// trait Bar: Foo { }
228/// impl<T: Bar> Foo for T { }
229/// impl<T> Bar for T { }
230/// ```
231///
232/// Here, in the `Foo` impl, we will check that `T: Copy` holds -- but
233/// we decide that this is true because `T: Bar` is in the
234/// where-clauses (and we can elaborate that to include `T:
235/// Copy`). This wouldn't be a problem, except that when we check the
236/// `Bar` impl, we decide that `T: Foo` must hold because of the `Foo`
237/// impl. And so nowhere did we check that `T: Copy` holds!
238///
239/// To resolve this, we elaborate the WF requirements that must be
240/// proven when checking impls. This means that (e.g.) the `impl Bar
241/// for T` will be forced to prove not only that `T: Foo` but also `T:
242/// Copy` (which it won't be able to do, because there is no `Copy`
243/// impl for `T`).
244#[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::marker::StructuralPartialEq for Elaborate { }
#[automatically_derived]
impl ::core::cmp::PartialEq for Elaborate {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Elaborate { }Eq, #[automatically_derived]
impl ::core::marker::Copy for Elaborate { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for Elaborate { }
#[automatically_derived]
impl ::core::clone::Clone for Elaborate {
#[inline]
fn clone(&self) -> Self { *self }
}Clone)]
245enum Elaborate {
246 All,
247None,
248}
249250/// Points the cause span of a super predicate at the relevant associated type.
251///
252/// Given a trait impl item:
253///
254/// ```ignore (incomplete)
255/// impl TargetTrait for TargetType {
256/// type Assoc = SomeType;
257/// }
258/// ```
259///
260/// And a super predicate of `TargetTrait` that has any of the following forms:
261///
262/// 1. `<OtherType as OtherTrait>::Assoc == <TargetType as TargetTrait>::Assoc`
263/// 2. `<<TargetType as TargetTrait>::Assoc as OtherTrait>::Assoc == OtherType`
264/// 3. `<TargetType as TargetTrait>::Assoc: OtherTrait`
265///
266/// Replace the span of the cause with the span of the associated item:
267///
268/// ```ignore (incomplete)
269/// impl TargetTrait for TargetType {
270/// type Assoc = SomeType;
271/// // ^^^^^^^^ this span
272/// }
273/// ```
274///
275/// Note that bounds that can be expressed as associated item bounds are **not**
276/// super predicates. This means that form 2 and 3 from above are only relevant if
277/// the [`GenericArgsRef`] of the projection type are not its identity arguments.
278fn extend_cause_with_original_assoc_item_obligation<'tcx>(
279 tcx: TyCtxt<'tcx>,
280 item: Option<&hir::Item<'tcx>>,
281 cause: &mut traits::ObligationCause<'tcx>,
282 pred: ty::Predicate<'tcx>,
283) {
284{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/traits/wf.rs:284",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(284u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
::tracing_core::field::FieldSet::new(&["message",
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("item")
}> =
::tracing::__macro_support::FieldName::new("item");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("cause")
}> =
::tracing::__macro_support::FieldName::new("cause");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("pred")
}> =
::tracing::__macro_support::FieldName::new("pred");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("extended_cause_with_original_assoc_item_obligation")
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&pred)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?item, ?cause, ?pred, "extended_cause_with_original_assoc_item_obligation");
285let (items, impl_def_id) = match item {
286Some(hir::Item { kind: hir::ItemKind::Impl(impl_), owner_id, .. }) => {
287 (impl_.items, *owner_id)
288 }
289_ => return,
290 };
291292let ty_to_impl_span = |ty: Ty<'_>| {
293if let ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, .. }) = ty.kind()
294 && let Some(&impl_item_id) = tcx.impl_item_implementor_ids(impl_def_id).get(def_id)
295 && let Some(impl_item) =
296items.iter().find(|item| item.owner_id.to_def_id() == impl_item_id)
297 {
298Some(tcx.hir_impl_item(*impl_item).expect_type().span)
299 } else {
300None301 }
302 };
303304// It is fine to skip the binder as we don't care about regions here.
305match pred.kind().skip_binder() {
306 ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)) => {
307// Form 1: The obligation comes not from the current `impl` nor the `trait` being
308 // implemented, but rather from a "second order" obligation, where an associated
309 // type has a projection coming from another associated type.
310 // See `tests/ui/traits/assoc-type-in-superbad.rs` for an example.
311if let Some(term_ty) = proj.term.as_type()
312 && let Some(impl_item_span) = ty_to_impl_span(term_ty)
313 {
314cause.span = impl_item_span;
315 }
316317// Form 2: A projection obligation for an associated item failed to be met.
318 // We overwrite the span from above to ensure that a bound like
319 // `Self::Assoc1: Trait<OtherAssoc = Self::Assoc2>` gets the same
320 // span for both obligations that it is lowered to.
321if let Some(impl_item_span) = ty_to_impl_span(proj.self_ty()) {
322cause.span = impl_item_span;
323 }
324 }
325326 ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
327// Form 3: A trait obligation for an associated item failed to be met.
328{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/traits/wf.rs:328",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(328u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("extended_cause_with_original_assoc_item_obligation trait proj {0:?}",
pred) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("extended_cause_with_original_assoc_item_obligation trait proj {:?}", pred);
329if let Some(impl_item_span) = ty_to_impl_span(pred.self_ty()) {
330cause.span = impl_item_span;
331 }
332 }
333_ => {}
334 }
335}
336337impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
338fn tcx(&self) -> TyCtxt<'tcx> {
339self.infcx.tcx
340 }
341342fn cause(&self, code: traits::ObligationCauseCode<'tcx>) -> traits::ObligationCause<'tcx> {
343 traits::ObligationCause::new(self.span, self.body_def_id, code)
344 }
345346fn normalize(self, infcx: &InferCtxt<'tcx>) -> PredicateObligations<'tcx> {
347// Do not normalize `wf` obligations with the new solver.
348 //
349 // The current deep normalization routine with the new solver does not
350 // handle ambiguity and the new solver correctly deals with unnnormalized goals.
351 // If the user relies on normalized types, e.g. for `fn implied_outlives_bounds`,
352 // it is their responsibility to normalize while avoiding ambiguity.
353if infcx.next_trait_solver() {
354return self.out;
355 }
356357let cause = self.cause(ObligationCauseCode::WellFormed(WellFormedLoc::None));
358let param_env = self.param_env;
359let mut obligations = PredicateObligations::with_capacity(self.out.len());
360for mut obligation in self.out {
361if !!obligation.has_escaping_bound_vars() {
::core::panicking::panic("assertion failed: !obligation.has_escaping_bound_vars()")
};assert!(!obligation.has_escaping_bound_vars());
362let mut selcx = traits::SelectionContext::new(infcx);
363// Don't normalize the whole obligation, the param env is either
364 // already normalized, or we're currently normalizing the
365 // param_env. Either way we should only normalize the predicate.
366let normalized_predicate = traits::normalize::normalize_with_depth_to(
367&mut selcx,
368 param_env,
369 cause.clone(),
370self.recursion_depth,
371 ty::Unnormalized::new_wip(obligation.predicate),
372&mut obligations,
373 );
374 obligation.predicate = normalized_predicate;
375 obligations.push(obligation);
376 }
377obligations378 }
379380/// Pushes the obligations required for `trait_ref` to be WF into `self.out`.
381fn add_wf_preds_for_trait_pred(
382&mut self,
383 trait_pred: ty::TraitClause<'tcx>,
384 elaborate: Elaborate,
385 ) {
386let tcx = self.tcx();
387let trait_ref = trait_pred.trait_ref;
388389// Negative trait predicates don't require supertraits to hold, just
390 // that their args are WF.
391if trait_pred.polarity == ty::ClausePolarity::Negative {
392self.add_wf_preds_for_negative_trait_pred(trait_ref);
393return;
394 }
395396let param_env = self.param_env;
397let depth = self.recursion_depth;
398399let item = self.item;
400401let extend = |traits::PredicateObligation { predicate, mut cause, .. }| {
402if let Some(parent_trait_pred) = predicate.as_trait_clause() {
403cause = cause.derived_cause(
404parent_trait_pred,
405 traits::ObligationCauseCode::WellFormedDerived,
406 );
407 }
408extend_cause_with_original_assoc_item_obligation(tcx, item, &mut cause, predicate);
409 traits::Obligation::with_depth(tcx, cause, depth, param_env, predicate)
410 };
411412// if the trait predicate is not const, the wf obligations should not be const as well.
413if let Elaborate::All = elaborate {
414let mut obligations = PredicateObligations::new();
415self.nominal_obligations(trait_ref.def_id, trait_ref.args, |_, obligation| {
416obligations.push(obligation)
417 });
418{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/traits/wf.rs:418",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(418u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("compute_trait_pred obligations {0:?}",
obligations) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("compute_trait_pred obligations {:?}", obligations);
419let implied_obligations = traits::util::elaborate(tcx, obligations);
420let implied_obligations = implied_obligations.map(extend);
421self.out.extend(implied_obligations);
422 } else {
423self.nominal_obligations(trait_ref.def_id, trait_ref.args, |this, obligation| {
424this.out.push(obligation)
425 });
426 }
427428self.out.extend(
429trait_ref430 .args
431 .iter()
432 .enumerate()
433 .filter_map(|(i, arg)| arg.as_term().map(|t| (i, t)))
434 .filter(|(_, term)| !term.has_escaping_bound_vars())
435 .map(|(i, term)| {
436let mut cause = traits::ObligationCause::misc(self.span, self.body_def_id);
437// The first arg is the self ty - use the correct span for it.
438if i == 0 {
439if let Some(hir::ItemKind::Impl(hir::Impl { self_ty, .. })) =
440item.map(|i| &i.kind)
441 {
442cause.span = self_ty.span;
443 }
444 }
445 traits::Obligation::with_depth(
446tcx,
447cause,
448depth,
449param_env,
450 ty::ClauseKind::WellFormed(term),
451 )
452 }),
453 );
454 }
455456// Compute the obligations that are required for `trait_ref` to be WF,
457 // given that it is a *negative* trait predicate.
458fn add_wf_preds_for_negative_trait_pred(&mut self, trait_ref: ty::TraitRef<'tcx>) {
459for arg in trait_ref.args {
460if let Some(term) = arg.as_term() {
461self.add_wf_preds_for_term(term);
462 }
463 }
464 }
465466/// Pushes the obligations required for a projection to be WF into `self.out`.
467fn add_wf_preds_for_projection_term(&mut self, data: ty::AliasTerm<'tcx>) {
468// A projection is well-formed if
469 //
470 // (a) its predicates hold (*)
471 // (b) its args are wf
472 //
473 // (*) The predicates of an associated type include the predicates of
474 // the trait that it's contained in. For example, given
475 //
476 // trait A<T>: Clone {
477 // type X where T: Copy;
478 // }
479 //
480 // The predicates of `<() as A<i32>>::X` are:
481 // [
482 // `(): Sized`
483 // `(): Clone`
484 // `(): A<i32>`
485 // `i32: Sized`
486 // `i32: Clone`
487 // `i32: Copy`
488 // ]
489self.nominal_obligations(data.expect_projection_def_id(), data.args, |this, obligation| {
490this.out.push(obligation)
491 });
492493self.add_wf_preds_for_projection_args(data.args);
494 }
495496/// Pushes the obligations required for an inherent alias to be WF
497 /// into `self.out`.
498// FIXME(inherent_associated_types): Merge this function with `fn compute_alias`.
499fn add_wf_preds_for_inherent_projection(&mut self, data: ty::AliasTerm<'tcx>) {
500// An inherent projection is well-formed if
501 //
502 // (a) its predicates hold (*)
503 // (b) its args are wf
504 //
505 // (*) The predicates of an inherent associated type include the
506 // predicates of the impl that it's contained in.
507508 // In an ideal world, there are no escaping bound vars here. However, WF is jank, and
509 // sometimes there are. We can only `compute_inherent_assoc_term_args` if the Self ty in the
510 // args has no escaping bound vars. If we already have impl format args, though,
511 // `compute_inherent_assoc_term_args` is a no-op (and we have no Self type), so no need to
512 // check for escaping bound vars.
513let can_compute_impl_args =
514#[allow(non_exhaustive_omitted_patterns)] match data.kind {
ty::AliasTermKind::InherentConstImpl { .. } => true,
_ => false,
}matches!(data.kind, ty::AliasTermKind::InherentConstImpl { .. })515 || !data.self_ty().has_escaping_bound_vars();
516517if can_compute_impl_args {
518// FIXME(inherent_associated_types): Should this happen inside of a snapshot?
519 // FIXME(inherent_associated_types): This is incompatible with the new solver and lazy norm!
520let args = traits::project::compute_inherent_assoc_term_args(
521&mut traits::SelectionContext::new(self.infcx),
522self.param_env,
523data,
524self.cause(ObligationCauseCode::WellFormed(WellFormedLoc::None)),
525self.recursion_depth,
526&mut self.out,
527 );
528let def_id = data.expect_inherent_def_id();
529self.nominal_obligations(def_id, args, |this, obligation| this.out.push(obligation));
530 }
531532data.args.visit_with(self);
533 }
534535fn add_wf_preds_for_projection_args(&mut self, args: GenericArgsRef<'tcx>) {
536let tcx = self.tcx();
537let cause = self.cause(ObligationCauseCode::WellFormed(WellFormedLoc::None));
538let param_env = self.param_env;
539let depth = self.recursion_depth;
540541self.out.extend(
542args.iter()
543 .filter_map(|arg| arg.as_term())
544 .filter(|term| !term.has_escaping_bound_vars())
545 .map(|term| {
546 traits::Obligation::with_depth(
547tcx,
548cause.clone(),
549depth,
550param_env,
551 ty::ClauseKind::WellFormed(term),
552 )
553 }),
554 );
555 }
556557fn require_sized(&mut self, subty: Ty<'tcx>, cause: traits::ObligationCauseCode<'tcx>) {
558if !subty.has_escaping_bound_vars() {
559let cause = self.cause(cause);
560let trait_ref = ty::TraitRef::new(
561self.tcx(),
562self.tcx().require_lang_item(LangItem::Sized, cause.span),
563 [subty],
564 );
565self.out.push(traits::Obligation::with_depth(
566self.tcx(),
567cause,
568self.recursion_depth,
569self.param_env,
570 ty::Binder::dummy(trait_ref),
571 ));
572 }
573 }
574575/// Pushes all the predicates needed to validate that `term` is WF into `out`.
576{}
#[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("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(576u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("term")
}> =
::tracing::__macro_support::FieldName::new("term");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&term)
as &dyn ::tracing::field::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 /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/traits/wf.rs:579",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(579u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("self.out")
}> =
::tracing::__macro_support::FieldName::new("self.out");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self.out)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
}
}
}#[instrument(level = "debug", skip(self))]577fn add_wf_preds_for_term(&mut self, term: Term<'tcx>) {
578 term.visit_with(self);
579debug!(?self.out);
580 }
581582{}
#[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("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(582u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("def_id")
}> =
::tracing::__macro_support::FieldName::new("def_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("args")
}> =
::tracing::__macro_support::FieldName::new("args");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args)
as &dyn ::tracing::field::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;
}
{
if self.tcx().is_lang_item(def_id, LangItem::Sized) { return; }
if self.tcx().is_lang_item(def_id, LangItem::ConstParamTy) &&
self.tcx().features().const_param_ty_unchecked() {
return;
}
let tcx = self.tcx();
let mut head = (def_id, tcx.clauses_of(def_id));
let mut inner_levels = Vec::new();
while let Some(parent) = head.1.parent {
inner_levels.push(head);
head = (parent, tcx.clauses_of(parent));
}
for &(origin_def_id, clauses) in
iter::once(&head).chain(inner_levels.iter().rev()) {
for (clause, span) in clauses.instantiate_own(tcx, args) {
if !clause.has_escaping_bound_vars() {
let code =
ObligationCauseCode::WhereClause(origin_def_id, span);
let cause = self.cause(code);
let obligation =
traits::Obligation::with_depth(tcx, cause,
self.recursion_depth, self.param_env,
clause.skip_norm_wip());
push_obligation(self, obligation);
}
}
}
}
}
}#[instrument(level = "debug", skip(self, push_obligation))]583fn nominal_obligations(
584&mut self,
585 def_id: DefId,
586 args: GenericArgsRef<'tcx>,
587mut push_obligation: impl FnMut(&mut Self, PredicateObligation<'tcx>),
588 ) {
589// PERF: `Sized`'s predicates include `MetaSized`, but both are compiler implemented marker
590 // traits, so `MetaSized` will always be WF if `Sized` is WF and vice-versa. Determining
591 // the nominal obligations of `Sized` would in-effect just elaborate `MetaSized` and make
592 // the compiler do a bunch of work needlessly.
593if self.tcx().is_lang_item(def_id, LangItem::Sized) {
594return;
595 }
596if self.tcx().is_lang_item(def_id, LangItem::ConstParamTy)
597 && self.tcx().features().const_param_ty_unchecked()
598 {
599return;
600 }
601602let tcx = self.tcx();
603let mut head = (def_id, tcx.clauses_of(def_id));
604let mut inner_levels = Vec::new(); // only allocates if a parent chain exists
605while let Some(parent) = head.1.parent {
606 inner_levels.push(head);
607 head = (parent, tcx.clauses_of(parent));
608 }
609610// Emit outermost first, as diagnostics rely on that order.
611for &(origin_def_id, clauses) in iter::once(&head).chain(inner_levels.iter().rev()) {
612for (clause, span) in clauses.instantiate_own(tcx, args) {
613if !clause.has_escaping_bound_vars() {
614let code = ObligationCauseCode::WhereClause(origin_def_id, span);
615let cause = self.cause(code);
616let obligation = traits::Obligation::with_depth(
617 tcx,
618 cause,
619self.recursion_depth,
620self.param_env,
621 clause.skip_norm_wip(),
622 );
623 push_obligation(self, obligation);
624 }
625 }
626 }
627 }
628629fn add_wf_preds_for_dyn_ty(
630&mut self,
631 ty: Ty<'tcx>,
632 data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
633 region: ty::Region<'tcx>,
634 ) {
635// Imagine a type like this:
636 //
637 // trait Foo { }
638 // trait Bar<'c> : 'c { }
639 //
640 // &'b (Foo+'c+Bar<'d>)
641 // ^
642 //
643 // In this case, the following relationships must hold:
644 //
645 // 'b <= 'c
646 // 'd <= 'c
647 //
648 // The first conditions is due to the normal region pointer
649 // rules, which say that a reference cannot outlive its
650 // referent.
651 //
652 // The final condition may be a bit surprising. In particular,
653 // you may expect that it would have been `'c <= 'd`, since
654 // usually lifetimes of outer things are conservative
655 // approximations for inner things. However, it works somewhat
656 // differently with trait objects: here the idea is that if the
657 // user specifies a region bound (`'c`, in this case) it is the
658 // "master bound" that *implies* that bounds from other traits are
659 // all met. (Remember that *all bounds* in a type like
660 // `Foo+Bar+Zed` must be met, not just one, hence if we write
661 // `Foo<'x>+Bar<'y>`, we know that the type outlives *both* 'x and
662 // 'y.)
663 //
664 // Note: in fact we only permit builtin traits, not `Bar<'d>`, I
665 // am looking forward to the future here.
666if !data.has_escaping_bound_vars() && !region.has_escaping_bound_vars() {
667let implicit_bounds = object_region_bounds(self.tcx(), data);
668669let explicit_bound = region;
670671self.out.reserve(implicit_bounds.len());
672for implicit_bound in implicit_bounds {
673let cause = self.cause(ObligationCauseCode::ObjectTypeBound(ty, explicit_bound));
674let outlives =
675 ty::Binder::dummy(ty::OutlivesClause(explicit_bound, implicit_bound));
676self.out.push(traits::Obligation::with_depth(
677self.tcx(),
678 cause,
679self.recursion_depth,
680self.param_env,
681 outlives,
682 ));
683 }
684685// We don't add any wf predicates corresponding to the trait ref's generic arguments
686 // which allows code like this to compile:
687 // ```rust
688 // trait Trait<T: Sized> {}
689 // fn foo(_: &dyn Trait<[u32]>) {}
690 // ```
691}
692 }
693694fn add_wf_preds_for_pat_ty(&mut self, base_ty: Ty<'tcx>, pat: ty::Pattern<'tcx>) {
695let tcx = self.tcx();
696match *pat {
697 ty::PatternKind::Range { start, end } => {
698let mut check = |c| {
699let cause = self.cause(ObligationCauseCode::Misc);
700self.out.push(traits::Obligation::with_depth(
701tcx,
702cause.clone(),
703self.recursion_depth,
704self.param_env,
705 ty::Binder::dummy(ty::PredicateKind::Clause(
706 ty::ClauseKind::ConstArgHasType(c, base_ty),
707 )),
708 ));
709if !tcx.features().generic_pattern_types() {
710if c.has_param() {
711if self.span.is_dummy() {
712self.tcx()
713 .dcx()
714 .delayed_bug("feature error should be reported elsewhere, too");
715 } else {
716feature_err(
717&self.tcx().sess,
718 sym::generic_pattern_types,
719self.span,
720"wraparound pattern type ranges cause monomorphization time errors",
721 )
722 .emit();
723 }
724 }
725 }
726 };
727check(start);
728check(end);
729 }
730 ty::PatternKind::NotNull => {}
731 ty::PatternKind::Or(patterns) => {
732for pat in patterns {
733self.add_wf_preds_for_pat_ty(base_ty, pat)
734 }
735 }
736 }
737 }
738}
739740impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for WfPredicates<'a, 'tcx> {
741fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
742{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/traits/wf.rs:742",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(742u32),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("wf bounds for t={0:?} t.kind={1:#?}",
t, t.kind()) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("wf bounds for t={:?} t.kind={:#?}", t, t.kind());
743744if !self.visited_tys.insert(t) {
745return;
746 }
747748let tcx = self.tcx();
749750match *t.kind() {
751 ty::Bool752 | ty::Char753 | ty::Int(..)
754 | ty::Uint(..)
755 | ty::Float(..)
756 | ty::Error(_)
757 | ty::Str758 | ty::CoroutineWitness(..)
759 | ty::Never760 | ty::Param(_)
761 | ty::Bound(..)
762 | ty::Placeholder(..)
763 | ty::Foreign(..) => {
764// WfScalar, WfParameter, etc
765}
766767// Can only infer to `ty::Int(_) | ty::Uint(_)`.
768ty::Infer(ty::IntVar(_)) => {}
769770// Can only infer to `ty::Float(_)`.
771ty::Infer(ty::FloatVar(_)) => {}
772773 ty::Slice(subty) => {
774self.require_sized(subty, ObligationCauseCode::SliceOrArrayElem);
775 }
776777 ty::Array(subty, len) => {
778self.require_sized(subty, ObligationCauseCode::SliceOrArrayElem);
779// Note that the len being WF is implicitly checked while visiting.
780 // Here we just check that it's of type usize.
781let cause = self.cause(ObligationCauseCode::ArrayLen(t));
782self.out.push(traits::Obligation::with_depth(
783tcx,
784cause,
785self.recursion_depth,
786self.param_env,
787 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(
788len,
789tcx.types.usize,
790 ))),
791 ));
792 }
793794 ty::Pat(base_ty, pat) => {
795self.require_sized(base_ty, ObligationCauseCode::Misc);
796self.add_wf_preds_for_pat_ty(base_ty, pat);
797 }
798799 ty::Tuple(tys) => {
800if let Some((last, rest)) = tys.split_last() {
801for &elem in rest {
802self.require_sized(elem, ObligationCauseCode::TupleElem);
803if elem.is_scalable_vector() && !self.span.is_dummy() {
804self.tcx()
805 .dcx()
806 .struct_span_err(
807self.span,
808"scalable vectors cannot be tuple fields",
809 )
810 .emit();
811 }
812 }
813814if last.is_scalable_vector() && !self.span.is_dummy() {
815self.tcx()
816 .dcx()
817 .struct_span_err(self.span, "scalable vectors cannot be tuple fields")
818 .emit();
819 }
820 }
821 }
822823 ty::RawPtr(_, _) => {
824// Simple cases that are WF if their type args are WF.
825}
826827 ty::Alias(
828_,
829 ty::AliasTy {
830 kind: ty::Projection { def_id } | ty::Opaque { def_id } | ty::Free { def_id },
831 args,
832 ..
833 },
834 ) => {
835self.nominal_obligations(def_id, args, |this, obligation| {
836this.out.push(obligation)
837 });
838 }
839 ty::Alias(_, data @ ty::AliasTy { kind: ty::Inherent { .. }, .. }) => {
840self.add_wf_preds_for_inherent_projection(data.into());
841return; // Subtree handled by compute_inherent_projection.
842}
843844 ty::Adt(def, args) => {
845// WfNominalType
846self.nominal_obligations(def.did(), args, |this, obligation| {
847this.out.push(obligation)
848 });
849 }
850851 ty::FnDef(did, args) => {
852let args = args.no_bound_vars().unwrap();
853// HACK: Check the return type of function definitions for
854 // well-formedness to mostly fix #84533. This is still not
855 // perfect and there may be ways to abuse the fact that we
856 // ignore requirements with escaping bound vars. That's a
857 // more general issue however.
858let fn_sig = tcx.fn_sig(did).instantiate(tcx, args).skip_norm_wip();
859fn_sig.output().skip_binder().visit_with(self);
860861self.nominal_obligations(did, args, |this, obligation| this.out.push(obligation));
862 }
863864 ty::Ref(r, rty, _) => {
865// WfReference
866if !r.has_escaping_bound_vars() && !rty.has_escaping_bound_vars() {
867let cause = self.cause(ObligationCauseCode::ReferenceOutlivesReferent(t));
868self.out.push(traits::Obligation::with_depth(
869tcx,
870cause,
871self.recursion_depth,
872self.param_env,
873 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(
874 ty::OutlivesClause(rty, r),
875 ))),
876 ));
877 }
878 }
879880 ty::Coroutine(did, args, ..) => {
881// Walk ALL the types in the coroutine: this will
882 // include the upvar types as well as the yield
883 // type. Note that this is mildly distinct from
884 // the closure case, where we have to be careful
885 // about the signature of the closure. We don't
886 // have the problem of implied bounds here since
887 // coroutines don't take arguments.
888self.nominal_obligations(did, args, |this, obligation| this.out.push(obligation));
889 }
890891 ty::Closure(did, args) => {
892// Note that we cannot skip the generic types
893 // types. Normally, within the fn
894 // body where they are created, the generics will
895 // always be WF, and outside of that fn body we
896 // are not directly inspecting closure types
897 // anyway, except via auto trait matching (which
898 // only inspects the upvar types).
899 // But when a closure is part of a type-alias-impl-trait
900 // then the function that created the defining site may
901 // have had more bounds available than the type alias
902 // specifies. This may cause us to have a closure in the
903 // hidden type that is not actually well formed and
904 // can cause compiler crashes when the user abuses unsafe
905 // code to procure such a closure.
906 // See tests/ui/type-alias-impl-trait/wf_check_closures.rs
907self.nominal_obligations(did, args, |this, obligation| this.out.push(obligation));
908// Only check the upvar types for WF, not the rest
909 // of the types within. This is needed because we
910 // capture the signature and it may not be WF
911 // without the implied bounds. Consider a closure
912 // like `|x: &'a T|` -- it may be that `T: 'a` is
913 // not known to hold in the creator's context (and
914 // indeed the closure may not be invoked by its
915 // creator, but rather turned to someone who *can*
916 // verify that).
917 //
918 // The special treatment of closures here really
919 // ought not to be necessary either; the problem
920 // is related to #25860 -- there is no way for us
921 // to express a fn type complete with the implied
922 // bounds that it is assuming. I think in reality
923 // the WF rules around fn are a bit messed up, and
924 // that is the rot problem: `fn(&'a T)` should
925 // probably always be WF, because it should be
926 // shorthand for something like `where(T: 'a) {
927 // fn(&'a T) }`, as discussed in #25860.
928let upvars = args.as_closure().tupled_upvars_ty();
929return upvars.visit_with(self);
930 }
931932 ty::CoroutineClosure(did, args) => {
933// See the above comments. The same apply to coroutine-closures.
934self.nominal_obligations(did, args, |this, obligation| this.out.push(obligation));
935let upvars = args.as_coroutine_closure().tupled_upvars_ty();
936return upvars.visit_with(self);
937 }
938939 ty::FnPtr(..) => {
940// Let the visitor iterate into the argument/return
941 // types appearing in the fn signature.
942}
943 ty::UnsafeBinder(ty) => {
944// FIXME(unsafe_binders): For now, we have no way to express
945 // that a type must be `ManuallyDrop` OR `Copy` (or a pointer).
946if !ty.has_escaping_bound_vars() {
947self.out.push(traits::Obligation::new(
948self.tcx(),
949self.cause(ObligationCauseCode::Misc),
950self.param_env,
951ty.map_bound(|ty| {
952 ty::TraitRef::new(
953self.tcx(),
954self.tcx().require_lang_item(
955 LangItem::BikeshedGuaranteedNoDrop,
956self.span,
957 ),
958 [ty],
959 )
960 }),
961 ));
962 }
963964// We recurse into the binder below.
965}
966967 ty::Dynamic(data, r) => {
968// WfObject
969 //
970 // Here, we defer WF checking due to higher-ranked
971 // regions. This is perhaps not ideal.
972self.add_wf_preds_for_dyn_ty(t, data, r);
973974// FIXME(#27579) RFC also considers adding trait
975 // obligations that don't refer to Self and
976 // checking those
977if let Some(principal) = data.principal() {
978let principal_def_id = principal.skip_binder().def_id;
979self.out.push(traits::Obligation::with_depth(
980tcx,
981self.cause(ObligationCauseCode::WellFormed(WellFormedLoc::None)),
982self.recursion_depth,
983self.param_env,
984 ty::Binder::dummy(ty::PredicateKind::DynCompatible(principal_def_id)),
985 ));
986987// For the most part we don't add wf predicates corresponding to
988 // the trait ref's generic arguments which allows code like this
989 // to compile:
990 // ```rust
991 // trait Trait<T: Sized> {}
992 // fn foo(_: &dyn Trait<[u32]>) {}
993 // ```
994 //
995 // However, we sometimes incidentally check that const arguments
996 // have the correct type as a side effect of the anon const
997 // desugaring. To make this "consistent" for users we explicitly
998 // check `ConstArgHasType` clauses so that const args that don't
999 // go through an anon const still have their types checked.
1000 //
1001 // See also: https://rustc-dev-guide.rust-lang.org/const-generics.html
1002let args = principal.skip_binder().with_self_ty(self.tcx(), t).args;
1003self.nominal_obligations(principal_def_id, args, |this, obligation| {
1004let kind = obligation.predicate.kind().skip_binder();
1005let keep = match kind {
1006 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, _))
1007if #[allow(non_exhaustive_omitted_patterns)] match ct.kind() {
ty::ConstKind::Param(..) | ty::ConstKind::Placeholder(..) => true,
_ => false,
}matches!(
1008 ct.kind(),
1009 ty::ConstKind::Param(..) | ty::ConstKind::Placeholder(..)
1010 ) =>
1011 {
1012// ConstArgHasType clauses are not higher kinded. Assert as
1013 // such so we can fix this up if that ever changes.
1014if !obligation.predicate.kind().bound_vars().is_empty() {
::core::panicking::panic("assertion failed: obligation.predicate.kind().bound_vars().is_empty()")
};assert!(obligation.predicate.kind().bound_vars().is_empty());
1015// In stable rust, variables from the trait object binder
1016 // cannot be referenced by a ConstArgHasType clause. However,
1017 // under `generic_const_parameter_types`, it can. Ignore those
1018 // predicates for now, to not have HKT-ConstArgHasTypes.
1019!kind.has_escaping_bound_vars()
1020 }
1021_ => false,
1022 };
1023if keep {
1024this.out.push(obligation);
1025 }
1026 });
1027 }
10281029if !t.has_escaping_bound_vars() {
1030for projection in data.projection_bounds() {
1031let pred_binder = projection
1032 .with_self_ty(tcx, t)
1033 .map_bound(|p| {
1034 p.term.as_const().map(|ct| {
1035let assoc_const_ty = tcx
1036 .type_of(p.def_id())
1037 .instantiate(tcx, p.projection_term.args)
1038 .skip_norm_wip();
1039 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(
1040 ct,
1041 assoc_const_ty,
1042 ))
1043 })
1044 })
1045 .transpose();
1046if let Some(pred_binder) = pred_binder {
1047self.out.push(traits::Obligation::with_depth(
1048 tcx,
1049self.cause(ObligationCauseCode::WellFormed(WellFormedLoc::None)),
1050self.recursion_depth,
1051self.param_env,
1052 pred_binder,
1053 ));
1054 }
1055 }
1056 }
1057 }
10581059// Inference variables are the complicated case, since we don't
1060 // know what type they are. We do two things:
1061 //
1062 // 1. Check if they have been resolved, and if so proceed with
1063 // THAT type.
1064 // 2. If not, we've at least simplified things (e.g., we went
1065 // from `Vec?0>: WF` to `?0: WF`), so we can
1066 // register a pending obligation and keep
1067 // moving. (Goal is that an "inductive hypothesis"
1068 // is satisfied to ensure termination.)
1069 // See also the comment on `fn obligations`, describing cycle
1070 // prevention, which happens before this can be reached.
1071ty::Infer(_) => {
1072let cause = self.cause(ObligationCauseCode::WellFormed(WellFormedLoc::None));
1073self.out.push(traits::Obligation::with_depth(
1074tcx,
1075cause,
1076self.recursion_depth,
1077self.param_env,
1078 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(
1079t.into(),
1080 ))),
1081 ));
1082 }
1083 }
10841085t.super_visit_with(self)
1086 }
10871088fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1089let tcx = self.tcx();
10901091match c.kind() {
1092 ty::ConstKind::Alias(_, alias_const) => {
1093if !c.has_escaping_bound_vars() {
1094// Skip type consts as mGCA doesn't support evaluatable clauses
1095if !alias_const.kind.is_direct_const(tcx) && !tcx.features().gca_const_items() {
1096let predicate = ty::Binder::dummy(ty::PredicateKind::Clause(
1097 ty::ClauseKind::ConstEvaluatable(c),
1098 ));
1099let cause =
1100self.cause(ObligationCauseCode::WellFormed(WellFormedLoc::None));
1101self.out.push(traits::Obligation::with_depth(
1102tcx,
1103cause,
1104self.recursion_depth,
1105self.param_env,
1106predicate,
1107 ));
1108 }
11091110match alias_const.kind {
1111 ty::AliasConstKind::InherentSelf { .. } => {
1112self.add_wf_preds_for_inherent_projection(alias_const.into());
1113return; // Subtree is handled by above function
1114}
1115// FIXME: This should be unreachable but isn't because we normalize in item
1116 // wfck before computing wf requirements
1117ty::AliasConstKind::InherentImpl { .. } => {
1118self.add_wf_preds_for_inherent_projection(alias_const.into());
1119return;
1120 }
1121 ty::AliasConstKind::Projection { def_id }
1122 | ty::AliasConstKind::Free { def_id }
1123 | ty::AliasConstKind::Anon { def_id } => {
1124self.nominal_obligations(
1125def_id,
1126alias_const.args,
1127 |this, obligation| this.out.push(obligation),
1128 );
1129 }
1130 }
1131 }
1132 }
1133 ty::ConstKind::Infer(_) => {
1134let cause = self.cause(ObligationCauseCode::WellFormed(WellFormedLoc::None));
11351136self.out.push(traits::Obligation::with_depth(
1137tcx,
1138cause,
1139self.recursion_depth,
1140self.param_env,
1141 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(
1142c.into(),
1143 ))),
1144 ));
1145 }
1146 ty::ConstKind::Expr(_) => {
1147// FIXME(generic_const_exprs): this doesn't verify that given `Expr(N + 1)` the
1148 // trait bound `typeof(N): Add<typeof(1)>` holds. This is currently unnecessary
1149 // as `ConstKind::Expr` is only produced via normalization of `ConstKind::Alias`
1150 // which means that the `DefId` would have been typeck'd elsewhere. However in
1151 // the future we may allow directly lowering to `ConstKind::Expr` in which case
1152 // we would not be proving bounds we should.
11531154let predicate = ty::Binder::dummy(ty::PredicateKind::Clause(
1155 ty::ClauseKind::ConstEvaluatable(c),
1156 ));
1157let cause = self.cause(ObligationCauseCode::WellFormed(WellFormedLoc::None));
1158self.out.push(traits::Obligation::with_depth(
1159tcx,
1160cause,
1161self.recursion_depth,
1162self.param_env,
1163predicate,
1164 ));
1165 }
11661167 ty::ConstKind::Error(_)
1168 | ty::ConstKind::Param(_)
1169 | ty::ConstKind::Bound(..)
1170 | ty::ConstKind::Placeholder(..) => {
1171// These variants are trivially WF, so nothing to do here.
1172}
1173 ty::ConstKind::Value(val) => {
1174// FIXME(mgca): no need to feature-gate once valtree lifetimes are not erased
1175if tcx.features().gca() {
1176match val.ty.kind() {
1177 ty::Adt(adt_def, args) => {
1178let adt_val = val.destructure_adt_const();
1179let variant_def = adt_def.variant(adt_val.variant);
1180let cause =
1181self.cause(ObligationCauseCode::WellFormed(WellFormedLoc::None));
1182self.out.extend(variant_def.fields.iter().zip(adt_val.fields).map(
1183 |(field_def, &field_val)| {
1184let field_ty = tcx1185 .type_of(field_def.did)
1186 .instantiate(tcx, args)
1187 .skip_norm_wip();
1188let predicate = ty::PredicateKind::Clause(
1189 ty::ClauseKind::ConstArgHasType(field_val, field_ty),
1190 );
1191 traits::Obligation::with_depth(
1192tcx,
1193cause.clone(),
1194self.recursion_depth,
1195self.param_env,
1196predicate,
1197 )
1198 },
1199 ));
1200 }
1201 ty::Tuple(field_tys) => {
1202let field_vals = val.to_branch();
1203let cause =
1204self.cause(ObligationCauseCode::WellFormed(WellFormedLoc::None));
1205self.out.extend(field_tys.iter().zip(field_vals).map(
1206 |(field_ty, &field_val)| {
1207let predicate = ty::PredicateKind::Clause(
1208 ty::ClauseKind::ConstArgHasType(field_val, field_ty),
1209 );
1210 traits::Obligation::with_depth(
1211tcx,
1212cause.clone(),
1213self.recursion_depth,
1214self.param_env,
1215predicate,
1216 )
1217 },
1218 ));
1219 }
1220 ty::Array(elem_ty, _len) => {
1221let elem_vals = val.to_branch();
1222let cause =
1223self.cause(ObligationCauseCode::WellFormed(WellFormedLoc::None));
12241225self.out.extend(elem_vals.iter().map(|&elem_val| {
1226let predicate = ty::PredicateKind::Clause(
1227 ty::ClauseKind::ConstArgHasType(elem_val, *elem_ty),
1228 );
1229 traits::Obligation::with_depth(
1230tcx,
1231cause.clone(),
1232self.recursion_depth,
1233self.param_env,
1234predicate,
1235 )
1236 }));
1237 }
1238_ => {}
1239 }
1240 }
12411242// FIXME: Enforce that values are structurally-matchable.
1243}
1244 }
12451246c.super_visit_with(self)
1247 }
12481249fn visit_predicate<P: PredicateProxy<TyCtxt<'tcx>>>(&mut self, _p: P) -> Self::Result {
1250::rustc_span::macros::bug_impl(None,
format_args!("predicate should not be checked for well-formedness"),
Location::caller());bug!("predicate should not be checked for well-formedness");
1251 }
1252}
12531254/// Given an object type like `SomeTrait + Send`, computes the lifetime
1255/// bounds that must hold on the elided self type. These are derived
1256/// from the declarations of `SomeTrait`, `Send`, and friends -- if
1257/// they declare `trait SomeTrait : 'static`, for example, then
1258/// `'static` would appear in the list.
1259///
1260/// N.B., in some cases, particularly around higher-ranked bounds,
1261/// this function returns a kind of conservative approximation.
1262/// That is, all regions returned by this function are definitely
1263/// required, but there may be other region bounds that are not
1264/// returned, as well as requirements like `for<'a> T: 'a`.
1265///
1266/// Requires that trait definitions have been processed so that we can
1267/// elaborate predicates and walk supertraits.
1268pub fn object_region_bounds<'tcx>(
1269 tcx: TyCtxt<'tcx>,
1270 existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1271) -> Vec<ty::Region<'tcx>> {
1272let erased_self_ty = tcx.types.trait_object_dummy_self;
12731274let clauses =
1275existential_predicates.iter().map(|predicate| predicate.with_self_ty(tcx, erased_self_ty));
12761277 traits::elaborate(tcx, clauses)
1278 .filter_map(|clause| {
1279{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/traits/wf.rs:1279",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/b6eeb93c992027a03e1fd120b6652546396b142c/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(1279u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("clause")
}> =
::tracing::__macro_support::FieldName::new("clause");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&clause)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?clause);
1280match clause.kind().skip_binder() {
1281 ty::ClauseKind::TypeOutlives(ty::OutlivesClause(ref t, ref r)) => {
1282// Search for a bound of the form `erased_self_ty
1283 // : 'a`, but be wary of something like `for<'a>
1284 // erased_self_ty : 'a` (we interpret a
1285 // higher-ranked bound like that as 'static,
1286 // though at present the code in `fulfill.rs`
1287 // considers such bounds to be unsatisfiable, so
1288 // it's kind of a moot point since you could never
1289 // construct such an object, but this seems
1290 // correct even if that code changes).
1291if t == &erased_self_ty && !r.has_escaping_bound_vars() {
1292Some(*r)
1293 } else {
1294None1295 }
1296 }
1297 ty::ClauseKind::Trait(_)
1298 | ty::ClauseKind::HostEffect(..)
1299 | ty::ClauseKind::RegionOutlives(_)
1300 | ty::ClauseKind::Projection(_)
1301 | ty::ClauseKind::ConstArgHasType(_, _)
1302 | ty::ClauseKind::WellFormed(_)
1303 | ty::ClauseKind::UnstableFeature(_)
1304 | ty::ClauseKind::ConstEvaluatable(_) => None,
1305 }
1306 })
1307 .collect()
1308}