1use dive_core::plan::Code;
17use dive_core::{Error, ErrorKind, Handle, Machine, Sink};
18
19use crate::{Explorer, state_identity};
20
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub enum Site {
24 Init,
26 Next(usize),
29 Constraint(usize),
31 ActionConstraint(usize),
34 Invariant(usize),
36 ImpliedInit(usize),
39 ImpliedAction(usize),
42 Incomplete,
45 Fingerprint,
48 View,
50}
51
52#[derive(Clone, Debug, PartialEq, Eq)]
54pub struct Failure {
55 pub site: Site,
57 pub message: String,
59 pub initial: bool,
61 pub parent: Option<Vec<Handle>>,
63 pub state: Option<Vec<Handle>>,
66 pub action: Option<usize>,
68 pub init_action: Option<usize>,
70 pub in_model: bool,
72 pub emitted: u64,
75}
76
77impl Failure {
78 #[must_use]
81 pub fn site_resumes(&self) -> bool {
82 matches!(self.site, Site::Invariant(_)) && !self.initial && self.in_model
83 }
84}
85
86#[derive(Clone, Debug, Default, PartialEq, Eq)]
88pub struct Replayed {
89 pub distinct: u64,
91 pub queued: u64,
93 pub error: Option<Failure>,
95}
96
97fn persist(m: &mut Machine, hs: &[Handle]) -> Result<Vec<Handle>, Error> {
98 let mut out = Vec::with_capacity(hs.len());
99 for &h in hs {
100 out.push(if h.is_empty() { h } else { m.heap.intern(h)? });
101 }
102 Ok(out)
103}
104
105impl Explorer<'_> {
106 pub(crate) fn fail_check(&mut self, m: &mut Machine, site: Site, e: Error) -> Error {
109 if e.kind() != ErrorKind::Eval {
110 return e;
111 }
112 match self.failure_at(m, site, e.message().to_owned()) {
113 Ok(f) => {
114 self.failure = Some(f);
115 Error::stop()
116 }
117 Err(e) => e,
118 }
119 }
120
121 pub(crate) fn failure_at(
123 &mut self,
124 m: &mut Machine,
125 site: Site,
126 message: String,
127 ) -> Result<Failure, Error> {
128 let state = Some(persist(m, &m.s1.clone())?);
129 let parent = if self.initial {
130 None
131 } else {
132 Some(m.s0.clone())
133 };
134 Ok(Failure {
135 site,
136 message,
137 initial: self.initial,
138 parent,
139 state,
140 action: self.action,
141 init_action: self.init_action,
142 in_model: self.in_model,
143 emitted: 0,
144 })
145 }
146
147 pub(crate) fn generator_failure(&self, m: &Machine, message: String) -> Failure {
149 Failure {
150 site: self.action.map_or(Site::Init, Site::Next),
151 message,
152 initial: self.initial,
153 parent: (!self.initial).then(|| m.s0.clone()),
154 state: None,
155 action: self.action,
156 init_action: self.init_action,
157 in_model: false,
158 emitted: self.emitted - self.action_start,
159 }
160 }
161}
162
163struct Collect {
165 states: Vec<(Vec<Handle>, bool)>,
166}
167
168impl Sink for Collect {
169 fn emit(&mut self, m: &mut Machine, _code: &Code) -> Result<(), Error> {
170 let complete = m.assigned == m.s1.len();
171 let values = persist(m, &m.s1.clone())?;
172 self.states.push((values, complete));
173 Ok(())
174 }
175}
176
177pub(crate) fn replay_after(
184 m: &mut Machine,
185 ex: &mut Explorer<'_>,
186 ordinal: u64,
187) -> Result<Replayed, Error> {
188 m.without_debugger(|m| replay_after_unobserved(m, ex, ordinal))
191}
192
193fn replay_after_unobserved(
194 m: &mut Machine,
195 ex: &mut Explorer<'_>,
196 ordinal: u64,
197) -> Result<Replayed, Error> {
198 let plan = ex.plan;
199 let code = &plan.code;
200 let s0 = m.s0.clone();
201 let mut out = Replayed::default();
202 let mut added = ex.seen.empty_like();
203 let mut emission = 0u64;
204 for (index, a) in plan.next.iter().enumerate() {
205 ex.action = Some(index);
206 let mut sink = Collect { states: Vec::new() };
207 let old = m.enter(a.frame);
208 for &(slot, v) in &a.preset {
209 if let Some(x) = m.frame.get_mut(m.base + slot as usize) {
210 *x = v;
211 }
212 }
213 let ran = m.run_action(code, a.g, &mut sink);
214 m.leave(old);
215 if let Err(e) = ran {
216 if e.kind() != ErrorKind::Eval {
217 return Err(e);
218 }
219 out.error = Some(Failure {
222 site: Site::Next(index),
223 message: e.message().to_owned(),
224 initial: false,
225 parent: Some(s0),
226 state: None,
227 action: Some(index),
228 init_action: None,
229 in_model: false,
230 emitted: sink.states.len() as u64,
231 });
232 return Ok(out);
233 }
234 for (values, complete) in sink.states {
235 let o = emission;
236 emission += 1;
237 if o < ordinal {
238 continue;
239 }
240 if !complete {
241 return Ok(out);
243 }
244 m.s0.copy_from_slice(&s0);
245 m.s1.copy_from_slice(&values);
246 if o == ordinal {
247 if !replay_implied(m, ex, &mut out)? {
249 return Ok(out);
250 }
251 continue;
252 }
253 ex.changed = crate::changed_vars(m);
254 let inside = match ex.in_model_of(m) {
255 Ok(b) => b,
256 Err((site, e)) => {
257 if e.kind() != ErrorKind::Eval {
258 return Err(e);
259 }
260 ex.in_model = true;
261 out.error = Some(ex.failure_at(m, site, e.message().to_owned())?);
262 return Ok(out);
263 }
264 };
265 let mut new = true;
266 if inside {
267 let mut identity = Vec::new();
268 let key =
269 match state_identity(m, plan, ex.seen.exact.as_ref().map(|_| &mut identity)) {
270 Ok(k) => ex.seen.key(k),
271 Err(e) if e.kind() == ErrorKind::Eval && plan.view.is_some() => {
272 out.error =
273 Some(ex.failure_at(m, Site::View, e.message().to_owned())?);
274 return Ok(out);
275 }
276 Err(e) => return Err(e),
277 };
278 new = !ex.seen_contains(key, &identity, &m.heap, ("ReplayMembership", Some(o)))?
279 && (ex.disk.is_some()
280 || !added.contains_row(key, &identity, &m.heap, ex.poll)?);
281 if new {
282 if ex.disk.is_some() {
283 ex.seen_insert(key, &identity, &m.heap, ("ReplayInsertion", Some(o)))?;
284 } else {
285 added.insert_row(key, &identity, &m.heap, u64::MAX, ex.poll)?;
288 }
289 out.distinct += 1;
290 }
291 }
292 if new && !replay_invariants(m, ex, inside, &mut out)? {
293 return Ok(out);
294 }
295 if !replay_implied(m, ex, &mut out)? {
296 return Ok(out);
297 }
298 if inside && new {
299 out.queued += 1;
300 }
301 }
302 }
303 Ok(out)
304}
305
306fn replay_invariants(
310 m: &mut Machine,
311 ex: &mut Explorer<'_>,
312 inside: bool,
313 out: &mut Replayed,
314) -> Result<bool, Error> {
315 let plan = ex.plan;
316 for (i, c) in plan.invariants.iter().enumerate() {
317 match ex.check(m, &plan.code, c) {
318 Ok(true) => {}
319 Ok(false) => return Ok(false),
320 Err(e) => {
321 if e.kind() != ErrorKind::Eval {
322 return Err(e);
323 }
324 ex.in_model = inside;
325 out.error = Some(ex.failure_at(m, Site::Invariant(i), e.message().to_owned())?);
326 return Ok(false);
327 }
328 }
329 }
330 Ok(true)
331}
332
333fn replay_implied(
337 m: &mut Machine,
338 ex: &mut Explorer<'_>,
339 out: &mut Replayed,
340) -> Result<bool, Error> {
341 let plan = ex.plan;
342 for (i, c) in plan.implied_actions.iter().enumerate() {
343 match crate::check_step(m, &plan.code, c) {
344 Ok(true) => {}
345 Ok(false) => return Ok(false),
346 Err(e) => {
347 if e.kind() != ErrorKind::Eval {
348 return Err(e);
349 }
350 out.error =
351 Some(ex.failure_at(m, Site::ImpliedAction(i), e.message().to_owned())?);
352 return Ok(false);
353 }
354 }
355 }
356 Ok(true)
357}