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
//! Public trace API contract tests.

#[path = "support/runtime.rs"]
mod runtime_support;
mod support;

use rsaeb::error::{
    RunError, RunFinishError, RunStepError, TraceSnapshotError, TraceSnapshotRunError,
    TracedRunError,
};
use rsaeb::execution::OwnedStepTransition;
use rsaeb::input::RunSeed;
use rsaeb::limits::{
    DEFAULT_MAX_INPUT_LEN, DEFAULT_MAX_RETURN_LEN, DEFAULT_MAX_STATE_LEN,
    DEFAULT_MAX_TRACE_SNAPSHOT_LEN, StepLimit, TraceSnapshotByteLimit,
};
use rsaeb::program::{Program, RunOutcome, RunResult};
use rsaeb::trace::{
    BorrowedTraceEffect, BorrowedTraceEvent, TraceSnapshotEffect, TraceSnapshotEvent,
};
use runtime_support::TestRunPolicy;
use support::{TestFailure, TestResult, ensure_eq, ensure_matches, parse_program};

/// Returns the expected trace snapshot run error.
///
/// # Errors
///
/// Returns `TestFailure` if the traced run succeeds.
fn expect_trace_snapshot_error<T>(
    result: Result<T, TraceSnapshotRunError<TestFailure>>,
) -> Result<TraceSnapshotRunError<TestFailure>, TestFailure> {
    match result {
        Ok(_) => Err(TestFailure::message("expected trace snapshot error")),
        Err(error) => Ok(error),
    }
}

/// Runs a standard trace snapshot example and returns its result and events.
///
/// # Errors
///
/// Returns `TestFailure` if parsing, input validation, runtime execution, or
/// trace snapshot materialization fails.
fn trace_snapshot_example(
    program: &Program,
) -> Result<(RunResult, Vec<TraceSnapshotEvent<'_>>), TestFailure> {
    let mut events = Vec::new();
    let limits = TestRunPolicy::new(
        DEFAULT_MAX_INPUT_LEN,
        StepLimit::new(10_000),
        DEFAULT_MAX_STATE_LEN,
        DEFAULT_MAX_RETURN_LEN,
    );
    let result = program.run_with_trace_snapshots(
        runtime_input(b"a", limits)?,
        DEFAULT_MAX_TRACE_SNAPSHOT_LEN,
        |event| {
            events.push(event);
            Ok::<(), TestFailure>(())
        },
    )?;

    Ok((result, events))
}

fn snapshot_event_bytes<'event>(event: &'event TraceSnapshotEvent<'_>) -> &'event [u8] {
    match event {
        TraceSnapshotEvent::Initial { state } => state.as_slice(),
        TraceSnapshotEvent::Step { effect, .. } => match effect {
            TraceSnapshotEffect::Continue { state } => state.as_slice(),
            TraceSnapshotEffect::Return { output } => output.as_slice(),
        },
    }
}

fn traced_test_failure(error: TracedRunError<TestFailure>) -> TestFailure {
    match error {
        TracedRunError::Run(error) => TestFailure::from(error),
        TracedRunError::Trace(error) => error,
    }
}

#[derive(Debug, PartialEq, Eq)]
enum CommittedStepSignature {
    Continue {
        step: usize,
        rule_position: usize,
        state: Vec<u8>,
    },
    Return {
        step: usize,
        rule_position: usize,
        output: Vec<u8>,
    },
}

/// Validates test bytes as runtime input.
///
/// # Errors
///
/// Returns `RuntimeInputError` if the bytes are not valid runtime input.
fn runtime_input(bytes: &[u8], limits: TestRunPolicy) -> Result<RunSeed, TestFailure> {
    runtime_support::run_seed(bytes, limits)
}

