oxeon 0.0.2

Rust-like scripting language for modding Bevy games, compiled to sandboxed WebAssembly.
Documentation
//! Oxeon declarations for the game's types, generated from Bevy's type
//! registry. Mods are compiled together with them, so they see the game's
//! components as if they had declared them.

use std::any::TypeId;
use std::collections::HashMap;

use bevy_ecs::prelude::*;
use bevy_ecs::reflect::ReflectComponent;
use bevy_reflect::{TypeInfo, TypeRegistry};

/// The game's clock. The host fills it from Bevy's `Time` before each call.
const TIME: &str = "\
/// The game's clock (Bevy's `Time`).
pub struct Time { delta: f32, elapsed: f32 }
impl Time {
    /// Seconds since the previous frame.
    pub fn delta_secs(&self) -> f32 { self.delta }
    /// Seconds since the game started.
    pub fn elapsed_secs(&self) -> f32 { self.elapsed }
}
";

/// Field types a binding can use: those with a fixed memory layout.
const PRIMITIVES: &[&str] = &[
    "f32", "f64", "i8", "i16", "i32", "i64", "u8", "u16", "u32", "u64", "isize", "usize", "bool",
    "char",
];

/// The declarations mods are compiled with, and the types behind them.
#[derive(Resource, Default, Clone)]
pub struct OxeonBindings {
    /// Oxeon source declaring the exposed types.
    pub prelude: String,
    /// Exposed component types by their name in Oxeon.
    pub components: HashMap<String, TypeId>,
}

/// Types the game opted in with [`crate::OxeonAppExt::expose_to_mods`].
#[derive(Resource, Default)]
pub(crate) struct ExposedTypes(pub Vec<TypeId>);

/// Builds bindings for `exposed` types. Returns problems with types that
/// can't be exposed (they're left out).
pub(crate) fn generate(
    registry: &TypeRegistry,
    exposed: &[TypeId],
) -> (OxeonBindings, Vec<String>) {
    let mut bindings = OxeonBindings {
        prelude: TIME.to_owned(),
        components: HashMap::new(),
    };
    let mut problems = Vec::new();
    for id in exposed {
        let Some(registration) = registry.get(*id) else {
            continue;
        };
        let info = registration.type_info();
        let name = info.type_path_table().short_path().to_owned();
        if registration.data::<ReflectComponent>().is_none() {
            problems.push(format!(
                "`{name}` is exposed to mods but isn't reflected as a component; add `#[reflect(Component)]`"
            ));
            continue;
        }
        let declaration = match info {
            TypeInfo::Struct(s) if s.field_len() == 0 => Ok(format!("pub struct {name};\n")),
            TypeInfo::Struct(s) => s
                .iter()
                .map(|f| {
                    primitive(f.type_path()).map(|ty| format!("    pub {}: {ty},\n", f.name()))
                })
                .collect::<Result<String, String>>()
                .map(|fields| format!("pub struct {name} {{\n{fields}}}\n")),
            TypeInfo::TupleStruct(s) => s
                .iter()
                .map(|f| primitive(f.type_path()).map(|ty| format!("pub {ty}")))
                .collect::<Result<Vec<String>, String>>()
                .map(|fields| format!("pub struct {name}({});\n", fields.join(", "))),
            _ => Err("it isn't a struct".to_owned()),
        };
        match declaration {
            Ok(text) => {
                bindings
                    .prelude
                    .push_str(&format!("/// The game's `{name}` component.\n{text}"));
                bindings.components.insert(name, *id);
            }
            Err(why) => problems.push(format!("`{name}` can't be exposed to mods yet: {why}")),
        }
    }
    (bindings, problems)
}

fn primitive(type_path: &str) -> Result<&str, String> {
    PRIMITIVES
        .iter()
        .find(|p| **p == type_path)
        .copied()
        .ok_or_else(|| format!("its field of type `{type_path}` isn't a number, `bool` or `char`"))
}