oo-bindgen 0.8.0

DSL-based binding geneator for C, C++, Java, and C#
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
517
518
519
use crate::backend::dotnet::helpers::*;
use crate::backend::dotnet::*;

trait ConstantReturnValue {
    fn get_constant_return_value(&self) -> String;
}

trait MaybeConstantReturnValue {
    fn try_get_constant_return_value(&self) -> Option<String>;
}

impl<T> MaybeConstantReturnValue for T
where
    T: ConstantReturnValue,
{
    fn try_get_constant_return_value(&self) -> Option<String> {
        Some(self.get_constant_return_value())
    }
}

impl ConstantReturnValue for PrimitiveValue {
    fn get_constant_return_value(&self) -> String {
        match self {
            PrimitiveValue::Bool(x) => x.to_string(),
            PrimitiveValue::U8(x) => x.to_string(),
            PrimitiveValue::S8(x) => x.to_string(),
            PrimitiveValue::U16(x) => x.to_string(),
            PrimitiveValue::S16(x) => x.to_string(),
            PrimitiveValue::U32(x) => x.to_string(),
            PrimitiveValue::S32(x) => x.to_string(),
            PrimitiveValue::U64(x) => x.to_string(),
            PrimitiveValue::S64(x) => x.to_string(),
            PrimitiveValue::Float(x) => x.to_string(),
            PrimitiveValue::Double(x) => x.to_string(),
        }
    }
}

impl ConstantReturnValue for EnumValue {
    fn get_constant_return_value(&self) -> String {
        format!(
            "{}.{}",
            self.handle.name.camel_case(),
            self.variant.name.camel_case()
        )
    }
}

impl ConstantReturnValue for DurationValue {
    fn get_constant_return_value(&self) -> String {
        match self {
            DurationValue::Milliseconds(x) => format!("TimeSpan.FromMilliseconds({x})"),
            DurationValue::Seconds(x) => format!("TimeSpan.FromSeconds({x})"),
        }
    }
}

impl ConstantReturnValue for BasicValue {
    fn get_constant_return_value(&self) -> String {
        match self {
            BasicValue::Primitive(x) => x.get_constant_return_value(),
            BasicValue::Duration(x) => x.get_constant_return_value(),
            BasicValue::Enum(x) => x.get_constant_return_value(),
        }
    }
}

impl ConstantReturnValue for ZeroParameterStructInitializer {
    fn get_constant_return_value(&self) -> String {
        match self.initializer.initializer_type {
            InitializerType::Normal => format!("new {}()", self.handle.name().camel_case()),
            InitializerType::Static => format!(
                "{}.{}()",
                self.handle.name().camel_case(),
                self.initializer.name.camel_case()
            ),
        }
    }
}

impl MaybeConstantReturnValue for DefaultCallbackReturnValue {
    fn try_get_constant_return_value(&self) -> Option<String> {
        match self {
            DefaultCallbackReturnValue::Void => None,
            DefaultCallbackReturnValue::Basic(x) => x.try_get_constant_return_value(),
            DefaultCallbackReturnValue::InitializedStruct(x) => x.try_get_constant_return_value(),
        }
    }
}

