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
use alloc::vec::Vec;
use core::slice;

use crate::allocation::{AllocationContext, RequestedCapacity, try_push, try_reserve_total_exact};
use crate::error::{
    ParseError, ParseErrorKind, ParseLimitError, ParseRepresentationError, RuleAttemptCursorError,
};
use crate::inspect::{OnceRuleCount as PublicOnceRuleCount, RuleCount, RulePosition};
use crate::limits::RuleLimit;
use crate::rule::{OnceRuleSlot, ParsedRule, Rule, RuleAvailability, RuleRepeatSyntax};

/// Immutable executable rule table built by the parser.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct RuleSet {
    /// Parsed rules in execution order.
    rules: Vec<Rule>,
    /// Parsed `(once)` slot count assigned while building this rule table.
    once_rule_count: PublicOnceRuleCount,
}

/// Borrowed executable rule scan minted from one parsed rule table.
#[derive(Debug, Clone, Copy)]
pub(crate) struct RuleScan<'program> {
    /// Parsed executable rules in execution order.
    rules: &'program [Rule],
}

/// Parser-owned rule table builder.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct RuleSetBuilder {
    /// Parsed rules in execution order.
    rules: Vec<Rule>,
    /// Next `(once)` slot to assign.
    once_rule_count: PublicOnceRuleCount,
}

/// Parsed rule after repeat-state assignment but before table insertion.
struct PendingRuleInsertion {
    /// Rule ready for storage in execution order.
    rule: Rule,
}

/// Checked permission to insert one parsed rule into the table.
struct RuleInsertionPermit {
    /// Rule count after the permitted insertion.
    attempted_rule_count: RuleCount,
    /// Execution-order position assigned to the accepted rule.
    position: RulePosition,
}

/// Zero-based executable rule index minted from a concrete rule set.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct RuleIndex {
    /// Zero-based rule-table offset.
    zero_based: usize,
    /// Public one-based rule position for diagnostics.
    position: RulePosition,
}

/// Cursor pointing to the next executable rule line in one rule-attempt run.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RuleCursor {
    /// Cursor points at the next executable rule index.
    Active(ActiveRuleCursor),
    /// No executable rule remains in this pass.
    Exhausted,
}

/// Active cursor state for rule-attempt execution.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ActiveRuleCursor {
    /// Zero-based rule index to evaluate next.
    next_rule_index: RuleIndex,
    /// Final executable rule index in this program.
    final_rule_index: RuleIndex,
}

/// Cursor movement after a non-applying rule line has been consumed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RuleCursorAfterMiss {
    /// Cursor advanced to the next executable rule.
    Advanced(ActiveRuleCursor),
    /// The consumed miss was the final executable rule.
    Stable,
}

/// Selection produced when a rule-attempt cursor is consumed for one step.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RuleCursorSelection {
    /// Cursor selected one executable rule line.
    Active(ActiveRuleCursor),
    /// The parsed program has no executable rule line for this attempt mode.
    NoExecutableRules,
}

/// Checked rule-attempt selection produced by a cursor and its owning rule table.
pub(crate) enum RuleAttemptTargetSelection<'program> {
    /// The cursor selected an executable target from this rule table.
    Target(RuleAttemptTarget<'program>),
    /// The cursor had no executable target left to select.
    NoExecutableRules,
}

/// Active rule-attempt cursor paired with the checked target it selected.
pub(crate) struct RuleAttemptTarget<'program> {
    /// Cursor state that selected this target.
    active_cursor: ActiveRuleCursor,
    /// Parsed rule selected by the cursor from the same rule table.
    target: RuleTarget<'program>,
}

/// Rule target selected by a rule-attempt cursor.
#[derive(Debug, Clone, Copy)]
pub(crate) struct RuleTarget<'program> {
    /// Parsed rule selected by the cursor.
    rule: &'program Rule,
}

impl RuleInsertionPermit {
    /// Checks rule-count budget and table-position representability together.
    ///
    /// # Errors
    ///
    /// Returns `ParseError` if the next rule count overflows, exceeds the
    /// parser rule budget, or cannot be represented as a checked rule position.
    fn new(
        current_len: usize,
        limit: RuleLimit,
        line_number: crate::source::SourceLineNumber,
    ) -> Result<Self, ParseError> {
        let attempted_rule_count = current_len.checked_add(1).ok_or_else(|| {
            ParseError::at_line(
                line_number,
                ParseErrorKind::Representation(ParseRepresentationError::RuleCount),
            )
        })?;
        let attempted_rule_count = RuleCount::new(attempted_rule_count);

        if !limit.accepts(attempted_rule_count) {
            return Err(ParseError::at_line(
                line_number,
                ParseErrorKind::Limit(ParseLimitError::rules(limit, attempted_rule_count)),
            ));
        }

        let position = RulePosition::from_zero_based(current_len).ok_or_else(|| {
            ParseError::at_line(
                line_number,
                ParseErrorKind::Representation(ParseRepresentationError::RulePosition),
            )
        })?;

        Ok(Self {
            attempted_rule_count,
            position,
        })
    }

