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, GenericArgs, PredicateProxy, Term, TermKind, Ty, TyCtxt, TypeSuperVisitable,
15TypeVisitable, 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/f5cedb83a788ea9581097abc36a2a8503a7f541c/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/f5cedb83a788ea9581097abc36a2a8503a7f541c/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/f5cedb83a788ea9581097abc36a2a8503a7f541c/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/f5cedb83a788ea9581097abc36a2a8503a7f541c/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/f5cedb83a788ea9581097abc36a2a8503a7f541c/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/f5cedb83a788ea9581097abc36a2a8503a7f541c/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/f5cedb83a788ea9581097abc36a2a8503a7f541c/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) => {
if !t.projection_term.kind.is_type() {
if !#[allow(non_exhaustive_omitted_patterns)] match t.projection_term.kind
{
ty::AliasTermKind::ProjectionConst { .. } => true,
_ => false,
} {
::core::panicking::panic("assertion failed: matches!(t.projection_term.kind, ty::AliasTermKind::ProjectionConst { .. })")
};
wf.require_const_item_ty(t.projection_term.expect_ct());
}
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/f5cedb83a788ea9581097abc36a2a8503a7f541c/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/f5cedb83a788ea9581097abc36a2a8503a7f541c/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) => {
190if !t.projection_term.kind.is_type() {
191assert!(matches!(
192 t.projection_term.kind,
193 ty::AliasTermKind::ProjectionConst { .. }
194 ));
195 wf.require_const_item_ty(t.projection_term.expect_ct());
196 }
197 wf.add_wf_preds_for_projection_term(t.projection_term);
198 wf.add_wf_preds_for_term(t.term);
199 }
200 ty::ClauseKind::ConstArgHasType(ct, ty) => {
201 wf.add_wf_preds_for_term(ct.into());
202 wf.add_wf_preds_for_term(ty.into());
203 }
204 ty::ClauseKind::WellFormed(term) => {
205 wf.add_wf_preds_for_term(term);
206 }
207208 ty::ClauseKind::ConstEvaluatable(ct) => {
209 wf.add_wf_preds_for_term(ct.into());
210 }
211 ty::ClauseKind::UnstableFeature(_) => {}
212 }
213214 wf.normalize(infcx)
215}
216217struct WfPredicates<'a, 'tcx> {
218 infcx: &'a InferCtxt<'tcx>,
219 param_env: ty::ParamEnv<'tcx>,
220 body_def_id: LocalDefId,
221 span: Span,
222 out: PredicateObligations<'tcx>,
223 recursion_depth: usize,
224 item: Option<&'tcx hir::Item<'tcx>>,
225 visited_tys: DelayedSet<Ty<'tcx>>,
226}
227228/// Controls whether we "elaborate" supertraits and so forth on the WF
229/// predicates. This is a kind of hack to address #43784. The
230/// underlying problem in that issue was a trait structure like:
231///
232/// ```ignore (illustrative)
233/// trait Foo: Copy { }
234/// trait Bar: Foo { }
235/// impl<T: Bar> Foo for T { }
236/// impl<T> Bar for T { }
237/// ```
238///
239/// Here, in the `Foo` impl, we will check that `T: Copy` holds -- but
240/// we decide that this is true because `T: Bar` is in the
241/// where-clauses (and we can elaborate that to include `T:
242/// Copy`). This wouldn't be a problem, except that when we check the
243/// `Bar` impl, we decide that `T: Foo` must hold because of the `Foo`
244/// impl. And so nowhere did we check that `T: Copy` holds!
245///
246/// To resolve this, we elaborate the WF requirements that must be
247/// proven when checking impls. This means that (e.g.) the `impl Bar
248/// for T` will be forced to prove not only that `T: Foo` but also `T:
249/// Copy` (which it won't be able to do, because there is no `Copy`
250/// impl for `T`).
251#[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)]
252enum Elaborate {
253 All,
254None,
255}
256257/// Points the cause span of a super predicate at the relevant associated type.
258///
259/// Given a trait impl item:
260///
261/// ```ignore (incomplete)
262/// impl TargetTrait for TargetType {
263/// type Assoc = SomeType;
264/// }
265/// ```
266///
267/// And a super predicate of `TargetTrait` that has any of the following forms:
268///
269/// 1. `<OtherType as OtherTrait>::Assoc == <TargetType as TargetTrait>::Assoc`
270/// 2. `<<TargetType as TargetTrait>::Assoc as OtherTrait>::Assoc == OtherType`
271/// 3. `<TargetType as TargetTrait>::Assoc: OtherTrait`
272///
273/// Replace the span of the cause with the span of the associated item:
274///
275/// ```ignore (incomplete)
276/// impl TargetTrait for TargetType {
277/// type Assoc = SomeType;
278/// // ^^^^^^^^ this span
279/// }
280/// ```
281///
282/// Note that bounds that can be expressed as associated item bounds are **not**
283/// super predicates. This means that form 2 and 3 from above are only relevant if
284/// the [`GenericArgs`] of the projection type are not its identity arguments.
285fn extend_cause_with_original_assoc_item_obligation<'tcx>(
286 tcx: TyCtxt<'tcx>,
287 item: Option<&hir::Item<'tcx>>,
288 cause: &mut traits::ObligationCause<'tcx>,
289 pred: ty::Predicate<'tcx>,
290) {
291{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_trait_selection/src/traits/wf.rs:291",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(291u32),
::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");
292let (items, impl_def_id) = match item {
293Some(hir::Item { kind: hir::ItemKind::Impl(impl_), owner_id, .. }) => {
294 (impl_.items, *owner_id)
295 }
296_ => return,
297 };
298299let ty_to_impl_span = |ty: Ty<'_>| {
300if let ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, .. }) = ty.kind()
301 && let Some(&impl_item_id) = tcx.impl_item_implementor_ids(impl_def_id).get(def_id)
302 && let Some(impl_item) =
303items.iter().find(|item| item.owner_id.to_def_id() == impl_item_id)
304 {
305Some(tcx.hir_impl_item(*impl_item).expect_type().span)
306 } else {
307None308 }
309 };
310311// It is fine to skip the binder as we don't care about regions here.
312match pred.kind().skip_binder() {
313 ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)) => {
314// Form 1: The obligation comes not from the current `impl` nor the `trait` being
315 // implemented, but rather from a "second order" obligation, where an associated
316 // type has a projection coming from another associated type.
317 // See `tests/ui/traits/assoc-type-in-superbad.rs` for an example.
318if let Some(term_ty) = proj.term.as_type()
319 && let Some(impl_item_span) = ty_to_impl_span(term_ty)
320 {
321cause.span = impl_item_span;
322 }
323324// Form 2: A projection obligation for an associated item failed to be met.
325 // We overwrite the span from above to ensure that a bound like
326 // `Self::Assoc1: Trait<OtherAssoc = Self::Assoc2>` gets the same
327 // span for both obligations that it is lowered to.
328if let Some(impl_item_span) = ty_to_impl_span(proj.self_ty()) {
329cause.span = impl_item_span;
330 }
331 }
332333 ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
334// Form 3: A trait obligation for an associated item failed to be met.
335{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_trait_selection/src/traits/wf.rs:335",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(335u32),
::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);
336if let Some(impl_item_span) = ty_to_impl_span(pred.self_ty()) {
337cause.span = impl_item_span;
338 }
339 }
340_ => {}
341 }
342}
343344impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
345fn tcx(&self) -> TyCtxt<'tcx> {
346self.infcx.tcx
347 }
348349fn cause(&self, code: traits::ObligationCauseCode<'tcx>) -> traits::ObligationCause<'tcx> {
350 traits::ObligationCause::new(self.span, self.body_def_id, code)
351 }
352353fn normalize(self, infcx: &InferCtxt<'tcx>) -> PredicateObligations<'tcx> {
354// Do not normalize `wf` obligations with the new solver.
355 //
356 // The current deep normalization routine with the new solver does not
357 // handle ambiguity and the new solver correctly deals with unnnormalized goals.
358 // If the user relies on normalized types, e.g. for `fn implied_outlives_bounds`,
359 // it is their responsibility to normalize while avoiding ambiguity.
360if infcx.next_trait_solver() {
361return self.out;
362 }
363364let cause = self.cause(ObligationCauseCode::WellFormed(WellFormedLoc::None));
365let param_env = self.param_env;
366let mut obligations = PredicateObligations::with_capacity(self.out.len());
367for mut obligation in self.out {
368if !!obligation.has_escaping_bound_vars() {
::core::panicking::panic("assertion failed: !obligation.has_escaping_bound_vars()")
};assert!(!obligation.has_escaping_bound_vars());
369let mut selcx = traits::SelectionContext::new(infcx);
370// Don't normalize the whole obligation, the param env is either
371 // already normalized, or we're currently normalizing the
372 // param_env. Either way we should only normalize the predicate.
373let normalized_predicate = traits::normalize::normalize_with_depth_to(
374&mut selcx,
375 param_env,
376 cause.clone(),
377self.recursion_depth,
378 ty::Unnormalized::new_wip(obligation.predicate),
379&mut obligations,
380 );
381 obligation.predicate = normalized_predicate;
382 obligations.push(obligation);
383 }
384obligations385 }
386387/// Pushes the obligations required for `trait_ref` to be WF into `self.out`.
388fn add_wf_preds_for_trait_pred(
389&mut self,
390 trait_pred: ty::TraitClause<'tcx>,
391 elaborate: Elaborate,
392 ) {
393let tcx = self.tcx();
394let trait_ref = trait_pred.trait_ref;
395396// Negative trait predicates don't require supertraits to hold, just
397 // that their args are WF.
398if trait_pred.polarity == ty::ClausePolarity::Negative {
399self.add_wf_preds_for_negative_trait_pred(trait_ref);
400return;
401 }
402403let param_env = self.param_env;
404let depth = self.recursion_depth;
405406let item = self.item;
407408let extend = |traits::PredicateObligation { predicate, mut cause, .. }| {
409if let Some(parent_trait_pred) = predicate.as_trait_clause() {
410cause = cause.derived_cause(
411parent_trait_pred,
412 traits::ObligationCauseCode::WellFormedDerived,
413 );
414 }
415extend_cause_with_original_assoc_item_obligation(tcx, item, &mut cause, predicate);
416 traits::Obligation::with_depth(tcx, cause, depth, param_env, predicate)
417 };
418419// if the trait predicate is not const, the wf obligations should not be const as well.
420if let Elaborate::All = elaborate {
421let mut obligations = PredicateObligations::new();
422self.nominal_obligations(trait_ref.def_id, trait_ref.args, |_, obligation| {
423obligations.push(obligation)
424 });
425{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_trait_selection/src/traits/wf.rs:425",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(425u32),
::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);
426let implied_obligations = traits::util::elaborate(tcx, obligations);
427let implied_obligations = implied_obligations.map(extend);
428self.out.extend(implied_obligations);
429 } else {
430self.nominal_obligations(trait_ref.def_id, trait_ref.args, |this, obligation| {
431this.out.push(obligation)
432 });
433 }
434435self.out.extend(
436trait_ref437 .args
438 .iter()
439 .enumerate()
440 .filter_map(|(i, arg)| arg.as_term().map(|t| (i, t)))
441 .filter(|(_, term)| !term.has_escaping_bound_vars())
442 .map(|(i, term)| {
443let mut cause = traits::ObligationCause::misc(self.span, self.body_def_id);
444// The first arg is the self ty - use the correct span for it.
445if i == 0 {
446if let Some(hir::ItemKind::Impl(hir::Impl { self_ty, .. })) =
447item.map(|i| &i.kind)
448 {
449cause.span = self_ty.span;
450 }
451 }
452 traits::Obligation::with_depth(
453tcx,
454cause,
455depth,
456param_env,
457 ty::ClauseKind::WellFormed(term),
458 )
459 }),
460 );
461 }
462463// Compute the obligations that are required for `trait_ref` to be WF,
464 // given that it is a *negative* trait predicate.
465fn add_wf_preds_for_negative_trait_pred(&mut self, trait_ref: ty::TraitRef<'tcx>) {
466for arg in trait_ref.args {
467if let Some(term) = arg.as_term() {
468self.add_wf_preds_for_term(term);
469 }
470 }
471 }
472473/// Pushes the obligations required for a projection to be WF into `self.out`.
474fn add_wf_preds_for_projection_term(&mut self, data: ty::AliasTerm<'tcx>) {
475// A projection is well-formed if
476 //
477 // (a) its predicates hold (*)
478 // (b) its args are wf
479 //
480 // (*) The predicates of an associated type include the predicates of
481 // the trait that it's contained in. For example, given
482 //
483 // trait A<T>: Clone {
484 // type X where T: Copy;
485 // }
486 //
487 // The predicates of `<() as A<i32>>::X` are:
488 // [
489 // `(): Sized`
490 // `(): Clone`
491 // `(): A<i32>`
492 // `i32: Sized`
493 // `i32: Clone`
494 // `i32: Copy`
495 // ]
496self.nominal_obligations(data.expect_projection_def_id(), data.args, |this, obligation| {
497this.out.push(obligation)
498 });
499500self.add_wf_preds_for_projection_args(data.args);
501 }
502503/// Pushes the obligations required for an inherent alias to be WF
504 /// into `self.out`.
505// FIXME(inherent_associated_types): Merge this function with `fn compute_alias`.
506fn add_wf_preds_for_inherent_projection(&mut self, data: ty::AliasTerm<'tcx>) {
507// An inherent projection is well-formed if
508 //
509 // (a) its predicates hold (*)
510 // (b) its args are wf
511 //
512 // (*) The predicates of an inherent associated type include the
513 // predicates of the impl that it's contained in.
514515 // In an ideal world, there are no escaping bound vars here. However, WF is jank, and
516 // sometimes there are. We can only `compute_inherent_assoc_term_args` if the Self ty in the
517 // args has no escaping bound vars. If we already have impl format args, though,
518 // `compute_inherent_assoc_term_args` is a no-op (and we have no Self type), so no need to
519 // check for escaping bound vars.
520let can_compute_impl_args =
521#[allow(non_exhaustive_omitted_patterns)] match data.kind {
ty::AliasTermKind::InherentConstImpl { .. } => true,
_ => false,
}matches!(data.kind, ty::AliasTermKind::InherentConstImpl { .. })522 || !data.self_ty().has_escaping_bound_vars();
523524if can_compute_impl_args {
525// FIXME(inherent_associated_types): Should this happen inside of a snapshot?
526 // FIXME(inherent_associated_types): This is incompatible with the new solver and lazy norm!
527let args = traits::project::compute_inherent_assoc_term_args(
528&mut traits::SelectionContext::new(self.infcx),
529self.param_env,
530data,
531self.cause(ObligationCauseCode::WellFormed(WellFormedLoc::None)),
532self.recursion_depth,
533&mut self.out,
534 );
535let def_id = data.expect_inherent_def_id();
536self.nominal_obligations(def_id, args, |this, obligation| this.out.push(obligation));
537 }
538539data.args.visit_with(self);
540 }
541542fn add_wf_preds_for_projection_args(&mut self, args: GenericArgs<'tcx>) {
543let tcx = self.tcx();
544let cause = self.cause(ObligationCauseCode::WellFormed(WellFormedLoc::None));
545let param_env = self.param_env;
546let depth = self.recursion_depth;
547548self.out.extend(
549args.iter()
550 .filter_map(|arg| arg.as_term())
551 .filter(|term| !term.has_escaping_bound_vars())
552 .map(|term| {
553 traits::Obligation::with_depth(
554tcx,
555cause.clone(),
556depth,
557param_env,
558 ty::ClauseKind::WellFormed(term),
559 )
560 }),
561 );
562 }
563564fn require_sized(&mut self, subty: Ty<'tcx>, cause: traits::ObligationCauseCode<'tcx>) {
565if !subty.has_escaping_bound_vars() {
566let cause = self.cause(cause);
567let trait_ref = ty::TraitRef::new(
568self.tcx(),
569self.tcx().require_lang_item(LangItem::Sized, cause.span),
570 [subty],
571 );
572self.out.push(traits::Obligation::with_depth(
573self.tcx(),
574cause,
575self.recursion_depth,
576self.param_env,
577 ty::Binder::dummy(trait_ref),
578 ));
579 }
580 }
581582fn require_const_item_ty(&mut self, ct: ty::AliasConst<'tcx>) {
583let ty = ct.type_of(self.tcx()).skip_norm_wip();
584585if ct.kind.is_direct_const(self.tcx()) {
586// This is already checked in `wfcheck::check_const_item`.
587return;
588 }
589590if self.tcx().features().const_param_ty_unchecked() || ty.has_escaping_bound_vars() {
591return;
592 }
593594let cause = self.cause(ObligationCauseCode::ConstItemTy(ty));
595let trait_ref = ty::TraitRef::new(
596self.tcx(),
597self.tcx().require_lang_item(LangItem::ConstParamTy, cause.span),
598 [ty],
599 );
600self.out.push(traits::Obligation::with_depth(
601self.tcx(),
602cause,
603self.recursion_depth,
604self.param_env,
605 ty::Binder::dummy(trait_ref),
606 ));
607 }
608609/// Pushes all the predicates needed to validate that `term` is WF into `out`.
610{}
#[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/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(610u32),
::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/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_trait_selection/src/traits/wf.rs:613",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(613u32),
::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))]611fn add_wf_preds_for_term(&mut self, term: Term<'tcx>) {
612 term.visit_with(self);
613debug!(?self.out);
614 }
615616{}
#[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/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(616u32),
::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))]617fn nominal_obligations(
618&mut self,
619 def_id: DefId,
620 args: GenericArgs<'tcx>,
621mut push_obligation: impl FnMut(&mut Self, PredicateObligation<'tcx>),
622 ) {
623// PERF: `Sized`'s predicates include `MetaSized`, but both are compiler implemented marker
624 // traits, so `MetaSized` will always be WF if `Sized` is WF and vice-versa. Determining
625 // the nominal obligations of `Sized` would in-effect just elaborate `MetaSized` and make
626 // the compiler do a bunch of work needlessly.
627if self.tcx().is_lang_item(def_id, LangItem::Sized) {
628return;
629 }
630if self.tcx().is_lang_item(def_id, LangItem::ConstParamTy)
631 && self.tcx().features().const_param_ty_unchecked()
632 {
633return;
634 }
635636let tcx = self.tcx();
637let mut head = (def_id, tcx.clauses_of(def_id));
638let mut inner_levels = Vec::new(); // only allocates if a parent chain exists
639while let Some(parent) = head.1.parent {
640 inner_levels.push(head);
641 head = (parent, tcx.clauses_of(parent));
642 }
643644// Emit outermost first, as diagnostics rely on that order.
645for &(origin_def_id, clauses) in iter::once(&head).chain(inner_levels.iter().rev()) {
646for (clause, span) in clauses.instantiate_own(tcx, args) {
647if !clause.has_escaping_bound_vars() {
648let code = ObligationCauseCode::WhereClause(origin_def_id, span);
649let cause = self.cause(code);
650let obligation = traits::Obligation::with_depth(
651 tcx,
652 cause,
653self.recursion_depth,
654self.param_env,
655 clause.skip_norm_wip(),
656 );
657 push_obligation(self, obligation);
658 }
659 }
660 }
661 }
662663fn add_wf_preds_for_dyn_ty(
664&mut self,
665 ty: Ty<'tcx>,
666 data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
667 region: ty::Region<'tcx>,
668 ) {
669// Imagine a type like this:
670 //
671 // trait Foo { }
672 // trait Bar<'c> : 'c { }
673 //
674 // &'b (Foo+'c+Bar<'d>)
675 // ^
676 //
677 // In this case, the following relationships must hold:
678 //
679 // 'b <= 'c
680 // 'd <= 'c
681 //
682 // The first conditions is due to the normal region pointer
683 // rules, which say that a reference cannot outlive its
684 // referent.
685 //
686 // The final condition may be a bit surprising. In particular,
687 // you may expect that it would have been `'c <= 'd`, since
688 // usually lifetimes of outer things are conservative
689 // approximations for inner things. However, it works somewhat
690 // differently with trait objects: here the idea is that if the
691 // user specifies a region bound (`'c`, in this case) it is the
692 // "master bound" that *implies* that bounds from other traits are
693 // all met. (Remember that *all bounds* in a type like
694 // `Foo+Bar+Zed` must be met, not just one, hence if we write
695 // `Foo<'x>+Bar<'y>`, we know that the type outlives *both* 'x and
696 // 'y.)
697 //
698 // Note: in fact we only permit builtin traits, not `Bar<'d>`, I
699 // am looking forward to the future here.
700if !data.has_escaping_bound_vars() && !region.has_escaping_bound_vars() {
701let implicit_bounds = object_region_bounds(self.tcx(), data);
702703let explicit_bound = region;
704705self.out.reserve(implicit_bounds.len());
706for implicit_bound in implicit_bounds {
707let cause = self.cause(ObligationCauseCode::ObjectTypeBound(ty, explicit_bound));
708let outlives =
709 ty::Binder::dummy(ty::OutlivesClause(explicit_bound, implicit_bound));
710self.out.push(traits::Obligation::with_depth(
711self.tcx(),
712 cause,
713self.recursion_depth,
714self.param_env,
715 outlives,
716 ));
717 }
718719// We don't add any wf predicates corresponding to the trait ref's generic arguments
720 // which allows code like this to compile:
721 // ```rust
722 // trait Trait<T: Sized> {}
723 // fn foo(_: &dyn Trait<[u32]>) {}
724 // ```
725}
726 }
727728fn add_wf_preds_for_pat_ty(&mut self, base_ty: Ty<'tcx>, pat: ty::Pattern<'tcx>) {
729let tcx = self.tcx();
730match *pat {
731 ty::PatternKind::Range { start, end } => {
732let mut check = |c| {
733let cause = self.cause(ObligationCauseCode::Misc);
734self.out.push(traits::Obligation::with_depth(
735tcx,
736cause.clone(),
737self.recursion_depth,
738self.param_env,
739 ty::Binder::dummy(ty::PredicateKind::Clause(
740 ty::ClauseKind::ConstArgHasType(c, base_ty),
741 )),
742 ));
743if !tcx.features().generic_pattern_types() {
744if c.has_param() {
745if self.span.is_dummy() {
746self.tcx()
747 .dcx()
748 .delayed_bug("feature error should be reported elsewhere, too");
749 } else {
750feature_err(
751&self.tcx().sess,
752 sym::generic_pattern_types,
753self.span,
754"wraparound pattern type ranges cause monomorphization time errors",
755 )
756 .emit();
757 }
758 }
759 }
760 };
761check(start);
762check(end);
763 }
764 ty::PatternKind::NotNull => {}
765 ty::PatternKind::Or(patterns) => {
766for pat in patterns {
767self.add_wf_preds_for_pat_ty(base_ty, pat)
768 }
769 }
770 }
771 }
772}
773774impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for WfPredicates<'a, 'tcx> {
775fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
776{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_trait_selection/src/traits/wf.rs:776",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(776u32),
::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());
777778if !self.visited_tys.insert(t) {
779return;
780 }
781782let tcx = self.tcx();
783784match *t.kind() {
785 ty::Bool786 | ty::Char787 | ty::Int(..)
788 | ty::Uint(..)
789 | ty::Float(..)
790 | ty::Error(_)
791 | ty::Str792 | ty::CoroutineWitness(..)
793 | ty::Never794 | ty::Param(_)
795 | ty::Bound(..)
796 | ty::Placeholder(..)
797 | ty::Foreign(..) => {
798// WfScalar, WfParameter, etc
799}
800801// Can only infer to `ty::Int(_) | ty::Uint(_)`.
802ty::Infer(ty::IntVar(_)) => {}
803804// Can only infer to `ty::Float(_)`.
805ty::Infer(ty::FloatVar(_)) => {}
806807 ty::Slice(subty) => {
808self.require_sized(subty, ObligationCauseCode::SliceOrArrayElem);
809 }
810811 ty::Array(subty, len) => {
812self.require_sized(subty, ObligationCauseCode::SliceOrArrayElem);
813// Note that the len being WF is implicitly checked while visiting.
814 // Here we just check that it's of type usize.
815let cause = self.cause(ObligationCauseCode::ArrayLen(t));
816self.out.push(traits::Obligation::with_depth(
817tcx,
818cause,
819self.recursion_depth,
820self.param_env,
821 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(
822len,
823tcx.types.usize,
824 ))),
825 ));
826 }
827828 ty::Pat(base_ty, pat) => {
829self.require_sized(base_ty, ObligationCauseCode::Misc);
830self.add_wf_preds_for_pat_ty(base_ty, pat);
831 }
832833 ty::Tuple(tys) => {
834if let Some((last, rest)) = tys.split_last() {
835for &elem in rest {
836self.require_sized(elem, ObligationCauseCode::TupleElem);
837if elem.is_scalable_vector() && !self.span.is_dummy() {
838self.tcx()
839 .dcx()
840 .struct_span_err(
841self.span,
842"scalable vectors cannot be tuple fields",
843 )
844 .emit();
845 }
846 }
847848if last.is_scalable_vector() && !self.span.is_dummy() {
849self.tcx()
850 .dcx()
851 .struct_span_err(self.span, "scalable vectors cannot be tuple fields")
852 .emit();
853 }
854 }
855 }
856857 ty::RawPtr(_, _) => {
858// Simple cases that are WF if their type args are WF.
859}
860861 ty::Alias(
862_,
863 ty::AliasTy {
864 kind: ty::Projection { def_id } | ty::Opaque { def_id } | ty::Free { def_id },
865 args,
866 ..
867 },
868 ) => {
869self.nominal_obligations(def_id, args, |this, obligation| {
870this.out.push(obligation)
871 });
872 }
873 ty::Alias(_, data @ ty::AliasTy { kind: ty::Inherent { .. }, .. }) => {
874self.add_wf_preds_for_inherent_projection(data.into());
875return; // Subtree handled by compute_inherent_projection.
876}
877878 ty::Adt(def, args) => {
879// WfNominalType
880self.nominal_obligations(def.did(), args, |this, obligation| {
881this.out.push(obligation)
882 });
883 }
884885 ty::FnDef(did, args) => {
886let args = args.no_bound_vars().unwrap();
887// HACK: Check the return type of function definitions for
888 // well-formedness to mostly fix #84533. This is still not
889 // perfect and there may be ways to abuse the fact that we
890 // ignore requirements with escaping bound vars. That's a
891 // more general issue however.
892let fn_sig = tcx.fn_sig(did).instantiate(tcx, args).skip_norm_wip();
893fn_sig.output().skip_binder().visit_with(self);
894895self.nominal_obligations(did, args, |this, obligation| this.out.push(obligation));
896 }
897898 ty::Ref(r, rty, _) => {
899// WfReference
900if !r.has_escaping_bound_vars() && !rty.has_escaping_bound_vars() {
901let cause = self.cause(ObligationCauseCode::ReferenceOutlivesReferent(t));
902self.out.push(traits::Obligation::with_depth(
903tcx,
904cause,
905self.recursion_depth,
906self.param_env,
907 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(
908 ty::OutlivesClause(rty, r),
909 ))),
910 ));
911 }
912 }
913914 ty::Coroutine(did, args, ..) => {
915// Walk ALL the types in the coroutine: this will
916 // include the upvar types as well as the yield
917 // type. Note that this is mildly distinct from
918 // the closure case, where we have to be careful
919 // about the signature of the closure. We don't
920 // have the problem of implied bounds here since
921 // coroutines don't take arguments.
922self.nominal_obligations(did, args, |this, obligation| this.out.push(obligation));
923 }
924925 ty::Closure(did, args) => {
926// Note that we cannot skip the generic types
927 // types. Normally, within the fn
928 // body where they are created, the generics will
929 // always be WF, and outside of that fn body we
930 // are not directly inspecting closure types
931 // anyway, except via auto trait matching (which
932 // only inspects the upvar types).
933 // But when a closure is part of a type-alias-impl-trait
934 // then the function that created the defining site may
935 // have had more bounds available than the type alias
936 // specifies. This may cause us to have a closure in the
937 // hidden type that is not actually well formed and
938 // can cause compiler crashes when the user abuses unsafe
939 // code to procure such a closure.
940 // See tests/ui/type-alias-impl-trait/wf_check_closures.rs
941self.nominal_obligations(did, args, |this, obligation| this.out.push(obligation));
942// Only check the upvar types for WF, not the rest
943 // of the types within. This is needed because we
944 // capture the signature and it may not be WF
945 // without the implied bounds. Consider a closure
946 // like `|x: &'a T|` -- it may be that `T: 'a` is
947 // not known to hold in the creator's context (and
948 // indeed the closure may not be invoked by its
949 // creator, but rather turned to someone who *can*
950 // verify that).
951 //
952 // The special treatment of closures here really
953 // ought not to be necessary either; the problem
954 // is related to #25860 -- there is no way for us
955 // to express a fn type complete with the implied
956 // bounds that it is assuming. I think in reality
957 // the WF rules around fn are a bit messed up, and
958 // that is the rot problem: `fn(&'a T)` should
959 // probably always be WF, because it should be
960 // shorthand for something like `where(T: 'a) {
961 // fn(&'a T) }`, as discussed in #25860.
962let upvars = args.as_closure().tupled_upvars_ty();
963return upvars.visit_with(self);
964 }
965966 ty::CoroutineClosure(did, args) => {
967// See the above comments. The same apply to coroutine-closures.
968self.nominal_obligations(did, args, |this, obligation| this.out.push(obligation));
969let upvars = args.as_coroutine_closure().tupled_upvars_ty();
970return upvars.visit_with(self);
971 }
972973 ty::FnPtr(..) => {
974// Let the visitor iterate into the argument/return
975 // types appearing in the fn signature.
976}
977 ty::UnsafeBinder(ty) => {
978// FIXME(unsafe_binders): For now, we have no way to express
979 // that a type must be `ManuallyDrop` OR `Copy` (or a pointer).
980if !ty.has_escaping_bound_vars() {
981self.out.push(traits::Obligation::new(
982self.tcx(),
983self.cause(ObligationCauseCode::Misc),
984self.param_env,
985ty.map_bound(|ty| {
986 ty::TraitRef::new(
987self.tcx(),
988self.tcx().require_lang_item(
989 LangItem::BikeshedGuaranteedNoDrop,
990self.span,
991 ),
992 [ty],
993 )
994 }),
995 ));
996 }
997998// We recurse into the binder below.
999}
10001001 ty::Dynamic(data, r) => {
1002// WfObject
1003 //
1004 // Here, we defer WF checking due to higher-ranked
1005 // regions. This is perhaps not ideal.
1006self.add_wf_preds_for_dyn_ty(t, data, r);
10071008// FIXME(#27579) RFC also considers adding trait
1009 // obligations that don't refer to Self and
1010 // checking those
1011if let Some(principal) = data.principal() {
1012let principal_def_id = principal.skip_binder().def_id;
1013self.out.push(traits::Obligation::with_depth(
1014tcx,
1015self.cause(ObligationCauseCode::WellFormed(WellFormedLoc::None)),
1016self.recursion_depth,
1017self.param_env,
1018 ty::Binder::dummy(ty::PredicateKind::DynCompatible(principal_def_id)),
1019 ));
10201021// For the most part we don't add wf predicates corresponding to
1022 // the trait ref's generic arguments which allows code like this
1023 // to compile:
1024 // ```rust
1025 // trait Trait<T: Sized> {}
1026 // fn foo(_: &dyn Trait<[u32]>) {}
1027 // ```
1028 //
1029 // However, we sometimes incidentally check that const arguments
1030 // have the correct type as a side effect of the anon const
1031 // desugaring. To make this "consistent" for users we explicitly
1032 // check `ConstArgHasType` clauses so that const args that don't
1033 // go through an anon const still have their types checked.
1034 //
1035 // See also: https://rustc-dev-guide.rust-lang.org/const-generics.html
1036let args = principal.skip_binder().with_self_ty(self.tcx(), t).args;
1037self.nominal_obligations(principal_def_id, args, |this, obligation| {
1038let kind = obligation.predicate.kind().skip_binder();
1039let keep = match kind {
1040 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, _))
1041if #[allow(non_exhaustive_omitted_patterns)] match ct.kind() {
ty::ConstKind::Param(..) | ty::ConstKind::Placeholder(..) => true,
_ => false,
}matches!(
1042 ct.kind(),
1043 ty::ConstKind::Param(..) | ty::ConstKind::Placeholder(..)
1044 ) =>
1045 {
1046// ConstArgHasType clauses are not higher kinded. Assert as
1047 // such so we can fix this up if that ever changes.
1048if !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());
1049// In stable rust, variables from the trait object binder
1050 // cannot be referenced by a ConstArgHasType clause. However,
1051 // under `generic_const_parameter_types`, it can. Ignore those
1052 // predicates for now, to not have HKT-ConstArgHasTypes.
1053!kind.has_escaping_bound_vars()
1054 }
1055_ => false,
1056 };
1057if keep {
1058this.out.push(obligation);
1059 }
1060 });
1061 }
10621063if !t.has_escaping_bound_vars() {
1064for projection in data.projection_bounds() {
1065let projection = projection.with_self_ty(tcx, t);
1066let projection_pred = projection.skip_binder();
1067if #[allow(non_exhaustive_omitted_patterns)] match projection_pred.projection_term.kind
{
ty::AliasTermKind::ProjectionConst { .. } => true,
_ => false,
}matches!(
1068 projection_pred.projection_term.kind,
1069 ty::AliasTermKind::ProjectionConst { .. }
1070 ) {
1071self.require_const_item_ty(projection_pred.projection_term.expect_ct());
1072 }
10731074let pred_binder = projection
1075 .map_bound(|p| {
1076 p.term.as_const().map(|ct| {
1077let assoc_const_ty = tcx
1078 .type_of(p.def_id())
1079 .instantiate(tcx, p.projection_term.args)
1080 .skip_norm_wip();
1081 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(
1082 ct,
1083 assoc_const_ty,
1084 ))
1085 })
1086 })
1087 .transpose();
1088if let Some(pred_binder) = pred_binder {
1089self.out.push(traits::Obligation::with_depth(
1090 tcx,
1091self.cause(ObligationCauseCode::WellFormed(WellFormedLoc::None)),
1092self.recursion_depth,
1093self.param_env,
1094 pred_binder,
1095 ));
1096 }
1097 }
1098 }
1099 }
11001101// Inference variables are the complicated case, since we don't
1102 // know what type they are. We do two things:
1103 //
1104 // 1. Check if they have been resolved, and if so proceed with
1105 // THAT type.
1106 // 2. If not, we've at least simplified things (e.g., we went
1107 // from `Vec?0>: WF` to `?0: WF`), so we can
1108 // register a pending obligation and keep
1109 // moving. (Goal is that an "inductive hypothesis"
1110 // is satisfied to ensure termination.)
1111 // See also the comment on `fn obligations`, describing cycle
1112 // prevention, which happens before this can be reached.
1113ty::Infer(_) => {
1114let cause = self.cause(ObligationCauseCode::WellFormed(WellFormedLoc::None));
1115self.out.push(traits::Obligation::with_depth(
1116tcx,
1117cause,
1118self.recursion_depth,
1119self.param_env,
1120 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(
1121t.into(),
1122 ))),
1123 ));
1124 }
1125 }
11261127t.super_visit_with(self)
1128 }
11291130fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1131let tcx = self.tcx();
11321133match c.kind() {
1134 ty::ConstKind::Alias(_, alias_const) => {
1135if !c.has_escaping_bound_vars() {
1136// Skip type consts as mGCA doesn't support evaluatable clauses
1137if !alias_const.kind.is_direct_const(tcx) && !tcx.features().gca_const_items() {
1138let predicate = ty::Binder::dummy(ty::PredicateKind::Clause(
1139 ty::ClauseKind::ConstEvaluatable(c),
1140 ));
1141let cause =
1142self.cause(ObligationCauseCode::WellFormed(WellFormedLoc::None));
1143self.out.push(traits::Obligation::with_depth(
1144tcx,
1145cause,
1146self.recursion_depth,
1147self.param_env,
1148predicate,
1149 ));
1150 }
11511152match alias_const.kind {
1153 ty::AliasConstKind::InherentSelf { .. } => {
1154self.add_wf_preds_for_inherent_projection(alias_const.into());
1155return; // Subtree is handled by above function
1156}
1157// FIXME: This should be unreachable but isn't because we normalize in item
1158 // wfck before computing wf requirements
1159ty::AliasConstKind::InherentImpl { .. } => {
1160self.add_wf_preds_for_inherent_projection(alias_const.into());
1161return;
1162 }
1163 ty::AliasConstKind::Projection { def_id }
1164 | ty::AliasConstKind::Free { def_id }
1165 | ty::AliasConstKind::Anon { def_id } => {
1166self.nominal_obligations(
1167def_id,
1168alias_const.args,
1169 |this, obligation| this.out.push(obligation),
1170 );
1171 }
1172 }
1173 }
1174 }
1175 ty::ConstKind::Infer(_) => {
1176let cause = self.cause(ObligationCauseCode::WellFormed(WellFormedLoc::None));
11771178self.out.push(traits::Obligation::with_depth(
1179tcx,
1180cause,
1181self.recursion_depth,
1182self.param_env,
1183 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(
1184c.into(),
1185 ))),
1186 ));
1187 }
1188 ty::ConstKind::Expr(_) => {
1189// FIXME(generic_const_exprs): this doesn't verify that given `Expr(N + 1)` the
1190 // trait bound `typeof(N): Add<typeof(1)>` holds. This is currently unnecessary
1191 // as `ConstKind::Expr` is only produced via normalization of `ConstKind::Alias`
1192 // which means that the `DefId` would have been typeck'd elsewhere. However in
1193 // the future we may allow directly lowering to `ConstKind::Expr` in which case
1194 // we would not be proving bounds we should.
11951196let predicate = ty::Binder::dummy(ty::PredicateKind::Clause(
1197 ty::ClauseKind::ConstEvaluatable(c),
1198 ));
1199let cause = self.cause(ObligationCauseCode::WellFormed(WellFormedLoc::None));
1200self.out.push(traits::Obligation::with_depth(
1201tcx,
1202cause,
1203self.recursion_depth,
1204self.param_env,
1205predicate,
1206 ));
1207 }
12081209 ty::ConstKind::Error(_)
1210 | ty::ConstKind::Param(_)
1211 | ty::ConstKind::Bound(..)
1212 | ty::ConstKind::Placeholder(..) => {
1213// These variants are trivially WF, so nothing to do here.
1214}
1215 ty::ConstKind::Value(val) => {
1216// FIXME(mgca): no need to feature-gate once valtree lifetimes are not erased
1217if tcx.features().gca() {
1218match val.ty.kind() {
1219 ty::Adt(adt_def, args) => {
1220let adt_val = val.destructure_adt_const();
1221let variant_def = adt_def.variant(adt_val.variant);
1222let cause =
1223self.cause(ObligationCauseCode::WellFormed(WellFormedLoc::None));
1224self.out.extend(variant_def.fields.iter().zip(adt_val.fields).map(
1225 |(field_def, &field_val)| {
1226let field_ty = tcx1227 .type_of(field_def.did)
1228 .instantiate(tcx, args)
1229 .skip_norm_wip();
1230let predicate = ty::PredicateKind::Clause(
1231 ty::ClauseKind::ConstArgHasType(field_val, field_ty),
1232 );
1233 traits::Obligation::with_depth(
1234tcx,
1235cause.clone(),
1236self.recursion_depth,
1237self.param_env,
1238predicate,
1239 )
1240 },
1241 ));
1242 }
1243 ty::Tuple(field_tys) => {
1244let field_vals = val.to_branch();
1245let cause =
1246self.cause(ObligationCauseCode::WellFormed(WellFormedLoc::None));
1247self.out.extend(field_tys.iter().zip(field_vals).map(
1248 |(field_ty, &field_val)| {
1249let predicate = ty::PredicateKind::Clause(
1250 ty::ClauseKind::ConstArgHasType(field_val, field_ty),
1251 );
1252 traits::Obligation::with_depth(
1253tcx,
1254cause.clone(),
1255self.recursion_depth,
1256self.param_env,
1257predicate,
1258 )
1259 },
1260 ));
1261 }
1262 ty::Array(elem_ty, _len) => {
1263let elem_vals = val.to_branch();
1264let cause =
1265self.cause(ObligationCauseCode::WellFormed(WellFormedLoc::None));
12661267self.out.extend(elem_vals.iter().map(|&elem_val| {
1268let predicate = ty::PredicateKind::Clause(
1269 ty::ClauseKind::ConstArgHasType(elem_val, *elem_ty),
1270 );
1271 traits::Obligation::with_depth(
1272tcx,
1273cause.clone(),
1274self.recursion_depth,
1275self.param_env,
1276predicate,
1277 )
1278 }));
1279 }
1280_ => {}
1281 }
1282 }
12831284// FIXME: Enforce that values are structurally-matchable.
1285}
1286 }
12871288c.super_visit_with(self)
1289 }
12901291fn visit_predicate<P: PredicateProxy<TyCtxt<'tcx>>>(&mut self, _p: P) -> Self::Result {
1292::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");
1293 }
1294}
12951296/// Given an object type like `SomeTrait + Send`, computes the lifetime
1297/// bounds that must hold on the elided self type. These are derived
1298/// from the declarations of `SomeTrait`, `Send`, and friends -- if
1299/// they declare `trait SomeTrait : 'static`, for example, then
1300/// `'static` would appear in the list.
1301///
1302/// N.B., in some cases, particularly around higher-ranked bounds,
1303/// this function returns a kind of conservative approximation.
1304/// That is, all regions returned by this function are definitely
1305/// required, but there may be other region bounds that are not
1306/// returned, as well as requirements like `for<'a> T: 'a`.
1307///
1308/// Requires that trait definitions have been processed so that we can
1309/// elaborate predicates and walk supertraits.
1310pub fn object_region_bounds<'tcx>(
1311 tcx: TyCtxt<'tcx>,
1312 existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1313) -> Vec<ty::Region<'tcx>> {
1314let erased_self_ty = tcx.types.trait_object_dummy_self;
13151316let clauses =
1317existential_predicates.iter().map(|predicate| predicate.with_self_ty(tcx, erased_self_ty));
13181319 traits::elaborate(tcx, clauses)
1320 .filter_map(|clause| {
1321{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_trait_selection/src/traits/wf.rs:1321",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(1321u32),
::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);
1322match clause.kind().skip_binder() {
1323 ty::ClauseKind::TypeOutlives(ty::OutlivesClause(ref t, ref r)) => {
1324// Search for a bound of the form `erased_self_ty
1325 // : 'a`, but be wary of something like `for<'a>
1326 // erased_self_ty : 'a` (we interpret a
1327 // higher-ranked bound like that as 'static,
1328 // though at present the code in `fulfill.rs`
1329 // considers such bounds to be unsatisfiable, so
1330 // it's kind of a moot point since you could never
1331 // construct such an object, but this seems
1332 // correct even if that code changes).
1333if t == &erased_self_ty && !r.has_escaping_bound_vars() {
1334Some(*r)
1335 } else {
1336None1337 }
1338 }
1339 ty::ClauseKind::Trait(_)
1340 | ty::ClauseKind::HostEffect(..)
1341 | ty::ClauseKind::RegionOutlives(_)
1342 | ty::ClauseKind::Projection(_)
1343 | ty::ClauseKind::ConstArgHasType(_, _)
1344 | ty::ClauseKind::WellFormed(_)
1345 | ty::ClauseKind::UnstableFeature(_)
1346 | ty::ClauseKind::ConstEvaluatable(_) => None,
1347 }
1348 })
1349 .collect()
1350}