rustc_infer/infer/snapshot/
undo_log.rs

1use std::assert_matches::assert_matches;
2use std::marker::PhantomData;
3
4use rustc_data_structures::undo_log::{Rollback, UndoLogs};
5use rustc_data_structures::{snapshot_vec as sv, unify as ut};
6use rustc_middle::ty::{self, OpaqueHiddenType, OpaqueTypeKey};
7use tracing::debug;
8
9use crate::infer::unify_key::{ConstVidKey, RegionVidKey};
10use crate::infer::{InferCtxtInner, region_constraints, type_variable};
11use crate::traits;
12
13pub struct Snapshot<'tcx> {
14    pub(crate) undo_len: usize,
15    _marker: PhantomData<&'tcx ()>,
16}
17
18/// Records the "undo" data for a single operation that affects some form of inference variable.
19#[derive(Clone)]
20pub(crate) enum UndoLog<'tcx> {
21    DuplicateOpaqueType,
22    OpaqueTypes(OpaqueTypeKey<'tcx>, Option<OpaqueHiddenType<'tcx>>),
23    TypeVariables(type_variable::UndoLog<'tcx>),
24    ConstUnificationTable(sv::UndoLog<ut::Delegate<ConstVidKey<'tcx>>>),
25    IntUnificationTable(sv::UndoLog<ut::Delegate<ty::IntVid>>),
26    FloatUnificationTable(sv::UndoLog<ut::Delegate<ty::FloatVid>>),
27    RegionConstraintCollector(region_constraints::UndoLog<'tcx>),
28    RegionUnificationTable(sv::UndoLog<ut::Delegate<RegionVidKey<'tcx>>>),
29    ProjectionCache(traits::UndoLog<'tcx>),
30    PushTypeOutlivesConstraint,
31    PushRegionAssumption,
32    PushHirTypeckPotentiallyRegionDependentGoal,
33}
34
35macro_rules! impl_from {
36    ($($ctor:ident ($ty:ty),)*) => {
37        $(
38        impl<'tcx> From<$ty> for UndoLog<'tcx> {
39            fn from(x: $ty) -> Self {
40                UndoLog::$ctor(x.into())
41            }
42        }
43        )*
44    }
45}
46
47// Upcast from a single kind of "undoable action" to the general enum
48impl_from! {
49    RegionConstraintCollector(region_constraints::UndoLog<'tcx>),
50
51    TypeVariables(sv::UndoLog<ut::Delegate<type_variable::TyVidEqKey<'tcx>>>),
52    TypeVariables(sv::UndoLog<ut::Delegate<type_variable::TyVidSubKey>>),
53    TypeVariables(type_variable::UndoLog<'tcx>),
54    IntUnificationTable(sv::UndoLog<ut::Delegate<ty::IntVid>>),
55    FloatUnificationTable(sv::UndoLog<ut::Delegate<ty::FloatVid>>),
56
57    ConstUnificationTable(sv::UndoLog<ut::Delegate<ConstVidKey<'tcx>>>),
58
59    RegionUnificationTable(sv::UndoLog<ut::Delegate<RegionVidKey<'tcx>>>),
60    ProjectionCache(traits::UndoLog<'tcx>),
61}
62
63/// The Rollback trait defines how to rollback a particular action.
64impl<'tcx> Rollback<UndoLog<'tcx>> for InferCtxtInner<'tcx> {
65    fn reverse(&mut self, undo: UndoLog<'tcx>) {
66        match undo {
67            UndoLog::DuplicateOpaqueType => self.opaque_type_storage.pop_duplicate_entry(),
68            UndoLog::OpaqueTypes(key, idx) => self.opaque_type_storage.remove(key, idx),
69            UndoLog::TypeVariables(undo) => self.type_variable_storage.reverse(undo),
70            UndoLog::ConstUnificationTable(undo) => self.const_unification_storage.reverse(undo),
71            UndoLog::IntUnificationTable(undo) => self.int_unification_storage.reverse(undo),
72            UndoLog::FloatUnificationTable(undo) => self.float_unification_storage.reverse(undo),
73            UndoLog::RegionConstraintCollector(undo) => {
74                self.region_constraint_storage.as_mut().unwrap().reverse(undo)
75            }
76            UndoLog::RegionUnificationTable(undo) => {
77                self.region_constraint_storage.as_mut().unwrap().unification_table.reverse(undo)
78            }
79            UndoLog::ProjectionCache(undo) => self.projection_cache.reverse(undo),
80            UndoLog::PushTypeOutlivesConstraint => {
81                let popped = self.region_obligations.pop();
82                assert_matches!(popped, Some(_), "pushed region constraint but could not pop it");
83            }
84            UndoLog::PushRegionAssumption => {
85                let popped = self.region_assumptions.pop();
86                assert_matches!(popped, Some(_), "pushed region assumption but could not pop it");
87            }
88            UndoLog::PushHirTypeckPotentiallyRegionDependentGoal => {
89                let popped = self.hir_typeck_potentially_region_dependent_goals.pop();
90                assert_matches!(popped, Some(_), "pushed goal but could not pop it");
91            }
92        }
93    }
94}
95
96/// The combined undo log for all the various unification tables. For each change to the storage
97/// for any kind of inference variable, we record an UndoLog entry in the vector here.
98#[derive(Clone, Default)]
99pub(crate) struct InferCtxtUndoLogs<'tcx> {
100    logs: Vec<UndoLog<'tcx>>,
101    num_open_snapshots: usize,
102}
103
104/// The UndoLogs trait defines how we undo a particular kind of action (of type T). We can undo any
105/// action that is convertible into an UndoLog (per the From impls above).
106impl<'tcx, T> UndoLogs<T> for InferCtxtUndoLogs<'tcx>
107where
108    UndoLog<'tcx>: From<T>,
109{
110    #[inline]
111    fn num_open_snapshots(&self) -> usize {
112        self.num_open_snapshots
113    }
114
115    #[inline]
116    fn push(&mut self, undo: T) {
117        if self.in_snapshot() {
118            self.logs.push(undo.into())
119        }
120    }
121
122    fn clear(&mut self) {
123        self.logs.clear();
124        self.num_open_snapshots = 0;
125    }
126
127    fn extend<J>(&mut self, undos: J)
128    where
129        Self: Sized,
130        J: IntoIterator<Item = T>,
131    {
132        if self.in_snapshot() {
133            self.logs.extend(undos.into_iter().map(UndoLog::from))
134        }
135    }
136}
137
138impl<'tcx> InferCtxtInner<'tcx> {
139    pub fn rollback_to(&mut self, snapshot: Snapshot<'tcx>) {
140        debug!("rollback_to({})", snapshot.undo_len);
141        self.undo_log.assert_open_snapshot(&snapshot);
142
143        while self.undo_log.logs.len() > snapshot.undo_len {
144            let undo = self.undo_log.logs.pop().unwrap();
145            self.reverse(undo);
146        }
147
148        self.type_variable_storage.finalize_rollback();
149
150        if self.undo_log.num_open_snapshots == 1 {
151            // After the root snapshot the undo log should be empty.
152            assert!(snapshot.undo_len == 0);
153            assert!(self.undo_log.logs.is_empty());
154        }
155
156        self.undo_log.num_open_snapshots -= 1;
157    }
158
159    pub fn commit(&mut self, snapshot: Snapshot<'tcx>) {
160        debug!("commit({})", snapshot.undo_len);
161
162        if self.undo_log.num_open_snapshots == 1 {
163            // The root snapshot. It's safe to clear the undo log because
164            // there's no snapshot further out that we might need to roll back
165            // to.
166            assert!(snapshot.undo_len == 0);
167            self.undo_log.logs.clear();
168        }
169
170        self.undo_log.num_open_snapshots -= 1;
171    }
172}
173
174impl<'tcx> InferCtxtUndoLogs<'tcx> {
175    pub(crate) fn start_snapshot(&mut self) -> Snapshot<'tcx> {
176        self.num_open_snapshots += 1;
177        Snapshot { undo_len: self.logs.len(), _marker: PhantomData }
178    }
179
180    pub(crate) fn region_constraints_in_snapshot(
181        &self,
182        s: &Snapshot<'tcx>,
183    ) -> impl Iterator<Item = &'_ region_constraints::UndoLog<'tcx>> + Clone {
184        self.logs[s.undo_len..].iter().filter_map(|log| match log {
185            UndoLog::RegionConstraintCollector(log) => Some(log),
186            _ => None,
187        })
188    }
189
190    pub(crate) fn opaque_types_in_snapshot(&self, s: &Snapshot<'tcx>) -> bool {
191        self.logs[s.undo_len..].iter().any(|log| matches!(log, UndoLog::OpaqueTypes(..)))
192    }
193
194    fn assert_open_snapshot(&self, snapshot: &Snapshot<'tcx>) {
195        // Failures here may indicate a failure to follow a stack discipline.
196        assert!(self.logs.len() >= snapshot.undo_len);
197        assert!(self.num_open_snapshots > 0);
198    }
199}
200
201impl<'tcx> std::ops::Index<usize> for InferCtxtUndoLogs<'tcx> {
202    type Output = UndoLog<'tcx>;
203
204    fn index(&self, key: usize) -> &Self::Output {
205        &self.logs[key]
206    }
207}
208
209impl<'tcx> std::ops::IndexMut<usize> for InferCtxtUndoLogs<'tcx> {
210    fn index_mut(&mut self, key: usize) -> &mut Self::Output {
211        &mut self.logs[key]
212    }
213}