rsaeb 0.7.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
//! Public stepwise execution typestates.
//!
//! [`Program::start_execution`](crate::Program::start_execution) returns a
//! [`RunningExecution`]. Calling [`RunningExecution::step`] consumes that value
//! and returns an [`ExecutionTransition`], so callers must handle the next
//! state explicitly: continue with [`AppliedExecution::into_running`], finish a
//! [`StableExecution`], or finish a [`ReturnedExecution`].
//!
//! This shape keeps terminal executions separate from the only state that can
//! still step. Runtime internals stay private; public values expose borrowed
//! state and rule views that are valid for observation without making the
//! mutable runtime engine part of the API.

use crate::error::{LimitError, RunError, StateLimitContext, TracedRunError};
use crate::program::{Program, RunLimits, RunResult, StepCount};
use crate::rule::Rule;
use crate::runtime::action::{AppliedRule, StepApplication, apply_matched_rule};
use crate::runtime::budget::StepBudget;
use crate::runtime::input::{InitialStateBytes, RuntimeInput};
use crate::runtime::matcher::{RuleSearch, find_next_match};
use crate::runtime::once::OnceStateSet;
use crate::runtime::rewrite::RewriteScratch;
use crate::runtime::state::State;
use crate::trace::{BorrowedTraceEffect, BorrowedTraceEvent, RuntimeStateView};
use crate::{inspect::PayloadView, inspect::RuleView};

/// Stateful execution that can still apply rules.
///
/// This type represents the only state with a `step` method. Stable and
/// returned executions are represented by separate terminal types, so callers
/// cannot step after completion. A running execution owns per-run `(once)`
/// state and the current runtime state.
pub struct RunningExecution<'program> {
    pub(crate) core: ExecutionCore<'program>,
}

#[derive(Debug, PartialEq, Eq)]
pub(crate) struct ExecutionCore<'program> {
    pub(crate) state: State,
    pub(crate) scratch: RewriteScratch,
    pub(crate) step_budget: StepBudget,
    pub(crate) rules: &'program [Rule],
    pub(crate) once_states: OnceStateSet,
    pub(crate) limits: RunLimits,
}

/// Result of advancing a running execution once.
///
/// The transition is exhaustive over the public execution lifecycle: one rule
/// committed and execution can continue, no rule matched, or a `(return)` rule
/// produced final output.
pub enum ExecutionTransition<'program> {
    /// One ordinary rewrite rule was applied and execution can continue.
    Applied(AppliedExecution<'program>),
    /// No rule matched the final runtime state.
    Stable(StableExecution<'program>),
    /// A matched rule executed `(return)`.
    Returned(ReturnedExecution<'program>),
}

/// One committed non-terminal rule application.
///
/// This value lets a caller inspect the applied rule and post-step state before
/// deciding whether to continue execution.
pub struct AppliedExecution<'program> {
    step: StepCount,
    rule: RuleView<'program>,
    execution: RunningExecution<'program>,
}

/// Terminal execution state reached by no matching rule.
///
/// Stable executions still own the final runtime state until the caller either
/// borrows it or materializes it with [`StableExecution::into_result`].
pub struct StableExecution<'program> {
    steps: StepCount,
    core: ExecutionCore<'program>,
}

/// Terminal execution state reached by `(return)`.
///
/// The output is a borrowed parsed payload until the caller materializes the
/// terminal [`RunResult`] through [`ReturnedExecution::into_result`].
#[derive(Clone, Copy)]
pub struct ReturnedExecution<'program> {
    step: StepCount,
    rule: RuleView<'program>,
    output: PayloadView<'program>,
}

/// Runtime failure that preserves the uncommitted running execution.
///
/// Step failures happen before the candidate rewrite is committed. The failed
/// [`RunningExecution`] is therefore returned by value so hosts can inspect,
/// update the limits with [`RunningExecution::with_limits`], or discard it
/// explicitly.
pub struct ExecutionStepError<'program> {
    error: RunError,
    execution: RunningExecution<'program>,
}

impl core::fmt::Debug for RunningExecution<'_> {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter
            .debug_struct("RunningExecution")
            .field("completed_steps", &self.completed_steps())
            .field("state", &self.state())
            .finish()
    }
}

impl core::fmt::Debug for ExecutionTransition<'_> {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Applied(applied) => formatter.debug_tuple("Applied").field(applied).finish(),
            Self::Stable(stable) => formatter.debug_tuple("Stable").field(stable).finish(),
            Self::Returned(returned) => formatter.debug_tuple("Returned").field(returned).finish(),
        }
    }
}

impl core::fmt::Debug for AppliedExecution<'_> {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter
            .debug_struct("AppliedExecution")
            .field("step", &self.step())
            .field("rule", &self.rule())
            .field("state", &self.state())
            .finish()
    }
}

impl core::fmt::Debug for StableExecution<'_> {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter
            .debug_struct("StableExecution")
            .field("steps", &self.steps())
            .field("state", &self.state())
            .finish()
    }
}

