rhaiper
The Rhai Reaper. A minifier for Rhai scripts, with Source Map v3 output.
Rhai scripts shipped to embedded targets sit in flash as raw text, where comments and indentation
are pure overhead. rhaiper strips them and records where every surviving token came from, so a
runtime error the device reports against the minified script can be traced back to the line you
actually wrote.
$ rhaiper stats sensor.rhai
total 645
code 240 37.2%
comments 314 48.7%
whitespace 91 14.1%
minified 250 38.8%
$ rhaiper minify sensor.rhai -o sensor.min.rhai --source-map sensor.min.rhai.map
645 -> 250 bytes (395 saved, 61.2%)
Then, when the device reports Variable not found: average (line 2, position 29):
$ rhaiper resolve --map sensor.min.rhai.map --script sensor.min.rhai --line 2 --pos 29
sensor.rhai:26:1
Or pipe a whole log through remap, which rewrites Rhai's line N, position M phrasing in place
and leaves everything else alone:
$ device-log | rhaiper remap --map sensor.min.rhai.map --script sensor.min.rhai
ERROR: Variable not found: average (line 26, position 1 [sensor.rhai])
Correctness
The interesting part of a minifier is not what it removes, it is how you know it removed only that.
Every call re-lexes its own output and requires the token stream to be identical to the input's. A
script that would not survive the round trip is never emitted — you get an error instead. That check
is what lets the whitespace logic be merely conservative rather than provably complete: separators
are decided by actually re-lexing each token boundary and confirming the first token still ends
where it did, so hazards like - + -1 forming the reserved -- are caught without anyone having
to enumerate them.
Rhai's own lexer does the tokenizing, via the internals feature, so there is no second
implementation of Rhai's lexical rules to drift out of sync.
Other invariants, all enforced by the test suite: tokens must tile the source with only whitespace
between them; minification must be idempotent; output must never grow; output must not depend on how
the input was formatted; and every emitted token must map back through the source map to its origin.
The suite runs over Rhai's own script corpus, vendored in crates/rhaiper/tests/corpus/, which
minifies from 17143 to 10183 bytes (40%).
Line wrapping is not cosmetic
Rhai's Position stores its column as a u16 and saturates on overflow, so on a single-line
output every character past column 65535 reports as column 65535 — which would destroy exactly the
error positions a source map exists to recover. Output is therefore wrapped, 200 characters by
default (--max-line-len). A newline is legal between any two tokens, so this costs one byte per
line.
Source maps
Standard Source Map v3, readable by any tooling that understands the format.
One subtlety is handled for you: the v3 specification counts columns in UTF-16 code units, while
Rhai counts them in characters. Stored columns follow the specification; resolve takes and returns
Rhai's 1-based character columns. The two only differ on lines containing astral-plane characters
such as emoji, which is why resolve and remap accept --script — the minified text is needed to
convert between the units. For an all-ASCII script it can be omitted.
crates/rhaiper-map is a separate no_std crate that resolves positions from the mappings string
alone, so firmware can embed that one field rather than a whole JSON document. It builds for bare
metal (verified against thumbv8m.main-none-eabi).
Renaming local variables
Off by default. With --rename, local bindings are shortened:
fn to_millivolts(raw) {
let scale = 3300.0 / 4095.0;
raw * scale
}
fn to_millivolts(b){let a=3300.0/4095.0;b*a}
Renamed: locals, loop variables and counters, catch bindings, and function and closure parameters.
Never renamed, because the host can reach them by name and the script text cannot show it:
top-level let/const (readable through a Scope and as global::NAME), function names
(Engine::call_fn dispatches by string), properties and map keys (string data, not variables), and
any name the script never declares.
Renaming is also declined for the whole script, with a printed reason, when the script does
anything that resolves names at runtime — eval, is_def_var, is_def_fn, Fn("name"),
foo!(...) parent-scope calls, get_fn_metadata_list, or an unrecognized custom keyword. You do
not have to work out whether your script qualifies.
The same applies to syntax this tool cannot account for. Stmt and Expr are #[non_exhaustive]
in Rhai, so a future release may add nodes this code cannot see; every identifier token must be
explained by some rule, and anything left over declines renaming. Unknown syntax costs compression,
never correctness.
Because top-level bindings are left alone, renaming only pays off in scripts that put their logic in functions. On a function-heavy script it is worth a few percent on top of the safe pass; on top-level-heavy code it does close to nothing.
Library use
use ;
let out = minify?;
write?;
write?;
If your host registers custom syntax or custom operators, a stock engine cannot parse the script at all — pass the engine the script will actually run under:
let out = minify_with_engine?;
Set OptimizationLevel::None on that engine when renaming, so the optimizer does not fold
declarations away before the scope analysis sees them.
Rhai feature configurations
Rhai's feature flags remove language features and, with them, parts of its API. Cargo unifies features across the dependency graph, so whatever you enable, rhaiper is compiled against that rhai. It is built to cope with all of them.
Almost everything needs nothing from you. no_closure, no_object, no_index, no_module,
no_custom_syntax, no_position, metadata, sync, debugging, decimal, unicode-xid-ident
and the numeric flags all just work: rhaiper avoids naming the API those features remove, rather than
relying on you to declare anything.
Three features remove API rhaiper genuinely calls, so enable the matching rhaiper feature alongside them. The names are identical on purpose:
| If you enable | Also enable | Why |
|---|---|---|
rhai/no_optimize |
rhaiper/no_optimize |
set_optimization_level and its argument type are both gone |
rhai/unchecked |
rhaiper/unchecked |
set_max_expr_depths is gone, and no limits exist to raise |
rhai/no_function |
rhaiper/no_function |
AST::iter_fn_def and ScriptFuncDef::body are gone |
= { = "1.25", = ["no_optimize"] }
= { = "0.2", = ["no_optimize"] }
Forgetting one is a compile error, not silent misbehaviour — which is why these are plain feature flags rather than something cleverer that could quietly degrade.
Two behavioural notes:
no_position— minification and source maps work normally, because spans come from the byte cursor and generated positions are counted by the emitter. Renaming cannot, since rhai's AST is the only source of the positions it needs, so it declines and says so. Detected at runtime; no feature flag needed.metadata— rhai swallows//!module comments into its own metadata rather than returning them as tokens. rhaiper reconstructs them so they are still stripped and still counted bystats.
rhai/no_std on a std target is not supported or tested.
CI runs a matrix over every one of these, plus two combined profiles, compiling a stand-in consumer crate and running the shared behavioural tests under each — because compiling is not the same as still working.
Relationship to Engine::compact_script
Rhai ships Engine::compact_script, which also strips comments and whitespace. It was not usable as
a basis for this tool:
- It returns only a
String. Positions are discarded and there is no hook to build a map from. - It emits a single line, which triggers the
u16column saturation described above. - It produces
a--1fora - -1, which does not parse. A negative literal carries its own-in its recorded text, and the spacing rule only separates identifier characters. Same fora + +1. - It truncates raw strings:
#"raw \n text"#comes back as#", silently losing the body.
The last two are pinned as regression tests in crates/rhaiper/tests/differential.rs, which will
start failing if upstream fixes them.
Not done
;immediately after a block-closing}is not elided. Knowing whether it is redundant requires knowing whether that}closed a statement or an expression —let x = #{a:1};andlet x = { 1 };look identical to the tokenizer.- No constant folding, dead-code elimination, or numeric literal shortening. None of them can be checked by the token-equivalence invariant, which is what makes the rest trustworthy.
- Renaming does not reuse one short name across disjoint scopes; every binding gets a distinct name, which compresses slightly worse but makes shadowing impossible to get wrong.
Building
cargo test # all invariants
cargo build -p rhaiper-map --target thumbv8m.main-none-eabi # no_std resolver
Requires Rust 1.88 or newer — 1.85 for edition 2024, 1.88 for one let-chain — which CI checks
against that exact toolchain. rhai is used with the internals feature; no_position must not be
enabled, since it compiles Position down to a zero-sized stub and makes source maps meaningless.
License
Copyright (c) 2026 Jack Hogan.
Dual-licensed under either of Apache-2.0 or MIT, at your option.
The scripts in crates/rhaiper/tests/corpus/ are copied from the Rhai project under the same terms;
see ATTRIBUTION.md.