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
//
// Wildland Project
//
// Copyright © 2022 Golem Foundation,
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as published by
// the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use super::templates::TargetLanguageTypeName;
use crate::binding_types::RustWrapperType;
use crate::extern_module_translator::ExternModuleTranslator;

pub fn generate_swig_based_on_wrappers(
    extern_module_translator: &ExternModuleTranslator,
) -> String {
    let templates = extern_module_translator
        .rust_types_wrappers
        .unordered_iter()
        .map(|key| match &key.rust_type {
            RustWrapperType::Vector(inner_type) => format!(
                "%template(Vec{0}) RustVec<{1}>;\n",
                inner_type.as_ref().wrapper_name,
                inner_type.get_name(),
            ),
            RustWrapperType::Option(inner_type) => format!(
                "%template(Optional{0}) Optional<{1}>;\n",
                inner_type.as_ref().wrapper_name,
                inner_type.get_name(),
            ),
            _ => "".to_owned(),
        })
        .collect();
    let directors = extern_module_translator
        .user_traits
        .keys()
        .map(|key| format!("%feature(\"director\") {};\n", key.wrapper_name))
        .collect::<String>();
    generate_swig(directors, templates)
}

fn generate_swig(directors: String, templates: String) -> String {
    format!(
        r#"%module(directors="1") ffi_interface
// The problem:
// Swig by default do some copying of the objects that come from the source
// language. The following SWIG typemaps introduces move semantics in the
// generated code instead of copying objects.
%typemap(out, optimal="1") SWIGTYPE %{{
  $result = new $1_ltype(( $1_ltype &&)$1);
%}}

// Python uses a different approach.
#if defined(SWIGPYTHON)
%typemap(out, optimal="1") SWIGTYPE %{{
  $result = SWIG_NewPointerObj((new $1_ltype(static_cast< $1_ltype&&  >($1))), $&1_descriptor, SWIG_POINTER_OWN |  0 );
%}}
#endif

{directors}

//////////////////////////////////
// Inlcude the generated C++ API
//////////////////////////////////
%{{
    #include "ffi_cxx.h"
%}}
%include "std_string.i"
%include "ffi_cxx.h"

{templates}

"#
    )
}