mirror of
https://github.com/rust-lang/rust.git
synced 2025-02-03 02:23:20 +00:00
Auto merge of #98584 - lcnr:region-stuff-more-beans, r=oli-obk
continue nll transition by removing stuff r? `@jackh726` for now building on #98641
This commit is contained in:
commit
efb171e235
@ -128,7 +128,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)),
|
||||
region_obligations.iter().map(|r_o| (r_o.sup_type, r_o.sub_region)),
|
||||
region_constraints,
|
||||
)
|
||||
});
|
||||
|
@ -4,7 +4,6 @@
|
||||
//! and use that to decide when one free region outlives another, and so forth.
|
||||
|
||||
use rustc_data_structures::transitive_relation::TransitiveRelation;
|
||||
use rustc_hir::def_id::DefId;
|
||||
use rustc_middle::ty::{self, Lift, Region, TyCtxt};
|
||||
|
||||
/// Combines a `FreeRegionMap` and a `TyCtxt`.
|
||||
@ -14,16 +13,13 @@ use rustc_middle::ty::{self, Lift, Region, TyCtxt};
|
||||
pub(crate) struct RegionRelations<'a, 'tcx> {
|
||||
pub tcx: TyCtxt<'tcx>,
|
||||
|
||||
/// The context used for debug messages
|
||||
pub context: DefId,
|
||||
|
||||
/// Free-region relationships.
|
||||
pub free_regions: &'a FreeRegionMap<'tcx>,
|
||||
}
|
||||
|
||||
impl<'a, 'tcx> RegionRelations<'a, 'tcx> {
|
||||
pub fn new(tcx: TyCtxt<'tcx>, context: DefId, free_regions: &'a FreeRegionMap<'tcx>) -> Self {
|
||||
Self { tcx, context, free_regions }
|
||||
pub fn new(tcx: TyCtxt<'tcx>, free_regions: &'a FreeRegionMap<'tcx>) -> Self {
|
||||
Self { tcx, free_regions }
|
||||
}
|
||||
|
||||
pub fn lub_free_regions(&self, r_a: Region<'tcx>, r_b: Region<'tcx>) -> Region<'tcx> {
|
||||
|
@ -120,13 +120,9 @@ impl<'cx, 'tcx> LexicalResolver<'cx, 'tcx> {
|
||||
) -> LexicalRegionResolutions<'tcx> {
|
||||
let mut var_data = self.construct_var_data(self.tcx());
|
||||
|
||||
// Dorky hack to cause `dump_constraints` to only get called
|
||||
// if debug mode is enabled:
|
||||
debug!(
|
||||
"----() End constraint listing (context={:?}) {:?}---",
|
||||
self.region_rels.context,
|
||||
self.dump_constraints(self.region_rels)
|
||||
);
|
||||
if cfg!(debug_assertions) {
|
||||
self.dump_constraints();
|
||||
}
|
||||
|
||||
let graph = self.construct_graph();
|
||||
self.expand_givens(&graph);
|
||||
@ -156,8 +152,8 @@ impl<'cx, 'tcx> LexicalResolver<'cx, 'tcx> {
|
||||
}
|
||||
}
|
||||
|
||||
fn dump_constraints(&self, free_regions: &RegionRelations<'_, 'tcx>) {
|
||||
debug!("----() Start constraint listing (context={:?}) ()----", free_regions.context);
|
||||
#[instrument(level = "debug", skip(self))]
|
||||
fn dump_constraints(&self) {
|
||||
for (idx, (constraint, _)) in self.data.constraints.iter().enumerate() {
|
||||
debug!("Constraint {} => {:?}", idx, constraint);
|
||||
}
|
||||
|
@ -15,7 +15,6 @@ use rustc_data_structures::sync::Lrc;
|
||||
use rustc_data_structures::undo_log::Rollback;
|
||||
use rustc_data_structures::unify as ut;
|
||||
use rustc_errors::{DiagnosticBuilder, ErrorGuaranteed};
|
||||
use rustc_hir as hir;
|
||||
use rustc_hir::def_id::{DefId, LocalDefId};
|
||||
use rustc_middle::infer::canonical::{Canonical, CanonicalVarValues};
|
||||
use rustc_middle::infer::unify_key::{ConstVarValue, ConstVariableValue};
|
||||
@ -147,7 +146,7 @@ pub struct InferCtxtInner<'tcx> {
|
||||
/// for each body-id in this map, which will process the
|
||||
/// obligations within. This is expected to be done 'late enough'
|
||||
/// that all type inference variables have been bound and so forth.
|
||||
region_obligations: Vec<(hir::HirId, RegionObligation<'tcx>)>,
|
||||
region_obligations: Vec<RegionObligation<'tcx>>,
|
||||
|
||||
undo_log: InferCtxtUndoLogs<'tcx>,
|
||||
|
||||
@ -171,7 +170,7 @@ impl<'tcx> InferCtxtInner<'tcx> {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn region_obligations(&self) -> &[(hir::HirId, RegionObligation<'tcx>)] {
|
||||
pub fn region_obligations(&self) -> &[RegionObligation<'tcx>] {
|
||||
&self.region_obligations
|
||||
}
|
||||
|
||||
@ -1267,7 +1266,6 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
|
||||
/// `resolve_vars_if_possible` as well as `fully_resolve`.
|
||||
pub fn resolve_regions(
|
||||
&self,
|
||||
region_context: DefId,
|
||||
outlives_env: &OutlivesEnvironment<'tcx>,
|
||||
) -> Vec<RegionResolutionError<'tcx>> {
|
||||
let (var_infos, data) = {
|
||||
@ -1286,8 +1284,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
|
||||
.into_infos_and_data()
|
||||
};
|
||||
|
||||
let region_rels =
|
||||
&RegionRelations::new(self.tcx, region_context, outlives_env.free_region_map());
|
||||
let region_rels = &RegionRelations::new(self.tcx, outlives_env.free_region_map());
|
||||
|
||||
let (lexical_region_resolutions, errors) =
|
||||
lexical_region_resolve::resolve(outlives_env.param_env, region_rels, var_infos, data);
|
||||
@ -1302,12 +1299,8 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
|
||||
/// result. After this, no more unification operations should be
|
||||
/// done -- or the compiler will panic -- but it is legal to use
|
||||
/// `resolve_vars_if_possible` as well as `fully_resolve`.
|
||||
pub fn resolve_regions_and_report_errors(
|
||||
&self,
|
||||
region_context: DefId,
|
||||
outlives_env: &OutlivesEnvironment<'tcx>,
|
||||
) {
|
||||
let errors = self.resolve_regions(region_context, outlives_env);
|
||||
pub fn resolve_regions_and_report_errors(&self, outlives_env: &OutlivesEnvironment<'tcx>) {
|
||||
let errors = self.resolve_regions(outlives_env);
|
||||
|
||||
if !self.is_tainted_by_errors() {
|
||||
// As a heuristic, just skip reporting region errors
|
||||
|
@ -1,8 +1,6 @@
|
||||
use crate::infer::free_regions::FreeRegionMap;
|
||||
use crate::infer::{GenericKind, InferCtxt};
|
||||
use crate::traits::query::OutlivesBound;
|
||||
use rustc_data_structures::fx::FxHashMap;
|
||||
use rustc_hir as hir;
|
||||
use rustc_middle::ty::{self, ReEarlyBound, ReFree, ReVar, Region};
|
||||
|
||||
use super::explicit_outlives_bounds;
|
||||
@ -31,9 +29,7 @@ pub struct OutlivesEnvironment<'tcx> {
|
||||
pub param_env: ty::ParamEnv<'tcx>,
|
||||
free_region_map: FreeRegionMap<'tcx>,
|
||||
|
||||
// Contains, for each body B that we are checking (that is, the fn
|
||||
// item, but also any nested closures), the set of implied region
|
||||
// bounds that are in scope in that particular body.
|
||||
// Contains the implied region bounds in scope for our current body.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
@ -43,24 +39,15 @@ pub struct OutlivesEnvironment<'tcx> {
|
||||
// } // body B0
|
||||
// ```
|
||||
//
|
||||
// Here, for body B0, the list would be `[T: 'a]`, because we
|
||||
// Here, when checking the body B0, the list would be `[T: 'a]`, because we
|
||||
// infer that `T` must outlive `'a` from the implied bounds on the
|
||||
// fn declaration.
|
||||
//
|
||||
// For the body B1, the list would be `[T: 'a, T: 'b]`, because we
|
||||
// For the body B1 however, the list would be `[T: 'a, T: 'b]`, because we
|
||||
// also can see that -- within the closure body! -- `T` must
|
||||
// outlive `'b`. This is not necessarily true outside the closure
|
||||
// body, since the closure may never be called.
|
||||
//
|
||||
// We collect this map as we descend the tree. We then use the
|
||||
// results when proving outlives obligations like `T: 'x` later
|
||||
// (e.g., if `T: 'x` must be proven within the body B1, then we
|
||||
// know it is true if either `'a: 'x` or `'b: 'x`).
|
||||
region_bound_pairs_map: FxHashMap<hir::HirId, RegionBoundPairs<'tcx>>,
|
||||
|
||||
// Used to compute `region_bound_pairs_map`: contains the set of
|
||||
// in-scope region-bound pairs thus far.
|
||||
region_bound_pairs_accum: RegionBoundPairs<'tcx>,
|
||||
region_bound_pairs: RegionBoundPairs<'tcx>,
|
||||
}
|
||||
|
||||
/// "Region-bound pairs" tracks outlives relations that are known to
|
||||
@ -73,8 +60,7 @@ impl<'a, 'tcx> OutlivesEnvironment<'tcx> {
|
||||
let mut env = OutlivesEnvironment {
|
||||
param_env,
|
||||
free_region_map: Default::default(),
|
||||
region_bound_pairs_map: Default::default(),
|
||||
region_bound_pairs_accum: vec![],
|
||||
region_bound_pairs: Default::default(),
|
||||
};
|
||||
|
||||
env.add_outlives_bounds(None, explicit_outlives_bounds(param_env));
|
||||
@ -87,62 +73,9 @@ impl<'a, 'tcx> OutlivesEnvironment<'tcx> {
|
||||
&self.free_region_map
|
||||
}
|
||||
|
||||
/// Borrows current value of the `region_bound_pairs`.
|
||||
pub fn region_bound_pairs_map(&self) -> &FxHashMap<hir::HirId, RegionBoundPairs<'tcx>> {
|
||||
&self.region_bound_pairs_map
|
||||
}
|
||||
|
||||
/// This is a hack to support the old-school regionck, which
|
||||
/// processes region constraints from the main function and the
|
||||
/// closure together. In that context, when we enter a closure, we
|
||||
/// want to be able to "save" the state of the surrounding a
|
||||
/// function. We can then add implied bounds and the like from the
|
||||
/// closure arguments into the environment -- these should only
|
||||
/// apply in the closure body, so once we exit, we invoke
|
||||
/// `pop_snapshot_post_typeck_child` to remove them.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// ```ignore (pseudo-rust)
|
||||
/// fn foo<T>() {
|
||||
/// callback(for<'a> |x: &'a T| {
|
||||
/// // ^^^^^^^ not legal syntax, but probably should be
|
||||
/// // within this closure body, `T: 'a` holds
|
||||
/// })
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This "containment" of closure's effects only works so well. In
|
||||
/// particular, we (intentionally) leak relationships between free
|
||||
/// regions that are created by the closure's bounds. The case
|
||||
/// where this is useful is when you have (e.g.) a closure with a
|
||||
/// signature like `for<'a, 'b> fn(x: &'a &'b u32)` -- in this
|
||||
/// case, we want to keep the relationship `'b: 'a` in the
|
||||
/// free-region-map, so that later if we have to take `LUB('b,
|
||||
/// 'a)` we can get the result `'b`.
|
||||
///
|
||||
/// I have opted to keep **all modifications** to the
|
||||
/// free-region-map, however, and not just those that concern free
|
||||
/// variables bound in the closure. The latter seems more correct,
|
||||
/// but it is not the existing behavior, and I could not find a
|
||||
/// case where the existing behavior went wrong. In any case, it
|
||||
/// seems like it'd be readily fixed if we wanted. There are
|
||||
/// similar leaks around givens that seem equally suspicious, to
|
||||
/// be honest. --nmatsakis
|
||||
pub fn push_snapshot_pre_typeck_child(&self) -> usize {
|
||||
self.region_bound_pairs_accum.len()
|
||||
}
|
||||
|
||||
/// See `push_snapshot_pre_typeck_child`.
|
||||
pub fn pop_snapshot_post_typeck_child(&mut self, len: usize) {
|
||||
self.region_bound_pairs_accum.truncate(len);
|
||||
}
|
||||
|
||||
/// Save the current set of region-bound pairs under the given `body_id`.
|
||||
pub fn save_implied_bounds(&mut self, body_id: hir::HirId) {
|
||||
let old =
|
||||
self.region_bound_pairs_map.insert(body_id, self.region_bound_pairs_accum.clone());
|
||||
assert!(old.is_none());
|
||||
/// Borrows current `region_bound_pairs`.
|
||||
pub fn region_bound_pairs(&self) -> &RegionBoundPairs<'tcx> {
|
||||
&self.region_bound_pairs
|
||||
}
|
||||
|
||||
/// Processes outlives bounds that are known to hold, whether from implied or other sources.
|
||||
@ -164,11 +97,10 @@ impl<'a, 'tcx> OutlivesEnvironment<'tcx> {
|
||||
debug!("add_outlives_bounds: outlives_bound={:?}", outlives_bound);
|
||||
match outlives_bound {
|
||||
OutlivesBound::RegionSubParam(r_a, param_b) => {
|
||||
self.region_bound_pairs_accum.push((r_a, GenericKind::Param(param_b)));
|
||||
self.region_bound_pairs.push((r_a, GenericKind::Param(param_b)));
|
||||
}
|
||||
OutlivesBound::RegionSubProjection(r_a, projection_b) => {
|
||||
self.region_bound_pairs_accum
|
||||
.push((r_a, GenericKind::Projection(projection_b)));
|
||||
self.region_bound_pairs.push((r_a, GenericKind::Projection(projection_b)));
|
||||
}
|
||||
OutlivesBound::RegionSubRegion(r_a, r_b) => {
|
||||
if let (ReEarlyBound(_) | ReFree(_), ReVar(vid_b)) = (r_a.kind(), r_b.kind()) {
|
||||
|
@ -60,18 +60,16 @@
|
||||
//! imply that `'b: 'a`.
|
||||
|
||||
use crate::infer::outlives::components::{push_outlives_components, Component};
|
||||
use crate::infer::outlives::env::OutlivesEnvironment;
|
||||
use crate::infer::outlives::env::RegionBoundPairs;
|
||||
use crate::infer::outlives::verify::VerifyBoundCx;
|
||||
use crate::infer::{
|
||||
self, GenericKind, InferCtxt, RegionObligation, SubregionOrigin, UndoLog, VerifyBound,
|
||||
};
|
||||
use crate::traits::{ObligationCause, ObligationCauseCode};
|
||||
use rustc_data_structures::undo_log::UndoLogs;
|
||||
use rustc_middle::ty::subst::GenericArgKind;
|
||||
use rustc_middle::ty::{self, Region, Ty, TyCtxt, TypeFoldable};
|
||||
|
||||
use rustc_data_structures::fx::FxHashMap;
|
||||
use rustc_data_structures::undo_log::UndoLogs;
|
||||
use rustc_hir as hir;
|
||||
use smallvec::smallvec;
|
||||
|
||||
impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
|
||||
@ -80,16 +78,11 @@ impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
|
||||
/// and later processed by regionck, when full type information is
|
||||
/// available (see `region_obligations` field for more
|
||||
/// information).
|
||||
pub fn register_region_obligation(
|
||||
&self,
|
||||
body_id: hir::HirId,
|
||||
obligation: RegionObligation<'tcx>,
|
||||
) {
|
||||
debug!("register_region_obligation(body_id={:?}, obligation={:?})", body_id, obligation);
|
||||
|
||||
#[instrument(level = "debug", skip(self))]
|
||||
pub fn register_region_obligation(&self, obligation: RegionObligation<'tcx>) {
|
||||
let mut inner = self.inner.borrow_mut();
|
||||
inner.undo_log.push(UndoLog::PushRegionObligation);
|
||||
inner.region_obligations.push((body_id, obligation));
|
||||
inner.region_obligations.push(obligation);
|
||||
}
|
||||
|
||||
pub fn register_region_obligation_with_cause(
|
||||
@ -109,14 +102,11 @@ impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
|
||||
)
|
||||
});
|
||||
|
||||
self.register_region_obligation(
|
||||
cause.body_id,
|
||||
RegionObligation { sup_type, sub_region, origin },
|
||||
);
|
||||
self.register_region_obligation(RegionObligation { sup_type, sub_region, origin });
|
||||
}
|
||||
|
||||
/// Trait queries just want to pass back type obligations "as is"
|
||||
pub fn take_registered_region_obligations(&self) -> Vec<(hir::HirId, RegionObligation<'tcx>)> {
|
||||
pub fn take_registered_region_obligations(&self) -> Vec<RegionObligation<'tcx>> {
|
||||
std::mem::take(&mut self.inner.borrow_mut().region_obligations)
|
||||
}
|
||||
|
||||
@ -144,10 +134,10 @@ impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
|
||||
/// - `param_env` is the parameter environment for the enclosing function.
|
||||
/// - `body_id` is the body-id whose region obligations are being
|
||||
/// processed.
|
||||
#[instrument(level = "debug", skip(self, region_bound_pairs_map))]
|
||||
#[instrument(level = "debug", skip(self, region_bound_pairs))]
|
||||
pub fn process_registered_region_obligations(
|
||||
&self,
|
||||
region_bound_pairs_map: &FxHashMap<hir::HirId, RegionBoundPairs<'tcx>>,
|
||||
region_bound_pairs: &RegionBoundPairs<'tcx>,
|
||||
param_env: ty::ParamEnv<'tcx>,
|
||||
) {
|
||||
assert!(
|
||||
@ -157,7 +147,7 @@ impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
|
||||
|
||||
let my_region_obligations = self.take_registered_region_obligations();
|
||||
|
||||
for (body_id, RegionObligation { sup_type, sub_region, origin }) in my_region_obligations {
|
||||
for RegionObligation { sup_type, sub_region, origin } in my_region_obligations {
|
||||
debug!(
|
||||
"process_registered_region_obligations: sup_type={:?} sub_region={:?} origin={:?}",
|
||||
sup_type, sub_region, origin
|
||||
@ -165,18 +155,23 @@ impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> {
|
||||
|
||||
let sup_type = self.resolve_vars_if_possible(sup_type);
|
||||
|
||||
if let Some(region_bound_pairs) = region_bound_pairs_map.get(&body_id) {
|
||||
let outlives =
|
||||
&mut TypeOutlives::new(self, self.tcx, ®ion_bound_pairs, None, param_env);
|
||||
outlives.type_must_outlive(origin, sup_type, sub_region);
|
||||
} else {
|
||||
self.tcx.sess.delay_span_bug(
|
||||
origin.span(),
|
||||
&format!("no region-bound-pairs for {:?}", body_id),
|
||||
);
|
||||
}
|
||||
let outlives =
|
||||
&mut TypeOutlives::new(self, self.tcx, ®ion_bound_pairs, None, param_env);
|
||||
outlives.type_must_outlive(origin, sup_type, sub_region);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn check_region_obligations_and_report_errors(
|
||||
&self,
|
||||
outlives_env: &OutlivesEnvironment<'tcx>,
|
||||
) {
|
||||
self.process_registered_region_obligations(
|
||||
outlives_env.region_bound_pairs(),
|
||||
outlives_env.param_env,
|
||||
);
|
||||
|
||||
self.resolve_regions_and_report_errors(outlives_env)
|
||||
}
|
||||
}
|
||||
|
||||
/// The `TypeOutlives` struct has the job of "lowering" a `T: 'a`
|
||||
|
@ -212,15 +212,7 @@ impl<'tcx> AutoTraitFinder<'tcx> {
|
||||
panic!("Unable to fulfill trait {:?} for '{:?}': {:?}", trait_did, ty, errors);
|
||||
}
|
||||
|
||||
let body_id_map: FxHashMap<_, _> = infcx
|
||||
.inner
|
||||
.borrow()
|
||||
.region_obligations()
|
||||
.iter()
|
||||
.map(|&(id, _)| (id, vec![]))
|
||||
.collect();
|
||||
|
||||
infcx.process_registered_region_obligations(&body_id_map, full_env);
|
||||
infcx.process_registered_region_obligations(&Default::default(), full_env);
|
||||
|
||||
let region_data = infcx
|
||||
.inner
|
||||
|
@ -16,7 +16,6 @@ use crate::traits::{
|
||||
//use rustc_data_structures::fx::FxHashMap;
|
||||
use rustc_errors::Diagnostic;
|
||||
use rustc_hir::def_id::{DefId, LOCAL_CRATE};
|
||||
use rustc_hir::CRATE_HIR_ID;
|
||||
use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
|
||||
use rustc_infer::traits::{util, TraitEngine};
|
||||
use rustc_middle::traits::specialization_graph::OverlapMode;
|
||||
@ -317,14 +316,13 @@ fn negative_impl<'cx, 'tcx>(
|
||||
let (subject2, obligations) =
|
||||
impl_subject_and_oblig(selcx, impl_env, impl2_def_id, impl2_substs);
|
||||
|
||||
!equate(&infcx, impl_env, impl1_def_id, subject1, subject2, obligations)
|
||||
!equate(&infcx, impl_env, subject1, subject2, obligations)
|
||||
})
|
||||
}
|
||||
|
||||
fn equate<'cx, 'tcx>(
|
||||
infcx: &InferCtxt<'cx, 'tcx>,
|
||||
impl_env: ty::ParamEnv<'tcx>,
|
||||
impl1_def_id: DefId,
|
||||
subject1: ImplSubject<'tcx>,
|
||||
subject2: ImplSubject<'tcx>,
|
||||
obligations: impl Iterator<Item = PredicateObligation<'tcx>>,
|
||||
@ -341,7 +339,7 @@ fn equate<'cx, 'tcx>(
|
||||
let opt_failing_obligation = obligations
|
||||
.into_iter()
|
||||
.chain(more_obligations)
|
||||
.find(|o| negative_impl_exists(selcx, impl_env, impl1_def_id, o));
|
||||
.find(|o| negative_impl_exists(selcx, impl_env, o));
|
||||
|
||||
if let Some(failing_obligation) = opt_failing_obligation {
|
||||
debug!("overlap: obligation unsatisfiable {:?}", failing_obligation);
|
||||
@ -356,18 +354,17 @@ fn equate<'cx, 'tcx>(
|
||||
fn negative_impl_exists<'cx, 'tcx>(
|
||||
selcx: &SelectionContext<'cx, 'tcx>,
|
||||
param_env: ty::ParamEnv<'tcx>,
|
||||
region_context: DefId,
|
||||
o: &PredicateObligation<'tcx>,
|
||||
) -> bool {
|
||||
let infcx = &selcx.infcx().fork();
|
||||
|
||||
if resolve_negative_obligation(infcx, param_env, region_context, o) {
|
||||
if resolve_negative_obligation(infcx, param_env, o) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Try to prove a negative obligation exists for super predicates
|
||||
for o in util::elaborate_predicates(infcx.tcx, iter::once(o.predicate)) {
|
||||
if resolve_negative_obligation(infcx, param_env, region_context, &o) {
|
||||
if resolve_negative_obligation(infcx, param_env, &o) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@ -379,7 +376,6 @@ fn negative_impl_exists<'cx, 'tcx>(
|
||||
fn resolve_negative_obligation<'cx, 'tcx>(
|
||||
infcx: &InferCtxt<'cx, 'tcx>,
|
||||
param_env: ty::ParamEnv<'tcx>,
|
||||
region_context: DefId,
|
||||
o: &PredicateObligation<'tcx>,
|
||||
) -> bool {
|
||||
let tcx = infcx.tcx;
|
||||
@ -397,19 +393,11 @@ fn resolve_negative_obligation<'cx, 'tcx>(
|
||||
return false;
|
||||
}
|
||||
|
||||
let mut outlives_env = OutlivesEnvironment::new(param_env);
|
||||
// FIXME -- add "assumed to be well formed" types into the `outlives_env`
|
||||
// FIXME -- also add "assumed to be well formed" types into the `outlives_env`
|
||||
let outlives_env = OutlivesEnvironment::new(param_env);
|
||||
infcx.process_registered_region_obligations(outlives_env.region_bound_pairs(), param_env);
|
||||
|
||||
// "Save" the accumulated implied bounds into the outlives environment
|
||||
// (due to the FIXME above, there aren't any, but this step is still needed).
|
||||
// The "body id" is given as `CRATE_HIR_ID`, which is the same body-id used
|
||||
// by the "dummy" causes elsewhere (body-id is only relevant when checking
|
||||
// function bodies with closures).
|
||||
outlives_env.save_implied_bounds(CRATE_HIR_ID);
|
||||
|
||||
infcx.process_registered_region_obligations(outlives_env.region_bound_pairs_map(), param_env);
|
||||
|
||||
let errors = infcx.resolve_regions(region_context, &outlives_env);
|
||||
let errors = infcx.resolve_regions(&outlives_env);
|
||||
|
||||
if !errors.is_empty() {
|
||||
return false;
|
||||
|
@ -198,17 +198,13 @@ pub fn type_known_to_meet_bound_modulo_regions<'a, 'tcx>(
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(level = "debug", skip(tcx, elaborated_env))]
|
||||
fn do_normalize_predicates<'tcx>(
|
||||
tcx: TyCtxt<'tcx>,
|
||||
region_context: DefId,
|
||||
cause: ObligationCause<'tcx>,
|
||||
elaborated_env: ty::ParamEnv<'tcx>,
|
||||
predicates: Vec<ty::Predicate<'tcx>>,
|
||||
) -> Result<Vec<ty::Predicate<'tcx>>, ErrorGuaranteed> {
|
||||
debug!(
|
||||
"do_normalize_predicates(predicates={:?}, region_context={:?}, cause={:?})",
|
||||
predicates, region_context, cause,
|
||||
);
|
||||
let span = cause.span;
|
||||
tcx.infer_ctxt().enter(|infcx| {
|
||||
// FIXME. We should really... do something with these region
|
||||
@ -240,7 +236,7 @@ fn do_normalize_predicates<'tcx>(
|
||||
// cares about declarations like `'a: 'b`.
|
||||
let outlives_env = OutlivesEnvironment::new(elaborated_env);
|
||||
|
||||
infcx.resolve_regions_and_report_errors(region_context, &outlives_env);
|
||||
infcx.resolve_regions_and_report_errors(&outlives_env);
|
||||
|
||||
let predicates = match infcx.fully_resolve(predicates) {
|
||||
Ok(predicates) => predicates,
|
||||
@ -269,9 +265,9 @@ fn do_normalize_predicates<'tcx>(
|
||||
|
||||
// FIXME: this is gonna need to be removed ...
|
||||
/// Normalizes the parameter environment, reporting errors if they occur.
|
||||
#[instrument(level = "debug", skip(tcx))]
|
||||
pub fn normalize_param_env_or_error<'tcx>(
|
||||
tcx: TyCtxt<'tcx>,
|
||||
region_context: DefId,
|
||||
unnormalized_env: ty::ParamEnv<'tcx>,
|
||||
cause: ObligationCause<'tcx>,
|
||||
) -> ty::ParamEnv<'tcx> {
|
||||
@ -289,12 +285,6 @@ pub fn normalize_param_env_or_error<'tcx>(
|
||||
// parameter environments once for every fn as it goes,
|
||||
// and errors will get reported then; so outside of type inference we
|
||||
// can be sure that no errors should occur.
|
||||
|
||||
debug!(
|
||||
"normalize_param_env_or_error(region_context={:?}, unnormalized_env={:?}, cause={:?})",
|
||||
region_context, unnormalized_env, cause
|
||||
);
|
||||
|
||||
let mut predicates: Vec<_> =
|
||||
util::elaborate_predicates(tcx, unnormalized_env.caller_bounds().into_iter())
|
||||
.map(|obligation| obligation.predicate)
|
||||
@ -338,7 +328,6 @@ pub fn normalize_param_env_or_error<'tcx>(
|
||||
);
|
||||
let Ok(non_outlives_predicates) = do_normalize_predicates(
|
||||
tcx,
|
||||
region_context,
|
||||
cause.clone(),
|
||||
elaborated_env,
|
||||
predicates,
|
||||
@ -362,7 +351,6 @@ pub fn normalize_param_env_or_error<'tcx>(
|
||||
);
|
||||
let Ok(outlives_predicates) = do_normalize_predicates(
|
||||
tcx,
|
||||
region_context,
|
||||
cause,
|
||||
outlives_env,
|
||||
outlives_predicates,
|
||||
|
@ -1,73 +1,7 @@
|
||||
use crate::infer::at::At;
|
||||
use crate::infer::canonical::OriginalQueryValues;
|
||||
use crate::infer::InferOk;
|
||||
|
||||
use rustc_middle::ty::subst::GenericArg;
|
||||
use rustc_middle::ty::{self, Ty, TyCtxt};
|
||||
|
||||
pub use rustc_middle::traits::query::{DropckConstraint, DropckOutlivesResult};
|
||||
|
||||
pub trait AtExt<'tcx> {
|
||||
fn dropck_outlives(&self, ty: Ty<'tcx>) -> InferOk<'tcx, Vec<GenericArg<'tcx>>>;
|
||||
}
|
||||
|
||||
impl<'cx, 'tcx> AtExt<'tcx> for At<'cx, 'tcx> {
|
||||
/// Given a type `ty` of some value being dropped, computes a set
|
||||
/// of "kinds" (types, regions) that must be outlive the execution
|
||||
/// of the destructor. These basically correspond to data that the
|
||||
/// destructor might access. This is used during regionck to
|
||||
/// impose "outlives" constraints on any lifetimes referenced
|
||||
/// within.
|
||||
///
|
||||
/// The rules here are given by the "dropck" RFCs, notably [#1238]
|
||||
/// and [#1327]. This is a fixed-point computation, where we
|
||||
/// explore all the data that will be dropped (transitively) when
|
||||
/// a value of type `ty` is dropped. For each type T that will be
|
||||
/// dropped and which has a destructor, we must assume that all
|
||||
/// the types/regions of T are live during the destructor, unless
|
||||
/// they are marked with a special attribute (`#[may_dangle]`).
|
||||
///
|
||||
/// [#1238]: https://github.com/rust-lang/rfcs/blob/master/text/1238-nonparametric-dropck.md
|
||||
/// [#1327]: https://github.com/rust-lang/rfcs/blob/master/text/1327-dropck-param-eyepatch.md
|
||||
fn dropck_outlives(&self, ty: Ty<'tcx>) -> InferOk<'tcx, Vec<GenericArg<'tcx>>> {
|
||||
debug!("dropck_outlives(ty={:?}, param_env={:?})", ty, self.param_env,);
|
||||
|
||||
// Quick check: there are a number of cases that we know do not require
|
||||
// any destructor.
|
||||
let tcx = self.infcx.tcx;
|
||||
if trivial_dropck_outlives(tcx, ty) {
|
||||
return InferOk { value: vec![], obligations: vec![] };
|
||||
}
|
||||
|
||||
let mut orig_values = OriginalQueryValues::default();
|
||||
let c_ty = self.infcx.canonicalize_query(self.param_env.and(ty), &mut orig_values);
|
||||
let span = self.cause.span;
|
||||
debug!("c_ty = {:?}", c_ty);
|
||||
if let Ok(result) = tcx.dropck_outlives(c_ty)
|
||||
&& result.is_proven()
|
||||
&& let Ok(InferOk { value, obligations }) =
|
||||
self.infcx.instantiate_query_response_and_region_obligations(
|
||||
self.cause,
|
||||
self.param_env,
|
||||
&orig_values,
|
||||
result,
|
||||
)
|
||||
{
|
||||
let ty = self.infcx.resolve_vars_if_possible(ty);
|
||||
let kinds = value.into_kinds_reporting_overflows(tcx, span, ty);
|
||||
return InferOk { value: kinds, obligations };
|
||||
}
|
||||
|
||||
// Errors and ambiguity in dropck occur in two cases:
|
||||
// - unresolved inference variables at the end of typeck
|
||||
// - non well-formed types where projections cannot be resolved
|
||||
// Either of these should have created an error before.
|
||||
tcx.sess.delay_span_bug(span, "dtorck encountered internal error");
|
||||
|
||||
InferOk { value: vec![], obligations: vec![] }
|
||||
}
|
||||
}
|
||||
|
||||
/// This returns true if the type `ty` is "trivial" for
|
||||
/// dropck-outlives -- that is, if it doesn't require any types to
|
||||
/// outlive. This is similar but not *quite* the same as the
|
||||
@ -79,6 +13,8 @@ impl<'cx, 'tcx> AtExt<'tcx> for At<'cx, 'tcx> {
|
||||
///
|
||||
/// Note also that `needs_drop` requires a "global" type (i.e., one
|
||||
/// with erased regions), but this function does not.
|
||||
///
|
||||
// FIXME(@lcnr): remove this module and move this function somewhere else.
|
||||
pub fn trivial_dropck_outlives<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool {
|
||||
match ty.kind() {
|
||||
// None of these types have a destructor and hence they do not
|
||||
@ -105,7 +41,7 @@ pub fn trivial_dropck_outlives<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool {
|
||||
ty::Array(ty, _) | ty::Slice(ty) => trivial_dropck_outlives(tcx, *ty),
|
||||
|
||||
// (T1..Tn) and closures have same properties as T1..Tn --
|
||||
// check if *any* of those are trivial.
|
||||
// check if *all* of them are trivial.
|
||||
ty::Tuple(tys) => tys.iter().all(|t| trivial_dropck_outlives(tcx, t)),
|
||||
ty::Closure(_, ref substs) => {
|
||||
trivial_dropck_outlives(tcx, substs.as_closure().tupled_upvars_ty())
|
||||
|
@ -95,7 +95,7 @@ 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))
|
||||
.map(|r_o| (r_o.sup_type, r_o.sub_region))
|
||||
.map(|(ty, r)| (infcx.resolve_vars_if_possible(ty), r)),
|
||||
®ion_constraint_data,
|
||||
);
|
||||
|
@ -211,7 +211,7 @@ fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
|
||||
tcx.hir().maybe_body_owned_by(id).map_or(id, |body| body.hir_id)
|
||||
});
|
||||
let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
|
||||
traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
|
||||
traits::normalize_param_env_or_error(tcx, unnormalized_env, cause)
|
||||
}
|
||||
|
||||
/// Elaborate the environment.
|
||||
|
@ -13,6 +13,7 @@ use rustc_hir::def_id::{DefId, LocalDefId};
|
||||
use rustc_hir::intravisit::Visitor;
|
||||
use rustc_hir::lang_items::LangItem;
|
||||
use rustc_hir::{ItemKind, Node, PathSegment};
|
||||
use rustc_infer::infer::outlives::env::OutlivesEnvironment;
|
||||
use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
|
||||
use rustc_infer::infer::{RegionVariableOrigin, TyCtxtInferExt};
|
||||
use rustc_infer::traits::Obligation;
|
||||
@ -736,10 +737,8 @@ fn check_opaque_meets_bounds<'tcx>(
|
||||
hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..) => {}
|
||||
// Can have different predicates to their defining use
|
||||
hir::OpaqueTyOrigin::TyAlias => {
|
||||
// Finally, resolve all regions. This catches wily misuses of
|
||||
// lifetime parameters.
|
||||
let fcx = FnCtxt::new(&inh, param_env, hir_id);
|
||||
fcx.regionck_item(hir_id, span, FxHashSet::default());
|
||||
let outlives_environment = OutlivesEnvironment::new(param_env);
|
||||
infcx.check_region_obligations_and_report_errors(&outlives_environment);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,3 +1,4 @@
|
||||
use crate::check::regionck::OutlivesEnvironmentExt;
|
||||
use crate::errors::LifetimesOrBoundsMismatchOnTrait;
|
||||
use rustc_data_structures::stable_set::FxHashSet;
|
||||
use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticId, ErrorGuaranteed};
|
||||
@ -5,6 +6,7 @@ use rustc_hir as hir;
|
||||
use rustc_hir::def::{DefKind, Res};
|
||||
use rustc_hir::intravisit;
|
||||
use rustc_hir::{GenericParamKind, ImplItemKind, TraitItemKind};
|
||||
use rustc_infer::infer::outlives::env::OutlivesEnvironment;
|
||||
use rustc_infer::infer::{self, InferOk, TyCtxtInferExt};
|
||||
use rustc_infer::traits::util;
|
||||
use rustc_middle::ty::error::{ExpectedFound, TypeError};
|
||||
@ -78,10 +80,11 @@ fn compare_predicate_entailment<'tcx>(
|
||||
let trait_to_impl_substs = impl_trait_ref.substs;
|
||||
|
||||
// This node-id should be used for the `body_id` field on each
|
||||
// `ObligationCause` (and the `FnCtxt`). This is what
|
||||
// `regionck_item` expects.
|
||||
// `ObligationCause` (and the `FnCtxt`).
|
||||
//
|
||||
// FIXME(@lcnr): remove that after removing `cause.body_id` from
|
||||
// obligations.
|
||||
let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m.def_id.expect_local());
|
||||
|
||||
// We sometimes modify the span further down.
|
||||
let mut cause = ObligationCause::new(
|
||||
impl_m_span,
|
||||
@ -208,8 +211,7 @@ fn compare_predicate_entailment<'tcx>(
|
||||
Reveal::UserFacing,
|
||||
hir::Constness::NotConst,
|
||||
);
|
||||
let param_env =
|
||||
traits::normalize_param_env_or_error(tcx, impl_m.def_id, param_env, normalize_cause);
|
||||
let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
|
||||
|
||||
tcx.infer_ctxt().enter(|infcx| {
|
||||
let inh = Inherited::new(infcx, impl_m.def_id.expect_local());
|
||||
@ -399,8 +401,9 @@ fn compare_predicate_entailment<'tcx>(
|
||||
|
||||
// Finally, resolve all regions. This catches wily misuses of
|
||||
// lifetime parameters.
|
||||
let fcx = FnCtxt::new(&inh, param_env, impl_m_hir_id);
|
||||
fcx.regionck_item(impl_m_hir_id, impl_m_span, wf_tys);
|
||||
let mut outlives_environment = OutlivesEnvironment::new(param_env);
|
||||
outlives_environment.add_implied_bounds(infcx, wf_tys, impl_m_hir_id);
|
||||
infcx.check_region_obligations_and_report_errors(&outlives_environment);
|
||||
|
||||
Ok(())
|
||||
})
|
||||
@ -1155,8 +1158,8 @@ pub(crate) fn compare_const_impl<'tcx>(
|
||||
return;
|
||||
}
|
||||
|
||||
let fcx = FnCtxt::new(&inh, param_env, impl_c_hir_id);
|
||||
fcx.regionck_item(impl_c_hir_id, impl_c_span, FxHashSet::default());
|
||||
let outlives_environment = OutlivesEnvironment::new(param_env);
|
||||
infcx.resolve_regions_and_report_errors(&outlives_environment);
|
||||
});
|
||||
}
|
||||
|
||||
@ -1247,12 +1250,7 @@ fn compare_type_predicate_entailment<'tcx>(
|
||||
Reveal::UserFacing,
|
||||
hir::Constness::NotConst,
|
||||
);
|
||||
let param_env = traits::normalize_param_env_or_error(
|
||||
tcx,
|
||||
impl_ty.def_id,
|
||||
param_env,
|
||||
normalize_cause.clone(),
|
||||
);
|
||||
let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause.clone());
|
||||
tcx.infer_ctxt().enter(|infcx| {
|
||||
let inh = Inherited::new(infcx, impl_ty.def_id.expect_local());
|
||||
let infcx = &inh.infcx;
|
||||
@ -1279,8 +1277,8 @@ fn compare_type_predicate_entailment<'tcx>(
|
||||
|
||||
// Finally, resolve all regions. This catches wily misuses of
|
||||
// lifetime parameters.
|
||||
let fcx = FnCtxt::new(&inh, param_env, impl_ty_hir_id);
|
||||
fcx.regionck_item(impl_ty_hir_id, impl_ty_span, FxHashSet::default());
|
||||
let outlives_environment = OutlivesEnvironment::new(param_env);
|
||||
infcx.check_region_obligations_and_report_errors(&outlives_environment);
|
||||
|
||||
Ok(())
|
||||
})
|
||||
@ -1504,12 +1502,16 @@ pub fn check_type_bounds<'tcx>(
|
||||
|
||||
// Finally, resolve all regions. This catches wily misuses of
|
||||
// lifetime parameters.
|
||||
//
|
||||
// FIXME: Remove that `FnCtxt`.
|
||||
let fcx = FnCtxt::new(&inh, param_env, impl_ty_hir_id);
|
||||
let implied_bounds = match impl_ty.container {
|
||||
ty::TraitContainer(_) => FxHashSet::default(),
|
||||
ty::ImplContainer(def_id) => fcx.impl_implied_bounds(def_id, impl_ty_span),
|
||||
};
|
||||
fcx.regionck_item(impl_ty_hir_id, impl_ty_span, implied_bounds);
|
||||
let mut outlives_environment = OutlivesEnvironment::new(param_env);
|
||||
outlives_environment.add_implied_bounds(infcx, implied_bounds, impl_ty_hir_id);
|
||||
infcx.check_region_obligations_and_report_errors(&outlives_environment);
|
||||
|
||||
Ok(())
|
||||
})
|
||||
|
@ -1,5 +1,6 @@
|
||||
use crate::check::regionck::RegionCtxt;
|
||||
use crate::hir;
|
||||
// FIXME(@lcnr): Move this module out of `rustc_typeck`.
|
||||
//
|
||||
// We don't do any drop checking during hir typeck.
|
||||
use crate::hir::def_id::{DefId, LocalDefId};
|
||||
use rustc_errors::{struct_span_err, ErrorGuaranteed};
|
||||
use rustc_middle::ty::error::TypeError;
|
||||
@ -7,7 +8,6 @@ use rustc_middle::ty::relate::{Relate, RelateResult, TypeRelation};
|
||||
use rustc_middle::ty::subst::SubstsRef;
|
||||
use rustc_middle::ty::util::IgnoreRegions;
|
||||
use rustc_middle::ty::{self, Predicate, Ty, TyCtxt};
|
||||
use rustc_span::Span;
|
||||
|
||||
/// This function confirms that the `Drop` implementation identified by
|
||||
/// `drop_impl_did` is not any more specialized than the type it is
|
||||
@ -229,19 +229,6 @@ fn ensure_drop_predicates_are_implied_by_item_defn<'tcx>(
|
||||
result
|
||||
}
|
||||
|
||||
/// This function is not only checking that the dropck obligations are met for
|
||||
/// the given type, but it's also currently preventing non-regular recursion in
|
||||
/// types from causing stack overflows (dropck_no_diverge_on_nonregular_*.rs).
|
||||
///
|
||||
/// FIXME: Completely rip out dropck and regionck.
|
||||
pub(crate) fn check_drop_obligations<'a, 'tcx>(
|
||||
_rcx: &mut RegionCtxt<'a, 'tcx>,
|
||||
_ty: Ty<'tcx>,
|
||||
_span: Span,
|
||||
_body_id: hir::HirId,
|
||||
) {
|
||||
}
|
||||
|
||||
// This is an implementation of the TypeRelation trait with the
|
||||
// aim of simply comparing for equality (without side-effects).
|
||||
// It is not intended to be used anywhere else other than here.
|
||||
|
@ -368,7 +368,7 @@ fn typeck_with_fallback<'tcx>(
|
||||
|
||||
let typeck_results = Inherited::build(tcx, def_id).enter(|inh| {
|
||||
let param_env = tcx.param_env(def_id);
|
||||
let (fcx, wf_tys) = if let Some(hir::FnSig { header, decl, .. }) = fn_sig {
|
||||
let fcx = if let Some(hir::FnSig { header, decl, .. }) = fn_sig {
|
||||
let fn_sig = if crate::collect::get_infer_ret_ty(&decl.output).is_some() {
|
||||
let fcx = FnCtxt::new(&inh, param_env, body.value.hir_id);
|
||||
<dyn AstConv<'_>>::ty_of_fn(&fcx, id, header.unsafety, header.abi, decl, None, None)
|
||||
@ -378,13 +378,7 @@ fn typeck_with_fallback<'tcx>(
|
||||
|
||||
check_abi(tcx, id, span, fn_sig.abi());
|
||||
|
||||
// When normalizing the function signature, we assume all types are
|
||||
// well-formed. So, we don't need to worry about the obligations
|
||||
// from normalization. We could just discard these, but to align with
|
||||
// compare_method and elsewhere, we just add implied bounds for
|
||||
// these types.
|
||||
let mut wf_tys = FxHashSet::default();
|
||||
// Compute the fty from point of view of inside the fn.
|
||||
// Compute the function signature from point of view of inside the fn.
|
||||
let fn_sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), fn_sig);
|
||||
let fn_sig = inh.normalize_associated_types_in(
|
||||
body.value.span,
|
||||
@ -392,10 +386,7 @@ fn typeck_with_fallback<'tcx>(
|
||||
param_env,
|
||||
fn_sig,
|
||||
);
|
||||
wf_tys.extend(fn_sig.inputs_and_output.iter());
|
||||
|
||||
let fcx = check_fn(&inh, param_env, fn_sig, decl, id, body, None, true).0;
|
||||
(fcx, wf_tys)
|
||||
check_fn(&inh, param_env, fn_sig, decl, id, body, None, true).0
|
||||
} else {
|
||||
let fcx = FnCtxt::new(&inh, param_env, body.value.hir_id);
|
||||
let expected_type = body_ty
|
||||
@ -458,7 +449,7 @@ fn typeck_with_fallback<'tcx>(
|
||||
|
||||
fcx.write_ty(id, expected_type);
|
||||
|
||||
(fcx, FxHashSet::default())
|
||||
fcx
|
||||
};
|
||||
|
||||
let fallback_has_occurred = fcx.type_inference_fallback();
|
||||
@ -490,11 +481,7 @@ fn typeck_with_fallback<'tcx>(
|
||||
|
||||
fcx.check_asms();
|
||||
|
||||
if fn_sig.is_some() {
|
||||
fcx.regionck_fn(id, body, span, wf_tys);
|
||||
} else {
|
||||
fcx.regionck_expr(body);
|
||||
}
|
||||
fcx.infcx.skip_region_resolution();
|
||||
|
||||
fcx.resolve_type_vars_in_body(body)
|
||||
});
|
||||
|
@ -1,106 +1,9 @@
|
||||
//! The region check is a final pass that runs over the AST after we have
|
||||
//! inferred the type constraints but before we have actually finalized
|
||||
//! the types. Its purpose is to embed a variety of region constraints.
|
||||
//! Inserting these constraints as a separate pass is good because (1) it
|
||||
//! localizes the code that has to do with region inference and (2) often
|
||||
//! we cannot know what constraints are needed until the basic types have
|
||||
//! been inferred.
|
||||
//!
|
||||
//! ### Interaction with the borrow checker
|
||||
//!
|
||||
//! In general, the job of the borrowck module (which runs later) is to
|
||||
//! check that all soundness criteria are met, given a particular set of
|
||||
//! regions. The job of *this* module is to anticipate the needs of the
|
||||
//! borrow checker and infer regions that will satisfy its requirements.
|
||||
//! It is generally true that the inference doesn't need to be sound,
|
||||
//! meaning that if there is a bug and we inferred bad regions, the borrow
|
||||
//! checker should catch it. This is not entirely true though; for
|
||||
//! example, the borrow checker doesn't check subtyping, and it doesn't
|
||||
//! check that region pointers are always live when they are used. It
|
||||
//! might be worthwhile to fix this so that borrowck serves as a kind of
|
||||
//! verification step -- that would add confidence in the overall
|
||||
//! correctness of the compiler, at the cost of duplicating some type
|
||||
//! checks and effort.
|
||||
//!
|
||||
//! ### Inferring the duration of borrows, automatic and otherwise
|
||||
//!
|
||||
//! Whenever we introduce a borrowed pointer, for example as the result of
|
||||
//! a borrow expression `let x = &data`, the lifetime of the pointer `x`
|
||||
//! is always specified as a region inference variable. `regionck` has the
|
||||
//! job of adding constraints such that this inference variable is as
|
||||
//! narrow as possible while still accommodating all uses (that is, every
|
||||
//! dereference of the resulting pointer must be within the lifetime).
|
||||
//!
|
||||
//! #### Reborrows
|
||||
//!
|
||||
//! Generally speaking, `regionck` does NOT try to ensure that the data
|
||||
//! `data` will outlive the pointer `x`. That is the job of borrowck. The
|
||||
//! one exception is when "re-borrowing" the contents of another borrowed
|
||||
//! pointer. For example, imagine you have a borrowed pointer `b` with
|
||||
//! lifetime `L1` and you have an expression `&*b`. The result of this
|
||||
//! expression will be another borrowed pointer with lifetime `L2` (which is
|
||||
//! an inference variable). The borrow checker is going to enforce the
|
||||
//! constraint that `L2 < L1`, because otherwise you are re-borrowing data
|
||||
//! for a lifetime larger than the original loan. However, without the
|
||||
//! routines in this module, the region inferencer would not know of this
|
||||
//! dependency and thus it might infer the lifetime of `L2` to be greater
|
||||
//! than `L1` (issue #3148).
|
||||
//!
|
||||
//! There are a number of troublesome scenarios in the tests
|
||||
//! `region-dependent-*.rs`, but here is one example:
|
||||
//!
|
||||
//! struct Foo { i: i32 }
|
||||
//! struct Bar { foo: Foo }
|
||||
//! fn get_i<'a>(x: &'a Bar) -> &'a i32 {
|
||||
//! let foo = &x.foo; // Lifetime L1
|
||||
//! &foo.i // Lifetime L2
|
||||
//! }
|
||||
//!
|
||||
//! Note that this comes up either with `&` expressions, `ref`
|
||||
//! bindings, and `autorefs`, which are the three ways to introduce
|
||||
//! a borrow.
|
||||
//!
|
||||
//! The key point here is that when you are borrowing a value that
|
||||
//! is "guaranteed" by a borrowed pointer, you must link the
|
||||
//! lifetime of that borrowed pointer (`L1`, here) to the lifetime of
|
||||
//! the borrow itself (`L2`). What do I mean by "guaranteed" by a
|
||||
//! borrowed pointer? I mean any data that is reached by first
|
||||
//! dereferencing a borrowed pointer and then either traversing
|
||||
//! interior offsets or boxes. We say that the guarantor
|
||||
//! of such data is the region of the borrowed pointer that was
|
||||
//! traversed. This is essentially the same as the ownership
|
||||
//! relation, except that a borrowed pointer never owns its
|
||||
//! contents.
|
||||
|
||||
use crate::check::dropck;
|
||||
use crate::check::FnCtxt;
|
||||
use crate::mem_categorization as mc;
|
||||
use crate::outlives::outlives_bounds::InferCtxtExt as _;
|
||||
use rustc_data_structures::stable_set::FxHashSet;
|
||||
use rustc_hir as hir;
|
||||
use rustc_hir::def_id::LocalDefId;
|
||||
use rustc_hir::intravisit::{self, Visitor};
|
||||
use rustc_hir::PatKind;
|
||||
use rustc_infer::infer::outlives::env::OutlivesEnvironment;
|
||||
use rustc_infer::infer::{self, InferCtxt, RegionObligation};
|
||||
use rustc_middle::hir::place::{PlaceBase, PlaceWithHirId};
|
||||
use rustc_middle::ty::adjustment;
|
||||
use rustc_middle::ty::{self, Ty};
|
||||
use rustc_span::Span;
|
||||
use std::ops::Deref;
|
||||
|
||||
// a variation on try that just returns unit
|
||||
macro_rules! ignore_err {
|
||||
($e:expr) => {
|
||||
match $e {
|
||||
Ok(e) => e,
|
||||
Err(_) => {
|
||||
debug!("ignoring mem-categorization error!");
|
||||
return ();
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
use rustc_infer::infer::InferCtxt;
|
||||
use rustc_middle::ty::Ty;
|
||||
|
||||
pub(crate) trait OutlivesEnvironmentExt<'tcx> {
|
||||
fn add_implied_bounds(
|
||||
@ -108,7 +11,6 @@ pub(crate) trait OutlivesEnvironmentExt<'tcx> {
|
||||
infcx: &InferCtxt<'_, 'tcx>,
|
||||
fn_sig_tys: FxHashSet<Ty<'tcx>>,
|
||||
body_id: hir::HirId,
|
||||
span: Span,
|
||||
);
|
||||
}
|
||||
|
||||
@ -135,750 +37,11 @@ impl<'tcx> OutlivesEnvironmentExt<'tcx> for OutlivesEnvironment<'tcx> {
|
||||
infcx: &InferCtxt<'a, 'tcx>,
|
||||
fn_sig_tys: FxHashSet<Ty<'tcx>>,
|
||||
body_id: hir::HirId,
|
||||
span: Span,
|
||||
) {
|
||||
for ty in fn_sig_tys {
|
||||
let ty = infcx.resolve_vars_if_possible(ty);
|
||||
let implied_bounds = infcx.implied_outlives_bounds(self.param_env, body_id, ty, span);
|
||||
let implied_bounds = infcx.implied_outlives_bounds(self.param_env, body_id, ty);
|
||||
self.add_outlives_bounds(Some(infcx), implied_bounds)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// PUBLIC ENTRY POINTS
|
||||
|
||||
impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
|
||||
pub fn regionck_expr(&self, body: &'tcx hir::Body<'tcx>) {
|
||||
let subject = self.tcx.hir().body_owner_def_id(body.id());
|
||||
let id = body.value.hir_id;
|
||||
let mut rcx = RegionCtxt::new(self, id, Subject(subject), self.param_env);
|
||||
|
||||
// There are no add'l implied bounds when checking a
|
||||
// standalone expr (e.g., the `E` in a type like `[u32; E]`).
|
||||
rcx.outlives_environment.save_implied_bounds(id);
|
||||
|
||||
if !self.errors_reported_since_creation() {
|
||||
// regionck assumes typeck succeeded
|
||||
rcx.visit_body(body);
|
||||
rcx.visit_region_obligations(id);
|
||||
}
|
||||
// Checked by NLL
|
||||
rcx.fcx.skip_region_resolution();
|
||||
}
|
||||
|
||||
/// Region checking during the WF phase for items. `wf_tys` are the
|
||||
/// types from which we should derive implied bounds, if any.
|
||||
#[instrument(level = "debug", skip(self))]
|
||||
pub fn regionck_item(&self, item_id: hir::HirId, span: Span, wf_tys: FxHashSet<Ty<'tcx>>) {
|
||||
let subject = self.tcx.hir().local_def_id(item_id);
|
||||
let mut rcx = RegionCtxt::new(self, item_id, Subject(subject), self.param_env);
|
||||
rcx.outlives_environment.add_implied_bounds(self, wf_tys, item_id, span);
|
||||
rcx.outlives_environment.save_implied_bounds(item_id);
|
||||
rcx.visit_region_obligations(item_id);
|
||||
rcx.resolve_regions_and_report_errors();
|
||||
}
|
||||
|
||||
/// Region check a function body. Not invoked on closures, but
|
||||
/// only on the "root" fn item (in which closures may be
|
||||
/// embedded). Walks the function body and adds various add'l
|
||||
/// constraints that are needed for region inference. This is
|
||||
/// separated both to isolate "pure" region constraints from the
|
||||
/// rest of type check and because sometimes we need type
|
||||
/// inference to have completed before we can determine which
|
||||
/// constraints to add.
|
||||
pub(crate) fn regionck_fn(
|
||||
&self,
|
||||
fn_id: hir::HirId,
|
||||
body: &'tcx hir::Body<'tcx>,
|
||||
span: Span,
|
||||
wf_tys: FxHashSet<Ty<'tcx>>,
|
||||
) {
|
||||
debug!("regionck_fn(id={})", fn_id);
|
||||
let subject = self.tcx.hir().body_owner_def_id(body.id());
|
||||
let hir_id = body.value.hir_id;
|
||||
let mut rcx = RegionCtxt::new(self, hir_id, Subject(subject), self.param_env);
|
||||
// We need to add the implied bounds from the function signature
|
||||
rcx.outlives_environment.add_implied_bounds(self, wf_tys, fn_id, span);
|
||||
rcx.outlives_environment.save_implied_bounds(fn_id);
|
||||
|
||||
if !self.errors_reported_since_creation() {
|
||||
// regionck assumes typeck succeeded
|
||||
rcx.visit_fn_body(fn_id, body, self.tcx.hir().span(fn_id));
|
||||
}
|
||||
|
||||
// Checked by NLL
|
||||
rcx.fcx.skip_region_resolution();
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// INTERNALS
|
||||
|
||||
pub struct RegionCtxt<'a, 'tcx> {
|
||||
pub fcx: &'a FnCtxt<'a, 'tcx>,
|
||||
|
||||
outlives_environment: OutlivesEnvironment<'tcx>,
|
||||
|
||||
// id of innermost fn body id
|
||||
body_id: hir::HirId,
|
||||
body_owner: LocalDefId,
|
||||
|
||||
// id of AST node being analyzed (the subject of the analysis).
|
||||
subject_def_id: LocalDefId,
|
||||
}
|
||||
|
||||
impl<'a, 'tcx> Deref for RegionCtxt<'a, 'tcx> {
|
||||
type Target = FnCtxt<'a, 'tcx>;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.fcx
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Subject(LocalDefId);
|
||||
|
||||
impl<'a, 'tcx> RegionCtxt<'a, 'tcx> {
|
||||
pub fn new(
|
||||
fcx: &'a FnCtxt<'a, 'tcx>,
|
||||
initial_body_id: hir::HirId,
|
||||
Subject(subject): Subject,
|
||||
param_env: ty::ParamEnv<'tcx>,
|
||||
) -> RegionCtxt<'a, 'tcx> {
|
||||
let outlives_environment = OutlivesEnvironment::new(param_env);
|
||||
RegionCtxt {
|
||||
fcx,
|
||||
body_id: initial_body_id,
|
||||
body_owner: subject,
|
||||
subject_def_id: subject,
|
||||
outlives_environment,
|
||||
}
|
||||
}
|
||||
|
||||
/// Try to resolve the type for the given node, returning `t_err` if an error results. Note that
|
||||
/// we never care about the details of the error, the same error will be detected and reported
|
||||
/// in the writeback phase.
|
||||
///
|
||||
/// Note one important point: we do not attempt to resolve *region variables* here. This is
|
||||
/// because regionck is essentially adding constraints to those region variables and so may yet
|
||||
/// influence how they are resolved.
|
||||
///
|
||||
/// Consider this silly example:
|
||||
///
|
||||
/// ```ignore UNSOLVED (does replacing @i32 with Box<i32> preserve the desired semantics for the example?)
|
||||
/// fn borrow(x: &i32) -> &i32 {x}
|
||||
/// fn foo(x: @i32) -> i32 { // block: B
|
||||
/// let b = borrow(x); // region: <R0>
|
||||
/// *b
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Here, the region of `b` will be `<R0>`. `<R0>` is constrained to be some subregion of the
|
||||
/// block B and some superregion of the call. If we forced it now, we'd choose the smaller
|
||||
/// region (the call). But that would make the *b illegal. Since we don't resolve, the type
|
||||
/// of b will be `&<R0>.i32` and then `*b` will require that `<R0>` be bigger than the let and
|
||||
/// the `*b` expression, so we will effectively resolve `<R0>` to be the block B.
|
||||
pub fn resolve_type(&self, unresolved_ty: Ty<'tcx>) -> Ty<'tcx> {
|
||||
self.resolve_vars_if_possible(unresolved_ty)
|
||||
}
|
||||
|
||||
/// Try to resolve the type for the given node.
|
||||
fn resolve_node_type(&self, id: hir::HirId) -> Ty<'tcx> {
|
||||
let t = self.node_ty(id);
|
||||
self.resolve_type(t)
|
||||
}
|
||||
|
||||
/// This is the "main" function when region-checking a function item or a
|
||||
/// closure within a function item. It begins by updating various fields
|
||||
/// (e.g., `outlives_environment`) to be appropriate to the function and
|
||||
/// then adds constraints derived from the function body.
|
||||
///
|
||||
/// Note that it does **not** restore the state of the fields that
|
||||
/// it updates! This is intentional, since -- for the main
|
||||
/// function -- we wish to be able to read the final
|
||||
/// `outlives_environment` and other fields from the caller. For
|
||||
/// closures, however, we save and restore any "scoped state"
|
||||
/// before we invoke this function. (See `visit_fn` in the
|
||||
/// `intravisit::Visitor` impl below.)
|
||||
fn visit_fn_body(
|
||||
&mut self,
|
||||
id: hir::HirId, // the id of the fn itself
|
||||
body: &'tcx hir::Body<'tcx>,
|
||||
span: Span,
|
||||
) {
|
||||
// When we enter a function, we can derive
|
||||
debug!("visit_fn_body(id={:?})", id);
|
||||
|
||||
let body_id = body.id();
|
||||
self.body_id = body_id.hir_id;
|
||||
self.body_owner = self.tcx.hir().body_owner_def_id(body_id);
|
||||
|
||||
let Some(fn_sig) = self.typeck_results.borrow().liberated_fn_sigs().get(id) else {
|
||||
bug!("No fn-sig entry for id={:?}", id);
|
||||
};
|
||||
|
||||
// Collect the types from which we create inferred bounds.
|
||||
// For the return type, if diverging, substitute `bool` just
|
||||
// because it will have no effect.
|
||||
//
|
||||
// FIXME(#27579) return types should not be implied bounds
|
||||
let fn_sig_tys: FxHashSet<_> =
|
||||
fn_sig.inputs().iter().cloned().chain(Some(fn_sig.output())).collect();
|
||||
|
||||
self.outlives_environment.add_implied_bounds(self.fcx, fn_sig_tys, body_id.hir_id, span);
|
||||
self.outlives_environment.save_implied_bounds(body_id.hir_id);
|
||||
self.link_fn_params(body.params);
|
||||
self.visit_body(body);
|
||||
self.visit_region_obligations(body_id.hir_id);
|
||||
}
|
||||
|
||||
fn visit_inline_const(&mut self, id: hir::HirId, body: &'tcx hir::Body<'tcx>) {
|
||||
debug!("visit_inline_const(id={:?})", id);
|
||||
|
||||
// Save state of current function. We will restore afterwards.
|
||||
let old_body_id = self.body_id;
|
||||
let old_body_owner = self.body_owner;
|
||||
let env_snapshot = self.outlives_environment.push_snapshot_pre_typeck_child();
|
||||
|
||||
let body_id = body.id();
|
||||
self.body_id = body_id.hir_id;
|
||||
self.body_owner = self.tcx.hir().body_owner_def_id(body_id);
|
||||
|
||||
self.outlives_environment.save_implied_bounds(body_id.hir_id);
|
||||
|
||||
self.visit_body(body);
|
||||
self.visit_region_obligations(body_id.hir_id);
|
||||
|
||||
// Restore state from previous function.
|
||||
self.outlives_environment.pop_snapshot_post_typeck_child(env_snapshot);
|
||||
self.body_id = old_body_id;
|
||||
self.body_owner = old_body_owner;
|
||||
}
|
||||
|
||||
fn visit_region_obligations(&mut self, hir_id: hir::HirId) {
|
||||
debug!("visit_region_obligations: hir_id={:?}", hir_id);
|
||||
|
||||
// region checking can introduce new pending obligations
|
||||
// which, when processed, might generate new region
|
||||
// obligations. So make sure we process those.
|
||||
self.select_all_obligations_or_error();
|
||||
}
|
||||
|
||||
fn resolve_regions_and_report_errors(&self) {
|
||||
self.infcx.process_registered_region_obligations(
|
||||
self.outlives_environment.region_bound_pairs_map(),
|
||||
self.param_env,
|
||||
);
|
||||
|
||||
self.fcx.resolve_regions_and_report_errors(
|
||||
self.subject_def_id.to_def_id(),
|
||||
&self.outlives_environment,
|
||||
);
|
||||
}
|
||||
|
||||
fn constrain_bindings_in_pat(&mut self, pat: &hir::Pat<'_>) {
|
||||
debug!("regionck::visit_pat(pat={:?})", pat);
|
||||
pat.each_binding(|_, hir_id, span, _| {
|
||||
let typ = self.resolve_node_type(hir_id);
|
||||
let body_id = self.body_id;
|
||||
dropck::check_drop_obligations(self, typ, span, body_id);
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, 'tcx> Visitor<'tcx> for RegionCtxt<'a, 'tcx> {
|
||||
// (..) FIXME(#3238) should use visit_pat, not visit_arm/visit_local,
|
||||
// However, right now we run into an issue whereby some free
|
||||
// regions are not properly related if they appear within the
|
||||
// types of arguments that must be inferred. This could be
|
||||
// addressed by deferring the construction of the region
|
||||
// hierarchy, and in particular the relationships between free
|
||||
// regions, until regionck, as described in #3238.
|
||||
|
||||
fn visit_fn(
|
||||
&mut self,
|
||||
fk: intravisit::FnKind<'tcx>,
|
||||
_: &'tcx hir::FnDecl<'tcx>,
|
||||
body_id: hir::BodyId,
|
||||
span: Span,
|
||||
hir_id: hir::HirId,
|
||||
) {
|
||||
assert!(
|
||||
matches!(fk, intravisit::FnKind::Closure),
|
||||
"visit_fn invoked for something other than a closure"
|
||||
);
|
||||
|
||||
// Save state of current function before invoking
|
||||
// `visit_fn_body`. We will restore afterwards.
|
||||
let old_body_id = self.body_id;
|
||||
let old_body_owner = self.body_owner;
|
||||
let env_snapshot = self.outlives_environment.push_snapshot_pre_typeck_child();
|
||||
|
||||
let body = self.tcx.hir().body(body_id);
|
||||
self.visit_fn_body(hir_id, body, span);
|
||||
|
||||
// Restore state from previous function.
|
||||
self.outlives_environment.pop_snapshot_post_typeck_child(env_snapshot);
|
||||
self.body_id = old_body_id;
|
||||
self.body_owner = old_body_owner;
|
||||
}
|
||||
|
||||
//visit_pat: visit_pat, // (..) see above
|
||||
|
||||
fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
|
||||
// see above
|
||||
self.constrain_bindings_in_pat(arm.pat);
|
||||
intravisit::walk_arm(self, arm);
|
||||
}
|
||||
|
||||
fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) {
|
||||
// see above
|
||||
self.constrain_bindings_in_pat(l.pat);
|
||||
self.link_local(l);
|
||||
intravisit::walk_local(self, l);
|
||||
}
|
||||
|
||||
fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
|
||||
// Check any autoderefs or autorefs that appear.
|
||||
let cmt_result = self.constrain_adjustments(expr);
|
||||
|
||||
// If necessary, constrain destructors in this expression. This will be
|
||||
// the adjusted form if there is an adjustment.
|
||||
match cmt_result {
|
||||
Ok(head_cmt) => {
|
||||
self.check_safety_of_rvalue_destructor_if_necessary(&head_cmt, expr.span);
|
||||
}
|
||||
Err(..) => {
|
||||
self.tcx.sess.delay_span_bug(expr.span, "cat_expr Errd");
|
||||
}
|
||||
}
|
||||
|
||||
match expr.kind {
|
||||
hir::ExprKind::AddrOf(hir::BorrowKind::Ref, m, ref base) => {
|
||||
self.link_addr_of(expr, m, base);
|
||||
|
||||
intravisit::walk_expr(self, expr);
|
||||
}
|
||||
|
||||
hir::ExprKind::Match(ref discr, arms, _) => {
|
||||
self.link_match(discr, arms);
|
||||
|
||||
intravisit::walk_expr(self, expr);
|
||||
}
|
||||
|
||||
hir::ExprKind::ConstBlock(anon_const) => {
|
||||
let body = self.tcx.hir().body(anon_const.body);
|
||||
self.visit_inline_const(anon_const.hir_id, body);
|
||||
}
|
||||
|
||||
_ => intravisit::walk_expr(self, expr),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, 'tcx> RegionCtxt<'a, 'tcx> {
|
||||
/// Creates a temporary `MemCategorizationContext` and pass it to the closure.
|
||||
fn with_mc<F, R>(&self, f: F) -> R
|
||||
where
|
||||
F: for<'b> FnOnce(mc::MemCategorizationContext<'b, 'tcx>) -> R,
|
||||
{
|
||||
f(mc::MemCategorizationContext::new(
|
||||
&self.infcx,
|
||||
self.outlives_environment.param_env,
|
||||
self.body_owner,
|
||||
&self.typeck_results.borrow(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Invoked on any adjustments that occur. Checks that if this is a region pointer being
|
||||
/// dereferenced, the lifetime of the pointer includes the deref expr.
|
||||
fn constrain_adjustments(
|
||||
&mut self,
|
||||
expr: &hir::Expr<'_>,
|
||||
) -> mc::McResult<PlaceWithHirId<'tcx>> {
|
||||
debug!("constrain_adjustments(expr={:?})", expr);
|
||||
|
||||
let mut place = self.with_mc(|mc| mc.cat_expr_unadjusted(expr))?;
|
||||
|
||||
let typeck_results = self.typeck_results.borrow();
|
||||
let adjustments = typeck_results.expr_adjustments(expr);
|
||||
if adjustments.is_empty() {
|
||||
return Ok(place);
|
||||
}
|
||||
|
||||
debug!("constrain_adjustments: adjustments={:?}", adjustments);
|
||||
|
||||
// If necessary, constrain destructors in the unadjusted form of this
|
||||
// expression.
|
||||
self.check_safety_of_rvalue_destructor_if_necessary(&place, expr.span);
|
||||
|
||||
for adjustment in adjustments {
|
||||
debug!("constrain_adjustments: adjustment={:?}, place={:?}", adjustment, place);
|
||||
|
||||
if let adjustment::Adjust::Deref(Some(deref)) = adjustment.kind {
|
||||
self.link_region(
|
||||
expr.span,
|
||||
deref.region,
|
||||
ty::BorrowKind::from_mutbl(deref.mutbl),
|
||||
&place,
|
||||
);
|
||||
}
|
||||
|
||||
if let adjustment::Adjust::Borrow(ref autoref) = adjustment.kind {
|
||||
self.link_autoref(expr, &place, autoref);
|
||||
}
|
||||
|
||||
place = self.with_mc(|mc| mc.cat_expr_adjusted(expr, place, adjustment))?;
|
||||
}
|
||||
|
||||
Ok(place)
|
||||
}
|
||||
|
||||
fn check_safety_of_rvalue_destructor_if_necessary(
|
||||
&mut self,
|
||||
place_with_id: &PlaceWithHirId<'tcx>,
|
||||
span: Span,
|
||||
) {
|
||||
if let PlaceBase::Rvalue = place_with_id.place.base {
|
||||
if place_with_id.place.projections.is_empty() {
|
||||
let typ = self.resolve_type(place_with_id.place.ty());
|
||||
let body_id = self.body_id;
|
||||
dropck::check_drop_obligations(self, typ, span, body_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Adds constraints to inference such that `T: 'a` holds (or
|
||||
/// reports an error if it cannot).
|
||||
///
|
||||
/// # Parameters
|
||||
///
|
||||
/// - `origin`, the reason we need this constraint
|
||||
/// - `ty`, the type `T`
|
||||
/// - `region`, the region `'a`
|
||||
pub fn type_must_outlive(
|
||||
&self,
|
||||
origin: infer::SubregionOrigin<'tcx>,
|
||||
ty: Ty<'tcx>,
|
||||
region: ty::Region<'tcx>,
|
||||
) {
|
||||
self.infcx.register_region_obligation(
|
||||
self.body_id,
|
||||
RegionObligation { sub_region: region, sup_type: ty, origin },
|
||||
);
|
||||
}
|
||||
|
||||
/// Computes the guarantor for an expression `&base` and then ensures that the lifetime of the
|
||||
/// resulting pointer is linked to the lifetime of its guarantor (if any).
|
||||
fn link_addr_of(
|
||||
&mut self,
|
||||
expr: &hir::Expr<'_>,
|
||||
mutability: hir::Mutability,
|
||||
base: &hir::Expr<'_>,
|
||||
) {
|
||||
debug!("link_addr_of(expr={:?}, base={:?})", expr, base);
|
||||
|
||||
let cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(base)));
|
||||
|
||||
debug!("link_addr_of: cmt={:?}", cmt);
|
||||
|
||||
self.link_region_from_node_type(expr.span, expr.hir_id, mutability, &cmt);
|
||||
}
|
||||
|
||||
/// Computes the guarantors for any ref bindings in a `let` and
|
||||
/// then ensures that the lifetime of the resulting pointer is
|
||||
/// linked to the lifetime of the initialization expression.
|
||||
fn link_local(&self, local: &hir::Local<'_>) {
|
||||
debug!("regionck::for_local()");
|
||||
let init_expr = match local.init {
|
||||
None => {
|
||||
return;
|
||||
}
|
||||
Some(expr) => &*expr,
|
||||
};
|
||||
let discr_cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(init_expr)));
|
||||
self.link_pattern(discr_cmt, local.pat);
|
||||
}
|
||||
|
||||
/// Computes the guarantors for any ref bindings in a match and
|
||||
/// then ensures that the lifetime of the resulting pointer is
|
||||
/// linked to the lifetime of its guarantor (if any).
|
||||
fn link_match(&self, discr: &hir::Expr<'_>, arms: &[hir::Arm<'_>]) {
|
||||
debug!("regionck::for_match()");
|
||||
let discr_cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(discr)));
|
||||
debug!("discr_cmt={:?}", discr_cmt);
|
||||
for arm in arms {
|
||||
self.link_pattern(discr_cmt.clone(), arm.pat);
|
||||
}
|
||||
}
|
||||
|
||||
/// Computes the guarantors for any ref bindings in a match and
|
||||
/// then ensures that the lifetime of the resulting pointer is
|
||||
/// linked to the lifetime of its guarantor (if any).
|
||||
fn link_fn_params(&self, params: &[hir::Param<'_>]) {
|
||||
for param in params {
|
||||
let param_ty = self.node_ty(param.hir_id);
|
||||
let param_cmt =
|
||||
self.with_mc(|mc| mc.cat_rvalue(param.hir_id, param.pat.span, param_ty));
|
||||
debug!("param_ty={:?} param_cmt={:?} param={:?}", param_ty, param_cmt, param);
|
||||
self.link_pattern(param_cmt, param.pat);
|
||||
}
|
||||
}
|
||||
|
||||
/// Link lifetimes of any ref bindings in `root_pat` to the pointers found
|
||||
/// in the discriminant, if needed.
|
||||
fn link_pattern(&self, discr_cmt: PlaceWithHirId<'tcx>, root_pat: &hir::Pat<'_>) {
|
||||
debug!("link_pattern(discr_cmt={:?}, root_pat={:?})", discr_cmt, root_pat);
|
||||
ignore_err!(self.with_mc(|mc| {
|
||||
mc.cat_pattern(discr_cmt, root_pat, |sub_cmt, hir::Pat { kind, span, hir_id, .. }| {
|
||||
// `ref x` pattern
|
||||
if let PatKind::Binding(..) = kind
|
||||
&& let Some(ty::BindByReference(mutbl)) = mc.typeck_results.extract_binding_mode(self.tcx.sess, *hir_id, *span) {
|
||||
self.link_region_from_node_type(*span, *hir_id, mutbl, sub_cmt);
|
||||
}
|
||||
})
|
||||
}));
|
||||
}
|
||||
|
||||
/// Link lifetime of borrowed pointer resulting from autoref to lifetimes in the value being
|
||||
/// autoref'd.
|
||||
fn link_autoref(
|
||||
&self,
|
||||
expr: &hir::Expr<'_>,
|
||||
expr_cmt: &PlaceWithHirId<'tcx>,
|
||||
autoref: &adjustment::AutoBorrow<'tcx>,
|
||||
) {
|
||||
debug!("link_autoref(autoref={:?}, expr_cmt={:?})", autoref, expr_cmt);
|
||||
|
||||
match *autoref {
|
||||
adjustment::AutoBorrow::Ref(r, m) => {
|
||||
self.link_region(expr.span, r, ty::BorrowKind::from_mutbl(m.into()), expr_cmt);
|
||||
}
|
||||
|
||||
adjustment::AutoBorrow::RawPtr(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Like `link_region()`, except that the region is extracted from the type of `id`,
|
||||
/// which must be some reference (`&T`, `&str`, etc).
|
||||
fn link_region_from_node_type(
|
||||
&self,
|
||||
span: Span,
|
||||
id: hir::HirId,
|
||||
mutbl: hir::Mutability,
|
||||
cmt_borrowed: &PlaceWithHirId<'tcx>,
|
||||
) {
|
||||
debug!(
|
||||
"link_region_from_node_type(id={:?}, mutbl={:?}, cmt_borrowed={:?})",
|
||||
id, mutbl, cmt_borrowed
|
||||
);
|
||||
|
||||
let rptr_ty = self.resolve_node_type(id);
|
||||
if let ty::Ref(r, _, _) = rptr_ty.kind() {
|
||||
debug!("rptr_ty={}", rptr_ty);
|
||||
self.link_region(span, *r, ty::BorrowKind::from_mutbl(mutbl), cmt_borrowed);
|
||||
}
|
||||
}
|
||||
|
||||
/// Informs the inference engine that `borrow_cmt` is being borrowed with
|
||||
/// kind `borrow_kind` and lifetime `borrow_region`.
|
||||
/// In order to ensure borrowck is satisfied, this may create constraints
|
||||
/// between regions, as explained in `link_reborrowed_region()`.
|
||||
fn link_region(
|
||||
&self,
|
||||
span: Span,
|
||||
borrow_region: ty::Region<'tcx>,
|
||||
borrow_kind: ty::BorrowKind,
|
||||
borrow_place: &PlaceWithHirId<'tcx>,
|
||||
) {
|
||||
let origin = infer::DataBorrowed(borrow_place.place.ty(), span);
|
||||
self.type_must_outlive(origin, borrow_place.place.ty(), borrow_region);
|
||||
|
||||
for pointer_ty in borrow_place.place.deref_tys() {
|
||||
debug!(
|
||||
"link_region(borrow_region={:?}, borrow_kind={:?}, pointer_ty={:?})",
|
||||
borrow_region, borrow_kind, borrow_place
|
||||
);
|
||||
match *pointer_ty.kind() {
|
||||
ty::RawPtr(_) => return,
|
||||
ty::Ref(ref_region, _, ref_mutability) => {
|
||||
if self.link_reborrowed_region(span, borrow_region, ref_region, ref_mutability)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
_ => assert!(pointer_ty.is_box(), "unexpected built-in deref type {}", pointer_ty),
|
||||
}
|
||||
}
|
||||
if let PlaceBase::Upvar(upvar_id) = borrow_place.place.base {
|
||||
self.link_upvar_region(span, borrow_region, upvar_id);
|
||||
}
|
||||
}
|
||||
|
||||
/// This is the most complicated case: the path being borrowed is
|
||||
/// itself the referent of a borrowed pointer. Let me give an
|
||||
/// example fragment of code to make clear(er) the situation:
|
||||
///
|
||||
/// ```ignore (incomplete Rust code)
|
||||
/// let r: &'a mut T = ...; // the original reference "r" has lifetime 'a
|
||||
/// ...
|
||||
/// &'z *r // the reborrow has lifetime 'z
|
||||
/// ```
|
||||
///
|
||||
/// Now, in this case, our primary job is to add the inference
|
||||
/// constraint that `'z <= 'a`. Given this setup, let's clarify the
|
||||
/// parameters in (roughly) terms of the example:
|
||||
///
|
||||
/// ```plain,ignore (pseudo-Rust)
|
||||
/// A borrow of: `& 'z bk * r` where `r` has type `& 'a bk T`
|
||||
/// borrow_region ^~ ref_region ^~
|
||||
/// borrow_kind ^~ ref_kind ^~
|
||||
/// ref_cmt ^
|
||||
/// ```
|
||||
///
|
||||
/// Here `bk` stands for some borrow-kind (e.g., `mut`, `uniq`, etc).
|
||||
///
|
||||
/// There is a complication beyond the simple scenario I just painted: there
|
||||
/// may in fact be more levels of reborrowing. In the example, I said the
|
||||
/// borrow was like `&'z *r`, but it might in fact be a borrow like
|
||||
/// `&'z **q` where `q` has type `&'a &'b mut T`. In that case, we want to
|
||||
/// ensure that `'z <= 'a` and `'z <= 'b`.
|
||||
///
|
||||
/// The return value of this function indicates whether we *don't* need to
|
||||
/// the recurse to the next reference up.
|
||||
///
|
||||
/// This is explained more below.
|
||||
fn link_reborrowed_region(
|
||||
&self,
|
||||
span: Span,
|
||||
borrow_region: ty::Region<'tcx>,
|
||||
ref_region: ty::Region<'tcx>,
|
||||
ref_mutability: hir::Mutability,
|
||||
) -> bool {
|
||||
debug!("link_reborrowed_region: {:?} <= {:?}", borrow_region, ref_region);
|
||||
self.sub_regions(infer::Reborrow(span), borrow_region, ref_region);
|
||||
|
||||
// Decide whether we need to recurse and link any regions within
|
||||
// the `ref_cmt`. This is concerned for the case where the value
|
||||
// being reborrowed is in fact a borrowed pointer found within
|
||||
// another borrowed pointer. For example:
|
||||
//
|
||||
// let p: &'b &'a mut T = ...;
|
||||
// ...
|
||||
// &'z **p
|
||||
//
|
||||
// What makes this case particularly tricky is that, if the data
|
||||
// being borrowed is a `&mut` or `&uniq` borrow, borrowck requires
|
||||
// not only that `'z <= 'a`, (as before) but also `'z <= 'b`
|
||||
// (otherwise the user might mutate through the `&mut T` reference
|
||||
// after `'b` expires and invalidate the borrow we are looking at
|
||||
// now).
|
||||
//
|
||||
// So let's re-examine our parameters in light of this more
|
||||
// complicated (possible) scenario:
|
||||
//
|
||||
// A borrow of: `& 'z bk * * p` where `p` has type `&'b bk & 'a bk T`
|
||||
// borrow_region ^~ ref_region ^~
|
||||
// borrow_kind ^~ ref_kind ^~
|
||||
// ref_cmt ^~~
|
||||
//
|
||||
// (Note that since we have not examined `ref_cmt.cat`, we don't
|
||||
// know whether this scenario has occurred; but I wanted to show
|
||||
// how all the types get adjusted.)
|
||||
match ref_mutability {
|
||||
hir::Mutability::Not => {
|
||||
// The reference being reborrowed is a shareable ref of
|
||||
// type `&'a T`. In this case, it doesn't matter where we
|
||||
// *found* the `&T` pointer, the memory it references will
|
||||
// be valid and immutable for `'a`. So we can stop here.
|
||||
true
|
||||
}
|
||||
|
||||
hir::Mutability::Mut => {
|
||||
// The reference being reborrowed is either an `&mut T`. This is
|
||||
// the case where recursion is needed.
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An upvar may be behind up to 2 references:
|
||||
///
|
||||
/// * One can come from the reference to a "by-reference" upvar.
|
||||
/// * Another one can come from the reference to the closure itself if it's
|
||||
/// a `FnMut` or `Fn` closure.
|
||||
///
|
||||
/// This function links the lifetimes of those references to the lifetime
|
||||
/// of the borrow that's provided. See [RegionCtxt::link_reborrowed_region] for some
|
||||
/// more explanation of this in the general case.
|
||||
///
|
||||
/// We also supply a *cause*, and in this case we set the cause to
|
||||
/// indicate that the reference being "reborrowed" is itself an upvar. This
|
||||
/// provides a nicer error message should something go wrong.
|
||||
fn link_upvar_region(
|
||||
&self,
|
||||
span: Span,
|
||||
borrow_region: ty::Region<'tcx>,
|
||||
upvar_id: ty::UpvarId,
|
||||
) {
|
||||
debug!("link_upvar_region(borrorw_region={:?}, upvar_id={:?}", borrow_region, upvar_id);
|
||||
// A by-reference upvar can't be borrowed for longer than the
|
||||
// upvar is borrowed from the environment.
|
||||
let closure_local_def_id = upvar_id.closure_expr_id;
|
||||
let mut all_captures_are_imm_borrow = true;
|
||||
for captured_place in self
|
||||
.typeck_results
|
||||
.borrow()
|
||||
.closure_min_captures
|
||||
.get(&closure_local_def_id.to_def_id())
|
||||
.and_then(|root_var_min_cap| root_var_min_cap.get(&upvar_id.var_path.hir_id))
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
match captured_place.info.capture_kind {
|
||||
ty::UpvarCapture::ByRef(upvar_borrow) => {
|
||||
self.sub_regions(
|
||||
infer::ReborrowUpvar(span, upvar_id),
|
||||
borrow_region,
|
||||
captured_place.region.unwrap(),
|
||||
);
|
||||
if let ty::ImmBorrow = upvar_borrow {
|
||||
debug!("link_upvar_region: capture by shared ref");
|
||||
} else {
|
||||
all_captures_are_imm_borrow = false;
|
||||
}
|
||||
}
|
||||
ty::UpvarCapture::ByValue => {
|
||||
all_captures_are_imm_borrow = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if all_captures_are_imm_borrow {
|
||||
return;
|
||||
}
|
||||
let fn_hir_id = self.tcx.hir().local_def_id_to_hir_id(closure_local_def_id);
|
||||
let ty = self.resolve_node_type(fn_hir_id);
|
||||
debug!("link_upvar_region: ty={:?}", ty);
|
||||
|
||||
// A closure capture can't be borrowed for longer than the
|
||||
// reference to the closure.
|
||||
if let ty::Closure(_, substs) = ty.kind() {
|
||||
match self.infcx.closure_kind(substs) {
|
||||
Some(ty::ClosureKind::Fn | ty::ClosureKind::FnMut) => {
|
||||
// Region of environment pointer
|
||||
let env_region = self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
|
||||
scope: upvar_id.closure_expr_id.to_def_id(),
|
||||
bound_region: ty::BrEnv,
|
||||
}));
|
||||
self.sub_regions(
|
||||
infer::ReborrowUpvar(span, upvar_id),
|
||||
borrow_region,
|
||||
env_region,
|
||||
);
|
||||
}
|
||||
Some(ty::ClosureKind::FnOnce) => {}
|
||||
None => {
|
||||
span_bug!(span, "Have not inferred closure kind before regionck");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -62,7 +62,10 @@ impl<'tcx> CheckWfFcxBuilder<'tcx> {
|
||||
}
|
||||
let wf_tys = f(&fcx);
|
||||
fcx.select_all_obligations_or_error();
|
||||
fcx.regionck_item(id, span, wf_tys);
|
||||
|
||||
let mut outlives_environment = OutlivesEnvironment::new(param_env);
|
||||
outlives_environment.add_implied_bounds(&fcx.infcx, wf_tys, id);
|
||||
fcx.infcx.check_region_obligations_and_report_errors(&outlives_environment);
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -655,13 +658,12 @@ fn resolve_regions_with_wf_tys<'tcx>(
|
||||
// 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");
|
||||
|
||||
|
@ -349,7 +349,7 @@ fn visit_implementation_of_dispatch_from_dyn<'tcx>(tcx: TyCtxt<'tcx>, impl_did:
|
||||
|
||||
// Finally, resolve all regions.
|
||||
let outlives_env = OutlivesEnvironment::new(param_env);
|
||||
infcx.resolve_regions_and_report_errors(impl_did.to_def_id(), &outlives_env);
|
||||
infcx.resolve_regions_and_report_errors(&outlives_env);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
@ -606,7 +606,7 @@ pub fn coerce_unsized_info<'tcx>(tcx: TyCtxt<'tcx>, impl_did: DefId) -> CoerceUn
|
||||
|
||||
// Finally, resolve all regions.
|
||||
let outlives_env = OutlivesEnvironment::new(param_env);
|
||||
infcx.resolve_regions_and_report_errors(impl_did.to_def_id(), &outlives_env);
|
||||
infcx.resolve_regions_and_report_errors(&outlives_env);
|
||||
|
||||
CoerceUnsizedInfo { custom_kind: kind }
|
||||
})
|
||||
|
@ -150,7 +150,7 @@ fn get_impl_substs<'tcx>(
|
||||
|
||||
// Conservatively use an empty `ParamEnv`.
|
||||
let outlives_env = OutlivesEnvironment::new(ty::ParamEnv::empty());
|
||||
infcx.resolve_regions_and_report_errors(impl1_def_id.to_def_id(), &outlives_env);
|
||||
infcx.resolve_regions_and_report_errors(&outlives_env);
|
||||
let Ok(impl2_substs) = infcx.fully_resolve(impl2_substs) else {
|
||||
let span = tcx.def_span(impl1_def_id);
|
||||
tcx.sess.emit_err(SubstsOnOverriddenImpl { span });
|
||||
|
@ -1,6 +1,5 @@
|
||||
use rustc_hir as hir;
|
||||
use rustc_middle::ty::{self, Ty};
|
||||
use rustc_span::source_map::Span;
|
||||
use rustc_trait_selection::infer::InferCtxt;
|
||||
use rustc_trait_selection::traits::query::type_op::{self, TypeOp, TypeOpOutput};
|
||||
use rustc_trait_selection::traits::query::NoSolution;
|
||||
@ -14,7 +13,6 @@ pub trait InferCtxtExt<'tcx> {
|
||||
param_env: ty::ParamEnv<'tcx>,
|
||||
body_id: hir::HirId,
|
||||
ty: Ty<'tcx>,
|
||||
span: Span,
|
||||
) -> Vec<OutlivesBound<'tcx>>;
|
||||
}
|
||||
|
||||
@ -38,16 +36,14 @@ impl<'cx, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'cx, 'tcx> {
|
||||
/// Note that this may cause outlives obligations to be injected
|
||||
/// into the inference context with this body-id.
|
||||
/// - `ty`, the type that we are supposed to assume is WF.
|
||||
/// - `span`, a span to use when normalizing, hopefully not important,
|
||||
/// might be useful if a `bug!` occurs.
|
||||
#[instrument(level = "debug", skip(self, param_env, body_id, span))]
|
||||
#[instrument(level = "debug", skip(self, param_env, body_id))]
|
||||
fn implied_outlives_bounds(
|
||||
&self,
|
||||
param_env: ty::ParamEnv<'tcx>,
|
||||
body_id: hir::HirId,
|
||||
ty: Ty<'tcx>,
|
||||
span: Span,
|
||||
) -> Vec<OutlivesBound<'tcx>> {
|
||||
let span = self.tcx.hir().span(body_id);
|
||||
let result = param_env
|
||||
.and(type_op::implied_outlives_bounds::ImpliedOutlivesBounds { ty })
|
||||
.fully_perform(self);
|
||||
|
Loading…
Reference in New Issue
Block a user