Revert "Better errors for implied static bound"

This reverts commit c75817b0a7.
This commit is contained in:
Jack Huey 2022-09-16 09:47:07 -04:00
parent bba514b7b4
commit 92b759f517
22 changed files with 98 additions and 330 deletions

View File

@ -15,7 +15,7 @@ use rustc_middle::ty::{self, RegionVid, TyCtxt};
use rustc_span::symbol::{kw, Symbol};
use rustc_span::{sym, DesugaringKind, Span};
use crate::region_infer::{BlameConstraint, ExtraConstraintInfo};
use crate::region_infer::BlameConstraint;
use crate::{
borrow_set::BorrowData, nll::ConstraintDescription, region_infer::Cause, MirBorrowckCtxt,
WriteKind,
@ -38,7 +38,6 @@ pub(crate) enum BorrowExplanation<'tcx> {
span: Span,
region_name: RegionName,
opt_place_desc: Option<String>,
extra_info: Vec<ExtraConstraintInfo>,
},
Unexplained,
}
@ -244,7 +243,6 @@ impl<'tcx> BorrowExplanation<'tcx> {
ref region_name,
ref opt_place_desc,
from_closure: _,
ref extra_info,
} => {
region_name.highlight_region_name(err);
@ -270,14 +268,6 @@ impl<'tcx> BorrowExplanation<'tcx> {
);
};
for extra in extra_info {
match extra {
ExtraConstraintInfo::PlaceholderFromPredicate(span) => {
err.span_note(*span, format!("due to current limitations in the borrow checker, this implies a `'static` lifetime"));
}
}
}
self.add_lifetime_bound_suggestion_to_diagnostic(err, &category, span, region_name);
}
_ => {}
@ -319,17 +309,16 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
&self,
borrow_region: RegionVid,
outlived_region: RegionVid,
) -> (ConstraintCategory<'tcx>, bool, Span, Option<RegionName>, Vec<ExtraConstraintInfo>) {
let (blame_constraint, extra_info) = self.regioncx.best_blame_constraint(
borrow_region,
NllRegionVariableOrigin::FreeRegion,
|r| self.regioncx.provides_universal_region(r, borrow_region, outlived_region),
);
let BlameConstraint { category, from_closure, cause, .. } = blame_constraint;
) -> (ConstraintCategory<'tcx>, bool, Span, Option<RegionName>) {
let BlameConstraint { category, from_closure, cause, variance_info: _ } = self
.regioncx
.best_blame_constraint(borrow_region, NllRegionVariableOrigin::FreeRegion, |r| {
self.regioncx.provides_universal_region(r, borrow_region, outlived_region)
});
let outlived_fr_name = self.give_region_a_name(outlived_region);
(category, from_closure, cause.span, outlived_fr_name, extra_info)
(category, from_closure, cause.span, outlived_fr_name)
}
/// Returns structured explanation for *why* the borrow contains the
@ -401,7 +390,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
None => {
if let Some(region) = self.to_error_region_vid(borrow_region_vid) {
let (category, from_closure, span, region_name, extra_info) =
let (category, from_closure, span, region_name) =
self.free_region_constraint_info(borrow_region_vid, region);
if let Some(region_name) = region_name {
let opt_place_desc = self.describe_place(borrow.borrowed_place.as_ref());
@ -411,7 +400,6 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
span,
region_name,
opt_place_desc,
extra_info,
}
} else {
debug!("Could not generate a region name");

View File

@ -354,12 +354,10 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
) {
debug!("report_region_error(fr={:?}, outlived_fr={:?})", fr, outlived_fr);
let BlameConstraint { category, cause, variance_info, .. } = self
.regioncx
.best_blame_constraint(fr, fr_origin, |r| {
let BlameConstraint { category, cause, variance_info, from_closure: _ } =
self.regioncx.best_blame_constraint(fr, fr_origin, |r| {
self.regioncx.provides_universal_region(r, fr, outlived_fr)
})
.0;
});
debug!("report_region_error: category={:?} {:?} {:?}", category, cause, variance_info);

View File

@ -245,11 +245,6 @@ enum Trace<'tcx> {
NotVisited,
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum ExtraConstraintInfo {
PlaceholderFromPredicate(Span),
}
impl<'tcx> RegionInferenceContext<'tcx> {
/// Creates a new region inference context with a total of
/// `num_region_variables` valid inference variables; the first N
@ -1823,9 +1818,10 @@ impl<'tcx> RegionInferenceContext<'tcx> {
fr1_origin: NllRegionVariableOrigin,
fr2: RegionVid,
) -> (ConstraintCategory<'tcx>, ObligationCause<'tcx>) {
let BlameConstraint { category, cause, .. } = self
.best_blame_constraint(fr1, fr1_origin, |r| self.provides_universal_region(r, fr1, fr2))
.0;
let BlameConstraint { category, cause, .. } =
self.best_blame_constraint(fr1, fr1_origin, |r| {
self.provides_universal_region(r, fr1, fr2)
});
(category, cause)
}
@ -2014,7 +2010,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {
from_region: RegionVid,
from_region_origin: NllRegionVariableOrigin,
target_test: impl Fn(RegionVid) -> bool,
) -> (BlameConstraint<'tcx>, Vec<ExtraConstraintInfo>) {
) -> BlameConstraint<'tcx> {
// Find all paths
let (path, target_region) =
self.find_constraint_paths_between_regions(from_region, target_test).unwrap();
@ -2030,18 +2026,6 @@ impl<'tcx> RegionInferenceContext<'tcx> {
.collect::<Vec<_>>()
);
let mut extra_info = vec![];
for constraint in path.iter() {
let outlived = constraint.sub;
let Some(origin) = self.var_infos.get(outlived) else { continue; };
let RegionVariableOrigin::Nll(NllRegionVariableOrigin::Placeholder(p)) = origin.origin else { continue; };
debug!(?constraint, ?p);
let ConstraintCategory::Predicate(span) = constraint.category else { continue; };
extra_info.push(ExtraConstraintInfo::PlaceholderFromPredicate(span));
// We only want to point to one
break;
}
// We try to avoid reporting a `ConstraintCategory::Predicate` as our best constraint.
// Instead, we use it to produce an improved `ObligationCauseCode`.
// FIXME - determine what we should do if we encounter multiple `ConstraintCategory::Predicate`
@ -2089,7 +2073,6 @@ impl<'tcx> RegionInferenceContext<'tcx> {
from_closure,
cause: ObligationCause::new(span, CRATE_HIR_ID, cause_code),
variance_info: constraint.variance_info,
outlives_constraint: *constraint,
}
})
.collect();
@ -2191,7 +2174,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {
let best_choice =
if blame_source { range.rev().find(find_region) } else { range.find(find_region) };
debug!(?best_choice, ?blame_source, ?extra_info);
debug!(?best_choice, ?blame_source);
if let Some(i) = best_choice {
if let Some(next) = categorized_path.get(i + 1) {
@ -2200,7 +2183,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {
{
// The return expression is being influenced by the return type being
// impl Trait, point at the return type and not the return expr.
return (next.clone(), extra_info);
return next.clone();
}
}
@ -2220,7 +2203,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {
}
}
return (categorized_path[i].clone(), extra_info);
return categorized_path[i].clone();
}
// If that search fails, that is.. unusual. Maybe everything
@ -2230,7 +2213,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {
categorized_path.sort_by(|p0, p1| p0.category.cmp(&p1.category));
debug!("sorted_path={:#?}", categorized_path);
(categorized_path.remove(0), extra_info)
categorized_path.remove(0)
}
pub(crate) fn universe_info(&self, universe: ty::UniverseIndex) -> UniverseInfo<'tcx> {
@ -2312,13 +2295,7 @@ impl<'tcx> ClosureRegionRequirementsExt<'tcx> for ClosureRegionRequirements<'tcx
outlives_requirement={:?}",
region, outlived_region, outlives_requirement,
);
(
ty::Binder::dummy(ty::OutlivesPredicate(
region.into(),
outlived_region,
)),
ConstraintCategory::BoringNoLocation,
)
ty::Binder::dummy(ty::OutlivesPredicate(region.into(), outlived_region))
}
ClosureOutlivesSubject::Ty(ty) => {
@ -2328,10 +2305,7 @@ impl<'tcx> ClosureRegionRequirementsExt<'tcx> for ClosureRegionRequirements<'tcx
outlives_requirement={:?}",
ty, outlived_region, outlives_requirement,
);
(
ty::Binder::dummy(ty::OutlivesPredicate(ty.into(), outlived_region)),
ConstraintCategory::BoringNoLocation,
)
ty::Binder::dummy(ty::OutlivesPredicate(ty.into(), outlived_region))
}
}
})
@ -2345,5 +2319,4 @@ pub struct BlameConstraint<'tcx> {
pub from_closure: bool,
pub cause: ObligationCause<'tcx>,
pub variance_info: ty::VarianceDiagInfo<'tcx>,
pub outlives_constraint: OutlivesConstraint<'tcx>,
}

