rsaeb 0.10.0

A no_std + alloc interpreter for A=B ordered rewrite programs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
use crate::error::{
    OwnedRuleAttemptStepError, OwnedRunStepError, RuleAttemptStepError, RunError, RunFinishError,
    RunStartError, RunStepError, TracedRunError,
};
use crate::input::RunSeed;
use crate::inspect::RuleView;
use crate::limits::{RuleAttemptCount, RuleAttemptLimit, StepCount};
use crate::program::{
    ActiveRuleCursor, Program, ReturnOutput, RuleCursor, RuleCursorAfterMiss, RunResult,
};
use crate::runtime::action::{AppliedRule, prepare_matched_rule};
use crate::runtime::budget::{RuleAttemptBudgetState, RuntimeBudgetState};
use crate::runtime::matcher::{
    RuleAttempt, RuleSearch, attempt_rule, find_next_match, runtime_rule_for_target,
};
use crate::runtime::once::OnceStateSet;
use crate::runtime::rewrite::RewriteScratch;
use crate::runtime::state::State;
use crate::trace::{BorrowedTraceEffect, BorrowedTraceEvent, RuntimeStateView};

use super::{OwnedRuleWitness, RuleAttemptStableReason, RuleMiss};

/// Mutable runtime state independent of program ownership mode.
#[derive(Debug)]
pub(super) struct RunCore {
    /// Current runtime byte state.
    state: State,
    /// Reusable buffer for candidate rewrites.
    scratch: RewriteScratch,
    /// Runtime limits and completed-step count.
    budget: RuntimeBudgetState,
    /// Per-run consumption state for `(once)` rules.
    once_states: OnceStateSet,
}

/// Runtime session parameterized by program ownership.
pub(super) struct Session<P> {
    /// Borrowed or owned parsed program.
    pub(super) program: P,
    /// Mutable execution state.
    pub(super) core: RunCore,
}

/// Runtime rule-attempt session parameterized by program ownership.
pub(super) struct AttemptSession<P> {
    /// Borrowed or owned parsed program.
    pub(super) program: P,
    /// Mutable execution state.
    pub(super) core: RunCore,
    /// Next executable rule line to evaluate.
    pub(super) cursor: RuleCursor,
    /// Rule-attempt budget and consumed-attempt count.
    pub(super) attempt_budget: RuleAttemptBudgetState,
}

/// All data needed to commit one non-applying rule attempt.
struct MissCommit<'attempt, RuleWitness> {
    /// Cursor to advance when the miss is not the final executable rule.
    cursor: &'attempt mut RuleCursor,
    /// Rule-attempt budget after the miss has been committed.
    attempt_budget: &'attempt RuleAttemptBudgetState,
    /// Runtime core observed by the attempted rule.
    core: &'attempt RunCore,
    /// Committed attempt count assigned to this miss.
    attempt: RuleAttemptCount,
    /// Active cursor that selected the missed rule.
    active_cursor: ActiveRuleCursor,
    /// Non-applying rule selected by the current cursor.
    miss: RuleMiss<RuleWitness>,
}

/// Mutable rule-attempt state needed to consume one executable rule line.
struct RuleAttemptContext<'attempt, 'program> {
    /// Parsed program that owns the rule selected by the cursor.
    program: &'program Program,
    /// Mutable runtime state observed by the attempted rule.
    core: &'attempt mut RunCore,
    /// Next executable rule line to evaluate.
    cursor: &'attempt mut RuleCursor,
    /// Rule-attempt budget and consumed-attempt count.
    attempt_budget: &'attempt mut RuleAttemptBudgetState,
}

/// Program ownership shape used by the internal runtime session.
pub(super) trait ProgramOwner {
    /// Borrows the parsed program.
    fn program(&self) -> &Program;
}

