Skip to main content

dive_core/
debug.rs

1//! Opt-in maps and observation of actual compiled instruction activations.
2use crate::plan::{Code, Node};
3use crate::{Error, Handle, Machine};
4use dive_ir::{FileInfo, Origin};
5use std::sync::Arc;
6
7/// An actual compiled instruction, not a source-text projection.
8#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
9pub enum Instruction {
10    /// A value instruction.
11    Value(u32),
12    /// A generator instruction.
13    Generator(u32),
14}
15
16/// A local's existing storage; inspection never evaluates a recipe.
17#[derive(Clone, Debug)]
18pub enum Binding {
19    /// A flat activation slot, possibly still unforced/unbound.
20    Slot(u32),
21    /// A compiled alias, readable only when already a scalar/storage read.
22    Alias(u32),
23    /// No readable storage exists for this source local.
24    Unavailable,
25}
26
27/// A source local and its actual compiled storage association.
28#[derive(Clone, Debug)]
29pub struct Local {
30    /// Original source name.
31    pub name: String,
32    /// Existing storage association.
33    pub binding: Binding,
34}
35
36/// An actual active compiler substitution, including dynamic INSTANCE contexts.
37#[derive(Clone, Debug)]
38pub struct Substitution {
39    /// The declaration being substituted.
40    pub declaration: String,
41    /// Origin of the actual expression, if the binding is an expression.
42    pub actual: Option<Origin>,
43    /// Unique substitution identity in this compilation.
44    pub identity: u32,
45}
46
47/// Source context captured while compiling an instruction.
48#[derive(Clone, Debug)]
49pub struct Location {
50    /// Exact IR origin, including INSTANCE ownership.
51    pub origin: Origin,
52    /// Definition whose environment compiled the instruction.
53    pub definition: String,
54    /// Definition identity; names alone do not identify an activation.
55    pub definition_id: usize,
56    /// Actual compiler environment identity, distinguishing inlined call sites.
57    pub environment_id: usize,
58    /// Source locals associated with actual flat storage/aliases.
59    pub locals: Vec<Local>,
60    /// Calling compilation context, before inlining/substitution.
61    pub caller: Option<usize>,
62    /// Actual active substitution prefix, distinct from static IR instantiation.
63    pub substitutions: Vec<Substitution>,
64}
65
66/// Optional instruction/source tables. Ordinary compilation allocates none.
67#[derive(Clone, Debug, Default)]
68pub struct SourceMap {
69    /// Source files already loaded by the caller, never opened by inspection.
70    pub files: Vec<FileInfo>,
71    /// State-variable names in actual machine order.
72    pub variables: Vec<String>,
73    /// Source compilation contexts.
74    pub locations: Vec<Location>,
75    /// Value instruction to source context; synthetic unmapped nodes are None.
76    pub values: Vec<Option<usize>>,
77    /// Generator instruction to source context.
78    pub generators: Vec<Option<usize>>,
79    /// Actual invariant/property root instructions and their configured names.
80    pub obligations: Vec<(u32, String)>,
81    /// Instructions reachable from the actual compiled plan roots.
82    pub executable: Vec<Instruction>,
83}
84
85impl SourceMap {
86    /// Finds the retained context for an actual instruction.
87    #[must_use]
88    pub fn location(&self, instruction: Instruction) -> Option<&Location> {
89        let index = match instruction {
90            Instruction::Value(index) => self.values.get(index as usize),
91            Instruction::Generator(index) => self.generators.get(index as usize),
92        };
93        index.and_then(|index| index.and_then(|index| self.locations.get(index)))
94    }
95}
96
97/// Actual completion of an observed instruction.
98#[derive(Clone, Copy, Debug)]
99pub enum Returned<'a> {
100    /// An actual returned value.
101    Value(Handle),
102    /// Completed generator traversal.
103    Generated,
104    /// The actual error before activation unwinding.
105    Failed(&'a Error),
106}
107
108/// Explicit producer-only instruction observer. Replay machines stay unobserved.
109pub trait Observer: Send + Sync + std::fmt::Debug {
110    /// Publishes the real compiled map before search begins.
111    ///
112    /// # Errors
113    /// Cancellation or an unsupported observation boundary.
114    fn prepared(&self, map: &SourceMap) -> Result<(), Error>;
115    /// Enters an actual instruction activation.
116    ///
117    /// # Errors
118    /// Cancellation or an unsupported observation boundary.
119    fn enter(&self, instruction: Instruction, code: &Code, machine: &Machine) -> Result<(), Error>;
120    /// Observes a result while its activation remains live.
121    ///
122    /// # Errors
123    /// Cancellation or an unsupported observation boundary.
124    fn returned(
125        &self,
126        instruction: Instruction,
127        code: &Code,
128        machine: &Machine,
129        result: Returned<'_>,
130    ) -> Result<(), Error>;
131    /// Leaves the matching activation, including on errors.
132    fn leave(&self);
133}
134
135pub(crate) struct Guard(Arc<dyn Observer>);
136impl Guard {
137    pub(crate) fn enter(
138        observer: &Arc<dyn Observer>,
139        instruction: Instruction,
140        code: &Code,
141        machine: &Machine,
142    ) -> Result<Self, Error> {
143        observer.enter(instruction, code, machine)?;
144        Ok(Self(Arc::clone(observer)))
145    }
146    pub(crate) fn returned(
147        &self,
148        instruction: Instruction,
149        code: &Code,
150        machine: &Machine,
151        result: Returned<'_>,
152    ) -> Result<(), Error> {
153        self.0.returned(instruction, code, machine, result)
154    }
155}
156impl Drop for Guard {
157    fn drop(&mut self) {
158        self.0.leave();
159    }
160}
161
162struct Suspended<'a> {
163    machine: &'a mut Machine,
164    observer: Option<Arc<dyn Observer>>,
165}
166impl Drop for Suspended<'_> {
167    fn drop(&mut self) {
168        self.machine.debugger = self.observer.take();
169    }
170}
171
172impl Machine {
173    /// Runs nonproducer reconstruction without this machine's debugger capability.
174    /// The original capability is restored when the operation returns or unwinds,
175    /// including on errors. The controller and its stopped snapshots are untouched.
176    pub fn without_debugger<T>(&mut self, operation: impl FnOnce(&mut Self) -> T) -> T {
177        let observer = self.debugger.take();
178        let suspended = Suspended {
179            machine: self,
180            observer,
181        };
182        operation(&mut *suspended.machine)
183    }
184}
185
186/// Reads only an already-existing scalar/storage alias. Compound expressions,
187/// unforced thunks and by-name recipes remain unavailable; no evaluator is called.
188#[must_use]
189pub fn read_binding(
190    binding: &Binding,
191    code: &Code,
192    machine: &Machine,
193    base: usize,
194) -> Option<Handle> {
195    let slot = |slot: u32| {
196        base.checked_add(slot as usize)
197            .and_then(|slot| machine.frame.get(slot))
198            .copied()
199    };
200    match binding {
201        Binding::Slot(index) => slot(*index),
202        Binding::Alias(index) => match code.nodes.get(*index as usize)? {
203            Node::Const(value) => Some(*value),
204            Node::Var(index) => machine.s0.get(usize::from(*index)).copied(),
205            Node::Primed(index) => machine.s1.get(usize::from(*index)).copied(),
206            Node::Slot(index) | Node::Lazy { slot: index, .. } => slot(*index),
207            _ => None,
208        },
209        Binding::Unavailable => None,
210    }
211}
212
213#[allow(
214    clippy::too_many_lines,
215    reason = "one arm per actual instruction kind for debug-only graph reachability"
216)]
217pub(crate) fn reachable(plan: &crate::plan::Plan) -> Vec<Instruction> {
218    use crate::plan::{GNode, LibArg, Unch};
219    let mut pending = Vec::new();
220    pending.extend(
221        plan.init
222            .iter()
223            .chain(&plan.next)
224            .map(|action| Instruction::Generator(action.g)),
225    );
226    for check in plan
227        .invariants
228        .iter()
229        .chain(&plan.constraints)
230        .chain(&plan.action_constraints)
231        .chain(&plan.implied_inits)
232        .chain(&plan.implied_actions)
233        .chain(plan.view.iter())
234    {
235        pending.extend(
236            check
237                .conjuncts
238                .iter()
239                .map(|part| Instruction::Value(part.p)),
240        );
241    }
242    let mut seen = std::collections::HashSet::new();
243    while let Some(instruction) = pending.pop() {
244        if !seen.insert(instruction) {
245            continue;
246        }
247        let mut values = Vec::new();
248        let mut generators = Vec::new();
249        match instruction {
250            Instruction::Value(index) => {
251                if let Some(node) = plan.code.nodes.get(index as usize) {
252                    match node {
253                        Node::Const(_) | Node::Slot(_) | Node::Var(_) | Node::Primed(_) => {}
254                        Node::Not(a)
255                        | Node::Neg(a)
256                        | Node::Powerset(a)
257                        | Node::BigUnion(a)
258                        | Node::Domain(a)
259                        | Node::Spec(a)
260                        | Node::Select(a, _) => values.push(*a),
261                        Node::Lazy { body, .. }
262                        | Node::Scope { body, .. }
263                        | Node::SameVars { eq: body, .. }
264                        | Node::Memo { body, .. } => values.push(*body),
265                        Node::Implies(a, b)
266                        | Node::Equiv(a, b)
267                        | Node::Eq(a, b)
268                        | Node::Neq(a, b)
269                        | Node::In(a, b)
270                        | Node::NotIn(a, b)
271                        | Node::Subseteq(a, b)
272                        | Node::Range(a, b)
273                        | Node::FcnSet(a, b)
274                        | Node::Apply(a, b)
275                        | Node::Arith(_, a, b)
276                        | Node::Cmp(_, a, b)
277                        | Node::SetBin(_, a, b) => values.extend([*a, *b]),
278                        Node::If(a, b, c) => values.extend([*a, *b, *c]),
279                        Node::And(items)
280                        | Node::Or(items)
281                        | Node::Product(items)
282                        | Node::Tuple(items)
283                        | Node::Std(_, items)
284                        | Node::SetEnum(items)
285                        | Node::Lib { args: items, .. } => values.extend(items.iter().copied()),
286                        Node::Record(items) | Node::RecSet(items) => {
287                            values.extend(items.iter().map(|(_, p)| *p));
288                        }
289                        Node::Case(arms, other) => {
290                            for (a, b) in arms {
291                                values.extend([*a, *b]);
292                            }
293                            values.extend(*other);
294                        }
295                        Node::Filter { bind, pred, .. } => values.extend([bind.domain, *pred]),
296                        Node::Map { binds, body }
297                        | Node::FcnCons { binds, body }
298                        | Node::Quant { binds, body, .. } => {
299                            values.extend(binds.iter().map(|bind| bind.domain));
300                            values.push(*body);
301                        }
302                        Node::Except { base, updates } => {
303                            values.push(*base);
304                            for update in updates {
305                                values.extend(update.path.iter().copied());
306                                values.push(update.value);
307                            }
308                        }
309                        Node::Call { fun, args } => {
310                            values.extend(args.iter().copied());
311                            if let Some(fun) = plan.code.funs.get(*fun as usize) {
312                                values.push(fun.body);
313                            }
314                        }
315                        Node::LibHo(_, args) => {
316                            for arg in args {
317                                values.push(match arg {
318                                    LibArg::Value(p) => *p,
319                                    LibArg::Op { body, .. } => *body,
320                                });
321                            }
322                        }
323                        Node::Enabled { g, .. } => generators.push(*g),
324                        Node::Composition { first, then, .. } => {
325                            generators.extend([*first, *then]);
326                        }
327                        Node::InLazy { elem, set, .. } => values.extend([*elem, *set]),
328                        Node::Beta { chain, fc, arg } => values.extend([*chain, *fc, *arg]),
329                        Node::DomCheck { domain, body, .. } => values.extend([*domain, *body]),
330                    }
331                }
332            }
333            Instruction::Generator(index) => {
334                if let Some(node) = plan.code.gnodes.get(index as usize) {
335                    let mut unchanged = |items: &[Unch]| {
336                        values.extend(items.iter().filter_map(|item| {
337                            if let Unch::Verify(p) = item {
338                                Some(*p)
339                            } else {
340                                None
341                            }
342                        }));
343                    };
344                    match node {
345                        GNode::Composition { first, then, .. } => {
346                            generators.extend([*first, *then]);
347                        }
348                        GNode::Conj(items) => {
349                            for (g, p) in items {
350                                generators.push(*g);
351                                values.push(*p);
352                            }
353                        }
354                        GNode::Disj(items) => generators.extend(items.iter().copied()),
355                        GNode::Exists {
356                            binds,
357                            body,
358                            body_p,
359                        }
360                        | GNode::Forall {
361                            binds,
362                            body,
363                            body_p,
364                        } => {
365                            values.extend(binds.iter().map(|bind| bind.domain));
366                            values.push(*body_p);
367                            generators.push(*body);
368                        }
369                        GNode::If { cond, then, other } => {
370                            values.push(*cond);
371                            generators.extend([*then, *other]);
372                        }
373                        GNode::Case { arms, other } => {
374                            for (p, g) in arms {
375                                values.push(*p);
376                                generators.push(*g);
377                            }
378                            generators.extend(*other);
379                        }
380                        GNode::Implies { lhs, rhs } => {
381                            values.push(*lhs);
382                            generators.push(*rhs);
383                        }
384                        GNode::Assign { rhs, .. } | GNode::Guard(rhs) => values.push(*rhs),
385                        GNode::AssignIn { set, .. } => values.push(*set),
386                        GNode::AssignInRaw { set, raw, .. } => {
387                            values.push(*set);
388                            raw_instructions(raw, &mut values);
389                        }
390                        GNode::Unchanged(items) => unchanged(items),
391                        GNode::StepBox { action, vars } => {
392                            unchanged(vars);
393                            generators.push(*action);
394                        }
395                        GNode::StepAngle { action, same } => {
396                            values.push(*same);
397                            generators.push(*action);
398                        }
399                        GNode::FcnAction { binds, arg, body } => {
400                            values.extend(binds.iter().map(|bind| bind.domain));
401                            values.push(*arg);
402                            generators.push(*body);
403                        }
404                        GNode::Scope { body, .. } => generators.push(*body),
405                    }
406                }
407            }
408        }
409        pending.extend(values.into_iter().map(Instruction::Value));
410        pending.extend(generators.into_iter().map(Instruction::Generator));
411    }
412    seen.into_iter().collect()
413}
414
415fn raw_instructions(raw: &crate::plan::Raw, values: &mut Vec<u32>) {
416    use crate::plan::Raw;
417    let mut pending = vec![raw];
418    while let Some(raw) = pending.pop() {
419        match raw {
420            Raw::Leaf(node) | Raw::UnionOf(node) => values.push(*node),
421            Raw::Cup(left, right) => pending.extend([&**left, &**right]),
422            Raw::Union(items) => pending.extend(items.iter()),
423            Raw::Filter { bind, pred, inner } => {
424                values.extend([bind.domain, *pred]);
425                pending.push(inner);
426            }
427            Raw::Cap(left, right, first, second) => {
428                pending.extend([&**left, &**right]);
429                values.extend([*first, *second]);
430            }
431            Raw::Minus(inner, other) => {
432                pending.push(inner);
433                values.push(*other);
434            }
435            Raw::Odometer(items, node) => {
436                pending.extend(items.iter());
437                values.push(*node);
438            }
439        }
440    }
441}