Skip to content

Commit

Permalink
Move opaque type cache into InferCtxt
Browse files Browse the repository at this point in the history
  • Loading branch information
oli-obk committed Aug 6, 2021
1 parent 1f94abc commit d998059
Show file tree
Hide file tree
Showing 7 changed files with 102 additions and 107 deletions.
19 changes: 19 additions & 0 deletions compiler/rustc_infer/src/infer/mod.rs
Expand Up @@ -4,6 +4,7 @@ pub use self::RegionVariableOrigin::*;
pub use self::SubregionOrigin::*;
pub use self::ValuePairs::*;

use self::opaque_types::OpaqueTypeDecl;
pub(crate) use self::undo_log::{InferCtxtUndoLogs, Snapshot, UndoLog};

use crate::traits::{self, ObligationCause, PredicateObligations, TraitEngine};
Expand All @@ -12,6 +13,7 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_data_structures::sync::Lrc;
use rustc_data_structures::undo_log::Rollback;
use rustc_data_structures::unify as ut;
use rustc_data_structures::vec_map::VecMap;
use rustc_errors::DiagnosticBuilder;
use rustc_hir as hir;
use rustc_hir::def_id::{DefId, LocalDefId};
Expand All @@ -25,6 +27,7 @@ use rustc_middle::ty::fold::{TypeFoldable, TypeFolder};
use rustc_middle::ty::relate::RelateResult;
use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef};
pub use rustc_middle::ty::IntVarValue;
use rustc_middle::ty::OpaqueTypeKey;
use rustc_middle::ty::{self, GenericParamDefKind, InferConst, Ty, TyCtxt};
use rustc_middle::ty::{ConstVid, FloatVid, IntVid, TyVid};
use rustc_session::config::BorrowckMode;
Expand Down Expand Up @@ -59,6 +62,7 @@ pub mod lattice;
mod lexical_region_resolve;
mod lub;
pub mod nll_relate;
pub mod opaque_types;
pub mod outlives;
pub mod region_constraints;
pub mod resolve;
Expand Down Expand Up @@ -191,6 +195,19 @@ pub struct InferCtxtInner<'tcx> {
region_obligations: Vec<(hir::HirId, RegionObligation<'tcx>)>,

undo_log: InferCtxtUndoLogs<'tcx>,

// Opaque types found in explicit return types and their
// associated fresh inference variable. Writeback resolves these
// variables to get the concrete type, which can be used to
// 'de-opaque' OpaqueTypeDecl, after typeck is done with all functions.
pub opaque_types: VecMap<OpaqueTypeKey<'tcx>, OpaqueTypeDecl<'tcx>>,

/// A map from inference variables created from opaque
/// type instantiations (`ty::Infer`) to the actual opaque
/// type (`ty::Opaque`). Used during fallback to map unconstrained
/// opaque type inference variables to their corresponding
/// opaque type.
pub opaque_types_vars: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
}

impl<'tcx> InferCtxtInner<'tcx> {
Expand All @@ -204,6 +221,8 @@ impl<'tcx> InferCtxtInner<'tcx> {
float_unification_storage: ut::UnificationTableStorage::new(),
region_constraint_storage: Some(RegionConstraintStorage::new()),
region_obligations: vec![],
opaque_types: Default::default(),
opaque_types_vars: Default::default(),
}
}

Expand Down
70 changes: 70 additions & 0 deletions compiler/rustc_infer/src/infer/opaque_types.rs
@@ -0,0 +1,70 @@
use rustc_data_structures::vec_map::VecMap;
use rustc_hir as hir;
use rustc_middle::ty::{OpaqueTypeKey, Ty};
use rustc_span::Span;

pub type OpaqueTypeMap<'tcx> = VecMap<OpaqueTypeKey<'tcx>, OpaqueTypeDecl<'tcx>>;

