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
use crate::{ContainerFormat, Function, Membrane, Registry, VariantFormat};
use membrane_types::{dart::dart_type, heck::ToUpperCamelCase};
use std::io::Write;

///
/// The types of interfaces that we generate. FFI and Web are used on
/// the platforms of the same name and C is used to generate headers for use by FFI.
///

pub(crate) struct Ffi {
  output: String,
  fun: Function,
}

pub(crate) struct Web {
  output: String,
  fun: Function,
}

pub(crate) struct C {
  output: String,
  fun: Function,
}

///
///
/// Convert a Function struct into a string representation of a Dart function
///
///

pub(crate) trait Builder {
  fn new(input: &Function) -> Self;
  fn build(&mut self, config: &Membrane) -> Self;
  fn as_bytes(&self) -> &[u8];
}

impl Builder for Ffi {
  fn new(input: &Function) -> Self {
    Self {
      output: "".to_string(),
      fun: input.clone(),
    }
  }

  fn as_bytes(&self) -> &[u8] {
    self.output.as_bytes()
  }

  fn build(&mut self, config: &Membrane) -> Ffi {
    let enum_registry = config
      .namespaced_registry
      .get(self.fun.namespace)
      .unwrap()
      // we've already inspected the registry for incomplete enums, now we'll have only valid ones
      .as_ref().unwrap();

    Ffi {
      output: self
        .begin()
        .signature()
        .body()
        .body_return(enum_registry, config)
        .end()
        .output
        .clone(),
      fun: self.fun.clone(),
    }
  }
}

impl Builder for Web {
  fn new(input: &Function) -> Self {
    Self {
      output: "".to_string(),
      fun: input.clone(),
    }
  }

  fn as_bytes(&self) -> &[u8] {
    self.output.as_bytes()
  }

  fn build(&mut self, _config: &Membrane) -> Web {
    Web {
      output: self.begin().signature().body().end().output.clone(),
      fun: self.fun.clone(),
    }
  }
}

impl Builder for C {
  fn new(input: &Function) -> Self {
    Self {
      output: "".to_string(),
      fun: input.clone(),
    }
  }

  fn as_bytes(&self) -> &[u8] {
    self.output.as_bytes()
  }

  fn build(&mut self, _config: &Membrane) -> C {
    C {
      output: self.begin().signature().output.clone(),
      fun: self.fun.clone(),
    }
  }
}

///
///
/// Write a string representation to the given buffer
///
///

pub(crate) trait Writable: Builder {
  fn write(&self, mut buffer: &std::fs::File) {
    buffer
      .write_all(self.as_bytes())
      .expect("function could not be written at path");
  }
}

impl Writable for Ffi {}
impl Writable for Web {}
impl Writable for C {}

impl Function {
  fn begin(&mut self) -> String {
    "\n".to_string()
  }

  fn signature(&mut self) -> String {
    format!(
      "  {output_style}{return_type} {fn_name}({fn_params}){asink}",
      output_style = if self.is_sync {
        ""
      } else if self.is_stream {
        "Stream"
      } else {
        "Future"
      },
      return_type = if self.is_sync {
        dart_type(self.return_type)
      } else {
        format!("<{}>", dart_type(self.return_type))
      },
      fn_name = self.fn_name,
      fn_params = if self.dart_outer_params.is_empty() {
        String::new()
      } else {
        format!("{{{}}}", self.dart_outer_params)
      },
      asink = if self.is_sync {
        ""
      } else if self.is_stream {
        " async*"
      } else {
        " async"
      }
    )
  }

  fn end(&mut self) -> String {
    "\n  }\n".to_string()
  }

  #[allow(clippy::only_used_in_recursion)]
  fn deserializer(
    &self,
    ty: &[&str],
    enum_tracer_registry: &Registry,
    config: &Membrane,
  ) -> String {
    let de;
    match ty[..] {
      ["String"] => "deserializer.deserializeString()",
      ["i8"] => "deserializer.deserializeInt8()",
      ["u8"] => "deserializer.deserializeUint8()",
      ["i16"] => "deserializer.deserializeInt16()",
      ["u16"] => "deserializer.deserializeUint16()",
      ["i32"] => "deserializer.deserializeInt32()",
      ["u32"] => "deserializer.deserializeUint32()",
      ["i64"] => "deserializer.deserializeInt64()",
      ["u64"] => "deserializer.deserializeUint64()",
      ["i128"] => "deserializer.deserializeInt128()",
      ["u128"] => "deserializer.deserializeUint128()",
      ["f32"] => "deserializer.deserializeFloat32()",
      ["f64"] => "deserializer.deserializeFloat64()",
      ["bool"] => "deserializer.deserializeBool()",
      ["()"] => "null",
      ["Vec", "Option", ..] => {
        de = format!(
          "List.generate(deserializer.deserializeLength(), (_i) {{
            if (deserializer.deserializeOptionTag()) {{
              return {};
            }}
            return null;
          }});",
          self.deserializer(&ty[2..], enum_tracer_registry, config)
        );
        &de
      }
      ["Vec", ..] => {
        de = format!(
          "List.generate(deserializer.deserializeLength(), (_i) {{
            return {};
          }});",
          self.deserializer(&ty[1..], enum_tracer_registry, config)
        );
        &de
      }
      ["Option", ..] => {
        de = format!(
          "() {{
            if (deserializer.deserializeOptionTag()) {{
              return {};
            }}
            return null;
          }}();",
          self.deserializer(&ty[1..], enum_tracer_registry, config)
        );
        &de
      }
      [ty, ..] => {
        de = match enum_tracer_registry.get(ty) {
          Some(ContainerFormat::Enum(variants))
            if config.c_style_enums
              && variants.values().all(|f| f.value == VariantFormat::Unit) =>
          {
            format!("{}Extension.deserialize(deserializer)", ty)
          }
          _ => format!("{}.deserialize(deserializer)", ty),
        };
        &de
      }
      [] => {
        unreachable!("Expected type information to exist")
      }
    }
    .to_string()
  }
}

