oxeon 0.0.6

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};

/// Field types a binding can use as they are (structs of them are declared
/// too): 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 mods are compiled with: Bevy's types, then
    /// [`OxeonBindings::declarations`].
    pub prelude: String,
    /// Oxeon declarations for the game's exposed types only, as written to
    /// the bindings file editors read (see `OxeonPlugin::bindings_file`).
    pub declarations: String,
    /// Exposed component types by their name in Oxeon.
    pub components: HashMap<String, TypeId>,
    /// Exposed message types by their name in Oxeon.
    pub messages: HashMap<String, TypeId>,
}

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

/// Message types the game opted in with
/// [`crate::OxeonAppExt::expose_message_to_mods`].
#[derive(Resource, Default)]
pub(crate) struct ExposedMessages(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],
    messages: &[TypeId],
) -> (OxeonBindings, Vec<String>) {
    let mut bindings = OxeonBindings {
        prelude: oxeon_compiler::bevy_prelude().to_owned(),
        declarations: String::new(),
        components: HashMap::new(),
        messages: HashMap::new(),
    };
    let mut problems = Vec::new();
    // Structs used as fields (`Vec3` in `Transform`), declared once, by
    // name, with their type paths.
    let mut declared: HashMap<String, &'static str> = HashMap::new();
    let kinds = exposed
        .iter()
        .map(|id| (id, false))
        .chain(messages.iter().map(|id| (id, true)));
    for (id, is_message) in kinds {
        let Some(registration) = registry.get(*id) else {
            continue;
        };
        let info = registration.type_info();
        let name = info.type_path_table().short_path().to_owned();
        if !is_message && 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 mut nested = String::new();
        // A type that can't be exposed declares nothing, nested types included.
        let before = declared.clone();
        let declaration = declare(info, &mut declared, &mut nested);
        if declaration.is_err() {
            declared = before;
        }
        match declaration {
            Ok(text) => {
                let declaration = format!("{nested}/// The game's `{name}`.\n{text}");
                bindings.prelude.push_str(&declaration);
                bindings.declarations.push_str(&declaration);
                if is_message {
                    bindings.messages.insert(name, *id);
                } else {
                    bindings.components.insert(name, *id);
                }
            }
            Err(why) => problems.push(format!("`{name}` can't be exposed to mods yet: {why}")),
        }
    }
    (bindings, problems)
}

/// The Oxeon declaration of an exposed type's fields: numbers, `bool`,
/// `char`, and structs of those, whose own declarations go into `nested`
/// (each once).
fn declare(
    info: &'static TypeInfo,
    declared: &mut HashMap<String, &'static str>,
    nested: &mut String,
) -> Result<String, String> {
    let name = info.type_path_table().short_path();
    let mut field_ty = |type_path: &str,
                        info: Option<&'static TypeInfo>|
     -> Result<String, String> {
        if let Ok(p) = primitive(type_path) {
            return Ok(p.to_owned());
        }
        let Some(info @ (TypeInfo::Struct(_) | TypeInfo::TupleStruct(_))) = info else {
            return Err(format!(
                "its field of type `{type_path}` isn't a number, `bool`, `char` or a struct of those"
            ));
        };
        if info.generics().iter().next().is_some() {
            return Err(format!("its field of type `{type_path}` is generic"));
        }
        let short = info.type_path_table().short_path().to_owned();
        // Bevy's math types are in the prelude, with their methods.
        if PRELUDE_TYPES.contains(&info.type_path()) {
            return Ok(short);
        }
        match declared.get(&short) {
            Some(path) if *path == info.type_path() => {}
            Some(path) => {
                return Err(format!(
                    "its field of type `{type_path}` has the same name as `{path}`, which is exposed too"
                ));
            }
            None => {
                declared.insert(short.clone(), info.type_path());
                let text = declare(info, declared, nested)?;
                nested.push_str(&format!("/// The game's `{short}`.\n{text}"));
            }
        }
        Ok(short)
    };
    // Mods can log every type the game gives them.
    let derive = if COPY_TYPES.contains(&info.type_path()) {
        "#[derive(Clone, Copy, Debug)]\n"
    } else {
        "#[derive(Debug)]\n"
    };
    let extras = extras(info.type_path());
    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| {
                field_ty(f.type_path(), f.type_info())
                    .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| field_ty(f.type_path(), f.type_info()).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()),
    }?;
    Ok(format!("{derive}{declaration}{extras}"))
}

