use std::any::TypeId;
use std::collections::HashMap;
use bevy_ecs::prelude::*;
use bevy_ecs::reflect::ReflectComponent;
use bevy_reflect::{TypeInfo, TypeRegistry};
const PRIMITIVES: &[&str] = &[
"f32", "f64", "i8", "i16", "i32", "i64", "u8", "u16", "u32", "u64", "isize", "usize", "bool",
"char",
];
#[derive(Resource, Default, Clone)]
pub struct OxeonBindings {
pub prelude: String,
pub declarations: String,
pub components: HashMap<String, TypeId>,
pub messages: HashMap<String, TypeId>,
}
#[derive(Resource, Default)]
pub(crate) struct ExposedTypes(pub Vec<TypeId>);
#[derive(Resource, Default)]
pub(crate) struct ExposedMessages(pub Vec<TypeId>);
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();
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 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) => {
let declaration = format!("/// 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)
}
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`"))
}