trait Callable {
  fn begin(&mut self) -> &mut Self;
  fn signature(&mut self) -> &mut Self;
  fn body(&mut self) -> &mut Self;
  fn body_return(&mut self, enum_tracer_registry: &Registry, config: &Membrane) -> &mut Self;
  fn end(&mut self) -> &mut Self;
}

impl Callable for Ffi {
  fn begin(&mut self) -> &mut Self {
    self.output += &self.fun.begin();
    self
  }

  fn signature(&mut self) -> &mut Self {
    self.output += &self.fun.signature();
    self
  }

  fn body(&mut self) -> &mut Self {
    self.output += format!(
      r#" {{{disable_logging}
    final List<Pointer> _toFree = [];{fn_transforms}{receive_port}

    MembraneResponse _taskResult;
    try {{
      if (!_loggingDisabled) {{
        _log.fine('Calling Rust `{fn_name}` via C `{extern_c_fn_name}`');
      }}
      _taskResult = _bindings.{extern_c_fn_name}({native_port}{dart_inner_args});
      if (_taskResult.kind == MembraneResponseKind.panic) {{
        final ptr = _taskResult.data.cast<Utf8>();
        throw {class_name}ApiError(ptr.toDartString());
      }} else if (_taskResult.kind != MembraneResponseKind.data) {{
        throw {class_name}ApiError('Found unknown MembraneResponseKind variant, mismatched code versions?');
      }}
    }} finally {{
      _toFree.forEach((ptr) => calloc.free(ptr));
      if (!_loggingDisabled) {{
        _log.fine('Freed arguments to `{extern_c_fn_name}`');
      }}
    }}
"#,
      disable_logging = if self.fun.disable_logging {
        "final _loggingDisabled = true;"
      } else {
        ""
      },
      fn_transforms = if self.fun.dart_transforms.is_empty() {
        String::new()
      } else {
        "\n    ".to_string() + self.fun.dart_transforms + ";"
      },
      receive_port = if self.fun.is_sync {
        ""
      } else {
        "\n    final _port = ReceivePort();"
      },
      extern_c_fn_name = self.fun.extern_c_fn_name,
      fn_name = self.fun.fn_name,
      native_port = if self.fun.is_sync {
        ""
      } else {
        "_port.sendPort.nativePort"
      },
      dart_inner_args = if self.fun.dart_inner_args.is_empty() {
        String::new()
      } else if self.fun.is_sync {
        String::new() + self.fun.dart_inner_args
      } else {
        String::from(", ") + self.fun.dart_inner_args
      },
      class_name = self.fun.namespace.to_upper_camel_case()
    )
    .as_str();
    self
  }

  fn end(&mut self) -> &mut Self {
    self.output += &self.fun.end();
    self
  }