    /// Rule-table capacity required before insertion.
    const fn requested_capacity(&self) -> RequestedCapacity {
        RequestedCapacity::from_rule_count(self.attempted_rule_count)
    }

    /// Execution-order position assigned to this insertion.
    const fn position(&self) -> RulePosition {
        self.position
    }
}

impl PendingRuleInsertion {
    /// Assigns runtime availability to one parsed rule before storage.
    fn from_parsed(
        position: RulePosition,
        parsed: ParsedRule,
        availability: RuleAvailability,
    ) -> Self {
        Self {
            rule: Rule::from_parsed(position, parsed, availability),
        }
    }

    /// Source line used if storing this rule fails.
    const fn line_number(&self) -> crate::source::SourceLineNumber {
        self.rule.line_number()
    }
}

impl RuleSetBuilder {
    /// Starts an empty parsed rule table.
    pub(crate) fn new() -> Self {
        Self {
            rules: Vec::new(),
            once_rule_count: PublicOnceRuleCount::ZERO,
        }
    }

    /// Stores one parsed rule and assigns its program-local position.
    ///
    /// # Errors
    ///
    /// Returns `AllocationError` if the rule position cannot be represented or
    /// the rule table cannot grow.
    pub(crate) fn push_parsed_rule(
        &mut self,
        parsed: ParsedRule,
        limit: RuleLimit,
    ) -> Result<(), ParseError> {
        let line_number = parsed.line_number();
        let insertion = RuleInsertionPermit::new(self.rules.len(), limit, line_number)?;
        let (availability, next_once_rule_count) =
            self.assign_rule_availability(&parsed, line_number)?;

        let pending = PendingRuleInsertion::from_parsed(insertion.position(), parsed, availability);

        let pending_line_number = pending.line_number();
        try_reserve_total_exact(
            &mut self.rules,
            insertion.requested_capacity(),
            AllocationContext::ProgramRuleTable,
        )
        .map_err(|error| {
            ParseError::at_line(pending_line_number, ParseErrorKind::Allocation(error))
        })?;
        try_push(
            &mut self.rules,
            pending.rule,
            AllocationContext::ProgramRuleTable,
        )
        .map_err(|error| {
            ParseError::at_line(pending_line_number, ParseErrorKind::Allocation(error))
        })?;
        self.once_rule_count = next_once_rule_count;
        Ok(())
    }

    /// Finalizes parsed rules into an immutable executable table.
    pub(crate) fn finish(self) -> RuleSet {
        RuleSet {
            rules: self.rules,
            once_rule_count: self.once_rule_count,
        }
    }

    /// Assigns parsed repeat syntax to runtime availability.
    ///
    /// # Errors
    ///
    /// Returns `ParseError` if the next parsed `(once)` count cannot be
    /// represented.
    fn assign_rule_availability(
        &self,
        parsed: &ParsedRule,
        line_number: crate::source::SourceLineNumber,
    ) -> Result<(RuleAvailability, PublicOnceRuleCount), ParseError> {
        match parsed.repeat_syntax() {
            RuleRepeatSyntax::Always => Ok((RuleAvailability::Always, self.once_rule_count)),
            RuleRepeatSyntax::Once => {
                let slot = OnceRuleSlot::from_count(self.once_rule_count);
                let next_once_rule_count =
                    self.once_rule_count.checked_next().ok_or_else(|| {
                        ParseError::at_line(
                            line_number,
                            ParseErrorKind::Representation(ParseRepresentationError::RuleCount),
                        )
                    })?;
                Ok((RuleAvailability::Once(slot), next_once_rule_count))
            }
        }
    }
}

impl RuleSet {
    /// Total executable rules in this table.
    pub(crate) fn rule_count(&self) -> RuleCount {
        RuleCount::new(self.rules.len())
    }

    /// Public count of parsed `(once)` rules.
    pub(crate) fn once_rule_count(&self) -> PublicOnceRuleCount {
        self.once_rule_count
    }

    /// Borrows rules in execution order.
    pub(crate) fn as_slice(&self) -> &[Rule] {
        &self.rules
    }

    /// Starts a runtime scan over this table's executable rules.
    pub(crate) fn scan(&self) -> RuleScan<'_> {
        RuleScan { rules: &self.rules }
    }

    /// Starts rule-attempt execution over this table's executable rules.
    pub(crate) fn rule_attempt_cursor(&self) -> RuleCursor {
        let Some(final_rule_index) = RuleIndex::last_for(self.rule_count()) else {
            return RuleCursor::Exhausted;
        };

        RuleCursor::Active(ActiveRuleCursor {
            next_rule_index: RuleIndex::first(),
            final_rule_index,
        })
    }

    /// Selects the parsed rule pointed at by an active rule-attempt cursor.
    ///
    /// # Errors
    ///
    /// Returns `RuleAttemptCursorError` if the cursor points outside this parsed
    /// rule table.
    fn target_for_cursor(
        &self,
        active_cursor: ActiveRuleCursor,
    ) -> Result<RuleTarget<'_>, RuleAttemptCursorError> {
        let rule = self
            .rules
            .get(active_cursor.current_index().get())
            .ok_or_else(|| {
                RuleAttemptCursorError::missing_rule(active_cursor.current_position())
            })?;
        Ok(RuleTarget { rule })
    }

    /// Selects the next rule-attempt target from a cursor minted by this table.
    ///
    /// # Errors
    ///
    /// Returns `RuleAttemptCursorError` if the active cursor no longer points
    /// at a rule in this table.
    pub(crate) fn select_attempt_target(
        &self,
        cursor: &mut RuleCursor,
    ) -> Result<RuleAttemptTargetSelection<'_>, RuleAttemptCursorError> {
        let active_cursor = match cursor.select_next() {
            RuleCursorSelection::Active(active_cursor) => active_cursor,
            RuleCursorSelection::NoExecutableRules => {
                return Ok(RuleAttemptTargetSelection::NoExecutableRules);
            }
        };

        Ok(RuleAttemptTargetSelection::Target(RuleAttemptTarget {
            active_cursor,
            target: self.target_for_cursor(active_cursor)?,
        }))
    }
}

