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

use crate::allocation::{AllocationContext, try_push};
use crate::bytes::{CompactByte, Payload, PayloadSyntax};
use crate::error::{LeftModifierKind, ParseError, ParseErrorKind, PayloadKind, RightActionKind};
use crate::limits::PayloadByteLimit;
use crate::rule::{
    ParsedRule, ParsedRuleAction, RewriteAction, RuleAnchorSyntax, RuleBody, RuleHead,
    RuleRepeatSyntax,
};
use crate::source::{SourceColumn, SourceLineNumber, SourcePosition};
use crate::syntax::SyntaxToken;

/// Compact executable line split into left and right rule syntax.
#[derive(Debug, PartialEq, Eq)]
pub(super) struct RuleSyntaxLine {
    /// Original source line for diagnostics.
    line_number: SourceLineNumber,
    /// Left-side syntax before `=`.
    left: OwnedCompactSyntax,
    /// Right-side syntax after `=`.
    right: OwnedCompactSyntax,
}

impl RuleSyntaxLine {
    /// Splits one compact source line around its rule separator.
    ///
    /// # Errors
    ///
    /// Returns `ParseError` if the line has no `=`, multiple `=` bytes, or a
    /// rule-side buffer cannot be allocated.
    pub(super) fn new(
        line_number: SourceLineNumber,
        bytes: Vec<CompactByte>,
    ) -> Result<Self, ParseError> {
        let parts = RuleSyntaxParts::split(line_number, bytes)?;
        Ok(Self {
            line_number,
            left: parts.left,
            right: parts.right,
        })
    }

    /// Parses this compact rule syntax into typed rule data.
    ///
    /// # Errors
    ///
    /// Returns `ParseError` if either rule side contains invalid modifier,
    /// action, or payload syntax.
    pub(super) fn parse(&self, payload_limit: PayloadByteLimit) -> Result<ParsedRule, ParseError> {
        let (left, right) = self.syntax_parts();
        let head = left.parse(payload_limit)?;
        let body = right.parse(payload_limit)?;

        Ok(ParsedRule::from_parts(self.line_number, head, body))
    }

    /// Borrows the compact line as left and right syntax slices.
    fn syntax_parts(&self) -> (LeftSyntax<'_>, RightSyntax<'_>) {
        (
            LeftSyntax {
                line_number: self.line_number,
                bytes: self.left.as_syntax(),
            },
            RightSyntax {
                line_number: self.line_number,
                bytes: self.right.as_syntax(),
            },
        )
    }
}

/// Owned syntax split around the single rule separator.
#[derive(Debug, PartialEq, Eq)]
struct RuleSyntaxParts {
    /// Left-side syntax before `=`.
    left: OwnedCompactSyntax,
    /// Right-side syntax after `=`.
    right: OwnedCompactSyntax,
}

/// Owned compact syntax bytes for one rule side.
#[derive(Debug, PartialEq, Eq)]
struct OwnedCompactSyntax {
    /// Compact bytes in the current syntax domain.
    bytes: Vec<CompactByte>,
}

/// Borrowed compact syntax bytes for one parser phase.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct CompactSyntax<'code> {
    /// Compact bytes in the current syntax domain.
    bytes: &'code [CompactByte],
}

/// Result of matching a concrete syntax token prefix.
#[derive(Clone, Copy)]
struct MatchedSyntaxPrefix<'code> {
    /// Source column of the matched token.
    column: SourceColumn,
    /// Remaining bytes after the matched token.
    rest: CompactSyntax<'code>,
}

/// Matched token classified into a parser-domain kind.
#[derive(Clone, Copy)]
struct MatchedToken<T> {
    /// Parser-domain token kind.
    kind: T,
    /// Source column where the token starts.
    column: SourceColumn,
}

impl RuleSyntaxParts {
    /// Splits compact syntax into owned left and right domains.
    ///
    /// # Errors
    ///
    /// Returns `ParseError` if the line has no `=`, multiple `=` bytes, or a
    /// side buffer cannot be allocated.
    fn split(line_number: SourceLineNumber, bytes: Vec<CompactByte>) -> Result<Self, ParseError> {
        let mut splitter = RuleSyntaxSplitter::new(line_number);

        for byte in bytes {
            splitter.push(byte)?;
        }

        splitter.finish()
    }
}