impl core::fmt::Debug for ReturnedExecution<'_> {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter
            .debug_struct("ReturnedExecution")
            .field("step", &self.step())
            .field("rule", &self.rule())
            .field("output", &self.output())
            .finish()
    }
}

impl core::fmt::Debug for ExecutionStepError<'_> {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter
            .debug_struct("ExecutionStepError")
            .field("error", &self.error())
            .field("execution", &self.execution())
            .finish()
    }
}

impl<'program> ExecutionCore<'program> {
    /// Builds the mutable runtime core for one execution.
    ///
    /// # Errors
    ///
    /// Returns `RunError` if input materialization fails, input exceeds runtime
    /// state limits, or per-execution rule state allocation fails.
    pub(crate) fn new(
        program: &'program Program,
        input: &RuntimeInput,
        limits: RunLimits,
    ) -> Result<Self, RunError> {
        let input = InitialStateBytes::materialize(input, limits)?;
        let state = State::from_input(input);
        let once_states = OnceStateSet::new(program.once_slot_count())?;
        Ok(Self {
            state,
            scratch: RewriteScratch::new(),
            step_budget: StepBudget::new(limits.step_limit()),
            rules: program.rule_slice(),
            once_states,
            limits,
        })
    }

    pub(crate) const fn completed_steps(&self) -> StepCount {
        self.step_budget.completed_steps()
    }

    pub(crate) fn state(&self) -> RuntimeStateView<'_> {
        self.state.view()
    }

    /// Materializes a stable terminal result.
    ///
    /// # Errors
    ///
    /// Returns `RunError` if final state materialization cannot allocate.
    pub(crate) fn into_stable_result(self, steps: StepCount) -> Result<RunResult, RunError> {
        Ok(RunResult::stable(self.state.into_snapshot()?, steps))
    }
}

impl<'program> RunningExecution<'program> {
    /// Starts a new running execution for a parsed program and validated input.
    ///
    /// # Errors
    ///
    /// Returns `RunError` if runtime input materialization fails, state limits
    /// reject the input, or per-execution rule state allocation fails.
    pub(crate) fn new(
        program: &'program Program,
        input: &RuntimeInput,
        limits: RunLimits,
    ) -> Result<Self, RunError> {
        Ok(Self {
            core: ExecutionCore::new(program, input, limits)?,
        })
    }

    /// Number of rewrite steps that have already completed in this execution.
    #[must_use]
    pub const fn completed_steps(&self) -> StepCount {
        self.core.completed_steps()
    }

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

    /// Replaces runtime limits for this uncommitted execution.
    ///
    /// # Errors
    ///
    /// Returns `RunError` if the already-completed step count or the current
    /// runtime state does not fit the replacement limits.
    pub fn with_limits(mut self, limits: RunLimits) -> Result<Self, RunError> {
        let completed_steps = self.core.step_budget.completed_steps();
        let state_len = self.core.state.byte_count();

        if completed_steps.get() > limits.step_limit().get() {
            return Err(LimitError::step(limits.step_limit(), completed_steps, state_len).into());
        }

        if state_len.get() > limits.state_byte_limit().get() {
            return Err(LimitError::state(
                StateLimitContext::CurrentState,
                limits.state_byte_limit(),
                state_len,
            )
            .into());
        }

        self.core.limits = limits;
        self.core.step_budget = self.core.step_budget.with_limit(limits.step_limit());
        Ok(self)
    }

    /// Advances this execution by exactly one matching rule when possible.
    ///
    /// Consuming `self` makes terminal states explicit. Call
    /// [`AppliedExecution::into_running`] to continue after an applied rule.
    ///
    /// # Errors
    ///
    /// Returns `ExecutionStepError` if the matching rule cannot commit because
    /// runtime limits or allocation fail. The error preserves the uncommitted
    /// execution.
    #[expect(
        clippy::result_large_err,
        reason = "ExecutionStepError preserves the uncommitted execution by value without allocating on the error path"
    )]
    pub fn step(mut self) -> Result<ExecutionTransition<'program>, ExecutionStepError<'program>> {
        let applied = {
            let ExecutionCore {
                state,
                scratch,
                step_budget,
                rules,
                once_states,
                limits,
            } = &mut self.core;

            let matched = match find_next_match(rules, once_states, state) {
                RuleSearch::Matched(matched) => matched,
                RuleSearch::Stable => {
                    let steps = step_budget.completed_steps();
                    return Ok(ExecutionTransition::Stable(StableExecution {
                        steps,
                        core: self.core,
                    }));
                }
            };

            apply_matched_rule(state, scratch, step_budget, once_states, *limits, matched)
        };

        let applied = match applied {
            Ok(applied) => applied,
            Err(error) => return Err(ExecutionStepError::new(error, self)),
        };

        Ok(applied.into_transition(self))
    }

    /// Runs this execution to completion.
    ///
    /// # Errors
    ///
    /// Returns `RunError` when applying a later matching rule would exceed the
    /// configured limits, allocation fails, or state-size arithmetic overflows.
    pub fn finish(mut self) -> Result<RunResult, RunError> {
        loop {
            match self.step() {
                Ok(ExecutionTransition::Applied(applied)) => {
                    self = applied.into_running();
                }
                Ok(ExecutionTransition::Stable(stable)) => {
                    return stable.into_result();
                }
                Ok(ExecutionTransition::Returned(returned)) => {
                    return returned.into_result();
                }
                Err(error) => return Err(error.into_error()),
            }
        }
    }
}

