Oxeon / Learn

Oxeon language guide

Oxeon is a scripting language for modding games made with the Bevy game engine. It uses Rust’s syntax and semantics. Mods are .ox files: the game loads them as Bevy assets, the Oxeon compiler turns them into WebAssembly, and they run sandboxed in Wasmtime inside the game’s process. A mod’s systems use Bevy’s own ECS, with the same Query, Res and schedules as the game’s Rust code.

Oxeon is open source (MIT or Apache-2.0) and in early development. This guide describes the language as it works today and marks the parts that are still planned.

At a glance

What it isA Rust-like language for writing mods for Bevy games
File extension.ox
Compiles toWebAssembly, run by Wasmtime with fuel limits (or, in a game built for the web, by the browser’s own engine)
Used from a game throughThe oxeon crate, a Bevy plugin (OxeonPlugin)
Bevy version0.20
Implemented inRust
LicenseMIT OR Apache-2.0
Source codegithub.com/kcuwashere/oxeon
Editor supportA VS Code extension (oxeon.oxeon) and a language server (oxeon-lsp)
StatusEarly development (version 0.0.x); not ready for production use

Oxeon isn’t a Rust compiler, and it can’t use crates from crates.io. A mod can use the language, its small built-in prelude, and whatever types the game exposes. Oxeon is an independent project, not affiliated with or endorsed by the Bevy project.

A first mod

The game adds the plugin and chooses which of its components mods may use:

src/main.rs
use bevy::prelude::*;
use oxeon::prelude::*;

#[derive(Component, Reflect)]
#[reflect(Component)]
struct Health {
    current: f32,
    max: f32,
}

#[derive(Component, Reflect)]
#[reflect(Component)]
struct Regen {
    per_sec: f32,
}

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_plugins(OxeonPlugin::default())
        .expose_to_mods::<Health>()
        .expose_to_mods::<Regen>()
        .add_systems(Startup, load_mods)
        .run();
}

fn load_mods(mut commands: Commands, assets: Res<AssetServer>) {
    commands.spawn(OxeonMod(assets.load("mods/regen.ox")));
}

The mod uses Health, Regen and Time without declaring them. They come from the game, and the compiler type-checks the mod against their real fields:

assets/mods/regen.ox
// assets/mods/regen.ox
fn regen(time: Res<Time>, mut q: Query<(&mut Health, &Regen)>) {
    for (mut hp, regen) in &mut q {
        if hp.current < hp.max {
            hp.current += regen.per_sec * time.delta_secs();
            if hp.current > hp.max {
                hp.current = hp.max;
            }
        }
    }
}

pub fn plugin(app: &mut App) {
    app.add_systems(Update, regen);
}

Every mod has a pub fn plugin(app: &mut App) entry point, the same shape as a Bevy plugin function. Systems are ordinary functions whose parameters are system parameters, registered with add_systems. The repository has this as a runnable demo: cargo run -p oxeon --example regen.

How a mod runs

  1. Loading. A .ox file is a Bevy asset. Spawning an entity with OxeonMod(handle) loads a mod. The asset loader only reads the source text.
  2. Bindings. Once every plugin is added, Oxeon reads the game’s TypeRegistry and generates Oxeon declarations for each component and resource exposed with expose_to_mods, and each message type exposed with expose_message_to_mods. Nobody writes bindings by hand. An exposed type needs #[derive(Reflect)] (with #[reflect(Component)] or #[reflect(Resource)]), and its fields must be numbers, bool, char, or structs of those, such as Transform with its Vec3 and Quat (declared too). With OxeonPlugin’s bindings_file set, the plugin also writes the bindings to a file, so editors know the game’s types.
  3. Compiling. Each mod is compiled together with the bindings. Errors are reported with source snippets, like rustc’s. An error inside the bindings is reported as a problem with the game, not with the mod.
  4. Running. Each frame, in Update, Oxeon copies the system’s resources, messages and the rows each Query matches into the mod’s WebAssembly memory, converting values through reflection. It calls each system with a fresh fuel budget, then writes back what the system took as &mut (only values that actually changed, so Changed filters stay accurate), sends the messages it wrote and applies its Commands. Startup systems run once each time the mod loads.
  5. Failures. A mod that traps or runs out of fuel is disabled, and the game keeps running. A call that fails writes nothing back.
  6. Hot reload. With the hot-reload feature, editing a .ox file recompiles the mod. If the new version has errors, the previous one keeps running. Game state lives in the ECS, so nothing is lost, and components the mod defines are kept if their layout didn’t change.