/// Information about the opaque types whose values we
/// are inferring in this function (these are the `impl Trait` that
/// appear in the return type).
#[derive(Copy, Clone, Debug)]
pub struct OpaqueTypeDecl<'tcx> {
/// The opaque type (`ty::Opaque`) for this declaration.
pub opaque_type: Ty<'tcx>,

/// The span of this particular definition of the opaque type. So
/// for example:
///
/// ```ignore (incomplete snippet)
/// type Foo = impl Baz;
/// fn bar() -> Foo {
/// // ^^^ This is the span we are looking for!
/// }
/// ```
///
/// In cases where the fn returns `(impl Trait, impl Trait)` or
/// other such combinations, the result is currently
/// over-approximated, but better than nothing.
pub definition_span: Span,

/// The type variable that represents the value of the opaque type
/// that we require. In other words, after we compile this function,
/// we will be created a constraint like:
///
/// Foo<'a, T> = ?C
///
/// where `?C` is the value of this type variable. =) It may
/// naturally refer to the type and lifetime parameters in scope
/// in this function, though ultimately it should only reference
/// those that are arguments to `Foo` in the constraint above. (In
/// other words, `?C` should not include `'b`, even though it's a
/// lifetime parameter on `foo`.)
pub concrete_ty: Ty<'tcx>,

/// Returns `true` if the `impl Trait` bounds include region bounds.
/// For example, this would be true for:
///
/// fn foo<'a, 'b, 'c>() -> impl Trait<'c> + 'a + 'b
///
/// but false for:
///
/// fn foo<'c>() -> impl Trait<'c>
///
/// unless `Trait` was declared like:
///
/// trait Trait<'c>: 'c
///
/// in which case it would be true.
///
/// This is used during regionck to decide whether we need to
/// impose any additional constraints to ensure that region
/// variables in `concrete_ty` wind up being constrained to
/// something from `substs` (or, at minimum, things that outlive
/// the fn body). (Ultimately, writeback is responsible for this
/// check.)
pub has_required_region_bounds: bool,

/// The origin of the opaque type.
pub origin: hir::OpaqueTyOrigin,
}
83 changes: 5 additions & 78 deletions compiler/rustc_trait_selection/src/opaque_types.rs
Expand Up @@ -2,11 +2,11 @@ use crate::infer::InferCtxtExt as _;
use crate::traits::{self, ObligationCause, PredicateObligation};
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::sync::Lrc;
use rustc_data_structures::vec_map::VecMap;
use rustc_hir as hir;
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_infer::infer::error_reporting::unexpected_hidden_region_diagnostic;
use rustc_infer::infer::free_regions::FreeRegionRelations;
use rustc_infer::infer::opaque_types::{OpaqueTypeDecl, OpaqueTypeMap};
use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
use rustc_infer::infer::{self, InferCtxt, InferOk};
use rustc_middle::ty::fold::{BottomUpFolder, TypeFoldable, TypeFolder, TypeVisitor};
Expand All @@ -16,72 +16,6 @@ use rustc_span::Span;

use std::ops::ControlFlow;

pub type OpaqueTypeMap<'tcx> = VecMap<OpaqueTypeKey<'tcx>, OpaqueTypeDecl<'tcx>>;

/// Information about the opaque types whose values we
/// are inferring in this function (these are the `impl Trait` that
/// appear in the return type).
#[derive(Copy, Clone, Debug)]
pub struct OpaqueTypeDecl<'tcx> {
/// The opaque type (`ty::Opaque`) for this declaration.
pub opaque_type: Ty<'tcx>,

/// The span of this particular definition of the opaque type. So
/// for example:
///
/// ```ignore (incomplete snippet)
/// type Foo = impl Baz;
/// fn bar() -> Foo {
/// // ^^^ This is the span we are looking for!
/// }
/// ```
///
/// In cases where the fn returns `(impl Trait, impl Trait)` or
/// other such combinations, the result is currently
/// over-approximated, but better than nothing.
pub definition_span: Span,

