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
use std::fmt::Display;

/// The module consists of methods and structures for Swift
/// code generation.
///
use super::{function_helper::*, templates::*, translate_c_enums};
use crate::binding_types::{Exceptions, RustWrapperType, WrapperType};
use crate::cpp::externs::create_extern_imports;
use crate::cpp::generator::create_classes_forward_declarations;
use crate::enum_helpers::{
    create_field_getter_function,
    create_variant_getter_function,
    enum_tag_name,
    get_fields,
    is_many_fields_variant,
    is_primitive_enum,
    variant_wrapper_ident,
};
use crate::extern_module_translator::{ExternFunction, ExternModuleTranslator, Function};
use crate::EXPORTED_SYMBOLS_PREFIX;

fn create_class_methods_definitions(extern_module_translator: &ExternModuleTranslator) -> String {
    extern_module_translator
        .user_custom_types
        .iter()
        .map(|(wrapper_type, vec_of_functions)| {
            let class_name = wrapper_type.wrapper_name.to_string();
            let class_functions = vec_of_functions
                .iter()
                .map(|f| FunctionTranslator::from_class_method(f, &class_name))
                .map(FunctionTranslator::generate_definition)
                .collect::<String>();
            custom_class_definition(&class_name, &class_functions)
        })
        .collect::<String>()
}

fn translate_type_names(mut fun: Function) -> Function {
    if let Some(ret_type) = &mut fun.return_type {
        if ret_type.wrapper_name.as_str() == "String" {
            ret_type.wrapper_name = "RustString".to_string()
        }
    }
    fun
}

fn create_complex_enum_wrappers(extern_module_translator: &ExternModuleTranslator) -> String {
    extern_module_translator
        .shared_enums
        .iter()
        .filter(|e| !is_primitive_enum(e))
        .map(|enum_item| {
            let class_name = enum_item.ident.to_string();

            let variant_getters = enum_item
                .variants
                .iter()
                .filter_map(|variant| create_variant_getter_function(enum_item, variant))
                .map(translate_type_names);

            let many_fields_variants_wrapper: String = enum_item
                .variants
                .iter()
                .filter(|v| is_many_fields_variant(v))
                .map(|variant| {
                    let fields = get_fields(variant).unwrap();
                    let variant_wrapper_name =
                        variant_wrapper_ident(&enum_item.ident, &variant.ident).to_string();
                    let variant_wrapper_getters = fields
                        .iter()
                        .enumerate()
                        .map(|(field_idx, field)| {
                            translate_type_names(create_field_getter_function(
                                enum_item, variant, field, field_idx,
                            ))
                        })
                        .map(|f| FunctionTranslator::from_class_method(&f, &variant_wrapper_name))
                        .map(FunctionTranslator::generate_definition)
                        .collect::<String>();
                    custom_class_definition(variant_wrapper_name.as_str(), &variant_wrapper_getters)
                })
                .collect();

            let class_functions = variant_getters
                .map(|f| FunctionTranslator::from_class_method(&f, &class_name))
                .map(FunctionTranslator::generate_definition)
                .collect::<String>();
            let enum_tag_name = enum_tag_name(&enum_item.ident);
            let tag_getter_fn = format!(
                "    public func getTag() -> {enum_tag_name} {{
        return self._self.load(as: {enum_tag_name}.self)
    }}\n"
            );
            custom_class_definition(&class_name, &(class_functions + &tag_getter_fn))
                + &many_fields_variants_wrapper
        })
        .collect::<String>()
}

fn create_abstract_classes_declarations(
    extern_module_translator: &ExternModuleTranslator,
) -> String {
    extern_module_translator
        .user_traits
        .iter()
        .map(|(wrapper_type, vec_of_functions)| {
            let class_name = wrapper_type.wrapper_name.to_string();
            let functions_declaration: String = vec_of_functions
                .iter()
                .map(|f| FunctionHelperVirtual::from_virtual_function(f, &class_name))
                .map(FunctionHelperVirtual::generate_virtual_declaration)
                .collect();
            abstract_class_declaration(&class_name, &functions_declaration)
        })
        .collect::<String>()
}

fn create_virtual_method_calls(extern_module_translator: &ExternModuleTranslator) -> String {
    extern_module_translator
        .user_traits
        .iter()
        .map(|(wrapper_type, vec_of_functions)| {
            let class_name = wrapper_type.wrapper_name.to_string();
            vec_of_functions
                .iter()
                .map(|f| FunctionHelperVirtual::from_virtual_function(f, &class_name))
                .map(FunctionHelperVirtual::generate_virtual_definition)
                .collect::<String>()
        })
        .collect::<String>()
}