What works today

Language

  • Integer types, f32, f64, bool and char
  • let, mut, shadowing, assignment and compound assignment (+= and others). Integer arithmetic wraps on overflow, like Rust’s release builds
  • if/else as an expression, while, loop with break values and labels, and for over ranges
  • Functions, constants and const fn
  • Structs (named, tuple and unit), enums whose variants carry data, and tuples, all passed by value; references
  • impl blocks with associated functions and methods
  • match with guards, @ bindings and ranges; if let, while let and let ... else. Every pattern form works except slice patterns
  • Generic functions, structs and enums, compiled once for each set of type arguments they’re used with (monomorphization)
  • Traits, implemented with impl Trait for Type: methods through bounds (T: Shape, T: A + B), default methods, and &dyn Trait for values of different types behind one reference type, with a check that the trait can be used that way
  • Closures, which capture by reference (&, or &mut for variables they change) or by value with move. They can be called directly or passed to generic functions with Fn, FnMut and FnOnce bounds, and their parameter types are inferred from those bounds, so |v| v + 1 needs no annotations
  • Option and Result, with methods such as is_some, unwrap_or, ok_or, ok, map, and_then, map_or, unwrap_or_else, is_some_and and map_err, and the ? operator. ? doesn’t convert errors with From yet, so both sides must have the same error type
  • Bevy’s math types, in every mod: Vec2, Vec3, Vec4 and Quat, with glam’s constants (Vec3::ZERO, Quat::IDENTITY), methods (length, normalize, dot, cross, lerp, Quat::from_rotation_z, slerp, ...) and operators (a + b, v * 2.0, rotation * v). With Transform exposed, mods also get its methods: from_xyz, rotate_z, forward, transform_point and more
  • Operators on your own types, through Rust’s std::ops traits: impl Add for Vec2 { type Output = Vec2; fn add(self, o: Vec2) -> Vec2 { .. } } makes a + b work, and impl Mul<f32> for Vec2 next to impl Mul<Vec2> for Vec2 are told apart by the operand types. += and the other compound assignments use AddAssign and so on, and -v uses Neg
  • Box<T> and Box<dyn Trait>, so a list can own values of different types: Vec<Box<dyn Shape>>. Branches of if and match, and function arguments, become a Box<dyn Trait> where one is expected, as in Rust
  • Vec<T>, with vec![a, b], vec![x; n], push, pop, get, get_mut, first, last, len, is_empty, capacity, clear, indexing (v[i], which traps when out of range) and for x in &v or &mut v. Memory comes from an arena that’s freed after each system call, and each mod’s memory is capped
  • A borrow checker like Rust’s: moves (including partial moves) and Copy types, mut and &mut, and conflicting borrows with non-lexical lifetimes. Its errors appear in the editor as you type
  • Rust’s methods on the primitive types, each compiled to its WebAssembly instruction where there is one: count_ones, leading_zeros, rotate_left, pow, abs, min, max and clamp on integers; sqrt, floor, round, copysign, min, max, is_nan, powi and to_bits on floats
  • The float functions WebAssembly has no instructions for, in software: sin, cos, tan, asin, acos, atan, atan2, exp, exp2, ln, log2, log10, powf, cbrt, hypot, the hyperbolic functions and more. f32 results match Rust’s, and f64 results are within 2 ULP of them
  • panic!, which traps the mod
  • Random numbers, like the rand crate’s: rand::random::<T>() for integers, f32 and f64 (at least 0 and less than 1) and bool; rand::random_range(1..=6) and rand::random_range(-1.0..1.0), with the range written in the call; and rand::random_bool(p). The game seeds them, differently for each mod unless it sets RuntimeConfig::random_seed
  • Traits’ associated functions through a generic bound: T::new(..) in fn make<T: Shape>() -> T, for your own types and for primitive types with an impl
  • Logging with Rust’s format strings: info!, warn!, error!, debug! and trace! go to the game’s log, and println! and eprintln! too. Arguments can be numbers, bool, char, Entity, tuples and structs with #[derive(Debug)] (which includes the game’s types and the math types), with captured variables ("{x}"), positions ({0}), names ({n} with n = ..) and formatting options ({:>8.2}, {:#x}, {:?}, {:#?}). The game formats the message, and it also sees it as a ModLog message. Text arguments and format! need strings, which come later
  • Inline mod blocks and use declarations within a file