/// Borrowed program owner for run-to-completion and tracing.
#[derive(Debug, Clone, Copy)]
pub(super) struct BorrowedProgram<'program> {
    /// Parsed program borrowed by this run.
    pub(super) program: &'program Program,
}

/// Owned program owner for public stepwise execution.
#[derive(Debug)]
pub(super) struct OwnedProgram {
    /// Parsed program owned by the public run session.
    pub(super) program: Program,
}

/// Internal non-error result of one core step attempt.
pub(super) enum CoreStep<RuleWitness> {
    /// A rule committed and may have terminal side effects.
    Applied(CoreAppliedRule<RuleWitness>),
    /// No rule matched the current runtime state.
    Stable(StepCount),
}

/// Internal runtime step retaining committed parsed-rule borrows.
enum RuntimeStep<'program> {
    /// A rule committed and may have terminal side effects.
    Applied(AppliedRule<'program>),
    /// No rule matched the current runtime state.
    Stable(StepCount),
}

/// Internal committed application paired with its public rule witness.
pub(super) enum CoreAppliedRule<RuleWitness> {
    /// One rewrite rule committed and execution may continue.
    Rewrite {
        /// Committed step count.
        step: StepCount,
        /// Rule witness selected before runtime side effects committed.
        rule: RuleWitness,
    },
    /// One return rule committed and execution is terminal.
    Return {
        /// Committed step count.
        step: StepCount,
        /// Rule witness selected before runtime side effects committed.
        rule: RuleWitness,
        /// Materialized return output.
        output: ReturnOutput,
    },
}

/// Internal non-error result of one rule-attempt step.
pub(super) enum CoreRuleAttempt<RuleWitness> {
    /// A rule line was consumed without applying.
    Missed {
        /// Rule-attempt count committed by this transition.
        attempt: RuleAttemptCount,
        /// Non-applying rule information.
        miss: RuleMiss<RuleWitness>,
    },
    /// A rule committed and may have terminal side effects.
    Applied {
        /// Rule-attempt count committed by this transition.
        attempt: RuleAttemptCount,
        /// Applied rule effect.
        applied: CoreAppliedRule<RuleWitness>,
    },
    /// No rule in the current pass matched the current runtime state.
    Stable {
        /// Rule attempts consumed before stability.
        attempts: RuleAttemptCount,
        /// Rewrite steps committed before stability.
        steps: StepCount,
        /// Why the rule-attempt pass reached stability.
        stable_reason: RuleAttemptStableReason<RuleWitness>,
    },
}

impl<RuleWitness> CoreAppliedRule<RuleWitness> {
    /// Combines a committed runtime application with its pre-commit rule witness.
    fn from_applied_rule(applied: AppliedRule<'_>, rule: RuleWitness) -> Self {
        match applied {
            AppliedRule::Rewrite(committed) => Self::Rewrite {
                step: committed.step(),
                rule,
            },
            AppliedRule::Return(committed) => Self::Return {
                step: committed.step(),
                rule,
                output: committed.into_output(),
            },
        }
    }
}

impl ProgramOwner for BorrowedProgram<'_> {
    fn program(&self) -> &Program {
        self.program
    }
}

impl ProgramOwner for OwnedProgram {
    fn program(&self) -> &Program {
        &self.program
    }
}

impl RunCore {
    /// Builds the mutable runtime core for one execution.
    ///
    /// # Errors
    ///
    /// Returns `RunStartError` if per-run rule state allocation fails.
    fn new(program: &Program, seed: RunSeed) -> Result<Self, RunStartError> {
        let (input, budget) = seed.into_runtime_parts();
        let state = State::from_input(input);
        let once_states = OnceStateSet::new(program.once_rule_count())?;
        Ok(Self {
            state,
            scratch: RewriteScratch::new(),
            budget,
            once_states,
        })
    }

    /// Number of steps already committed in this core.
    pub(super) const fn completed_steps(&self) -> StepCount {
        self.budget.completed_steps()
    }

