jyafn-ext 0.1.1

Jyafn extension creation helper library
Documentation
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
//! This crate is intended to help extension authors. It exposes a minimal version of
//! `jyafn` and many convenience macros to generate all the boilerplate involved.

mod io;
mod layout;
mod outcome;
mod resource;

/// Reexporting from the `paste` crate. This is neeede because we have to programatically
/// generate new identifiers to be used as symbols in the final shared object.
pub use paste::paste;
/// We need JSON support to zip JSON values around the FFI boundary.
pub use serde_json;

pub use io::{Input, OutputBuilder, InputReader};
pub use layout::{Layout, Struct, ISOFORMAT};
pub use outcome::Outcome;
pub use resource::{Method, Resource};

/// Generates the boilerplate code for a `jyafn` extension.
///
/// # Usage
///
/// This macro accepts a list of comman-separated types, each of which has to implement
/// the [`Resource`] trait, like so
/// ```
/// extension! {
///     Foo, Bar, Baz
/// }
/// ```
/// Optionally, you may define an init function, which takes no arguments and returns
/// `Result<(), String>`, like so
/// ```
/// extension! {
///     init = my_init;
///     Foo, Bar, Baz
/// }
///
/// fn my_init() -> Result<(), String> { /* ... */}
/// ```
#[macro_export]
macro_rules! extension {
    ($($ty:ty),*) => {
        fn noop() -> Result<(), String> { Ok (()) }

        $crate::extension! {
            init = noop;
            $($ty),*
        }
    };
    (init = $init_fn:ident; $($ty:ty),*) => {
        use std::ffi::{c_char, CString};
        use $crate::Outcome;

        /// Creates a C-style string out of a `String` in a way that doesn't produce errors. This
        /// function substitutes nul characters by the ` ` (space) character. This avoids an
        /// allocation.
        ///
        /// This method **leaks** the string. So, don't forget to guarantee that somene somewhere
        /// is freeing it.
        ///
        /// # Note
        ///
        /// Yes, I know! It's a pretty lousy implementation that is even... O(n^2) (!!). You can
        /// do better than I in 10mins.
        pub(crate) fn make_safe_c_str(s: String) -> CString {
            let mut v = s.into_bytes();
            loop {
                match std::ffi::CString::new(v) {
                    Ok(c_str) => return c_str,
                    Err(err) => {
                        let nul_position = err.nul_position();
                        v = err.into_vec();
                        v[nul_position] = b' ';
                    }
                }
            }
        }


        /// # Safety
        ///
        /// Expecting a valid pointer from input.
        #[no_mangle]
        pub unsafe extern "C" fn outcome_get_err(outcome: *mut Outcome) -> *const c_char {
            let outcome = &*outcome;

            match outcome {
                Outcome::Ok(_) => std::ptr::null(),
                Outcome::Err(err) => err.as_ptr(),
            }
        }

        /// # Safety
        ///
        /// Expecting a valid pointer from input.
        #[no_mangle]
        pub unsafe extern "C" fn outcome_get_ok(outcome: *mut Outcome) -> *mut () {
            let outcome = &*outcome;

            match outcome {
                Outcome::Ok(ptr) => *ptr,
                Outcome::Err(_) => std::ptr::null_mut(),
            }
        }

        /// # Safety
        ///
        /// Expecting a valid pointer from input.
        #[no_mangle]
        pub unsafe extern "C" fn outcome_drop(outcome: *mut Outcome) {
            let _ = Box::from_raw(outcome);
        }

        /// # Safety
        ///
        /// Expecting a valid pointer from input.
        #[no_mangle]
        pub unsafe extern "C" fn dump_get_len(dump: *const Vec<u8>) -> usize {
            let dump = &*dump;
            dump.len()
        }

        /// # Safety
        ///
        /// Expecting a valid pointer from input.
        #[no_mangle]
        pub unsafe extern "C" fn dump_get_ptr(dump: *const Vec<u8>) -> *const u8 {
            let dump = &*dump;
            dump.as_ptr()
        }

        /// # Safety
        ///
        /// Expecting a valid pointer from input.
        #[no_mangle]
        pub unsafe extern "C" fn dump_drop(dump: *mut Vec<u8>) {
            let _ = Box::from_raw(dump);
        }

        #[no_mangle]
        pub unsafe extern "C" fn string_drop(method: *mut c_char) {
            let _ = CString::from_raw(method);
        }

        #[no_mangle]
        pub extern "C" fn extension_init() -> *const c_char {
            fn safe_extension_init() -> Result<$crate::serde_json::Value, String> {
                $init_fn()?;

                let manifest = $crate::serde_json::json!({
                    "metadata": {
                        "name": env!("CARGO_PKG_NAME"),
                        "version": env!("CARGO_PKG_VERSION"),
                        "about": env!("CARGO_PKG_DESCRIPTION"),
                        "authors": env!("CARGO_PKG_AUTHORS"),
                        "license": env!("CARGO_PKG_LICENSE"),
                    },
                    "outcome": {
                        "fn_get_err": "outcome_get_err",
                        "fn_get_ok": "outcome_get_ok",
                        "fn_drop": "outcome_drop"
                    },
                    "dumped": {
                        "fn_get_ptr": "dump_get_ptr",
                        "fn_get_len": "dump_get_len",
                        "fn_drop": "dump_drop"
                    },
                    "string": {
                        "fn_drop": "string_drop"
                    },
                    "resources": {$(
                        stringify!($ty): {
                            "fn_from_bytes": stringify!($ty).to_string() + "_from_bytes",
                            "fn_dump": stringify!($ty).to_string() + "_dump",
                            "fn_size": stringify!($ty).to_string() + "_size",
                            "fn_get_method_def": stringify!($ty).to_string() + "_get_method",
                            "fn_drop": stringify!($ty).to_string() + "_drop"
                        },
                    )*}
                });

                Ok(manifest)
            }

            let outcome = std::panic::catch_unwind(|| {
                match safe_extension_init() {
                    Ok(manifest) => manifest,
                    Err(err) => {
                        $crate::serde_json::json!({"error": err})
                    }
                }
            }).unwrap_or_else(|_| {
                $crate::serde_json::json!({
                    "error": "extension initialization panicked. See stderr"
                })
            });

            match CString::new(outcome.to_string()) {
                Ok(s) => s.into_raw(),
                Err(_) => std::ptr::null(),
            }
        }

        $(
            $crate::resource! { $ty }
        )*
    };
}