pub(crate) fn generate(
    f: &mut dyn Printer,
    interface: &InterfaceType<Validated>,
    lib: &Library,
    framework: TargetFramework,
) -> FormattingResult<()> {
    let interface_name = format!("I{}", interface.name().camel_case());

    let destroy_func_name = lib.settings.interface.destroy_func_name.clone();
    let ctx_variable_name = lib.settings.interface.context_variable_name.clone();

    print_license(f, &lib.info.license_description)?;
    print_imports(f)?;
    f.newline()?;

    let is_private = interface
        .untyped()
        .get_functional_callback()
        .map(|cb| cb.functional_transform.enabled())
        .unwrap_or(false);
    let visibility = if is_private { "internal" } else { "public" };

    namespaced(f, &lib.settings.name, |f| {
        documentation(f, |f| {
            // Print top-level documentation
            xmldoc_print(f, interface.doc())
        })?;

        f.writeln(&format!("{visibility} interface {interface_name}"))?;
        blocked(f, |f| {
            // Write each required method
            interface.untyped().callbacks.iter().try_for_each(|func| {
                // Documentation
                documentation(f, |f| {
                    // Print top-level documentation
                    xmldoc_print(f, &func.doc)?;
                    f.newline()?;

                    // Print each parameter value
                    for arg in &func.arguments {
                        f.writeln(&format!("<param name=\"{}\">", arg.name.mixed_case()))?;
                        docstring_print(f, &arg.doc)?;
                        f.write("</param>")?;
                    }

                    // Print return value
                    if let Some(doc) = &func.return_type.get_doc() {
                        f.writeln("<returns>")?;
                        docstring_print(f, doc)?;
                        f.write("</returns>")?;
                    }

                    Ok(())
                })?;

                // Callback signature
                f.writeln(&format!(
                    "{} {}(",
                    func.return_type.get_dotnet_type(),
                    func.name.camel_case()
                ))?;
                f.write(
                    &func
                        .arguments
                        .iter()
                        .map(|arg| {
                            format!(
                                "{} {}",
                                arg.arg_type.get_dotnet_type(),
                                arg.name.mixed_case()
                            )
                        })
                        .collect::<Vec<String>>()
                        .join(", "),
                )?;
                match &func.default_implementation {
                    None => {
                        f.write(");")
                    }
                    Some(di) => {
                        if framework.supports_default_interface_methods() {
                            match di.try_get_constant_return_value() {
                                None => {
                                    f.write(") {}")
                                }
                                Some(value) => {
                                    f.write(") {")?;
                                    indented(f, |f| {
                                        f.writeln(&format!("return {value};"))
                                    })?;
                                    f.writeln("}")
                                }
                            }
                        } else {
                            tracing::warn!("Method {}::{} has a default implementation defined, but it cannot be supported in C# 7.3", interface.name().camel_case(), func.name.camel_case());
                            f.write(");")
                        }
                    }
                }
            })
        })?;

        f.newline()?;

        // Write the Action<>/Func<> based implementation if it's a functional interface
        if let Some(callback) = interface.untyped().get_functional_callback() {
            namespaced(f, "functional", |f| {
                generate_functional_helpers(f, interface.untyped(), callback)
            })?;
            f.newline()?;
        }

        // write a Task-based implementation if it's a future interface
        if let InterfaceType::Future(fi) = interface {
            let class_name = fi.interface.name.camel_case();
            let value_type = fi.value_type.get_dotnet_type();
            let success_method_name = fi
                .interface
                .settings
                .future
                .success_callback_method_name
                .camel_case();

            f.writeln(&format!("internal class {class_name}: {interface_name}"))?;
            blocked(f, |f| {
                f.writeln(&format!(
                    "private TaskCompletionSource<{value_type}> tcs = new TaskCompletionSource<{value_type}>();"
                ))?;
                f.newline()?;
                f.writeln(&format!(
                    "internal {class_name}(TaskCompletionSource<{value_type}> tcs)"
                ))?;
                blocked(f, |f| f.writeln("this.tcs = tcs;"))?;
                f.newline()?;
                f.writeln(&format!(
                    "void {interface_name}.{success_method_name}({value_type} value)"
                ))?;
                blocked(f, |f| f.writeln("Task.Run(() => tcs.SetResult(value));"))?;
                f.newline()?;

                let error_method_name = fi
                    .interface
                    .settings
                    .future
                    .failure_callback_method_name
                    .camel_case();
                f.writeln(&format!(
                    "void {}.{}({} err)",
                    interface_name,
                    error_method_name,
                    fi.error_type.inner.get_dotnet_type()
                ))?;
                blocked(f, |f| {
                    f.writeln(&format!(
                        "Task.Run(() => tcs.SetException(new {}(err)));",
                        fi.error_type.exception_name.camel_case()
                    ))
                })?;

                Ok(())
            })?;
            f.newline()?;
        }

        // Create the native adapter
        f.writeln("[StructLayout(LayoutKind.Sequential)]")?;
        f.writeln(&format!("internal struct {interface_name}NativeAdapter"))?;
        blocked(f, |f| {
            // Define each delegate type
            for cb in &interface.untyped().callbacks {
                f.writeln("[UnmanagedFunctionPointer(CallingConvention.Cdecl)]")?; // C calling convetion
                f.writeln(&format!(
                    "private delegate {} {}_delegate(",
                    cb.return_type.get_native_type(),
                    cb.name
                ))?;
                f.write(
                    &cb.arguments
                        .iter()
                        .map(|arg| {
                            format!(
                                "{} {}",
                                arg.arg_type.get_native_type(),
                                arg.name.mixed_case()
                            )
                        })
                        .chain(std::iter::once(format!(
                            "IntPtr {}",
                            lib.settings.interface.context_variable_name
                        )))
                        .collect::<Vec<String>>()
                        .join(", "),
                )?;
                f.write(");")?;
                f.writeln(&format!(
                    "private static {}_delegate {}_static_delegate = {}NativeAdapter.{}_cb;",
                    cb.name, cb.name, interface_name, cb.name
                ))?;
            }

            f.writeln("[UnmanagedFunctionPointer(CallingConvention.Cdecl)]")?; // C calling convetion
            f.writeln(&format!(
                "private delegate void {destroy_func_name}_delegate(IntPtr arg);"
            ))?;

            f.writeln(&format!(
                "private static {destroy_func_name}_delegate {destroy_func_name}_static_delegate = {interface_name}NativeAdapter.{destroy_func_name}_cb;"
            ))?;

            f.newline()?;

            // Define each structure element that will be marshalled
            for cb in &interface.untyped().callbacks {
                f.writeln(&format!("private {}_delegate {};", cb.name, cb.name))?;
            }

            f.writeln(&format!(
                "private {destroy_func_name}_delegate {destroy_func_name};"
            ))?;
            f.writeln(&format!("public IntPtr {ctx_variable_name};"))?;

            f.newline()?;

            // Define the constructor
            f.writeln(&format!(
                "internal {interface_name}NativeAdapter({interface_name} impl)"
            ))?;
            blocked(f, |f| {
                f.writeln("var _handle = GCHandle.Alloc(impl);")?;
                f.newline()?;

                for cb in &interface.untyped().callbacks {
                    f.writeln(&format!(
                        "this.{} = {}NativeAdapter.{}_static_delegate;",
                        cb.name, interface_name, cb.name
                    ))?;

                    f.newline()?;
                }

                f.writeln(&format!(
                    "this.{destroy_func_name} = {interface_name}NativeAdapter.{destroy_func_name}_static_delegate;"
                ))?;

                f.writeln(&format!(
                    "this.{ctx_variable_name} = GCHandle.ToIntPtr(_handle);"
                ))?;
                Ok(())
            })?;

            // Define each delegate function
            for cb in &interface.untyped().callbacks {
                f.writeln(&format!(
                    "internal static {} {}_cb(",
                    cb.return_type.get_native_type(),
                    cb.name
                ))?;
                f.write(
                    &cb.arguments
                        .iter()
                        .map(|arg| {
                            format!(
                                "{} {}",
                                arg.arg_type.get_native_type(),
                                arg.name.mixed_case()
                            )
                        })
                        .chain(std::iter::once(format!("IntPtr {ctx_variable_name}")))
                        .collect::<Vec<String>>()
                        .join(", "),
                )?;
                f.write(")")?;

                blocked(f, |f| {
                    f.writeln(&format!(
                        "var _handle = GCHandle.FromIntPtr({ctx_variable_name});"
                    ))?;
                    f.writeln(&format!("var _impl = ({interface_name})_handle.Target;"))?;
                    call_dotnet_function(f, cb, "return ")
                })?;

                f.newline()?;
            }

            // destroy delegate
            f.writeln(&format!(
                "internal static void {destroy_func_name}_cb(IntPtr arg)"
            ))?;

            blocked(f, |f| {
                f.writeln("var _handle = GCHandle.FromIntPtr(arg);")?;
                f.writeln("_handle.Free();")
            })?;

            f.newline()?;

            f.newline()?;

            // Write the conversion routine
            f.writeln(&format!(
                "internal static {interface_name} FromNative(IntPtr self)"
            ))?;
            blocked(f, |f| {
                f.writeln("if (self != IntPtr.Zero)")?;
                blocked(f, |f| {
                    f.writeln("var handle = GCHandle.FromIntPtr(self);")?;
                    f.writeln(&format!("return handle.Target as {interface_name};"))
                })?;
                f.writeln("else")?;
                blocked(f, |f| f.writeln("return null;"))
            })
        })
    })
}

