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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
//
// 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 std::fmt::Display;

use crate::extern_module_translator::{
    ExternModuleTranslator,
    Function,
    RustWrapperType,
    WrapperType,
};
use crate::{DROP_FUNCTION_SYMBOL_NAME, EXPORTED_SYMBOLS_PREFIX};

pub const RUST_EXCEPTION_BASE_CLASS_NAME: &str = "RustExceptionBase";
pub const IMPORTS: &str = r#"
#include <string>
#include <cstring>
#include <memory>
#include <utility>
#include <stdexcept>
#include <cstdint>
"#;

pub const TYPEDEFS: &str = r#"
using u8 = unsigned char;
using u16 = unsigned short;
using u32 = unsigned int;
using u64 = unsigned long long;

using i8 = char;
using i16 = short;
using i32 = int;
using i64 = long long;

using f32 = float;
using f64 = double;

using isize = int;
using usize = unsigned int;
"#;

pub trait TargetLanguageTypeName {
    fn get_name(&self) -> String;
    fn get_name_for_abstract_method(&self) -> String;
}

impl TargetLanguageTypeName for WrapperType {
    fn get_name(&self) -> String {
        match self {
            WrapperType {
                rust_type: RustWrapperType::Vector(inner_type),
                ..
            } => {
                let inner_name = inner_type.get_name();
                format!("RustVec<{inner_name}>")
            }
            WrapperType {
                rust_type: RustWrapperType::Option(inner_type),
                ..
            } => {
                let inner_name = inner_type.get_name();
                format!("Optional<{inner_name}>")
            }
            WrapperType {
                rust_type: RustWrapperType::Result(ok_type, _),
                ..
            } => ok_type.get_name(),
            _ => self.wrapper_name.clone(),
        }
    }
    fn get_name_for_abstract_method(&self) -> String {
        match self {
            WrapperType {
                rust_type: RustWrapperType::Vector(inner_type),
                ..
            } => {
                let inner_name = inner_type.get_name();
                format!("RustVec<{inner_name}>")
            }
            WrapperType {
                rust_type: RustWrapperType::Option(inner_type),
                ..
            } => {
                let inner_name = inner_type.get_name();
                format!("Optional<{inner_name}>")
            }
            _ => self.wrapper_name.clone(),
        }
    }
}