/// Declares a single resource for this extension, given a type. This writes all the
/// boilerplate code thar corresponds to the extension side of the API.
#[macro_export]
macro_rules! resource {
    ($ty:ty) => {
        $crate::paste! {

            #[allow(unused)]
            fn [<$ty _test_is_a_resource>]() where $ty: $crate::Resource {}

            #[no_mangle]
            pub unsafe extern "C" fn [<$ty _size>](raw: *mut $ty) -> usize {
                std::panic::catch_unwind(|| (&*raw).size())
                    .unwrap_or_else(|_| {
                        eprintln!(
                            "calling `size` on resource {:?} panicked. Size will be set to zero. See stderr.",
                            stringify!($ty)
                        );
                        0
                    })
            }

            #[no_mangle]
            pub unsafe extern "C" fn [<$ty _dump>](raw: *mut $ty) -> *mut $crate::Outcome {
                std::panic::catch_unwind(|| {
                    let boxed = Box::new($crate::Outcome::from((&*raw).dump()));
                    Box::leak(boxed) as *mut _
                }).unwrap_or_else(|_| {
                    eprintln!(
                        "calling `dump` on resource {:?} panicked. Will return null. See stderr.",
                        stringify!($ty)
                    );
                    std::ptr::null_mut()
                })
            }

            #[no_mangle]
            pub unsafe extern "C" fn [<$ty _from_bytes>](
                bytes_ptr: *const u8,
                bytes_len: usize,
            ) -> *mut $crate::Outcome {
                std::panic::catch_unwind(|| {
                    let bytes = std::slice::from_raw_parts(bytes_ptr, bytes_len);
                    let boxed = Box::new($crate::Outcome::from($ty::from_bytes(bytes)));
                    Box::leak(boxed) as *mut _
                }).unwrap_or_else(|_| {
                    eprintln!(
                        "calling `dump` on resource {:?} panicked. Will return null. See stderr.",
                        stringify!($ty)
                    );
                    std::ptr::null_mut()
                })
            }

            #[no_mangle]
            pub unsafe extern "C" fn [<$ty _get_method>](
                raw: *mut $ty,
                name: *const c_char,
            ) -> *const c_char {
                std::panic::catch_unwind(|| {
                    let name = std::ffi::CStr::from_ptr(name);
                    let method = (&*raw).get_method(&name.to_string_lossy());

                    if let Some(method) = method {
                        CString::new(
                            $crate::serde_json::to_string_pretty(&method)
                                .expect("can always serialize method as json")
                        )
                        .expect("json representation does not contain nul chars")
                        .into_raw()
                    } else {
                        std::ptr::null()
                    }
                }).unwrap_or_else(|_| {
                    eprintln!(
                        "calling `get_method` on resource {:?} panicked. See stderr.",
                        stringify!($ty)
                    );
                    std::ptr::null()
                })
            }

            #[no_mangle]
            pub unsafe extern "C" fn [<$ty _drop>](raw: *mut $ty) {
                std::panic::catch_unwind(|| {
                    let _ = Box::from_raw(raw);
                }).unwrap_or_else(|_| {
                    eprintln!(
                        "calling `drop` on resource {:?} panicked. See stderr.",
                        stringify!($ty)
                    );
                })
            }
        }
    };
}

