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
#![cfg_attr(rustfmt, rustfmt::skip)]
#![allow(irrefutable_let_patterns)]

use_prelude!();
use {
    ::std::io::{
        self,
        Write as _,
    },
    super::{
        Definer,
    },
};

pub use c::C;
mod c;

__cfg_csharp__! {
    pub use csharp::CSharp;
    mod csharp;
}

__cfg_python__! {
    pub use python::Python;
    mod python;
}

pub
struct Indentation {
    depth: ::core::cell::Cell<usize>,
    width: usize,
}

impl Indentation {
    pub
    fn new (width: usize)
      -> Indentation
    {
        Self { depth: 0.into(), width }
    }

    pub
    fn scope (self: &'_ Self)
      -> impl '_ + Sized
    {
        self.depth.set(self.depth.get() + 1);
        ::scopeguard::guard((), move |()| {
            self.depth.set(self.depth.get() - 1);
        })
    }
}

impl ::core::fmt::Display for Indentation {
    fn fmt (
        self: &'_ Indentation,
        fmt: &'_ mut ::core::fmt::Formatter<'_>,
    ) -> ::core::fmt::Result
    {
        write!(fmt, "{: <indent$}", "", indent = self.depth.get() * self.width)
    }
}

type Docs<'lt> = &'lt [&'lt str];

pub
trait HeaderLanguage : UpcastAny {
    fn language_name(&self) -> &'static str {
        ::core::any::type_name::<Self>()
    }

    fn emit_simple_enum (
        self: &'_ Self,
        ctx: &'_ mut dyn Definer,
        docs: Docs<'_>,
        self_ty: &'_ dyn PhantomCType,
        backing_integer: Option<&'_ dyn PhantomCType>,
        variants: &'_ [EnumVariant<'_>],
    ) -> io::Result<()>
    ;

    fn emit_struct (
        self: &'_ Self,
        ctx: &'_ mut dyn Definer,
        docs: Docs<'_>,
        self_ty: &'_ dyn PhantomCType,
        fields: &'_ [StructField<'_>]
    ) -> io::Result<()>
    ;

    fn emit_opaque_type (
        self: &'_ Self,
        ctx: &'_ mut dyn Definer,
        docs: Docs<'_>,
        self_ty: &'_ dyn PhantomCType,
    ) -> io::Result<()>
    ;

    fn emit_function (
        self: &'_ Self,
        ctx: &'_ mut dyn Definer,
        docs: Docs<'_>,
        fname: &'_ str,
        args: &'_ [FunctionArg<'_>],
        ret_ty: &'_ dyn PhantomCType,
    ) -> io::Result<()>
    ;

    fn emit_constant (
        self: &'_ Self,
        ctx: &'_ mut dyn Definer,
        docs: Docs<'_>,
        name: &'_ str,
        ty: &'_ dyn PhantomCType,
        value: &'_ dyn ::core::fmt::Debug,
    ) -> io::Result<()>
    ;

    fn emit_docs (
        self: &'_ Self,
        _ctx: &'_ mut dyn Definer,
        _docs: Docs<'_>,
        _indentation: &'_ Indentation,
    ) -> io::Result<()>
    {
        // This function is just offered as a convenience helper;
        // it is not directly called by the framework.
        Ok(())
    }
}

pub
struct EnumVariant<'lt> {
    pub
    docs: Docs<'lt>,

    pub
    name: &'lt str,

    pub
    discriminant: Option<&'lt dyn ::core::fmt::Debug>,
}

pub
struct StructField<'lt> {
    pub
    docs: Docs<'lt>,

    pub
    name: &'lt str,

    pub
    ty: &'lt dyn PhantomCType,
}

pub
struct FunctionArg<'lt> {
    // pub
    // docs: Docs<'lt>,

    pub
    name: &'lt str,

    pub
    ty: &'lt dyn PhantomCType,
}

/// `T::assoc_func()` -> `PhantomData::<T>.method()` conversion
/// so as to become `dyn`-friendly (you can't pass a heterogeneous array of
/// *distinct* `T : Trait`s *types* to a function, but you can pass a slice of
/// `PhantomData`-materialized `dyn Trait`s).
///
/// In other words, we are projecting a compile-time type-level knowledge
/// of an array / struct / "table" of a type's associated functions
/// into a _runtime_ table of such, thence allowing runtime / `dyn`amic
/// unification within a heterogeneous collection.
pub
trait PhantomCType {
    fn short_name (
        self: &'_ Self,
    ) -> String
    ;