/// Predefined C++ classes and primitive types typedefs useful
/// during the standard work on FFI basic structures. It
/// consists of a custom RustVector and String implementations
/// that keep track of some object ownership aspects. Items
/// returned by `RustVec::at(x)` method should be treated as
/// references, since the underlying objects are owned by
/// the vector.
///
pub const PREDEFINED: &str = const_format::formatcp!(
    r#"
extern "C" {{
    void {DROP_FUNCTION_SYMBOL_NAME}(void* input) {{
    }}
}}

template <typename T>
class Optional {{
    void* self = nullptr;
    bool is_owned = false;
public:
    Optional();
    Optional(T val);
    Optional(void* self, bool is_owned = true) : self(self), is_owned(is_owned) {{}}
    Optional(Optional&& a) : self(a.self), is_owned(a.is_owned) {{ a.self = nullptr; a.is_owned = false; }};
    Optional(const Optional& a);
    Optional& operator=(const Optional& a);
    virtual ~Optional();
    T unwrap();
    bool is_some();
    operator void*() {{
        this->is_owned = false;
        return this->self;
    }}
    void* as_ref() const {{
        return this->self;
    }}
}};

template <typename T>
class RustVec;

// RustIterator is separated from the RustVec class because SWIG does not fully support nested classes.
template <typename T>
struct RustIterator {{
    RustIterator(T* buf_ptr, size_t index, bool is_primitive, RustVec<T>* vec)
    : buf_ptr(buf_ptr), is_primitive(is_primitive), index(index), vec(vec)
    {{}}

    T operator*() const {{
        return deref();
    }}
    T operator->() {{
        return deref();
    }}

    RustIterator& operator++() {{
        index++; return *this;
    }}
    RustIterator operator++(int) {{
        RustIterator tmp = *this; ++(*this); return tmp;
    }}
    RustIterator operator+(int advance) {{
        return RustIterator(buf_ptr, index + advance, is_primitive, vec);
    }}

    RustIterator& operator--() {{
        index--; return *this;
    }}
    RustIterator operator--(int) {{
        RustIterator tmp = *this; --(*this); return tmp;
    }}
    RustIterator operator-(int advance) {{
        return RustIterator(buf_ptr, index - advance, is_primitive, vec);
    }}

    friend bool operator== (const RustIterator& a, const RustIterator& b) {{ return a.buf_ptr == b.buf_ptr && a.index == b.index ; }};
    friend bool operator!= (const RustIterator& a, const RustIterator& b) {{ return a.buf_ptr != b.buf_ptr || a.index != b.index ; }};

private:
    T deref() const {{
        if (is_primitive) {{
            return *(buf_ptr + index);
        }} else {{
            return vec->at(index).unwrap();
        }}
    }}

    RustVec<T>* vec;
    T* buf_ptr;
    bool is_primitive;
    size_t index;
}};

template <typename T>
class RustVec {{
    void* self = nullptr;
    bool is_owned = false;

    T* as_mut_ptr();

public:
    RustVec();
    RustVec(RustVec&& a) : self(a.self), is_owned(a.is_owned) {{
        a.self = nullptr;
        a.is_owned = false;
    }};
    RustVec(const RustVec&);
    RustVec& operator=(const RustVec&);
    RustVec(void* self, bool is_owned = true)
        : self(self), is_owned(is_owned) {{}}
    virtual ~RustVec();
    operator void*() {{
        this->is_owned = false;
        return this->self;
    }}
    void* as_ref() const {{
        return this->self;
    }}
    void push(T item);
    Optional<T> at(usize index);
    size_t size();

    RustIterator<T> begin();
    RustIterator<T> end();
}};

class RustString {{
    void* self = nullptr;
    bool is_owned = false;
public:
    RustString() = default;
    RustString(void* self, bool is_owned = true)
        : self(self), is_owned(is_owned) {{}}
    RustString(const char* str) {{
        this->self = {EXPORTED_SYMBOLS_PREFIX}$RustString$from_c_str((void*) str);
        this->is_owned = true;
    }}
    RustString(std::string str) {{
        this->self = {EXPORTED_SYMBOLS_PREFIX}$RustString$from_c_str((void*) str.data());
        this->is_owned = true;
    }}
    RustString(const RustString& a) {{
        this->self = {EXPORTED_SYMBOLS_PREFIX}$RustString$clone(a.self);
        this->is_owned = true;
    }}
    RustString(RustString&& a)
        : self(a.self),
          is_owned(a.is_owned) {{
        a.self = nullptr;
        a.is_owned = false;
    }}
    RustString& operator=(const RustString& a) {{
        this->self = {EXPORTED_SYMBOLS_PREFIX}$RustString$clone(a.self);
        this->is_owned = true;
        return *this;
    }};
    RustString& operator=(RustString&& a) {{
        this->is_owned = true;
        a.is_owned = false;
        this->self = a.self;
        a.self = nullptr;
        return *this;
    }}
    std::string to_string() {{
        char* str = (char*) {EXPORTED_SYMBOLS_PREFIX}$RustString$as_mut_ptr(this->self);
        usize length = {EXPORTED_SYMBOLS_PREFIX}$RustString$len(this->self);
        return std::string(str, length);
    }}
    operator void*() {{
        this->is_owned = false;
        return this->self;
    }}
    void* as_ref() const {{
        return this->self;
    }}
    virtual ~RustString() {{
        if(is_owned && self != nullptr) {{
            {EXPORTED_SYMBOLS_PREFIX}$RustString$drop(this->self);
        }}
    }}
}};

using String = RustString;
"#
);

/// Creates an implementation of RustVec<T> begin and end implementation.
/// It should be generated for primitive types only, cause pointer arithmetics for Rust opaque types is not trivial.
///
pub fn begin_end_impl(inner_type: &str, rust_type: &RustWrapperType) -> String {
    let is_primitive = if matches!(rust_type, RustWrapperType::Primitive) {
        "true"
    } else {
        "false"
    };
    format!(
        "
template<>
RustIterator<{inner_type}> RustVec<{inner_type}>::begin() {{
    return RustIterator( as_mut_ptr(), 0, {is_primitive}, this );
}}
template<>
RustIterator<{inner_type}> RustVec<{inner_type}>::end() {{
    return RustIterator( as_mut_ptr(), size(), {is_primitive}, this );
}}
"
    )
}

