godot-codegen 0.5.3

Internal crate used by godot-rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
/*
 * 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/.
 */

//! Code generation for `gdextension_interface.json` types and interface functions.
//!
//! Generates:
//! - Type definitions (enums, structs, handles, aliases, function pointer types).
//! - Typedefs for interface functions (`unsafe extern "C" fn(...)`).
//! - `GDExtensionInterface` struct:
//!   - Fields for each interface function, non-Option, `#[cfg(since_api = "4.x")]` gated according to version.
//!   - Constructor `load()` impl that populates the struct via `get_proc_address`.

use heck::ToPascalCase as _;
use proc_macro2::{Ident, Literal, TokenStream};
use quote::{format_ident, quote};

use crate::models::header_json::{
    HeaderInterfaceFunction, HeaderJson, HeaderReturnValue, HeaderType,
};
use crate::util::{ident, make_load_safety_doc, option_as_slice, safe_ident};

/// Generate Rust type definitions from header JSON.
///
/// Produces the `gdextension_interface.rs` module with enums, structs, handles, aliases, and function pointer types.
pub fn generate_header_types(types: &[HeaderType]) -> TokenStream {
    let type_definitions = types.iter().map(generate_type_definition);

    quote! {
        #( #type_definitions )*
    }
}

/// Holds the three generated `TokenStream`s for the interface function pointers.
pub struct InterfaceParts {
    /// Per-function type aliases: `pub type GDExtensionInterface... = unsafe extern "C" fn(...)`.
    pub function_types: TokenStream,

    /// `GDExtensionInterface` struct definition.
    pub struct_def: TokenStream,

    /// `impl GDExtensionInterface` with `load()` function.
    pub struct_impl: TokenStream,
}