impl<'program> AppliedRule<'program> {
    fn into_transition(
        self,
        execution: RunningExecution<'program>,
    ) -> ExecutionTransition<'program> {
        match self.effect {
            StepApplication::Continue => ExecutionTransition::Applied(AppliedExecution {
                step: self.step,
                rule: self.rule,
                execution,
            }),
            StepApplication::Return(output) => ExecutionTransition::Returned(ReturnedExecution {
                step: self.step,
                rule: self.rule,
                output,
            }),
        }
    }
}

impl<'program> AppliedExecution<'program> {
    /// One-based applied step count.
    #[must_use]
    pub const fn step(&self) -> StepCount {
        self.step
    }

    /// Structured view of the applied rule.
    #[must_use]
    pub const fn rule(&self) -> RuleView<'program> {
        self.rule
    }

    /// Runtime state after the applied rewrite step.
    #[must_use]
    pub fn state(&self) -> RuntimeStateView<'_> {
        self.execution.state()
    }

    /// Continue running after observing this applied step.
    #[must_use]
    pub fn into_running(self) -> RunningExecution<'program> {
        self.execution
    }
}

impl StableExecution<'_> {
    /// Number of rewrite steps applied before reaching the stable state.
    #[must_use]
    pub const fn steps(&self) -> StepCount {
        self.steps
    }

    /// Borrowed final runtime state.
    #[must_use]
    pub fn state(&self) -> RuntimeStateView<'_> {
        self.core.state()
    }

    /// Materializes this stable execution as a run result.
    ///
    /// # Errors
    ///
    /// Returns `RunError` if final state materialization cannot allocate.
    pub fn into_result(self) -> Result<RunResult, RunError> {
        self.core.into_stable_result(self.steps)
    }
}

impl<'program> ReturnedExecution<'program> {
    /// One-based applied step count for the return rule.
    #[must_use]
    pub const fn step(&self) -> StepCount {
        self.step
    }

    /// Structured view of the return rule.
    #[must_use]
    pub const fn rule(&self) -> RuleView<'program> {
        self.rule
    }

    /// Borrowed return payload from the parsed program.
    #[must_use]
    pub const fn output(&self) -> PayloadView<'program> {
        self.output
    }

    /// Materializes this returned execution as a run result.
    ///
    /// # Errors
    ///
    /// Returns `RunError` if return output materialization cannot allocate.
    pub fn into_result(self) -> Result<RunResult, RunError> {
        Ok(RunResult::from_return(
            ExecutionCore::materialize_return_output(self.output)?,
            self.step,
        ))
    }
}

impl<'program> ExecutionStepError<'program> {
    fn new(error: RunError, execution: RunningExecution<'program>) -> Self {
        Self { error, execution }
    }

    /// Runtime error that prevented the step from committing.
    #[must_use]
    pub const fn error(&self) -> &RunError {
        &self.error
    }

    /// Borrow the uncommitted execution.
    #[must_use]
    pub const fn execution(&self) -> &RunningExecution<'program> {
        &self.execution
    }

    /// Recover the uncommitted execution.
    #[must_use]
    pub fn into_execution(self) -> RunningExecution<'program> {
        self.execution
    }

    /// Discard the uncommitted execution and return the runtime error.
    #[must_use]
    pub fn into_error(self) -> RunError {
        self.error
    }
}

impl core::fmt::Display for ExecutionStepError<'_> {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        self.error.fmt(formatter)
    }
}

impl core::error::Error for ExecutionStepError<'_> {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        Some(&self.error)
    }
}

impl<'program> RunningExecution<'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(crate) 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.step() {
                Ok(ExecutionTransition::Applied(applied)) => {
                    Self::emit_step_trace(
                        &mut trace,
                        applied.step(),
                        applied.rule(),
                        BorrowedTraceEffect::Continue {
                            state: applied.state(),
                        },
                    )?;
                    self = applied.into_running();
                }
                Ok(ExecutionTransition::Stable(stable)) => {
                    return stable.into_result().map_err(TracedRunError::Run);
                }
                Ok(ExecutionTransition::Returned(returned)) => {
                    Self::emit_step_trace(
                        &mut trace,
                        returned.step(),
                        returned.rule(),
                        BorrowedTraceEffect::Return {
                            output: returned.output(),
                        },
                    )?;
                    return returned.into_result().map_err(TracedRunError::Run);
                }
                Err(error) => return Err(TracedRunError::Run(error.into_error())),
            }
        }
    }

    /// 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)
    }
}