Bevy

  • Res<Time> (delta_secs() and elapsed_secs()), and Res<T> and ResMut<T> for the game’s exposed resources
  • Query parameters over exposed components and components the mod defines, such as Query<&mut Health> or Query<(Entity, &mut Health, &Regen)>, iterated with for ... in &mut q or for ... in &q
  • Query filters: With<T>, Without<T>, Changed<T> and Added<T>, alone or in a tuple
  • Commands: commands.spawn(component) or spawn((a, b)), .insert(..), commands.entity(e).insert(..) and commands.entity(e).despawn(), applied after the system returns
  • Messages: MessageReader<M> (for m in reader.read()) and MessageWriter<M> (writer.write(m)), for the game’s exposed message types and for message structs the mod declares. Mods that declare the same message type the same way share it
  • Components defined by the mod with #[derive(Component)]. They become dynamic Bevy components named after the mod
  • Resources defined by the mod with #[derive(Resource)], added in plugin with app.init_resource::<T>() (which needs #[derive(Default)] and starts at zero) or app.insert_resource(T { .. }), and used with Res<T> and ResMut<T>. Only the mod that declares a resource sees it. A hot reload keeps a resource that init_resource added and replaces one that insert_resource added, as in Bevy
  • app.add_systems(Startup, ...) and app.add_systems(Update, ...) in the mod’s plugin function, with one system, a tuple of systems or (a, b).chain(). A system can have no parameters. A mod’s systems run one at a time, not in parallel
  • A fuel limit on every call, disabling of mods that trap, and hot reloading. With OxeonPlugin { restart_on_reload: true, .. }, reloading or removing a mod also despawns what it spawned and removes its resources, so each version starts from scratch, as in the playground
  • Oxeon code from the game (app.add_mod_source(..)): methods on its exposed types, constants and enums, for mods to use
  • Mods from source text instead of files (LoadModSource), for an editor inside the game, with a ModReport message for each: loaded, doesn’t compile, or disabled, and why, and a ModLog message for each line a mod logs

Tools

  • The playground: write mods for a small game and play it in your browser. The compiler, the sandbox, the language server and the game all run on the page
  • The oxeon command-line tool: check (report errors), build (write a .wasm file), run (call one function in the sandbox, as in oxeon run math.ox fib 10, printing what it logs), fmt (format files in place; --check lists the ones that aren’t formatted), plus lex, parse and mir to print the compiler’s intermediate results for debugging. oxeon completions <shell> sets up Tab completion, which also lists a file’s functions for oxeon run
  • oxeon-lsp, a language server with diagnostics, go to definition, find references, completion, rename, hover with types and docs, signature help, inlay hints, semantic tokens and quick fixes. It formats files in Rust’s style (only whitespace changes; lines aren’t joined or split, except to put the braces of a block that spans lines on lines of their own). It knows the built-in prelude and Bevy’s types, and the game’s types from an oxeon-bindings.ox file next to the mod or in a folder above it
  • A VS Code extension, on the VS Code Marketplace and Open VSX, which includes the language server. It formats .ox files when you save them ("[oxeon]": { "editor.formatOnSave": false } turns that off)

When the compiler can’t compile a function yet, it skips it with a note that says why, such as "isn’t compiled to WebAssembly yet: it uses a string". The rest of the mod still compiles.

Not yet implemented

These parts of the design are planned. Code that uses them parses and gets editor support, but doesn’t compile to WebAssembly yet:

  • Strings and slices: &str, String and &[T]
  • Iterators and iterator chains such as (1..=5).map(..).collect()
  • Traits: associated types, supertraits, blanket implementations (impl<T: A> B for T) and impl Trait
  • Lifetimes in signatures. Until then, references returned from functions or stored in structs are checked conservatively
  • Drop
  • Modules in other files (mod name;) and the rest of std, such as HashMap
  • Exhaustiveness checking for match. For now, a value that no arm matches traps at run time
  • In Bevy: components, resources and messages with fields that are enums, strings, Vecs, boxes or references; schedules other than Startup and Update (a mod that uses one gets a warning); run conditions (.run_if(..) is accepted but ignored); and mod systems as real Bevy systems that run in parallel with the game’s
  • Sandbox: per-mod capabilities and a fuel budget per frame
  • Mod state carried across hot reloads, through reflection
  • async/.await, with the host’s executor doing the work
  • Macros: macro_rules!, and procedural macros compiled to WebAssembly that run sandboxed
  • core::arch::wasm32: SIMD and memory intrinsics, with Rust’s names
  • mul_add, which must round once, so it needs a software version
  • Oxeon-only extensions: compile-time evaluation beyond const fn