/// State machine that splits one compact rule line around its single separator.
#[derive(Debug, PartialEq, Eq)]
struct RuleSyntaxSplitter {
    /// Original source line for diagnostics.
    line_number: SourceLineNumber,
    /// Left-side syntax before `=`.
    left: OwnedCompactSyntax,
    /// Right-side syntax after `=`.
    right: OwnedCompactSyntax,
    /// Current split state.
    state: RuleSyntaxSplitState,
}

/// Current side receiving compact syntax bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RuleSyntaxSplitState {
    /// Separator has not been consumed yet.
    BeforeEquals,
    /// Separator has been consumed; subsequent bytes belong to the right side.
    AfterEquals,
}

impl RuleSyntaxSplitter {
    /// Starts splitting one compact rule line.
    const fn new(line_number: SourceLineNumber) -> Self {
        Self {
            line_number,
            left: OwnedCompactSyntax::new(),
            right: OwnedCompactSyntax::new(),
            state: RuleSyntaxSplitState::BeforeEquals,
        }
    }

    /// Pushes one compact syntax byte through the current split state.
    ///
    /// # Errors
    ///
    /// Returns `ParseError` if a second separator appears or a side buffer
    /// cannot be allocated.
    fn push(&mut self, byte: CompactByte) -> Result<(), ParseError> {
        match (self.state, byte.as_u8()) {
            (RuleSyntaxSplitState::BeforeEquals, b'=') => {
                self.state = RuleSyntaxSplitState::AfterEquals;
                Ok(())
            }
            (RuleSyntaxSplitState::AfterEquals, b'=') => Err(ParseError::at_position(
                SourcePosition::new(self.line_number, byte.source_column()),
                ParseErrorKind::MultipleEquals,
            )),
            (RuleSyntaxSplitState::BeforeEquals, _) => self.left.push(byte, self.line_number),
            (RuleSyntaxSplitState::AfterEquals, _) => self.right.push(byte, self.line_number),
        }
    }

    /// Finishes the split after all bytes have been consumed.
    ///
    /// # Errors
    ///
    /// Returns `ParseError` if no separator was consumed.
    fn finish(self) -> Result<RuleSyntaxParts, ParseError> {
        match self.state {
            RuleSyntaxSplitState::BeforeEquals => Err(ParseError::at_line(
                self.line_number,
                ParseErrorKind::MissingEquals,
            )),
            RuleSyntaxSplitState::AfterEquals => Ok(RuleSyntaxParts {
                left: self.left,
                right: self.right,
            }),
        }
    }
}

impl OwnedCompactSyntax {
    /// Starts an empty owned syntax side.
    const fn new() -> Self {
        Self { bytes: Vec::new() }
    }

    /// Adds one compact byte to this side.
    ///
    /// # Errors
    ///
    /// Returns `ParseError` if storing the side byte fails.
    fn push(&mut self, byte: CompactByte, line_number: SourceLineNumber) -> Result<(), ParseError> {
        try_push(&mut self.bytes, byte, AllocationContext::ProgramCodeLine)
            .map_err(|error| ParseError::at_line(line_number, ParseErrorKind::Allocation(error)))
    }

    /// Borrows this owned syntax side.
    fn as_syntax(&self) -> CompactSyntax<'_> {
        CompactSyntax { bytes: &self.bytes }
    }
}

impl<'code> CompactSyntax<'code> {
    /// Returns the compact bytes in this syntax domain.
    const fn as_slice(self) -> &'code [CompactByte] {
        self.bytes
    }

    /// Removes a leading syntax token when it is present.
    fn strip_token(self, token: SyntaxToken) -> Option<MatchedSyntaxPrefix<'code>> {
        let token_bytes = token.bytes();

        if self.bytes.len() < token_bytes.len() {
            return None;
        }

        let starts_with_token = self
            .bytes
            .iter()
            .take(token_bytes.len())
            .copied()
            .map(CompactByte::as_u8)
            .eq(token_bytes.iter().copied());

        if starts_with_token {
            let column = self.bytes.first().copied()?.source_column();
            self.bytes
                .get(token_bytes.len()..)
                .map(|bytes| MatchedSyntaxPrefix {
                    column,
                    rest: Self { bytes },
                })
        } else {
            None
        }
    }
}

