Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions compiler/rustc_borrowck/src/type_check/liveness/trace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
use rustc_index::bit_set::DenseBitSet;
use rustc_index::interval::IntervalSet;
use rustc_infer::infer::canonical::QueryRegionConstraints;
use rustc_infer::infer::outlives::for_liveness;
use rustc_middle::mir::{BasicBlock, Body, ConstraintCategory, HasLocalDecls, Local, Location};
use rustc_middle::traits::query::DropckOutlivesResult;
use rustc_middle::ty::relate::Relate;
Expand All @@ -14,6 +13,7 @@ use rustc_mir_dataflow::{Analysis, ResultsCursor};
use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span};
use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
use rustc_trait_selection::traits::ObligationCtxt;
use rustc_trait_selection::traits::outlives_for_liveness::FreeRegionsVisitor;
use rustc_trait_selection::traits::query::dropck_outlives;
use rustc_trait_selection::traits::query::type_op::{DropckOutlives, TypeOp, TypeOpOutput};
use tracing::debug;
Expand Down Expand Up @@ -611,7 +611,7 @@ impl<'tcx> LivenessContext<'_, '_, 'tcx> {
values::pretty_print_points(location_map, live_at.iter()),
);

value.visit_with(&mut for_liveness::FreeRegionsVisitor {
value.visit_with(&mut FreeRegionsVisitor {
tcx: typeck.tcx(),
param_env: typeck.infcx.param_env,
op: |r| {
Expand Down
70 changes: 4 additions & 66 deletions compiler/rustc_hir_analysis/src/check/wfcheck.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ use rustc_hir::def::{DefKind, Res};
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::lang_items::LangItem;
use rustc_hir::{AmbigArg, ItemKind, find_attr};
use rustc_infer::infer::TyCtxtInferExt;
use rustc_infer::infer::outlives::env::OutlivesEnvironment;
use rustc_infer::infer::{self, InferCtxt, SubregionOrigin, TyCtxtInferExt};
use rustc_infer::traits::PredicateObligations;
use rustc_lint_defs::builtin::SHADOWING_SUPERTRAIT_ITEMS;
use rustc_macros::Diagnostic;
Expand All @@ -30,7 +30,9 @@ use rustc_middle::{bug, span_bug};
use rustc_session::errors::feature_err;
use rustc_span::{DUMMY_SP, Span, sym};
use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
use rustc_trait_selection::regions::{InferCtxtRegionExt, OutlivesEnvironmentBuildExt};
use rustc_trait_selection::regions::{
InferCtxtRegionExt, OutlivesEnvironmentBuildExt, region_known_to_outlive, ty_known_to_outlive,
};
use rustc_trait_selection::traits::misc::{
ConstParamTyImplementationError, type_allowed_to_implement_const_param_ty,
};
Expand Down Expand Up @@ -691,70 +693,6 @@ fn gather_gat_bounds<'tcx, T: TypeFoldable<TyCtxt<'tcx>>>(
Some(bounds)
}

/// Given a known `param_env` and a set of well formed types, can we prove that
/// `ty` outlives `region`.
fn ty_known_to_outlive<'tcx>(
tcx: TyCtxt<'tcx>,
id: LocalDefId,
param_env: ty::ParamEnv<'tcx>,
wf_tys: &FxIndexSet<Ty<'tcx>>,
ty: Ty<'tcx>,
region: ty::Region<'tcx>,
) -> bool {
test_region_obligations(tcx, id, param_env, wf_tys, |infcx| {
infcx.register_type_outlives_constraint_inner(infer::TypeOutlivesConstraint {
sub_region: region,
sup_type: ty,
origin: SubregionOrigin::RelateParamBound(DUMMY_SP, ty, None),
});
})
}

/// Given a known `param_env` and a set of well formed types, can we prove that
/// `region_a` outlives `region_b`
fn region_known_to_outlive<'tcx>(
tcx: TyCtxt<'tcx>,
id: LocalDefId,
param_env: ty::ParamEnv<'tcx>,
wf_tys: &FxIndexSet<Ty<'tcx>>,
region_a: ty::Region<'tcx>,
region_b: ty::Region<'tcx>,
) -> bool {
test_region_obligations(tcx, id, param_env, wf_tys, |infcx| {
infcx.sub_regions(
SubregionOrigin::RelateRegionParamBound(DUMMY_SP, None),
region_b,
region_a,
ty::VisibleForLeakCheck::Unreachable,
);
})
}

/// Given a known `param_env` and a set of well formed types, set up an
/// `InferCtxt`, call the passed function (to e.g. set up region constraints
/// to be tested), then resolve region and return errors
fn test_region_obligations<'tcx>(
tcx: TyCtxt<'tcx>,
id: LocalDefId,
param_env: ty::ParamEnv<'tcx>,
wf_tys: &FxIndexSet<Ty<'tcx>>,
add_constraints: impl FnOnce(&InferCtxt<'tcx>),
) -> bool {
// Unfortunately, we have to use a new `InferCtxt` each call, because
// region constraints get added and solved there and we need to test each
// call individually.
let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());

add_constraints(&infcx);

let errors = infcx.resolve_regions(id, param_env, wf_tys.iter().copied());
debug!(?errors, "errors");

// If we were able to prove that the type outlives the region without
// an error, it must be because of the implied or explicit bounds...
errors.is_empty()
}

/// TypeVisitor that looks for uses of GATs like
/// `<P0 as Trait<P1..Pn>>::GAT<Pn..Pm>` and adds the arguments `P0..Pm` into
/// the two vectors, `regions` and `types` (depending on their kind). For each
Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_infer/src/infer/outlives/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ use crate::infer::lexical_region_resolve;
use crate::infer::region_constraints::ConstraintKind;

pub mod env;
pub mod for_liveness;
pub mod obligations;
pub mod test_type_match;
pub(crate) mod verify;
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,7 @@ provide! { tcx, def_id, other, cdata,
}
anon_const_kind => { table }
const_of_item => { table }
args_known_to_outlive_alias_params => { table }
}

pub(in crate::rmeta) fn provide(providers: &mut Providers) {
Expand Down
16 changes: 16 additions & 0 deletions compiler/rustc_metadata/src/rmeta/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1613,6 +1613,9 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
self.tables
.type_alias_is_lazy
.set(def_id.index, self.tcx.type_alias_is_lazy(def_id));
if self.tcx.type_alias_is_lazy(def_id) {
record!(self.tables.args_known_to_outlive_alias_params[def_id] <- tcx.args_known_to_outlive_alias_params(def_id));
}
}
if let DefKind::OpaqueTy = def_kind {
self.encode_explicit_item_bounds(def_id);
Expand All @@ -1623,6 +1626,19 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
record_defaulted_array!(self.tables.explicit_implied_const_bounds[def_id]
<- tcx.explicit_implied_const_bounds(def_id).skip_binder());
}
record!(self.tables.args_known_to_outlive_alias_params[def_id] <- tcx.args_known_to_outlive_alias_params(def_id));
}
if let DefKind::AssocTy = def_kind {
let assoc_item = tcx.associated_item(def_id);
match assoc_item.container {
ty::AssocContainer::Trait => {
record!(self.tables.args_known_to_outlive_alias_params[def_id] <- tcx.args_known_to_outlive_alias_params(def_id));
}
ty::AssocContainer::InherentImpl => {
record!(self.tables.args_known_to_outlive_alias_params[def_id] <- tcx.args_known_to_outlive_alias_params(def_id));
}
ty::AssocContainer::TraitImpl(_) => {}
}
}
if let DefKind::AnonConst = def_kind {
record!(self.tables.anon_const_kind[def_id] <- self.tcx.anon_const_kind(def_id));
Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_metadata/src/rmeta/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,8 @@ define_tables! {
anon_const_kind: Table<DefIndex, LazyValue<ty::AnonConstKind>>,
const_of_item: Table<DefIndex, LazyValue<ty::EarlyBinder<'static, ty::Const<'static>>>>,
associated_types_for_impl_traits_in_trait_or_impl: Table<DefIndex, LazyValue<DefIdMap<Vec<DefId>>>>,
live_args_for_alias_from_outlives_bounds: Table<DefIndex, LazyValue<Option<ty::EarlyBinder<'static, Vec<ty::GenericArg<'static>>>>>>,
args_known_to_outlive_alias_params: Table<DefIndex, LazyValue<ty::EarlyBinder<'static, Vec<(ty::Region<'static>, Vec<ty::GenericArg<'static>>)>>>>,
}

#[derive(TyEncodable, TyDecodable)]
Expand Down
11 changes: 10 additions & 1 deletion compiler/rustc_metadata/src/rmeta/parameterized.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::hash::Hash;
use rustc_data_structures::unord::UnordMap;
use rustc_hir::def_id::DefIndex;
use rustc_index::{Idx, IndexVec};
use rustc_middle::ty::{Binder, EarlyBinder};
use rustc_middle::ty::{Binder, EarlyBinder, GenericArg, Region};
use rustc_span::Symbol;

use crate::rmeta::{LazyArray, LazyValue};
Expand Down Expand Up @@ -48,6 +48,14 @@ impl<T: ParameterizedOverTcx> ParameterizedOverTcx for LazyArray<T> {
type Value<'tcx> = LazyArray<T::Value<'tcx>>;
}

impl ParameterizedOverTcx for Region<'static> {
type Value<'tcx> = Region<'tcx>;
}

