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

use crate::bytes::{
    PayloadByteCount, ReturnOutputByteCount, RuntimeInputByteCount, RuntimeStateByteCount,
    TraceSnapshotByteCount,
};
use crate::inspect::RuleCount;

/// Documents the internal default byte budget item.
const DEFAULT_BYTE_BUDGET: usize = 16_777_216;

/// Default program-source byte budget for callers that want the crate policy value.
pub const DEFAULT_MAX_SOURCE_LEN: SourceByteLimit = SourceByteLimit::new(DEFAULT_BYTE_BUDGET);
/// Default executable code-line byte budget for callers that want the crate policy value.
pub const DEFAULT_MAX_CODE_LINE_LEN: CodeLineByteLimit =
    CodeLineByteLimit::new(DEFAULT_BYTE_BUDGET);
/// Default executable payload byte budget for callers that want the crate policy value.
pub const DEFAULT_MAX_PAYLOAD_LEN: PayloadByteLimit = PayloadByteLimit::new(DEFAULT_BYTE_BUDGET);
/// Default parsed-rule budget for callers that want the crate policy value.
pub const DEFAULT_MAX_RULES: RuleLimit = RuleLimit::new(1_000_000);
/// Default execution-step budget for callers that want the crate policy value.
pub const DEFAULT_MAX_STEPS: StepLimit = StepLimit::new(1_000_000);
/// Default rule-attempt budget for callers that want the crate policy value.
pub const DEFAULT_MAX_RULE_ATTEMPTS: RuleAttemptLimit = RuleAttemptLimit::new(1_000_000);
/// Default runtime-state byte budget for callers that want the crate policy value.
pub const DEFAULT_MAX_STATE_LEN: RuntimeStateByteLimit =
    RuntimeStateByteLimit::new(DEFAULT_BYTE_BUDGET);
/// Default runtime-input byte budget for callers that want the crate policy value.
pub const DEFAULT_MAX_INPUT_LEN: RuntimeInputByteLimit =
    RuntimeInputByteLimit::new(DEFAULT_BYTE_BUDGET);
/// Default `(return)` output byte budget for callers that want the crate policy value.
pub const DEFAULT_MAX_RETURN_LEN: ReturnByteLimit = ReturnByteLimit::new(DEFAULT_BYTE_BUDGET);
/// Default trace snapshot byte budget for callers that want the crate default.
pub const DEFAULT_MAX_TRACE_SNAPSHOT_LEN: TraceSnapshotByteLimit =
    TraceSnapshotByteLimit::new(DEFAULT_BYTE_BUDGET);
/// Default parser budgets for callers that want the crate policy value.
pub const DEFAULT_PARSE_LIMITS: ParseLimits = ParseLimits::new(
    DEFAULT_MAX_SOURCE_LEN,
    DEFAULT_MAX_CODE_LINE_LEN,
    DEFAULT_MAX_PAYLOAD_LEN,
    DEFAULT_MAX_RULES,
);

/// Source byte length measured before parsing starts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SourceByteCount {
    /// Source byte length before parsing.
    value: usize,
}

impl SourceByteCount {
    /// Creates a source byte count from a primitive length.
    #[must_use]
    pub(crate) const fn new(value: usize) -> Self {
        Self { value }
    }

    /// Returns this count as a primitive length.
    #[must_use]
    pub const fn get(self) -> usize {
        self.value
    }
}

impl fmt::Display for SourceByteCount {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.value.fmt(f)
    }
}

/// Executable code-line byte length after comment removal and before whitespace compaction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CodeLineByteCount {
    /// Executable code-line length before whitespace compaction.
    value: usize,
}

impl CodeLineByteCount {
    /// Creates a code-line byte count from a primitive length.
    #[must_use]
    pub(crate) const fn new(value: usize) -> Self {
        Self { value }
    }

    /// Returns this count as a primitive length.
    #[must_use]
    pub const fn get(self) -> usize {
        self.value
    }
}

impl fmt::Display for CodeLineByteCount {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.value.fmt(f)
    }
}

/// Maximum source length accepted by [`program::Program::parse`](crate::program::Program::parse).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SourceByteLimit {
    /// Maximum accepted source byte length.
    value: usize,
}

impl SourceByteLimit {
    /// Creates a source byte limit from a primitive length.
    #[must_use]
    pub const fn new(value: usize) -> Self {
        Self { value }
    }

