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
//! C headers generation.
//!
//! This module is only enabled when the `"headers"` feature of `::safer_ffi` is
//! enabled, which is expected to be done through a cargo feature within the
//! (downstream) crate defining the `#[ffi_export]`ed
//! functions.
//!
//! ```toml
//! [dependencies]
//! safer-ffi = { version = "...", features = ["proc_macros"] }
//!
//! [features]
//! generate-headers = ["safer-ffi/headers"]
//! ```
//!
//! Then, to generate the bindings, just define a
//! `#[safer_ffi::cfg_headers]`-gated `#[test]` function,
//! which can then call the [`builder`] to do the work:
//!
//! ```rust
//! use ::std::{io, fs};
//! use ::safer_ffi::prelude::*;
//!
//! /// Concatenate two strings.
//! ///
//! /// The returned value must be freed with `rust_free`
//! #[ffi_export]
//! fn rust_concat (fst: char_p::Ref<'_>, snd: char_p::Ref<'_>)
//!   -> char_p::Box
//! {
//!     let s: String = format!("{}{}\0", fst, snd);
//!     s   .try_into() // Try to convert to a boxed `char *` pointer
//!         .unwrap()   // Only fails if there is an inner nul byte.
//! }
//!
//! /// Frees a pointer obtained by calling `rust_concat`.
//! #[ffi_export]
//! fn rust_free (it: char_p::Box)
//! {
//!     drop(it);
//! }
//!
//! # macro_rules! ignore { ($($t:tt)*) => () } ignore! {
//! #[::safer_ffi::cfg_headers]
//! #[test]
//! # }
//! fn generate_c_header ()
//!   -> io::Result<()>
//! {
//!     ::safer_ffi::headers::builder()
//!         .with_guard("__ASGARD__")
//!         .to_file("filename.h")?
//!         .generate()
//! }
// //! # generate_c_header().unwrap();
//! ```
//!
//! so that
//!
//! ```shell
//! cargo test --features generate-headers -- \
//!     --exact generate_c_header \
//!     --nocapture
//! ```
//!
//! generates a `"filename.h"` file (⚠️ overwriting it if it exists ⚠️) with
//! the following contents:
//!
//! <pre style="color:#000020;background:#f6f8ff;"><span style="color:#3f7f8f; ">/*! \file */</span>
//! <span style="color:#3f7f8f; ">/*******************************************</span>
//! <span style="color:#3f7f8f; ">&nbsp;*                                         *</span>
//! <span style="color:#3f7f8f; ">&nbsp;*  File auto-generated by `::safer_ffi`.  *</span>
//! <span style="color:#3f7f8f; ">&nbsp;*                                         *</span>
//! <span style="color:#3f7f8f; ">&nbsp;*  Do not manually edit this file.        *</span>
//! <span style="color:#3f7f8f; ">&nbsp;*                                         *</span>
//! <span style="color:#3f7f8f; ">&nbsp;*******************************************/</span>
//!
//! <span style="color:#004a43; ">#</span><span style="color:#004a43; ">ifndef</span><span style="color:#004a43; "> __ASGARD__</span>
//! <span style="color:#004a43; ">#</span><span style="color:#004a43; ">define</span><span style="color:#004a43; "> __ASGARD__</span>
//!
//!
//! <span style="color:#3f7f8f; ">/** \brief</span>
//! <span style="color:#3f7f8f; ">&nbsp;*  Concatenate two strings.</span>
//! <span style="color:#3f7f8f; ">&nbsp;* </span>
//! <span style="color:#3f7f8f; ">&nbsp;*  The returned value must be freed with `rust_free_string`</span>
//! <span style="color:#3f7f8f; ">&nbsp;*/</span>
//! <span style="color:#200080; font-weight:bold; ">char</span> <span style="color:#308080; ">*</span> rust_concat <span style="color:#308080; ">(</span>
//!     <span style="color:#200080; font-weight:bold; ">char</span> <span style="color:#200080; font-weight:bold; ">const</span> <span style="color:#308080; ">*</span> fst<span style="color:#308080; ">,</span>
//!     <span style="color:#200080; font-weight:bold; ">char</span> <span style="color:#200080; font-weight:bold; ">const</span> <span style="color:#308080; ">*</span> snd<span style="color:#308080; ">)</span><span style="color:#406080; ">;</span>
//!
//! <span style="color:#3f7f8f; ">/** \brief</span>
//! <span style="color:#3f7f8f; ">&nbsp;*  Frees a pointer obtained by calling `rust_concat`.</span>
//! <span style="color:#3f7f8f; ">&nbsp;*/</span>
//! <span style="color:#200080; font-weight:bold; ">void</span> rust_free_string <span style="color:#308080; ">(</span>
//!     <span style="color:#200080; font-weight:bold; ">char</span> <span style="color:#308080; ">*</span> it<span style="color:#308080; ">)</span><span style="color:#406080; ">;</span>
//!
//!
//! <span style="color:#004a43; ">#</span><span style="color:#004a43; ">endif</span><span style="color:#004a43; "> </span><span style="color:#595979; ">/* __ASGARD__ */</span>
//! </pre>

