use std::{any::TypeId, borrow::Cow};
use bevy_mod_scripting_bindings_domain::ScriptOperatorNames;
use bevy_mod_scripting_display::OrFakeId;
use bevy_mod_scripting_world::WorldGuard;
use crate::{
DynamicScriptFunction, EnumVariantRef, FunctionCallContext, FunctionScope, InteropError,
ReflectReference, ScriptValue, WorldExtensions,
world_extensions::{FunctionLookups, Lookups},
};
pub enum Member {
Method(DynamicScriptFunction),
Static(ScriptValue),
}
impl From<Member> for ScriptValue {
fn from(member: Member) -> Self {
match member {
Member::Method(func) => ScriptValue::Function(func),
Member::Static(value) => value,
}
}
}
fn is_method(func: &DynamicScriptFunction, type_id: TypeId) -> bool {
type_id == TypeId::of::<EnumVariantRef>()
|| matches!(func.info.namespace, FunctionScope::OnType(on)
if on == type_id || FunctionScope::OnType(on) == FunctionScope::all_references())
}
pub fn index(
world: WorldGuard,
reference: ReflectReference,
key: ScriptValue,
ctx: FunctionCallContext,
) -> Result<Member, InteropError> {
match key.as_string() {
Ok(name) => index_name(world, Cow::Owned(reference), name, ctx),
Err(key) => magic_get(world, reference, key, ctx),
}
}
pub fn index_name<'n>(
world: WorldGuard,
reference: Cow<'_, ReflectReference>,
name: impl Into<Cow<'n, str>>,
ctx: FunctionCallContext,
) -> Result<Member, InteropError> {
profiling::function_scope!("dispatch::index");
let type_id = reference.tail_type_id(world.clone())?.or_fake_id();
let (member, get) = Lookups::with(&world, |lookups| {
let member = lookups.member(&reference, type_id, name);
(member, lookups.registry.magic_functions.get)
});
match member {
Ok(ScriptValue::Function(func)) if is_method(&func, type_id) => Ok(Member::Method(func)),
Ok(member) => Ok(Member::Static(member)),
Err(name) => get(
ctx,
reference.into_owned(),
ScriptValue::String(Cow::Owned(name.into_owned())),
)
.map(Member::Static),
}
}
fn magic_get(
world: WorldGuard,
reference: ReflectReference,
key: ScriptValue,
ctx: FunctionCallContext,
) -> Result<Member, InteropError> {
let get = world.script_function_registry().read().magic_functions.get;
get(ctx, reference, key).map(Member::Static)
}
pub fn set_index(
world: WorldGuard,
reference: ReflectReference,
key: ScriptValue,
value: ScriptValue,
ctx: FunctionCallContext,
) -> Result<(), InteropError> {
profiling::function_scope!("dispatch::set_index");
let set = world.script_function_registry().read().magic_functions.set;
set(ctx, reference, key, value)
}
pub fn static_index(
world: WorldGuard,
type_id: TypeId,
key: ScriptValue,
ctx: FunctionCallContext,
) -> Result<ScriptValue, InteropError> {
profiling::function_scope!("dispatch::static_index");
let key = match key.as_string() {
Ok(name) => match world.lookup_static_member(type_id, name) {
Ok(value) => return Ok(value),
Err(name) => ScriptValue::String(name),
},
Err(key) => key,
};
Err(InteropError::missing_function(
format!("{key:#?}"),
FunctionScope::OnType(type_id),
Some(ctx),
))
}
pub fn binary(
world: WorldGuard,
operator: ScriptOperatorNames,
lhs: ScriptValue,
rhs: ScriptValue,
ctx: FunctionCallContext,
) -> Result<ScriptValue, InteropError> {
profiling::function_scope!("dispatch::binary");
let (receiver, other, name) = match (lhs, rhs) {
(ScriptValue::Reference(receiver), other) => {
(receiver, other, operator.script_function_name())
}
(other, ScriptValue::Reference(receiver)) => {
match operator.reflected_script_function_name() {
Some(name) => (receiver, other, name),
None => {
return Err(InteropError::str(
"the right operand of this operator can't be a value",
));
}
}
}
_ => {
return Err(InteropError::str(
"neither operand of this operator is a value",
));
}
};
let type_id = receiver.tail_type_id(world.clone())?.or_fake_id();
world.call_operator(
type_id,
name,
vec![ScriptValue::Reference(receiver), other],
ctx,
)
}
pub fn unary(
world: WorldGuard,
operator: ScriptOperatorNames,
value: ReflectReference,
ctx: FunctionCallContext,
) -> Result<ScriptValue, InteropError> {
profiling::function_scope!("dispatch::unary");
let type_id = value.tail_type_id(world.clone())?.or_fake_id();
world.call_operator(
type_id,
operator.script_function_name(),
vec![ScriptValue::Reference(value)],
ctx,
)
}
pub fn len(
world: WorldGuard,
value: ScriptValue,
ctx: FunctionCallContext,
) -> Result<ScriptValue, InteropError> {
profiling::function_scope!("dispatch::len");
match value {
ScriptValue::List(list) => Ok(ScriptValue::Integer(list.len() as i64)),
ScriptValue::Reference(reference) => {
unary(world, ScriptOperatorNames::Length, reference, ctx)
}
_ => Ok(ScriptValue::Unit),
}
}
fn call_reserved(
world: WorldGuard,
operator: ScriptOperatorNames,
reference: ReflectReference,
ctx: FunctionCallContext,
) -> Result<ScriptValue, InteropError> {
world
.lookup_reserved_function(operator.script_function_name(), ctx.clone())?
.call(vec![ScriptValue::Reference(reference)], ctx)
}
pub fn iter(
world: WorldGuard,
reference: ReflectReference,
ctx: FunctionCallContext,
) -> Result<ScriptValue, InteropError> {
profiling::function_scope!("dispatch::iter");
call_reserved(world, ScriptOperatorNames::Iteration, reference, ctx)
}
fn into_string(value: ScriptValue, name: &'static str) -> Result<String, InteropError> {
match value {
ScriptValue::String(string) => Ok(string.into_owned()),
_ => Err(InteropError::invariant(format!(
"{name} did not return a string"
))),
}
}
pub fn display(
world: WorldGuard,
reference: ReflectReference,
ctx: FunctionCallContext,
) -> Result<String, InteropError> {
profiling::function_scope!("dispatch::display");
into_string(
call_reserved(world, ScriptOperatorNames::DisplayPrint, reference, ctx)?,
"display",
)
}
pub fn debug(
world: WorldGuard,
reference: ReflectReference,
ctx: FunctionCallContext,
) -> Result<String, InteropError> {
profiling::function_scope!("dispatch::debug");
into_string(
call_reserved(world, ScriptOperatorNames::DebugPrint, reference, ctx)?,
"debug",
)
}