/// Generate the interface struct, including function-pointer types and `impl` block.
pub fn generate_interface_parts(interface: &[HeaderInterfaceFunction]) -> InterfaceParts {
    let safety_doc = make_load_safety_doc();
    let mut typedefs = Vec::new();
    let mut fields = Vec::new();
    let mut field_inits = Vec::new();

    for func in interface {
        let cfg_attr = make_since_attribute(&func.since);
        let type_name = interface_type_name(func);
        let field_name = ident(&func.name);

        let params = generate_params(&func.arguments);
        let return_clause = func
            .return_value
            .as_ref()
            .map(map_return_clause)
            .unwrap_or_default();
        typedefs.push(quote! {
            #cfg_attr
            pub type #type_name = unsafe extern "C" fn(#( #params ),*) #return_clause;
        });

        let doc_attr = make_interface_func_doc(func);
        fields.push(quote! {
            #cfg_attr
            #doc_attr
            pub #field_name: #type_name,
        });

        let name_cstr = Literal::c_string(&std::ffi::CString::new(func.name.as_str()).unwrap());
        let name_str = &func.name;
        field_inits.push(quote! {
            #cfg_attr
            #field_name: {
                let fptr = get_proc_address(#name_cstr.as_ptr())
                    .unwrap_or_else(|| panic!("failed to load `{}`", #name_str));
                // SAFETY: Godot guarantees the returned pointer matches the documented signature.
                unsafe { std::mem::transmute::<unsafe extern "C" fn(), #type_name>(fptr) }
            },
        });
    }

    InterfaceParts {
        function_types: quote! { #( #typedefs )* },
        struct_def: quote! {
            pub struct GDExtensionInterface {
                #( #fields )*
            }
        },
        struct_impl: quote! {
            impl GDExtensionInterface {
                #safety_doc
                pub(crate) unsafe fn load(
                    get_proc_address: crate::GDExtensionInterfaceGetProcAddress,
                ) -> Self {
                    let get_proc_address = get_proc_address.expect("invalid get_proc_address function pointer");
                    Self { #( #field_inits )* }
                }
            }
        },
    }
}

/// Generate complete `gdextension_interface.rs` content from JSON.
///
/// Contains all type definitions and the interface spec. This file was formerly generated by bindgen.
pub fn generate_sys_gdextension_interface_from_json(header: &HeaderJson) -> TokenStream {
    let header_types = generate_header_types(&header.types);
    let InterfaceParts {
        function_types: iface_function_types,
        struct_def: iface_struct_def,
        struct_impl: iface_struct_impl,
    } = generate_interface_parts(&header.interface);

    quote! {
        /// UTF-16 character type.
        pub type char16_t = u16;

        /// UTF-32 character type.
        pub type char32_t = u32;

        /// Wide character type.
        pub type wchar_t = std::ffi::c_int;

        #header_types
        #iface_function_types
        #iface_struct_def
        #iface_struct_impl
    }
}

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

/// Derive the PascalCase type name for an interface function.
///
/// E.g. `mem_alloc` -> `GDExtensionInterfaceMemAlloc`.
fn interface_type_name(func: &HeaderInterfaceFunction) -> Ident {
    format_ident!("GDExtensionInterface{}", func.name.to_pascal_case())
}

/// Parse the `since` field (e.g. `"4.3"`) and return a `#[cfg(since_api = "4.3")]` attribute.
///
/// Returns empty `TokenStream` for versions at or below the minimum supported version, since those functions are unconditionally present.
fn make_since_attribute(since: &str) -> TokenStream {
    let since_minor: u8 = since
        .strip_prefix("4.")
        .expect("major version must be 4")
        .parse()
        .expect("invalid minor version in `since` field");

    let (_, min_minor) = godot_bindings::MIN_SUPPORTED_VERSION;
    if since_minor <= min_minor {
        TokenStream::new()
    } else {
        quote! { #[cfg(since_api = #since)] }
    }
}

/// Build a `#[doc = "..."]` attribute with parameter and return value documentation.
fn make_interface_func_doc(func: &HeaderInterfaceFunction) -> TokenStream {
    let mut doc_parts = Vec::new();

    if !func.description.is_empty() {
        doc_parts.push(func.description.join("\n"));
    }

    if !func.arguments.is_empty() {
        let mut param_docs = Vec::new();

        for arg in &func.arguments {
            if let Some(name) = &arg.name
                && let Some(desc_lines) = &arg.description
                && !desc_lines.is_empty()
            {
                param_docs.push(format!("- `{}` - {}", name, desc_lines.join(" ")));
            }
        }

        if !param_docs.is_empty() {
            doc_parts.push(String::new());
            doc_parts.push("## Parameters".to_string());
            doc_parts.extend(param_docs);
        }
    }

    let is_void = func
        .return_value
        .as_ref()
        .is_none_or(|rv| rv.type_ == "void");
    if !is_void
        && let Some(rv) = &func.return_value
        && let Some(ret_desc_lines) = &rv.description
        && !ret_desc_lines.is_empty()
    {
        doc_parts.push(String::new());
        doc_parts.push("## Return value".to_string());
        doc_parts.push(ret_desc_lines.join(" "));
    }

    if !doc_parts.is_empty() {
        let doc_str = doc_parts.join("\n");
        quote! { #[doc = #doc_str] }
    } else {
        TokenStream::new()
    }
}

fn generate_type_definition(type_def: &HeaderType) -> TokenStream {
    match type_def.kind.as_str() {
        "enum" => generate_enum_type(type_def),
        "handle" => generate_handle_type(type_def),
        "alias" => generate_alias_type(type_def),
        "struct" => generate_struct_type(type_def),
        "function" => generate_function_type(type_def),
        _ => TokenStream::new(),
    }
}

fn generate_enum_type(type_def: &HeaderType) -> TokenStream {
    let name = ident(&type_def.name);

    let values = option_as_slice(&type_def.values).iter().map(|val| {
        let variant_name = ident(&val.name);
        let variant_value = Literal::i64_unsuffixed(val.value);
        quote! {
            pub const #variant_name: #name = #variant_value;
        }
    });

    // Note: C enums are implementation-defined but typically 'int' (signed, usually 32 bit).
    quote! {
        pub type #name = std::ffi::c_int;

        #( #values )*
    }
}

fn generate_handle_type(type_def: &HeaderType) -> TokenStream {
    let name = ident(&type_def.name);
    let is_const = type_def.is_const == Some(true); // absent means false.

    // Derive opaque struct name: strip "GDExtension" prefix, optionally "Const", and "Ptr" suffix.
    // E.g. "GDExtensionVariantPtr"              -> "__GdextVariant"
    //      "GDExtensionConstVariantPtr"         -> "__GdextVariant" too (const pointer)
    //      "GDExtensionUninitializedVariantPtr" -> "__GdextUninitializedVariant"
    let opaque_name = if let Some(parent) = &type_def.parent {
        if is_const {
            handle_opaque_name(parent)
        } else {
            handle_opaque_name(&type_def.name)
        }
    } else {
        handle_opaque_name(&type_def.name)
    };

    let opaque_ident = ident(&opaque_name);

    // Only generate the opaque struct definition for types that "own" it
    // (i.e., not const aliases that reference their parent's struct).
    let struct_def = if is_const && type_def.parent.is_some() {
        // Const variant: parent already defined the struct.
        TokenStream::new()
    } else {
        quote! {
            #[repr(C)]
            #[derive(Debug, Copy, Clone)]
            pub struct #opaque_ident {
                _unused: [u8; 0],
            }
        }
    };

    let type_alias = if is_const {
        quote! {
            pub type #name = *const #opaque_ident;
        }
    } else {
        quote! {
            pub type #name = *mut #opaque_ident;
        }
    };

    quote! {
        #struct_def
        #type_alias
    }
}

/// Derive opaque struct name from a handle type name.
///
/// Strips "GDExtension" prefix, optional "Const" after it, and "Ptr" suffix,
/// then prepends "__Gdext".
fn handle_opaque_name(handle_name: &str) -> String {
    let stripped = handle_name
        .strip_prefix("GDExtension")
        .unwrap_or(handle_name);
    let stripped = stripped.strip_prefix("Const").unwrap_or(stripped);
    let stripped = stripped.strip_suffix("Ptr").unwrap_or(stripped);
    format!("__Gdext{stripped}")
}

fn generate_alias_type(type_def: &HeaderType) -> TokenStream {
    let name = ident(&type_def.name);
    let target_type = type_def.type_.as_ref().map(|t| map_c_type(t));

    quote! {
        pub type #name = #target_type;
    }
}

fn generate_struct_type(type_def: &HeaderType) -> TokenStream {
    let name = ident(&type_def.name);

    let fields = if let Some(members) = &type_def.members {
        members
            .iter()
            .map(|member| {
                let field_name = safe_ident(&member.name);
                let field_type = map_c_type(&member.type_);
                quote! {
                    pub #field_name: #field_type,
                }
            })
            .collect::<Vec<_>>()
    } else {
        vec![]
    };

    quote! {
        #[repr(C)]
        #[derive(Debug, Copy, Clone)]
        pub struct #name {
            #( #fields )*
        }
    }
}

fn generate_function_type(type_def: &HeaderType) -> TokenStream {
    let name = ident(&type_def.name);
    let return_clause = type_def
        .return_value
        .as_ref()
        .map(map_return_clause)
        .unwrap_or_default();

    let params = type_def
        .arguments
        .as_ref()
        .map(|args| generate_params(args))
        .unwrap_or_default();

    // C function pointer typedefs are nullable, so wrap in Option.
    quote! {
        pub type #name = Option<unsafe extern "C" fn(#( #params ),*) #return_clause>;
    }
}

/// Generate named parameter tokens from a list of arguments.
fn generate_params(args: &[crate::models::header_json::HeaderArgument]) -> Vec<TokenStream> {
    args.iter()
        .map(|arg| {
            let param_type = map_c_type(&arg.type_);
            if let Some(param_name_str) = &arg.name {
                if param_name_str.is_empty() {
                    quote! { #param_type }
                } else {
                    let param_name = safe_ident(param_name_str);
                    quote! { #param_name: #param_type }
                }
            } else {
                quote! { #param_type }
            }
        })
        .collect()
}

fn map_c_type(c_type: &str) -> TokenStream {
    // Code duplication: pointer parsing logic - conv/type_conversions.rs::to_rust_type_uncached().

    let (is_const, c_type) = if let Some(rest) = c_type.strip_prefix("const ") {
        (true, rest.trim())
    } else {
        (false, c_type)
    };

    // Handle pointer types
    if c_type.ends_with('*') {
        let base_type = c_type.trim_end_matches('*').trim();
        let inner = map_c_type_as_pointee(base_type);

        return if is_const {
            quote! { *const #inner }
        } else {
            quote! { *mut #inner }
        };
    }

    // Base types
    map_c_base_type(c_type)
}

/// Map a C type that appears as the pointee of a pointer.
/// `void` maps to `std::ffi::c_void` (not `()`) so that `void*` becomes `*mut c_void`.
fn map_c_type_as_pointee(c_type: &str) -> TokenStream {
    if c_type == "void" {
        quote! { std::ffi::c_void }
    } else {
        map_c_type(c_type)
    }
}

/// Map a C base type (non-pointer) to a Rust type.
fn map_c_base_type(c_type: &str) -> TokenStream {
    match c_type {
        "void" => quote! { () },
        "char" => quote! { std::ffi::c_char },
        "int" => quote! { std::ffi::c_int }, // Only appears once in current JSON (worker_thread_pool_add_native_group_task).
        "int8_t" => quote! { i8 },
        "int16_t" => quote! { i16 },
        "int32_t" => quote! { i32 },
        "int64_t" => quote! { i64 },
        "uint8_t" => quote! { u8 },
        "uint16_t" => quote! { u16 },
        "uint32_t" => quote! { u32 },
        "uint64_t" => quote! { u64 },
        "size_t" => quote! { usize },
        "float" => quote! { f32 },
        "double" => quote! { f64 },
        _ => {
            // Fallback: use the type as-is (should be a GDExtension type)
            let type_ident = ident(c_type);
            quote! { #type_ident }
        }
    }
}

/// Map a return value to a return clause (`-> T`), or empty for void.
fn map_return_clause(return_value: &HeaderReturnValue) -> TokenStream {
    if return_value.type_ == "void" {
        TokenStream::new()
    } else {
        let ty = map_c_type(&return_value.type_);
        quote! { -> #ty }
    }
}

// ----------------------------------------------------------------------------------------------------------------------------------------------
// Tests

#[cfg(test)] #[cfg_attr(published_docs, doc(cfg(test)))]
mod tests {
    use nanoserde::DeJson;

    use super::*;

    fn load_header() -> HeaderJson {
        let mut watch = godot_bindings::StopWatch::start();
        let json_str = godot_bindings::load_gdextension_interface_json(&mut watch);
        DeJson::deserialize_json(json_str.as_ref()).expect("failed to deserialize JSON")
    }

    #[test]
    fn test_generate_header_code() {
        let header = load_header();

        // Test structs/enums/pointer types generation.
        let header_types = generate_header_types(&header.types).to_string();
        assert!(header_types.contains("pub type GDExtensionVariantType"));
        assert!(header_types.contains("GDEXTENSION_VARIANT_TYPE_NIL"));
        assert!(header_types.contains("pub struct GDExtensionCallError"));
        // Handle types generate opaque struct pointers.
        assert!(header_types.contains("pub struct __GdextMethodBind"));
        assert!(header_types.contains("* const __GdextMethodBind"));
        // Mutable handle pointers.
        assert!(header_types.contains("* mut __GdextVariant"));
        // Const handles produce *const pointers.
        assert!(header_types.contains("* const __GdextVariant"));
        // Callback function types (from `types` section) are still Option-wrapped.
        assert!(header_types.contains("Option < unsafe extern \"C\" fn"));

        let parts = generate_interface_parts(&header.interface);

        // Test interface typedefs (bare fn ptrs, not Option-wrapped).
        let function_types = parts.function_types.to_string();
        assert!(function_types.contains("pub type GDExtensionInterfaceMemAlloc"));
        assert!(function_types.contains("unsafe extern \"C\" fn"));
        assert!(
            !function_types.contains("Option"),
            "interface typedefs should be bare fn ptrs, not Option"
        );

        // Test GDExtensionInterface struct (bare typedefs, no Option wrapping).
        let struct_def = parts.struct_def.to_string();
        assert!(struct_def.contains("pub struct GDExtensionInterface"));
        assert!(struct_def.contains("pub mem_alloc : GDExtensionInterfaceMemAlloc"));
        assert!(!struct_def.contains("Option"));

        // Test GDExtensionInterface impl with load() function.
        let struct_impl = parts.struct_impl.to_string();
        assert!(struct_impl.contains("unsafe fn load"));
        assert!(struct_impl.contains("get_proc_address"));
        assert!(struct_impl.contains("transmute"));
        // Should use unwrap_or_else/panic, not raw transmute of Option.
        assert!(struct_impl.contains("unwrap_or_else"));
    }
}