/// The type variable that represents the value of the opaque type
/// that we require. In other words, after we compile this function,
/// we will be created a constraint like:
///
/// Foo<'a, T> = ?C
///
/// where `?C` is the value of this type variable. =) It may
/// naturally refer to the type and lifetime parameters in scope
/// in this function, though ultimately it should only reference
/// those that are arguments to `Foo` in the constraint above. (In
/// other words, `?C` should not include `'b`, even though it's a
/// lifetime parameter on `foo`.)
pub concrete_ty: Ty<'tcx>,

/// Returns `true` if the `impl Trait` bounds include region bounds.
/// For example, this would be true for:
///
/// fn foo<'a, 'b, 'c>() -> impl Trait<'c> + 'a + 'b
///
/// but false for:
///
/// fn foo<'c>() -> impl Trait<'c>
///
/// unless `Trait` was declared like:
///
/// trait Trait<'c>: 'c
///
/// in which case it would be true.
///
/// This is used during regionck to decide whether we need to
/// impose any additional constraints to ensure that region
/// variables in `concrete_ty` wind up being constrained to
/// something from `substs` (or, at minimum, things that outlive
/// the fn body). (Ultimately, writeback is responsible for this
/// check.)
pub has_required_region_bounds: bool,

/// The origin of the opaque type.
pub origin: hir::OpaqueTyOrigin,
}

/// Whether member constraints should be generated for all opaque types
#[derive(Debug)]
pub enum GenerateMemberConstraints {
Expand All @@ -105,11 +39,7 @@ pub trait InferCtxtExt<'tcx> {
value_span: Span,
) -> InferOk<'tcx, (T, OpaqueTypeMap<'tcx>)>;

fn constrain_opaque_types<FRR: FreeRegionRelations<'tcx>>(
&self,
opaque_types: &OpaqueTypeMap<'tcx>,
free_region_relations: &FRR,
);
fn constrain_opaque_types<FRR: FreeRegionRelations<'tcx>>(&self, free_region_relations: &FRR);