/// Left-side syntax before repeat and anchor classification.
#[derive(Clone, Copy)]
struct LeftSyntax<'code> {
    /// Original source line for diagnostics.
    line_number: SourceLineNumber,
    /// Left-side compact syntax.
    bytes: CompactSyntax<'code>,
}

impl<'code> LeftSyntax<'code> {
    /// Parses left-side syntax into a typed rule head.
    ///
    /// # Errors
    ///
    /// Returns `ParseError` if left-side modifier order or payload syntax is
    /// invalid.
    fn parse(self, payload_limit: PayloadByteLimit) -> Result<RuleHead, ParseError> {
        self.into_after_repeat().parse(payload_limit)
    }

    /// Classifies the optional `(once)` prefix.
    fn into_after_repeat(self) -> LeftAfterRepeat<'code> {
        if let Some(matched) = self.bytes.strip_token(SyntaxToken::Once) {
            LeftAfterRepeat {
                line_number: self.line_number,
                bytes: matched.rest,
                repeat: RuleRepeatSyntax::Once,
            }
        } else {
            LeftAfterRepeat {
                line_number: self.line_number,
                bytes: self.bytes,
                repeat: RuleRepeatSyntax::Always,
            }
        }
    }
}

/// Left-side syntax after repeat classification.
#[derive(Clone, Copy)]
struct LeftAfterRepeat<'code> {
    /// Original source line for diagnostics.
    line_number: SourceLineNumber,
    /// Remaining compact syntax after optional repeat.
    bytes: CompactSyntax<'code>,
    /// Parsed repeat modifier.
    repeat: RuleRepeatSyntax,
}

impl<'code> LeftAfterRepeat<'code> {
    /// Parses left-side syntax after optional repeat classification.
    ///
    /// # Errors
    ///
    /// Returns `ParseError` if the remaining left-side syntax cannot become a
    /// valid payload with its anchor.
    fn parse(self, payload_limit: PayloadByteLimit) -> Result<RuleHead, ParseError> {
        self.into_payload_syntax()?.parse(payload_limit)
    }

    /// Classifies the left-side anchor and payload slice.
    ///
    /// # Errors
    ///
    /// Returns `ParseError` when modifiers appear after the anchor/payload
    /// boundary or source-column lookup overflows.
    fn into_payload_syntax(self) -> Result<LeftPayloadSyntax<'code>, ParseError> {
        let (anchor, bytes) = if let Some(matched) = self.bytes.strip_token(SyntaxToken::Start) {
            (RuleAnchorSyntax::Start, matched.rest)
        } else if let Some(matched) = self.bytes.strip_token(SyntaxToken::End) {
            (RuleAnchorSyntax::End, matched.rest)
        } else {
            (RuleAnchorSyntax::Anywhere, self.bytes)
        };

        if let Some(modifier) = left_modifier_kind(bytes) {
            return Err(ParseError::at_position(
                SourcePosition::new(self.line_number, modifier.column),
                ParseErrorKind::UnsupportedLeftModifierOrder {
                    modifier: modifier.kind,
                },
            ));
        }

        Ok(LeftPayloadSyntax {
            line_number: self.line_number,
            bytes,
            repeat: self.repeat,
            anchor,
        })
    }
}

/// Left-side payload syntax after modifier classification.
#[derive(Clone, Copy)]
struct LeftPayloadSyntax<'code> {
    /// Original source line for diagnostics.
    line_number: SourceLineNumber,
    /// Payload bytes after repeat and anchor modifiers.
    bytes: CompactSyntax<'code>,
    /// Parsed repeat modifier.
    repeat: RuleRepeatSyntax,
    /// Parsed match anchor.
    anchor: RuleAnchorSyntax,
}

impl LeftPayloadSyntax<'_> {
    /// Parses left-side payload syntax into a typed rule head.
    ///
    /// # Errors
    ///
    /// Returns `ParseError` if the left-side payload contains invalid
    /// executable payload bytes or allocation fails.
    fn parse(self, payload_limit: PayloadByteLimit) -> Result<RuleHead, ParseError> {
        let payload = parse_payload(
            self.bytes.as_slice(),
            self.line_number,
            PayloadKind::LeftSideData,
            payload_limit,
        )?;
        Ok(RuleHead::new(self.repeat, self.anchor, payload))
    }
}

