rsaeb is a Rust 2024 no_std + alloc, byte-oriented interpreter for A=B
ordered rewrite programs.
A=B: https://store.steampowered.com/app/1720850/AB/
This project is an unofficial, independently developed interpreter library. It is not affiliated with, endorsed by, or maintained by Artless Games or the original A=B author.
A=B's compact lhs=rhs ordered rewrite system is an unusually elegant
programming-puzzle idea. This crate exists because that design is worth
studying, testing, and reimplementing. If this interpreter interests you,
please support the original game.
- This README is the package entry point. It explains the interpreter shape, the accepted A=B surface, byte-domain boundaries, and release checks.
- The generated rustdoc is the exact API reference and carries the complete doctested public examples.
- The GitHub Wiki is a short navigation layer for use cases and embedding boundaries.
The crate root intentionally does not re-export duplicate type paths. Public
types live under their domain modules, such as source, input, program,
policy, limits, execution, inspect, trace, and error.
Parse source through the executable-program boundary, validate runtime input, admit it into one execution under an execution policy, then run:
use rsaeb::input::{RuntimeInput, RuntimeInputSource};
use rsaeb::policy::{DefaultExecutionPolicy, DefaultParsePolicy, DefaultRuntimeInputPolicy};
use rsaeb::program::{ExecutableProgram, RunOutcome};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let executable = ExecutableProgram::parse_text::<DefaultParsePolicy>("a=b")?;
let input = RuntimeInput::validate::<DefaultRuntimeInputPolicy>(RuntimeInputSource::from_bytes(b"a"))?;
let admitted = input.admit::<DefaultExecutionPolicy>()?;
let result = executable.execute(admitted)?;
if !matches!(
result.outcome(),
RunOutcome::Stable(output) if output.as_slice() == b"b"
) {
return Err("unexpected stable output".into());
}
Ok(())
}ExecutableProgram::parse_text / parse_bytes and
EmptyProgram::parse_text / parse_bytes are the public source boundaries.
The target program type selects the expected shape, while parsing validates
syntax and rejects content that does not match that shape. Parse and input
policies are selected only at construction; they do not parameterize the
resulting ExecutableProgram, EmptyProgram, or RuntimeInput values.
Empty-target parsing rejects the first fully parsed executable rule immediately.
RuntimeInputSource and RuntimeInput::validate do the same for runtime input
bytes. Reuse parsed executable programs freely: an ExecutableProgram is
immutable, and (once) consumption is local to each execution. Runtime state
encodes each (once) rule as a fresh or consumed runtime cell variant, so
(once) availability cannot become a parser-assigned lookup failure.
The normal host flow is:
- Load source bytes or text outside the interpreter.
- Parse with
ExecutableProgram::parse_text/parse_bytesorEmptyProgram::parse_text/parse_bytes. - Label host input bytes with
RuntimeInputSource::from_bytes. - Validate with
RuntimeInput::validate. - Admit with
RuntimeInput::admit::<E>()under anExecutionPolicy. - Execute, step, trace, or rule-attempt step from
ExecutableProgram, or callEmptyProgram::stabilizefor empty source.
The crate intentionally contains no filesystem, process, argument parsing, environment access, stdout/stderr, or lossy display boundary. Hosts perform I/O outside the interpreter and pass already-loaded bytes into typed boundaries.
ExecutableProgram starts reusable runs with .execute(admitted),
.trace(admitted, request), .steps(admitted), or
.rule_attempts::<A, _>(admitted). Rule-attempt execution is borrowed because
its resumable cursor is tied to the executable rule table. The rule-attempt
cursor must be matched as continuing or final before stepping, so a final rule
cannot be confused with a missed rule that still has a successor. EmptyProgram
exposes only .stabilize(admitted), which materializes the admitted input as a
zero-step stable result.
Successful outcomes expose the exact concrete rule view that committed:
AlwaysRewriteRuleView, OnceRewriteRuleView, AlwaysReturnRuleView, or
OnceReturnRuleView. General inspect::RuleView remains only the
program-inspection classification surface; callers match it into a concrete rule
view before reading rule metadata. Committed successes, continuing rule-attempt
misses, and final stable-after-miss terminals all keep repeat/action provenance
on exact transition variants. Trace events carry the same boundary directly
through exact rewritten/returned variants.
Executable rule counts are non-zero by type, and parsed rule positions are
stored topology witnesses rather than iterator-derived numbers. (once) is
represented by concrete rule variants, and each execution moves matching
once-only runtime cells from fresh variants to consumed variants.
The exact typestate names, transition variants, tracing events, and error variants are documented in rustdoc.
A program source is a byte sequence containing one rewrite rule per non-empty code line:
lhs=rhs
Each line is parsed in this order:
#starts a comment. Everything from#to the end of the line is ignored.- Non-ASCII bytes are rejected in the remaining code part.
- ASCII whitespace in the code part is removed completely.
- Remaining non-whitespace code bytes must be printable ASCII.
- Empty compact code is ignored.
- Non-empty compact code must contain exactly one
=. - The left side and right side are parsed as compact rule syntax.
Examples:
a=b# this is parsed as a=b
#a=b this whole line is a comment
a b = b b # this is parsed as ab=bb
Comments may contain arbitrary non-ASCII or non-UTF-8 bytes when source is
provided through parse_bytes. Executable code outside comments must be ASCII.
ASCII control bytes are invalid in executable code except for ASCII whitespace
that is removed during compaction.
Parse error columns are one-based byte positions in the original source line before whitespace compaction. Diagnostics point at the user's source text, not at the internal compacted representation.
The following characters are reserved in program code:
= # ( )
Their meanings are fixed:
=separates the left side from the right side.#starts a comment.(and)are only allowed as part of supported modifier/action tokens.
A second = in compact code is a parse error:
a=b=c
A second = inside a comment is ignored:
a=b#=c
Reserved syntax where payload data is expected is always a parse error:
a=b(
a=b)
a=b()
a=()
a=b(start)
a=(once)b
a(once)=b
Because whitespace is removed from program code, spaces cannot be represented as
rule data. Because =, #, (, and ) are reserved, program payloads also
refuse them as rule data.
Runtime input is different. Input bytes are runtime data, not program code. Input must be ASCII, but it may contain whitespace, ASCII control bytes, and reserved characters. Ordinary rewrite actions cannot match, create, or delete those bytes directly.
program: a=b
input: a=()#c
output: b=()#c
Rules cannot match across preserved runtime-only bytes:
program: ab=bb
input: a bc
output: a bc
(return) stops execution and replaces the final output with its return
payload, so runtime-only input bytes are not preserved after a matching return
rule:
program: a=(return)x
input: a=()#c
output: x
The left side may start with one repeat modifier and one anchor modifier:
(once): the rule may be used at most once per runtime execution.(start): the rule only matches at the start of the current state.(end): the rule only matches at the end of the current state.
Supported modifier order is (once) first, then an optional anchor. Duplicated
or unsupported left-side modifier order is a parse error.
Examples:
a=b
(once)a=b
(start)a=b
(end)a=b
(once)(start)a=b
Because code whitespace is ignored, this is also valid and equivalent to
(once)(start)a=b:
( once ) ( start ) a = b
The right side selects the action for a matching rule:
text: replace the matched left side withtext.(start)text: remove the match and inserttextat the start of the state.(end)text: remove the match and appendtextto the end of the state.(return)text: stop execution immediately and outputtext, discarding the current runtime state.
The action payload is still program data, so it cannot contain whitespace,
reserved characters, non-ASCII bytes, or ASCII control bytes. (return) can
therefore output only program-representable bytes, even if the discarded runtime
state contained spaces or reserved characters from the original input.
Examples:
a=b
x=(start)y
x=(end)y
x=(return)y
The left side and right side may be empty.
An empty right side deletes the matched left side:
a=
An empty left side matches an empty byte sequence. For unanchored rules and
(start) rules, it matches at the start of the current state:
(once)=x
With input ab, this inserts x at the start and produces xab.
For (end) rules, an empty left side matches at the end of the current state:
(once)(end)=x
With input ab, this inserts x at the end and produces abx.
An unanchored empty-left rule without (once), (return), or some later rule
that makes execution stop can rewrite forever until the step limit is reached.
That is legal syntax; execution remains governed by the selected
ExecutionPolicy.
Execution is ordered and single-step.
On each step, the runtime scans rules from top to bottom and applies the first rule that matches the current state. For an unanchored non-empty left side, the leftmost match in the current state is used. After one applied step, scanning restarts from the first rule.
Example:
program:
aa=x
a=y
input:
aaaa
output:
xx
The first rule is preferred over the second rule, and each application rewrites
the leftmost matching aa.
Program source and runtime input are deliberately different byte domains:
- Program code is compact printable ASCII syntax.
- ASCII whitespace in program code is ignored before parsing.
#starts a comment for the rest of the source line.- Comments may contain non-ASCII or non-UTF-8 bytes.
- Executable code outside comments must be ASCII.
- Program payloads cannot contain whitespace,
=,#,(,), non-ASCII bytes, or ASCII control bytes. - Runtime input is ASCII data and may contain spaces, ASCII control bytes, and reserved syntax bytes.
- Normal rewrites preserve runtime-only bytes that program code cannot construct or match.
(return)stops execution and replaces the whole output with its return payload.
Internally, parser and runtime phases stay separate instead of passing raw byte buffers through every stage:
raw line bytes
-> RawSourceLine
-> CodeLine # comment removed, executable code ASCII validated
-> CompactCodeLine # whitespace removed, SourceColumn retained
-> NonEmptyCompactCodeLine # empty compact lines cannot enter rule parsing
-> RuleSyntaxLine # exactly one '=' has been proven
-> LeftSyntax / RightSyntax
-> ProgramByte # bytes that program code may construct and match
runtime input bytes
-> AsciiByte # runtime input domain validation
-> RuntimeByte # private ProgramConstructible(ProgramByte) or Opaque(NonProgramAsciiByte)
-> execution session # consumes RuntimeInput and owns mutable execution state
Program payloads are stored as ProgramByte, not raw u8. Runtime state is
stored as RuntimeByte: payload-compatible input and rule output become
editable program bytes, while whitespace, control bytes, and reserved syntax
bytes from input become opaque ASCII bytes. Ordinary rules match only editable
bytes. Opaque input bytes are preserved by surrounding rewrites but cannot be
directly matched, created, or deleted by program payloads.
Public observation crosses explicit materialization boundaries. Runtime state
views materialize to snapshots only when requested, stable run results own final
state bytes, (return) outputs use a separate return-output domain, parsed
payload inspection materializes explicitly, and snapshot tracing has its own
byte limit. During execution, the active state and rewrite scratch buffer remain
separate typed buffers until a successful continuation step commits.
(once) rules are recorded as concrete parsed rule variants. Each execution
builds fresh once-only runtime rule cells, and only a committed application can
move the matched cell into its consumed variant.
The library crate is #![no_std] and uses alloc only at owned-buffer
boundaries such as parsed rules, runtime input validation, per-rule runtime state,
run results, canonical rule source, explicit view materialization, and trace
snapshots. It requires an allocator, but not std.
Allocation is explicit and fallible. Parser/runtime paths reserve explicitly
and report AllocationError instead of relying on accidental Vec growth.
Runtime expansion is budgeted through the selected ExecutionPolicy; the
runtime checks size limits before allocating oversized states or return outputs.
Step budget is reserved before rewrite or return-output materialization, so an
exhausted step limit cannot allocate a candidate state or return buffer. Trace
snapshot materialization is budgeted separately through TraceSnapshotPolicy.
Owned public values that contain byte buffers intentionally do not implement
Clone; copying bytes is an explicit materialization step, not a hidden
infallible API. Parser payload validation is reported before payload storage
allocation, so invalid source bytes are not hidden behind allocation failures.
A downstream std application can use the library normally. A downstream
no_std application must provide an allocator before calling APIs that
allocate.
The library error model is intentionally split. Parse errors, runtime input
errors, run-admission errors, runtime execution errors, allocation errors, and
trace materialization errors have separate structured types under
rsaeb::error.
Allocation failures preserve the allocation boundary as AllocationContext.
Reservation failures also report a typed RequestedCapacity, so hosts can
distinguish failures while validating input, materializing state views,
building canonical rule source, producing final output, or retaining trace
snapshots without parsing display strings.
Configured byte budgets and step budgets are reported through concrete errors
such as ParseLimitError, RuntimeStateLimitError, ReturnOutputLimitError,
StepLimitError, and RuleAttemptLimitError. Trace snapshot byte limits are
reported through TraceSnapshotError, because snapshot materialization is
outside runtime execution.
Filesystem failures are not part of the library error model. External I/O must
be handled before bytes enter parse_bytes, parse_text, or
RuntimeInputSource::from_bytes.
Run the public documentation and package checks before publishing changes:
rustup target add thumbv7em-none-eabihf
cargo fmt --check
cargo check --lib --no-default-features
cargo check --lib --all-features --target thumbv7em-none-eabihf
cargo clippy --all-targets --all-features -- -D warnings
cargo test --all-targets --all-features
cargo test --doc --all-features
latest_rlib="$(find target/debug/deps -maxdepth 1 -name 'librsaeb-*.rlib' -printf '%T@ %p\n' | sort -nr | awk 'NR == 1 { print $2 }')"
rustdoc --edition=2024 --test README.md -L dependency=target/debug/deps --extern "rsaeb=${latest_rlib}"
RUSTDOCFLAGS="-D warnings" cargo doc --all-features --no-deps
cargo package --list
cargo package