/// Creates an implementation of RustVec<T> for a given T that maps to the Rust Vec<T> object.
///
pub fn vector_impl(inner_type: &str, rust_wrapper_name: &str) -> String {
    format!(
        "
template<>
RustVec<{inner_type}>::~RustVec()
{{
    if(this->self && this->is_owned) {{
        {EXPORTED_SYMBOLS_PREFIX}$Vec{rust_wrapper_name}$drop(this->self);
    }}
}}

template<>
void RustVec<{inner_type}>::push({inner_type} item) {{
    {EXPORTED_SYMBOLS_PREFIX}$Vec{rust_wrapper_name}$push(this->self, item);
}}
template<>
RustVec<{inner_type}>::RustVec(const RustVec& vec) {{
    this->self = {EXPORTED_SYMBOLS_PREFIX}$Vec{rust_wrapper_name}$clone(vec.self);
    this->is_owned = true;
}}
template<>
RustVec<{inner_type}>& RustVec<{inner_type}>::operator=(const RustVec& vec) {{
    this->self = {EXPORTED_SYMBOLS_PREFIX}$Vec{rust_wrapper_name}$clone(vec.self);
    this->is_owned = true;
    return *this;
}}
template<>
RustVec<{inner_type}>::RustVec() {{
    this->self = {EXPORTED_SYMBOLS_PREFIX}$Vec{rust_wrapper_name}$new();
    this->is_owned = true;
}}
template<>
Optional<{inner_type}> RustVec<{inner_type}>::at(usize index) {{
    return Optional<{inner_type}>({EXPORTED_SYMBOLS_PREFIX}$Vec{rust_wrapper_name}$get(this->self, index));
}}
template<>
{inner_type}* RustVec<{inner_type}>::as_mut_ptr() {{
    return ({inner_type}*) {EXPORTED_SYMBOLS_PREFIX}$Vec{rust_wrapper_name}$as_mut_ptr(this->self);
}}
template<>
size_t RustVec<{inner_type}>::size() {{
    return (size_t) {EXPORTED_SYMBOLS_PREFIX}$Vec{rust_wrapper_name}$len(this->self);
}}"
    )
}

/// Creates a class that maps onto the Rust Option<T> object.
/// The ownership depends on the source from which the object is created.
///
pub fn option_class(inner_type: &str, rust_wrapper_name: &str) -> String {
    format!(
        "
template<>
Optional<{inner_type}>::Optional() {{
    this->self = {EXPORTED_SYMBOLS_PREFIX}$Optional{rust_wrapper_name}$default();
    this->is_owned = true;
}}
template<>
Optional<{inner_type}>::Optional({inner_type} val) {{
    this->self = {EXPORTED_SYMBOLS_PREFIX}$Optional{rust_wrapper_name}$from(val);
    this->is_owned = true;
}}
template<>
Optional<{inner_type}>::Optional(const Optional<{inner_type}>& a) {{
    this->self = {EXPORTED_SYMBOLS_PREFIX}$Optional{rust_wrapper_name}$clone(a.self);
    this->is_owned = true;
}}
template<>
Optional<{inner_type}>& Optional<{inner_type}>::operator=(const Optional<{inner_type}>& a) {{
    this->self = {EXPORTED_SYMBOLS_PREFIX}$Optional{rust_wrapper_name}$clone(a.self);
    this->is_owned = true;
    return *this;
}}
template<>
Optional<{inner_type}>::~Optional() {{
    if(this->self && this->is_owned) {{
        {EXPORTED_SYMBOLS_PREFIX}$Optional{rust_wrapper_name}$drop(this->self);
    }}
}};
template<>
{inner_type} Optional<{inner_type}>::unwrap() {{
    auto cloned = {EXPORTED_SYMBOLS_PREFIX}$Optional{rust_wrapper_name}$clone(this->self);
    return {inner_type}({EXPORTED_SYMBOLS_PREFIX}$Optional{rust_wrapper_name}$unwrap(cloned));
}}
template<>
bool Optional<{inner_type}>::is_some() {{
    return {EXPORTED_SYMBOLS_PREFIX}$Optional{rust_wrapper_name}$is_some(this->self);
}}
"
    )
}

