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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
/*
* 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/.
*/
//! Type and expression conversions (Godot -> Rust)
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::is_builtin_type_scalar;
use crate::util::ident;
// ----------------------------------------------------------------------------------------------------------------------------------------------
// Godot -> Rust types
/// Returns `(identifier, is_copy)` for a hardcoded Rust type, if it exists.
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) {
// Integers
("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",
// TODO handle char types as `char`?
("int", Some("char16")) => "u16",
("int", Some("char32")) => "u32",
("int", Some(meta)) => panic!("unhandled type int with meta {meta:?}"),
// Floats (with single precision builds)
("float", Some("double") | None) => "f64",
("float", Some("float")) => "f32",
("float", Some(meta)) => panic!("unhandled type float with meta {meta:?}"),
// Doubles (with double precision builds)
("double", None) => "f64",
("double", Some(meta)) => panic!("unhandled type double with meta {meta:?}"),
// Others. Keep in sync with BuiltinClass::from_json().
("bool", None) => "bool",
("String", None) => "GString",
// Arrays/Dictionaries use flexibility for parameters (Rust->Godot), and strong typing for returns (Godot->Rust).
// Keep also in line with default-exprs e.g. `Array::new()`.
("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",
},
// Types needed for native structures mapping
("uint8_t", None) => "u8",
("uint16_t", None) => "u16",
("uint32_t", None) => "u32",
("uint64_t", None) => "u64",
("int8_t", None) => "i8",
("int16_t", None) => "i16",
("int32_t", None) => "i32",
("int64_t", None) => "i64",
("real_t", None) => "real",
("void", None) => "c_void",
// meta="required" is a special case of non-null object parameters/return types.
// Other metas are unrecognized.
(ty, Some(meta)) if meta != "required" => {
panic!("unhandled type {ty:?} with meta {meta:?}")
}
_ => return None,
};
Some(ident(result))
}
fn to_hardcoded_rust_enum(ty: &str) -> Option<Ident> {
// Some types like Vector2[i].Axis may not appear in Godot's current JSON, but they are encountered
// in custom Godot builds, e.g. when extending PhysicsServer2D.
let result = match ty {
//"enum::Error" => "GodotError",
"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))
}
/// Maps an input type to a Godot type with the same C representation. This is subtly different from [`to_rust_type`],
/// which maps to an appropriate corresponding Rust type. This function should be used in situations where the C ABI for
/// a type must match the Godot equivalent exactly, such as when dealing with pointers.
pub(crate) fn to_rust_type_abi(ty: &str, ctx: &mut Context) -> (RustTy, bool) {
let mut is_obj = false;
let ty = match ty {
// In native structures, object pointers are mapped to opaque entities. Instead, an accessor function is provided.
"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)
}
/// Maps an _input_ type from the Godot JSON to the corresponding Rust type (wrapping some sort of token stream).
///
/// Uses an internal cache (via `ctx`), as several types are ubiquitous.
// TODO take TyName as input
pub(crate) fn to_rust_type<'a>(
json_ty: &'a str,
meta: Option<&'a String>,
flow: Option<FlowDirection>,
ctx: &mut Context,
) -> RustTy {
// Flow is only relevant for Array and Dictionary, which map to different Rust types depending on direction (e.g. AnyArray vs VarArray).
// For all other types, flow is don't-care and set to None. Nested collections like Array[Array] or Array[Dictionary] need flow preserved
// because the element type is recursively resolved via to_rust_type(), and the element itself may be Array or Dictionary.
let flow = match json_ty {
"Array" | "Dictionary" | "typedarray::Array" | "typedarray::Dictionary" => flow,
_ if json_ty.starts_with("typeddictionary::") => flow, // Hard to test, as of 4.6 there are no such methods in the JSON.
_ => None, // Do not panic if not set (used in to_temporary_rust_type()).
};
let full_ty = GodotTy {
ty: json_ty.to_string(),
meta: meta.cloned(),
flow,
};
// Separate find + insert slightly slower, but much easier with lifetimes.
// The insert path will be hit less often and thus doesn't matter.
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
}
}
/// Converts a Godot type to a Rust type without caching, suitable for cases where only parts of the returned RustTy are needed.
///
/// This is a lightweight alternative to [`to_rust_type()`] for scenarios where only parts of the returned `RustTy` are needed (e.g.
/// just the identifier name).
///
/// The returned type may have inaccuracies in fields that depend on metad or flow direction, so this should only be used when
/// those fields are not needed. This allows for simpler call sites in code that doesn't require complete type information.
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();
/// Transforms a Godot class/builtin/enum IDENT (without `::` or other syntax) to a Rust one
fn rustify_ty(ty: &str) -> Ident {
if is_builtin_type_scalar(ty) {
ident(ty)
} else {
// Convert as-is. Includes StringName and NodePath.
TyName::from_godot(ty).rust_ty
}
}
if ty.ends_with('*') {
// Pointer type; strip '*', see if const, and then resolve the inner type.
let mut ty = ty[0..ty.len() - 1].to_string();
// 'const' should apply to the innermost pointer, if present.
let is_const = ty.starts_with("const ") && !ty.ends_with('*');
if is_const {
ty = ty.replace("const ", "");
}
// Sys pointer type defined in `gdextension_interface` and used as param for given method, e.g. `GDExtensionInitializationFunction`.
// Note: we branch here to avoid clashes with actual GDExtension classes.
if ty.starts_with("GDExtension") {
let ty = rustify_ty(&ty);
return RustTy::RawPointer {
inner: Box::new(RustTy::SysPointerType {
tokens: quote! { sys::#ty },
}),
is_const,
};
}
// .trim() is necessary here, as Godot places a space between a type and the stars when representing a double pointer.
// Example: "int*" but "int **".
let inner_type = to_rust_type(ty.trim(), None, None, ctx);
return RustTy::RawPointer {
inner: Box::new(inner_type),
is_const,
};
}
// Only place where meta is relevant is here.
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, // would need class passed in
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") {
// Don't trigger on PackedScene ;P
if packed_arr_ty.ends_with("Array") {
return RustTy::BuiltinIdent {
ty: rustify_ty(ty),
arg_passing: ArgPassing::ByRef, // Packed arrays are passed by-ref.
};
}
} else if let Some(elem_ty) = ty.strip_prefix("typedarray::") {
// In Array, store Gd and not Option<Gd> elements.
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}"));
// In Dictionary, store Gd and not Option<Gd> elements.
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()),
};
}
// Note: do not check if it's a known engine class, because that will not work in minimal mode (since not all classes are stored)
if ctx.is_builtin(ty) || ctx.is_native_structure(ty) {
// Unchanged.
// Native structures might not all be Copy, but they should have value semantics.
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 };
// Stores unwrapped Gd<T> directly in `gd_tokens`.
let gd_tokens = quote! { Gd<#qualified_class> };
// Use Option for `impl_as_object_arg` if nullable.
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,
}
}
}
/// Converts a Godot JSON type-name to a Rust enum/bitfield.
///
/// Input: `bitfield::Mesh.ArrayFormat` or `enum::Error` **without** the `bitfield::` or `enum::` prefix. \
/// I.e. just `Mesh.ArrayFormat` or `Error`.
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" {
// FIXME – in https://github.com/godotengine/godot/pull/100673#issuecomment-2916116489 `ResourceDeepDuplicateMode` has been wrongly marked as an Engine Enum.
// Remove this workaround after the fix appears.
to_class_enum_uncached("Resource", enum_or_bitfield, is_bitfield)
} else {
// Global enum or bitfield.
let enum_or_bitfield_name = conv::make_enum_name(enum_or_bitfield);
RustTy::EngineEnum {
tokens: quote! { crate::global::#enum_or_bitfield_name },
surrounding_class: None,
is_bitfield,
}
}
}
fn to_class_enum_uncached(class: &str, enum_: &str, is_bitfield: bool) -> RustTy {
// Class-local enum or bitfield.
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,
}
}
// ----------------------------------------------------------------------------------------------------------------------------------------------
// Godot -> Rust expressions
pub(crate) fn to_rust_expr(expr: &str, ty: &RustTy) -> TokenStream {
// println!("\n> to_rust_expr({expr}, {ty:?})");
to_rust_expr_inner(expr, ty, false)
}
fn to_rust_expr_inner(expr: &str, ty: &RustTy, is_inner: bool) -> TokenStream {
// println!("> to_rust_expr_inner({expr}, {is_inner})");
// Simple literals
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() }, // VarArray or Array<T>
"{}" if matches!(ty, RustTy::BuiltinIdent { ty, .. } if ty == "AnyDictionary") => {
return quote! { AnyDictionary::new_untyped() };
}
"{}" => return quote! { Dictionary::new() }, // VarDictionary or Dictionary<K, V>
"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:?}"),
};
}
_ => {}
}
// Integer literals
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 _ },
// _ => quote! { #lit as #ty },
_ => panic!("cannot map integer literal {expr} to type {ty:?}"),
};
}
// Float literals (some floats already handled by integer literals)
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:?}"),
};
}
// "..." -> String|StringName|NodePath
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) },
//_ => panic!("cannot map string literal \"{expr}\" to type {ty:?}"),
}
};
}
// "&..." -> StringName
if let Some(expr) = expr.strip_prefix("&\"") {
let expr = expr.strip_suffix('"').expect("unmatched opening '&\"'");
return quote! { StringName::from(#expr) };
}
// "^..." -> NodePath
if let Some(expr) = expr.strip_prefix("^\"") {
let expr = expr.strip_suffix('"').expect("unmatched opening '^\"'");
return quote! { NodePath::from(#expr) };
}
// Constructor calls
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}"),
};
// Split wrapped parts by comma
let subtokens = wrapped.split(',').map(|part| {
let part = part.trim(); // ignore whitespace around commas
// If there is no comma, there will still be one part (the empty string) -- do not substitute
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 {
// i32, u16 etc. happen to be also the literal suffixes
let combined = format!("{num}{suffix}");
combined
.parse::<Literal>()
.unwrap_or_else(|_| panic!("invalid literal {combined}"))
.to_token_stream()
}
// ----------------------------------------------------------------------------------------------------------------------------------------------
// Tests
#[test]
fn gdscript_to_rust_expr() {
// The 'None' type is used to simulate absence of type information. Some tests are commented out, because this functionality is not
// yet needed. If we ever want to reuse to_rust_expr() in other contexts, we could re-enable them.
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_object = RustTy::EngineClass {
// tokens: quote! { Gd<MyClass> },
// class: "MyClass".to_string(),
// };
// let ty_object = Some(&ty_object);
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 = [
// int
("0", ty_int, quote! { 0i64 }),
("-1", ty_int, quote! { -1i64 }),
("2147483647", ty_int, quote! { 2147483647i64 }),
("-2147483648", ty_int, quote! { -2147483648i64 }),
// ("2147483647", None, quote! { 2147483647 }),
// ("-2147483648", None, quote! { -2147483648 }),
// int, meta=uint16
("0", ty_int_u16, quote! { 0u16 }),
("65535", ty_int_u16, quote! { 65535u16 }),
// float (from int/float)
("0", ty_float, quote! { 0f64 }),
("2147483647", ty_float, quote! { 2147483647f64 }),
("-1.5", ty_float, quote! { -1.5f64 }),
("2e3", ty_float, quote! { 2000f64 }),
// ("1.0", None, quote! { 1.0 }),
// ("1e-05", None, quote! { 0.00001 }),
// float, meta=f32 (from int/float)
("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 }),
// enum (from int)
("7", ty_enum, quote! { crate::obj::EngineEnum::from_ord(7) }),
// bitfield (from int)
("7", ty_bitfield, quote! { crate::obj::EngineBitfield::from_ord(7) }),
// Variant (from int)
("8", ty_variant, quote! { Variant::from(8) }),
// Special literals
("true", None, quote! { true }),
("false", None, quote! { false }),
("{}", None, quote! { Dictionary::new() }),
("[]", None, quote! { Array::new() }),
("null", ty_variant, quote! { Variant::nil() }),
// TODO implement #156:
//("null", ty_object, quote! { None }),
// String-likes
("\" \"", 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") }),
// Composites
("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() }),
// Due to type inference, it should be enough to just write `Array::new()`
("Array[Plane]([])", None, quote! { Array::new() }),
("Array[RDPipelineSpecializationConstant]([])", None, quote! { Array::new() }),
("Array[RID]([])", None, quote! { Array::new() }),
// Composites with destructuring
("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 {
// Use arbitrary type if not specified -> should not be read
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();
// println!("{actual} -> {expected}");
assert_eq!(actual, expected);
}
}
/// Converts a potential "meta" type (like u32) to its canonical type (like i64).
///
/// Avoids dragging along the meta type through [`RustTy::BuiltinIdent`].
pub(crate) fn unmap_meta(rust_ty: &RustTy) -> Option<Ident> {
let RustTy::BuiltinIdent { ty: rust_ty, .. } = rust_ty else {
return None;
};
// Don't use match because it needs allocation (unless == is repeated)
// Even though i64 and f64 can have a meta of the same type, there's no need to return that here, as there won't be any conversion.
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
}