  fn body_return(&mut self, enum_tracer_registry: &Registry, config: &Membrane) -> &mut Self {
    self.output += if self.fun.is_sync {
      format!(
        r#"
    final data = _taskResult.data.cast<Uint8>();
    final length = ByteData.view(data.asTypedList(8).buffer).getInt64(0, Endian.little);
    try {{
      if (!_loggingDisabled) {{
        _log.fine('Deserializing data from {fn_name}');
      }}
      final deserializer = BincodeDeserializer(data.asTypedList(length + 8).sublist(8));
      if (deserializer.deserializeUint8() == MembraneMsgKind.ok) {{
        return {return_de};
      }}
      throw {class_name}ApiError({error_de});
    }} finally {{
      if (_taskResult.kind == MembraneResponseKind.data && _bindings.membrane_free_membrane_vec(length + 8, _taskResult.data) < 1) {{
        throw {class_name}ApiError('Resource freeing call to C failed');
      }}
    }}"#,
        return_de = self.fun.deserializer(self.fun.return_type, enum_tracer_registry, config),
        error_de = self.fun.deserializer(self.fun.error_type, enum_tracer_registry, config),
        class_name = self.fun.namespace.to_upper_camel_case(),
        fn_name = self.fun.fn_name,
      )
    } else if self.fun.is_stream {
      format!(
        r#"
    try {{
      yield* _port{timeout}.map((input) {{
        if (!_loggingDisabled) {{
          _log.fine('Deserializing data from {fn_name}');
        }}
        final deserializer = BincodeDeserializer(input as Uint8List);
        if (deserializer.deserializeUint8() == MembraneMsgKind.ok) {{
          return {return_de};
        }}
        throw {class_name}ApiError({error_de});
      }});
    }} finally {{
      if (_taskResult.kind == MembraneResponseKind.data && _bindings.membrane_cancel_membrane_task(_taskResult.data) < 1) {{
        throw {class_name}ApiError('Cancellation call to C failed');
      }}
    }}"#,
        return_de = self.fun.deserializer(self.fun.return_type, enum_tracer_registry, config),
        error_de = self.fun.deserializer(self.fun.error_type, enum_tracer_registry, config),
        class_name = self.fun.namespace.to_upper_camel_case(),
        fn_name = self.fun.fn_name,
        timeout = if let Some(val) = self.fun.timeout {
          // check the async_dart option configured timeout
          format!(".timeout(const Duration(milliseconds: {}))", val)
        } else {
          // we default to no timeout even if a global timeout is configured because
          // having all streams auto-disconnect after a pause in events is not desirable
          "".to_string()
        },
      )
    } else {
      format!(
        r#"
    try {{
      if (!_loggingDisabled) {{
        _log.fine('Deserializing data from {fn_name}');
      }}
      final deserializer = BincodeDeserializer(await _port.first{timeout} as Uint8List);
      if (deserializer.deserializeUint8() == MembraneMsgKind.ok) {{
        return {return_de};
      }}
      throw {class_name}ApiError({error_de});
    }} finally {{
      if (_taskResult.kind == MembraneResponseKind.data && _bindings.membrane_cancel_membrane_task(_taskResult.data) < 1) {{
        throw {class_name}ApiError('Cancellation call to C failed');
      }}
    }}"#,
        return_de = self.fun.deserializer(self.fun.return_type, enum_tracer_registry, config),
        error_de = self.fun.deserializer(self.fun.error_type, enum_tracer_registry, config),
        class_name = self.fun.namespace.to_upper_camel_case(),
        fn_name = self.fun.fn_name,
        timeout = if let Some(val) = self.fun.timeout {
          // if #[async_dart(timeout = false)] is set then it will be represented
          //  here as a -1 value and we will disable the timeout for this instance
          if val < 0 {
            "".to_string()
          } else {
            // use the async_dart option configured timeout
            format!(".timeout(const Duration(milliseconds: {}))", val)
          }
        } else if let Some(val) = config.timeout {
          // fall back to global timeout
          format!(".timeout(const Duration(milliseconds: {}))", val)
        } else {
          // and by default we won't time out at all
          "".to_string()
        },
      )
    }
    .as_str();

    self
  }
}

impl Callable for Web {
  fn begin(&mut self) -> &mut Self {
    self.output += &self.fun.begin();
    self
  }

  fn signature(&mut self) -> &mut Self {
    self.output += &self.fun.signature();
    self
  }

  fn body(&mut self) -> &mut Self {
    self.output += "{
      throw UnimplementedError();";

    self
  }

  fn body_return(&mut self, _enum_tracer_registry: &Registry, _config: &Membrane) -> &mut Self {
    self
  }

  fn end(&mut self) -> &mut Self {
    self.output += &self.fun.end();
    self
  }
}

impl Callable for C {
  fn begin(&mut self) -> &mut Self {
    self.output += &self.fun.begin();
    self
  }

  fn signature(&mut self) -> &mut Self {
    self.output += format!(
      "MembraneResponse {extern_c_fn_name}({port}{extern_c_fn_types});",
      extern_c_fn_name = self.fun.extern_c_fn_name,
      port = if self.fun.is_sync { "" } else { "int64_t port" },
      extern_c_fn_types = if self.fun.extern_c_fn_types.is_empty() {
        String::new()
      } else if self.fun.is_sync {
        String::new() + self.fun.extern_c_fn_types
      } else {
        String::from(", ") + self.fun.extern_c_fn_types
      }
    )
    .as_str();
    self
  }

  fn body(&mut self) -> &mut Self {
    self
  }

  fn body_return(&mut self, _enum_tracer_registry: &Registry, _config: &Membrane) -> &mut Self {
    self
  }

  fn end(&mut self) -> &mut Self {
    self
  }
}