    /// Returns this limit as a primitive length.
    #[must_use]
    pub const fn get(self) -> usize {
        self.value
    }

    /// Checks whether a measured source length exceeds this parser budget.
    pub(crate) const fn accepts(self, attempted_len: SourceByteCount) -> bool {
        attempted_len.get() <= self.value
    }
}

/// Maximum executable code-line length accepted by [`program::Program::parse`](crate::program::Program::parse).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CodeLineByteLimit {
    /// Maximum accepted executable code-line byte length.
    value: usize,
}

impl CodeLineByteLimit {
    /// Creates a code-line byte limit from a primitive length.
    #[must_use]
    pub const fn new(value: usize) -> Self {
        Self { value }
    }

    /// Returns this limit as a primitive length.
    #[must_use]
    pub const fn get(self) -> usize {
        self.value
    }

    /// Checks whether a measured executable line length exceeds this parser budget.
    pub(crate) const fn accepts(self, attempted_len: CodeLineByteCount) -> bool {
        attempted_len.get() <= self.value
    }
}

/// Maximum parsed payload length accepted by [`program::Program::parse`](crate::program::Program::parse).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PayloadByteLimit {
    /// Maximum accepted executable payload byte length.
    value: usize,
}

impl PayloadByteLimit {
    /// Creates a payload byte limit from a primitive length.
    #[must_use]
    pub const fn new(value: usize) -> Self {
        Self { value }
    }

    /// Returns this limit as a primitive length.
    #[must_use]
    pub const fn get(self) -> usize {
        self.value
    }

    /// Checks whether a measured payload length exceeds this parser budget.
    pub(crate) const fn accepts(self, attempted_len: PayloadByteCount) -> bool {
        attempted_len.get() <= self.value
    }
}

/// Maximum executable rule count accepted by [`program::Program::parse`](crate::program::Program::parse).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RuleLimit {
    /// Maximum accepted executable rule count.
    value: usize,
}

impl RuleLimit {
    /// Creates a parsed-rule limit from a primitive count.
    #[must_use]
    pub const fn new(value: usize) -> Self {
        Self { value }
    }

    /// Returns this limit as a primitive count.
    #[must_use]
    pub const fn get(self) -> usize {
        self.value
    }

    /// Checks whether a parsed-rule count remains inside this parser budget.
    pub(crate) const fn accepts(self, attempted_count: RuleCount) -> bool {
        attempted_count.get() <= self.value
    }
}

/// Resource limits for one parser invocation.
///
/// Parser limits are host policy. They are checked before parser-owned
/// allocations grow beyond the declared source, line, payload, or rule budgets.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParseLimits {
    /// Source byte budget.
    source_len: SourceByteLimit,
    /// Per-line executable byte budget.
    code_line_len: CodeLineByteLimit,
    /// Per-payload executable byte budget.
    payload_len: PayloadByteLimit,
    /// Parsed rule-count budget.
    rules: RuleLimit,
}

impl ParseLimits {
    /// Creates parser limits with every budget specified explicitly.
    #[must_use]
    pub const fn new(
        max_source_len: SourceByteLimit,
        max_code_line_len: CodeLineByteLimit,
        max_payload_len: PayloadByteLimit,
        max_rules: RuleLimit,
    ) -> Self {
        Self {
            source_len: max_source_len,
            code_line_len: max_code_line_len,
            payload_len: max_payload_len,
            rules: max_rules,
        }
    }

    /// Maximum source bytes accepted before line parsing starts.
    #[must_use]
    pub const fn source_byte_limit(self) -> SourceByteLimit {
        self.source_len
    }

    /// Maximum bytes accepted in one executable code line before whitespace compaction.
    #[must_use]
    pub const fn code_line_byte_limit(self) -> CodeLineByteLimit {
        self.code_line_len
    }

    /// Maximum bytes accepted in one executable payload.
    #[must_use]
    pub const fn payload_byte_limit(self) -> PayloadByteLimit {
        self.payload_len
    }

    /// Maximum executable rules accepted in one parsed program.
    #[must_use]
    pub const fn rule_limit(self) -> RuleLimit {
        self.rules
    }
}