/// A safe convenience macro for method call. This macro does three things for you:
/// 1. Converts the raw pointer to a reference.
/// 2. Converts the pointers into slices correctly.
/// 3. Treats possible panics, converting them to errors. Panics are always unwanted, but
///    panicking through an FFI boundary is UB. Therefore, this treatment is always necessary.
///
/// # Usage
///
/// ```
/// impl MyResource {
///     fn something_safe(
///         &self,
///         input: Input,
///         output: OutputBuilder,
///     ) -> Result<(), String> {   // or anything else implementing `ToString`...
///         // ...
///         todo!()
///     }
///
///     method!(something_safe)  // can only call from inside an impl block!
///                              // This is for type safety reasons
/// }
///
/// ```
#[macro_export]
macro_rules! method {
    ($safe_interface:ident) => {
        $crate::paste! {
            #[allow(non_snake_case)]
            pub unsafe extern "C" fn [<raw_method__ $safe_interface>](
                resource_ptr: *const (),
                input_ptr: *const u8,
                input_slots: u64,
                output_ptr: *mut u8,
                output_slots: u64,
            ) -> *mut u8 {
                match std::panic::catch_unwind(|| {
                    unsafe {
                        // Safety: all this stuff came from jyafn code. The jyafn code should
                        // provide valid parameters. Plus, it's the responsibility of the
                        // implmementer guarantee that the types match.

                        let resource: &Self = &*(resource_ptr as *const _);

                        Self::$safe_interface(
                            resource,
                            $crate::Input::new(input_ptr, input_slots as usize),
                            $crate::OutputBuilder::new(output_ptr, output_slots as usize),
                        )
                    }
                }) {
                    Ok(Ok(())) => std::ptr::null_mut(),
                    Ok(Err(err)) => {
                        make_safe_c_str(err).into_raw() as *mut u8
                    }
                    // DON'T forget the nul character when working with bytes directly!
                    Err(_) => {
                        make_safe_c_str(format!(
                            "method {:?} panicked. See stderr",
                            stringify!($safe_interface),
                        )).into_raw() as *mut u8
                    }
                }
            }
        }
    };
}

/// A convenience macro to get references to methods created with [`method`].
#[macro_export]
macro_rules! get_method_ptr {
    ($safe_interface:ident) => {
        $crate::paste!(Self::[<raw_method__ $safe_interface>]) as usize
    }
}

/// This macro provides a standard implementation for the [`Resource::get_method`]
/// function from a list of methods.
///
/// # Usage
///
/// ```
/// impl Resource for MyResource {
///     // ...
///
///     fn get_method(&self, method: &str) -> Option<Method> {
///         declare_methods! {
///             // This the the variable containing the method name.
///             match method:
///                 // Use the layout notation to declare the method (an yes, you can use
///                 // `self` anywhere in the declaration)
///                 foo_method(x: scalar, y: [datetime; self.size]) -> [datetime; self.size];
///         }
///     }
/// }
/// ```
#[macro_export]
macro_rules! declare_methods {
    ($( $safe_interface:ident ($($key:tt : $ty:tt),*) -> $output:tt; )*) => {
        $crate::declare_methods! {
            match method:  $( $safe_interface ($($key : $ty),*) -> $output; )*
        }
    };
    ( match $method:ident : $( $safe_interface:ident ($($key:tt : $ty:tt),*) -> $output:tt; )*) => {
        Some(match $method {
            $(
                stringify!($safe_interface) => $crate::Method {
                    fn_ptr: $crate::get_method_ptr!($safe_interface),
                    input_layout: $crate::r#struct!($($key : $ty),*),
                    output_layout: $crate::layout!($output),
                },
            )*
            _ => return None,
        })
    };
}