View File

@ -25,7 +25,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
/// constraints should occur within this method so that those
/// constraints can be properly localized!**
#[instrument(skip(self, op), level = "trace")]
pub(super) fn fully_perform_op<R: fmt::Debug, Op>(
pub(super) fn fully_perform_op<R, Op>(
&mut self,
locations: Locations,
category: ConstraintCategory<'tcx>,
@ -39,8 +39,6 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
let TypeOpOutput { output, constraints, error_info } = op.fully_perform(self.infcx)?;
debug!(?output, ?constraints);
if let Some(data) = constraints {
self.push_region_constraints(locations, category, data);
}

View File

@ -86,7 +86,7 @@ impl<'a, 'tcx> ConstraintConversion<'a, 'tcx> {
}
}
fn convert(&mut self, query_constraint: &QueryOutlivesConstraint<'tcx>) {
pub(super) fn convert(&mut self, query_constraint: &QueryOutlivesConstraint<'tcx>) {
debug!("generate: constraints at: {:#?}", self.locations);
// Extract out various useful fields we'll need below.
@ -98,18 +98,15 @@ impl<'a, 'tcx> ConstraintConversion<'a, 'tcx> {
// region constraints like `for<'a> 'a: 'b`. At some point
// when we move to universes, we will, and this assertion
// will start to fail.
let ty::OutlivesPredicate(k1, r2) =
query_constraint.0.no_bound_vars().unwrap_or_else(|| {
bug!("query_constraint {:?} contained bound vars", query_constraint,);
});
let constraint_category = query_constraint.1;
let ty::OutlivesPredicate(k1, r2) = query_constraint.no_bound_vars().unwrap_or_else(|| {
bug!("query_constraint {:?} contained bound vars", query_constraint,);
});
match k1.unpack() {
GenericArgKind::Lifetime(r1) => {
let r1_vid = self.to_region_vid(r1);
let r2_vid = self.to_region_vid(r2);
self.add_outlives(r1_vid, r2_vid, constraint_category);
self.add_outlives(r1_vid, r2_vid);
}
GenericArgKind::Type(t1) => {
@ -124,7 +121,7 @@ impl<'a, 'tcx> ConstraintConversion<'a, 'tcx> {
Some(implicit_region_bound),
param_env,
)
.type_must_outlive(origin, t1, r2, constraint_category);
.type_must_outlive(origin, t1, r2);
}
GenericArgKind::Const(_) => {
@ -171,19 +168,10 @@ impl<'a, 'tcx> ConstraintConversion<'a, 'tcx> {
}
}
fn add_outlives(
&mut self,
sup: ty::RegionVid,
sub: ty::RegionVid,
category: ConstraintCategory<'tcx>,
) {
let category = match self.category {
ConstraintCategory::Boring | ConstraintCategory::BoringNoLocation => category,
_ => self.category,
};
fn add_outlives(&mut self, sup: ty::RegionVid, sub: ty::RegionVid) {
self.constraints.outlives_constraints.push(OutlivesConstraint {
locations: self.locations,
category,
category: self.category,
span: self.span,
sub,
sup,
@ -203,11 +191,10 @@ impl<'a, 'b, 'tcx> TypeOutlivesDelegate<'tcx> for &'a mut ConstraintConversion<'
_origin: SubregionOrigin<'tcx>,
a: ty::Region<'tcx>,
b: ty::Region<'tcx>,
constraint_category: ConstraintCategory<'tcx>,
) {
let b = self.to_region_vid(b);
let a = self.to_region_vid(a);
self.add_outlives(b, a, constraint_category);
self.add_outlives(b, a);
}
fn push_verify(

View File

@ -2591,7 +2591,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
.enumerate()
.filter_map(|(idx, constraint)| {
let ty::OutlivesPredicate(k1, r2) =
constraint.0.no_bound_vars().unwrap_or_else(|| {
constraint.no_bound_vars().unwrap_or_else(|| {
bug!("query_constraint {:?} contained bound vars", constraint,);
});

View File

@ -110,7 +110,6 @@ infer_relate_param_bound = ...so that the type `{$name}` will meet its required
infer_relate_param_bound_2 = ...that is required by this bound
infer_relate_region_param_bound = ...so that the declared lifetime parameter bounds are satisfied
infer_compare_impl_item_obligation = ...so that the definition in impl matches the definition from the trait
infer_ascribe_user_type_prove_predicate = ...so that the where clause holds
infer_nothing = {""}

View File

@ -22,7 +22,6 @@ use rustc_data_structures::captures::Captures;
use rustc_index::vec::Idx;
use rustc_index::vec::IndexVec;
use rustc_middle::arena::ArenaAllocatable;
use rustc_middle::mir::ConstraintCategory;
use rustc_middle::ty::error::TypeError;
use rustc_middle::ty::fold::TypeFoldable;
use rustc_middle::ty::relate::TypeRelation;
@ -130,9 +129,7 @@ impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
let region_constraints = self.with_region_constraints(|region_constraints| {
make_query_region_constraints(
tcx,
region_obligations
.iter()
.map(|r_o| (r_o.sup_type, r_o.sub_region, r_o.origin.to_constraint_category())),
region_obligations.iter().map(|r_o| (r_o.sup_type, r_o.sub_region)),
region_constraints,
)
});
@ -251,8 +248,6 @@ impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
// the original values `v_o` that was canonicalized into a
// variable...
let constraint_category = cause.to_constraint_category();
for (index, original_value) in original_values.var_values.iter().enumerate() {
// ...with the value `v_r` of that variable from the query.
let result_value = query_response.substitute_projected(self.tcx, &result_subst, |v| {
@ -268,14 +263,12 @@ impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
(GenericArgKind::Lifetime(v_o), GenericArgKind::Lifetime(v_r)) => {
// To make `v_o = v_r`, we emit `v_o: v_r` and `v_r: v_o`.
if v_o != v_r {
output_query_region_constraints.outlives.push((
ty::Binder::dummy(ty::OutlivesPredicate(v_o.into(), v_r)),
constraint_category,
));
output_query_region_constraints.outlives.push((
ty::Binder::dummy(ty::OutlivesPredicate(v_r.into(), v_o)),
constraint_category,
));
output_query_region_constraints
.outlives
.push(ty::Binder::dummy(ty::OutlivesPredicate(v_o.into(), v_r)));
output_query_region_constraints
.outlives
.push(ty::Binder::dummy(ty::OutlivesPredicate(v_r.into(), v_o)));
}
}
@ -321,7 +314,7 @@ impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
// Screen out `'a: 'a` cases -- we skip the binder here but
// only compare the inner values to one another, so they are still at
// consistent binding levels.
let ty::OutlivesPredicate(k1, r2) = r_c.0.skip_binder();
let ty::OutlivesPredicate(k1, r2) = r_c.skip_binder();
if k1 != r2.into() { Some(r_c) } else { None }
}),
);
@ -566,7 +559,7 @@ impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
cause: ObligationCause<'tcx>,
param_env: ty::ParamEnv<'tcx>,
) -> Obligation<'tcx, ty::Predicate<'tcx>> {
let ty::OutlivesPredicate(k1, r2) = predicate.0.skip_binder();
let ty::OutlivesPredicate(k1, r2) = predicate.skip_binder();
let atom = match k1.unpack() {
GenericArgKind::Lifetime(r1) => {
@ -581,7 +574,7 @@ impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
span_bug!(cause.span, "unexpected const outlives {:?}", predicate);
}
};
let predicate = predicate.0.rebind(atom).to_predicate(self.tcx);
let predicate = predicate.rebind(atom).to_predicate(self.tcx);
Obligation::new(cause, param_env, predicate)
}
@ -632,7 +625,7 @@ impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
/// creates query region constraints.
pub fn make_query_region_constraints<'tcx>(
tcx: TyCtxt<'tcx>,
outlives_obligations: impl Iterator<Item = (Ty<'tcx>, ty::Region<'tcx>, ConstraintCategory<'tcx>)>,
outlives_obligations: impl Iterator<Item = (Ty<'tcx>, ty::Region<'tcx>)>,
region_constraints: &RegionConstraintData<'tcx>,
) -> QueryRegionConstraints<'tcx> {
let RegionConstraintData { constraints, verifys, givens, member_constraints } =
@ -645,31 +638,26 @@ pub fn make_query_region_constraints<'tcx>(
let outlives: Vec<_> = constraints
.iter()
.map(|(k, origin)| {
// no bound vars in the code above
let constraint = ty::Binder::dummy(match *k {
// Swap regions because we are going from sub (<=) to outlives
// (>=).
Constraint::VarSubVar(v1, v2) => ty::OutlivesPredicate(
tcx.mk_region(ty::ReVar(v2)).into(),
tcx.mk_region(ty::ReVar(v1)),
),
Constraint::VarSubReg(v1, r2) => {
ty::OutlivesPredicate(r2.into(), tcx.mk_region(ty::ReVar(v1)))
}
Constraint::RegSubVar(r1, v2) => {
ty::OutlivesPredicate(tcx.mk_region(ty::ReVar(v2)).into(), r1)
}
Constraint::RegSubReg(r1, r2) => ty::OutlivesPredicate(r2.into(), r1),
});
(constraint, origin.to_constraint_category())
.map(|(k, _)| match *k {
// Swap regions because we are going from sub (<=) to outlives
// (>=).
Constraint::VarSubVar(v1, v2) => ty::OutlivesPredicate(
tcx.mk_region(ty::ReVar(v2)).into(),
tcx.mk_region(ty::ReVar(v1)),
),
Constraint::VarSubReg(v1, r2) => {
ty::OutlivesPredicate(r2.into(), tcx.mk_region(ty::ReVar(v1)))
}
Constraint::RegSubVar(r1, v2) => {
ty::OutlivesPredicate(tcx.mk_region(ty::ReVar(v2)).into(), r1)
}
Constraint::RegSubReg(r1, r2) => ty::OutlivesPredicate(r2.into(), r1),
})
.map(ty::Binder::dummy) // no bound vars in the code above
.chain(
outlives_obligations
// no bound vars in the code above
.map(|(ty, r, constraint_category)| {
(ty::Binder::dummy(ty::OutlivesPredicate(ty.into(), r)), constraint_category)
}),
.map(|(ty, r)| ty::OutlivesPredicate(ty.into(), r))
.map(ty::Binder::dummy), // no bound vars in the code above
)
.collect();

View File

@ -77,13 +77,6 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
infer::CheckAssociatedTypeBounds { ref parent, .. } => {
self.note_region_origin(err, &parent);
}
infer::AscribeUserTypeProvePredicate(span) => {
RegionOriginNote::Plain {
span,
msg: fluent::infer::ascribe_user_type_prove_predicate,
}
.add_to_diagnostic(err);
}
}
}
@ -363,27 +356,6 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
err
}
infer::AscribeUserTypeProvePredicate(span) => {
let mut err =
struct_span_err!(self.tcx.sess, span, E0478, "lifetime bound not satisfied");
note_and_explain_region(
self.tcx,
&mut err,
"lifetime instantiated with ",
sup,
"",
None,
);
note_and_explain_region(
self.tcx,
&mut err,
"but lifetime must outlive ",
sub,
"",
None,
);
err
}
}
}

View File

@ -20,7 +20,6 @@ use rustc_middle::infer::canonical::{Canonical, CanonicalVarValues};
use rustc_middle::infer::unify_key::{ConstVarValue, ConstVariableValue};
use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind, ToType};
use rustc_middle::mir::interpret::{ErrorHandled, EvalToValTreeResult};
use rustc_middle::mir::ConstraintCategory;
use rustc_middle::traits::select;
use rustc_middle::ty::abstract_const::{AbstractConst, FailureKind};
use rustc_middle::ty::error::{ExpectedFound, TypeError};
@ -409,11 +408,7 @@ pub enum SubregionOrigin<'tcx> {
/// Comparing the signature and requirements of an impl method against
/// the containing trait.
CompareImplItemObligation {
span: Span,
impl_item_def_id: LocalDefId,
trait_item_def_id: DefId,
},
CompareImplItemObligation { span: Span, impl_item_def_id: LocalDefId, trait_item_def_id: DefId },
/// Checking that the bounds of a trait's associated type hold for a given impl
CheckAssociatedTypeBounds {
@ -421,24 +416,12 @@ pub enum SubregionOrigin<'tcx> {
impl_item_def_id: LocalDefId,
trait_item_def_id: DefId,
},
AscribeUserTypeProvePredicate(Span),
}
// `SubregionOrigin` is used a lot. Make sure it doesn't unintentionally get bigger.
#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
static_assert_size!(SubregionOrigin<'_>, 32);
impl<'tcx> SubregionOrigin<'tcx> {
pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
match self {
Self::Subtype(type_trace) => type_trace.cause.to_constraint_category(),
Self::AscribeUserTypeProvePredicate(span) => ConstraintCategory::Predicate(*span),
_ => ConstraintCategory::BoringNoLocation,
}
}
}
/// Times when we replace late-bound regions with variables:
#[derive(Clone, Copy, Debug)]
pub enum LateBoundRegionConversionTime {
@ -2008,7 +1991,6 @@ impl<'tcx> SubregionOrigin<'tcx> {
DataBorrowed(_, a) => a,
ReferenceOutlivesReferent(_, a) => a,
CompareImplItemObligation { span, .. } => span,
AscribeUserTypeProvePredicate(span) => span,
CheckAssociatedTypeBounds { ref parent, .. } => parent.span(),
}
}
@ -2041,10 +2023,6 @@ impl<'tcx> SubregionOrigin<'tcx> {
parent: Box::new(default()),
},
traits::ObligationCauseCode::AscribeUserTypeProvePredicate(span) => {
SubregionOrigin::AscribeUserTypeProvePredicate(span)
}
_ => default(),
}
}

View File

@ -69,7 +69,6 @@ use crate::infer::{
use crate::traits::{ObligationCause, ObligationCauseCode};
use rustc_data_structures::undo_log::UndoLogs;
use rustc_hir::def_id::LocalDefId;
use rustc_middle::mir::ConstraintCategory;
use rustc_middle::ty::subst::GenericArgKind;
use rustc_middle::ty::{self, Region, Ty, TyCtxt, TypeVisitable};
use smallvec::smallvec;
@ -164,8 +163,7 @@ impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
let outlives =
&mut TypeOutlives::new(self, self.tcx, &region_bound_pairs, None, param_env);
let category = origin.to_constraint_category();
outlives.type_must_outlive(origin, sup_type, sub_region, category);
outlives.type_must_outlive(origin, sup_type, sub_region);
}
}
@ -209,7 +207,6 @@ pub trait TypeOutlivesDelegate<'tcx> {
origin: SubregionOrigin<'tcx>,
a: ty::Region<'tcx>,
b: ty::Region<'tcx>,
constraint_category: ConstraintCategory<'tcx>,
);
fn push_verify(
@ -258,13 +255,12 @@ where
origin: infer::SubregionOrigin<'tcx>,
ty: Ty<'tcx>,
region: ty::Region<'tcx>,
category: ConstraintCategory<'tcx>,
) {
assert!(!ty.has_escaping_bound_vars());
let mut components = smallvec![];
push_outlives_components(self.tcx, ty, &mut components);
self.components_must_outlive(origin, &components, region, category);
self.components_must_outlive(origin, &components, region);
}
fn components_must_outlive(
@ -272,13 +268,12 @@ where
origin: infer::SubregionOrigin<'tcx>,
components: &[Component<'tcx>],
region: ty::Region<'tcx>,
category: ConstraintCategory<'tcx>,
) {
for component in components.iter() {
let origin = origin.clone();
match component {
Component::Region(region1) => {
self.delegate.push_sub_region_constraint(origin, region, *region1, category);
self.delegate.push_sub_region_constraint(origin, region, *region1);
}
Component::Param(param_ty) => {
self.param_ty_must_outlive(origin, region, *param_ty);
@ -287,7 +282,7 @@ where
self.projection_must_outlive(origin, region, *projection_ty);
}
Component::EscapingProjection(subcomponents) => {
self.components_must_outlive(origin, &subcomponents, region, category);
self.components_must_outlive(origin, &subcomponents, region);
}
Component::UnresolvedInferenceVariable(v) => {
// ignore this, we presume it will yield an error
@ -397,20 +392,10 @@ where
for k in projection_ty.substs {
match k.unpack() {
GenericArgKind::Lifetime(lt) => {
self.delegate.push_sub_region_constraint(
origin.clone(),
region,
lt,
origin.to_constraint_category(),
);
self.delegate.push_sub_region_constraint(origin.clone(), region, lt);
}
GenericArgKind::Type(ty) => {
self.type_must_outlive(
origin.clone(),
ty,
region,
origin.to_constraint_category(),
);
self.type_must_outlive(origin.clone(), ty, region);
}
GenericArgKind::Const(_) => {
// Const parameters don't impose constraints.
@ -448,8 +433,7 @@ where
let unique_bound = trait_bounds[0];
debug!("projection_must_outlive: unique trait bound = {:?}", unique_bound);
debug!("projection_must_outlive: unique declared bound appears in trait ref");
let category = origin.to_constraint_category();
self.delegate.push_sub_region_constraint(origin, region, unique_bound, category);
self.delegate.push_sub_region_constraint(origin, region, unique_bound);
return;
}
@ -471,7 +455,6 @@ impl<'cx, 'tcx> TypeOutlivesDelegate<'tcx> for &'cx InferCtxt<'cx, 'tcx> {
origin: SubregionOrigin<'tcx>,
a: ty::Region<'tcx>,
b: ty::Region<'tcx>,
_constraint_category: ConstraintCategory<'tcx>,
) {
self.sub_regions(origin, a, b)
}

View File

@ -22,7 +22,6 @@
//! [c]: https://rust-lang.github.io/chalk/book/canonical_queries/canonicalization.html
use crate::infer::MemberConstraint;
use crate::mir::ConstraintCategory;
use crate::ty::subst::GenericArg;
use crate::ty::{self, BoundVar, List, Region, Ty, TyCtxt};
use rustc_index::vec::IndexVec;
@ -302,10 +301,8 @@ impl<'tcx, V> Canonical<'tcx, V> {
}
}
pub type QueryOutlivesConstraint<'tcx> = (
ty::Binder<'tcx, ty::OutlivesPredicate<GenericArg<'tcx>, Region<'tcx>>>,
ConstraintCategory<'tcx>,
);
pub type QueryOutlivesConstraint<'tcx> =
ty::Binder<'tcx, ty::OutlivesPredicate<GenericArg<'tcx>, Region<'tcx>>>;
TrivialTypeTraversalAndLiftImpls! {
for <'tcx> {

View File

@ -327,7 +327,7 @@ rustc_data_structures::static_assert_size!(ConstraintCategory<'_>, 16);
///
/// See also `rustc_const_eval::borrow_check::constraints`.
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash)]
#[derive(TyEncodable, TyDecodable, HashStable, Lift, TypeVisitable, TypeFoldable)]
#[derive(TyEncodable, TyDecodable, HashStable)]
pub enum ConstraintCategory<'tcx> {
Return(ReturnConstraint),
Yield,
@ -369,7 +369,7 @@ pub enum ConstraintCategory<'tcx> {
}
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash)]
#[derive(TyEncodable, TyDecodable, HashStable, TypeVisitable, TypeFoldable)]
#[derive(TyEncodable, TyDecodable, HashStable)]
pub enum ReturnConstraint {
Normal,
ClosureUpvar(Field),

View File

@ -10,7 +10,6 @@ mod structural_impls;
pub mod util;
use crate::infer::canonical::Canonical;
use crate::mir::ConstraintCategory;
use crate::ty::abstract_const::NotConstEvaluatable;
use crate::ty::subst::SubstsRef;
use crate::ty::{self, AdtKind, Ty, TyCtxt};
@ -184,16 +183,6 @@ impl<'tcx> ObligationCause<'tcx> {
variant(DerivedObligationCause { parent_trait_pred, parent_code: self.code }).into();
self
}
pub fn to_constraint_category(&self) -> ConstraintCategory<'tcx> {
match self.code() {
MatchImpl(cause, _) => cause.to_constraint_category(),
AscribeUserTypeProvePredicate(predicate_span) => {
ConstraintCategory::Predicate(*predicate_span)
}
_ => ConstraintCategory::BoringNoLocation,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Lift)]
@ -429,8 +418,6 @@ pub enum ObligationCauseCode<'tcx> {
is_lit: bool,
output_ty: Option<Ty<'tcx>>,
},
AscribeUserTypeProvePredicate(Span),
}
/// The 'location' at which we try to perform HIR-based wf checking.

View File

@ -2256,8 +2256,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
| ObligationCauseCode::QuestionMark
| ObligationCauseCode::CheckAssociatedTypeBounds { .. }
| ObligationCauseCode::LetElse
| ObligationCauseCode::BinOp { .. }
| ObligationCauseCode::AscribeUserTypeProvePredicate(..) => {}
| ObligationCauseCode::BinOp { .. } => {}
ObligationCauseCode::SliceOrArrayElem => {
err.note("slice and array elements must have `Sized` type");
}

View File

@ -23,7 +23,7 @@ impl<F, G> CustomTypeOp<F, G> {
}
}
impl<'tcx, F, R: fmt::Debug, G> super::TypeOp<'tcx> for CustomTypeOp<F, G>
impl<'tcx, F, R, G> super::TypeOp<'tcx> for CustomTypeOp<F, G>
where
F: for<'a, 'cx> FnOnce(&'a InferCtxt<'cx, 'tcx>) -> Fallible<InferOk<'tcx, R>>,
G: Fn() -> String,
@ -89,8 +89,8 @@ pub fn scrape_region_constraints<'tcx, Op: super::TypeOp<'tcx, Output = R>, R>(
infcx.tcx,
region_obligations
.iter()
.map(|r_o| (r_o.sup_type, r_o.sub_region, r_o.origin.to_constraint_category()))
.map(|(ty, r, cc)| (infcx.resolve_vars_if_possible(ty), r, cc)),
.map(|r_o| (r_o.sup_type, r_o.sub_region))
.map(|(ty, r)| (infcx.resolve_vars_if_possible(ty), r)),
&region_constraint_data,
);

View File

@ -26,7 +26,7 @@ pub use rustc_middle::traits::query::type_op::*;
/// extract out the resulting region constraints (or an error if it
/// cannot be completed).
pub trait TypeOp<'tcx>: Sized + fmt::Debug {
type Output: fmt::Debug;
type Output;
type ErrorInfo;
/// Processes the operation and all resulting obligations,

View File

@ -3,7 +3,7 @@ use rustc_hir::def_id::DefId;
use rustc_infer::infer::at::ToTrace;
use rustc_infer::infer::canonical::{Canonical, QueryResponse};
use rustc_infer::infer::{DefiningAnchor, InferCtxt, TyCtxtInferExt};
use rustc_infer::traits::{ObligationCauseCode, TraitEngineExt as _};
use rustc_infer::traits::TraitEngineExt as _;
use rustc_middle::ty::query::Providers;
use rustc_middle::ty::subst::{GenericArg, Subst, UserSelfTy, UserSubsts};
use rustc_middle::ty::{
@ -22,7 +22,6 @@ use rustc_trait_selection::traits::query::type_op::subtype::Subtype;
use rustc_trait_selection::traits::query::{Fallible, NoSolution};
use rustc_trait_selection::traits::{Normalized, Obligation, ObligationCause, TraitEngine};
use std::fmt;
use std::iter::zip;
pub(crate) fn provide(p: &mut Providers) {
*p = Providers {
@ -62,15 +61,14 @@ pub fn type_op_ascribe_user_type_with_span<'a, 'tcx: 'a>(
mir_ty, def_id, user_substs
);
let mut cx = AscribeUserTypeCx { infcx, param_env, span: span.unwrap_or(DUMMY_SP), fulfill_cx };
cx.relate_mir_and_user_ty(mir_ty, def_id, user_substs)?;
let mut cx = AscribeUserTypeCx { infcx, param_env, fulfill_cx };
cx.relate_mir_and_user_ty(mir_ty, def_id, user_substs, span)?;
Ok(())
}
struct AscribeUserTypeCx<'me, 'tcx> {
infcx: &'me InferCtxt<'me, 'tcx>,
param_env: ParamEnv<'tcx>,
span: Span,
fulfill_cx: &'me mut dyn TraitEngine<'tcx>,
}
@ -81,7 +79,7 @@ impl<'me, 'tcx> AscribeUserTypeCx<'me, 'tcx> {
{
self.infcx
.partially_normalize_associated_types_in(
ObligationCause::misc(self.span, hir::CRATE_HIR_ID),
ObligationCause::misc(DUMMY_SP, hir::CRATE_HIR_ID),
self.param_env,
value,
)
@ -93,13 +91,18 @@ impl<'me, 'tcx> AscribeUserTypeCx<'me, 'tcx> {
T: ToTrace<'tcx>,
{
self.infcx
.at(&ObligationCause::dummy_with_span(self.span), self.param_env)
.at(&ObligationCause::dummy(), self.param_env)
.relate(a, variance, b)?
.into_value_registering_obligations(self.infcx, self.fulfill_cx);
Ok(())
}
fn prove_predicate(&mut self, predicate: Predicate<'tcx>, cause: ObligationCause<'tcx>) {
fn prove_predicate(&mut self, predicate: Predicate<'tcx>, span: Option<Span>) {
let cause = if let Some(span) = span {
ObligationCause::dummy_with_span(span)
} else {
ObligationCause::dummy()
};
self.fulfill_cx.register_predicate_obligation(
self.infcx,
Obligation::new(cause, self.param_env, predicate),
@ -123,6 +126,7 @@ impl<'me, 'tcx> AscribeUserTypeCx<'me, 'tcx> {
mir_ty: Ty<'tcx>,
def_id: DefId,
user_substs: UserSubsts<'tcx>,
span: Option<Span>,
) -> Result<(), NoSolution> {
let UserSubsts { user_self_ty, substs } = user_substs;
let tcx = self.tcx();
@ -141,20 +145,10 @@ impl<'me, 'tcx> AscribeUserTypeCx<'me, 'tcx> {
// outlives" error messages.
let instantiated_predicates =
self.tcx().predicates_of(def_id).instantiate(self.tcx(), substs);
let cause = ObligationCause::dummy_with_span(self.span);
debug!(?instantiated_predicates);
for (instantiated_predicate, predicate_span) in
zip(instantiated_predicates.predicates, instantiated_predicates.spans)
{
let span = if self.span == DUMMY_SP { predicate_span } else { self.span };
let cause = ObligationCause::new(
span,
hir::CRATE_HIR_ID,
ObligationCauseCode::AscribeUserTypeProvePredicate(predicate_span),
);
self.prove_predicate(instantiated_predicate, cause);
for instantiated_predicate in instantiated_predicates.predicates {
let instantiated_predicate = self.normalize(instantiated_predicate);
self.prove_predicate(instantiated_predicate, span);
}
if let Some(UserSelfTy { impl_def_id, self_ty }) = user_self_ty {
@ -167,7 +161,7 @@ impl<'me, 'tcx> AscribeUserTypeCx<'me, 'tcx> {
self.prove_predicate(
ty::Binder::dummy(ty::PredicateKind::WellFormed(impl_self_ty.into()))
.to_predicate(self.tcx()),
cause.clone(),
span,
);
}
@ -184,7 +178,7 @@ impl<'me, 'tcx> AscribeUserTypeCx<'me, 'tcx> {
// which...could happen with normalization...
self.prove_predicate(
ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into())).to_predicate(self.tcx()),
cause,
span,
);
Ok(())
}

View File

@ -10,7 +10,6 @@ use rustc_hir::ItemKind;
use rustc_infer::infer::outlives::env::{OutlivesEnvironment, RegionBoundPairs};
use rustc_infer::infer::outlives::obligations::TypeOutlives;
use rustc_infer::infer::{self, InferCtxt, TyCtxtInferExt};
use rustc_middle::mir::ConstraintCategory;
use rustc_middle::ty::query::Providers;
use rustc_middle::ty::subst::{GenericArgKind, InternalSubsts, Subst};
use rustc_middle::ty::trait_def::TraitSpecializationKind;
@ -664,7 +663,7 @@ fn ty_known_to_outlive<'tcx>(
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, None, param_env);
outlives.type_must_outlive(origin, ty, region, ConstraintCategory::BoringNoLocation);
outlives.type_must_outlive(origin, ty, region);
})
}
@ -682,12 +681,7 @@ fn region_known_to_outlive<'tcx>(
use rustc_infer::infer::outlives::obligations::TypeOutlivesDelegate;
let origin = infer::RelateRegionParamBound(DUMMY_SP);
// `region_a: region_b` -> `region_b <= region_a`
infcx.push_sub_region_constraint(
origin,
region_b,
region_a,
ConstraintCategory::BoringNoLocation,
);
infcx.push_sub_region_constraint(origin, region_b, region_a);
})
}

View File

@ -1,35 +0,0 @@
// check-fail
// known-bug
// This gives us problems because `for<'a> I::Item<'a>: Debug` should mean "for
// all 'a where I::Item<'a> is WF", but really means "for all 'a possible"
use std::fmt::Debug;
pub trait LendingIterator {
type Item<'this>
where
Self: 'this;
}
pub struct WindowsMut<'x> {
slice: &'x (),
}
impl<'y> LendingIterator for WindowsMut<'y> {
type Item<'this> = &'this mut () where 'y: 'this;
}
fn print_items<I>(_iter: I)
where
I: LendingIterator,
for<'a> I::Item<'a>: Debug,
{
}
fn main() {
let slice = &mut ();
//~^ temporary value dropped while borrowed
let windows = WindowsMut { slice };
print_items::<WindowsMut<'_>>(windows);
}

View File

@ -1,20 +0,0 @@
error[E0716]: temporary value dropped while borrowed
--> $DIR/hrtb-implied-1.rs:31:22
|
LL | let slice = &mut ();
| ^^ creates a temporary which is freed while still in use
...
LL | print_items::<WindowsMut<'_>>(windows);
| -------------------------------------- argument requires that borrow lasts for `'static`
LL | }
| - temporary value is freed at the end of this statement
|
note: due to current limitations in the borrow checker, this implies a `'static` lifetime
--> $DIR/hrtb-implied-1.rs:26:26
|
LL | for<'a> I::Item<'a>: Debug,
| ^^^^^
error: aborting due to previous error
For more information about this error, try `rustc --explain E0716`.

View File

@ -9,12 +9,6 @@ LL | assert_static_via_hrtb(&local);
LL | assert_static_via_hrtb_with_assoc_type(&&local);
LL | }
| - `local` dropped here while still borrowed
|
note: due to current limitations in the borrow checker, this implies a `'static` lifetime
--> $DIR/local-outlives-static-via-hrtb.rs:15:53
|
LL | fn assert_static_via_hrtb<G>(_: G) where for<'a> G: Outlives<'a> {}
| ^^^^^^^^^^^^
error[E0597]: `local` does not live long enough
--> $DIR/local-outlives-static-via-hrtb.rs:25:45
@ -26,12 +20,6 @@ LL | assert_static_via_hrtb_with_assoc_type(&&local);
| argument requires that `local` is borrowed for `'static`
LL | }
| - `local` dropped here while still borrowed
|
note: due to current limitations in the borrow checker, this implies a `'static` lifetime
--> $DIR/local-outlives-static-via-hrtb.rs:19:20
|
LL | for<'a> &'a T: Reference<AssociatedType = &'a ()>,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error: aborting due to 2 previous errors