/// Maximum number of committed execution steps allowed before the next matching rule fails.
///
/// A limit of `0` allows parsing and input materialization, but the first
/// matching rule fails with a step-limit error instead of committing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct StepLimit {
    /// Maximum number of committed execution steps.
    value: usize,
}

impl StepLimit {
    /// Creates a step limit from a primitive count.
    #[must_use]
    pub const fn new(value: usize) -> Self {
        Self { value }
    }

    /// Returns this limit as a primitive count.
    #[must_use]
    pub const fn get(self) -> usize {
        self.value
    }

    /// Checks whether another step may be reserved after the completed count.
    pub(crate) const fn allows_next_after(self, completed_steps: StepCount) -> bool {
        completed_steps.get() < self.value
    }
}

/// Maximum number of executable rule-line attempts allowed in rule-attempt execution.
///
/// This is separate from [`StepLimit`]. A rule attempt observes one executable
/// rule line, whether or not that rule matches the current runtime state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RuleAttemptLimit {
    /// Maximum number of consumed rule attempts.
    value: usize,
}

impl RuleAttemptLimit {
    /// Creates a rule-attempt limit from a primitive count.
    #[must_use]
    pub const fn new(value: usize) -> Self {
        Self { value }
    }

    /// Returns this limit as a primitive count.
    #[must_use]
    pub const fn get(self) -> usize {
        self.value
    }

    /// Checks whether another rule attempt may be reserved after the completed count.
    pub(crate) const fn allows_next_after(self, completed_attempts: RuleAttemptCount) -> bool {
        completed_attempts.get() < self.value
    }
}

/// Maximum runtime state length in bytes.
///
/// This applies both to the materialized initial input state and to every state
/// that would be produced by a rewrite.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RuntimeStateByteLimit {
    /// Maximum runtime-state byte length.
    value: usize,
}

impl RuntimeStateByteLimit {
    /// Creates a runtime-state byte limit from a primitive length.
    #[must_use]
    pub const fn new(value: usize) -> Self {
        Self { value }
    }

    /// Returns this limit as a primitive length.
    #[must_use]
    pub const fn get(self) -> usize {
        self.value
    }

    /// Checks whether a runtime-state length remains inside this execution budget.
    pub(crate) const fn accepts(self, attempted_len: RuntimeStateByteCount) -> bool {
        attempted_len.get() <= self.value
    }
}

/// Maximum runtime input length accepted before owned byte classification.
///
/// This limit is part of [`RuntimeInputLimits`] and is enforced by
/// [`input::RuntimeInput::validate`](crate::input::RuntimeInput::validate)
/// before owned input allocation starts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RuntimeInputByteLimit {
    /// Maximum raw runtime-input byte length.
    value: usize,
}

impl RuntimeInputByteLimit {
    /// Creates a runtime-input byte limit from a primitive length.
    #[must_use]
    pub const fn new(value: usize) -> Self {
        Self { value }
    }

    /// Returns this limit as a primitive length.
    #[must_use]
    pub const fn get(self) -> usize {
        self.value
    }

    /// Checks whether a runtime-input length remains inside this input budget.
    pub(crate) const fn accepts(self, attempted_len: RuntimeInputByteCount) -> bool {
        attempted_len.get() <= self.value
    }
}

/// Maximum `(return)` output length in bytes.
///
/// This applies only to output produced by a matched `(return)` rule. Stable
/// final states are governed by [`RuntimeStateByteLimit`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ReturnByteLimit {
    /// Maximum materialized `(return)` output byte length.
    value: usize,
}

impl ReturnByteLimit {
    /// Creates a `(return)` output byte limit from a primitive length.
    #[must_use]
    pub const fn new(value: usize) -> Self {
        Self { value }
    }

    /// Returns this limit as a primitive length.
    #[must_use]
    pub const fn get(self) -> usize {
        self.value
    }

    /// Checks whether a return-output length remains inside this execution budget.
    pub(crate) const fn accepts(self, attempted_len: ReturnOutputByteCount) -> bool {
        attempted_len.get() <= self.value
    }
}

/// Maximum state/output bytes materialized for one trace snapshot event.
///
/// This limit is checked per event when converting borrowed trace events into
/// snapshot events.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TraceSnapshotByteLimit {
    /// Maximum materialized bytes in one trace snapshot event.
    value: usize,
}