The examples show what code using these features is meant to look like. Each one says which parts work today.

How Oxeon differs from Rust

  • A subset of Rust. Oxeon’s syntax is a strict subset of Rust’s. A mod that sticks to the core language and the mod API is meant to also compile as a native Bevy plugin, through the oxeon-shim crate.
  • The game’s types come from bindings. A mod doesn’t declare or import the game’s components. It uses them by name, and the compiler gets their definitions from the game’s type registry.
  • No crates. A mod can’t depend on crates from crates.io or link native code. Everything it can reach is the language, its prelude and what the game exposes.
  • Panics don’t unwind. A panic, a trap or running out of fuel stops that one mod, and the game keeps going.
  • Wrapping arithmetic. Integer overflow wraps, as in Rust’s release builds, rather than panicking as in debug builds.
  • Canonical NaNs. NaN values are canonicalized, which removes one source of differences between platforms.
  • Planned extensions that make a file invalid Rust: procedural macros that run sandboxed, and wider compile-time evaluation. They’re opt-in. WebAssembly instructions don’t need one: they’re reached through Rust’s primitive methods and core::arch::wasm32, as in Rust.

Sandbox

  • Isolation. Each mod has its own instance and linear memory: a Wasmtime store natively, a WebAssembly instance in the browser.
  • Fuel. Each call into a mod gets a fuel budget. A mod in an infinite loop runs out of fuel and is disabled, instead of freezing the game. The compiler counts fuel in the module itself, so this works in browsers too, which have no fuel of their own.
  • Capabilities. A mod gets no imports by default. It sees only the components the game exposes and the data passed to its systems. Granting access to other resources, messages, assets, time and randomness per mod is planned.
  • Determinism. Designed in from the start: no ambient time or randomness, and canonical NaNs.

Architecture

.ox source ─lex→ tokens ─parse→ AST ─check→ typed AST ─lower→ MIR ─codegen→ .wasm
                                                                              │
                         Bevy app ── OxeonPlugin ── oxeon-runtime (Wasmtime) ◄┘

The compiler is a set of crates that don’t depend on Bevy: oxeon-syntax (a lexer built with logos and a hand-written parser), oxeon-types (name resolution and type checking), oxeon-mir (a control-flow graph per function), oxeon-codegen (WebAssembly through wasm-encoder, with structured control flow rebuilt using Ramsey’s "Beyond Relooper" algorithm) and oxeon-compiler, which drives them. oxeon-runtime wraps Wasmtime. Only the oxeon crate, the Bevy plugin, depends on Bevy. Keeping Bevy out of the compiler keeps it fast to build, lets the CLI and language server work without Bevy, and confines Bevy’s breaking changes to one crate.

Frequently asked questions

Is Oxeon just Rust? No. It looks like Rust and follows Rust’s semantics, but it’s a separate language with its own compiler, and it runs sandboxed as WebAssembly. Code written for Oxeon uses the game’s exposed types and Oxeon’s prelude, not Rust’s standard library or crates.

Why not embed Lua or another existing scripting language? Mods written in Oxeon are statically typed against the game’s real Bevy types, and they use the same ECS concepts as the game’s own code. Bevy developers don’t need to learn a second language or write bindings by hand.

Can a mod crash or freeze the game? It’s designed not to. A trap, a panic or running out of fuel disables that mod, and the game keeps running.

Can Oxeon be used outside Bevy? Not as a goal. The compiler and runtime don’t depend on Bevy, but the language and its mod API are designed around Bevy’s ECS.

Is it ready for use? Not yet. Mods run in Bevy today with the subset of the language described in What works today. The roadmap tracks the rest.

See the examples →