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