/// Creates a class that maps onto the Rust Result<T, E> object.
/// The ownership depends on the source from which the object is created.
///
pub fn result_class(name: &str, ok_type: &str, err_type: &str) -> String {
    format!(
        "
class {name} {{
    void* self = nullptr;
    bool is_owned = false;
public:
    {name}() = default;
    {name}({name}&& a) : self(a.self), is_owned(a.is_owned) {{
        a.self = nullptr;
        a.is_owned = false;
    }};
    {name}(const {name}& a) {{
        this->self = {EXPORTED_SYMBOLS_PREFIX}${name}$clone(a.self);
        this->is_owned = true;
    }}
    {name}& operator=(const {name}& a) {{
        this->self = {EXPORTED_SYMBOLS_PREFIX}${name}$clone(a.self);
        this->is_owned = true;
        return *this;
    }}
    {name}(void* self, bool is_owned = true) : self(self), is_owned(is_owned) {{ }}
    virtual ~{name}() {{
        if(this->self && this->is_owned) {{
            {EXPORTED_SYMBOLS_PREFIX}${name}$drop(this->self);
        }}
    }}
    static {name} from_ok({ok_type} val) {{
        return {name}({EXPORTED_SYMBOLS_PREFIX}${name}$from_ok(val));
    }}
    static {name} from_err({err_type} val) {{
        return {name}({EXPORTED_SYMBOLS_PREFIX}${name}$from_err(val));
    }}
    {ok_type} unwrap() {{
        auto cloned = {EXPORTED_SYMBOLS_PREFIX}${name}$clone(this->self);
        return {ok_type}({EXPORTED_SYMBOLS_PREFIX}${name}$unwrap(cloned));
    }}
    {err_type} unwrap_err() {{
        auto cloned = {EXPORTED_SYMBOLS_PREFIX}${name}$clone(this->self);
        return {err_type}({EXPORTED_SYMBOLS_PREFIX}${name}$unwrap_err_unchecked(cloned));
    }}
    bool is_ok() {{
        return {EXPORTED_SYMBOLS_PREFIX}${name}$is_ok(this->self);
    }}
    operator void*() {{
        this->is_owned = false;
        return this->self;
    }}
    void* as_ref() const {{
        return this->self;
    }}
}};
"
    )
}

/// Creates a class that maps onto the custom structures with methods
/// that are available in the FFI.
/// The ownership depends on the source from which the object is created.
///
pub fn custom_class_definition(name: impl Display, functions_declaration: impl Display) -> String {
    format!(
            "
class {name} {{
    void* self = nullptr;
    bool is_owned = false;
public:
    {name}() = default;
    {name}(void* self, bool is_owned = true) : self(self), is_owned(is_owned) {{ }}
    {name}({name}&& a) : self(a.self), is_owned(a.is_owned) {{ a.self = nullptr; a.is_owned = false; }};
    {name}(const {name}& a) {{
        this->self = {EXPORTED_SYMBOLS_PREFIX}${name}$clone(a.self);
        this->is_owned = true;
    }}
    {name}& operator=(const {name}& a) {{
        this->self = {EXPORTED_SYMBOLS_PREFIX}${name}$clone(a.self);
        this->is_owned = true;
        return *this;
    }}
    {name}& operator=({name}&& a) {{
        this->is_owned = true;
        a.is_owned = false;
        this->self = a.self;
        a.self = nullptr;
        return *this;
    }}
    virtual ~{name}() {{ if(this->self && this->is_owned) {{ {EXPORTED_SYMBOLS_PREFIX}${name}$drop(this->self); }} }};
    operator void*() {{
        this->is_owned = false;
        return this->self;
    }}
    void* raw_self() const {{ return this->self;}}
    void* as_ref() const {{
        return this->self;
    }}
{functions_declaration}
}};
\n")
}

/// Creates a class that maps onto the custom structures with methods
/// that are available in the FFI.
/// The ownership depends on the source from which the object is created.
///
pub fn abstract_class_declaration(name: &str, functions_declaration: &str) -> String {
    format!(
        "
class {name} {{
public:
    {name}() = default;
    virtual ~{name}() {{}};
    operator void*() const {{
        return (void*) this;
    }}
{functions_declaration}}};
\n"
    )
}

/// 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_non_primitive_enum_exception_custom_methods(custom_methods, err_name);
    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_primitive_enum_exception_custom_methods(custom_methods, err_name);
    format_exception_class(exception, err_name, &custom_methods)
}