    /// Borrows the current runtime state.
    pub(super) fn state(&self) -> RuntimeStateView<'_> {
        self.state.view()
    }

    /// Materializes a stable terminal result.
    ///
    /// # Errors
    ///
    /// Returns `RunFinishError` if final state materialization cannot allocate.
    pub(super) fn into_stable_result(self, steps: StepCount) -> Result<RunResult, RunFinishError> {
        let output = self
            .state
            .into_snapshot()
            .map_err(RunFinishError::FinalOutput)?;
        Ok(RunResult::stable(output, steps))
    }

    /// Advances the mutable runtime core against the supplied immutable program.
    ///
    /// # Errors
    ///
    /// Returns `RunStepError` if applying the matched rule exceeds limits or allocation fails.
    fn step_runtime<'program>(
        &mut self,
        program: &'program Program,
    ) -> Result<RuntimeStep<'program>, RunStepError> {
        let matched =
            match find_next_match(program.rule_slice(), &mut self.once_states, &self.state)? {
                RuleSearch::Matched(matched) => matched,
                RuleSearch::Stable => {
                    return Ok(RuntimeStep::Stable(self.budget.completed_steps()));
                }
            };

        let state_len = self.state.byte_count();
        let prepared =
            prepare_matched_rule(&mut self.scratch, &mut self.budget, state_len, matched)?;
        let applied = prepared.commit(&mut self.state, &mut self.scratch);
        Ok(RuntimeStep::Applied(applied))
    }

    /// Advances the mutable runtime core against the supplied immutable program.
    ///
    /// # Errors
    ///
    /// Returns `RunStepError` if applying the matched rule exceeds limits or allocation fails.
    fn step(&mut self, program: &Program) -> Result<CoreStep<()>, RunStepError> {
        let applied = match self.step_runtime(program)? {
            RuntimeStep::Applied(applied) => applied,
            RuntimeStep::Stable(steps) => return Ok(CoreStep::Stable(steps)),
        };
        Ok(CoreStep::Applied(CoreAppliedRule::from_applied_rule(
            applied,
            (),
        )))
    }
}

impl<P: ProgramOwner> Session<P> {
    /// Starts a new run session for a parsed program and admitted run seed.
    ///
    /// # Errors
    ///
    /// Returns `RunStartError` if allocating per-run rule state fails.
    pub(super) fn new(program: P, seed: RunSeed) -> Result<Self, RunStartError> {
        let core = RunCore::new(program.program(), seed)?;
        Ok(Self { program, core })
    }

    /// Borrows the parsed program.
    pub(super) fn program(&self) -> &Program {
        self.program.program()
    }

    /// Number of execution steps that have already completed in this run.
    pub(super) const fn completed_steps(&self) -> StepCount {
        self.core.completed_steps()
    }

    /// Borrow the current runtime state.
    pub(super) fn state(&self) -> RuntimeStateView<'_> {
        self.core.state()
    }

    /// Advances this run by exactly one matching rule when possible.
    ///
    /// # Errors
    ///
    /// Returns `RunStepError` if rule matching or rule application fails.
    pub(super) fn step(&mut self) -> Result<CoreStep<()>, RunStepError> {
        self.core.step(self.program.program())
    }

    /// Runs this session to completion.
    ///
    /// # Errors
    ///
    /// Returns `RunFinishError` when a later matching rule would exceed configured
    /// limits.
    pub(super) fn finish(mut self) -> Result<RunResult, RunFinishError> {
        loop {
            match self.step().map_err(RunFinishError::from)? {
                CoreStep::Applied(CoreAppliedRule::Rewrite { .. }) => {}
                CoreStep::Applied(CoreAppliedRule::Return { step, output, .. }) => {
                    return Ok(RunResult::from_return(output, step));
                }
                CoreStep::Stable(steps) => return self.core.into_stable_result(steps),
            }
        }
    }
}