/// Right-side syntax before action classification.
#[derive(Clone, Copy)]
struct RightSyntax<'code> {
    /// Original source line for diagnostics.
    line_number: SourceLineNumber,
    /// Right-side compact syntax.
    bytes: CompactSyntax<'code>,
}

impl<'code> RightSyntax<'code> {
    /// Parses right-side syntax into a typed rule body.
    ///
    /// # Errors
    ///
    /// Returns `ParseError` if right-side action or payload syntax is invalid.
    fn parse(self, payload_limit: PayloadByteLimit) -> Result<RuleBody, ParseError> {
        self.into_payload_syntax()?.parse(payload_limit)
    }

    /// Classifies right-side syntax into replacement payload or action payload.
    ///
    /// # Errors
    ///
    /// Returns `ParseError` if an action payload starts with another
    /// right-side action token.
    fn into_payload_syntax(self) -> Result<RightPayloadSyntax<'code>, ParseError> {
        if let Some(matched) = self.bytes.strip_token(SyntaxToken::Start) {
            return Ok(RightPayloadSyntax::Action(RightActionPayloadSyntax::new(
                self.line_number,
                matched.rest,
                RightActionSyntax::MoveStart,
            )?));
        } else if let Some(matched) = self.bytes.strip_token(SyntaxToken::End) {
            return Ok(RightPayloadSyntax::Action(RightActionPayloadSyntax::new(
                self.line_number,
                matched.rest,
                RightActionSyntax::MoveEnd,
            )?));
        } else if let Some(matched) = self.bytes.strip_token(SyntaxToken::Return) {
            return Ok(RightPayloadSyntax::Action(RightActionPayloadSyntax::new(
                self.line_number,
                matched.rest,
                RightActionSyntax::Return,
            )?));
        }

        Ok(RightPayloadSyntax::Replace(RightReplacePayloadSyntax {
            line_number: self.line_number,
            bytes: self.bytes,
        }))
    }
}

/// Right-side action token classified before payload parsing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RightActionSyntax {
    /// `(start)` action moving output to the beginning.
    MoveStart,
    /// `(end)` action moving output to the end.
    MoveEnd,
    /// `(return)` action ending execution.
    Return,
}

impl RightActionSyntax {
    /// Payload diagnostic domain implied by this action token.
    const fn payload_kind(self) -> PayloadKind {
        match self {
            Self::MoveStart => PayloadKind::RightSideMoveStartPayload,
            Self::MoveEnd => PayloadKind::RightSideMoveEndPayload,
            Self::Return => PayloadKind::RightSideReturnPayload,
        }
    }

    /// Combines this action token with its parsed payload.
    fn into_body(self, payload: Payload) -> RuleBody {
        let action = match self {
            Self::MoveStart => ParsedRuleAction::Rewrite(RewriteAction::MoveStart(payload)),
            Self::MoveEnd => ParsedRuleAction::Rewrite(RewriteAction::MoveEnd(payload)),
            Self::Return => ParsedRuleAction::Return(payload),
        };

        RuleBody::new(action)
    }
}

/// Right-side payload domain after action-token classification.
#[derive(Clone, Copy)]
enum RightPayloadSyntax<'code> {
    /// Plain replacement payload with no action token.
    Replace(RightReplacePayloadSyntax<'code>),
    /// Payload belonging to a right-side action token.
    Action(RightActionPayloadSyntax<'code>),
}

impl RightPayloadSyntax<'_> {
    /// Parses classified right-side payload syntax into a typed rule body.
    ///
    /// # Errors
    ///
    /// Returns `ParseError` if payload bytes are invalid or allocation fails.
    fn parse(self, payload_limit: PayloadByteLimit) -> Result<RuleBody, ParseError> {
        match self {
            Self::Replace(payload) => payload.parse(payload_limit),
            Self::Action(payload) => payload.parse(payload_limit),
        }
    }
}

/// Right-side replacement payload syntax.
#[derive(Clone, Copy)]
struct RightReplacePayloadSyntax<'code> {
    /// Original source line for diagnostics.
    line_number: SourceLineNumber,
    /// Replacement payload bytes.
    bytes: CompactSyntax<'code>,
}