pub fn exception_class_name(
    error_enum_name: impl Display,
    exception_variant: impl Display,
) -> String {
    format!("{error_enum_name}_{exception_variant}Exception")
}

fn format_exception_class(
    exception: &impl Display,
    err_name: &impl Display,
    custom_methods: &impl Display,
) -> String {
    let exception_name = exception_class_name(err_name, exception);
    format!(
        "
class {exception_name} : public {RUST_EXCEPTION_BASE_CLASS_NAME} {{
    {err_name} err;
    public:
        {exception_name}({err_name} err) : err{{err}} {{}}

        virtual const char* what() const throw() override
        {{
            return \"{exception_name} thrown from Rust\";
        }}

        virtual ExceptionClass exception_class() override {{
            return ExceptionClass::{exception_name};
        }}

{custom_methods}
    }};
"
    )
}

fn create_exception_custom_methods<'a>(
    custom_methods: impl Iterator<Item = &'a Function>,
    err_name: &impl Display,
    inner_err_cast: &(impl Display + ?Sized),
) -> 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}({inner_err_cast})");
            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!(
                "        {return_type} {function_name}() const override {{
            return {ffi_call};
        }}"
            )
        })
        .collect::<Vec<_>>()
        .join("\n")
}

fn create_primitive_enum_exception_custom_methods<'a>(
    custom_methods: impl Iterator<Item = &'a Function>,
    err_name: &impl Display,
) -> impl Display {
    create_exception_custom_methods(custom_methods, err_name, "(void*)&err")
}

fn create_non_primitive_enum_exception_custom_methods<'a>(
    custom_methods: impl Iterator<Item = &'a Function>,
    err_name: &impl Display,
) -> impl Display {
    create_exception_custom_methods(custom_methods, err_name, "err.raw_self()")
}

fn base_exception_virtual_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!(
        "    virtual {return_type} {name}() const = 0;
"
    )
}

fn wasm_delegated_exception_method(function: &Function) -> String {
    let return_type = &function
        .return_type
        .as_ref()
        .map(|t| t.get_name())
        .unwrap_or_else(|| "".to_string());
    let fun_name = &function.name;
    format!(
        "    virtual {return_type} {fun_name}() const {{
        return rbe->{fun_name}();
    }};
"
    )
}

pub fn base_exception_class(emt: &ExternModuleTranslator) -> String {
    let exception_trait_virtual_methods = emt
        .exception_trait_methods
        .iter()
        .map(base_exception_virtual_method)
        .collect::<Vec<_>>()
        .join("\n");
    let wasm_delegated_methods = emt
        .exception_trait_methods
        .iter()
        .map(wasm_delegated_exception_method)
        .collect::<Vec<_>>()
        .join("\n");
    format!(
        "class {RUST_EXCEPTION_BASE_CLASS_NAME} : public std::exception {{
public:
    virtual const char* what() const throw()
    {{
        return \"Exception thrown from Rust\";
    }}

    virtual ExceptionClass exception_class() {{
        return ExceptionClass::{RUST_EXCEPTION_BASE_CLASS_NAME};
    }}

{exception_trait_virtual_methods}
}};

// Exceptions wrapper for WASM
class WasmException {{
    std::shared_ptr<{RUST_EXCEPTION_BASE_CLASS_NAME}> rbe;
public:
    WasmException(unsigned addr) : rbe{{({RUST_EXCEPTION_BASE_CLASS_NAME}*) addr}} {{}}

    ExceptionClass exception_class() {{
        return rbe->exception_class();
    }}

    std::string what() {{
        return std::string{{rbe->what()}};
    }}

{wasm_delegated_methods}
}};
"
    )
}