/// Collects committed step signatures from borrowed tracing.
///
/// # Errors
///
/// Returns `TestFailure` if tracing or materialization fails.
fn borrowed_trace_step_signatures(
    program: &Program,
    seed: RunSeed,
) -> Result<Vec<CommittedStepSignature>, TestFailure> {
    let mut signatures = Vec::new();
    program
        .run_with_borrowed_trace(seed, |event| {
            if let BorrowedTraceEvent::Step { step, rule, effect } = event {
                match effect {
                    BorrowedTraceEffect::Continue { state } => {
                        signatures.push(CommittedStepSignature::Continue {
                            step: step.get(),
                            rule_position: rule.position().number().get(),
                            state: state.materialize()?.into_raw_bytes(),
                        });
                    }
                    BorrowedTraceEffect::Return { output } => {
                        signatures.push(CommittedStepSignature::Return {
                            step: step.get(),
                            rule_position: rule.position().number().get(),
                            output: output.materialize()?.into_raw_bytes(),
                        });
                    }
                }
            }
            Ok(())
        })
        .map_err(traced_test_failure)?;
    Ok(signatures)
}

/// Collects committed step signatures from owned stepwise execution.
///
/// # Errors
///
/// Returns `TestFailure` if stepping or materialization fails.
fn owned_step_signatures(
    program: Program,
    seed: RunSeed,
) -> Result<Vec<CommittedStepSignature>, TestFailure> {
    let mut signatures = Vec::new();
    let mut session = program.into_run(seed)?;
    loop {
        match session.step() {
            OwnedStepTransition::Applied(applied) => {
                signatures.push(CommittedStepSignature::Continue {
                    step: applied.step().get(),
                    rule_position: applied.rule().position().number().get(),
                    state: applied.state().materialize()?.into_raw_bytes(),
                });
                session = applied.into_session();
            }
            OwnedStepTransition::Returned(returned) => {
                signatures.push(CommittedStepSignature::Return {
                    step: returned.step().get(),
                    rule_position: returned.rule().position().number().get(),
                    output: returned.output().as_slice().to_vec(),
                });
                return Ok(signatures);
            }
            OwnedStepTransition::Stable(_) => return Ok(signatures),
            OwnedStepTransition::Failed(failed) => {
                return Err(TestFailure::from(failed.into_error()));
            }
        }
    }
}

/// # Errors
///
/// Returns `TestFailure` if borrowed trace events allocate snapshots or expose
/// incorrect byte data.
#[test]
fn trace_borrowed_events_are_emitted_without_snapshots() -> TestResult {
    let program = parse_program("a=b\nb=(return)ok")?;
    let mut seen = Vec::new();
    let limits = TestRunPolicy::new(
        DEFAULT_MAX_INPUT_LEN,
        StepLimit::new(10_000),
        DEFAULT_MAX_STATE_LEN,
        DEFAULT_MAX_RETURN_LEN,
    );

    let result = program
        .run_with_borrowed_trace(runtime_input(b"a", limits)?, |event| {
            let bytes = match event {
                BorrowedTraceEvent::Initial { state }
                | BorrowedTraceEvent::Step {
                    effect: BorrowedTraceEffect::Continue { state },
                    ..
                } => state.materialize()?.into_raw_bytes(),
                BorrowedTraceEvent::Step {
                    effect: BorrowedTraceEffect::Return { output },
                    ..
                } => output.materialize()?.into_raw_bytes(),
            };
            seen.push((event.byte_count().get(), bytes));
            Ok(())
        })
        .map_err(traced_test_failure)?;

    ensure_matches(
        matches!(result.outcome(), RunOutcome::Return(output) if output.as_slice() == b"ok"),
        "expected return output",
    )?;
    ensure_eq!(
        seen.as_slice(),
        &[(1, b"a".to_vec()), (1, b"b".to_vec()), (2, b"ok".to_vec())],
    )
}

/// # Errors
///
/// Returns `TestFailure` if borrowed trace and owned stepwise execution report
/// different committed rule effects.
#[test]
fn trace_borrowed_steps_match_owned_stepwise_commits() -> TestResult {
    let source = "(once)a=b\nb=(return)ok";
    let limits = TestRunPolicy::new(
        DEFAULT_MAX_INPUT_LEN,
        StepLimit::new(10),
        DEFAULT_MAX_STATE_LEN,
        DEFAULT_MAX_RETURN_LEN,
    );

    let borrowed = parse_program(source)?;
    let borrowed_steps = borrowed_trace_step_signatures(&borrowed, runtime_input(b"a", limits)?)?;
    let owned_steps = owned_step_signatures(parse_program(source)?, runtime_input(b"a", limits)?)?;

    ensure_eq!(borrowed_steps, owned_steps)
}

