oxeon 0.0.4

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();
        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)
    };
    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()),
    }
}

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