impl<P: ProgramOwner> AttemptSession<P> {
    /// Starts a new rule-attempt session for a parsed program and admitted run seed.
    ///
    /// # Errors
    ///
    /// Returns `RunStartError` if allocating per-run rule state fails.
    pub(super) fn new(
        program: P,
        seed: RunSeed,
        limit: RuleAttemptLimit,
    ) -> Result<Self, RunStartError> {
        let cursor = program.program().rule_attempt_cursor();
        let core = RunCore::new(program.program(), seed)?;
        Ok(Self {
            program,
            core,
            cursor,
            attempt_budget: RuleAttemptBudgetState::new(limit),
        })
    }

    /// Borrows the parsed program.
    pub(super) fn program(&self) -> &Program {
        self.program.program()
    }

    /// Number of execution steps that have already completed in this run.
    pub(super) const fn completed_steps(&self) -> StepCount {
        self.core.completed_steps()
    }

    /// Number of executable rule-line attempts consumed so far.
    pub(super) const fn completed_attempts(&self) -> RuleAttemptCount {
        self.attempt_budget.completed_attempts()
    }

    /// Borrow the current runtime state.
    pub(super) fn state(&self) -> RuntimeStateView<'_> {
        self.core.state()
    }
}

impl<'program> Session<BorrowedProgram<'program>> {
    /// Advances this run by one matching rule with borrowed rule witnesses.
    ///
    /// # Errors
    ///
    /// Returns `RunStepError` if matching, preparation, or application fails.
    pub(super) fn step_borrowed(&mut self) -> Result<CoreStep<RuleView<'program>>, RunStepError> {
        step_with_witness(&mut self.core, self.program.program, Ok)
    }
}

impl Session<OwnedProgram> {
    /// Advances this run by one matching rule with owned rule witnesses.
    ///
    /// # Errors
    ///
    /// Returns `OwnedRunStepError` if matching, preparation, witness materialization,
    /// or application fails.
    pub(super) fn step_owned(&mut self) -> Result<CoreStep<OwnedRuleWitness>, OwnedRunStepError> {
        step_with_witness(&mut self.core, &self.program.program, |rule| {
            OwnedRuleWitness::from_rule_view(rule).map_err(OwnedRunStepError::RuleWitnessAllocation)
        })
    }
}

impl<'program> AttemptSession<BorrowedProgram<'program>> {
    /// Advances this rule-attempt run by one executable rule with borrowed rule witnesses.
    ///
    /// # Errors
    ///
    /// Returns `RuleAttemptStepError` if rule-attempt matching, preparation, or application
    /// fails.
    pub(super) fn step_borrowed(
        &mut self,
    ) -> Result<CoreRuleAttempt<RuleView<'program>>, RuleAttemptStepError> {
        let mut context = RuleAttemptContext {
            program: self.program.program,
            core: &mut self.core,
            cursor: &mut self.cursor,
            attempt_budget: &mut self.attempt_budget,
        };
        attempt_current_rule_with_witness(&mut context, Ok)
    }
}

impl AttemptSession<OwnedProgram> {
    /// Advances this rule-attempt run by one executable rule with owned rule witnesses.
    ///
    /// # Errors
    ///
    /// Returns `OwnedRuleAttemptStepError` if rule-attempt matching, preparation, witness
    /// materialization, or application fails.
    pub(super) fn step_owned(
        &mut self,
    ) -> Result<CoreRuleAttempt<OwnedRuleWitness>, OwnedRuleAttemptStepError> {
        let mut context = RuleAttemptContext {
            program: &self.program.program,
            core: &mut self.core,
            cursor: &mut self.cursor,
            attempt_budget: &mut self.attempt_budget,
        };
        attempt_current_rule_with_witness(&mut context, |rule| {
            OwnedRuleWitness::from_rule_view(rule)
                .map_err(OwnedRuleAttemptStepError::RuleWitnessAllocation)
        })
    }
}