/// # Errors
///
/// Returns `TestFailure` if trace snapshot events lose materialized bytes or
/// structured effects.
#[test]
fn trace_snapshot_events_carry_bytes_and_structured_effects() -> TestResult {
    let program = parse_program("a=b\nb=(return)ok")?;
    let (result, events) = trace_snapshot_example(&program)?;

    ensure_matches(
        matches!(result.outcome(), RunOutcome::Return(output) if output.as_slice() == b"ok"),
        "expected return output",
    )?;
    ensure_eq!(events.len(), 3)?;

    let initial = events
        .first()
        .ok_or(TestFailure::message("expected initial trace event"))?;
    let first_step = events
        .get(1)
        .ok_or(TestFailure::message("expected first trace step"))?;
    let second_step = events
        .get(2)
        .ok_or(TestFailure::message("expected second trace step"))?;

    ensure_eq!(snapshot_event_bytes(initial), b"a".as_slice())?;
    ensure_eq!(snapshot_event_bytes(first_step), b"b".as_slice())?;
    ensure_eq!(snapshot_event_bytes(second_step), b"ok".as_slice())?;
    ensure_matches(
        matches!(
            first_step,
            TraceSnapshotEvent::Step {
                effect: TraceSnapshotEffect::Continue { .. },
                ..
            }
        ),
        "expected continue step",
    )?;
    ensure_matches(
        matches!(
            second_step,
            TraceSnapshotEvent::Step {
                effect: TraceSnapshotEffect::Return { .. },
                ..
            }
        ),
        "expected return step",
    )
}

/// # Errors
///
/// Returns `TestFailure` if a continuing trace snapshot step does not carry the
/// expected rule view.
#[test]
fn trace_snapshot_continue_step_carries_rule_view() -> TestResult {
    let program = parse_program("a=b\nb=(return)ok")?;
    let (_, events) = trace_snapshot_example(&program)?;
    let first_step = events
        .get(1)
        .ok_or(TestFailure::message("expected first trace step"))?;

    match first_step {
        TraceSnapshotEvent::Step {
            rule,
            effect: TraceSnapshotEffect::Continue { state },
            ..
        } => {
            ensure_eq!(state.as_slice(), b"b".as_slice())?;
            ensure_eq!(rule.canonical_source()?.as_slice(), b"a=b".as_slice())?;
            Ok(())
        }
        TraceSnapshotEvent::Initial { .. } | TraceSnapshotEvent::Step { .. } => {
            Err(TestFailure::message("expected continuing step event"))
        }
    }
}

/// # Errors
///
/// Returns `TestFailure` if borrowed-to-snapshot conversion uses runtime limits
/// instead of only the snapshot limit.
#[test]
fn trace_borrowed_to_snapshot_uses_only_snapshot_limit() -> TestResult {
    let program = parse_program("a=b")?;
    let mut materialization = None;
    let limits = TestRunPolicy::new(
        DEFAULT_MAX_INPUT_LEN,
        StepLimit::new(10),
        DEFAULT_MAX_STATE_LEN,
        DEFAULT_MAX_RETURN_LEN,
    );

    program
        .run_with_borrowed_trace(runtime_input(b"a", limits)?, |event| {
            if materialization.is_none() {
                materialization = Some(event.to_snapshot(TraceSnapshotByteLimit::new(0)));
            }
            Ok::<(), TestFailure>(())
        })
        .map_err(traced_test_failure)?;

    ensure_matches(
        matches!(
            materialization.ok_or(TestFailure::message("expected trace event"))?,
            Err(TraceSnapshotError::Limit {
                limit,
                attempted_len,
            }) if limit == TraceSnapshotByteLimit::new(0) && attempted_len.get() == 1
        ),
        "expected trace snapshot byte limit",
    )
}