pub(crate) fn generate_interface_implementation(
    f: &mut dyn Printer,
    interface: &Handle<Interface<Validated>>,
    cb: &CallbackFunction<Validated>,
) -> FormattingResult<()> {
    let functor_type = full_functor_type(cb);

    f.writeln(&format!(
        "internal class Implementation: I{}",
        interface.name.camel_case()
    ))?;
    blocked(f, |f| {
        f.writeln(&format!("private readonly {functor_type} action;"))?;
        f.newline()?;

        // constructor
        f.writeln(&format!("internal Implementation({functor_type} action)"))?;
        blocked(f, |f| f.writeln("this.action = action;"))?;

        f.newline()?;

        f.writeln(&format!(
            "public {} {}(",
            cb.return_type.get_dotnet_type(),
            cb.name.camel_case()
        ))?;
        f.write(
            &cb.arguments
                .iter()
                .map(|param| {
                    format!(
                        "{} {}",
                        param.arg_type.get_dotnet_type(),
                        param.name.mixed_case()
                    )
                })
                .collect::<Vec<_>>()
                .join(", "),
        )?;
        f.write(")")?;
        blocked(f, |f| {
            f.newline()?;

            if !cb.return_type.is_none() {
                f.write("return ")?;
            }

            let params = cb
                .arguments
                .iter()
                .map(|param| param.name.mixed_case())
                .collect::<Vec<_>>()
                .join(", ");

            f.write(&format!("this.action.Invoke({params});"))
        })
    })
}