fn create_rust_types_wrappers(extern_module_translator: &ExternModuleTranslator) -> String {
    extern_module_translator
        .rust_types_wrappers
        .ordered_iter()
        .filter_map(|wrapper| match wrapper {
            WrapperType {
                rust_type: RustWrapperType::Vector(inner_type),
                ..
            } => {
                let inner_type_name = inner_type.get_name();
                let is_generic = matches!(inner_type.rust_type, RustWrapperType::Option(_))
                    || matches!(inner_type.rust_type, RustWrapperType::Vector(_));
                Some(vector_impl(
                    &inner_type_name,
                    &inner_type.wrapper_name,
                    is_generic,
                ))
            }
            WrapperType {
                rust_type: RustWrapperType::Option(inner_type),
                ..
            } => {
                let inner_type_name = inner_type.get_name();
                let is_generic = matches!(inner_type.rust_type, RustWrapperType::Option(_))
                    || matches!(inner_type.rust_type, RustWrapperType::Vector(_));
                Some(option_class(
                    &inner_type_name,
                    &inner_type.wrapper_name,
                    is_generic,
                ))
            }
            WrapperType {
                rust_type: RustWrapperType::Exceptions(Exceptions::NonPrimitive(idents)),
                wrapper_name,
                ..
            } => Some(
                idents
                    .iter()
                    .map(|exception| {
                        create_non_primitive_exception_class(
                            &exception.to_string(),
                            wrapper_name,
                            extern_module_translator.exception_trait_methods.iter(),
                        )
                    })
                    .collect::<String>(),
            ),
            WrapperType {
                rust_type: RustWrapperType::Exceptions(Exceptions::Primitive(idents)),
                wrapper_name,
                ..
            } => Some(
                idents
                    .iter()
                    .map(|exception| {
                        create_primitive_exception_class(
                            &exception.to_string(),
                            wrapper_name,
                            extern_module_translator.exception_trait_methods.iter(),
                        )
                    })
                    .collect::<String>(),
            ),
            _ => None,
        })
        .collect()
}

fn create_global_functions_definitions(
    extern_module_translator: &ExternModuleTranslator,
) -> String {
    extern_module_translator
        .global_functions
        .iter()
        .map(FunctionTranslator::from_global_function)
        .map(FunctionTranslator::generate_definition)
        .collect()
}

/// Creates exception class for an error variant that may be returned from rust
pub fn create_non_primitive_exception_class<'a>(
    exception: &impl Display,
    err_name: &impl Display,
    custom_methods: impl Iterator<Item = &'a Function>,
) -> String {
    let custom_methods = create_exception_custom_methods(custom_methods, err_name, "err._self");
    format_exception_class(exception, err_name, &custom_methods)
}

/// Creates exception class for an error variant of primitive enum that may be returned from rust
pub fn create_primitive_exception_class<'a>(
    exception: &impl Display,
    err_name: &impl Display,
    custom_methods: impl Iterator<Item = &'a Function>,
) -> String {
    let custom_methods = create_exception_custom_methods(custom_methods, err_name, "&err");
    format_exception_class(exception, err_name, &custom_methods)
}

fn format_exception_class(
    exception: &impl Display,
    err_name: &impl Display,
    custom_methods: &impl Display,
) -> String {
    let exception_name = format!("{err_name}_{exception}Exception");
    format!(
        "
public class {exception_name} : {RUST_EXCEPTION_BASE_CLASS_NAME} {{
    private(set) var err: {err_name}
    init(_ err: {err_name}) {{ self.err = err }}
{custom_methods}
}}
"
    )
}

fn create_enum_init_method(extern_module_translator: &ExternModuleTranslator) -> String {
    extern_module_translator
        .shared_enums
        .iter()
        .filter(|e| is_primitive_enum(e))
        .map(|enum_class| {
            let enum_name = &enum_class.ident;
            format!(
                "extension {enum_name} {{
    init(_ enumObj: {enum_name}) {{
        self = enumObj
    }}
}}\n"
            )
        })
        .collect()
}