impl RightReplacePayloadSyntax<'_> {
    /// Parses direct replacement payload syntax into a typed rule body.
    ///
    /// # Errors
    ///
    /// Returns `ParseError` if payload bytes are invalid or allocation fails.
    fn parse(self, payload_limit: PayloadByteLimit) -> Result<RuleBody, ParseError> {
        let payload = parse_payload(
            self.bytes.as_slice(),
            self.line_number,
            PayloadKind::RightSideData,
            payload_limit,
        )?;
        Ok(RuleBody::new(ParsedRuleAction::Rewrite(
            RewriteAction::Replace(payload),
        )))
    }
}

/// Right-side action payload syntax after nested-action rejection.
#[derive(Clone, Copy)]
struct RightActionPayloadSyntax<'code> {
    /// Original source line for diagnostics.
    line_number: SourceLineNumber,
    /// Action payload bytes.
    bytes: CompactSyntax<'code>,
    /// Action token that owns this payload.
    action: RightActionSyntax,
}

impl<'code> RightActionPayloadSyntax<'code> {
    /// Builds a right-side action payload after rejecting nested action tokens.
    ///
    /// # Errors
    ///
    /// Returns `ParseError` if the action payload starts with another
    /// right-side action token.
    fn new(
        line_number: SourceLineNumber,
        bytes: CompactSyntax<'code>,
        action: RightActionSyntax,
    ) -> Result<Self, ParseError> {
        reject_nested_rhs_action(bytes, line_number)?;
        Ok(Self {
            line_number,
            bytes,
            action,
        })
    }

    /// Parses action payload syntax into a typed rule body.
    ///
    /// # Errors
    ///
    /// Returns `ParseError` if payload bytes are invalid or allocation fails.
    fn parse(self, payload_limit: PayloadByteLimit) -> Result<RuleBody, ParseError> {
        let payload = parse_payload(
            self.bytes.as_slice(),
            self.line_number,
            self.action.payload_kind(),
            payload_limit,
        )?;
        Ok(self.action.into_body(payload))
    }
}

/// Checks payload length and validates bytes before owned payload construction.
///
/// # Errors
///
/// Returns `ParseError` if the payload exceeds `limit`, contains invalid bytes,
/// or cannot allocate owned payload storage.
fn parse_payload(
    bytes: &[CompactByte],
    line_number: SourceLineNumber,
    payload_kind: PayloadKind,
    limit: PayloadByteLimit,
) -> Result<Payload, ParseError> {
    let syntax = PayloadSyntax::check(bytes, line_number, payload_kind, limit)?;
    syntax.validate()
}

/// Classifies the first token from an ordered token map.
fn first_matching_token_kind<T: Copy>(
    input: CompactSyntax<'_>,
    mappings: &[(SyntaxToken, T)],
) -> Option<MatchedToken<T>> {
    mappings.iter().find_map(|&(token, kind)| {
        input.strip_token(token).map(|matched| MatchedToken {
            kind,
            column: matched.column,
        })
    })
}

/// Classifies a left-side modifier token at the current syntax boundary.
fn left_modifier_kind(input: CompactSyntax<'_>) -> Option<MatchedToken<LeftModifierKind>> {
    first_matching_token_kind(
        input,
        &[
            (SyntaxToken::Once, LeftModifierKind::Once),
            (SyntaxToken::Start, LeftModifierKind::Start),
            (SyntaxToken::End, LeftModifierKind::End),
        ],
    )
}

/// Classifies a right-side action token at the current syntax boundary.
fn right_action_kind(input: CompactSyntax<'_>) -> Option<MatchedToken<RightActionKind>> {
    first_matching_token_kind(
        input,
        &[
            (SyntaxToken::Start, RightActionKind::Start),
            (SyntaxToken::End, RightActionKind::End),
            (SyntaxToken::Return, RightActionKind::Return),
        ],
    )
}

/// Rejects action tokens that appear inside a right-side action payload.
///
/// # Errors
///
/// Returns `ParseError` if the payload starts with another right-side action
/// token or its source column cannot be represented.
fn reject_nested_rhs_action(
    input: CompactSyntax<'_>,
    line_number: SourceLineNumber,
) -> Result<(), ParseError> {
    if let Some(action) = right_action_kind(input) {
        return Err(ParseError::at_position(
            SourcePosition::new(line_number, action.column),
            ParseErrorKind::UnsupportedRightActionSyntax {
                action: action.kind,
            },
        ));
    }

    Ok(())
}