/// Advances the current run using the supplied rule-witness boundary.
///
/// # Errors
///
/// Returns `Error` if matching, rule preparation, rule-witness materialization,
/// or rule application fails.
fn step_with_witness<'program, RuleWitness, Error>(
    core: &mut RunCore,
    program: &'program Program,
    make_witness: impl FnOnce(RuleView<'program>) -> Result<RuleWitness, Error>,
) -> Result<CoreStep<RuleWitness>, Error>
where
    Error: From<RunStepError>,
{
    let matched = match find_next_match(program.rule_slice(), &mut core.once_states, &core.state)
        .map_err(RunStepError::from)?
    {
        RuleSearch::Matched(matched) => matched,
        RuleSearch::Stable => return Ok(CoreStep::Stable(core.budget.completed_steps())),
    };
    let state_len = core.state.byte_count();
    let prepared = prepare_matched_rule(&mut core.scratch, &mut core.budget, state_len, matched)?;
    let witness = make_witness(RuleView::new(prepared.rule()))?;
    let applied = prepared.commit(&mut core.state, &mut core.scratch);
    Ok(CoreStep::Applied(CoreAppliedRule::from_applied_rule(
        applied, witness,
    )))
}

/// Evaluates the current cursor against a parsed program.
///
/// # Errors
///
/// Returns `Error` if rule-attempt, rule matching, or rule application
/// fails.
fn attempt_current_rule_with_witness<'program, RuleWitness, Error>(
    context: &mut RuleAttemptContext<'_, 'program>,
    make_witness: impl FnOnce(RuleView<'program>) -> Result<RuleWitness, Error>,
) -> Result<CoreRuleAttempt<RuleWitness>, Error>
where
    Error: From<RuleAttemptStepError> + From<RunStepError>,
{
    let Some(active_cursor) = context.cursor.take_active() else {
        return Ok(no_executable_rules(context));
    };
    let target = context
        .program
        .target_for_cursor(active_cursor)
        .map_err(RuleAttemptStepError::from)?;
    let runtime_rule = runtime_rule_for_target(&mut context.core.once_states, target)
        .map_err(RunStepError::from)?;

    let reservation = context
        .attempt_budget
        .reserve_next_attempt(context.core.state.byte_count())?;
    let attempted = attempt_rule(runtime_rule, &context.core.state);

    match attempted {
        RuleAttempt::Missed(missed) => {
            let witness = make_witness(RuleView::new(missed.rule()))?;
            let attempt = reservation.commit();
            Ok(commit_miss(MissCommit {
                cursor: &mut *context.cursor,
                attempt_budget: &*context.attempt_budget,
                core: &*context.core,
                attempt,
                active_cursor,
                miss: RuleMiss::new(witness, missed.reason()),
            }))
        }
        RuleAttempt::Matched(matched) => {
            let state_len = context.core.state.byte_count();
            let prepared = prepare_matched_rule(
                &mut context.core.scratch,
                &mut context.core.budget,
                state_len,
                matched,
            )?;
            let witness = make_witness(RuleView::new(prepared.rule()))?;
            let attempt = reservation.commit();
            let applied = prepared.commit(&mut context.core.state, &mut context.core.scratch);
            let applied = CoreAppliedRule::from_applied_rule(applied, witness);
            if matches!(applied, CoreAppliedRule::Rewrite { .. }) {
                *context.cursor = RuleCursor::Active(active_cursor.reset_to_first());
            }
            Ok(CoreRuleAttempt::Applied { attempt, applied })
        }
    }
}

/// Materializes a stable rule-attempt result when the cursor has no executable target.
fn no_executable_rules<RuleWitness>(
    context: &RuleAttemptContext<'_, '_>,
) -> CoreRuleAttempt<RuleWitness> {
    CoreRuleAttempt::Stable {
        attempts: context.attempt_budget.completed_attempts(),
        steps: context.core.completed_steps(),
        stable_reason: RuleAttemptStableReason::NoExecutableRules,
    }
}