impl RuleCursor {
    /// Takes the cursor state, leaving this cursor exhausted until the attempt commits.
    fn select_next(&mut self) -> RuleCursorSelection {
        match core::mem::replace(self, Self::Exhausted) {
            Self::Active(active) => RuleCursorSelection::Active(active),
            Self::Exhausted => RuleCursorSelection::NoExecutableRules,
        }
    }
}

impl<'program> RuleScan<'program> {
    /// Iterates executable rules in parser-owned execution order.
    pub(crate) fn iter(self) -> slice::Iter<'program, Rule> {
        self.rules.iter()
    }
}

impl ActiveRuleCursor {
    /// Current zero-based rule index.
    pub(crate) const fn current_index(self) -> RuleIndex {
        self.next_rule_index
    }

    /// Current public rule position.
    pub(crate) const fn current_position(self) -> RulePosition {
        self.next_rule_index.position()
    }

    /// Advances after a miss or reports that the pass is stable.
    pub(crate) fn advance_after_miss(self) -> RuleCursorAfterMiss {
        if self.next_rule_index >= self.final_rule_index {
            return RuleCursorAfterMiss::Stable;
        }

        if let Some(next_rule_index) = self.next_rule_index.checked_next() {
            RuleCursorAfterMiss::Advanced(Self {
                next_rule_index,
                final_rule_index: self.final_rule_index,
            })
        } else {
            RuleCursorAfterMiss::Stable
        }
    }

    /// Resets to the first executable rule after a committed match.
    pub(crate) const fn reset_to_first(self) -> Self {
        Self {
            next_rule_index: RuleIndex::first(),
            final_rule_index: self.final_rule_index,
        }
    }
}

impl RuleIndex {
    /// First executable rule index.
    const fn first() -> Self {
        Self {
            zero_based: 0,
            position: RulePosition::FIRST,
        }
    }

    /// Builds an index from a zero-based rule-table offset.
    fn from_zero_based(zero_based: usize) -> Option<Self> {
        let position = RulePosition::from_zero_based(zero_based)?;
        Some(Self {
            zero_based,
            position,
        })
    }

    /// Final executable rule index for a parsed rule count.
    fn last_for(rule_count: RuleCount) -> Option<Self> {
        let zero_based = rule_count.get().checked_sub(1)?;
        Self::from_zero_based(zero_based)
    }

    /// Returns the checked next index.
    fn checked_next(self) -> Option<Self> {
        let zero_based = self.zero_based.checked_add(1)?;
        Self::from_zero_based(zero_based)
    }

    /// Zero-based rule-table offset.
    pub(crate) const fn get(self) -> usize {
        self.zero_based
    }

    /// Public one-based rule position.
    const fn position(self) -> RulePosition {
        self.position
    }
}

impl<'program> RuleTarget<'program> {
    /// Parsed rule selected by the cursor.
    pub(crate) const fn rule(self) -> &'program Rule {
        self.rule
    }
}

impl<'program> RuleAttemptTarget<'program> {
    /// Splits the checked target into cursor progress and selected rule.
    pub(crate) const fn into_parts(self) -> (ActiveRuleCursor, RuleTarget<'program>) {
        (self.active_cursor, self.target)
    }
}

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

    /// # Errors
    ///
    /// Returns `TestFailure` if an active cursor pointing outside the rule table
    /// is folded into an executable-rule absence instead of a cursor error.
    #[test]
    fn missing_cursor_rule_is_rule_attempt_step_error() -> TestResult {
        let rule_set = RuleSet {
            rules: Vec::new(),
            once_rule_count: PublicOnceRuleCount::ZERO,
        };
        let cursor = ActiveRuleCursor {
            next_rule_index: RuleIndex::first(),
            final_rule_index: RuleIndex::first(),
        };

        let Err(RuleAttemptStepError::RuleCursor(error)) = rule_set
            .target_for_cursor(cursor)
            .map_err(RuleAttemptStepError::from)
        else {
            return Err(TestFailure::message("expected missing cursor rule error"));
        };

        ensure_eq!(error.rule(), RulePosition::FIRST)
    }
}