Skip to content

Commit

Permalink
bring in bms_lua changes
Browse files Browse the repository at this point in the history
  • Loading branch information
makspll committed Nov 10, 2024
1 parent 44f66c3 commit 1a783f3
Show file tree
Hide file tree
Showing 33 changed files with 15,203 additions and 14,429 deletions.
1 change: 1 addition & 0 deletions crates/bevy_api_gen/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ fn default_ignored_types() -> String {
"bevy_reflect::DynamicTuple",
"bevy_reflect::DynamicTupleStruct",
"bevy_reflect::DynamicEnum",
"bevy_reflect::DynamicSet",
"bevy_reflect::OsString", // TODO: once macros allow Vecs for primitives as args remove this from ignored types
]
.join(",")
Expand Down
3 changes: 2 additions & 1 deletion crates/bevy_api_gen/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ impl ReflectType<'_> {

pub(crate) const DEF_PATHS_FROM_LUA: [&str; 2] = ["value::FromLuaMulti", "mlua::FromLuaMulti"];
pub(crate) const DEF_PATHS_INTO_LUA: [&str; 2] = ["value::IntoLuaMulti", "mlua::IntoLuaMulti"];
pub(crate) const DEF_PATHS_REFLECT: [&str; 2] = ["bevy_reflect::Reflect", "reflect::Reflect"];
pub(crate) const DEF_PATHS_REFLECT: [&str; 2] =
["bevy_reflect::PartialReflect", "reflect::PartialReflect"];
pub(crate) const DEF_PATHS_GET_TYPE_REGISTRATION: [&str; 2] = [
"bevy_reflect::GetTypeRegistration",
"reflect::GetTypeRegistration",
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_api_gen/templates/footer.tera
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pub struct {{ "ScriptingPlugin" | prefix_cratename | convert_case(case="upper_ca
impl bevy::app::Plugin for {{ "ScriptingPlugin" | prefix_cratename | convert_case(case="upper_camel")}} {
fn build(&self, app: &mut bevy::prelude::App) {
{% for item in items %}
app.register_proxy::<{{ item.import_path }}>();
app.register_lua_proxy::<{{ item.import_path }}>();
{% endfor %}
app.add_context_initializer::<()>({{ "ContextInitializer" | prefix_cratename | convert_case(case="snake") }});
app.add_documentation_fragment(
Expand Down
4 changes: 2 additions & 2 deletions crates/bevy_api_gen/templates/header.tera
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use super::{{crate}}::*;
use bevy_mod_scripting_core::{AddContextInitializer, StoreDocumentation, bindings::ReflectReference};

{% if args.self_is_bms_lua %}
use crate::{bindings::proxy::{LuaReflectRefProxy,LuaReflectRefMutProxy,LuaReflectValProxy,LuaValProxy,IdentityProxy},RegisterLuaProxy, tealr::mlu::mlua::IntoLua};
use crate::{bindings::proxy::{LuaReflectRefProxy,LuaReflectRefMutProxy,LuaReflectValProxy,LuaValProxy,LuaIdentityProxy},RegisterLua, tealr::mlu::mlua::IntoLua};
{% else %}
use bevy_mod_scripting::{lua::bindings::proxy::{LuaReflectRefProxy,LuaReflectRefMutProxy,LuaReflectValProxy,LuaValProxy,IdentityProxy}, RegisterLuaProxy, tealr::mlu::mlua::IntoLua};
use bevy_mod_scripting::{lua::bindings::proxy::{LuaReflectRefProxy,LuaReflectRefMutProxy,LuaReflectValProxy,LuaValProxy,LuaIdentityProxy}, RegisterLua, tealr::mlu::mlua::IntoLua};
{% endif %}
2 changes: 1 addition & 1 deletion crates/bevy_api_gen/templates/item.tera
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
{% set bms_lua_path="bevy_mod_scripting::lua" %}
{% endif %}

#[derive(bevy_mod_scripting_lua_derive::LuaProxy)]
#[derive(bevy_mod_scripting_derive::LuaProxy)]
#[proxy(
remote="{{ item.import_path }}",
bms_core_path="{{bms_core_path}}",
Expand Down
10 changes: 4 additions & 6 deletions crates/bevy_api_gen/templates/macros.tera
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{% macro vector_index(num_type) %}
#[lua(metamethod="Index")]
fn index(self, idx: usize) -> IdentityProxy<{{ num_type }}> {
fn index(self, idx: usize) -> LuaIdentityProxy<{{ num_type }}> {
_self[idx - 1]
}
{% endmacro vector_index %}
Expand All @@ -14,15 +14,13 @@ fn index(&mut self, idx: usize, val: {{ num_type }}) -> () {

{% macro matrix_index(col_type, mat_type, bms_core_path) %}
#[lua(metamethod="Index")]
fn index(_self: IdentityProxy<Self>, idx: usize) -> IdentityProxy<{{ col_type | prefix_lua }}> {
fn index(_self: LuaIdentityProxy<Self>, idx: usize) -> LuaIdentityProxy<{{ col_type | prefix_lua }}> {
let mut curr_ref = _self.0.clone();
let def_ref = {{bms_core_path}}::bindings::DeferredReflection{
get: std::sync::Arc::new(|ref_| Err(bevy::reflect::ReflectPathError::InvalidDowncast)),
get_mut: std::sync::Arc::new(move |ref_| {
if ref_.is::<bevy::math::{{ mat_type }}>(){
Ok(ref_.downcast_mut::<bevy::math::{{ mat_type }}>()
.unwrap()
.col_mut(idx - 1))
if let Some(ret) = ref_.try_as_reflect_mut().map(|ret| ret.downcast_mut::<bevy::math::{{ mat_type }}>()).flatten(){
Ok(ret.col_mut(idx - 1))
} else {
Err(bevy::reflect::ReflectPathError::InvalidDowncast)
}
Expand Down
31 changes: 31 additions & 0 deletions crates/bevy_mod_scripting_derive/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
[package]
name = "bevy_mod_scripting_derive"
version = "0.6.0"
authors = ["Maksymilian Mozolewski <[email protected]>"]
edition = "2021"
license = "MIT OR Apache-2.0"
description = "Necessary functionality for Lua support with bevy_mod_scripting"
repository = "https://github.com/makspll/bevy_mod_scripting"
homepage = "https://github.com/makspll/bevy_mod_scripting"
keywords = ["bevy", "gamedev", "scripting", "rhai"]
categories = ["game-development"]
readme = "readme.md"

[lib]
name = "bevy_mod_scripting_derive"
path = "src/lib.rs"
proc-macro = true

[dependencies]
paste = "1.0.7"
darling = "0.20.3"
syn = { version = "2.0.38", features = ["full", "fold", "extra-traits"] }
quote = "1.0.8"
proc-macro2 = "1.0"
convert_case = "0.5.0"
rustdoc-types = "0.11.0"
serde = { version = "1.0", features = ["derive"] }
serde_derive = "1.0.137"
indexmap = { version = "1.9.1", features = ["serde"] }
strum = { version = "0.24.1", features = ["derive"] }
vec1 = "1.10.1"
3 changes: 3 additions & 0 deletions crates/bevy_mod_scripting_derive/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# bevy_mod_scripting_lua_derive

This crate is a part of the ["bevy_mod_scripting" workspace](https://github.com/makspll/bevy_mod_scripting).
115 changes: 115 additions & 0 deletions crates/bevy_mod_scripting_derive/src/input.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
use darling::{util::Flag, FromDeriveInput, FromMeta};
use proc_macro2::Ident;
use std::ops::{Deref, DerefMut};
use syn::{spanned::Spanned, visit_mut::VisitMut, Attribute, Field, TraitItemFn, Variant};

#[derive(FromMeta)]
pub struct BMSCorePath(pub syn::Path);

impl Default for BMSCorePath {
fn default() -> Self {
Self(syn::parse_quote!(bevy_mod_scripting::core))
}
}

#[derive(FromMeta)]
pub struct BMSLuaPath(pub syn::Path);

impl Default for BMSLuaPath {
fn default() -> Self {
Self(syn::parse_quote!(bevy_mod_scripting::lua))
}
}

#[derive(FromDeriveInput)]
#[darling(attributes(proxy), forward_attrs(allow, doc, cfg))]
pub struct ProxyInput {
/// The name of the type for which we are generating a proxy (target type)
pub ident: syn::Ident,
/// The visibility of the target type
pub vis: syn::Visibility,
/// The generics on the target type
pub generics: syn::Generics,
/// The attributes on the target type
pub attrs: Vec<Attribute>,

/// The path to the type for which we are generating a proxy if it's a foreign type
pub remote: Option<syn::Path>,

/// if provided will call the function at this path to get the world callback access. Normally this is retrieved using a global variable.
pub get_world_callback_access_fn: Option<syn::Path>,

/// If set will use the given path as the type for the proxy instead of generating a new one
/// Only used for the special world proxies, probably not useful for anything else, the macro assumes we have an inner ReflectReference in the wrapper
pub proxy_as_type: Option<syn::Path>,

/// The path to the bevy_mod_scripting_core crate
#[darling(default)]
pub bms_core_path: BMSCorePath,
/// The path to the bevy_mod_scripting_lua crate
#[darling(default)]
pub bms_lua_path: BMSLuaPath,

/// The name to use for the proxy type, if not provided the language derive macro
/// will generate one using a standard prefix.
#[darling(rename = "name")]
pub proxy_name: Option<Ident>,

/// The body of the type for which we are generating a proxy
pub data: darling::ast::Data<Variant, Field>,

/// A list of multi-lang function definitions to be generated on the proxy type
#[darling(default)]
pub functions: TraitItemFnsWrapper,
}

#[derive(Default)]
pub struct TraitItemFnsWrapper(pub Vec<TraitItemFn>);

impl FromMeta for TraitItemFnsWrapper {
fn from_string(value: &str) -> darling::Result<Self> {
let token_stream: proc_macro2::TokenStream = value.parse().map_err(syn::Error::from)?;
let trait_items_vec = vec![syn::parse2(token_stream)?];
Ok(TraitItemFnsWrapper(trait_items_vec))
}

fn from_list(items: &[darling::ast::NestedMeta]) -> darling::Result<Self> {
Ok(TraitItemFnsWrapper(
items
.iter()
.map(Self::from_nested_meta)
.collect::<Result<Vec<_>, _>>()?
.into_iter()
.flat_map(|v| v.0.into_iter())
.collect::<Vec<_>>(),
))
}
}

impl Deref for TraitItemFnsWrapper {
type Target = Vec<TraitItemFn>;

fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for TraitItemFnsWrapper {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}

/// Replaces every occurence of an identifier with
/// the given string while preserving the original span
pub struct IdentifierRenamingVisitor<'a> {
pub target: &'a str,
pub replacement: &'a str,
}

impl VisitMut for IdentifierRenamingVisitor<'_> {
fn visit_ident_mut(&mut self, i: &mut Ident) {
if *i == self.target {
*i = Ident::new(self.replacement, i.span());
}
}
}
Loading

0 comments on commit 1a783f3

Please sign in to comment.