impl ParameterizedOverTcx for GenericArg<'static> {
type Value<'tcx> = GenericArg<'tcx>;
}

macro_rules! trivially_parameterized_over_tcx {
($($ty:ty),+ $(,)?) => {
$(
Expand All @@ -61,6 +69,7 @@ macro_rules! trivially_parameterized_over_tcx {

trivially_parameterized_over_tcx! {
bool,
u32,
u64,
usize,
std::string::String,
Expand Down
30 changes: 30 additions & 0 deletions compiler/rustc_middle/src/queries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2122,6 +2122,36 @@ rustc_queries! {
desc { "listing captured lifetimes for opaque `{}`", tcx.def_path_str(def_id) }
}

/// For an opaque type or trait associated type, return the list of potentially live
/// (identity) generic args from the set of outlives bounds on that alias. Callers should
/// instantiate the returned args with the concrete args of the alias.
/// ```ignore (illustrative)
/// // Edition 2024: all args are captured
/// fn foo<'a, 'b, T: 'static>(&'a &'b T) -> impl Sized + 'a {}
/// fn bar<'a, 'b, T: 'static>(&'a &'b T) -> impl Sized + 'static {}
/// fn baz<'a, 'b, T: 'static>(&'a &'b T) -> impl Sized {}
/// ```
///
/// In the above:
/// - `foo` outlives `'a`, but we know that `'b: 'a` holds, so `'b` is *also* potentially live
/// (and so is `T`, since `T: 'static` implies `T: 'a`)
/// - `bar` outlives `'static`, so we know that no args are potentially live and we can return an empty set
/// - `baz` has no outlives bound, so return `None` and let the caller decide what to do
query live_args_for_alias_from_outlives_bounds(kind: ty::AliasTyKind<'tcx>) -> &'tcx Option<ty::EarlyBinder<'tcx, Vec<ty::GenericArg<'tcx>>>> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

feel like as a query we want to just take a DefId and have a wrapper function that calls this query if necessary?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See https://github.com/rust-lang/rust/pull/156027/changes#diff-5d86c3fc35a603e984030459eb67d4870a975e53a460c331f15e48813ce8ce0eR40

The issue is that we search through the bounds on the item and need to match against the self type. Probably what this indicates is that item_bounds should potentially return something akin to ExistentialPredicate where there is no self type. But that's definitely out of scope for the current PR.

arena_cache
desc { "identifying live args for alias `{:?}`", kind }
}

/// For each region param of an alias, the identity args that are known to
/// outlive it given only the alias's declared where-clauses. Used for liveness:
/// these are the only args whose regions the underlying type of the alias
/// could capture while satisfying an outlives bound on that param.
query args_known_to_outlive_alias_params(def_id: DefId) -> &'tcx ty::EarlyBinder<'tcx, Vec<(ty::Region<'tcx>, Vec<ty::GenericArg<'tcx>>)>> {
arena_cache
desc { "computing the args known to outlive each region param of alias `{}`", tcx.def_path_str(def_id) }
separate_provide_extern
}

/// Computes the visibility of the provided `def_id`.
///
/// If the item from the `def_id` doesn't have a visibility, it will panic. For example
Expand Down
12 changes: 12 additions & 0 deletions compiler/rustc_middle/src/query/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,18 @@ impl<'tcx> QueryKey for ty::Clauses<'tcx> {
}
}

impl<'tcx> QueryKey for ty::AliasTyKind<'tcx> {
fn default_span(&self, tcx: TyCtxt<'_>) -> Span {
let def_id = match self {
ty::AliasTyKind::Projection { def_id }
| ty::AliasTyKind::Inherent { def_id }
| ty::AliasTyKind::Opaque { def_id }
| ty::AliasTyKind::Free { def_id } => def_id,
};
tcx.def_span(*def_id)
}
}

impl<'tcx, T: QueryKey> QueryKey for ty::PseudoCanonicalInput<'tcx, T> {
fn default_span(&self, tcx: TyCtxt<'_>) -> Span {
self.value.default_span(tcx)
Expand Down
73 changes: 70 additions & 3 deletions compiler/rustc_trait_selection/src/regions.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
use rustc_data_structures::fx::FxIndexSet;
use rustc_hir::def_id::LocalDefId;
use rustc_infer::infer::outlives::env::OutlivesEnvironment;
use rustc_infer::infer::{InferCtxt, RegionResolutionError};
use rustc_infer::infer::{
InferCtxt, RegionResolutionError, SubregionOrigin, TyCtxtInferExt, TypeOutlivesConstraint,
};
use rustc_macros::extension;
use rustc_middle::traits::ObligationCause;
use rustc_middle::traits::query::NoSolution;
use rustc_middle::ty::{self, Ty, Unnormalized, elaborate};
use rustc_span::Span;
use rustc_middle::ty::{self, Ty, TyCtxt, TypingMode, Unnormalized, elaborate};
use rustc_span::{DUMMY_SP, Span};

use crate::traits::ScrubbedTraitError;
use crate::traits::outlives_bounds::InferCtxtExt;
Expand Down Expand Up @@ -120,3 +123,67 @@ impl<'tcx> InferCtxt<'tcx> {
)
}
}

/// Given a known `param_env` and a set of well formed types, can we prove that
/// `ty` outlives `region`.
pub fn ty_known_to_outlive<'tcx>(
tcx: TyCtxt<'tcx>,
id: LocalDefId,
param_env: ty::ParamEnv<'tcx>,
wf_tys: &FxIndexSet<Ty<'tcx>>,
ty: Ty<'tcx>,
region: ty::Region<'tcx>,
) -> bool {
test_region_obligations(tcx, id, param_env, wf_tys, |infcx| {
infcx.register_type_outlives_constraint_inner(TypeOutlivesConstraint {
sub_region: region,
sup_type: ty,
origin: SubregionOrigin::RelateParamBound(DUMMY_SP, ty, None),
});
})
}

/// Given a known `param_env` and a set of well formed types, can we prove that
/// `region_a` outlives `region_b`
pub fn region_known_to_outlive<'tcx>(
tcx: TyCtxt<'tcx>,
id: LocalDefId,
param_env: ty::ParamEnv<'tcx>,
wf_tys: &FxIndexSet<Ty<'tcx>>,
region_a: ty::Region<'tcx>,
region_b: ty::Region<'tcx>,
) -> bool {
test_region_obligations(tcx, id, param_env, wf_tys, |infcx| {
infcx.sub_regions(
SubregionOrigin::RelateRegionParamBound(DUMMY_SP, None),
region_b,
region_a,
ty::VisibleForLeakCheck::Unreachable,
);
})
}

/// Given a known `param_env` and a set of well formed types, set up an
/// `InferCtxt`, call the passed function (to e.g. set up region constraints
/// to be tested), then resolve region and return errors
pub fn test_region_obligations<'tcx>(
tcx: TyCtxt<'tcx>,
id: LocalDefId,
param_env: ty::ParamEnv<'tcx>,
wf_tys: &FxIndexSet<Ty<'tcx>>,
add_constraints: impl FnOnce(&InferCtxt<'tcx>),
) -> bool {
// Unfortunately, we have to use a new `InferCtxt` each call, because
// region constraints get added and solved there and we need to test each
// call individually.
let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());

add_constraints(&infcx);

let errors = infcx.resolve_regions(id, param_env, wf_tys.iter().copied());
tracing::debug!(?errors, "errors");

// If we were able to prove that the type outlives the region without
// an error, it must be because of the implied or explicit bounds...
errors.is_empty()
}
5 changes: 5 additions & 0 deletions compiler/rustc_trait_selection/src/traits/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ mod fulfill;
pub mod misc;
pub mod normalize;
pub mod outlives_bounds;
pub mod outlives_for_liveness;
pub mod project;
pub mod query;
#[allow(hidden_glob_reexports)]
Expand Down Expand Up @@ -947,6 +948,10 @@ pub fn provide(providers: &mut Providers) {
specialization_enabled_in: specialize::specialization_enabled_in,
instantiate_and_check_impossible_predicates,
is_impossible_associated_item,
live_args_for_alias_from_outlives_bounds:
outlives_for_liveness::live_args_for_alias_from_outlives_bounds,
args_known_to_outlive_alias_params:
outlives_for_liveness::args_known_to_outlive_alias_params,
..*providers
};
}
Loading
Loading