/// # Errors
///
/// Returns `TestFailure` if the snapshot API conflates runtime, snapshot, and
/// sink failures.
#[test]
fn trace_snapshot_api_splits_runtime_snapshot_and_sink_failures() -> TestResult {
    let program = parse_program("a=b")?;
    let runtime_limits = TestRunPolicy::new(
        DEFAULT_MAX_INPUT_LEN,
        StepLimit::new(0),
        DEFAULT_MAX_STATE_LEN,
        DEFAULT_MAX_RETURN_LEN,
    );
    let runtime_error = program.run_with_trace_snapshots(
        runtime_input(b"a", runtime_limits)?,
        TraceSnapshotByteLimit::new(10),
        |_event| Ok::<(), TestFailure>(()),
    );
    let runtime_error = expect_trace_snapshot_error(runtime_error)?;
    ensure_matches(
        matches!(
            runtime_error,
            TraceSnapshotRunError::Run(RunError::Finish(RunFinishError::Step(
                RunStepError::StepLimit(_)
            )))
        ),
        "expected runtime failure variant",
    )?;

    let snapshot_limits = TestRunPolicy::new(
        DEFAULT_MAX_INPUT_LEN,
        StepLimit::new(10),
        DEFAULT_MAX_STATE_LEN,
        DEFAULT_MAX_RETURN_LEN,
    );
    let snapshot_error = program.run_with_trace_snapshots(
        runtime_input(b"a", snapshot_limits)?,
        TraceSnapshotByteLimit::new(0),
        |_event| Ok::<(), TestFailure>(()),
    );
    ensure_matches(
        matches!(
            snapshot_error,
            Err(TraceSnapshotRunError::Snapshot(TraceSnapshotError::Limit {
                limit,
                attempted_len,
            })) if limit == TraceSnapshotByteLimit::new(0) && attempted_len.get() == 1
        ),
        "expected snapshot materialization limit",
    )?;

    let sink_limits = TestRunPolicy::new(
        DEFAULT_MAX_INPUT_LEN,
        StepLimit::new(10),
        DEFAULT_MAX_STATE_LEN,
        DEFAULT_MAX_RETURN_LEN,
    );
    let sink_error = program.run_with_trace_snapshots(
        runtime_input(b"a", sink_limits)?,
        TraceSnapshotByteLimit::new(10),
        |_event| Err::<(), _>("trace sink full"),
    );
    ensure_eq!(
        sink_error,
        Err(TraceSnapshotRunError::Trace("trace sink full")),
    )
}

/// # Errors
///
/// Returns `TestFailure` if the final trace event no longer matches the run
/// result.
#[test]
fn trace_final_event_matches_run_result() -> TestResult {
    let program = parse_program("a=b\nb=(return)c")?;
    let mut events = Vec::new();
    let limits = TestRunPolicy::new(
        DEFAULT_MAX_INPUT_LEN,
        StepLimit::new(10),
        DEFAULT_MAX_STATE_LEN,
        DEFAULT_MAX_RETURN_LEN,
    );

    let result = program.run_with_trace_snapshots(
        runtime_input(b"a", limits)?,
        DEFAULT_MAX_TRACE_SNAPSHOT_LEN,
        |event| {
            events.push(event);
            Ok::<(), TestFailure>(())
        },
    )?;

    let last = events
        .last()
        .ok_or(TestFailure::message("expected final trace event"))?;
    let result_bytes = match result.outcome() {
        RunOutcome::Stable(output) => output.as_slice(),
        RunOutcome::Return(output) => output.as_slice(),
    };
    ensure_eq!(snapshot_event_bytes(last), result_bytes)?;
    let expected_event_count = result
        .steps()
        .get()
        .checked_add(1)
        .ok_or(TestFailure::message("trace event count overflow"))?;
    ensure_eq!(events.len(), expected_event_count)?;
    ensure_matches(
        matches!(
            last,
            TraceSnapshotEvent::Step {
                effect: TraceSnapshotEffect::Return { .. },
                ..
            }
        ),
        "expected final return step",
    )
}