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
//
// 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 crate::binding_types::{Function, RustWrapperType, WrapperType};
use crate::cpp::templates::TargetLanguageTypeName;
use crate::EXPORTED_SYMBOLS_PREFIX;

pub struct FunctionVirtualTranslator {
    pub function_name: String,
    pub generated_args: String,
    pub generated_function_body: Vec<String>,
    pub generated_virtual_function_signature: String,
    pub return_type: Option<WrapperType>,
    pub arg_names: Vec<String>,
    class_name: String,
}

impl FunctionVirtualTranslator {
    fn create_list_of_arguments_translated_to_cpp(function: &Function) -> Vec<String> {
        let mut generated_args = function
            .arguments
            .iter()
            .skip(1)
            .map(|arg| match &arg.typ {
                WrapperType {
                    rust_type: RustWrapperType::Primitive | RustWrapperType::FieldlessEnum,
                    ..
                } => format!("{} {}", arg.typ.wrapper_name, arg.arg_name),
                _ => format!("void* {}", arg.arg_name),
            })
            .collect::<Vec<String>>();
        generated_args.insert(0, "void* self".to_owned());
        generated_args
    }

    fn create_function_signature(function: &Function) -> String {
        function
            .arguments
            .iter()
            .skip(1)
            .map(|arg| format!("{} {}", arg.typ.get_name(), arg.arg_name))
            .collect::<Vec<String>>()
            .join(", ")
    }

    fn create_function_body(function: &Function) -> Vec<String> {
        function
            .arguments
            .iter()
            .skip(1)
            .map(|arg| {
                let inner_type_name = arg.typ.get_name();
                let arg_name = &arg.arg_name;
                format!("{inner_type_name}({arg_name})")
            })
            .collect()
    }

    /// Translates the intermediate form of a parsed function into
    /// the elements ready-to-use in the C++ code generation process.
    /// It prepares code for a C++ virtual method declaration and
    /// extern "C" function that calls the virtual method. Due to this,
    /// Rust code can call virtual C++ methods like trait functions.
    ///
    /// Pseudocode:
    ///
    /// Rust Trait {
    ///     method_a();
    /// }
    ///
    /// C++ Class {
    ///     virtual method_a();
    /// }
    ///
    /// extern "C" __method_a(C++Class* obj) {
    ///     obj->method_a();
    /// }
    ///
    pub fn from_virtual_function(function: &Function, class_name: &str) -> Self {
        let generated_args =
            FunctionVirtualTranslator::create_list_of_arguments_translated_to_cpp(function);
        let generated_args = generated_args.join(", ");
        let generated_virtual_function_signature =
            FunctionVirtualTranslator::create_function_signature(function);
        let generated_function_body: Vec<String> =
            FunctionVirtualTranslator::create_function_body(function);
        let function_name = function.name.to_string();
        let arg_names = function
            .arguments
            .iter()
            .map(|arg| arg.arg_name.to_string())
            .collect();
        FunctionVirtualTranslator {
            function_name,
            generated_args,
            generated_function_body,
            generated_virtual_function_signature,
            return_type: function.return_type.clone(),
            arg_names,
            class_name: class_name.to_owned(),
        }
    }

    /// Generates a virtual function declaration that can be used
    /// within a class declaration.
    ///
    pub fn generate_virtual_declaration(self) -> String {
        let FunctionVirtualTranslator {
            function_name,
            generated_args: _,
            generated_function_body: _,
            generated_virtual_function_signature,
            return_type,
            ..
        } = self;
        let return_type_string = return_type
            .as_ref()
            .map(|w| w.get_name_for_abstract_method())
            .unwrap_or_else(|| "void".to_string());
        format!("    virtual {return_type_string} {function_name}({generated_virtual_function_signature}) = 0;\n")
    }

    /// Generates an extern function that calls the virtual
    /// method on a dynamic C++ object that can be mapped to
    /// some Rust trait object.
    ///
    pub fn generate_virtual_definition(self) -> String {
        let FunctionVirtualTranslator {
            function_name,
            generated_args,
            generated_function_body,
            generated_virtual_function_signature: _,
            return_type,
            arg_names: _,
            class_name,
        } = self;
        let class_function_name = format!("{class_name}$");
        let generated_function_body = generated_function_body.join(", ");
        match return_type {
                Some(WrapperType {
                    rust_type: RustWrapperType::Primitive | RustWrapperType::FieldlessEnum,
                    wrapper_name,
                    ..
                }) =>
                format!(
                    "extern \"C\" {wrapper_name} {EXPORTED_SYMBOLS_PREFIX}${class_function_name}{function_name}({generated_args}) {{
        return (({class_name}*)self)->{function_name}({generated_function_body});\n}}\n"),
                None => format!(
                    "extern \"C\" void {EXPORTED_SYMBOLS_PREFIX}${class_function_name}{function_name}({generated_args}) {{
        (({class_name}*)self)->{function_name}({generated_function_body});\n}}\n"),
                _ =>
                    format!(
                    "extern \"C\" void* {EXPORTED_SYMBOLS_PREFIX}${class_function_name}{function_name}({generated_args}) {{
        return ((({class_name}*)self)->{function_name}({generated_function_body}));\n}}\n"),
            }
    }
}