impl TraceSnapshotByteLimit {
    /// Creates a trace snapshot byte limit from a primitive length.
    #[must_use]
    pub const fn new(value: usize) -> Self {
        Self { value }
    }

    /// Returns this limit as a primitive length.
    #[must_use]
    pub const fn get(self) -> usize {
        self.value
    }

    /// Checks whether one materialized trace event remains inside this snapshot budget.
    pub(crate) const fn accepts(self, attempted_len: TraceSnapshotByteCount) -> bool {
        attempted_len.get() <= self.value
    }
}

/// Number of committed execution steps.
///
/// Counts report committed rule applications only. A non-terminal rewrite and a
/// terminal `(return)` both increment this value; failed step attempts and
/// non-applying rule attempts do not.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct StepCount {
    /// Committed execution steps.
    value: usize,
}

impl StepCount {
    /// ZERO boundary value.
    pub(crate) const ZERO: Self = Self { value: 0 };

    /// Returns this completed-step count as a primitive count.
    #[must_use]
    pub const fn get(self) -> usize {
        self.value
    }

    /// Returns the checked next result.
    pub(crate) fn checked_next(self) -> Option<Self> {
        let value = self.value.checked_add(1)?;
        Some(Self { value })
    }
}

/// Number of executable rule-line attempts consumed by a rule-attempt run.
///
/// Counts report inspected executable rule lines. A miss increments this count,
/// and a matched rule increments it independently from committed execution steps.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RuleAttemptCount {
    /// Consumed rule attempts.
    value: usize,
}

impl RuleAttemptCount {
    /// ZERO boundary value.
    pub(crate) const ZERO: Self = Self { value: 0 };

    /// Returns this rule-attempt count as a primitive count.
    #[must_use]
    pub const fn get(self) -> usize {
        self.value
    }

    /// Returns the checked next result.
    pub(crate) fn checked_next(self) -> Option<Self> {
        let value = self.value.checked_add(1)?;
        Some(Self { value })
    }
}

/// Resource limits for runtime input validation.
///
/// Input limits are host policy for raw runtime input only. They do not carry
/// execution budgets, so validated input cannot accidentally decide how a run is
/// executed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RuntimeInputLimits {
    /// Raw input byte budget checked before owned classification.
    input_len: RuntimeInputByteLimit,
}

impl RuntimeInputLimits {
    /// Creates runtime input limits with every input budget specified explicitly.
    #[must_use]
    pub const fn new(max_input_len: RuntimeInputByteLimit) -> Self {
        Self {
            input_len: max_input_len,
        }
    }

    /// Maximum runtime input bytes accepted before owned classification.
    #[must_use]
    pub const fn input_byte_limit(self) -> RuntimeInputByteLimit {
        self.input_len
    }
}

/// Resource limits for one execution invocation.
///
/// The interpreter checks these limits before allocating oversized runtime
/// states or return outputs. Step limits alone are not enough for a rewriting
/// system because a tiny number of steps can still expand into a very large
/// state. Initial state admission is checked by
/// [`input::RunSeed::admit`](crate::input::RunSeed::admit); later rewrite and
/// return checks use the same policy after execution starts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExecutionLimits {
    /// Budget for committed execution steps.
    steps: StepLimit,
    /// Budget for initial and rewritten runtime states.
    state_len: RuntimeStateByteLimit,
    /// Budget for materialized `(return)` output.
    return_len: ReturnByteLimit,
}

impl ExecutionLimits {
    /// Creates execution limits with every runtime execution budget specified explicitly.
    #[must_use]
    pub const fn new(
        max_steps: StepLimit,
        max_state_len: RuntimeStateByteLimit,
        max_return_len: ReturnByteLimit,
    ) -> Self {
        Self {
            steps: max_steps,
            state_len: max_state_len,
            return_len: max_return_len,
        }
    }

    /// Maximum number of execution steps that may be committed.
    #[must_use]
    pub const fn step_limit(self) -> StepLimit {
        self.steps
    }

    /// Maximum runtime state length, including initial input and rewrite results.
    #[must_use]
    pub const fn state_byte_limit(self) -> RuntimeStateByteLimit {
        self.state_len
    }

    /// Maximum byte length accepted for `(return)` output.
    #[must_use]
    pub const fn return_byte_limit(self) -> ReturnByteLimit {
        self.return_len
    }
}