    fn name_wrapping_var (
        self: &'_ Self,
        language: &'_ dyn HeaderLanguage,
        var_name: &'_ str,
    ) -> String
    ;

    fn name (
        self: &'_ Self,
        language: &'_ dyn HeaderLanguage,
    ) -> String
    ;

    fn csharp_marshaler (
        self: &'_ Self,
    ) -> Option<String>
    ;

    fn size (
        self: &'_ Self,
    ) -> usize
    ;

    fn align (
        self: &'_ Self,
    ) -> usize
    ;
}

impl<T : ?Sized>
    PhantomCType
for
    ::core::marker::PhantomData<T>
where
    T : CType,
{
    fn short_name (
        self: &'_ Self,
    ) -> String
    {
        <T as CType>::short_name()
    }

    fn name_wrapping_var (
        self: &'_ Self,
        language: &'_ dyn HeaderLanguage,
        var_name: &'_ str,
    ) -> String
    {
        T::name_wrapping_var(language, var_name)
    }

    fn name (
        self: &'_ Self,
        language: &'_ dyn HeaderLanguage,
    ) -> String
    {
        T::name(language)
    }

    fn csharp_marshaler (
        self: &'_ Self,
    ) -> Option<String>
    {
        T::csharp_marshaler()
    }

    fn size (
        self: &'_ Self,
    ) -> usize
    {
        ::core::mem::size_of::<T>()
    }

    fn align (
        self: &'_ Self,
    ) -> usize
    {
        ::core::mem::align_of::<T>()
    }
}

/// Generates an `out!` macro.
///
/// Important: the `out!` macro accepts a `("foo" "bar" "baz")` shorthand
/// for the format literal parameter, to automatically convert it to:
///
/** ```rust ,ignore
concat!(
    "{indent}foo\n",
    "{indent}bar\n",
    "{indent}baz\n",
)
``` */
///
/// where `"{indent}"` is the first parameter passed to `mk_out!`,
/// and the second parameter is the `impl Write` the `write!`s will
/// be outputting to.
macro_rules! mk_out {
    (
        $indent_name:ident,
        // $indent:tt,
        $out:expr $(,)?
    ) => (
        mk_out! { $indent_name /* $indent */ $out $ }
    );

    (
        $indent_name:tt /* $indent:tt */ $out:tt $_:tt
    ) => (
        macro_rules! out {
            (
                ($_(
                    $line:tt
                )*) $_($rest:tt)*
            ) => (
                // we have to use eager expansion of `concat!` coupled with
                // span manipulation for the implicit format args to work…
                ::with_builtin_macros::with_builtin! {
                    let $concat = concat!($_(
                        "{", stringify!($indent_name), "}",
                        $line,
                        "\n",
                    )*) in {
                        ::safer_ffi_proc_macros::__respan! {
                            // take the (first) span of the format string
                            // literals provided by the caller…
                            ( $_($line)* ) (
                                // …and replace, with it, the spans of the whole
                                //  `write!(` invocation.
                                for line in
                                    format!(
                                        $concat
                                        $_($rest)*
                                    )
                                    .split_inclusive('\n')
                                {
                                    let new_line = if line.ends_with('\n') { "\n" } else { "" };
                                    write!($out, "{}{new_line}", line.trim_end())?;
                                }
                            )
                        }
                    }
                }
                /* for reference, here is the "simple usecase" I'd have expected
                 * to Just Work™: */
                // write!(
                //     $out,
                //     concat!($_(
                //         // "{", stringify!($indent), "}",
                //         $indent,
                //         $line,
                //         "\n",
                //     )*)
                //     // , $indent_name = $indent_name
                //     $_($rest)*
                // )
            );

            ( $_($tt:tt)* ) => (
                write!($out, $_($tt)*)?
            )
        }
    );
} use mk_out;

pub
trait UpcastAny : 'static {
    fn upcast_any (self: &'_ Self)
      -> &'_ dyn ::core::any::Any
    ;
}
impl<T : 'static> UpcastAny for T {
    fn upcast_any (self: &'_ Self)
      -> &'_ dyn ::core::any::Any
    {
        self
    }
}

impl dyn HeaderLanguage {
    pub
    fn is<Concrete : HeaderLanguage> (
        self: &'_ Self,
    ) -> bool
    {
        self.upcast_any().is::<Concrete>()
    }

    pub
    fn downcast_ref<Concrete : HeaderLanguage> (
        self: &'_ Self,
    ) -> Option<&'_ Concrete>
    {
        self.upcast_any()
            .downcast_ref()
    }
}