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::{ObligationCauseCode, PredicateObligation, PredicateObligations};
11use rustc_middle::ty::{
12self, DelayedSet, GenericArgsRef, PredicateProxy, Term, TermKind, Ty, TyCtxt,
13TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor,
14};
15use rustc_session::diagnostics::feature_err;
16use rustc_span::def_id::{DefId, LocalDefId};
17use rustc_span::{Span, bug, sym};
18use tracing::{debug, instrument};
1920use crate::infer::InferCtxt;
21use crate::traits;
2223/// Returns the set of obligations needed to make `term` well-formed.
24/// If `term` contains unresolved inference variables, this may include
25/// further WF obligations. However, if `term` IS an unresolved
26/// inference variable, returns `None`, because we are not able to
27/// make any progress at all. This is to prevent cycles where we
28/// say "?0 is WF if ?0 is WF".
29pub fn obligations<'tcx>(
30 infcx: &InferCtxt<'tcx>,
31 param_env: ty::ParamEnv<'tcx>,
32 body_def_id: LocalDefId,
33 recursion_depth: usize,
34 term: Term<'tcx>,
35 span: Span,
36) -> Option<PredicateObligations<'tcx>> {
37// Handle the "cycle" case (see comment above) by bailing out if necessary.
38let term = match term.kind() {
39TermKind::Ty(ty) => {
40match ty.kind() {
41 ty::Infer(ty::TyVar(_)) => {
42let resolved_ty = infcx.shallow_resolve(ty);
43if resolved_ty == ty {
44// No progress, bail out to prevent cycles.
45return None;
46 } else {
47resolved_ty48 }
49 }
50_ => ty,
51 }
52 .into()
53 }
54TermKind::Const(ct) => {
55match ct.kind() {
56 ty::ConstKind::Infer(_) => {
57let resolved = infcx.shallow_resolve_const(ct);
58if resolved == ct {
59// No progress, bail out to prevent cycles.
60return None;
61 } else {
62resolved63 }
64 }
65_ => ct,
66 }
67 .into()
68 }
69 };
7071let mut wf = WfPredicates {
72infcx,
73param_env,
74body_def_id,
75span,
76 out: PredicateObligations::new(),
77recursion_depth,
78 item: None,
79 visited_tys: Default::default(),
80 };
81wf.add_wf_preds_for_term(term);
82{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs:82",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(82u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__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);
8384let result = wf.normalize(infcx);
85{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs:85",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(85u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__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);
86Some(result)
87}
8889/// Compute the predicates that are required for a type to be well-formed.
90///
91/// This is only intended to be used in the new solver, since it does not
92/// take into account recursion depth or proper error-reporting spans.
93pub fn unnormalized_obligations<'tcx>(
94 infcx: &InferCtxt<'tcx>,
95 param_env: ty::ParamEnv<'tcx>,
96 term: Term<'tcx>,
97 span: Span,
98 body_def_id: LocalDefId,
99) -> Option<PredicateObligations<'tcx>> {
100if 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));
101102// However, if `term` IS an unresolved inference variable, returns `None`,
103 // because we are not able to make any progress at all. This is to prevent
104 // cycles where we say "?0 is WF if ?0 is WF".
105if term.is_infer() {
106return None;
107 }
108109let mut wf = WfPredicates {
110infcx,
111param_env,
112body_def_id,
113span,
114 out: PredicateObligations::new(),
115 recursion_depth: 0,
116 item: None,
117 visited_tys: Default::default(),
118 };
119wf.add_wf_preds_for_term(term);
120Some(wf.out)
121}
122123/// Returns the obligations that make this trait reference
124/// well-formed. For example, if there is a trait `Set` defined like
125/// `trait Set<K: Eq>`, then the trait bound `Foo: Set<Bar>` is WF
126/// if `Bar: Eq`.
127pub fn trait_obligations<'tcx>(
128 infcx: &InferCtxt<'tcx>,
129 param_env: ty::ParamEnv<'tcx>,
130 body_def_id: LocalDefId,
131 trait_pred: ty::TraitClause<'tcx>,
132 span: Span,
133 item: &'tcx hir::Item<'tcx>,
134) -> PredicateObligations<'tcx> {
135let mut wf = WfPredicates {
136infcx,
137param_env,
138body_def_id,
139span,
140 out: PredicateObligations::new(),
141 recursion_depth: 0,
142 item: Some(item),
143 visited_tys: Default::default(),
144 };
145wf.add_wf_preds_for_trait_pred(trait_pred, Elaborate::All);
146{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs:146",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(146u32),
::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);
147wf.normalize(infcx)
148}
149150/// Returns the requirements for `clause` to be well-formed.
151///
152/// For example, if there is a trait `Set` defined like
153/// `trait Set<K: Eq>`, then the trait bound `Foo: Set<Bar>` is WF
154/// if `Bar: Eq`.
155{}
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/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(155u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::wf"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("param_env")
}> =
::tracing::__macro_support::FieldName::new("param_env");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("body_def_id")
}> =
::tracing::__macro_support::FieldName::new("body_def_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("clause")
}> =
::tracing::__macro_support::FieldName::new("clause");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("span")
}> =
::tracing::__macro_support::FieldName::new("span");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(¶m_env)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&body_def_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&clause)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy
:: needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: PredicateObligations<'tcx> =
loop {};
return __tracing_attr_fake_return;
}
{
let mut wf =
WfPredicates {
infcx,
param_env,
body_def_id,
span,
out: PredicateObligations::new(),
recursion_depth: 0,
item: None,
visited_tys: Default::default(),
};
match clause.kind().skip_binder() {
ty::ClauseKind::Trait(t) => {
wf.add_wf_preds_for_trait_pred(t, Elaborate::None);
}
ty::ClauseKind::HostEffect(..) => {}
ty::ClauseKind::RegionOutlives(..) => {}
ty::ClauseKind::TypeOutlives(ty::OutlivesClause(ty, _reg))
=> {
wf.add_wf_preds_for_term(ty.into());
}
ty::ClauseKind::Projection(t) => {
wf.add_wf_preds_for_projection_term(t.projection_term);
wf.add_wf_preds_for_term(t.term);
}
ty::ClauseKind::ConstArgHasType(ct, ty) => {
wf.add_wf_preds_for_term(ct.into());
wf.add_wf_preds_for_term(ty.into());
}
ty::ClauseKind::WellFormed(term) => {
wf.add_wf_preds_for_term(term);
}
ty::ClauseKind::ConstEvaluatable(ct) => {
wf.add_wf_preds_for_term(ct.into());
}
ty::ClauseKind::UnstableFeature(_) => {}
}
wf.normalize(infcx)
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs:155",
"rustc_trait_selection::traits::wf", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(155u32),
::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)]156pub fn clause_obligations<'tcx>(
157 infcx: &InferCtxt<'tcx>,
158 param_env: ty::ParamEnv<'tcx>,
159 body_def_id: LocalDefId,
160 clause: ty::Clause<'tcx>,
161 span: Span,
162) -> PredicateObligations<'tcx> {
163let mut wf = WfPredicates {
164 infcx,
165 param_env,
166 body_def_id,
167 span,
168 out: PredicateObligations::new(),
169 recursion_depth: 0,
170 item: None,
171 visited_tys: Default::default(),
172 };
173174// It's ok to skip the binder here because wf code is prepared for it
175match clause.kind().skip_binder() {
176 ty::ClauseKind::Trait(t) => {
177 wf.add_wf_preds_for_trait_pred(t, Elaborate::None);
178 }
179 ty::ClauseKind::HostEffect(..) => {
180// Technically the well-formedness of this clause is implied by
181 // the corresponding trait clause it should've been generated beside.
182}
183 ty::ClauseKind::RegionOutlives(..) => {}
184 ty::ClauseKind::TypeOutlives(ty::OutlivesClause(ty, _reg)) => {
185 wf.add_wf_preds_for_term(ty.into());
186 }
187 ty::ClauseKind::Projection(t) => {
188 wf.add_wf_preds_for_projection_term(t.projection_term);
189 wf.add_wf_preds_for_term(t.term);
190 }
191 ty::ClauseKind::ConstArgHasType(ct, ty) => {
192 wf.add_wf_preds_for_term(ct.into());
193 wf.add_wf_preds_for_term(ty.into());
194 }
195 ty::ClauseKind::WellFormed(term) => {
196 wf.add_wf_preds_for_term(term);
197 }
198199 ty::ClauseKind::ConstEvaluatable(ct) => {
200 wf.add_wf_preds_for_term(ct.into());
201 }
202 ty::ClauseKind::UnstableFeature(_) => {}
203 }
204205 wf.normalize(infcx)
206}
207208struct WfPredicates<'a, 'tcx> {
209 infcx: &'a InferCtxt<'tcx>,
210 param_env: ty::ParamEnv<'tcx>,
211 body_def_id: LocalDefId,
212 span: Span,
213 out: PredicateObligations<'tcx>,
214 recursion_depth: usize,
215 item: Option<&'tcx hir::Item<'tcx>>,
216 visited_tys: DelayedSet<Ty<'tcx>>,
217}
218219/// Controls whether we "elaborate" supertraits and so forth on the WF
220/// predicates. This is a kind of hack to address #43784. The
221/// underlying problem in that issue was a trait structure like:
222///
223/// ```ignore (illustrative)
224/// trait Foo: Copy { }
225/// trait Bar: Foo { }
226/// impl<T: Bar> Foo for T { }
227/// impl<T> Bar for T { }
228/// ```
229///
230/// Here, in the `Foo` impl, we will check that `T: Copy` holds -- but
231/// we decide that this is true because `T: Bar` is in the
232/// where-clauses (and we can elaborate that to include `T:
233/// Copy`). This wouldn't be a problem, except that when we check the
234/// `Bar` impl, we decide that `T: Foo` must hold because of the `Foo`
235/// impl. And so nowhere did we check that `T: Copy` holds!
236///
237/// To resolve this, we elaborate the WF requirements that must be
238/// proven when checking impls. This means that (e.g.) the `impl Bar
239/// for T` will be forced to prove not only that `T: Foo` but also `T:
240/// Copy` (which it won't be able to do, because there is no `Copy`
241/// impl for `T`).
242#[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)]
243enum Elaborate {
244 All,
245None,
246}
247248/// Points the cause span of a super predicate at the relevant associated type.
249///
250/// Given a trait impl item:
251///
252/// ```ignore (incomplete)
253/// impl TargetTrait for TargetType {
254/// type Assoc = SomeType;
255/// }
256/// ```
257///
258/// And a super predicate of `TargetTrait` that has any of the following forms:
259///
260/// 1. `<OtherType as OtherTrait>::Assoc == <TargetType as TargetTrait>::Assoc`
261/// 2. `<<TargetType as TargetTrait>::Assoc as OtherTrait>::Assoc == OtherType`
262/// 3. `<TargetType as TargetTrait>::Assoc: OtherTrait`
263///
264/// Replace the span of the cause with the span of the associated item:
265///
266/// ```ignore (incomplete)
267/// impl TargetTrait for TargetType {
268/// type Assoc = SomeType;
269/// // ^^^^^^^^ this span
270/// }
271/// ```
272///
273/// Note that bounds that can be expressed as associated item bounds are **not**
274/// super predicates. This means that form 2 and 3 from above are only relevant if
275/// the [`GenericArgsRef`] of the projection type are not its identity arguments.
276fn extend_cause_with_original_assoc_item_obligation<'tcx>(
277 tcx: TyCtxt<'tcx>,
278 item: Option<&hir::Item<'tcx>>,
279 cause: &mut traits::ObligationCause<'tcx>,
280 pred: ty::Predicate<'tcx>,
281) {
282{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs:282",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(282u32),
::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");
283let (items, impl_def_id) = match item {
284Some(hir::Item { kind: hir::ItemKind::Impl(impl_), owner_id, .. }) => {
285 (impl_.items, *owner_id)
286 }
287_ => return,
288 };
289290let ty_to_impl_span = |ty: Ty<'_>| {
291if let ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, .. }) = ty.kind()
292 && let Some(&impl_item_id) = tcx.impl_item_implementor_ids(impl_def_id).get(def_id)
293 && let Some(impl_item) =
294items.iter().find(|item| item.owner_id.to_def_id() == impl_item_id)
295 {
296Some(tcx.hir_impl_item(*impl_item).expect_type().span)
297 } else {
298None299 }
300 };
301302// It is fine to skip the binder as we don't care about regions here.
303match pred.kind().skip_binder() {
304 ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)) => {
305// Form 1: The obligation comes not from the current `impl` nor the `trait` being
306 // implemented, but rather from a "second order" obligation, where an associated
307 // type has a projection coming from another associated type.
308 // See `tests/ui/traits/assoc-type-in-superbad.rs` for an example.
309if let Some(term_ty) = proj.term.as_type()
310 && let Some(impl_item_span) = ty_to_impl_span(term_ty)
311 {
312cause.span = impl_item_span;
313 }
314315// Form 2: A projection obligation for an associated item failed to be met.
316 // We overwrite the span from above to ensure that a bound like
317 // `Self::Assoc1: Trait<OtherAssoc = Self::Assoc2>` gets the same
318 // span for both obligations that it is lowered to.
319if let Some(impl_item_span) = ty_to_impl_span(proj.self_ty()) {
320cause.span = impl_item_span;
321 }
322 }
323324 ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => {
325// Form 3: A trait obligation for an associated item failed to be met.
326{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs:326",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(326u32),
::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);
327if let Some(impl_item_span) = ty_to_impl_span(pred.self_ty()) {
328cause.span = impl_item_span;
329 }
330 }
331_ => {}
332 }
333}
334335impl<'a, 'tcx> WfPredicates<'a, 'tcx> {
336fn tcx(&self) -> TyCtxt<'tcx> {
337self.infcx.tcx
338 }
339340fn cause(&self, code: traits::ObligationCauseCode<'tcx>) -> traits::ObligationCause<'tcx> {
341 traits::ObligationCause::new(self.span, self.body_def_id, code)
342 }
343344fn normalize(self, infcx: &InferCtxt<'tcx>) -> PredicateObligations<'tcx> {
345// Do not normalize `wf` obligations with the new solver.
346 //
347 // The current deep normalization routine with the new solver does not
348 // handle ambiguity and the new solver correctly deals with unnnormalized goals.
349 // If the user relies on normalized types, e.g. for `fn implied_outlives_bounds`,
350 // it is their responsibility to normalize while avoiding ambiguity.
351if infcx.next_trait_solver() {
352return self.out;
353 }
354355let cause = self.cause(ObligationCauseCode::WellFormed(None));
356let param_env = self.param_env;
357let mut obligations = PredicateObligations::with_capacity(self.out.len());
358for mut obligation in self.out {
359if !!obligation.has_escaping_bound_vars() {
::core::panicking::panic("assertion failed: !obligation.has_escaping_bound_vars()")
};assert!(!obligation.has_escaping_bound_vars());
360let mut selcx = traits::SelectionContext::new(infcx);
361// Don't normalize the whole obligation, the param env is either
362 // already normalized, or we're currently normalizing the
363 // param_env. Either way we should only normalize the predicate.
364let normalized_predicate = traits::normalize::normalize_with_depth_to(
365&mut selcx,
366 param_env,
367 cause.clone(),
368self.recursion_depth,
369 ty::Unnormalized::new_wip(obligation.predicate),
370&mut obligations,
371 );
372 obligation.predicate = normalized_predicate;
373 obligations.push(obligation);
374 }
375obligations376 }
377378/// Pushes the obligations required for `trait_ref` to be WF into `self.out`.
379fn add_wf_preds_for_trait_pred(
380&mut self,
381 trait_pred: ty::TraitClause<'tcx>,
382 elaborate: Elaborate,
383 ) {
384let tcx = self.tcx();
385let trait_ref = trait_pred.trait_ref;
386387// Negative trait predicates don't require supertraits to hold, just
388 // that their args are WF.
389if trait_pred.polarity == ty::ClausePolarity::Negative {
390self.add_wf_preds_for_negative_trait_pred(trait_ref);
391return;
392 }
393394let param_env = self.param_env;
395let depth = self.recursion_depth;
396397let item = self.item;
398399let extend = |traits::PredicateObligation { predicate, mut cause, .. }| {
400if let Some(parent_trait_pred) = predicate.as_trait_clause() {
401cause = cause.derived_cause(
402parent_trait_pred,
403 traits::ObligationCauseCode::WellFormedDerived,
404 );
405 }
406extend_cause_with_original_assoc_item_obligation(tcx, item, &mut cause, predicate);
407 traits::Obligation::with_depth(tcx, cause, depth, param_env, predicate)
408 };
409410// if the trait predicate is not const, the wf obligations should not be const as well.
411if let Elaborate::All = elaborate {
412let mut obligations = PredicateObligations::new();
413self.nominal_obligations(trait_ref.def_id, trait_ref.args, |_, obligation| {
414obligations.push(obligation)
415 });
416{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs:416",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(416u32),
::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);
417let implied_obligations = traits::util::elaborate(tcx, obligations);
418let implied_obligations = implied_obligations.map(extend);
419self.out.extend(implied_obligations);
420 } else {
421self.nominal_obligations(trait_ref.def_id, trait_ref.args, |this, obligation| {
422this.out.push(obligation)
423 });
424 }
425426self.out.extend(
427trait_ref428 .args
429 .iter()
430 .enumerate()
431 .filter_map(|(i, arg)| arg.as_term().map(|t| (i, t)))
432 .filter(|(_, term)| !term.has_escaping_bound_vars())
433 .map(|(i, term)| {
434let mut cause = traits::ObligationCause::misc(self.span, self.body_def_id);
435// The first arg is the self ty - use the correct span for it.
436if i == 0 {
437if let Some(hir::ItemKind::Impl(hir::Impl { self_ty, .. })) =
438item.map(|i| &i.kind)
439 {
440cause.span = self_ty.span;
441 }
442 }
443 traits::Obligation::with_depth(
444tcx,
445cause,
446depth,
447param_env,
448 ty::ClauseKind::WellFormed(term),
449 )
450 }),
451 );
452 }
453454// Compute the obligations that are required for `trait_ref` to be WF,
455 // given that it is a *negative* trait predicate.
456fn add_wf_preds_for_negative_trait_pred(&mut self, trait_ref: ty::TraitRef<'tcx>) {
457for arg in trait_ref.args {
458if let Some(term) = arg.as_term() {
459self.add_wf_preds_for_term(term);
460 }
461 }
462 }
463464/// Pushes the obligations required for a projection to be WF into `self.out`.
465fn add_wf_preds_for_projection_term(&mut self, data: ty::AliasTerm<'tcx>) {
466// A projection is well-formed if
467 //
468 // (a) its predicates hold (*)
469 // (b) its args are wf
470 //
471 // (*) The predicates of an associated type include the predicates of
472 // the trait that it's contained in. For example, given
473 //
474 // trait A<T>: Clone {
475 // type X where T: Copy;
476 // }
477 //
478 // The predicates of `<() as A<i32>>::X` are:
479 // [
480 // `(): Sized`
481 // `(): Clone`
482 // `(): A<i32>`
483 // `i32: Sized`
484 // `i32: Clone`
485 // `i32: Copy`
486 // ]
487self.nominal_obligations(data.expect_projection_def_id(), data.args, |this, obligation| {
488this.out.push(obligation)
489 });
490491self.add_wf_preds_for_projection_args(data.args);
492 }
493494/// Pushes the obligations required for an inherent alias to be WF
495 /// into `self.out`.
496// FIXME(inherent_associated_types): Merge this function with `fn compute_alias`.
497fn add_wf_preds_for_inherent_projection(&mut self, data: ty::AliasTerm<'tcx>) {
498// An inherent projection is well-formed if
499 //
500 // (a) its predicates hold (*)
501 // (b) its args are wf
502 //
503 // (*) The predicates of an inherent associated type include the
504 // predicates of the impl that it's contained in.
505506 // In an ideal world, there are no escaping bound vars here. However, WF is jank, and
507 // sometimes there are. We can only `compute_inherent_assoc_term_args` if the Self ty in the
508 // args has no escaping bound vars. If we already have impl format args, though,
509 // `compute_inherent_assoc_term_args` is a no-op (and we have no Self type), so no need to
510 // check for escaping bound vars.
511let can_compute_impl_args =
512#[allow(non_exhaustive_omitted_patterns)] match data.kind {
ty::AliasTermKind::InherentConstImpl { .. } => true,
_ => false,
}matches!(data.kind, ty::AliasTermKind::InherentConstImpl { .. })513 || !data.self_ty().has_escaping_bound_vars();
514515if can_compute_impl_args {
516// FIXME(inherent_associated_types): Should this happen inside of a snapshot?
517 // FIXME(inherent_associated_types): This is incompatible with the new solver and lazy norm!
518let args = traits::project::compute_inherent_assoc_term_args(
519&mut traits::SelectionContext::new(self.infcx),
520self.param_env,
521data,
522self.cause(ObligationCauseCode::WellFormed(None)),
523self.recursion_depth,
524&mut self.out,
525 );
526let def_id = data.expect_inherent_def_id();
527self.nominal_obligations(def_id, args, |this, obligation| this.out.push(obligation));
528 }
529530data.args.visit_with(self);
531 }
532533fn add_wf_preds_for_projection_args(&mut self, args: GenericArgsRef<'tcx>) {
534let tcx = self.tcx();
535let cause = self.cause(ObligationCauseCode::WellFormed(None));
536let param_env = self.param_env;
537let depth = self.recursion_depth;
538539self.out.extend(
540args.iter()
541 .filter_map(|arg| arg.as_term())
542 .filter(|term| !term.has_escaping_bound_vars())
543 .map(|term| {
544 traits::Obligation::with_depth(
545tcx,
546cause.clone(),
547depth,
548param_env,
549 ty::ClauseKind::WellFormed(term),
550 )
551 }),
552 );
553 }
554555fn require_sized(&mut self, subty: Ty<'tcx>, cause: traits::ObligationCauseCode<'tcx>) {
556if !subty.has_escaping_bound_vars() {
557let cause = self.cause(cause);
558let trait_ref = ty::TraitRef::new(
559self.tcx(),
560self.tcx().require_lang_item(LangItem::Sized, cause.span),
561 [subty],
562 );
563self.out.push(traits::Obligation::with_depth(
564self.tcx(),
565cause,
566self.recursion_depth,
567self.param_env,
568 ty::Binder::dummy(trait_ref),
569 ));
570 }
571 }
572573/// Pushes all the predicates needed to validate that `term` is WF into `out`.
574{}
#[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/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(574u32),
::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/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs:577",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(577u32),
::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))]575fn add_wf_preds_for_term(&mut self, term: Term<'tcx>) {
576 term.visit_with(self);
577debug!(?self.out);
578 }
579580{}
#[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/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(580u32),
::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))]581fn nominal_obligations(
582&mut self,
583 def_id: DefId,
584 args: GenericArgsRef<'tcx>,
585mut push_obligation: impl FnMut(&mut Self, PredicateObligation<'tcx>),
586 ) {
587// PERF: `Sized`'s predicates include `MetaSized`, but both are compiler implemented marker
588 // traits, so `MetaSized` will always be WF if `Sized` is WF and vice-versa. Determining
589 // the nominal obligations of `Sized` would in-effect just elaborate `MetaSized` and make
590 // the compiler do a bunch of work needlessly.
591if self.tcx().is_lang_item(def_id, LangItem::Sized) {
592return;
593 }
594if self.tcx().is_lang_item(def_id, LangItem::ConstParamTy)
595 && self.tcx().features().const_param_ty_unchecked()
596 {
597return;
598 }
599600let tcx = self.tcx();
601let mut head = (def_id, tcx.clauses_of(def_id));
602let mut inner_levels = Vec::new(); // only allocates if a parent chain exists
603while let Some(parent) = head.1.parent {
604 inner_levels.push(head);
605 head = (parent, tcx.clauses_of(parent));
606 }
607608// Emit outermost first, as diagnostics rely on that order.
609for &(origin_def_id, clauses) in iter::once(&head).chain(inner_levels.iter().rev()) {
610for (clause, span) in clauses.instantiate_own(tcx, args) {
611if !clause.has_escaping_bound_vars() {
612let code = ObligationCauseCode::WhereClause(origin_def_id, span);
613let cause = self.cause(code);
614let obligation = traits::Obligation::with_depth(
615 tcx,
616 cause,
617self.recursion_depth,
618self.param_env,
619 clause.skip_norm_wip(),
620 );
621 push_obligation(self, obligation);
622 }
623 }
624 }
625 }
626627fn add_wf_preds_for_dyn_ty(
628&mut self,
629 ty: Ty<'tcx>,
630 data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
631 region: ty::Region<'tcx>,
632 ) {
633// Imagine a type like this:
634 //
635 // trait Foo { }
636 // trait Bar<'c> : 'c { }
637 //
638 // &'b (Foo+'c+Bar<'d>)
639 // ^
640 //
641 // In this case, the following relationships must hold:
642 //
643 // 'b <= 'c
644 // 'd <= 'c
645 //
646 // The first conditions is due to the normal region pointer
647 // rules, which say that a reference cannot outlive its
648 // referent.
649 //
650 // The final condition may be a bit surprising. In particular,
651 // you may expect that it would have been `'c <= 'd`, since
652 // usually lifetimes of outer things are conservative
653 // approximations for inner things. However, it works somewhat
654 // differently with trait objects: here the idea is that if the
655 // user specifies a region bound (`'c`, in this case) it is the
656 // "master bound" that *implies* that bounds from other traits are
657 // all met. (Remember that *all bounds* in a type like
658 // `Foo+Bar+Zed` must be met, not just one, hence if we write
659 // `Foo<'x>+Bar<'y>`, we know that the type outlives *both* 'x and
660 // 'y.)
661 //
662 // Note: in fact we only permit builtin traits, not `Bar<'d>`, I
663 // am looking forward to the future here.
664if !data.has_escaping_bound_vars() && !region.has_escaping_bound_vars() {
665let implicit_bounds = object_region_bounds(self.tcx(), data);
666667let explicit_bound = region;
668669self.out.reserve(implicit_bounds.len());
670for implicit_bound in implicit_bounds {
671let cause = self.cause(ObligationCauseCode::ObjectTypeBound(ty, explicit_bound));
672let outlives =
673 ty::Binder::dummy(ty::OutlivesClause(explicit_bound, implicit_bound));
674self.out.push(traits::Obligation::with_depth(
675self.tcx(),
676 cause,
677self.recursion_depth,
678self.param_env,
679 outlives,
680 ));
681 }
682683// We don't add any wf predicates corresponding to the trait ref's generic arguments
684 // which allows code like this to compile:
685 // ```rust
686 // trait Trait<T: Sized> {}
687 // fn foo(_: &dyn Trait<[u32]>) {}
688 // ```
689}
690 }
691692fn add_wf_preds_for_pat_ty(&mut self, base_ty: Ty<'tcx>, pat: ty::Pattern<'tcx>) {
693let tcx = self.tcx();
694match *pat {
695 ty::PatternKind::Range { start, end } => {
696let mut check = |c| {
697let cause = self.cause(ObligationCauseCode::Misc);
698self.out.push(traits::Obligation::with_depth(
699tcx,
700cause.clone(),
701self.recursion_depth,
702self.param_env,
703 ty::Binder::dummy(ty::PredicateKind::Clause(
704 ty::ClauseKind::ConstArgHasType(c, base_ty),
705 )),
706 ));
707if !tcx.features().generic_pattern_types() {
708if c.has_param() {
709if self.span.is_dummy() {
710self.tcx()
711 .dcx()
712 .delayed_bug("feature error should be reported elsewhere, too");
713 } else {
714feature_err(
715&self.tcx().sess,
716 sym::generic_pattern_types,
717self.span,
718"wraparound pattern type ranges cause monomorphization time errors",
719 )
720 .emit();
721 }
722 }
723 }
724 };
725check(start);
726check(end);
727 }
728 ty::PatternKind::NotNull => {}
729 ty::PatternKind::Or(patterns) => {
730for pat in patterns {
731self.add_wf_preds_for_pat_ty(base_ty, pat)
732 }
733 }
734 }
735 }
736}
737738impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for WfPredicates<'a, 'tcx> {
739fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
740{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs:740",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(740u32),
::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());
741742if !self.visited_tys.insert(t) {
743return;
744 }
745746let tcx = self.tcx();
747748match *t.kind() {
749 ty::Bool750 | ty::Char751 | ty::Int(..)
752 | ty::Uint(..)
753 | ty::Float(..)
754 | ty::Error(_)
755 | ty::Str756 | ty::CoroutineWitness(..)
757 | ty::Never758 | ty::Param(_)
759 | ty::Bound(..)
760 | ty::Placeholder(..)
761 | ty::Foreign(..) => {
762// WfScalar, WfParameter, etc
763}
764765// Can only infer to `ty::Int(_) | ty::Uint(_)`.
766ty::Infer(ty::IntVar(_)) => {}
767768// Can only infer to `ty::Float(_)`.
769ty::Infer(ty::FloatVar(_)) => {}
770771 ty::Slice(subty) => {
772self.require_sized(subty, ObligationCauseCode::SliceOrArrayElem);
773 }
774775 ty::Array(subty, len) => {
776self.require_sized(subty, ObligationCauseCode::SliceOrArrayElem);
777// Note that the len being WF is implicitly checked while visiting.
778 // Here we just check that it's of type usize.
779let cause = self.cause(ObligationCauseCode::ArrayLen(t));
780self.out.push(traits::Obligation::with_depth(
781tcx,
782cause,
783self.recursion_depth,
784self.param_env,
785 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(
786len,
787tcx.types.usize,
788 ))),
789 ));
790 }
791792 ty::Pat(base_ty, pat) => {
793self.require_sized(base_ty, ObligationCauseCode::Misc);
794self.add_wf_preds_for_pat_ty(base_ty, pat);
795 }
796797 ty::Tuple(tys) => {
798if let Some((last, rest)) = tys.split_last() {
799for &elem in rest {
800self.require_sized(elem, ObligationCauseCode::TupleElem);
801if elem.is_scalable_vector() && !self.span.is_dummy() {
802self.tcx()
803 .dcx()
804 .struct_span_err(
805self.span,
806"scalable vectors cannot be tuple fields",
807 )
808 .emit();
809 }
810 }
811812if last.is_scalable_vector() && !self.span.is_dummy() {
813self.tcx()
814 .dcx()
815 .struct_span_err(self.span, "scalable vectors cannot be tuple fields")
816 .emit();
817 }
818 }
819 }
820821 ty::RawPtr(_, _) => {
822// Simple cases that are WF if their type args are WF.
823}
824825 ty::Alias(
826_,
827 ty::AliasTy {
828 kind: ty::Projection { def_id } | ty::Opaque { def_id } | ty::Free { def_id },
829 args,
830 ..
831 },
832 ) => {
833self.nominal_obligations(def_id, args, |this, obligation| {
834this.out.push(obligation)
835 });
836 }
837 ty::Alias(_, data @ ty::AliasTy { kind: ty::Inherent { .. }, .. }) => {
838self.add_wf_preds_for_inherent_projection(data.into());
839return; // Subtree handled by compute_inherent_projection.
840}
841842 ty::Adt(def, args) => {
843// WfNominalType
844self.nominal_obligations(def.did(), args, |this, obligation| {
845this.out.push(obligation)
846 });
847 }
848849 ty::FnDef(did, args) => {
850let args = args.no_bound_vars().unwrap();
851// HACK: Check the return type of function definitions for
852 // well-formedness to mostly fix #84533. This is still not
853 // perfect and there may be ways to abuse the fact that we
854 // ignore requirements with escaping bound vars. That's a
855 // more general issue however.
856let fn_sig = tcx.fn_sig(did).instantiate(tcx, args).skip_norm_wip();
857fn_sig.output().skip_binder().visit_with(self);
858859self.nominal_obligations(did, args, |this, obligation| this.out.push(obligation));
860 }
861862 ty::Ref(r, rty, _) => {
863// WfReference
864if !r.has_escaping_bound_vars() && !rty.has_escaping_bound_vars() {
865let cause = self.cause(ObligationCauseCode::ReferenceOutlivesReferent(t));
866self.out.push(traits::Obligation::with_depth(
867tcx,
868cause,
869self.recursion_depth,
870self.param_env,
871 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(
872 ty::OutlivesClause(rty, r),
873 ))),
874 ));
875 }
876 }
877878 ty::Coroutine(did, args, ..) => {
879// Walk ALL the types in the coroutine: this will
880 // include the upvar types as well as the yield
881 // type. Note that this is mildly distinct from
882 // the closure case, where we have to be careful
883 // about the signature of the closure. We don't
884 // have the problem of implied bounds here since
885 // coroutines don't take arguments.
886self.nominal_obligations(did, args, |this, obligation| this.out.push(obligation));
887 }
888889 ty::Closure(did, args) => {
890// Note that we cannot skip the generic types
891 // types. Normally, within the fn
892 // body where they are created, the generics will
893 // always be WF, and outside of that fn body we
894 // are not directly inspecting closure types
895 // anyway, except via auto trait matching (which
896 // only inspects the upvar types).
897 // But when a closure is part of a type-alias-impl-trait
898 // then the function that created the defining site may
899 // have had more bounds available than the type alias
900 // specifies. This may cause us to have a closure in the
901 // hidden type that is not actually well formed and
902 // can cause compiler crashes when the user abuses unsafe
903 // code to procure such a closure.
904 // See tests/ui/type-alias-impl-trait/wf_check_closures.rs
905self.nominal_obligations(did, args, |this, obligation| this.out.push(obligation));
906// Only check the upvar types for WF, not the rest
907 // of the types within. This is needed because we
908 // capture the signature and it may not be WF
909 // without the implied bounds. Consider a closure
910 // like `|x: &'a T|` -- it may be that `T: 'a` is
911 // not known to hold in the creator's context (and
912 // indeed the closure may not be invoked by its
913 // creator, but rather turned to someone who *can*
914 // verify that).
915 //
916 // The special treatment of closures here really
917 // ought not to be necessary either; the problem
918 // is related to #25860 -- there is no way for us
919 // to express a fn type complete with the implied
920 // bounds that it is assuming. I think in reality
921 // the WF rules around fn are a bit messed up, and
922 // that is the rot problem: `fn(&'a T)` should
923 // probably always be WF, because it should be
924 // shorthand for something like `where(T: 'a) {
925 // fn(&'a T) }`, as discussed in #25860.
926let upvars = args.as_closure().tupled_upvars_ty();
927return upvars.visit_with(self);
928 }
929930 ty::CoroutineClosure(did, args) => {
931// See the above comments. The same apply to coroutine-closures.
932self.nominal_obligations(did, args, |this, obligation| this.out.push(obligation));
933let upvars = args.as_coroutine_closure().tupled_upvars_ty();
934return upvars.visit_with(self);
935 }
936937 ty::FnPtr(..) => {
938// Let the visitor iterate into the argument/return
939 // types appearing in the fn signature.
940}
941 ty::UnsafeBinder(ty) => {
942// FIXME(unsafe_binders): For now, we have no way to express
943 // that a type must be `ManuallyDrop` OR `Copy` (or a pointer).
944if !ty.has_escaping_bound_vars() {
945self.out.push(traits::Obligation::new(
946self.tcx(),
947self.cause(ObligationCauseCode::Misc),
948self.param_env,
949ty.map_bound(|ty| {
950 ty::TraitRef::new(
951self.tcx(),
952self.tcx().require_lang_item(
953 LangItem::BikeshedGuaranteedNoDrop,
954self.span,
955 ),
956 [ty],
957 )
958 }),
959 ));
960 }
961962// We recurse into the binder below.
963}
964965 ty::Dynamic(data, r) => {
966// WfObject
967 //
968 // Here, we defer WF checking due to higher-ranked
969 // regions. This is perhaps not ideal.
970self.add_wf_preds_for_dyn_ty(t, data, r);
971972// FIXME(#27579) RFC also considers adding trait
973 // obligations that don't refer to Self and
974 // checking those
975if let Some(principal) = data.principal() {
976let principal_def_id = principal.skip_binder().def_id;
977self.out.push(traits::Obligation::with_depth(
978tcx,
979self.cause(ObligationCauseCode::WellFormed(None)),
980self.recursion_depth,
981self.param_env,
982 ty::Binder::dummy(ty::PredicateKind::DynCompatible(principal_def_id)),
983 ));
984985// For the most part we don't add wf predicates corresponding to
986 // the trait ref's generic arguments which allows code like this
987 // to compile:
988 // ```rust
989 // trait Trait<T: Sized> {}
990 // fn foo(_: &dyn Trait<[u32]>) {}
991 // ```
992 //
993 // However, we sometimes incidentally check that const arguments
994 // have the correct type as a side effect of the anon const
995 // desugaring. To make this "consistent" for users we explicitly
996 // check `ConstArgHasType` clauses so that const args that don't
997 // go through an anon const still have their types checked.
998 //
999 // See also: https://rustc-dev-guide.rust-lang.org/const-generics.html
1000let args = principal.skip_binder().with_self_ty(self.tcx(), t).args;
1001self.nominal_obligations(principal_def_id, args, |this, obligation| {
1002let kind = obligation.predicate.kind().skip_binder();
1003let keep = match kind {
1004 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, _))
1005if #[allow(non_exhaustive_omitted_patterns)] match ct.kind() {
ty::ConstKind::Param(..) | ty::ConstKind::Placeholder(..) => true,
_ => false,
}matches!(
1006 ct.kind(),
1007 ty::ConstKind::Param(..) | ty::ConstKind::Placeholder(..)
1008 ) =>
1009 {
1010// ConstArgHasType clauses are not higher kinded. Assert as
1011 // such so we can fix this up if that ever changes.
1012if !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());
1013// In stable rust, variables from the trait object binder
1014 // cannot be referenced by a ConstArgHasType clause. However,
1015 // under `generic_const_parameter_types`, it can. Ignore those
1016 // predicates for now, to not have HKT-ConstArgHasTypes.
1017!kind.has_escaping_bound_vars()
1018 }
1019_ => false,
1020 };
1021if keep {
1022this.out.push(obligation);
1023 }
1024 });
1025 }
10261027if !t.has_escaping_bound_vars() {
1028for projection in data.projection_bounds() {
1029let pred_binder = projection
1030 .with_self_ty(tcx, t)
1031 .map_bound(|p| {
1032 p.term.as_const().map(|ct| {
1033let assoc_const_ty = tcx
1034 .type_of(p.def_id())
1035 .instantiate(tcx, p.projection_term.args)
1036 .skip_norm_wip();
1037 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(
1038 ct,
1039 assoc_const_ty,
1040 ))
1041 })
1042 })
1043 .transpose();
1044if let Some(pred_binder) = pred_binder {
1045self.out.push(traits::Obligation::with_depth(
1046 tcx,
1047self.cause(ObligationCauseCode::WellFormed(None)),
1048self.recursion_depth,
1049self.param_env,
1050 pred_binder,
1051 ));
1052 }
1053 }
1054 }
1055 }
10561057// Inference variables are the complicated case, since we don't
1058 // know what type they are. We do two things:
1059 //
1060 // 1. Check if they have been resolved, and if so proceed with
1061 // THAT type.
1062 // 2. If not, we've at least simplified things (e.g., we went
1063 // from `Vec?0>: WF` to `?0: WF`), so we can
1064 // register a pending obligation and keep
1065 // moving. (Goal is that an "inductive hypothesis"
1066 // is satisfied to ensure termination.)
1067 // See also the comment on `fn obligations`, describing cycle
1068 // prevention, which happens before this can be reached.
1069ty::Infer(_) => {
1070let cause = self.cause(ObligationCauseCode::WellFormed(None));
1071self.out.push(traits::Obligation::with_depth(
1072tcx,
1073cause,
1074self.recursion_depth,
1075self.param_env,
1076 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(
1077t.into(),
1078 ))),
1079 ));
1080 }
1081 }
10821083t.super_visit_with(self)
1084 }
10851086fn visit_const(&mut self, c: ty::Const<'tcx>) -> Self::Result {
1087let tcx = self.tcx();
10881089match c.kind() {
1090 ty::ConstKind::Alias(_, alias_const) => {
1091if !c.has_escaping_bound_vars() {
1092// Skip type consts as mGCA doesn't support evaluatable clauses
1093if !alias_const.kind.is_direct_const(tcx) && !tcx.features().gca_const_items() {
1094let predicate = ty::Binder::dummy(ty::PredicateKind::Clause(
1095 ty::ClauseKind::ConstEvaluatable(c),
1096 ));
1097let cause = self.cause(ObligationCauseCode::WellFormed(None));
1098self.out.push(traits::Obligation::with_depth(
1099tcx,
1100cause,
1101self.recursion_depth,
1102self.param_env,
1103predicate,
1104 ));
1105 }
11061107match alias_const.kind {
1108 ty::AliasConstKind::InherentSelf { .. } => {
1109self.add_wf_preds_for_inherent_projection(alias_const.into());
1110return; // Subtree is handled by above function
1111}
1112// FIXME: This should be unreachable but isn't because we normalize in item
1113 // wfck before computing wf requirements
1114ty::AliasConstKind::InherentImpl { .. } => {
1115self.add_wf_preds_for_inherent_projection(alias_const.into());
1116return;
1117 }
1118 ty::AliasConstKind::Projection { def_id }
1119 | ty::AliasConstKind::Free { def_id }
1120 | ty::AliasConstKind::Anon { def_id } => {
1121self.nominal_obligations(
1122def_id,
1123alias_const.args,
1124 |this, obligation| this.out.push(obligation),
1125 );
1126 }
1127 }
1128 }
1129 }
1130 ty::ConstKind::Infer(_) => {
1131let cause = self.cause(ObligationCauseCode::WellFormed(None));
11321133self.out.push(traits::Obligation::with_depth(
1134tcx,
1135cause,
1136self.recursion_depth,
1137self.param_env,
1138 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(
1139c.into(),
1140 ))),
1141 ));
1142 }
1143 ty::ConstKind::Expr(_) => {
1144// FIXME(generic_const_exprs): this doesn't verify that given `Expr(N + 1)` the
1145 // trait bound `typeof(N): Add<typeof(1)>` holds. This is currently unnecessary
1146 // as `ConstKind::Expr` is only produced via normalization of `ConstKind::Alias`
1147 // which means that the `DefId` would have been typeck'd elsewhere. However in
1148 // the future we may allow directly lowering to `ConstKind::Expr` in which case
1149 // we would not be proving bounds we should.
11501151let predicate = ty::Binder::dummy(ty::PredicateKind::Clause(
1152 ty::ClauseKind::ConstEvaluatable(c),
1153 ));
1154let cause = self.cause(ObligationCauseCode::WellFormed(None));
1155self.out.push(traits::Obligation::with_depth(
1156tcx,
1157cause,
1158self.recursion_depth,
1159self.param_env,
1160predicate,
1161 ));
1162 }
11631164 ty::ConstKind::Error(_)
1165 | ty::ConstKind::Param(_)
1166 | ty::ConstKind::Bound(..)
1167 | ty::ConstKind::Placeholder(..) => {
1168// These variants are trivially WF, so nothing to do here.
1169}
1170 ty::ConstKind::Value(val) => {
1171// FIXME(mgca): no need to feature-gate once valtree lifetimes are not erased
1172if tcx.features().gca_min_const_items() {
1173match val.ty.kind() {
1174 ty::Adt(adt_def, args) => {
1175let adt_val = val.destructure_adt_const();
1176let variant_def = adt_def.variant(adt_val.variant);
1177let cause = self.cause(ObligationCauseCode::WellFormed(None));
1178self.out.extend(variant_def.fields.iter().zip(adt_val.fields).map(
1179 |(field_def, &field_val)| {
1180let field_ty = tcx1181 .type_of(field_def.did)
1182 .instantiate(tcx, args)
1183 .skip_norm_wip();
1184let predicate = ty::PredicateKind::Clause(
1185 ty::ClauseKind::ConstArgHasType(field_val, field_ty),
1186 );
1187 traits::Obligation::with_depth(
1188tcx,
1189cause.clone(),
1190self.recursion_depth,
1191self.param_env,
1192predicate,
1193 )
1194 },
1195 ));
1196 }
1197 ty::Tuple(field_tys) => {
1198let field_vals = val.to_branch();
1199let cause = self.cause(ObligationCauseCode::WellFormed(None));
1200self.out.extend(field_tys.iter().zip(field_vals).map(
1201 |(field_ty, &field_val)| {
1202let predicate = ty::PredicateKind::Clause(
1203 ty::ClauseKind::ConstArgHasType(field_val, field_ty),
1204 );
1205 traits::Obligation::with_depth(
1206tcx,
1207cause.clone(),
1208self.recursion_depth,
1209self.param_env,
1210predicate,
1211 )
1212 },
1213 ));
1214 }
1215 ty::Array(elem_ty, _len) => {
1216let elem_vals = val.to_branch();
1217let cause = self.cause(ObligationCauseCode::WellFormed(None));
12181219self.out.extend(elem_vals.iter().map(|&elem_val| {
1220let predicate = ty::PredicateKind::Clause(
1221 ty::ClauseKind::ConstArgHasType(elem_val, *elem_ty),
1222 );
1223 traits::Obligation::with_depth(
1224tcx,
1225cause.clone(),
1226self.recursion_depth,
1227self.param_env,
1228predicate,
1229 )
1230 }));
1231 }
1232_ => {}
1233 }
1234 }
12351236// FIXME: Enforce that values are structurally-matchable.
1237}
1238 }
12391240c.super_visit_with(self)
1241 }
12421243fn visit_predicate<P: PredicateProxy<TyCtxt<'tcx>>>(&mut self, _p: P) -> Self::Result {
1244::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");
1245 }
1246}
12471248/// Given an object type like `SomeTrait + Send`, computes the lifetime
1249/// bounds that must hold on the elided self type. These are derived
1250/// from the declarations of `SomeTrait`, `Send`, and friends -- if
1251/// they declare `trait SomeTrait : 'static`, for example, then
1252/// `'static` would appear in the list.
1253///
1254/// N.B., in some cases, particularly around higher-ranked bounds,
1255/// this function returns a kind of conservative approximation.
1256/// That is, all regions returned by this function are definitely
1257/// required, but there may be other region bounds that are not
1258/// returned, as well as requirements like `for<'a> T: 'a`.
1259///
1260/// Requires that trait definitions have been processed so that we can
1261/// elaborate predicates and walk supertraits.
1262pub fn object_region_bounds<'tcx>(
1263 tcx: TyCtxt<'tcx>,
1264 existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
1265) -> Vec<ty::Region<'tcx>> {
1266let erased_self_ty = tcx.types.trait_object_dummy_self;
12671268let clauses =
1269existential_predicates.iter().map(|predicate| predicate.with_self_ty(tcx, erased_self_ty));
12701271 traits::elaborate(tcx, clauses)
1272 .filter_map(|clause| {
1273{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs:1273",
"rustc_trait_selection::traits::wf",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/traits/wf.rs"),
::tracing_core::__macro_support::Option::Some(1273u32),
::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);
1274match clause.kind().skip_binder() {
1275 ty::ClauseKind::TypeOutlives(ty::OutlivesClause(ref t, ref r)) => {
1276// Search for a bound of the form `erased_self_ty
1277 // : 'a`, but be wary of something like `for<'a>
1278 // erased_self_ty : 'a` (we interpret a
1279 // higher-ranked bound like that as 'static,
1280 // though at present the code in `fulfill.rs`
1281 // considers such bounds to be unsatisfiable, so
1282 // it's kind of a moot point since you could never
1283 // construct such an object, but this seems
1284 // correct even if that code changes).
1285if t == &erased_self_ty && !r.has_escaping_bound_vars() {
1286Some(*r)
1287 } else {
1288None1289 }
1290 }
1291 ty::ClauseKind::Trait(_)
1292 | ty::ClauseKind::HostEffect(..)
1293 | ty::ClauseKind::RegionOutlives(_)
1294 | ty::ClauseKind::Projection(_)
1295 | ty::ClauseKind::ConstArgHasType(_, _)
1296 | ty::ClauseKind::WellFormed(_)
1297 | ty::ClauseKind::UnstableFeature(_)
1298 | ty::ClauseKind::ConstEvaluatable(_) => None,
1299 }
1300 })
1301 .collect()
1302}