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
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
use super::functions::{is_bytes_result_method, params_require_marshal};
use super::types::{cgo_type_for_primitive, emit_type_doc, go_return_expr, primitive_max_sentinel};
use crate::backends::go::type_map::{go_optional_type, go_type, go_zero_value};
use crate::codegen::naming::{go_param_name, go_type_name, to_go_name};
use crate::core::ir::{MethodDef, ParamDef, TypeDef, TypeRef};
use heck::ToSnakeCase;
/// Generate a streaming wrapper for a method decorated with the `Streaming` adapter pattern.
///
/// The returned Go method consumes the FFI iterator-handle exports
/// (`<prefix>_<type>_<method>_start`, `_next`, `_free`) and exposes a typed
/// `<-chan <ItemType>` to Go callers. A goroutine drives `_next` until null
/// (clean end-of-stream) or an error is signalled, then frees the handle.
#[allow(clippy::too_many_arguments)]
pub(super) fn gen_streaming_method_wrapper(
typ: &TypeDef,
method: &MethodDef,
ffi_prefix: &str,
item_type: &str,
data_enum_names: &std::collections::HashSet<&str>,
opaque_names: &std::collections::HashSet<&str>,
_value_only_types: &std::collections::HashSet<String>,
enum_names: &std::collections::HashSet<String>,
ffi_param_enum_names: &std::collections::HashSet<String>,
) -> String {
let mut out = String::with_capacity(2048);
let method_go_name = to_go_name(&method.name);
emit_type_doc(&mut out, &method_go_name, &method.doc, "is a streaming method.");
// Receiver name follows the pattern used by gen_method_wrapper: opaque -> "h", non-opaque -> "r".
let receiver_name = if typ.is_opaque { "h" } else { "r" };
let go_receiver_type = go_type_name(&typ.name);
let item_go_type = go_type_name(item_type);
// A data-enum item type is emitted as a Go sealed interface. A bare
// `json.Unmarshal` into a named-interface variable fails at runtime
// ("cannot unmarshal object into Go value of type <Interface>"), so the
// generated `Unmarshal<Type>` discriminator function must be used instead.
let item_is_sum_type = data_enum_names.contains(item_type);
// Build the parameter list mirroring gen_method_wrapper. We do not honour
// bridge stripping here because streaming adapters never use trait bridges.
let params: Vec<String> = method
.params
.iter()
.map(|p| {
let param_type: String = if p.optional {
go_optional_type(&p.ty).into_owned()
} else if let TypeRef::Named(name) = &p.ty {
if opaque_names.contains(name.as_str()) {
format!("*{}", go_type(&p.ty))
} else {
go_type(&p.ty).into_owned()
}
} else {
go_type(&p.ty).into_owned()
};
format!("{} {}", go_param_name(&p.name), param_type)
})
.collect();
out.push_str(&crate::backends::go::template_env::render(
"streaming_method_signature.jinja",
minijinja::context! {
receiver_name => receiver_name,
receiver_type => &go_receiver_type,
method_name => &method_go_name,
params => params.join(", "),
item_type => &item_go_type,
},
));
// Marshal each parameter exactly like gen_method_wrapper does for the
// synchronous case. The start function's signature accepts the same C
// request handle as the regular `chat` method, so reuse the existing
// gen_param_to_c emitter (returning `(value, error)`-shape).
for param in &method.params {
out.push_str(&gen_param_to_c(
param,
/* err_return_prefix = */
"nil, ", // streaming returns (<-chan T, error); channel zero-value is nil
/* can_return_error = */ true,
ffi_prefix,
opaque_names,
enum_names,
ffi_param_enum_names,
));
}
// Build the C parameter list (e.g. `cReq`) — same as gen_method_wrapper.
let c_params: Vec<String> = method
.params
.iter()
.flat_map(|p| -> Vec<String> {
let c_name = go_param_name(&format!("c_{}", p.name));
if matches!(p.ty, TypeRef::Bytes) {
vec![c_name.clone(), format!("{}Len", c_name)]
} else {
vec![c_name]
}
})
.collect();
let type_snake = typ.name.to_snake_case();
let method_snake = method.name.to_snake_case();
let item_snake = item_type.to_snake_case();
let upper_prefix = ffi_prefix.to_uppercase();
// Start the stream. Non-static streaming methods always have a non-null
// opaque receiver — cast `h.ptr` like other opaque-receiver methods do.
let c_receiver = format!(
"(*C.{}{})(unsafe.Pointer({}.ptr))",
upper_prefix, typ.name, receiver_name
);
let start_call = if c_params.is_empty() {
format!("C.{}_{}_{}_start({})", ffi_prefix, type_snake, method_snake, c_receiver)
} else {
format!(
"C.{}_{}_{}_start({}, {})",
ffi_prefix,
type_snake,
method_snake,
c_receiver,
c_params.join(", "),
)
};
out.push_str(&crate::backends::go::template_env::render(
"streaming_method_body.jinja",
minijinja::context! {
start_call => &start_call,
ffi_prefix => ffi_prefix,
type_snake => &type_snake,
method_snake => &method_snake,
item_snake => &item_snake,
item_type => &item_go_type,
item_is_sum_type => item_is_sum_type,
},
));
out
}
/// Generate a wrapper method for a struct method.
pub(super) fn gen_method_wrapper(
typ: &TypeDef,
method: &MethodDef,
ffi_prefix: &str,
opaque_names: &std::collections::HashSet<&str>,
value_only_types: &std::collections::HashSet<String>,
enum_names: &std::collections::HashSet<String>,
ffi_param_enum_names: &std::collections::HashSet<String>,
) -> String {
let mut out = String::with_capacity(2048);
let method_go_name = to_go_name(&method.name);
emit_type_doc(&mut out, &method_go_name, &method.doc, "is a method.");
// A non-opaque, non-static method marshals its receiver to JSON — that is fallible.
// Also include params that require marshaling.
let receiver_requires_marshal = !method.is_static && !typ.is_opaque;
let method_marshals = receiver_requires_marshal || params_require_marshal(&method.params, opaque_names);
let method_can_return_error = method.error_type.is_some() || method_marshals;
// Detect Result<Vec<u8>> — uses out-param convention, always returns ([]byte, error).
let is_bytes_result = is_bytes_result_method(method);
let return_type = if is_bytes_result {
// Out-param bytes result always returns ([]byte, error)
"([]byte, error)".to_string()
} else if method_can_return_error {
if matches!(method.return_type, TypeRef::Unit) {
"error".to_string()
} else {
// Scalar types (primitives, Duration, String, Char, Path) stay scalar in the (value, error) tuple.
// Their conversion bodies produce value expressions or closures returning the bare Go type,
// so the signature must match.
// Named / Json / Optional / reference types keep go_optional_type because their conversion
// bodies produce pointer/slice values and the signature must match.
let ret_go_type = if matches!(
method.return_type,
TypeRef::Primitive(_) | TypeRef::Duration | TypeRef::String | TypeRef::Char | TypeRef::Path
) {
go_type(&method.return_type).into_owned()
} else {
go_optional_type(&method.return_type).into_owned()
};
format!("({}, error)", ret_go_type)
}
} else if matches!(method.return_type, TypeRef::Unit) {
"".to_string()
} else if matches!(
method.return_type,
TypeRef::Primitive(_) | TypeRef::Duration | TypeRef::String | TypeRef::Char | TypeRef::Path
) {
// Mirrors the value-form scalar-return condition in the `method_can_return_error`
// branch above. The body emitter (`go_return_expr` in `types.rs`) produces a plain
// value expression for `TypeRef::Primitive` (e.g. `ptr != 0`, `uint(ptr)`) and
// closures for string types that return the bare Go type, so the signature must use
// the value type — `*bool`/`*string` here would mismatch the body.
go_type(&method.return_type).into_owned()
} else {
go_optional_type(&method.return_type).into_owned()
};
// Opaque types use "h" (for "handle") to match the receiver name in Free().
// Non-opaque types use "r" (for "receiver").
let receiver_name = if typ.is_opaque { "h" } else { "r" };
let go_receiver_type = go_type_name(&typ.name);
let params: Vec<String> = method
.params
.iter()
.map(|p| {
let param_type: String = if p.optional {
go_optional_type(&p.ty).into_owned()
} else if let TypeRef::Named(name) = &p.ty {
if opaque_names.contains(name.as_str()) {
format!("*{}", go_type(&p.ty))
} else {
go_type(&p.ty).into_owned()
}
} else {
go_type(&p.ty).into_owned()
};
format!("{} {}", go_param_name(&p.name), param_type)
})
.collect();
let params_str = params.join(", ");
// Prefix return type with a space so the template can emit `() returntype {`
// or `() {` (no double-space) when return_type is empty.
let ret_type_str = if return_type.is_empty() {
String::new()
} else {
format!(" {return_type}")
};
// Emit the full method signature on a single canonical line so gofmt is a no-op.
if method.is_static {
out.push_str(&crate::backends::go::template_env::render(
"method_signature_static.jinja",
minijinja::context! {
receiver_type => &go_receiver_type,
method_name => &method_go_name,
params => ¶ms_str,
return_type => &ret_type_str,
},
));
} else {
out.push_str(&crate::backends::go::template_env::render(
"method_signature_instance.jinja",
minijinja::context! {
receiver_name => receiver_name,
receiver_type => &go_receiver_type,
method_name => &method_go_name,
params => ¶ms_str,
return_type => &ret_type_str,
},
));
}
{
// Synchronous method - just convert params and call FFI
// Note: method_can_return_error is set above (includes synthesized error for marshal-requiring methods).
let returns_value_and_error = method_can_return_error && !matches!(method.return_type, TypeRef::Unit);
let param_err_return_prefix: String = if returns_value_and_error {
format!("{}, ", go_zero_value(&method.return_type))
} else {
String::new()
};
for param in &method.params {
out.push_str(&gen_param_to_c(
param,
¶m_err_return_prefix,
method_can_return_error,
ffi_prefix,
opaque_names,
enum_names,
ffi_param_enum_names,
));
}
// Bytes params expand to two C arguments: the pointer and the length.
let c_params: Vec<String> = method
.params
.iter()
.flat_map(|p| -> Vec<String> {
let c_name = go_param_name(&format!("c_{}", p.name));
if matches!(p.ty, TypeRef::Bytes) {
vec![c_name.clone(), format!("{}Len", c_name)]
} else {
vec![c_name]
}
})
.collect();
let type_snake = typ.name.to_snake_case();
let method_snake = method.name.to_snake_case();
let base_c_call = if method.is_static {
// Static methods don't pass a receiver
if c_params.is_empty() {
format!("C.{}_{}_{}()", ffi_prefix, type_snake, method_snake)
} else {
format!(
"C.{}_{}_{}({})",
ffi_prefix,
type_snake,
method_snake,
c_params.join(", ")
)
}
} else if typ.is_opaque {
// Opaque types have a ptr field — cast it directly.
let c_receiver = format!(
"(*C.{}{})(unsafe.Pointer({}.ptr))",
ffi_prefix.to_uppercase(),
typ.name,
receiver_name
);
if c_params.is_empty() {
format!("C.{}_{}_{}({})", ffi_prefix, type_snake, method_snake, c_receiver)
} else {
format!(
"C.{}_{}_{}({}, {})",
ffi_prefix,
type_snake,
method_snake,
c_receiver,
c_params.join(", ")
)
}
} else {
// Non-opaque structs: marshal to JSON, create a temporary handle, use it, and free it.
// err_prefix is the leading "<zero>, " in `return <zero>, fmt.Errorf(...)` early returns.
// For (value, error) signatures the zero value depends on the value type — `nil` for
// pointer/slice/map/Named, `0`/`false`/`""` for plain primitives/strings/bools.
let err_prefix = if returns_value_and_error {
format!("{}, ", go_zero_value(&method.return_type))
} else {
String::new()
};
// method_can_return_error is always true here (receiver_requires_marshal is true for
// non-opaque non-static methods), so we always emit fmt.Errorf, never panic.
let err_action = format!("return {err_prefix}fmt.Errorf(\"failed to marshal receiver: %w\", err)");
let from_json_err_action = format!(
"return {err_prefix}fmt.Errorf(\"failed to create receiver: %s\", C.GoString(C.{ffi_prefix}_last_error_context()))"
);
out.push_str(&crate::backends::go::template_env::render(
"marshal_receiver_to_c.jinja",
minijinja::context! {
receiver_name => receiver_name,
err_action => &err_action,
from_json_err_action => &from_json_err_action,
ffi_prefix => ffi_prefix,
type_snake => &type_snake,
},
));
if c_params.is_empty() {
format!("C.{}_{}_{}(cRecv)", ffi_prefix, type_snake, method_snake)
} else {
format!(
"C.{}_{}_{}(cRecv, {})",
ffi_prefix,
type_snake,
method_snake,
c_params.join(", ")
)
}
};
// For Result<Vec<u8>> (bytes_result), append the three out-param references to the call.
let c_call = if is_bytes_result {
let base = base_c_call.trim_end_matches(')');
if base.ends_with('(') {
format!("{}&outPtr, &outLen, &outCap)", base)
} else {
format!("{}, &outPtr, &outLen, &outCap)", base)
}
} else {
base_c_call
};
// Result<Vec<u8>> uses the out-param convention — emit specialized body and return early.
if is_bytes_result {
out.push_str(&crate::backends::go::template_env::render(
"bytes_result_call.jinja",
minijinja::context! { c_call => &c_call, ffi_prefix => ffi_prefix },
));
out.push_str("}\n");
return out;
}
// Detect builder pattern: opaque type METHOD (not static constructor) that returns the same opaque type.
// The C function consumes (Box::from_raw) the input pointer and returns a new pointer.
// Instead of creating a new Go struct, update h.ptr so the caller's handle stays valid.
// For static constructors, we create a new struct wrapper instead.
let is_builder_return = !method.is_static
&& typ.is_opaque
&& matches!(&method.return_type, TypeRef::Named(n) if n.as_str() == typ.name.as_str());
if method_can_return_error {
if matches!(method.return_type, TypeRef::Unit) {
out.push_str(&crate::backends::go::template_env::render(
"c_call_unit.jinja",
minijinja::context! {
c_call => &c_call,
},
));
// For non-opaque, non-static methods with Unit return, the C function may have
// mutated cRecv in place (e.g. apply_update). Write the updated state back to
// the Go receiver so the mutation is visible to the caller.
if !method.is_static && !typ.is_opaque {
out.push_str(&crate::backends::go::template_env::render(
"method_update_from_json.jinja",
minijinja::context! {
ffi_prefix => ffi_prefix,
type_snake => &type_snake,
recv => receiver_name,
},
));
}
if method.error_type.is_some() {
out.push_str("\treturn lastError()\n");
} else {
out.push_str("\treturn nil\n");
}
} else {
out.push_str(&crate::backends::go::template_env::render(
"c_call_with_ptr_assign.jinja",
minijinja::context! {
c_call => &c_call,
},
));
if method.error_type.is_some() {
out.push_str("\tif err := lastError(); err != nil {\n");
// Free the pointer if non-nil even on error, to avoid leaks.
// Bytes pointers are NOT freed — they alias internal storage.
if matches!(
method.return_type,
TypeRef::String | TypeRef::Char | TypeRef::Path | TypeRef::Json
) {
out.push_str("\t\tif ptr != nil {\n");
out.push_str(&crate::backends::go::template_env::render(
"free_string_on_error.jinja",
minijinja::context! {
ffi_prefix => ffi_prefix,
},
));
out.push_str("\t\t}\n");
}
// Use the type-appropriate zero value: `nil` for pointer/slice/Named returns,
// `0`/`false`/`""` for scalar Primitive/Duration value-form returns.
let zero_value = go_zero_value(&method.return_type);
out.push_str(&crate::backends::go::template_env::render(
"return_zero_err.jinja",
minijinja::context! {
zero_value => &zero_value,
},
));
out.push_str("\t}\n");
}
// Free the FFI-allocated string after unmarshaling.
// Bytes pointers are NOT freed — they alias internal storage.
if matches!(
method.return_type,
TypeRef::String | TypeRef::Char | TypeRef::Path | TypeRef::Json
) {
out.push_str(&crate::backends::go::template_env::render(
"free_string.jinja",
minijinja::context! {
ffi_prefix => ffi_prefix,
ptr => "ptr",
},
));
}
// For non-opaque Named return types, free the handle after JSON extraction.
// Opaque types are NOT freed here — the caller owns them via the Go wrapper.
if let TypeRef::Named(name) = &method.return_type {
if !opaque_names.contains(name.as_str()) {
let type_snake = name.to_snake_case();
out.push_str(&crate::backends::go::template_env::render(
"free_type.jinja",
minijinja::context! {
ffi_prefix => ffi_prefix,
type_snake => &type_snake,
ptr => "ptr",
},
));
}
}
if is_builder_return {
// Builder pattern: C consumed the old pointer and returned a new one.
// Update r.ptr in-place so the caller's handle remains valid.
out.push_str(&crate::backends::go::template_env::render(
"receiver_ptr_assign.jinja",
minijinja::context! {
receiver_name => receiver_name,
},
));
out.push_str(&crate::backends::go::template_env::render(
"return_value_and_nil.jinja",
minijinja::context! {
value => receiver_name,
},
));
} else {
let return_expr =
go_return_expr(&method.return_type, "ptr", ffi_prefix, opaque_names, value_only_types);
out.push_str(&crate::backends::go::template_env::render(
"method_return_simple.jinja",
minijinja::context! {
value => format!("{}, nil", return_expr),
},
));
}
}
} else if matches!(method.return_type, TypeRef::Unit) {
out.push_str(&crate::backends::go::template_env::render(
"c_call_simple.jinja",
minijinja::context! {
c_call => &c_call,
},
));
} else {
out.push_str(&crate::backends::go::template_env::render(
"c_call_with_ptr_assign.jinja",
minijinja::context! {
c_call => &c_call,
},
));
// Add defer free for C string returns.
// Bytes pointers are NOT freed — they alias internal storage.
if matches!(
method.return_type,
TypeRef::String | TypeRef::Char | TypeRef::Path | TypeRef::Json
) {
out.push_str(&crate::backends::go::template_env::render(
"free_string.jinja",
minijinja::context! {
ffi_prefix => ffi_prefix,
ptr => "ptr",
},
));
}
// For non-opaque Named return types, free the handle after JSON extraction.
// Opaque types are NOT freed here — the caller owns them via the Go wrapper.
if let TypeRef::Named(name) = &method.return_type {
if !opaque_names.contains(name.as_str()) {
let type_snake = name.to_snake_case();
out.push_str(&crate::backends::go::template_env::render(
"free_type.jinja",
minijinja::context! {
ffi_prefix => ffi_prefix,
type_snake => &type_snake,
ptr => "ptr",
},
));
}
}
if is_builder_return {
// Builder pattern: C consumed the old pointer and returned a new one.
// Update r.ptr in-place so the caller's handle remains valid.
out.push_str(&crate::backends::go::template_env::render(
"method_receiver_ptr_assign.jinja",
minijinja::context! {
receiver_name => receiver_name,
},
));
out.push_str(&crate::backends::go::template_env::render(
"method_return_simple.jinja",
minijinja::context! {
value => receiver_name,
},
));
} else {
let return_expr =
go_return_expr(&method.return_type, "ptr", ffi_prefix, opaque_names, value_only_types);
out.push_str(&crate::backends::go::template_env::render(
"method_return_simple.jinja",
minijinja::context! {
value => return_expr,
},
));
}
}
}
out.push_str("}\n");
out
}
/// Generate parameter conversion code from Go to C.
/// `err_return_prefix` is the leading `"<zero>, "` (or `""` for value-less returns) prepended to
/// every `return ... fmt.Errorf(...)` early exit. Callers compute it from the enclosing function's
/// return type — `"nil, "` for pointer/slice/channel returns, `"0, "` / `"false, "` / `"\"\", "`
/// for plain primitive/string returns, and `""` when the function only returns `error`.
/// `can_return_error` should be true when the enclosing function has `error` in its return type.
/// When false, marshal failures are handled with `panic` since the function signature has no error return.
pub(super) fn gen_param_to_c(
param: &ParamDef,
err_return_prefix: &str,
can_return_error: bool,
ffi_prefix: &str,
opaque_names: &std::collections::HashSet<&str>,
enum_names: &std::collections::HashSet<String>,
ffi_param_enum_names: &std::collections::HashSet<String>,
) -> String {
let mut out = String::with_capacity(512);
// Go param names must be lowerCamelCase (no underscores), and internal C-side
// temporaries use the same stem with acronym uppercasing applied.
let go_param = go_param_name(¶m.name);
let c_name = go_param_name(&format!("c_{}", param.name));
match ¶m.ty {
TypeRef::String | TypeRef::Char => {
if param.optional {
// Optional string param (ty=String, optional=true): the Go variable holds *string.
out.push_str(&crate::backends::go::template_env::render(
"param_string_optional.jinja",
minijinja::context! {
c_name => &c_name,
go_param => &go_param,
},
));
out.push('\n');
} else {
out.push_str(&crate::backends::go::template_env::render(
"param_string_required.jinja",
minijinja::context! {
c_name => &c_name,
go_param => &go_param,
},
));
out.push('\n');
}
}
TypeRef::Path => {
if param.optional {
out.push_str(&crate::backends::go::template_env::render(
"param_string_optional.jinja",
minijinja::context! {
c_name => &c_name,
go_param => &go_param,
},
));
out.push('\n');
} else {
out.push_str(&crate::backends::go::template_env::render(
"param_string_required.jinja",
minijinja::context! {
c_name => &c_name,
go_param => &go_param,
},
));
out.push('\n');
}
}
TypeRef::Bytes => {
// Empty slices have no first element — `&slice[0]` panics. Pass a nil
// pointer in that case; the FFI side reads zero bytes either way.
out.push_str(&crate::backends::go::template_env::render(
"bytes_to_c_pointer.jinja",
minijinja::context! {
c_name => &c_name,
go_param => &go_param,
},
));
out.push('\n');
}
TypeRef::Named(name) => {
if opaque_names.contains(name.as_str()) {
// Opaque types are pointer wrappers — cast the raw pointer to the C type.
let c_type = format!("{}{}", ffi_prefix.to_uppercase(), name);
out.push_str(&crate::backends::go::template_env::render(
"param_opaque_cast.jinja",
minijinja::context! {
c_name => &c_name,
go_param => &go_param,
c_type => &c_type,
},
));
out.push('\n');
} else if ffi_param_enum_names.contains(name) {
// Unit-variant enums: the go-side type is a string alias (e.g.
// `type Method string`), so convert via the existing C helper
// `{prefix}_{enum}_from_str(*c_char) -> i32` rather than direct
// `C.int32_t(...)` which would fail to compile on a string-typed value.
let enum_snake = name.to_snake_case();
out.push_str(&crate::backends::go::template_env::render(
"param_enum_to_i32.jinja",
minijinja::context! {
c_name => &c_name,
go_param => &go_param,
ffi_prefix => ffi_prefix,
enum_snake => &enum_snake,
},
));
out.push('\n');
} else if enum_names.contains(name) {
// Data enums: marshal to JSON, create a handle via _from_json.
let type_snake = name.to_snake_case();
let err_action = if can_return_error {
format!("return {err_return_prefix}fmt.Errorf(\"failed to marshal: %w\", err)")
} else {
"panic(fmt.Sprintf(\"failed to marshal: %v\", err))".to_string()
};
let from_json_err_action = if can_return_error {
format!(
"return {err_return_prefix}fmt.Errorf(\"failed to create {type_snake}: %s\", C.GoString(C.{ffi_prefix}_last_error_context()))"
)
} else {
format!(
"panic(\"failed to create {type_snake}: \" + C.GoString(C.{ffi_prefix}_last_error_context()))"
)
};
out.push_str(&crate::backends::go::template_env::render(
"param_named_type.jinja",
minijinja::context! {
c_name => &c_name,
go_param => &go_param,
err_action => &err_action,
from_json_err_action => &from_json_err_action,
ffi_prefix => ffi_prefix,
type_snake => &type_snake,
},
));
out.push('\n');
} else {
// Non-opaque, non-enum Named types: marshal to JSON, create a handle via _from_json,
// and pass that to the C function.
let type_snake = name.to_snake_case();
let err_action = if can_return_error {
format!("return {err_return_prefix}fmt.Errorf(\"failed to marshal: %w\", err)")
} else {
"panic(fmt.Sprintf(\"failed to marshal: %v\", err))".to_string()
};
let from_json_err_action = if can_return_error {
format!(
"return {err_return_prefix}fmt.Errorf(\"failed to create {type_snake}: %s\", C.GoString(C.{ffi_prefix}_last_error_context()))"
)
} else {
format!(
"panic(\"failed to create {type_snake}: \" + C.GoString(C.{ffi_prefix}_last_error_context()))"
)
};
out.push_str(&crate::backends::go::template_env::render(
"param_named_type.jinja",
minijinja::context! {
c_name => &c_name,
go_param => &go_param,
err_action => &err_action,
from_json_err_action => &from_json_err_action,
ffi_prefix => ffi_prefix,
type_snake => &type_snake,
},
));
out.push('\n');
}
}
TypeRef::Vec(_) | TypeRef::Map(_, _) | TypeRef::Json => {
// Vec, Map, and raw-JSON (json.RawMessage) types are serialized as JSON strings
// across the FFI boundary. json.Marshal on a json.RawMessage returns its bytes
// verbatim, so the same path produces the C string the call-site references.
let err_action = if can_return_error {
format!("return {err_return_prefix}fmt.Errorf(\"failed to marshal: %w\", err)")
} else {
"panic(fmt.Sprintf(\"failed to marshal: %v\", err))".to_string()
};
out.push_str(&crate::backends::go::template_env::render(
"param_vec_or_map.jinja",
minijinja::context! {
c_name => &c_name,
go_param => &go_param,
err_action => &err_action,
},
));
out.push('\n');
}
TypeRef::Optional(inner) => {
match inner.as_ref() {
TypeRef::String | TypeRef::Char | TypeRef::Path => {
out.push_str(&crate::backends::go::template_env::render(
"param_string_optional.jinja",
minijinja::context! {
c_name => &c_name,
go_param => &go_param,
},
));
out.push('\n');
}
TypeRef::Named(name) if opaque_names.contains(name.as_str()) => {
// Optional opaque type: cast the raw pointer to the C type or pass nil.
let c_type = format!("{}{}", ffi_prefix.to_uppercase(), name);
out.push_str(&crate::backends::go::template_env::render(
"param_optional_opaque.jinja",
minijinja::context! {
c_name => &c_name,
c_type => &c_type,
go_param => &go_param,
},
));
out.push('\n');
}
TypeRef::Named(_) => {
out.push_str(&crate::backends::go::template_env::render(
"param_optional_named_inline.jinja",
minijinja::context! {
c_name => &c_name,
go_param => &go_param,
},
));
out.push('\n');
}
_ => {
// For other optional types, just pass nil or default
out.push_str(&crate::backends::go::template_env::render(
"param_optional_decl.jinja",
minijinja::context! {
c_name => &c_name,
},
));
out.push('\n');
}
}
}
TypeRef::Primitive(prim) if !param.optional => {
// Non-optional primitive: cast to the CGo type so the value can be passed directly
// to C functions that expect C types (e.g., uintptr_t, uint32_t).
let cgo_ty = cgo_type_for_primitive(prim);
let go_ty = go_type(&TypeRef::Primitive(prim.clone()));
// Special case for bool: Go bool cannot be directly cast to C.uchar.
// Convert via conditional: if true, 1; else 0.
if matches!(prim, crate::core::ir::PrimitiveType::Bool) {
out.push_str(&crate::backends::go::template_env::render(
"param_primitive_bool.jinja",
minijinja::context! {
c_name => &c_name,
cgo_ty => &cgo_ty,
go_param => &go_param,
},
));
out.push('\n');
} else {
out.push_str(&crate::backends::go::template_env::render(
"param_primitive_numeric.jinja",
minijinja::context! {
c_name => &c_name,
cgo_ty => &cgo_ty,
go_ty => &go_ty,
go_param => &go_param,
},
));
out.push('\n');
}
}
TypeRef::Primitive(prim) if param.optional => {
// Optional primitive: the Go param is a pointer (*T). Dereference it if non-nil,
// otherwise pass the max-value sentinel (e.g. u64::MAX) so the FFI layer knows
// the parameter was omitted.
//
// Declare the variable using the CGo type (e.g. C.uint64_t) so that CGo does
// not reject the value when it is passed directly to the C function. Go's native
// numeric types (uint64, uint32, …) are distinct from CGo types and cannot be
// passed without an explicit cast — using the CGo type at declaration avoids a
// second cast at every call-site.
let cgo_ty = cgo_type_for_primitive(prim);
let go_ty = go_type(&TypeRef::Primitive(prim.clone()));
let sentinel = primitive_max_sentinel(prim);
// Special case for bool: Go bool cannot be directly cast to C.uchar.
if matches!(prim, crate::core::ir::PrimitiveType::Bool) {
out.push_str(&crate::backends::go::template_env::render(
"param_optional_primitive_bool.jinja",
minijinja::context! {
c_name => &c_name,
cgo_ty => &cgo_ty,
go_param => &go_param,
},
));
out.push('\n');
} else {
out.push_str(&crate::backends::go::template_env::render(
"param_optional_primitive_numeric.jinja",
minijinja::context! {
c_name => &c_name,
cgo_ty => &cgo_ty,
go_ty => &go_ty,
sentinel => &sentinel,
go_param => &go_param,
},
));
out.push('\n');
}
}
_ => {
// Primitives and other types pass through directly
}
}
if !out.is_empty() {
out.push('\n');
}
out
}
#[cfg(test)]
mod tests;