godot-codegen 0.5.6

Internal crate used by godot-rust
Documentation
/*
 * Copyright (c) godot-rust; Bromeon and contributors.
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

use proc_macro2::{Ident, TokenStream};
use quote::{ToTokens, format_ident, quote};

use crate::context::Context;
use crate::conv;
use crate::generator::{enums, gdext_build_struct};
use crate::models::domain::{ExtensionApi, FlowDirection};
use crate::util::ident;

pub fn make_sys_central_code(api: &ExtensionApi) -> TokenStream {
    let build_config_struct = gdext_build_struct::make_gdext_build_struct(&api.godot_version);
    let variant_type_enum = make_variant_type_enum(api, true);
    let [opaque_32bit, opaque_64bit] = make_opaque_types(api);
    let godot_type_name_method = make_godot_type_name_method(api);
    let inplace_variant_method = make_is_inplace_variant_method(api);

    quote! {
        #[cfg(target_pointer_width = "32")] #[cfg_attr(published_docs, doc(cfg(target_pointer_width = "32")))]
        pub mod types {
            #(#opaque_32bit)*
        }
        #[cfg(target_pointer_width = "64")] #[cfg_attr(published_docs, doc(cfg(target_pointer_width = "64")))]
        pub mod types {
            #(#opaque_64bit)*
        }

        // ----------------------------------------------------------------------------------------------------------------------------------------------

        #build_config_struct
        #variant_type_enum

        impl VariantType {
            // This will need refactoring if VariantType is changed to a real enum.
            #[doc(hidden)]
            pub fn from_sys(enumerator: crate::GDExtensionVariantType) -> Self {
                #[allow(clippy::unnecessary_cast)] // on Windows already i32.
                Self { ord: enumerator as i32 }
            }

            #[doc(hidden)]
            pub fn sys(self) -> crate::GDExtensionVariantType {
                self.ord as _
            }

            #godot_type_name_method
            #inplace_variant_method
        }
    }
}

pub fn make_core_central_code(api: &ExtensionApi, ctx: &mut Context) -> TokenStream {
    let VariantEnums {
        variant_ty_enumerators_pascal,
        variant_ty_enumerators_shout,
        variant_ty_enumerators_rust,
        ..
    } = make_variant_enums(api, ctx);

    let (global_enum_defs, global_reexported_enum_defs) = make_global_enums(api);
    let variant_type_traits = make_variant_type_enum(api, false);

    // TODO impl Clone, Debug, PartialEq, PartialOrd, Hash for VariantDispatch
    // TODO could use try_to().unwrap_unchecked(), since type is already verified. Also directly overload from_variant().
    // But this requires that all the variant types support this.
    quote! {
        use crate::builtin::*;
        use crate::classes::Object;
        use crate::obj::Gd;

        // Remaining trait impls for sys::VariantType (traits only defined in godot-core).
        #variant_type_traits

        #[allow(dead_code)]
        // Exhaustive, because only new Godot minor versions add new variants, which need either godot-rust minor bump or `api-*` feature.
        pub enum VariantDispatch {
            Nil,
            #(
                #variant_ty_enumerators_pascal(#variant_ty_enumerators_rust),
            )*
            /// Special case of a `Variant` holding an object that has been destroyed.
            FreedObject,
        }

        impl VariantDispatch {
            pub fn from_variant(variant: &Variant) -> Self {
                match variant.get_type() {
                    VariantType::NIL => Self::Nil,
                    VariantType::OBJECT if !variant.is_object_alive() => Self::FreedObject,
                    #(
                        VariantType::#variant_ty_enumerators_shout
                            => Self::#variant_ty_enumerators_pascal(variant.to::<#variant_ty_enumerators_rust>()),
                    )*

                    // Panic can be removed as soon as VariantType is a proper, non-exhaustive enum.
                    _ => panic!("Variant type not supported: {:?}", variant.get_type()),
                }
            }
        }

        impl std::fmt::Debug for VariantDispatch {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                match self {
                    Self::Nil => write!(f, "null"),
                    #(
                        Self::#variant_ty_enumerators_pascal(v) => write!(f, "{v:?}"),
                    )*
                    Self::FreedObject => write!(f, "<Freed Object>"),
                }
            }
        }

        /// Global enums and constants, generated by Godot.
        pub mod global_enums {
            use crate::sys;
            #( #global_enum_defs )*
        }

        pub mod global_reexported_enums {
            use crate::sys;
            #( #global_reexported_enum_defs )*
        }
    }
}

// ----------------------------------------------------------------------------------------------------------------------------------------------
// Implementation

struct VariantEnums {
    variant_ty_enumerators_pascal: Vec<Ident>,
    variant_ty_enumerators_shout: Vec<Ident>,
    variant_ty_enumerators_rust: Vec<TokenStream>,
}

fn make_opaque_types(api: &ExtensionApi) -> [Vec<TokenStream>; 2] {
    let mut opaque_types = [Vec::new(), Vec::new()];

    for b in api.builtin_sizes.iter() {
        let index = b.config.is_64bit() as usize;
        let type_def = make_opaque_type(&b.builtin_original_name, b.size);

        opaque_types[index].push(type_def);
    }

    opaque_types
}

fn make_opaque_type(godot_original_name: &str, size: usize) -> TokenStream {
    let name = conv::to_pascal_case(godot_original_name);
    let (first, rest) = name.split_at(1);

    // Capitalize: "int" -> "Int".
    let ident = format_ident!("Opaque{}{}", first.to_ascii_uppercase(), rest);
    quote! {
        pub type #ident = crate::opaque::Opaque<#size>;
    }
}

fn make_variant_enums(api: &ExtensionApi, ctx: &mut Context) -> VariantEnums {
    // Generate builtin methods, now with info for all types available.
    // Separate vectors because that makes usage in quote! easier.
    let len = api.builtins.len();

    let mut result = VariantEnums {
        variant_ty_enumerators_pascal: Vec::with_capacity(len),
        variant_ty_enumerators_shout: Vec::with_capacity(len),
        variant_ty_enumerators_rust: Vec::with_capacity(len),
    };

    // When extracting variant, data moves Godot->Rust. Means `VariantArray` for `Array`.
    let flow = FlowDirection::GodotToRust;

    // Note: NIL is not part of this iteration, it will be added manually.
    for builtin in api.builtins.iter() {
        let original_name = builtin.godot_original_name();
        let shout_case = builtin.godot_shout_name();
        let rust_ty = conv::to_rust_type(original_name, None, Some(flow), ctx);
        let pascal_case = conv::to_pascal_case(original_name);

        result
            .variant_ty_enumerators_pascal
            .push(ident(&pascal_case));
        result.variant_ty_enumerators_shout.push(ident(shout_case));
        result
            .variant_ty_enumerators_rust
            .push(rust_ty.to_token_stream());
    }

    result
}

fn make_global_enums(api: &ExtensionApi) -> (Vec<TokenStream>, Vec<TokenStream>) {
    let mut global_enum_defs = vec![];
    let mut global_reexported_enum_defs = vec![];

    for enum_ in api.global_enums.iter() {
        // Skip VariantType, which is already defined in godot-ffi.
        if enum_.name == "VariantType" {
            continue;
        }

        let def = enums::make_enum_definition(enum_);

        if enum_.is_private {
            global_reexported_enum_defs.push(def);
        } else {
            global_enum_defs.push(def);
        }
    }

    (global_enum_defs, global_reexported_enum_defs)
}

fn make_variant_type_enum(api: &ExtensionApi, is_definition: bool) -> TokenStream {
    let variant_type_enum = api
        .global_enums
        .iter()
        .find(|e| e.name == "VariantType")
        .expect("missing VariantType enum in API JSON");

    let define_enum = is_definition;
    let define_traits = !is_definition;

    enums::make_enum_definition_with(variant_type_enum, define_enum, define_traits)
}

/// Generates the `VariantType::is_inplace_variant()` method from the builtins list.
///
/// Returns `false` if a variant of this type requires `variant_destroy` on drop, for two reasons:
/// 1. Non-trivial destructor in `extension_api.json` (refcounted: `String`, `Array`, `Dictionary`, `Object`, ...).
/// 2. Stored heap-allocated inside `Variant` because it exceeds the inline data segment (`Transform2D`, `Transform3D`, `Basis`, `Aabb`,
///    `Projection`). Godot reports `has_destructor=false` for these (trivially destructible in C++), but `Variant` still owns the allocation.
fn make_is_inplace_variant_method(api: &ExtensionApi) -> TokenStream {
    use crate::models::domain::BuildConfiguration;

    // Detecting case 2 needs the type's byte size. Godot's inline buffer is `max(sizeof(ObjData), 4 * sizeof(real_t))` -> 16 bytes in single,
    // 32 bytes in double precision. Pointer width doesn't affect it (`ObjData` is 2 pointers, thus <= 16), so the 32-bit configuration's sizes
    // decide it for both pointer widths. Only configurations of the current precision are present in `builtin_sizes`, see `is_applicable()`.
    let (size_config, inplace_bytes_threshold) = if cfg!(feature = "double-precision") {
        (BuildConfiguration::Double32, 32)
    } else {
        (BuildConfiguration::Float32, 16)
    };

    let sizes: std::collections::HashMap<&str, usize> = api
        .builtin_sizes
        .iter()
        .filter(|s| s.config == size_config)
        .map(|s| (s.builtin_original_name.as_str(), s.size))
        .collect();

    // `Nil` is not part of `api.builtins`, but the empty variant is stored in-place and trivially destructible. Include it explicitly, so the
    // lifecycle fast paths (Clone/Drop) and `set_value` treat a nil variant as overwritable/copyable without FFI.
    let mut inplace_mask = 1_u64; // Bit 0 = NIL.
    let mut max_ord = 0_i32;

    for builtin in api.builtins.iter() {
        let size = sizes
            .get(builtin.godot_original_name())
            .copied()
            .unwrap_or_else(|| {
                panic!(
                    "no size found for builtin `{}`",
                    builtin.godot_original_name()
                )
            });

        let ord = builtin.variant_type_ord;
        max_ord = max_ord.max(ord);

        if size <= inplace_bytes_threshold && !builtin.has_destructor {
            inplace_mask |= 1_u64 << ord;
        }
    }

    assert!(
        max_ord < 64,
        "VariantType ord {max_ord} >= 64 no longer fits the `& 63` optimization"
    );

    quote! {
        /// Returns `true` if _variants_ of this type can store the value in-place (SBO) and thus don't require FFI copies and destruction.
        ///
        /// `false` for types that either:
        /// - always need Godot-side destruction (refcounted like `GString`, `Array` etc.).
        /// - are too big to be stored in-place in `Variant`, thus needing heap storage (`Aabb`, `Basis`, `Transform2D`, `Transform3D`, `Projection`).
        #[doc(hidden)]
        #[inline] // Few instructions (shift, and, test) -- runs on every Variant clone/drop.
        pub const fn is_inplace_variant(&self) -> bool {
            // Bitmask instead of matches! -- LLVM compiles it to range compare + branch. `& 63` elides shift-overflow check (all ords < 64) and
            // is free on x86. `variant_roundtrip_i64` benchmark may be slower due to LLVM loop layout, not due to this function.
            const INPLACE_MASK: u64 = #inplace_mask;

            let ord_u6 = self.ord as u32 & 63;
            (INPLACE_MASK >> ord_u6) & 1 != 0
        }
    }
}

/// Generates the `VariantType::godot_type_name()` method from the builtins list.
fn make_godot_type_name_method(api: &ExtensionApi) -> TokenStream {
    // NIL is not in api.builtins; handle it manually.
    let mut ordinals = vec![0i32];
    let mut names: Vec<&str> = vec!["Variant"];

    for builtin in api.builtins.iter() {
        ordinals.push(builtin.variant_type_ord);
        names.push(builtin.godot_original_name());
    }

    quote! {
        /// Returns the canonical Godot type name for this variant type.
        ///
        /// Examples: `INT` -> `"int"`, `STRING` -> `"String"`, `VECTOR3` -> `"Vector3"`.
        pub fn godot_type_name(&self) -> &'static str {
            match self.ord {
                #( #ordinals => #names, )*
                _ => "Unknown",
            }
        }
    }
}