use crate::check::regionck::OutlivesEnvironmentExt;
-use crate::check::{FnCtxt, Inherited};
use crate::constrained_generic_params::{identify_constrained_generic_params, Parameter};
-
use rustc_ast as ast;
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
-use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed};
+use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed};
use rustc_hir as hir;
use rustc_hir::def_id::{DefId, LocalDefId};
-use rustc_hir::intravisit as hir_visit;
-use rustc_hir::intravisit::Visitor;
-use rustc_hir::itemlikevisit::ParItemLikeVisitor;
use rustc_hir::lang_items::LangItem;
use rustc_hir::ItemKind;
-use rustc_infer::infer::outlives::env::OutlivesEnvironment;
+use rustc_infer::infer::outlives::env::{OutlivesEnvironment, RegionBoundPairs};
use rustc_infer::infer::outlives::obligations::TypeOutlives;
-use rustc_infer::infer::region_constraints::GenericKind;
use rustc_infer::infer::{self, InferCtxt, TyCtxtInferExt};
-use rustc_middle::hir::nested_filter;
+use rustc_infer::traits::Normalized;
+use rustc_middle::ty::query::Providers;
use rustc_middle::ty::subst::{GenericArgKind, InternalSubsts, Subst};
use rustc_middle::ty::trait_def::TraitSpecializationKind;
use rustc_middle::ty::{
- self, AdtKind, EarlyBinder, GenericParamDefKind, ToPredicate, Ty, TyCtxt, TypeFoldable,
- TypeSuperFoldable, TypeVisitor,
+ self, AdtKind, DefIdTree, GenericParamDefKind, ToPredicate, Ty, TyCtxt, TypeFoldable,
+ TypeSuperVisitable, TypeVisitable, TypeVisitor,
};
use rustc_session::parse::feature_err;
use rustc_span::symbol::{sym, Ident, Symbol};
use rustc_span::{Span, DUMMY_SP};
+use rustc_trait_selection::autoderef::Autoderef;
+use rustc_trait_selection::traits::error_reporting::InferCtxtExt;
use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
-use rustc_trait_selection::traits::{self, ObligationCause, ObligationCauseCode, WellFormedLoc};
+use rustc_trait_selection::traits::query::normalize::AtExt;
+use rustc_trait_selection::traits::query::NoSolution;
+use rustc_trait_selection::traits::{
+ self, ObligationCause, ObligationCauseCode, ObligationCtxt, WellFormedLoc,
+};
use std::cell::LazyCell;
use std::convert::TryInto;
use std::iter;
-use std::ops::ControlFlow;
+use std::ops::{ControlFlow, Deref};
-/// Helper type of a temporary returned by `.for_item(...)`.
-/// This is necessary because we can't write the following bound:
-///
-/// ```ignore (illustrative)
-/// F: for<'b, 'tcx> where 'tcx FnOnce(FnCtxt<'b, 'tcx>)
-/// ```
-pub(super) struct CheckWfFcxBuilder<'tcx> {
- inherited: super::InheritedBuilder<'tcx>,
- id: hir::HirId,
+pub(super) struct WfCheckingCtxt<'a, 'tcx> {
+ pub(super) ocx: ObligationCtxt<'a, 'tcx>,
span: Span,
+ body_id: hir::HirId,
param_env: ty::ParamEnv<'tcx>,
}
+impl<'a, 'tcx> Deref for WfCheckingCtxt<'a, 'tcx> {
+ type Target = ObligationCtxt<'a, 'tcx>;
+ fn deref(&self) -> &Self::Target {
+ &self.ocx
+ }
+}
+
+impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
+ fn tcx(&self) -> TyCtxt<'tcx> {
+ self.ocx.infcx.tcx
+ }
-impl<'tcx> CheckWfFcxBuilder<'tcx> {
- pub(super) fn with_fcx<F>(&mut self, f: F)
+ fn normalize<T>(&self, span: Span, loc: Option<WellFormedLoc>, value: T) -> T
where
- F: for<'b> FnOnce(&FnCtxt<'b, 'tcx>) -> FxHashSet<Ty<'tcx>>,
+ T: TypeFoldable<'tcx>,
{
- let id = self.id;
- let span = self.span;
- let param_env = self.param_env;
- self.inherited.enter(|inh| {
- let fcx = FnCtxt::new(&inh, param_env, id);
- if !inh.tcx.features().trivial_bounds {
- // As predicates are cached rather than obligations, this
- // needs to be called first so that they are checked with an
- // empty `param_env`.
- check_false_global_bounds(&fcx, span, id);
- }
- let wf_tys = f(&fcx);
- fcx.select_all_obligations_or_error();
- fcx.regionck_item(id, span, wf_tys);
- });
+ self.ocx.normalize(
+ ObligationCause::new(span, self.body_id, ObligationCauseCode::WellFormed(loc)),
+ self.param_env,
+ value,
+ )
+ }
+
+ fn register_wf_obligation(
+ &self,
+ span: Span,
+ loc: Option<WellFormedLoc>,
+ arg: ty::GenericArg<'tcx>,
+ ) {
+ let cause =
+ traits::ObligationCause::new(span, self.body_id, ObligationCauseCode::WellFormed(loc));
+ self.ocx.register_obligation(traits::Obligation::new(
+ cause,
+ self.param_env,
+ ty::Binder::dummy(ty::PredicateKind::WellFormed(arg)).to_predicate(self.tcx()),
+ ));
+ }
+}
+
+pub(super) fn enter_wf_checking_ctxt<'tcx, F>(
+ tcx: TyCtxt<'tcx>,
+ span: Span,
+ body_def_id: LocalDefId,
+ f: F,
+) where
+ F: for<'a> FnOnce(&WfCheckingCtxt<'a, 'tcx>) -> FxHashSet<Ty<'tcx>>,
+{
+ let param_env = tcx.param_env(body_def_id);
+ let body_id = tcx.hir().local_def_id_to_hir_id(body_def_id);
+ tcx.infer_ctxt().enter(|ref infcx| {
+ let ocx = ObligationCtxt::new(infcx);
+ let mut wfcx = WfCheckingCtxt { ocx, span, body_id, param_env };
+
+ if !tcx.features().trivial_bounds {
+ wfcx.check_false_global_bounds()
+ }
+ let wf_tys = f(&mut wfcx);
+ let errors = wfcx.select_all_or_error();
+ if !errors.is_empty() {
+ infcx.report_fulfillment_errors(&errors, None, false);
+ return;
+ }
+
+ let mut outlives_environment = OutlivesEnvironment::new(param_env);
+ outlives_environment.add_implied_bounds(infcx, wf_tys, body_id);
+ infcx.check_region_obligations_and_report_errors(body_def_id, &outlives_environment);
+ })
+}
+
+fn check_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
+ let node = tcx.hir().expect_owner(def_id);
+ match node {
+ hir::OwnerNode::Crate(_) => {}
+ hir::OwnerNode::Item(item) => check_item(tcx, item),
+ hir::OwnerNode::TraitItem(item) => check_trait_item(tcx, item),
+ hir::OwnerNode::ImplItem(item) => check_impl_item(tcx, item),
+ hir::OwnerNode::ForeignItem(item) => check_foreign_item(tcx, item),
+ }
+
+ if let Some(generics) = node.generics() {
+ for param in generics.params {
+ check_param_wf(tcx, param)
+ }
}
}
/// not included it frequently leads to confusing errors in fn bodies. So it's better to check
/// the types first.
#[instrument(skip(tcx), level = "debug")]
-pub fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
- let item = tcx.hir().expect_item(def_id);
+fn check_item<'tcx>(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) {
+ let def_id = item.def_id;
debug!(
?item.def_id,
// We match on both `ty::ImplPolarity` and `ast::ImplPolarity` just to get the `!` span.
match (tcx.impl_polarity(def_id), impl_.polarity) {
(ty::ImplPolarity::Positive, _) => {
- check_impl(tcx, item, impl_.self_ty, &impl_.of_trait);
+ check_impl(tcx, item, impl_.self_ty, &impl_.of_trait, impl_.constness);
}
(ty::ImplPolarity::Negative, ast::ImplPolarity::Negative(span)) => {
// FIXME(#27579): what amount of WF checking do we need for neg impls?
hir::ItemKind::Const(ty, ..) => {
check_item_type(tcx, item.def_id, ty.span, false);
}
- hir::ItemKind::ForeignMod { items, .. } => {
- for it in items.iter() {
- let it = tcx.hir().foreign_item(it.id);
- match it.kind {
- hir::ForeignItemKind::Fn(decl, ..) => {
- check_item_fn(tcx, it.def_id, it.ident, it.span, decl)
- }
- hir::ForeignItemKind::Static(ty, ..) => {
- check_item_type(tcx, it.def_id, ty.span, true)
- }
- hir::ForeignItemKind::Type => (),
- }
- }
- }
hir::ItemKind::Struct(ref struct_def, ref ast_generics) => {
- check_type_defn(tcx, item, false, |fcx| vec![fcx.non_enum_variant(struct_def)]);
+ check_type_defn(tcx, item, false, |wfcx| vec![wfcx.non_enum_variant(struct_def)]);
check_variances_for_type_defn(tcx, item, ast_generics);
}
hir::ItemKind::Union(ref struct_def, ref ast_generics) => {
- check_type_defn(tcx, item, true, |fcx| vec![fcx.non_enum_variant(struct_def)]);
+ check_type_defn(tcx, item, true, |wfcx| vec![wfcx.non_enum_variant(struct_def)]);
check_variances_for_type_defn(tcx, item, ast_generics);
}
hir::ItemKind::Enum(ref enum_def, ref ast_generics) => {
- check_type_defn(tcx, item, true, |fcx| fcx.enum_variants(enum_def));
+ check_type_defn(tcx, item, true, |wfcx| wfcx.enum_variants(enum_def));
check_variances_for_type_defn(tcx, item, ast_generics);
}
hir::ItemKind::TraitAlias(..) => {
check_trait(tcx, item);
}
+ // `ForeignItem`s are handled separately.
+ hir::ItemKind::ForeignMod { .. } => {}
_ => {}
}
}
-pub fn check_trait_item(tcx: TyCtxt<'_>, def_id: LocalDefId) {
- let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
- let trait_item = tcx.hir().expect_trait_item(def_id);
+fn check_foreign_item(tcx: TyCtxt<'_>, item: &hir::ForeignItem<'_>) {
+ let def_id = item.def_id;
+
+ debug!(
+ ?item.def_id,
+ item.name = ? tcx.def_path_str(def_id.to_def_id())
+ );
+
+ match item.kind {
+ hir::ForeignItemKind::Fn(decl, ..) => {
+ check_item_fn(tcx, item.def_id, item.ident, item.span, decl)
+ }
+ hir::ForeignItemKind::Static(ty, ..) => check_item_type(tcx, item.def_id, ty.span, true),
+ hir::ForeignItemKind::Type => (),
+ }
+}
+
+fn check_trait_item(tcx: TyCtxt<'_>, trait_item: &hir::TraitItem<'_>) {
+ let def_id = trait_item.def_id;
let (method_sig, span) = match trait_item.kind {
hir::TraitItemKind::Fn(ref sig, _) => (Some(sig), trait_item.span),
check_object_unsafe_self_trait_by_name(tcx, trait_item);
check_associated_item(tcx, trait_item.def_id, span, method_sig);
- let encl_trait_def_id = tcx.hir().get_parent_item(hir_id);
+ let encl_trait_def_id = tcx.local_parent(def_id);
let encl_trait = tcx.hir().expect_item(encl_trait_def_id);
let encl_trait_def_id = encl_trait.def_id.to_def_id();
let fn_lang_item_name = if Some(encl_trait_def_id) == tcx.lang_items().fn_trait() {
unsatisfied_bounds.sort();
if !unsatisfied_bounds.is_empty() {
- let plural = if unsatisfied_bounds.len() > 1 { "s" } else { "" };
+ let plural = pluralize!(unsatisfied_bounds.len());
let mut err = tcx.sess.struct_span_err(
gat_item_hir.span,
&format!("missing required bound{} on `{}`", plural, gat_item_hir.ident),
) -> bool {
resolve_regions_with_wf_tys(tcx, id, param_env, &wf_tys, |infcx, region_bound_pairs| {
let origin = infer::RelateParamBound(DUMMY_SP, ty, None);
- let outlives = &mut TypeOutlives::new(
- infcx,
- tcx,
- region_bound_pairs,
- Some(infcx.tcx.lifetimes.re_root_empty),
- param_env,
- );
+ let outlives = &mut TypeOutlives::new(infcx, tcx, region_bound_pairs, None, param_env);
outlives.type_must_outlive(origin, ty, region);
})
}
id: hir::HirId,
param_env: ty::ParamEnv<'tcx>,
wf_tys: &FxHashSet<Ty<'tcx>>,
- add_constraints: impl for<'a> FnOnce(
- &'a InferCtxt<'a, 'tcx>,
- &'a Vec<(ty::Region<'tcx>, GenericKind<'tcx>)>,
- ),
+ add_constraints: impl for<'a> FnOnce(&'a InferCtxt<'a, 'tcx>, &'a RegionBoundPairs<'tcx>),
) -> bool {
// Unfortunately, we have to use a new `InferCtxt` each call, because
// region constraints get added and solved there and we need to test each
// call individually.
tcx.infer_ctxt().enter(|infcx| {
let mut outlives_environment = OutlivesEnvironment::new(param_env);
- outlives_environment.add_implied_bounds(&infcx, wf_tys.clone(), id, DUMMY_SP);
- outlives_environment.save_implied_bounds(id);
- let region_bound_pairs = outlives_environment.region_bound_pairs_map().get(&id).unwrap();
+ outlives_environment.add_implied_bounds(&infcx, wf_tys.clone(), id);
+ let region_bound_pairs = outlives_environment.region_bound_pairs();
add_constraints(&infcx, region_bound_pairs);
- let errors = infcx.resolve_regions(id.expect_owner().to_def_id(), &outlives_environment);
+ let errors = infcx.resolve_regions(&outlives_environment);
debug!(?errors, "errors");
}
}
-pub fn check_impl_item(tcx: TyCtxt<'_>, def_id: LocalDefId) {
- let impl_item = tcx.hir().expect_impl_item(def_id);
+fn check_impl_item(tcx: TyCtxt<'_>, impl_item: &hir::ImplItem<'_>) {
+ let def_id = impl_item.def_id;
let (method_sig, span) = match impl_item.kind {
hir::ImplItemKind::Fn(ref sig, _) => (Some(sig), impl_item.span),
_ => (None, impl_item.span),
};
- check_associated_item(tcx, impl_item.def_id, span, method_sig);
+ check_associated_item(tcx, def_id, span, method_sig);
}
fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) {
let ty = tcx.type_of(tcx.hir().local_def_id(param.hir_id));
if tcx.features().adt_const_params {
- let err = match ty.peel_refs().kind() {
- ty::FnPtr(_) => Some("function pointers"),
- ty::RawPtr(_) => Some("raw pointers"),
- _ => None,
- };
-
- if let Some(unsupported_type) = err {
- tcx.sess.span_err(
- hir_ty.span,
- &format!(
- "using {} as const generic parameters is forbidden",
- unsupported_type
- ),
- );
- }
-
if let Some(non_structural_match_ty) =
- traits::search_for_structural_match_violation(param.span, tcx, ty)
+ traits::search_for_adt_const_param_violation(param.span, tcx, ty)
{
// We use the same error code in both branches, because this is really the same
// issue: we just special-case the message for type parameters to make it
// clearer.
- if let ty::Param(_) = ty.peel_refs().kind() {
- // Const parameters may not have type parameters as their types,
- // because we cannot be sure that the type parameter derives `PartialEq`
- // and `Eq` (just implementing them is not enough for `structural_match`).
- struct_span_err!(
- tcx.sess,
- hir_ty.span,
- E0741,
- "`{}` is not guaranteed to `#[derive(PartialEq, Eq)]`, so may not be \
- used as the type of a const parameter",
- ty,
- )
- .span_label(
- hir_ty.span,
- format!("`{}` may not derive both `PartialEq` and `Eq`", ty),
- )
- .note(
- "it is not currently possible to use a type parameter as the type of a \
- const parameter",
- )
- .emit();
- } else {
- let mut diag = struct_span_err!(
- tcx.sess,
- hir_ty.span,
- E0741,
- "`{}` must be annotated with `#[derive(PartialEq, Eq)]` to be used as \
- the type of a const parameter",
- non_structural_match_ty.ty,
- );
-
- if ty == non_structural_match_ty.ty {
- diag.span_label(
+ match non_structural_match_ty.kind() {
+ ty::Param(_) => {
+ // Const parameters may not have type parameters as their types,
+ // because we cannot be sure that the type parameter derives `PartialEq`
+ // and `Eq` (just implementing them is not enough for `structural_match`).
+ struct_span_err!(
+ tcx.sess,
hir_ty.span,
- format!("`{ty}` doesn't derive both `PartialEq` and `Eq`"),
- );
+ E0741,
+ "`{ty}` is not guaranteed to `#[derive(PartialEq, Eq)]`, so may not be \
+ used as the type of a const parameter",
+ )
+ .span_label(
+ hir_ty.span,
+ format!("`{ty}` may not derive both `PartialEq` and `Eq`"),
+ )
+ .note(
+ "it is not currently possible to use a type parameter as the type of a \
+ const parameter",
+ )
+ .emit();
+ }
+ ty::Float(_) => {
+ struct_span_err!(
+ tcx.sess,
+ hir_ty.span,
+ E0741,
+ "`{ty}` is forbidden as the type of a const generic parameter",
+ )
+ .note("floats do not derive `Eq` or `Ord`, which are required for const parameters")
+ .emit();
+ }
+ ty::FnPtr(_) => {
+ struct_span_err!(
+ tcx.sess,
+ hir_ty.span,
+ E0741,
+ "using function pointers as const generic parameters is forbidden",
+ )
+ .emit();
}
+ ty::RawPtr(_) => {
+ struct_span_err!(
+ tcx.sess,
+ hir_ty.span,
+ E0741,
+ "using raw pointers as const generic parameters is forbidden",
+ )
+ .emit();
+ }
+ _ => {
+ let mut diag = struct_span_err!(
+ tcx.sess,
+ hir_ty.span,
+ E0741,
+ "`{}` must be annotated with `#[derive(PartialEq, Eq)]` to be used as \
+ the type of a const parameter",
+ non_structural_match_ty,
+ );
+
+ if ty == non_structural_match_ty {
+ diag.span_label(
+ hir_ty.span,
+ format!("`{ty}` doesn't derive both `PartialEq` and `Eq`"),
+ );
+ }
- diag.emit();
+ diag.emit();
+ }
}
}
} else {
span: Span,
sig_if_method: Option<&hir::FnSig<'_>>,
) {
- let code = ObligationCauseCode::WellFormed(Some(WellFormedLoc::Ty(item_id)));
- for_id(tcx, item_id, span).with_fcx(|fcx| {
- let item = fcx.tcx.associated_item(item_id);
+ let loc = Some(WellFormedLoc::Ty(item_id));
+ enter_wf_checking_ctxt(tcx, span, item_id, |wfcx| {
+ let item = tcx.associated_item(item_id);
let (mut implied_bounds, self_ty) = match item.container {
- ty::TraitContainer(_) => (FxHashSet::default(), fcx.tcx.types.self_param),
- ty::ImplContainer(def_id) => {
- (fcx.impl_implied_bounds(def_id, span), fcx.tcx.type_of(def_id))
+ ty::TraitContainer => (FxHashSet::default(), tcx.types.self_param),
+ ty::ImplContainer => {
+ let def_id = item.container_id(tcx);
+ (
+ impl_implied_bounds(tcx, wfcx.param_env, def_id.expect_local(), span),
+ tcx.type_of(def_id),
+ )
}
};
match item.kind {
ty::AssocKind::Const => {
- let ty = fcx.tcx.type_of(item.def_id);
- let ty = fcx.normalize_associated_types_in_wf(span, ty, WellFormedLoc::Ty(item_id));
- fcx.register_wf_obligation(ty.into(), span, code.clone());
+ let ty = tcx.type_of(item.def_id);
+ let ty = wfcx.normalize(span, Some(WellFormedLoc::Ty(item_id)), ty);
+ wfcx.register_wf_obligation(span, loc, ty.into());
}
ty::AssocKind::Fn => {
- let sig = fcx.tcx.fn_sig(item.def_id);
+ let sig = tcx.fn_sig(item.def_id);
let hir_sig = sig_if_method.expect("bad signature for method");
check_fn_or_method(
- fcx,
- item.ident(fcx.tcx).span,
+ wfcx,
+ item.ident(tcx).span,
sig,
hir_sig.decl,
item.def_id.expect_local(),
&mut implied_bounds,
);
- check_method_receiver(fcx, hir_sig, item, self_ty);
+ check_method_receiver(wfcx, hir_sig, item, self_ty);
}
ty::AssocKind::Type => {
- if let ty::AssocItemContainer::TraitContainer(_) = item.container {
- check_associated_type_bounds(fcx, item, span)
+ if let ty::AssocItemContainer::TraitContainer = item.container {
+ check_associated_type_bounds(wfcx, item, span)
}
- if item.defaultness.has_value() {
- let ty = fcx.tcx.type_of(item.def_id);
- let ty =
- fcx.normalize_associated_types_in_wf(span, ty, WellFormedLoc::Ty(item_id));
- fcx.register_wf_obligation(ty.into(), span, code.clone());
+ if item.defaultness(tcx).has_value() {
+ let ty = tcx.type_of(item.def_id);
+ let ty = wfcx.normalize(span, Some(WellFormedLoc::Ty(item_id)), ty);
+ wfcx.register_wf_obligation(span, loc, ty.into());
}
}
}
})
}
-pub(super) fn for_item<'tcx>(tcx: TyCtxt<'tcx>, item: &hir::Item<'_>) -> CheckWfFcxBuilder<'tcx> {
- for_id(tcx, item.def_id, item.span)
-}
-
-fn for_id(tcx: TyCtxt<'_>, def_id: LocalDefId, span: Span) -> CheckWfFcxBuilder<'_> {
- CheckWfFcxBuilder {
- inherited: Inherited::build(tcx, def_id),
- id: hir::HirId::make_owner(def_id),
- span,
- param_env: tcx.param_env(def_id),
- }
-}
-
fn item_adt_kind(kind: &ItemKind<'_>) -> Option<AdtKind> {
match kind {
ItemKind::Struct(..) => Some(AdtKind::Struct),
all_sized: bool,
mut lookup_fields: F,
) where
- F: for<'fcx> FnMut(&FnCtxt<'fcx, 'tcx>) -> Vec<AdtVariant<'tcx>>,
+ F: FnMut(&WfCheckingCtxt<'_, 'tcx>) -> Vec<AdtVariant<'tcx>>,
{
- for_item(tcx, item).with_fcx(|fcx| {
- let variants = lookup_fields(fcx);
+ enter_wf_checking_ctxt(tcx, item.span, item.def_id, |wfcx| {
+ let variants = lookup_fields(wfcx);
let packed = tcx.adt_def(item.def_id).repr().packed();
for variant in &variants {
+ // All field types must be well-formed.
+ for field in &variant.fields {
+ wfcx.register_wf_obligation(
+ field.span,
+ Some(WellFormedLoc::Ty(field.def_id)),
+ field.ty.into(),
+ )
+ }
+
// For DST, or when drop needs to copy things around, all
// intermediate types must be sized.
let needs_drop_copy = || {
}
}
};
+ // All fields (except for possibly the last) should be sized.
let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
let unsized_len = if all_sized { 0 } else { 1 };
for (idx, field) in
variant.fields[..variant.fields.len() - unsized_len].iter().enumerate()
{
let last = idx == variant.fields.len() - 1;
- fcx.register_bound(
- field.ty,
- tcx.require_lang_item(LangItem::Sized, None),
+ wfcx.register_bound(
traits::ObligationCause::new(
field.span,
- fcx.body_id,
+ wfcx.body_id,
traits::FieldSized {
adt_kind: match item_adt_kind(&item.kind) {
Some(i) => i,
last,
},
),
+ wfcx.param_env,
+ field.ty,
+ tcx.require_lang_item(LangItem::Sized, None),
);
}
- // All field types must be well-formed.
- for field in &variant.fields {
- fcx.register_wf_obligation(
- field.ty.into(),
- field.span,
- ObligationCauseCode::WellFormed(Some(WellFormedLoc::Ty(field.def_id))),
- )
- }
-
// Explicit `enum` discriminant values must const-evaluate successfully.
if let Some(discr_def_id) = variant.explicit_discr {
let discr_substs = InternalSubsts::identity_for_item(tcx, discr_def_id.to_def_id());
let cause = traits::ObligationCause::new(
tcx.def_span(discr_def_id),
- fcx.body_id,
+ wfcx.body_id,
traits::MiscObligation,
);
- fcx.register_predicate(traits::Obligation::new(
+ wfcx.register_obligation(traits::Obligation::new(
cause,
- fcx.param_env,
+ wfcx.param_env,
ty::Binder::dummy(ty::PredicateKind::ConstEvaluatable(ty::Unevaluated::new(
ty::WithOptConstParam::unknown(discr_def_id.to_def_id()),
discr_substs,
}
}
- check_where_clauses(fcx, item.span, item.def_id, None);
+ check_where_clauses(wfcx, item.span, item.def_id);
// No implied bounds in a struct definition.
FxHashSet::default()
}
}
- // FIXME: this shouldn't use an `FnCtxt` at all.
- for_item(tcx, item).with_fcx(|fcx| {
- check_where_clauses(fcx, item.span, item.def_id, None);
+ enter_wf_checking_ctxt(tcx, item.span, item.def_id, |wfcx| {
+ check_where_clauses(wfcx, item.span, item.def_id);
FxHashSet::default()
});
///
/// Assuming the defaults are used, check that all predicates (bounds on the
/// assoc type and where clauses on the trait) hold.
-fn check_associated_type_bounds(fcx: &FnCtxt<'_, '_>, item: &ty::AssocItem, span: Span) {
- let tcx = fcx.tcx;
-
- let bounds = tcx.explicit_item_bounds(item.def_id);
+fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: &ty::AssocItem, span: Span) {
+ let bounds = wfcx.tcx().explicit_item_bounds(item.def_id);
debug!("check_associated_type_bounds: bounds={:?}", bounds);
let wf_obligations = bounds.iter().flat_map(|&(bound, bound_span)| {
- let normalized_bound = fcx.normalize_associated_types_in(span, bound);
+ let normalized_bound = wfcx.normalize(span, None, bound);
traits::wf::predicate_obligations(
- fcx,
- fcx.param_env,
- fcx.body_id,
+ wfcx.infcx,
+ wfcx.param_env,
+ wfcx.body_id,
normalized_bound,
bound_span,
)
});
- for obligation in wf_obligations {
- debug!("next obligation cause: {:?}", obligation.cause);
- fcx.register_predicate(obligation);
- }
+ wfcx.register_obligations(wf_obligations);
}
fn check_item_fn(
span: Span,
decl: &hir::FnDecl<'_>,
) {
- for_id(tcx, def_id, span).with_fcx(|fcx| {
+ enter_wf_checking_ctxt(tcx, span, def_id, |wfcx| {
let sig = tcx.fn_sig(def_id);
let mut implied_bounds = FxHashSet::default();
- check_fn_or_method(fcx, ident.span, sig, decl, def_id, &mut implied_bounds);
+ check_fn_or_method(wfcx, ident.span, sig, decl, def_id, &mut implied_bounds);
implied_bounds
})
}
fn check_item_type(tcx: TyCtxt<'_>, item_id: LocalDefId, ty_span: Span, allow_foreign_ty: bool) {
debug!("check_item_type: {:?}", item_id);
- for_id(tcx, item_id, ty_span).with_fcx(|fcx| {
+ enter_wf_checking_ctxt(tcx, ty_span, item_id, |wfcx| {
let ty = tcx.type_of(item_id);
- let item_ty = fcx.normalize_associated_types_in_wf(ty_span, ty, WellFormedLoc::Ty(item_id));
+ let item_ty = wfcx.normalize(ty_span, Some(WellFormedLoc::Ty(item_id)), ty);
let mut forbid_unsized = true;
if allow_foreign_ty {
- let tail = fcx.tcx.struct_tail_erasing_lifetimes(item_ty, fcx.param_env);
+ let tail = tcx.struct_tail_erasing_lifetimes(item_ty, wfcx.param_env);
if let ty::Foreign(_) = tail.kind() {
forbid_unsized = false;
}
}
- fcx.register_wf_obligation(
- item_ty.into(),
- ty_span,
- ObligationCauseCode::WellFormed(Some(WellFormedLoc::Ty(item_id))),
- );
+ wfcx.register_wf_obligation(ty_span, Some(WellFormedLoc::Ty(item_id)), item_ty.into());
if forbid_unsized {
- fcx.register_bound(
+ wfcx.register_bound(
+ traits::ObligationCause::new(ty_span, wfcx.body_id, traits::WellFormed(None)),
+ wfcx.param_env,
item_ty,
tcx.require_lang_item(LangItem::Sized, None),
- traits::ObligationCause::new(ty_span, fcx.body_id, traits::MiscObligation),
);
}
&& !tcx.is_thread_local_static(item_id.to_def_id());
if should_check_for_sync {
- fcx.register_bound(
+ wfcx.register_bound(
+ traits::ObligationCause::new(ty_span, wfcx.body_id, traits::SharedStatic),
+ wfcx.param_env,
item_ty,
tcx.require_lang_item(LangItem::Sync, Some(ty_span)),
- traits::ObligationCause::new(ty_span, fcx.body_id, traits::SharedStatic),
);
}
item: &'tcx hir::Item<'tcx>,
ast_self_ty: &hir::Ty<'_>,
ast_trait_ref: &Option<hir::TraitRef<'_>>,
+ constness: hir::Constness,
) {
- for_item(tcx, item).with_fcx(|fcx| {
+ enter_wf_checking_ctxt(tcx, item.span, item.def_id, |wfcx| {
match *ast_trait_ref {
Some(ref ast_trait_ref) => {
// `#[rustc_reservation_impl]` impls are not real impls and
// therefore don't need to be WF (the trait's `Self: Trait` predicate
// won't hold).
let trait_ref = tcx.impl_trait_ref(item.def_id).unwrap();
- let trait_ref =
- fcx.normalize_associated_types_in(ast_trait_ref.path.span, trait_ref);
+ let trait_ref = wfcx.normalize(ast_trait_ref.path.span, None, trait_ref);
+ let trait_pred = ty::TraitPredicate {
+ trait_ref,
+ constness: match constness {
+ hir::Constness::Const => ty::BoundConstness::ConstIfConst,
+ hir::Constness::NotConst => ty::BoundConstness::NotConst,
+ },
+ polarity: ty::ImplPolarity::Positive,
+ };
let obligations = traits::wf::trait_obligations(
- fcx,
- fcx.param_env,
- fcx.body_id,
- &trait_ref,
+ wfcx.infcx,
+ wfcx.param_env,
+ wfcx.body_id,
+ &trait_pred,
ast_trait_ref.path.span,
item,
);
debug!(?obligations);
- for obligation in obligations {
- fcx.register_predicate(obligation);
- }
+ wfcx.register_obligations(obligations);
}
None => {
let self_ty = tcx.type_of(item.def_id);
- let self_ty = fcx.normalize_associated_types_in(item.span, self_ty);
- fcx.register_wf_obligation(
- self_ty.into(),
+ let self_ty = wfcx.normalize(item.span, None, self_ty);
+ wfcx.register_wf_obligation(
ast_self_ty.span,
- ObligationCauseCode::WellFormed(Some(WellFormedLoc::Ty(
- item.hir_id().expect_owner(),
- ))),
+ Some(WellFormedLoc::Ty(item.hir_id().expect_owner())),
+ self_ty.into(),
);
}
}
- check_where_clauses(fcx, item.span, item.def_id, None);
+ check_where_clauses(wfcx, item.span, item.def_id);
- fcx.impl_implied_bounds(item.def_id.to_def_id(), item.span)
+ impl_implied_bounds(tcx, wfcx.param_env, item.def_id, item.span)
});
}
/// Checks where-clauses and inline bounds that are declared on `def_id`.
-#[instrument(skip(fcx), level = "debug")]
-fn check_where_clauses<'tcx, 'fcx>(
- fcx: &FnCtxt<'fcx, 'tcx>,
- span: Span,
- def_id: LocalDefId,
- return_ty: Option<(Ty<'tcx>, Span)>,
-) {
- let tcx = fcx.tcx;
+#[instrument(level = "debug", skip(wfcx))]
+fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, span: Span, def_id: LocalDefId) {
+ let infcx = wfcx.infcx;
+ let tcx = wfcx.tcx();
- let predicates = tcx.predicates_of(def_id);
+ let predicates = tcx.bound_predicates_of(def_id.to_def_id());
let generics = tcx.generics_of(def_id);
let is_our_default = |def: &ty::GenericParamDef| match def.kind {
// parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
// be sure if it will error or not as user might always specify the other.
if !ty.needs_subst() {
- fcx.register_wf_obligation(
- ty.into(),
- tcx.def_span(param.def_id),
- ObligationCauseCode::MiscObligation,
- );
+ wfcx.register_wf_obligation(tcx.def_span(param.def_id), None, ty.into());
}
}
}
// we should eagerly error.
let default_ct = tcx.const_param_default(param.def_id);
if !default_ct.needs_subst() {
- fcx.register_wf_obligation(
- default_ct.into(),
+ wfcx.register_wf_obligation(
tcx.def_span(param.def_id),
- ObligationCauseCode::WellFormed(None),
+ None,
+ default_ct.into(),
);
}
}
// Now we build the substituted predicates.
let default_obligations = predicates
+ .0
.predicates
.iter()
.flat_map(|&(pred, sp)| {
struct CountParams {
params: FxHashSet<u32>,
}
- impl<'tcx> ty::fold::TypeVisitor<'tcx> for CountParams {
+ impl<'tcx> ty::visit::TypeVisitor<'tcx> for CountParams {
type BreakTy = ();
fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
}
let mut param_count = CountParams::default();
let has_region = pred.visit_with(&mut param_count).is_break();
- let substituted_pred = EarlyBinder(pred).subst(tcx, substs);
+ let substituted_pred = predicates.rebind(pred).subst(tcx, substs);
// Don't check non-defaulted params, dependent defaults (including lifetimes)
// or preds with multiple params.
if substituted_pred.has_param_types_or_consts()
|| has_region
{
None
- } else if predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
+ } else if predicates.0.predicates.iter().any(|&(p, _)| p == substituted_pred) {
// Avoid duplication of predicates that contain no parameters, for example.
None
} else {
// Note the subtle difference from how we handle `predicates`
// below: there, we are not trying to prove those predicates
// to be *true* but merely *well-formed*.
- let pred = fcx.normalize_associated_types_in(sp, pred);
+ let pred = wfcx.normalize(sp, None, pred);
let cause = traits::ObligationCause::new(
sp,
- fcx.body_id,
+ wfcx.body_id,
traits::ItemObligation(def_id.to_def_id()),
);
- traits::Obligation::new(cause, fcx.param_env, pred)
+ traits::Obligation::new(cause, wfcx.param_env, pred)
});
- let predicates = predicates.instantiate_identity(tcx);
-
- if let Some((return_ty, _)) = return_ty {
- if return_ty.has_infer_types_or_consts() {
- fcx.select_obligations_where_possible(false, |_| {});
- }
- }
+ let predicates = predicates.0.instantiate_identity(tcx);
- let predicates = fcx.normalize_associated_types_in(span, predicates);
+ let predicates = wfcx.normalize(span, None, predicates);
debug!(?predicates.predicates);
assert_eq!(predicates.predicates.len(), predicates.spans.len());
let wf_obligations =
iter::zip(&predicates.predicates, &predicates.spans).flat_map(|(&p, &sp)| {
- traits::wf::predicate_obligations(fcx, fcx.param_env, fcx.body_id, p, sp)
+ traits::wf::predicate_obligations(infcx, wfcx.param_env, wfcx.body_id, p, sp)
});
- for obligation in wf_obligations.chain(default_obligations) {
- debug!("next obligation cause: {:?}", obligation.cause);
- fcx.register_predicate(obligation);
- }
+ let obligations: Vec<_> = wf_obligations.chain(default_obligations).collect();
+ wfcx.register_obligations(obligations);
}
-#[tracing::instrument(level = "debug", skip(fcx, span, hir_decl))]
-fn check_fn_or_method<'fcx, 'tcx>(
- fcx: &FnCtxt<'fcx, 'tcx>,
+#[tracing::instrument(level = "debug", skip(wfcx, span, hir_decl))]
+fn check_fn_or_method<'tcx>(
+ wfcx: &WfCheckingCtxt<'_, 'tcx>,
span: Span,
sig: ty::PolyFnSig<'tcx>,
hir_decl: &hir::FnDecl<'_>,
def_id: LocalDefId,
implied_bounds: &mut FxHashSet<Ty<'tcx>>,
) {
- let sig = fcx.tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
+ let tcx = wfcx.tcx();
+ let sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
// Normalize the input and output types one at a time, using a different
// `WellFormedLoc` for each. We cannot call `normalize_associated_types`
// for each type, preventing the HIR wf check from generating
// a nice error message.
let ty::FnSig { mut inputs_and_output, c_variadic, unsafety, abi } = sig;
- inputs_and_output =
- fcx.tcx.mk_type_list(inputs_and_output.iter().enumerate().map(|(i, ty)| {
- fcx.normalize_associated_types_in_wf(
- span,
- ty,
- WellFormedLoc::Param {
- function: def_id,
- // Note that the `param_idx` of the output type is
- // one greater than the index of the last input type.
- param_idx: i.try_into().unwrap(),
- },
- )
- }));
+ inputs_and_output = tcx.mk_type_list(inputs_and_output.iter().enumerate().map(|(i, ty)| {
+ wfcx.normalize(
+ span,
+ Some(WellFormedLoc::Param {
+ function: def_id,
+ // Note that the `param_idx` of the output type is
+ // one greater than the index of the last input type.
+ param_idx: i.try_into().unwrap(),
+ }),
+ ty,
+ )
+ }));
// Manually call `normalize_associated_types_in` on the other types
// in `FnSig`. This ensures that if the types of these fields
// ever change to include projections, we will start normalizing
// them automatically.
let sig = ty::FnSig {
inputs_and_output,
- c_variadic: fcx.normalize_associated_types_in(span, c_variadic),
- unsafety: fcx.normalize_associated_types_in(span, unsafety),
- abi: fcx.normalize_associated_types_in(span, abi),
+ c_variadic: wfcx.normalize(span, None, c_variadic),
+ unsafety: wfcx.normalize(span, None, unsafety),
+ abi: wfcx.normalize(span, None, abi),
};
for (i, (&input_ty, ty)) in iter::zip(sig.inputs(), hir_decl.inputs).enumerate() {
- fcx.register_wf_obligation(
- input_ty.into(),
+ wfcx.register_wf_obligation(
ty.span,
- ObligationCauseCode::WellFormed(Some(WellFormedLoc::Param {
- function: def_id,
- param_idx: i.try_into().unwrap(),
- })),
+ Some(WellFormedLoc::Param { function: def_id, param_idx: i.try_into().unwrap() }),
+ input_ty.into(),
);
}
implied_bounds.extend(sig.inputs());
- fcx.register_wf_obligation(
- sig.output().into(),
- hir_decl.output.span(),
- ObligationCauseCode::ReturnType,
- );
+ wfcx.register_wf_obligation(hir_decl.output.span(), None, sig.output().into());
// FIXME(#27579) return types should not be implied bounds
implied_bounds.insert(sig.output());
debug!(?implied_bounds);
- check_where_clauses(fcx, span, def_id, Some((sig.output(), hir_decl.output.span())));
+ check_where_clauses(wfcx, span, def_id);
}
const HELP_FOR_SELF_TYPE: &str = "consider changing to `self`, `&self`, `&mut self`, `self: Box<Self>`, \
`self: Rc<Self>`, `self: Arc<Self>`, or `self: Pin<P>` (where P is one \
of the previous types except `Self`)";
-#[tracing::instrument(level = "debug", skip(fcx))]
-fn check_method_receiver<'fcx, 'tcx>(
- fcx: &FnCtxt<'fcx, 'tcx>,
+#[tracing::instrument(level = "debug", skip(wfcx))]
+fn check_method_receiver<'tcx>(
+ wfcx: &WfCheckingCtxt<'_, 'tcx>,
fn_sig: &hir::FnSig<'_>,
method: &ty::AssocItem,
self_ty: Ty<'tcx>,
) {
- // Check that the method has a valid receiver type, given the type `Self`.
- debug!("check_method_receiver({:?}, self_ty={:?})", method, self_ty);
+ let tcx = wfcx.tcx();
if !method.fn_has_self_parameter {
return;
let span = fn_sig.decl.inputs[0].span;
- let sig = fcx.tcx.fn_sig(method.def_id);
- let sig = fcx.tcx.liberate_late_bound_regions(method.def_id, sig);
- let sig = fcx.normalize_associated_types_in(span, sig);
+ let sig = tcx.fn_sig(method.def_id);
+ let sig = tcx.liberate_late_bound_regions(method.def_id, sig);
+ let sig = wfcx.normalize(span, None, sig);
debug!("check_method_receiver: sig={:?}", sig);
- let self_ty = fcx.normalize_associated_types_in(span, self_ty);
+ let self_ty = wfcx.normalize(span, None, self_ty);
let receiver_ty = sig.inputs()[0];
- let receiver_ty = fcx.normalize_associated_types_in(span, receiver_ty);
+ let receiver_ty = wfcx.normalize(span, None, receiver_ty);
- if fcx.tcx.features().arbitrary_self_types {
- if !receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
+ if tcx.features().arbitrary_self_types {
+ if !receiver_is_valid(wfcx, span, receiver_ty, self_ty, true) {
// Report error; `arbitrary_self_types` was enabled.
- e0307(fcx, span, receiver_ty);
+ e0307(tcx, span, receiver_ty);
}
} else {
- if !receiver_is_valid(fcx, span, receiver_ty, self_ty, false) {
- if receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
+ if !receiver_is_valid(wfcx, span, receiver_ty, self_ty, false) {
+ if receiver_is_valid(wfcx, span, receiver_ty, self_ty, true) {
// Report error; would have worked with `arbitrary_self_types`.
feature_err(
- &fcx.tcx.sess.parse_sess,
+ &tcx.sess.parse_sess,
sym::arbitrary_self_types,
span,
&format!(
.emit();
} else {
// Report error; would not have worked with `arbitrary_self_types`.
- e0307(fcx, span, receiver_ty);
+ e0307(tcx, span, receiver_ty);
}
}
}
}
-fn e0307<'tcx>(fcx: &FnCtxt<'_, 'tcx>, span: Span, receiver_ty: Ty<'_>) {
+fn e0307<'tcx>(tcx: TyCtxt<'tcx>, span: Span, receiver_ty: Ty<'_>) {
struct_span_err!(
- fcx.tcx.sess.diagnostic(),
+ tcx.sess.diagnostic(),
span,
E0307,
"invalid `self` parameter type: {receiver_ty}"
/// N.B., there are cases this function returns `true` but causes an error to be emitted,
/// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
/// wrong lifetime. Be careful of this if you are calling this function speculatively.
-fn receiver_is_valid<'fcx, 'tcx>(
- fcx: &FnCtxt<'fcx, 'tcx>,
+fn receiver_is_valid<'tcx>(
+ wfcx: &WfCheckingCtxt<'_, 'tcx>,
span: Span,
receiver_ty: Ty<'tcx>,
self_ty: Ty<'tcx>,
arbitrary_self_types_enabled: bool,
) -> bool {
- let cause = fcx.cause(span, traits::ObligationCauseCode::MethodReceiver);
+ let infcx = wfcx.infcx;
+ let tcx = wfcx.tcx();
+ let cause =
+ ObligationCause::new(span, wfcx.body_id, traits::ObligationCauseCode::MethodReceiver);
- let can_eq_self = |ty| fcx.infcx.can_eq(fcx.param_env, self_ty, ty).is_ok();
+ let can_eq_self = |ty| infcx.can_eq(wfcx.param_env, self_ty, ty).is_ok();
// `self: Self` is always valid.
if can_eq_self(receiver_ty) {
- if let Some(mut err) = fcx.demand_eqtype_with_origin(&cause, self_ty, receiver_ty) {
- err.emit();
+ if let Err(err) = wfcx.equate_types(&cause, wfcx.param_env, self_ty, receiver_ty) {
+ infcx.report_mismatched_types(&cause, self_ty, receiver_ty, err).emit();
}
return true;
}
- let mut autoderef = fcx.autoderef(span, receiver_ty);
+ let mut autoderef =
+ Autoderef::new(infcx, wfcx.param_env, wfcx.body_id, span, receiver_ty, span);
// The `arbitrary_self_types` feature allows raw pointer receivers like `self: *const Self`.
if arbitrary_self_types_enabled {
// The first type is `receiver_ty`, which we know its not equal to `self_ty`; skip it.
autoderef.next();
- let receiver_trait_def_id = fcx.tcx.require_lang_item(LangItem::Receiver, None);
+ let receiver_trait_def_id = tcx.require_lang_item(LangItem::Receiver, None);
// Keep dereferencing `receiver_ty` until we get to `self_ty`.
loop {
);
if can_eq_self(potential_self_ty) {
- fcx.register_predicates(autoderef.into_obligations());
+ wfcx.register_obligations(autoderef.into_obligations());
- if let Some(mut err) =
- fcx.demand_eqtype_with_origin(&cause, self_ty, potential_self_ty)
+ if let Err(err) =
+ wfcx.equate_types(&cause, wfcx.param_env, self_ty, potential_self_ty)
{
- err.emit();
+ infcx.report_mismatched_types(&cause, self_ty, potential_self_ty, err).emit();
}
break;
// deref chain implement `receiver`
if !arbitrary_self_types_enabled
&& !receiver_is_implemented(
- fcx,
+ wfcx,
receiver_trait_def_id,
cause.clone(),
potential_self_ty,
// Without `feature(arbitrary_self_types)`, we require that `receiver_ty` implements `Receiver`.
if !arbitrary_self_types_enabled
- && !receiver_is_implemented(fcx, receiver_trait_def_id, cause.clone(), receiver_ty)
+ && !receiver_is_implemented(wfcx, receiver_trait_def_id, cause.clone(), receiver_ty)
{
return false;
}
}
fn receiver_is_implemented<'tcx>(
- fcx: &FnCtxt<'_, 'tcx>,
+ wfcx: &WfCheckingCtxt<'_, 'tcx>,
receiver_trait_def_id: DefId,
cause: ObligationCause<'tcx>,
receiver_ty: Ty<'tcx>,
) -> bool {
+ let tcx = wfcx.tcx();
let trait_ref = ty::Binder::dummy(ty::TraitRef {
def_id: receiver_trait_def_id,
- substs: fcx.tcx.mk_substs_trait(receiver_ty, &[]),
+ substs: tcx.mk_substs_trait(receiver_ty, &[]),
});
- let obligation = traits::Obligation::new(
- cause,
- fcx.param_env,
- trait_ref.without_const().to_predicate(fcx.tcx),
- );
+ let obligation =
+ traits::Obligation::new(cause, wfcx.param_env, trait_ref.without_const().to_predicate(tcx));
- if fcx.predicate_must_hold_modulo_regions(&obligation) {
+ if wfcx.infcx.predicate_must_hold_modulo_regions(&obligation) {
true
} else {
debug!(
err.emit()
}
-/// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
-/// aren't true.
-fn check_false_global_bounds(fcx: &FnCtxt<'_, '_>, mut span: Span, id: hir::HirId) {
- let empty_env = ty::ParamEnv::empty();
-
- let def_id = fcx.tcx.hir().local_def_id(id);
- let predicates_with_span =
- fcx.tcx.predicates_of(def_id).predicates.iter().map(|(p, span)| (*p, *span));
- // Check elaborated bounds.
- let implied_obligations = traits::elaborate_predicates_with_span(fcx.tcx, predicates_with_span);
+impl<'tcx> WfCheckingCtxt<'_, 'tcx> {
+ /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
+ /// aren't true.
+ fn check_false_global_bounds(&mut self) {
+ let tcx = self.ocx.infcx.tcx;
+ let mut span = self.span;
+ let empty_env = ty::ParamEnv::empty();
+
+ let def_id = tcx.hir().local_def_id(self.body_id);
+ let predicates_with_span = tcx.predicates_of(def_id).predicates.iter().copied();
+ // Check elaborated bounds.
+ let implied_obligations = traits::elaborate_predicates_with_span(tcx, predicates_with_span);
+
+ for obligation in implied_obligations {
+ // We lower empty bounds like `Vec<dyn Copy>:` as
+ // `WellFormed(Vec<dyn Copy>)`, which will later get checked by
+ // regular WF checking
+ if let ty::PredicateKind::WellFormed(..) = obligation.predicate.kind().skip_binder() {
+ continue;
+ }
+ let pred = obligation.predicate;
+ // Match the existing behavior.
+ if pred.is_global() && !pred.has_late_bound_regions() {
+ let pred = self.normalize(span, None, pred);
+ let hir_node = tcx.hir().find(self.body_id);
- for obligation in implied_obligations {
- let pred = obligation.predicate;
- // Match the existing behavior.
- if pred.is_global() && !pred.has_late_bound_regions() {
- let pred = fcx.normalize_associated_types_in(span, pred);
- let hir_node = fcx.tcx.hir().find(id);
+ // only use the span of the predicate clause (#90869)
- // only use the span of the predicate clause (#90869)
+ if let Some(hir::Generics { predicates, .. }) =
+ hir_node.and_then(|node| node.generics())
+ {
+ let obligation_span = obligation.cause.span();
+
+ span = predicates
+ .iter()
+ // There seems to be no better way to find out which predicate we are in
+ .find(|pred| pred.span().contains(obligation_span))
+ .map(|pred| pred.span())
+ .unwrap_or(obligation_span);
+ }
- if let Some(hir::Generics { predicates, .. }) =
- hir_node.and_then(|node| node.generics())
- {
- let obligation_span = obligation.cause.span(fcx.tcx);
-
- span = predicates
- .iter()
- // There seems to be no better way to find out which predicate we are in
- .find(|pred| pred.span().contains(obligation_span))
- .map(|pred| pred.span())
- .unwrap_or(obligation_span);
+ let obligation = traits::Obligation::new(
+ traits::ObligationCause::new(span, self.body_id, traits::TrivialBound),
+ empty_env,
+ pred,
+ );
+ self.ocx.register_obligation(obligation);
}
-
- let obligation = traits::Obligation::new(
- traits::ObligationCause::new(span, id, traits::TrivialBound),
- empty_env,
- pred,
- );
- fcx.register_predicate(obligation);
}
}
-
- fcx.select_all_obligations_or_error();
-}
-
-#[derive(Clone, Copy)]
-pub struct CheckTypeWellFormedVisitor<'tcx> {
- tcx: TyCtxt<'tcx>,
-}
-
-impl<'tcx> CheckTypeWellFormedVisitor<'tcx> {
- pub fn new(tcx: TyCtxt<'tcx>) -> CheckTypeWellFormedVisitor<'tcx> {
- CheckTypeWellFormedVisitor { tcx }
- }
}
-impl<'tcx> ParItemLikeVisitor<'tcx> for CheckTypeWellFormedVisitor<'tcx> {
- fn visit_item(&self, i: &'tcx hir::Item<'tcx>) {
- Visitor::visit_item(&mut self.clone(), i);
- }
-
- fn visit_trait_item(&self, trait_item: &'tcx hir::TraitItem<'tcx>) {
- Visitor::visit_trait_item(&mut self.clone(), trait_item);
- }
-
- fn visit_impl_item(&self, impl_item: &'tcx hir::ImplItem<'tcx>) {
- Visitor::visit_impl_item(&mut self.clone(), impl_item);
- }
-
- fn visit_foreign_item(&self, foreign_item: &'tcx hir::ForeignItem<'tcx>) {
- Visitor::visit_foreign_item(&mut self.clone(), foreign_item)
- }
-}
-
-impl<'tcx> Visitor<'tcx> for CheckTypeWellFormedVisitor<'tcx> {
- type NestedFilter = nested_filter::OnlyBodies;
-
- fn nested_visit_map(&mut self) -> Self::Map {
- self.tcx.hir()
- }
-
- #[instrument(skip(self, i), level = "debug")]
- fn visit_item(&mut self, i: &'tcx hir::Item<'tcx>) {
- trace!(?i);
- self.tcx.ensure().check_item_well_formed(i.def_id);
- hir_visit::walk_item(self, i);
- }
-
- #[instrument(skip(self, trait_item), level = "debug")]
- fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) {
- trace!(?trait_item);
- self.tcx.ensure().check_trait_item_well_formed(trait_item.def_id);
- hir_visit::walk_trait_item(self, trait_item);
- }
-
- #[instrument(skip(self, impl_item), level = "debug")]
- fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) {
- trace!(?impl_item);
- self.tcx.ensure().check_impl_item_well_formed(impl_item.def_id);
- hir_visit::walk_impl_item(self, impl_item);
- }
-
- fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) {
- check_param_wf(self.tcx, p);
- hir_visit::walk_generic_param(self, p);
- }
+fn check_mod_type_wf(tcx: TyCtxt<'_>, module: LocalDefId) {
+ let items = tcx.hir_module_items(module);
+ items.par_items(|item| tcx.ensure().check_well_formed(item.def_id));
+ items.par_impl_items(|item| tcx.ensure().check_well_formed(item.def_id));
+ items.par_trait_items(|item| tcx.ensure().check_well_formed(item.def_id));
+ items.par_foreign_items(|item| tcx.ensure().check_well_formed(item.def_id));
}
///////////////////////////////////////////////////////////////////////////
span: Span,
}
-impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
+impl<'a, 'tcx> WfCheckingCtxt<'a, 'tcx> {
// FIXME(eddyb) replace this with getting fields through `ty::AdtDef`.
fn non_enum_variant(&self, struct_def: &hir::VariantData<'_>) -> AdtVariant<'tcx> {
let fields = struct_def
.fields()
.iter()
.map(|field| {
- let def_id = self.tcx.hir().local_def_id(field.hir_id);
- let field_ty = self.tcx.type_of(def_id);
- let field_ty = self.normalize_associated_types_in(field.ty.span, field_ty);
- let field_ty = self.resolve_vars_if_possible(field_ty);
+ let def_id = self.tcx().hir().local_def_id(field.hir_id);
+ let field_ty = self.tcx().type_of(def_id);
+ let field_ty = self.normalize(field.ty.span, None, field_ty);
debug!("non_enum_variant: type of field {:?} is {:?}", field, field_ty);
AdtField { ty: field_ty, span: field.ty.span, def_id }
})
fields: self.non_enum_variant(&variant.data).fields,
explicit_discr: variant
.disr_expr
- .map(|explicit_discr| self.tcx.hir().local_def_id(explicit_discr.hir_id)),
+ .map(|explicit_discr| self.tcx().hir().local_def_id(explicit_discr.hir_id)),
})
.collect()
}
+}
- pub(super) fn impl_implied_bounds(
- &self,
- impl_def_id: DefId,
- span: Span,
- ) -> FxHashSet<Ty<'tcx>> {
- match self.tcx.impl_trait_ref(impl_def_id) {
+pub fn impl_implied_bounds<'tcx>(
+ tcx: TyCtxt<'tcx>,
+ param_env: ty::ParamEnv<'tcx>,
+ impl_def_id: LocalDefId,
+ span: Span,
+) -> FxHashSet<Ty<'tcx>> {
+ // We completely ignore any obligations caused by normalizing the types
+ // we assume to be well formed. Considering that the user of the implied
+ // bounds will also normalize them, we leave it to them to emit errors
+ // which should result in better causes and spans.
+ tcx.infer_ctxt().enter(|infcx| {
+ let cause = ObligationCause::misc(span, tcx.hir().local_def_id_to_hir_id(impl_def_id));
+ match tcx.impl_trait_ref(impl_def_id) {
Some(trait_ref) => {
// Trait impl: take implied bounds from all types that
// appear in the trait reference.
- let trait_ref = self.normalize_associated_types_in(span, trait_ref);
- trait_ref.substs.types().collect()
+ match infcx.at(&cause, param_env).normalize(trait_ref) {
+ Ok(Normalized { value, obligations: _ }) => value.substs.types().collect(),
+ Err(NoSolution) => FxHashSet::default(),
+ }
}
None => {
// Inherent impl: take implied bounds from the `self` type.
- let self_ty = self.tcx.type_of(impl_def_id);
- let self_ty = self.normalize_associated_types_in(span, self_ty);
- FxHashSet::from_iter([self_ty])
+ let self_ty = tcx.type_of(impl_def_id);
+ match infcx.at(&cause, param_env).normalize(self_ty) {
+ Ok(Normalized { value, obligations: _ }) => FxHashSet::from_iter([value]),
+ Err(NoSolution) => FxHashSet::default(),
+ }
}
}
- }
+ })
}
fn error_392(
err.span_label(span, "unused parameter");
err
}
+
+pub fn provide(providers: &mut Providers) {
+ *providers = Providers { check_mod_type_wf, check_well_formed, ..*providers };
+}