/// Bevy's math types, which the prelude declares with glam's methods.
const PRELUDE_TYPES: &[&str] = &["glam::Vec2", "glam::Vec3", "glam::Vec4", "glam::Quat"];

/// Game types that are `Copy` in Rust, so they are in mods too.
const COPY_TYPES: &[&str] = &["bevy_transform::components::transform::Transform"];

/// Methods a type has in Rust that mods get too, for the types they need.
fn extras(type_path: &str) -> &'static str {
    match type_path {
        "bevy_transform::components::transform::Transform" => TRANSFORM,
        _ => "",
    }
}

/// Bevy's `Transform` methods.
const TRANSFORM: &str = r#"impl Transform {
    /// No translation or rotation, and a scale of 1.
    pub const IDENTITY: Transform = Transform { translation: Vec3::ZERO, rotation: Quat::IDENTITY, scale: Vec3::ONE };
    /// At this position.
    pub fn from_xyz(x: f32, y: f32, z: f32) -> Transform { Transform::from_translation(Vec3::new(x, y, z)) }
    /// At this position.
    pub fn from_translation(translation: Vec3) -> Transform { Transform { translation, rotation: Quat::IDENTITY, scale: Vec3::ONE } }
    /// With this rotation.
    pub fn from_rotation(rotation: Quat) -> Transform { Transform { translation: Vec3::ZERO, rotation, scale: Vec3::ONE } }
    /// With this scale.
    pub fn from_scale(scale: Vec3) -> Transform { Transform { translation: Vec3::ZERO, rotation: Quat::IDENTITY, scale } }
    /// The same, at another position.
    pub fn with_translation(self, translation: Vec3) -> Transform { Transform { translation, rotation: self.rotation, scale: self.scale } }
    /// The same, with another rotation.
    pub fn with_rotation(self, rotation: Quat) -> Transform { Transform { translation: self.translation, rotation, scale: self.scale } }
    /// The same, with another scale.
    pub fn with_scale(self, scale: Vec3) -> Transform { Transform { translation: self.translation, rotation: self.rotation, scale } }
    /// Rotates by `rotation`, around the transform's origin.
    pub fn rotate(&mut self, rotation: Quat) { self.rotation = rotation * self.rotation; }
    /// Rotates around the x axis.
    pub fn rotate_x(&mut self, angle: f32) { self.rotate(Quat::from_rotation_x(angle)); }
    /// Rotates around the y axis.
    pub fn rotate_y(&mut self, angle: f32) { self.rotate(Quat::from_rotation_y(angle)); }
    /// Rotates around the z axis (a 2D rotation).
    pub fn rotate_z(&mut self, angle: f32) { self.rotate(Quat::from_rotation_z(angle)); }
    /// Rotates by `rotation`, around its own axes.
    pub fn rotate_local(&mut self, rotation: Quat) { self.rotation = self.rotation * rotation; }
    /// Rotates around its own z axis.
    pub fn rotate_local_z(&mut self, angle: f32) { self.rotate_local(Quat::from_rotation_z(angle)); }
    /// Where `point`, in the transform's own space, is.
    pub fn transform_point(&self, point: Vec3) -> Vec3 { self.rotation * (self.scale * point) + self.translation }
    /// Its own x axis (its right).
    pub fn local_x(&self) -> Vec3 { self.rotation * Vec3::X }
    /// Its own y axis (its up).
    pub fn local_y(&self) -> Vec3 { self.rotation * Vec3::Y }
    /// Its own z axis (its back).
    pub fn local_z(&self) -> Vec3 { self.rotation * Vec3::Z }
    /// Its forward direction: its own negative z axis.
    pub fn forward(&self) -> Vec3 { -self.local_z() }
    /// Its back direction.
    pub fn back(&self) -> Vec3 { self.local_z() }
    /// Its up direction.
    pub fn up(&self) -> Vec3 { self.local_y() }
    /// Its down direction.
    pub fn down(&self) -> Vec3 { -self.local_y() }
    /// Its right direction.
    pub fn right(&self) -> Vec3 { self.local_x() }
    /// Its left direction.
    pub fn left(&self) -> Vec3 { -self.local_x() }
}
"#;

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`"))
}