rsaeb 0.10.1

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
use core::error::Error;

use crate::allocation::AllocationError;
use crate::bytes::{
    NonAsciiInputByte, PayloadByteCount, ReturnOutputByteCount, RuntimeInputByteCount,
    RuntimeStateByteCount,
};
use crate::inspect::RulePosition;
use crate::limits::{
    ReturnByteLimit, RuleAttemptCount, RuleAttemptLimit, RuntimeInputByteLimit,
    RuntimeStateByteLimit, StepCount, StepLimit,
};

/// Run-to-completion execution error.
///
/// This is the composed error returned by [`Program::run`](crate::program::Program::run)
/// and traced run APIs. It does not include input validation or run admission,
/// because those happen before execution starts.
#[derive(Debug, PartialEq, Eq)]
pub enum RunError {
    /// The run could not be started.
    Start(RunStartError),
    /// The started run failed before producing a terminal result.
    Finish(RunFinishError),
}

impl Error for RunError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Start(error) => Some(error),
            Self::Finish(error) => Some(error),
        }
    }
}

impl From<RunStartError> for RunError {
    fn from(value: RunStartError) -> Self {
        Self::Start(value)
    }
}

impl From<RunFinishError> for RunError {
    fn from(value: RunFinishError) -> Self {
        Self::Finish(value)
    }
}

/// Error while constructing one runtime execution from an admitted seed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RunStartError {
    /// Per-run execution state allocation failed.
    Allocation(AllocationError),
}

impl Error for RunStartError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Allocation(error) => Some(error),
        }
    }
}

impl From<AllocationError> for RunStartError {
    fn from(value: AllocationError) -> Self {
        Self::Allocation(value)
    }
}

/// Error while advancing one ordinary matched-rule step.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RunStepError {
    /// Runtime allocation failed while preparing or committing the candidate step.
    Allocation(AllocationError),
    /// Rewrite length arithmetic could not be represented.
    RewriteSize(RewriteSizeError),
    /// The candidate rewrite would exceed the runtime-state limit.
    RuntimeStateLimit(RuntimeStateLimitError),
    /// The candidate `(return)` output would exceed the return-output limit.
    ReturnOutputLimit(ReturnOutputLimitError),
    /// The candidate step would exceed the step limit.
    StepLimit(StepLimitError),
    /// Runtime rule metadata and per-run rule state no longer align.
    RuleRuntimeState(RuleRuntimeStateError),
}

impl Error for RunStepError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Allocation(error) => Some(error),
            Self::RewriteSize(error) => Some(error),
            Self::RuntimeStateLimit(error) => Some(error),
            Self::ReturnOutputLimit(error) => Some(error),
            Self::StepLimit(error) => Some(error),
            Self::RuleRuntimeState(error) => Some(error),
        }
    }
}

impl From<AllocationError> for RunStepError {
    fn from(value: AllocationError) -> Self {
        Self::Allocation(value)
    }
}

impl From<RewriteSizeError> for RunStepError {
    fn from(value: RewriteSizeError) -> Self {
        Self::RewriteSize(value)
    }
}

impl From<RuntimeStateLimitError> for RunStepError {
    fn from(value: RuntimeStateLimitError) -> Self {
        Self::RuntimeStateLimit(value)
    }
}

impl From<ReturnOutputLimitError> for RunStepError {
    fn from(value: ReturnOutputLimitError) -> Self {
        Self::ReturnOutputLimit(value)
    }
}

impl From<StepLimitError> for RunStepError {
    fn from(value: StepLimitError) -> Self {
        Self::StepLimit(value)
    }
}

impl From<RuleRuntimeStateError> for RunStepError {
    fn from(value: RuleRuntimeStateError) -> Self {
        Self::RuleRuntimeState(value)
    }
}

/// Error while advancing an owned ordinary step.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OwnedRunStepError {
    /// Ordinary runtime step preparation failed.
    Step(RunStepError),
    /// Retaining the owned rule witness failed.
    RuleWitnessAllocation(AllocationError),
}

impl Error for OwnedRunStepError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Step(error) => Some(error),
            Self::RuleWitnessAllocation(error) => Some(error),
        }
    }
}

impl From<RunStepError> for OwnedRunStepError {
    fn from(value: RunStepError) -> Self {
        Self::Step(value)
    }
}

