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
use std::mem::ManuallyDrop;

use necsim_core::reporter::{
    boolean::{Boolean, True},
    Reporter,
};

pub trait SerializeableReporter: Reporter + erased_serde::Serialize {
    fn reporter_name(&self) -> &'static str;
}

pub struct ReporterPluginDeclaration {
    pub rustc_version: &'static str,
    pub core_version: &'static str,

    #[allow(improper_ctypes_definitions)]
    pub init: unsafe extern "C" fn(&'static dyn log::Log, log::LevelFilter),

    #[allow(improper_ctypes_definitions)]
    pub deserialise:
        unsafe extern "C" fn(
            &mut dyn erased_serde::Deserializer,
        )
            -> Result<ManuallyDrop<UnsafeReporterPlugin>, erased_serde::Error>,

    #[allow(improper_ctypes_definitions)]
    pub library_path: unsafe extern "C" fn() -> Option<::std::path::PathBuf>,

    #[allow(improper_ctypes_definitions)]
    pub drop: unsafe extern "C" fn(ManuallyDrop<UnsafeReporterPlugin>),
}

#[derive(Copy, Clone)]
#[allow(dead_code)]
pub struct ReporterPluginFilter {
    pub(crate) report_speciation: bool,
    pub(crate) report_dispersal: bool,
    pub(crate) report_progress: bool,
}

impl ReporterPluginFilter {
    #[must_use]
    pub fn from_reporter<R: SerializeableReporter>() -> Self {
        Self {
            report_speciation: R::ReportSpeciation::VALUE,
            report_dispersal: R::ReportDispersal::VALUE,
            report_progress: R::ReportProgress::VALUE,
        }
    }
}

pub type DynReporterPlugin = dyn SerializeableReporter<
    ReportSpeciation = True,
    ReportDispersal = True,
    ReportProgress = True,
>;

#[repr(C)]
pub struct UnsafeReporterPlugin {
    pub(crate) reporter: Box<DynReporterPlugin>,
    pub(crate) filter: ReporterPluginFilter,
}

impl<R: SerializeableReporter> From<R> for UnsafeReporterPlugin {
    fn from(reporter: R) -> Self {
        let boxed_reporter: Box<
            dyn SerializeableReporter<
                ReportSpeciation = R::ReportSpeciation,
                ReportDispersal = R::ReportDispersal,
                ReportProgress = R::ReportProgress,
            >,
        > = Box::new(reporter);

        Self {
            reporter: unsafe {
                std::mem::transmute::<
                    Box<
                        dyn SerializeableReporter<
                            ReportDispersal = R::ReportDispersal,
                            ReportProgress = R::ReportProgress,
                            ReportSpeciation = R::ReportSpeciation,
                        >,
                    >,
                    Box<
                        dyn SerializeableReporter<
                            ReportDispersal = True,
                            ReportProgress = True,
                            ReportSpeciation = True,
                        >,
                    >,
                >(boxed_reporter)
            },
            filter: ReporterPluginFilter::from_reporter::<R>(),
        }
    }
}

#[macro_export]
#[allow(clippy::module_name_repetitions)]
macro_rules! export_plugin {
    ($($name:ident => $plugin:ty),+$(,)?) => {
        #[doc(hidden)]
        extern "C" fn __necsim_reporter_plugin_init(
            log: &'static dyn $crate::log::Log,
            max_level: $crate::log::LevelFilter,
        ) {
            let _ = $crate::log::set_logger(log);

            $crate::log::set_max_level(max_level);
        }

        #[doc(hidden)]
        extern "C" fn __necsim_reporter_plugin_deserialise<'de>(
            deserializer: &mut dyn $crate::erased_serde::Deserializer<'de>,
        ) -> Result<
            ::std::mem::ManuallyDrop<$crate::export::UnsafeReporterPlugin>,
            $crate::erased_serde::Error,
        > {
            #[allow(clippy::enum_variant_names)]
            #[derive($crate::serde::Deserialize)]
            #[serde(crate = "::necsim_plugins_core::serde")]
            enum Reporters {
                $($name($plugin)),*
            }

            $crate::erased_serde::deserialize::<Reporters>(deserializer).map(|reporter| {
                match reporter {
                    $(Reporters::$name(reporter) => reporter.into()),*
                }
            }).map(::std::mem::ManuallyDrop::new)
        }

        $(impl $crate::export::SerializeableReporter for $plugin {
            fn reporter_name(&self) -> &'static str {
                stringify!($name)
            }
        })*

        #[doc(hidden)]
        extern "C" fn __necsim_reporter_plugin_library_path() -> Option<::std::path::PathBuf> {
            ::necsim_plugins_core::process_path::get_dylib_path()
        }

        #[doc(hidden)]
        extern "C" fn __necsim_reporter_plugin_drop(
            plugin: ::std::mem::ManuallyDrop<$crate::export::UnsafeReporterPlugin>,
        ) {
            ::std::mem::drop(::std::mem::ManuallyDrop::into_inner(plugin))
        }

        #[doc(hidden)]
        #[no_mangle]
        pub static NECSIM_REPORTER_PLUGIN_DECLARATION: $crate::export::ReporterPluginDeclaration =
            $crate::export::ReporterPluginDeclaration {
                rustc_version: $crate::RUSTC_VERSION,
                core_version: $crate::CORE_VERSION,

                init: __necsim_reporter_plugin_init,
                deserialise: __necsim_reporter_plugin_deserialise,
                library_path: __necsim_reporter_plugin_library_path,
                drop: __necsim_reporter_plugin_drop,
            };
    };
}

pub enum Reporters<'r> {
    DynReporter(&'r DynReporterPlugin),
}

impl<'r> serde::Serialize for Reporters<'r> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        struct Reporter<'r>(&'r DynReporterPlugin);

        impl<'r> serde::Serialize for Reporter<'r> {
            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                erased_serde::serialize(self.0, serializer)
            }
        }

        let Self::DynReporter(reporter) = self;

        serializer.serialize_newtype_variant(
            "Reporters",
            0,
            reporter.reporter_name(),
            &Reporter(*reporter),
        )
    }
}