Rhai Grain
Rhai Grain is a bytecodes transpiler and VM for Rhai scripts.
It is only available under the grain feature.
See documentation on Rhai Grain.
When to Use Rhai Grain
Use Rhai Grain when you want to:
-
ship a script without shipping source code,
-
significantly reduce per-script memory and CPU costs on constrained devices,
-
run faster than the standard Rhai interpreter,
-
avoid keeping an
ASTresident, -
run the same script on a second Rhai instance without reparsing it.
Use the normal AST for the most straight-forward developer experience, including
debugging, when the script source is available, or when the script
is short-lived and compiled just once in-process.
Rhai Grain is most valuable when a script is treated as an artifact: transpiled into bytecodes once, serialized once, validated once and then executed many times directly on a target machine.
Caveats
-
Program::writeonly succeeds whenProgram::residual_countis zero. -
Anything that fails to transpile is kept as an
ASTfragment and interpreted by Rhai. -
Program::write_strippedis for shipping bytecodes plus a host-sideSidecarfor diagnostics.
Unsupported Features
Rhai Grain does not support every feature of the language.
When the transpiler fails, it preserves that part as a residual AST fragment and hands it back
to Rhai for processing.
They include:
-
eval! -
custom syntax which modifies the
Scope -
custom syntax which contains a
return,continueorbreakstatement that affects an outer loop -
custom types recorded as constants – this usually only occur under
OptimizationLevel::Full.
Check Program::residual_count() to see how many residual AST fragments exist.
If it is non-zero, the program still runs, but parts of it will fall back
to Rhai’s normal AST evaluation path.