/// Error while advancing one rule-attempt step.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RuleAttemptStepError {
    /// Matched-rule execution failed.
    Step(RunStepError),
    /// The next executable rule-line attempt would exceed the attempt limit.
    RuleAttemptLimit(RuleAttemptLimitError),
    /// The rule-attempt cursor no longer points at a parsed rule.
    RuleCursor(RuleAttemptCursorError),
}

impl Error for RuleAttemptStepError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Step(error) => Some(error),
            Self::RuleAttemptLimit(error) => Some(error),
            Self::RuleCursor(error) => Some(error),
        }
    }
}

impl From<RunStepError> for RuleAttemptStepError {
    fn from(value: RunStepError) -> Self {
        Self::Step(value)
    }
}

impl From<RuleAttemptLimitError> for RuleAttemptStepError {
    fn from(value: RuleAttemptLimitError) -> Self {
        Self::RuleAttemptLimit(value)
    }
}

impl From<RuleAttemptCursorError> for RuleAttemptStepError {
    fn from(value: RuleAttemptCursorError) -> Self {
        Self::RuleCursor(value)
    }
}

/// Error while advancing one owned rule-attempt step.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OwnedRuleAttemptStepError {
    /// Ordinary borrowed rule-attempt failure domain.
    Attempt(RuleAttemptStepError),
    /// Retaining the owned rule witness failed.
    RuleWitnessAllocation(AllocationError),
}

impl Error for OwnedRuleAttemptStepError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Attempt(error) => Some(error),
            Self::RuleWitnessAllocation(error) => Some(error),
        }
    }
}

impl From<RuleAttemptStepError> for OwnedRuleAttemptStepError {
    fn from(value: RuleAttemptStepError) -> Self {
        Self::Attempt(value)
    }
}

impl From<RunStepError> for OwnedRuleAttemptStepError {
    fn from(value: RunStepError) -> Self {
        Self::Attempt(RuleAttemptStepError::Step(value))
    }
}

/// Error while finishing a run session that has already started.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RunFinishError {
    /// A later matched-rule step failed.
    Step(RunStepError),
    /// Stable final-output materialization failed.
    FinalOutput(AllocationError),
}

impl Error for RunFinishError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Step(error) => Some(error),
            Self::FinalOutput(error) => Some(error),
        }
    }
}

impl From<RunStepError> for RunFinishError {
    fn from(value: RunStepError) -> Self {
        Self::Step(value)
    }
}

/// Runtime input validation boundary error.
///
/// This error is produced before execution starts, while raw host bytes are
/// being classified as [`input::RuntimeInput`](crate::input::RuntimeInput).
/// It is intentionally separate from [`RunError`] so callers can report invalid
/// input without treating it as a runtime failure.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RuntimeInputError {
    /// Runtime input contained a non-ASCII byte.
    NonAscii {
        /// One-based input column.
        column: InputColumn,
        /// Rejected byte.
        byte: NonAsciiInputByte,
    },
    /// A one-based input column could not be represented.
    ColumnOverflow,
    /// Runtime input exceeded its input-byte construction budget.
    InputLimit {
        /// Configured maximum runtime input length.
        limit: RuntimeInputByteLimit,
        /// Runtime input length that would have been classified.
        attempted_len: RuntimeInputByteCount,
    },
    /// Storing validated runtime input failed.
    Allocation(AllocationError),
}

impl RuntimeInputError {
    /// Builds the non ascii value.
    pub(crate) const fn non_ascii(column: InputColumn, byte: NonAsciiInputByte) -> Self {
        Self::NonAscii { column, byte }
    }

    /// Builds the column overflow value.
    pub(crate) const fn column_overflow() -> Self {
        Self::ColumnOverflow
    }

    /// Builds the input limit value.
    pub(crate) const fn input_limit(
        limit: RuntimeInputByteLimit,
        attempted_len: RuntimeInputByteCount,
    ) -> Self {
        Self::InputLimit {
            limit,
            attempted_len,
        }
    }
}

impl Error for RuntimeInputError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Allocation(error) => Some(error),
            Self::NonAscii { .. } | Self::ColumnOverflow | Self::InputLimit { .. } => None,
        }
    }
}

impl From<AllocationError> for RuntimeInputError {
    fn from(value: AllocationError) -> Self {
        Self::Allocation(value)
    }
}