fn create_result_wrappers(extern_module_translator: &ExternModuleTranslator) -> String {
    extern_module_translator
        .rust_types_wrappers
        .ordered_iter()
        .filter_map(|wrapper| match wrapper {
            WrapperType {
                rust_type: RustWrapperType::Result(ok_type, exceptions_type),
                ..
            } => {
                let ok_type = ok_type.get_name();
                let error_enum_name = &exceptions_type.wrapper_name;
                Some(result_class(
                    &wrapper.wrapper_name,
                    &ok_type,
                    error_enum_name,
                ))
            }
            _ => None,
        })
        .collect()
}

fn create_exception_custom_methods<'a>(
    custom_methods: impl Iterator<Item = &'a Function>,
    err_name: &impl Display,
    rust_obj_ptr: impl Display,
) -> impl Display {
    custom_methods
        .map(|fun| {
            let return_type = fun
                .return_type
                .as_ref()
                .map(|wrapper| wrapper.wrapper_name.as_str())
                .unwrap_or("");
            let function_name = &fun.name;
            let ffi_call = format!("{EXPORTED_SYMBOLS_PREFIX}${err_name}${function_name}");
            let ffi_call = format!("{ffi_call}({rust_obj_ptr})");
            let ffi_call = match &fun.return_type {
                None
                | Some(WrapperType {
                    rust_type: RustWrapperType::Primitive | RustWrapperType::FieldlessEnum,
                    ..
                }) => ffi_call,
                Some(WrapperType { wrapper_name, .. }) => {
                    format!("{wrapper_name}({ffi_call})")
                }
            };
            format!(
                "        public func {function_name}() -> {return_type} {{
            return {ffi_call}
        }}"
            )
        })
        .collect::<Vec<_>>()
        .join("\n")
}

fn base_exception_method(function: &Function) -> String {
    let return_type = &function
        .return_type
        .as_ref()
        .map(|t| t.get_name())
        .unwrap_or_else(|| "".to_string());
    let name = &function.name;
    format!("    func {name}() -> {return_type};")
}

fn base_exception_class(emt: &ExternModuleTranslator) -> String {
    let exception_trait_methods = emt
        .exception_trait_methods
        .iter()
        .map(base_exception_method)
        .collect::<Vec<_>>()
        .join("\n");
    format!("public protocol {RUST_EXCEPTION_BASE_CLASS_NAME} : Error {{\n{exception_trait_methods}\n}}\n")
}

/// Function generates a C header that can be used as an Objective-C bridging
/// layer to the compiled Rust static library.
///
pub fn generate_swift_file(extern_module_translator: &ExternModuleTranslator) -> String {
    let classes_definition = create_class_methods_definitions(extern_module_translator);
    let complex_enum_classes_definitions = create_complex_enum_wrappers(extern_module_translator);
    let abstract_classes_declaration =
        create_abstract_classes_declarations(extern_module_translator);
    let virtual_methods_calls = create_virtual_method_calls(extern_module_translator);
    let rust_types_wrappers = create_rust_types_wrappers(extern_module_translator);
    let global_functions_definition: String =
        create_global_functions_definitions(extern_module_translator);
    let base_exception_class = base_exception_class(extern_module_translator);
    let result_wrapper = create_result_wrappers(extern_module_translator);
    let enum_init_methods = create_enum_init_method(extern_module_translator);
    format!(
        "{PREDEFINED}
{enum_init_methods}
{complex_enum_classes_definitions}
{result_wrapper}
{base_exception_class}
{rust_types_wrappers}
{classes_definition}
{global_functions_definition}
{virtual_methods_calls}
{abstract_classes_declaration}"
    )
}

/// Extern functions can be saved in another header file. Particularly
/// useful while importing C methods in Swift.
///
pub fn generate_c_externs_file(
    extern_module_translator: &ExternModuleTranslator,
    extern_functions: &[ExternFunction],
) -> String {
    let externs = create_extern_imports(extern_functions);
    let classes_forward_declarations =
        create_classes_forward_declarations(extern_module_translator);
    let enum_classes_definitions = translate_c_enums(extern_module_translator);
    format!(
        "#include <stdbool.h>
#include <stdint.h>

typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint64_t u64;

typedef int8_t i8;
typedef int16_t i16;
typedef int32_t i32;
typedef int64_t i64;

typedef float f32;
typedef double f64;

typedef intptr_t isize;
typedef uintptr_t usize;

{enum_classes_definitions}
{classes_forward_declarations}
{externs}
"
    )
}