fn constrain_opaque_type<FRR: FreeRegionRelations<'tcx>>(
&self,
Expand Down Expand Up @@ -350,12 +280,9 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
/// - `opaque_types` -- the map produced by `instantiate_opaque_types`
/// - `free_region_relations` -- something that can be used to relate
/// the free regions (`'a`) that appear in the impl trait.
fn constrain_opaque_types<FRR: FreeRegionRelations<'tcx>>(
&self,
opaque_types: &OpaqueTypeMap<'tcx>,
free_region_relations: &FRR,
) {
for &(opaque_type_key, opaque_defn) in opaque_types {
fn constrain_opaque_types<FRR: FreeRegionRelations<'tcx>>(&self, free_region_relations: &FRR) {
let opaque_types = self.inner.borrow().opaque_types.clone();
for (opaque_type_key, opaque_defn) in opaque_types {
self.constrain_opaque_type(
opaque_type_key,
&opaque_defn,
Expand Down
9 changes: 4 additions & 5 deletions compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs
Expand Up @@ -385,8 +385,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
value_span,
));

let mut opaque_types = self.opaque_types.borrow_mut();
let mut opaque_types_vars = self.opaque_types_vars.borrow_mut();
let mut infcx = self.infcx.inner.borrow_mut();

for (ty, decl) in opaque_type_map {
if let Some(feature) = feature {
Expand All @@ -402,8 +401,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
}
}
let _ = opaque_types.insert(ty, decl);
let _ = opaque_types_vars.insert(decl.concrete_ty, decl.opaque_type);
let _ = infcx.opaque_types.insert(ty, decl);
let _ = infcx.opaque_types_vars.insert(decl.concrete_ty, decl.opaque_type);
}

value
Expand Down Expand Up @@ -726,7 +725,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// We treat this as a non-defining use by making the inference
// variable fall back to the opaque type itself.
if let FallbackMode::All = mode {
if let Some(opaque_ty) = self.opaque_types_vars.borrow().get(ty) {
if let Some(opaque_ty) = self.infcx.inner.borrow().opaque_types_vars.get(ty) {
debug!(
"fallback_if_possible: falling back opaque type var {:?} to {:?}",
ty, opaque_ty
Expand Down
20 changes: 1 addition & 19 deletions compiler/rustc_typeck/src/check/inherited.rs
@@ -1,18 +1,15 @@
use super::callee::DeferredCallResolution;
use super::MaybeInProgressTables;

use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::vec_map::VecMap;
use rustc_hir as hir;
use rustc_hir::def_id::{DefIdMap, LocalDefId};
use rustc_hir::HirIdMap;
use rustc_infer::infer;
use rustc_infer::infer::{InferCtxt, InferOk, TyCtxtInferExt};
use rustc_middle::ty::fold::TypeFoldable;
use rustc_middle::ty::{self, OpaqueTypeKey, Ty, TyCtxt};
use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_span::{self, Span};
use rustc_trait_selection::infer::InferCtxtExt as _;
use rustc_trait_selection::opaque_types::OpaqueTypeDecl;
use rustc_trait_selection::traits::{self, ObligationCause, TraitEngine, TraitEngineExt};

use std::cell::RefCell;
Expand Down Expand Up @@ -55,19 +52,6 @@ pub struct Inherited<'a, 'tcx> {
pub(super) deferred_generator_interiors:
RefCell<Vec<(hir::BodyId, Ty<'tcx>, hir::GeneratorKind)>>,

// Opaque types found in explicit return types and their
// associated fresh inference variable. Writeback resolves these
// variables to get the concrete type, which can be used to
// 'de-opaque' OpaqueTypeDecl, after typeck is done with all functions.
pub(super) opaque_types: RefCell<VecMap<OpaqueTypeKey<'tcx>, OpaqueTypeDecl<'tcx>>>,

/// A map from inference variables created from opaque
/// type instantiations (`ty::Infer`) to the actual opaque
/// type (`ty::Opaque`). Used during fallback to map unconstrained
/// opaque type inference variables to their corresponding
/// opaque type.
pub(super) opaque_types_vars: RefCell<FxHashMap<Ty<'tcx>, Ty<'tcx>>>,

pub(super) body_id: Option<hir::BodyId>,
}

Expand Down Expand Up @@ -124,8 +108,6 @@ impl Inherited<'a, 'tcx> {
deferred_call_resolutions: RefCell::new(Default::default()),
deferred_cast_checks: RefCell::new(Vec::new()),
deferred_generator_interiors: RefCell::new(Vec::new()),
opaque_types: RefCell::new(Default::default()),
opaque_types_vars: RefCell::new(Default::default()),
body_id,
}
}
Expand Down
5 changes: 1 addition & 4 deletions compiler/rustc_typeck/src/check/regionck.rs
Expand Up @@ -291,10 +291,7 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> {
self.visit_body(body);
self.visit_region_obligations(body_id.hir_id);

self.constrain_opaque_types(
&self.fcx.opaque_types.borrow(),
self.outlives_environment.free_region_map(),
);
self.constrain_opaque_types(self.outlives_environment.free_region_map());
}

fn visit_region_obligations(&mut self, hir_id: hir::HirId) {
Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_typeck/src/check/writeback.rs
Expand Up @@ -498,7 +498,8 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
}

fn visit_opaque_types(&mut self, span: Span) {
for &(opaque_type_key, opaque_defn) in self.fcx.opaque_types.borrow().iter() {
let opaque_types = self.fcx.infcx.inner.borrow().opaque_types.clone();
for (opaque_type_key, opaque_defn) in opaque_types {
let hir_id =
self.tcx().hir().local_def_id_to_hir_id(opaque_type_key.def_id.expect_local());
let instantiated_ty = self.resolve(opaque_defn.concrete_ty, &hir_id);
Expand Down

0 comments on commit d998059

Please sign in to comment.