/// Run admission boundary error.
///
/// This error is produced after runtime input validation and before execution
/// starts, while validated input is admitted as the initial runtime state under
/// execution limits. It means the input bytes were valid runtime input, but the
/// execution policy rejected them as the initial state for this run.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RunAdmissionError {
    /// Runtime input exceeded the initial runtime-state budget for this run.
    InitialStateTooLarge {
        /// Configured maximum runtime state length.
        limit: RuntimeStateByteLimit,
        /// Runtime state length that would have been materialized.
        attempted_len: RuntimeStateByteCount,
    },
}

impl RunAdmissionError {
    /// Builds the initial state limit value.
    pub(crate) const fn initial_state_limit(
        limit: RuntimeStateByteLimit,
        attempted_len: RuntimeStateByteCount,
    ) -> Self {
        Self::InitialStateTooLarge {
            limit,
            attempted_len,
        }
    }
}

impl Error for RunAdmissionError {}

/// Runtime rule-state mismatch.
///
/// This is an internal contradiction surfaced as a structured runtime error
/// instead of being folded into successful stability.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuleRuntimeStateError {
    /// Parsed rule whose runtime state was missing.
    rule: RulePosition,
}

impl RuleRuntimeStateError {
    /// Builds the missing once-rule state error.
    pub(crate) const fn missing_once_rule_state(rule: RulePosition) -> Self {
        Self { rule }
    }

    /// Parsed rule whose `(once)` runtime state was missing.
    #[must_use]
    pub const fn rule(&self) -> RulePosition {
        self.rule
    }
}

impl Error for RuleRuntimeStateError {}

/// Rule-attempt cursor mismatch.
///
/// This is an internal contradiction surfaced as a structured rule-attempt
/// error instead of being folded into `NoExecutableRules`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuleAttemptCursorError {
    /// Rule position the active cursor attempted to select.
    rule: RulePosition,
}

impl RuleAttemptCursorError {
    /// Builds the missing rule error.
    pub(crate) const fn missing_rule(rule: RulePosition) -> Self {
        Self { rule }
    }

    /// Rule position that was missing from the parsed program.
    #[must_use]
    pub const fn rule(&self) -> RulePosition {
        self.rule
    }
}

impl Error for RuleAttemptCursorError {}

/// One-based runtime input column.
///
/// Columns count raw input bytes starting at one. They are reported only by the
/// runtime-input boundary, not by source parsing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct InputColumn {
    /// One-based runtime-input byte column.
    one_based: usize,
}

impl InputColumn {
    /// Builds an index from a zero-based offset.
    pub(crate) fn from_zero_based(zero_based: usize) -> Option<Self> {
        let one_based = zero_based.checked_add(1)?;
        Some(Self { one_based })
    }

    /// One-based input column as a primitive value.
    #[must_use]
    pub const fn get(self) -> usize {
        self.one_based
    }
}

/// Rewrite size failure caused by arithmetic overflow.
///
/// This is distinct from a configured byte limit. It means the interpreter
/// could not represent the length of the state that a rewrite would produce.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RewriteSizeError {
    /// Runtime state length before the rewrite.
    state: RuntimeStateByteCount,
    /// Matched left-side payload length being removed.
    lhs: PayloadByteCount,
    /// Right-side payload length being inserted.
    rhs: PayloadByteCount,
}

impl RewriteSizeError {
    /// Records the lengths that overflowed rewrite-size arithmetic.
    pub(crate) const fn new(
        state_len: RuntimeStateByteCount,
        lhs_len: PayloadByteCount,
        rhs_len: PayloadByteCount,
    ) -> Self {
        Self {
            state: state_len,
            lhs: lhs_len,
            rhs: rhs_len,
        }
    }

    /// Runtime state length before the failing rewrite.
    #[must_use]
    pub const fn state_len(&self) -> RuntimeStateByteCount {
        self.state
    }

    /// Matched left-side length that would be removed.
    #[must_use]
    pub const fn lhs_len(&self) -> PayloadByteCount {
        self.lhs
    }

    /// Right-side payload length that would be inserted.
    #[must_use]
    pub const fn rhs_len(&self) -> PayloadByteCount {
        self.rhs
    }
}

impl Error for RewriteSizeError {}

/// Runtime state byte-limit failure.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuntimeStateLimitError {
    /// Configured maximum runtime state length.
    limit: RuntimeStateByteLimit,
    /// State length that would have been accepted without this guard.
    attempted_len: RuntimeStateByteCount,
}

