use std::fmt;
use proc_macro2::{Ident, Literal, TokenStream};
use quote::{ToTokens, quote};
use crate::context::Context;
use crate::conv;
use crate::models::domain::{ArgPassing, FlowDirection, GodotTy, ModName, RustTy, TyName};
use crate::special_cases::{get_global_enum_module_path, is_builtin_type_scalar};
use crate::util::ident;
fn to_hardcoded_rust_ident(full_ty: &GodotTy) -> Option<Ident> {
let ty = full_ty.ty.as_str();
let meta = full_ty.meta.as_deref();
let result = match (ty, meta) {
("int", Some("int64") | None) => "i64",
("int", Some("int32")) => "i32",
("int", Some("int16")) => "i16",
("int", Some("int8")) => "i8",
("int", Some("uint64")) => "u64",
("int", Some("uint32")) => "u32",
("int", Some("uint16")) => "u16",
("int", Some("uint8")) => "u8",
("int", Some("char16")) => "u16",
("int", Some("char32")) => "u32",
("int", Some(meta)) => panic!("unhandled type int with meta {meta:?}"),
("float", Some("double") | None) => "f64",
("float", Some("float")) => "f32",
("float", Some(meta)) => panic!("unhandled type float with meta {meta:?}"),
("double", None) => "f64",
("double", Some(meta)) => panic!("unhandled type double with meta {meta:?}"),
("bool", None) => "bool",
("String", None) => "GString",
("Array", None) => match full_ty.flow {
Some(FlowDirection::RustToGodot) => "AnyArray",
Some(FlowDirection::GodotToRust) => "VarArray",
None => "_unused__Array_must_not_appear_in_idents",
},
("Dictionary", None) => match full_ty.flow {
Some(FlowDirection::RustToGodot) => "AnyDictionary",
Some(FlowDirection::GodotToRust) => "VarDictionary",
None => "_unused__Dictionary_must_not_appear_in_idents",
},
("real_t", None) => "real",
("void", None) => "c_void",
(ty, Some(meta)) if meta != "required" => {
panic!("unhandled type {ty:?} with meta {meta:?}")
}
(ty, None) => conv::fixed_width_c_int_ident(ty)?,
_ => return None,
};
Some(ident(result))
}
pub(crate) fn fixed_width_c_int_ident(c_type: &str) -> Option<&'static str> {
match c_type {
"int8_t" => Some("i8"),
"int16_t" => Some("i16"),
"int32_t" => Some("i32"),
"int64_t" => Some("i64"),
"uint8_t" => Some("u8"),
"uint16_t" => Some("u16"),
"uint32_t" => Some("u32"),
"uint64_t" => Some("u64"),
_ => None,
}
}
fn to_hardcoded_rust_enum(ty: &str) -> Option<Ident> {
let result = match ty {
"enum::Variant.Type" => "VariantType",
"enum::Variant.Operator" => "VariantOperator",
"enum::Vector2.Axis" => "Vector2Axis",
"enum::Vector2i.Axis" => "Vector2Axis",
"enum::Vector3.Axis" => "Vector3Axis",
"enum::Vector3i.Axis" => "Vector3Axis",
_ => return None,
};
Some(ident(result))
}
pub(crate) fn to_rust_type_abi(ty: &str, ctx: &mut Context) -> (RustTy, bool) {
let mut is_obj = false;
let ty = match ty {
"Object*" => {
is_obj = true;
RustTy::RawPointer {
inner: Box::new(RustTy::BuiltinIdent {
ty: ident("c_void"),
arg_passing: ArgPassing::ByValue,
}),
is_const: false,
}
}
"int" => RustTy::BuiltinIdent {
ty: ident("i32"),
arg_passing: ArgPassing::ByValue,
},
"float" => RustTy::BuiltinIdent {
ty: ident("f32"),
arg_passing: ArgPassing::ByValue,
},
"double" => RustTy::BuiltinIdent {
ty: ident("f64"),
arg_passing: ArgPassing::ByValue,
},
_ => to_rust_temporary_type(ty, ctx),
};
(ty, is_obj)
}
pub(crate) fn to_rust_type<'a>(
json_ty: &'a str,
meta: Option<&'a String>,
flow: Option<FlowDirection>,
ctx: &mut Context,
) -> RustTy {
let flow = match json_ty {
"Array" | "Dictionary" | "typedarray::Array" | "typedarray::Dictionary" => flow,
_ if json_ty.starts_with("typeddictionary::") => flow, _ => None, };
let full_ty = GodotTy {
ty: json_ty.to_string(),
meta: meta.cloned(),
flow,
};
if let Some(rust_ty) = ctx.find_rust_type(&full_ty) {
rust_ty.clone()
} else {
let rust_ty = to_rust_type_uncached(&full_ty, ctx);
ctx.insert_rust_type(full_ty, rust_ty.clone());
rust_ty
}
}
pub(crate) fn to_rust_temporary_type(ty: &str, ctx: &mut Context) -> RustTy {
to_rust_type(ty, None, None, ctx)
}
fn to_rust_type_uncached(full_ty: &GodotTy, ctx: &mut Context) -> RustTy {
let ty = full_ty.ty.as_str();
fn rustify_ty(ty: &str) -> Ident {
if is_builtin_type_scalar(ty) {
ident(ty)
} else {
TyName::from_godot(ty).rust_ty
}
}
if ty.ends_with('*') {
let mut ty = ty[0..ty.len() - 1].to_string();
let is_const = ty.starts_with("const ") && !ty.ends_with('*');
if is_const {
ty = ty.replace("const ", "");
}
if ty.starts_with("GDExtension") {
let ty = rustify_ty(&ty);
return RustTy::RawPointer {
inner: Box::new(RustTy::SysPointerType {
tokens: quote! { sys::#ty },
}),
is_const,
};
}
let inner_type = to_rust_type(ty.trim(), None, None, ctx);
return RustTy::RawPointer {
inner: Box::new(inner_type),
is_const,
};
}
if !ty.starts_with("typedarray::")
&& !ty.starts_with("typeddictionary::")
&& let Some(hardcoded) = to_hardcoded_rust_ident(full_ty)
{
return RustTy::BuiltinIdent {
ty: hardcoded,
arg_passing: ctx.get_builtin_arg_passing(full_ty),
};
}
if let Some(hardcoded) = to_hardcoded_rust_enum(ty) {
return RustTy::EngineEnum {
tokens: hardcoded.to_token_stream(),
surrounding_class: None, is_bitfield: false,
};
}
if let Some(bitfield) = ty.strip_prefix("bitfield::") {
return to_enum_type_uncached(bitfield, true);
} else if let Some(qualified_enum) = ty.strip_prefix("enum::") {
return to_enum_type_uncached(qualified_enum, false);
} else if let Some(packed_arr_ty) = ty.strip_prefix("Packed") {
if packed_arr_ty.ends_with("Array") {
return RustTy::BuiltinIdent {
ty: rustify_ty(ty),
arg_passing: ArgPassing::ByRef, };
}
} else if let Some(elem_ty) = ty.strip_prefix("typedarray::") {
let rust_elem_ty = to_rust_type(elem_ty, full_ty.meta.as_ref(), full_ty.flow, ctx);
let tokens = rust_elem_ty.tokens_non_null();
return RustTy::TypedArray {
tokens: quote! { Array<#tokens> },
#[cfg(not(feature = "codegen-full"))] #[cfg_attr(published_docs, doc(cfg(not(feature = "codegen-full"))))]
elem_class: (!ctx.is_builtin(elem_ty)).then(|| elem_ty.to_string()),
};
} else if let Some(kv_ty) = ty.strip_prefix("typeddictionary::") {
let (key_ty, value_ty) = kv_ty
.split_once(';')
.unwrap_or_else(|| panic!("typeddictionary missing ';' separator: {ty}"));
let rust_key_ty = to_rust_type(key_ty, None, full_ty.flow, ctx);
let rust_value_ty = to_rust_type(value_ty, None, full_ty.flow, ctx);
let key_tokens = rust_key_ty.tokens_non_null();
let value_tokens = rust_value_ty.tokens_non_null();
return RustTy::TypedDictionary {
tokens: quote! { Dictionary<#key_tokens, #value_tokens> },
#[cfg(not(feature = "codegen-full"))] #[cfg_attr(published_docs, doc(cfg(not(feature = "codegen-full"))))]
key_class: (!ctx.is_builtin(key_ty)).then(|| key_ty.to_string()),
#[cfg(not(feature = "codegen-full"))] #[cfg_attr(published_docs, doc(cfg(not(feature = "codegen-full"))))]
value_class: (!ctx.is_builtin(value_ty)).then(|| value_ty.to_string()),
};
}
if ctx.is_builtin(ty) || ctx.is_native_structure(ty) {
RustTy::BuiltinIdent {
ty: rustify_ty(ty),
arg_passing: ctx.get_builtin_arg_passing(full_ty),
}
} else {
let is_nullable = if cfg!(since_api = "4.6") {
full_ty.meta.as_ref().is_none_or(|m| m != "required")
} else {
true
};
let inner_class = rustify_ty(ty);
let qualified_class = quote! { crate::classes::#inner_class };
let gd_tokens = quote! { Gd<#qualified_class> };
let impl_as_object_arg = if is_nullable {
quote! { impl AsArg<Option<Gd<#qualified_class>>> }
} else {
quote! { impl AsArg<Gd<#qualified_class>> }
};
RustTy::EngineClass {
gd_tokens,
impl_as_object_arg,
inner_class,
is_nullable,
}
}
}
pub(crate) fn to_enum_type_uncached(enum_or_bitfield: &str, is_bitfield: bool) -> RustTy {
if let Some((class, enum_)) = enum_or_bitfield.split_once('.') {
to_class_enum_uncached(class, enum_, is_bitfield)
} else if enum_or_bitfield == "ResourceDeepDuplicateMode" {
to_class_enum_uncached("Resource", enum_or_bitfield, is_bitfield)
} else {
let path: TokenStream = get_global_enum_module_path(enum_or_bitfield)
.parse()
.expect("valid module path");
let enum_or_bitfield_name = conv::make_enum_name(enum_or_bitfield);
RustTy::EngineEnum {
tokens: quote! { #path::#enum_or_bitfield_name },
surrounding_class: None,
is_bitfield,
}
}
}
fn to_class_enum_uncached(class: &str, enum_: &str, is_bitfield: bool) -> RustTy {
let module = ModName::from_godot(class);
let enum_or_bitfield_name = conv::make_enum_name(enum_);
RustTy::EngineEnum {
tokens: quote! { crate::classes::#module::#enum_or_bitfield_name },
surrounding_class: Some(class.to_string()),
is_bitfield,
}
}
pub(crate) fn to_rust_expr(expr: &str, ty: &RustTy) -> TokenStream {
to_rust_expr_inner(expr, ty, false)
}
fn to_rust_expr_inner(expr: &str, ty: &RustTy, is_inner: bool) -> TokenStream {
match expr {
"true" => return quote! { true },
"false" => return quote! { false },
"[]" | "{}" if is_inner => return quote! {},
"[]" if matches!(ty, RustTy::BuiltinIdent { ty, .. } if ty == "AnyArray") => {
return quote! { AnyArray::new_untyped() };
}
"[]" => return quote! { Array::new() }, "{}" if matches!(ty, RustTy::BuiltinIdent { ty, .. } if ty == "AnyDictionary") => {
return quote! { AnyDictionary::new_untyped() };
}
"{}" => return quote! { Dictionary::new() }, "null" => {
return match ty {
RustTy::BuiltinIdent { ty: ident, .. } if ident == "Variant" => {
quote! { Variant::nil() }
}
RustTy::EngineClass { .. } => {
quote! { Gd::null_arg() }
}
_ => panic!("null not representable in target type {ty:?}"),
};
}
"RID()" | "Callable()" if !is_inner => {
return match ty {
RustTy::BuiltinIdent { ty: ident, .. } if ident == "Rid" => quote! { Rid::Invalid },
RustTy::BuiltinIdent { ty: ident, .. } if ident == "Callable" => {
quote! { Callable::invalid() }
}
_ => panic!("empty string not representable in target type {ty:?}"),
};
}
_ => {}
}
if let Ok(num) = expr.parse::<i64>() {
let lit = Literal::i64_unsuffixed(num);
return match ty {
RustTy::EngineEnum {
is_bitfield: true, ..
} => quote! { crate::obj::EngineBitfield::from_ord(#lit) },
RustTy::EngineEnum {
is_bitfield: false, ..
} => quote! { crate::obj::EngineEnum::from_ord(#lit) },
RustTy::BuiltinIdent { ty: ident, .. } if ident == "Variant" => {
quote! { Variant::from(#lit) }
}
RustTy::BuiltinIdent { ty: ident, .. }
if ident == "i64" || ident == "f64" || unmap_meta(ty).is_some() =>
{
suffixed_lit(num, ident)
}
_ if is_inner => quote! { #lit as _ },
_ => panic!("cannot map integer literal {expr} to type {ty:?}"),
};
}
if let Ok(num) = expr.parse::<f64>() {
return match ty {
RustTy::BuiltinIdent { ty: ident, .. }
if ident == "f64" || unmap_meta(ty).is_some() =>
{
suffixed_lit(num, ident)
}
_ if is_inner => {
let lit = Literal::f64_unsuffixed(num);
quote! { #lit as _ }
}
_ => panic!("cannot map float literal {expr} to type {ty:?}"),
};
}
if let Some(expr) = expr.strip_prefix('"') {
let expr = expr.strip_suffix('"').expect("unmatched opening '\"'");
return if is_inner {
quote! { #expr }
} else {
match ty {
RustTy::BuiltinIdent { ty: ident, .. }
if ident == "GString" || ident == "StringName" || ident == "NodePath" =>
{
quote! { #ident::from(#expr) }
}
_ => quote! { GString::from(#expr) },
}
};
}
if let Some(expr) = expr.strip_prefix("&\"") {
let expr = expr.strip_suffix('"').expect("unmatched opening '&\"'");
return quote! { StringName::from(#expr) };
}
if let Some(expr) = expr.strip_prefix("^\"") {
let expr = expr.strip_suffix('"').expect("unmatched opening '^\"'");
return quote! { NodePath::from(#expr) };
}
if let Some(pos) = expr.find('(') {
let godot_ty = &expr[..pos];
let wrapped = expr[pos + 1..].strip_suffix(')').expect("unmatched '('");
let (rust_ty, ctor) = match godot_ty {
"NodePath" => ("NodePath", "from"),
"String" => ("GString", "from"),
"StringName" => ("StringName", "from"),
"RID" => ("Rid", "default"),
"Rect2" => ("Rect2", "from_components"),
"Rect2i" => ("Rect2i", "from_components"),
"Vector2" | "Vector2i" | "Vector3" | "Vector3i" => (godot_ty, "new"),
"Transform2D" => ("Transform2D", "__internal_codegen"),
"Transform3D" => ("Transform3D", "__internal_codegen"),
"Color" => {
if wrapped.chars().filter(|&c| c == ',').count() == 2 {
("Color", "from_rgb")
} else {
("Color", "from_rgba")
}
}
array if array.starts_with("Packed") && array.ends_with("Array") => {
assert_eq!(wrapped, "", "only empty packed arrays supported for now");
(array, "new")
}
array if array.starts_with("Array[") => {
assert_eq!(wrapped, "[]", "only empty typed arrays supported for now");
("Array", "new")
}
_ => panic!("unsupported type: {godot_ty}"),
};
let subtokens = wrapped.split(',').map(|part| {
let part = part.trim();
if part.is_empty() {
quote! {}
} else {
to_rust_expr_inner(part, ty, true)
}
});
let rust_ty = ident(rust_ty);
let ctor = ident(ctor);
return quote! {
#rust_ty::#ctor(#(#subtokens),*)
};
}
panic!(
"Not yet supported GDScript expression: '{expr}'\n\
Please report this at https://github.com/godot-rust/gdext/issues/new."
);
}
fn suffixed_lit(num: impl fmt::Display, suffix: &Ident) -> TokenStream {
let combined = format!("{num}{suffix}");
combined
.parse::<Literal>()
.unwrap_or_else(|_| panic!("invalid literal {combined}"))
.to_token_stream()
}
#[test]
fn gdscript_to_rust_expr() {
let ty_int = RustTy::BuiltinIdent {
ty: ident("i64"),
arg_passing: ArgPassing::ByValue,
};
let ty_int = Some(&ty_int);
let ty_int_u16 = RustTy::BuiltinIdent {
ty: ident("u16"),
arg_passing: ArgPassing::ByValue,
};
let ty_int_u16 = Some(&ty_int_u16);
let ty_float = RustTy::BuiltinIdent {
ty: ident("f64"),
arg_passing: ArgPassing::ByValue,
};
let ty_float = Some(&ty_float);
let ty_float_f32 = RustTy::BuiltinIdent {
ty: ident("f32"),
arg_passing: ArgPassing::ByValue,
};
let ty_float_f32 = Some(&ty_float_f32);
let ty_enum = RustTy::EngineEnum {
tokens: quote! { SomeEnum },
surrounding_class: None,
is_bitfield: false,
};
let ty_enum = Some(&ty_enum);
let ty_bitfield = RustTy::EngineEnum {
tokens: quote! { SomeEnum },
surrounding_class: None,
is_bitfield: true,
};
let ty_bitfield = Some(&ty_bitfield);
let ty_variant = RustTy::BuiltinIdent {
ty: ident("Variant"),
arg_passing: ArgPassing::ByRef,
};
let ty_variant = Some(&ty_variant);
let ty_string = RustTy::BuiltinIdent {
ty: ident("GString"),
arg_passing: ArgPassing::ImplAsArg,
};
let ty_string = Some(&ty_string);
let ty_stringname = RustTy::BuiltinIdent {
ty: ident("StringName"),
arg_passing: ArgPassing::ImplAsArg,
};
let ty_stringname = Some(&ty_stringname);
let ty_nodepath = RustTy::BuiltinIdent {
ty: ident("NodePath"),
arg_passing: ArgPassing::ImplAsArg,
};
let ty_nodepath = Some(&ty_nodepath);
#[rustfmt::skip]
let table = [
("0", ty_int, quote! { 0i64 }),
("-1", ty_int, quote! { -1i64 }),
("2147483647", ty_int, quote! { 2147483647i64 }),
("-2147483648", ty_int, quote! { -2147483648i64 }),
("0", ty_int_u16, quote! { 0u16 }),
("65535", ty_int_u16, quote! { 65535u16 }),
("0", ty_float, quote! { 0f64 }),
("2147483647", ty_float, quote! { 2147483647f64 }),
("-1.5", ty_float, quote! { -1.5f64 }),
("2e3", ty_float, quote! { 2000f64 }),
("0", ty_float_f32, quote! { 0f32 }),
("-2147483648", ty_float_f32, quote! { -2147483648f32 }),
("-2.5", ty_float_f32, quote! { -2.5f32 }),
("3e3", ty_float, quote! { 3000f64 }),
("7", ty_enum, quote! { crate::obj::EngineEnum::from_ord(7) }),
("7", ty_bitfield, quote! { crate::obj::EngineBitfield::from_ord(7) }),
("8", ty_variant, quote! { Variant::from(8) }),
("true", None, quote! { true }),
("false", None, quote! { false }),
("{}", None, quote! { Dictionary::new() }),
("[]", None, quote! { Array::new() }),
("null", ty_variant, quote! { Variant::nil() }),
("\" \"", None, quote! { GString::from(" ") }),
("\"{_}\"", None, quote! { GString::from("{_}") }),
("&\"text\"", None, quote! { StringName::from("text") }),
("^\"text\"", None, quote! { NodePath::from("text") }),
("\"text\"", ty_string, quote! { GString::from("text") }),
("\"text\"", ty_stringname, quote! { StringName::from("text") }),
("\"text\"", ty_nodepath, quote! { NodePath::from("text") }),
("NodePath(\"\")", None, quote! { NodePath::from("") }),
("Color(1, 0, 0.5, 1)", None, quote! { Color::from_rgba(1 as _, 0 as _, 0.5 as _, 1 as _) }),
("Vector3(0, 1, 2.5)", None, quote! { Vector3::new(0 as _, 1 as _, 2.5 as _) }),
("Rect2(1, 2.2, -3.3, 0)", None, quote! { Rect2::from_components(1 as _, 2.2 as _, -3.3 as _, 0 as _) }),
("Rect2i(1, 2.2, -3.3, 0)", None, quote! { Rect2i::from_components(1 as _, 2.2 as _, -3.3 as _, 0 as _) }),
("PackedFloat32Array()", None, quote! { PackedFloat32Array::new() }),
("Array[Plane]([])", None, quote! { Array::new() }),
("Array[RDPipelineSpecializationConstant]([])", None, quote! { Array::new() }),
("Array[RID]([])", None, quote! { Array::new() }),
("Transform3D(1, 2, 3, 4, -1.1, -1.2, -1.3, -1.4, 0, 0, 0, 0)", None, quote! {
Transform3D::__internal_codegen(
1 as _, 2 as _, 3 as _,
4 as _, -1.1 as _, -1.2 as _,
-1.3 as _, -1.4 as _, 0 as _,
0 as _, 0 as _, 0 as _
)
}),
("Transform2D(1, 2, -1.1,1.2, 0, 0)", None, quote! {
Transform2D::__internal_codegen(
1 as _, 2 as _,
-1.1 as _, 1.2 as _,
0 as _, 0 as _
)
}),
];
for (gdscript, ty, rust) in table {
let ty_dontcare = RustTy::TypedArray {
tokens: TokenStream::new(),
#[cfg(not(feature = "codegen-full"))] #[cfg_attr(published_docs, doc(cfg(not(feature = "codegen-full"))))]
elem_class: None,
};
let ty = ty.unwrap_or(&ty_dontcare);
let actual = to_rust_expr(gdscript, ty).to_string();
let expected = rust.to_string();
assert_eq!(actual, expected);
}
}
pub(crate) fn unmap_meta(rust_ty: &RustTy) -> Option<Ident> {
let RustTy::BuiltinIdent { ty: rust_ty, .. } = rust_ty else {
return None;
};
for ty in ["u64", "u32", "u16", "u8", "i32", "i16", "i8"] {
if rust_ty == ty {
return Some(ident("i64"));
}
}
if rust_ty == "f32" {
return Some(ident("f64"));
}
None
}