/// Commits a non-applying rule attempt and decides whether the run is stable.
fn commit_miss<RuleWitness>(context: MissCommit<'_, RuleWitness>) -> CoreRuleAttempt<RuleWitness> {
    match context.active_cursor.advance_after_miss() {
        RuleCursorAfterMiss::Stable => CoreRuleAttempt::Stable {
            attempts: context.attempt_budget.completed_attempts(),
            steps: context.core.completed_steps(),
            stable_reason: RuleAttemptStableReason::FinalMiss(context.miss),
        },
        RuleCursorAfterMiss::Advanced(active_cursor) => {
            *context.cursor = RuleCursor::Active(active_cursor);
            CoreRuleAttempt::Missed {
                attempt: context.attempt,
                miss: context.miss,
            }
        }
    }
}

impl<'program> Session<BorrowedProgram<'program>> {
    /// Runs to completion while emitting borrowed trace events.
    ///
    /// # Errors
    ///
    /// Returns `TracedRunError::Trace` if the trace sink fails. Returns
    /// `TracedRunError::Run` if runtime execution fails.
    pub(super) fn run_with_borrowed_trace<F, E>(
        mut self,
        mut trace: F,
    ) -> Result<RunResult, TracedRunError<E>>
    where
        F: for<'run> FnMut(BorrowedTraceEvent<'program, 'run>) -> Result<(), E>,
    {
        trace(BorrowedTraceEvent::Initial {
            state: self.state(),
        })
        .map_err(TracedRunError::Trace)?;

        loop {
            match self
                .core
                .step_runtime(self.program.program)
                .map_err(RunFinishError::from)
                .map_err(RunError::from)
                .map_err(TracedRunError::Run)?
            {
                RuntimeStep::Applied(AppliedRule::Rewrite(committed)) => {
                    let step = committed.step();
                    let rule = RuleView::new(committed.rule());
                    Self::emit_step_trace(
                        &mut trace,
                        step,
                        rule,
                        BorrowedTraceEffect::Continue {
                            state: self.state(),
                        },
                    )?;
                }
                RuntimeStep::Applied(AppliedRule::Return(committed)) => {
                    let step = committed.step();
                    let rule = RuleView::new(committed.rule());
                    let output = committed.output_view();
                    Self::emit_step_trace(
                        &mut trace,
                        step,
                        rule,
                        BorrowedTraceEffect::Return { output },
                    )?;
                    return Ok(RunResult::from_return(committed.into_output(), step));
                }
                RuntimeStep::Stable(steps) => {
                    return self
                        .core
                        .into_stable_result(steps)
                        .map_err(RunError::from)
                        .map_err(TracedRunError::Run);
                }
            }
        }
    }

    /// Emits one borrowed step trace event.
    ///
    /// # Errors
    ///
    /// Returns `TracedRunError::Trace` if the trace sink rejects the event.
    fn emit_step_trace<F, E>(
        trace: &mut F,
        step: StepCount,
        rule: RuleView<'program>,
        effect: BorrowedTraceEffect<'program, '_>,
    ) -> Result<(), TracedRunError<E>>
    where
        F: for<'run> FnMut(BorrowedTraceEvent<'program, 'run>) -> Result<(), E>,
    {
        trace(BorrowedTraceEvent::Step { step, rule, effect }).map_err(TracedRunError::Trace)
    }
}

impl Session<OwnedProgram> {
    /// Splits an owned session into its program and mutable core.
    pub(super) fn into_program_core(self) -> (Program, RunCore) {
        (self.program.program, self.core)
    }
}

impl AttemptSession<OwnedProgram> {
    /// Splits an owned rule-attempt session into its program and mutable core.
    pub(super) fn into_program_core(self) -> (Program, RunCore) {
        (self.program.program, self.core)
    }
}