impl RuntimeStateLimitError {
    /// Builds a runtime state limit error.
    pub(crate) const fn new(
        limit: RuntimeStateByteLimit,
        attempted_len: RuntimeStateByteCount,
    ) -> Self {
        Self {
            limit,
            attempted_len,
        }
    }

    /// Configured maximum runtime state length.
    #[must_use]
    pub const fn limit(&self) -> RuntimeStateByteLimit {
        self.limit
    }

    /// State length rejected by the limit.
    #[must_use]
    pub const fn attempted_len(&self) -> RuntimeStateByteCount {
        self.attempted_len
    }
}

impl Error for RuntimeStateLimitError {}

/// Return-output byte-limit failure.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReturnOutputLimitError {
    /// Configured maximum `(return)` output length.
    limit: ReturnByteLimit,
    /// Return payload length that would have been allocated.
    attempted_len: ReturnOutputByteCount,
}

impl ReturnOutputLimitError {
    /// Builds a return-output limit error.
    pub(crate) const fn new(limit: ReturnByteLimit, attempted_len: ReturnOutputByteCount) -> Self {
        Self {
            limit,
            attempted_len,
        }
    }

    /// Configured maximum return-output length.
    #[must_use]
    pub const fn limit(&self) -> ReturnByteLimit {
        self.limit
    }

    /// Return-output length rejected by the limit.
    #[must_use]
    pub const fn attempted_len(&self) -> ReturnOutputByteCount {
        self.attempted_len
    }
}

impl Error for ReturnOutputLimitError {}

/// Step-limit failure.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StepLimitError {
    /// Configured maximum step count.
    max_steps: StepLimit,
    /// Number of completed execution steps when the next match was found.
    completed_steps: StepCount,
    /// Runtime state length when the limit was hit.
    state_len: RuntimeStateByteCount,
}

impl StepLimitError {
    /// Builds a step-limit error.
    pub(crate) const fn new(
        max_steps: StepLimit,
        completed_steps: StepCount,
        state_len: RuntimeStateByteCount,
    ) -> Self {
        Self {
            max_steps,
            completed_steps,
            state_len,
        }
    }

    /// Configured maximum step count.
    #[must_use]
    pub const fn max_steps(&self) -> StepLimit {
        self.max_steps
    }

    /// Number of committed steps before rejection.
    #[must_use]
    pub const fn completed_steps(&self) -> StepCount {
        self.completed_steps
    }

    /// Runtime state length at rejection.
    #[must_use]
    pub const fn state_len(&self) -> RuntimeStateByteCount {
        self.state_len
    }
}

impl Error for StepLimitError {}

/// Rule-attempt-limit failure.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuleAttemptLimitError {
    /// Configured maximum executable rule-line attempts.
    max_attempts: RuleAttemptLimit,
    /// Number of completed rule attempts when the next rule line was reached.
    completed_attempts: RuleAttemptCount,
    /// Runtime state length when the limit was hit.
    state_len: RuntimeStateByteCount,
}

impl RuleAttemptLimitError {
    /// Builds a rule-attempt-limit error.
    pub(crate) const fn new(
        max_attempts: RuleAttemptLimit,
        completed_attempts: RuleAttemptCount,
        state_len: RuntimeStateByteCount,
    ) -> Self {
        Self {
            max_attempts,
            completed_attempts,
            state_len,
        }
    }

    /// Configured maximum executable rule-line attempts.
    #[must_use]
    pub const fn max_attempts(&self) -> RuleAttemptLimit {
        self.max_attempts
    }

    /// Number of committed rule attempts before rejection.
    #[must_use]
    pub const fn completed_attempts(&self) -> RuleAttemptCount {
        self.completed_attempts
    }

    /// Runtime state length at rejection.
    #[must_use]
    pub const fn state_len(&self) -> RuntimeStateByteCount {
        self.state_len
    }
}

impl Error for RuleAttemptLimitError {}

#[cfg(test)]
mod tests {
    use super::InputColumn;
    use crate::test_support::{TestResult, ensure_eq};

    /// # Errors
    ///
    /// Returns `TestFailure` if input-column conversion accepts an
    /// unrepresentable index or rejects zero.
    #[test]
    fn input_column_rejects_unrepresentable_zero_based_index() -> TestResult {
        ensure_eq!(InputColumn::from_zero_based(usize::MAX), None)?;
        ensure_eq!(
            InputColumn::from_zero_based(0).map(InputColumn::get),
            Some(1),
        )?;
        Ok(())
    }
}