pub(crate) fn generate_functional_helpers(
    f: &mut dyn Printer,
    interface: &Handle<Interface<Validated>>,
    cb: &CallbackFunction<Validated>,
) -> FormattingResult<()> {
    let interface_name = format!("I{}", interface.name.camel_case());
    let class_name = interface.name.camel_case();
    let functor_type = full_functor_type(cb);

    let visibility = if cb.functional_transform.enabled() {
        "internal"
    } else {
        "public"
    };

    documentation(f, |f| {
        f.writeln("<summary>")?;
        f.writeln(&format!(
            "Provides a method to create an implementation of {interface_name} from a functor"
        ))?;
        f.writeln("</summary>")
    })?;
    f.writeln(&format!("{visibility} static class {class_name}"))?;
    blocked(f, |f| {
        f.newline()?;
        // write the private implementation class
        generate_interface_implementation(f, interface, cb)?;
        f.newline()?;

        documentation(f, |f| {
            f.writeln("<summary>")?;
            f.write(&format!(
                "Creates an instance of {} which invokes a {}",
                interface_name,
                base_functor_type(cb)
            ))?;
            f.write("</summary>")?;
            f.newline()?;
            f.writeln("<param name=\"action\">")?;
            f.writeln("Callback to execute")?;
            f.writeln("</param>")?;
            f.writeln(&format!(
                "<return>An implementation of {interface_name}</return>"
            ))?;
            Ok(())
        })?;
        // write the factory function
        f.writeln(&format!(
            "{visibility} static {interface_name} create({functor_type} action)"
        ))?;
        blocked(f, |f| f.writeln("return new Implementation(action);"))?;

        Ok(())
    })
}