#![allow(missing_copy_implementations, missing_debug_implementations)]

use ::std::{
    collections::HashSet,
    env,
    fs,
    io,
    path::Path,
};

use_prelude!();
use rust::{String, Vec};

pub use definer::{Definer, HashSetDefiner};
mod definer;

macro_rules! with_optional_fields {(
    $(
        $(#[$field_meta:meta])*
        $field:ident : $field_ty:ty
    ),* $(,)?
) => (
    #[derive(Default)]
    pub
    struct Builder<'__, W> {
        target: W,
        $(
            $field : Option<$field_ty>,
        )*
    }

    pub
    fn builder<'__> ()
      -> Builder<'__, WhereTo>
    {
        Builder::default()
    }

    use __::WhereTo;
    mod __ {
        #[derive(Default)]
        pub
        struct WhereTo;
    }

    ::paste::item! {
        impl<'__, W> Builder<'__, W> {
            $(
                $(#[$field_meta])*
                pub
                fn [<with_$field>] (self, $field : $field_ty)
                  -> Self
                {
                    let $field = Some($field);
                    Self {
                        $field,
                        .. self
                    }
                }
            )*
        }
    }

    impl<'__> Builder<'__, WhereTo> {
        /// Specify the path to the file to be generated.
        ///
        /// **⚠️ If it already exists, its contents will be overwritten ⚠️**
        ///
        /// There is no default value here, either `.to_file()` or [`.to_writer()`]
        /// need to be called to be able to [`.generate()`] the headers.
        ///
        /// For more fine-grained control over the "output stream" where the
        /// headers will be written to, use [`.to_writer()`].
        ///
        /// # Example
        ///
        /// ```rust,no_run
        /// # fn main () -> ::std::io::Result<()> { Ok({
        /// ::safer_ffi::headers::builder()
        ///     .to_file("my_header.h")?
        ///     .generate()?
        /// # })}
        /// ```
        ///
        /// [`.to_writer()`]: `Builder::to_writer`
        /// [`.generate()`]: `Builder::generate`
        pub
        fn to_file (
            self: Self,
            filename: impl AsRef<Path>,
        ) -> io::Result<Builder<'__, fs::File>>
        {
            Ok(self.to_writer(
                fs::OpenOptions::new()
                    .create(true)/*or*/.truncate(true)
                    .write(true)
                    .open(filename)?
            ))
        }

        /// Specify the [`Write`][`io::Write`] "stream" where the headers will
        /// be written to.
        ///
        /// # Example
        ///
        /// ```rust,no_run
        /// // Display the headers to the standard output
        /// // (may need the `--nocapture` flag when running the tests)
        /// # fn main () -> ::std::io::Result<()> { Ok({
        /// ::safer_ffi::headers::builder()
        ///     .to_writer(::std::io::stdout())
        ///     .generate()?
        /// # })}
        /// ```
        pub
        fn to_writer<W> (
            self: Self,
            out: W,
        ) -> Builder<'__, W>
        where
            W : io::Write
        {
            let Self {
                target: WhereTo, $(
                $field, )*
                ..
            } = self;
            Builder {
                target: out,
                $($field ,)*
            }
        }
    }

    impl<'__, W : io::Write> Builder<'__, W> {
        /// Generate the C header file.
        pub
        fn generate (self)
          -> io::Result<()>
        {
            let Self { mut target, $($field ,)* } = self;
            Builder {
                target: WhereTo, $(
                $field, )*
            }.generate_with_definer(HashSetDefiner {
                out: &mut target,
                defines_set: Default::default(),
            })
        }

        // pub
        // fn as_mut_dyn (self: &'__ mut Self)
        //   -> Builder<'__, &'__ mut dyn io::Write>
        // where
        //     W : '__,
        // {
        //     let Self { ref mut target, $($field ,)* } = *self;
        //     Builder {
        //         target, $(
        //         $field, )*
        //     }
        // }
    }
)}

with_optional_fields! {
    /// Sets up the name of the `ifndef` guard of the header file.
    ///
    /// It defaults to:
    ///
    /// ```rust,ignore
    /// format!("__RUST_{}__", env::var("CARGO_PKG_NAME")?.to_ascii_uppercase())
    /// ```
    guard: &'__ str,

    /// Sets up the banner of the generated C header file.
    ///
    /// It defaults to:
    ///
    /// ```rust,ignore
    /// concat!(
    ///     "/*! \\file */\n",
    ///     "/*******************************************\n",
    ///     " *                                         *\n",
    ///     " *  File auto-generated by `::safer_ffi`.  *\n",
    ///     " *                                         *\n",
    ///     " *  Do not manually edit this file.        *\n",
    ///     " *                                         *\n",
    ///     " *******************************************/\n",
    /// )
    /// ```
    ///
    /// <pre style="color:#000020;background:#f6f8ff;"><span style="color:#3f7f8f; ">/*! \file */</span>
    /// <span style="color:#3f7f8f; ">/*******************************************</span>
    /// <span style="color:#3f7f8f; ">&nbsp;*                                         *</span>
    /// <span style="color:#3f7f8f; ">&nbsp;*  File auto-generated by `::safer_ffi`.  *</span>
    /// <span style="color:#3f7f8f; ">&nbsp;*                                         *</span>
    /// <span style="color:#3f7f8f; ">&nbsp;*  Do not manually edit this file.        *</span>
    /// <span style="color:#3f7f8f; ">&nbsp;*                                         *</span>
    /// <span style="color:#3f7f8f; ">&nbsp;*******************************************/</span>
    /// </pre>
    banner: &'__ str,
}

impl Builder<'_, WhereTo> {
    /// More customizable version of [`.generate()`][`Builder::generate].
    ///
    /// With this call, one can provide a custom implementation of a [`Definer`],
    /// which can be useful for mock tests, mainly.
    pub
    fn generate_with_definer (self, mut definer: impl Definer)
      -> io::Result<()>
    {
        let s;
        let config = self;
        let guard: &'_ str =
            if let Some(it) = config.guard { it } else {
                s = format!("__RUST_{}__",
                    env::var("CARGO_PKG_NAME")
                        .unwrap()
                        .to_ascii_uppercase()
                );
                &*s
            }
        ;
        let banner: &'_ str = config.banner.unwrap_or(concat!(
            "/*! \\file */\n",
            "/*******************************************\n",
            " *                                         *\n",
            " *  File auto-generated by `::safer_ffi`.  *\n",
            " *                                         *\n",
            " *  Do not manually edit this file.        *\n",
            " *                                         *\n",
            " *******************************************/",
        ));

        write!(definer.out(),
            concat!(
                "{banner}\n\n",
                "#ifndef {guard}\n",
                "#define {guard}\n",
                "\n",
                "#ifdef __cplusplus\n",
                "extern \"C\" {{\n",
                "#endif\n\n",
            ),
            guard = guard,
            banner = banner,
        )?;
        crate::inventory::iter
            .into_iter()
            // Iterate in reverse fashion to more closely match
            // the Rust definition order.
            .collect::<Vec<_>>().into_iter().rev()
            .try_for_each(|crate::FfiExport(define)| define(&mut definer))
            ?
        ;
        write!(definer.out(),
            concat!(
                "\n",
                "#ifdef __cplusplus\n",
                "}} /* extern \"C\" */\n",
                "#endif\n",
                "\n",
                "#endif /* {} */\n",
            ),
            guard,
        )?;
        Ok(())
    }
}