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

use super::*;

pub(in crate)
fn derive (
    args: Args,
    attrs: &'_ mut Vec<Attribute>,
    pub_: &'_ Visibility,
    EnumName @ _: &'_ Ident,
    generics: &'_ Generics,
    variants: &'_ Punctuated<Variant, Token![,]>,
) -> Result<TokenStream2>
{
    if matches!(
        attrs.iter().find_map(|attr| {
            bool::then(
                attr.path.is_ident("repr"),
                || attr.parse_args::<Ident>().ok()
            ).flatten()
        }),
        Some(repr) if repr.to_string() == "opaque"
    )
    {
        return super::struct_::derive_opaque(
            args,
            attrs,
            pub_,
            EnumName,
            generics,
        );
    }

    let mut ret = quote!();

    if let Some(payload) =
        variants
            .iter()
            .find(|Variant { fields, .. }| matches!(
                fields,
                Fields::Unit,
            ).not())
    {
        bail! {
            "Non field-less `enum`s are not supported yet." => payload.fields,
        }
    }

    if let Some(param) = generics.params.first() {
        bail! {
            "generic `enum`s are not supported yet." => param,
        }
    }
    if let Some(where_clause) = &generics.where_clause {
        bail! {
            "not supported" => where_clause.where_token,
        }
    }

    if variants.is_empty() {
        bail! {
            "C does not support empty enums!"
        }
    }

    let (mb_phantom_int, Int @ _) = parse_discriminant_type(attrs, &mut ret)?;

    let EnumName_Layout @ _ = format_ident!("{}_Layout", EnumName);

    #[apply(let_quote!)]
    use ::safer_ffi::{
        ඞ,
        ඞ::{
            mem,
        },
        layout::{
            // __HasNiche__,
            CLayoutOf,
            CType,
            OpaqueKind,
            ReprC,
        },
    };

    ret.extend(quote!(
        #[allow(warnings, clippy::all)]
        #[repr(transparent)]
        #[#ඞ::derive(
            #ඞ::Clone, #ඞ::Copy,
            // FIXME: try to skip these for faster compilation.
            #ඞ::PartialEq, #ඞ::Eq,
        )]
        #pub_
        struct #EnumName_Layout {
            #pub_
            discriminant: #Int,
        }

        impl
            #ඞ::From<#Int>
        for
            #EnumName_Layout
        {
            #[inline]
            fn from (discriminant: #Int)
              -> Self
            {
                Self { discriminant }
            }
        }
    ));

    let mut impl_body = quote!(
        type OPAQUE_KIND = #OpaqueKind::Concrete;
    );

    let ref each_doc = utils::extract_docs(attrs)?;

    if cfg!(feature = "headers") {
        #[apply(let_quote!)]
        use ::safer_ffi::{
            ඞ::fmt,
            headers::{
                Definer,
                languages::{
                    HeaderLanguage,
                    EnumVariant,
                },
            },
        };

        let ref EnumName_str =
            args.rename.map_or_else(
                || EnumName.to_string().into_token_stream(),
                ToTokens::into_token_stream,
            )
        ;
        let ref each_enum_variant =
            variants.try_vmap(|v| Result::Ok({
                let ref VariantName_str = v.ident.to_string();
                let discriminant = if let Some((_eq, disc)) = &v.discriminant {
                    quote!(
                        #ඞ::Some(&(#disc, ).0 as _)
                    )
                } else {
                    quote!(
                        #ඞ::None
                    )
                };
                let docs = utils::extract_docs(&v.attrs)?;
                quote!(
                    #EnumVariant {
                        docs: &[#(#docs),*],
                        name: #VariantName_str,
                        discriminant: #discriminant,
                    }
                )
            }))?
        ;

        impl_body.extend(quote!(
            fn short_name ()
              -> #ඞ::String
            {
                #EnumName_str.into()
            }

            #[allow(nonstandard_style)]
            fn define_self__impl (
                language: &'_ dyn #HeaderLanguage,
                definer: &'_ mut dyn #Definer,
            ) -> #ඞ::io::Result<()>
            {
                <#Int as #CType>::define_self(language, definer)?;
                language.emit_simple_enum(
                    definer,
                    &[#(#each_doc),*],
                    &#ඞ::marker::PhantomData::<Self>,
                    #mb_phantom_int,
                    &[#(#each_enum_variant),*],
                )
            }
        ));
    }

    ret.extend(quote!(
        unsafe
        impl
            #CType
        for
            #EnumName_Layout
        {
            #impl_body
        }

        unsafe
        impl
            #ReprC
        for
            #EnumName_Layout
        {
            type CLayout = Self;

            fn is_valid (
                _: &'_ #EnumName_Layout,
            ) -> #ඞ::bool
            {
                true
            }
        }
    ));

    if cfg!(feature = "js") && args.js.is_some() {
        let EachVariant @ _ =
            variants.iter().map(|v| &v.ident)
        ;
        ret.extend(quote!(
            ::safer_ffi::layout::CType! {
                @js_enum
                #EnumName_Layout {
                    #(
                        #EachVariant = #EnumName_Layout {
                            discriminant: #EnumName::#EachVariant as _,
                        },
                    )*
                }
            }
        ))
    }

    ret.extend({
        let ref EachVariant @ _ = variants.iter().vmap(|it| &it.ident);
        quote!(
            unsafe
            impl #ReprC for #EnumName {
                type CLayout = #EnumName_Layout;

                #[inline]
                fn is_valid (
                    &#EnumName_Layout { discriminant }: &'_ Self::CLayout,
                ) -> #ඞ::bool
                {
                    #![allow(nonstandard_style)]
                #(
                    const #EachVariant: #Int = #EnumName::#EachVariant as _;
                )*
                    #ඞ::matches!(discriminant, #( #EachVariant )|*)
                }
            }
        )
    });

    // ret.extend(quote!(
    //     unsafe
    //     impl #__HasNiche__
    //     for
    //         #EnumName
    //     {
    //         #[inline]
    //         fn is_niche (
    //             &#EnumName_Layout { discriminant }: &'_ #CLayoutOf<Self>,
    //         ) -> #ඞ::bool
    //         {
    //             /// Safety: should this ever become ill-defined, it would fail to compile.
    //             const DISCRIMINANT_OF_NONE: #Int = unsafe {
    //                 #ඞ::mem::transmute::<_, #Int>(
    //                     #ඞ::None::<#EnumName>
    //                 )
    //             };

    //             #ඞ::matches!(discriminant, DISCRIMINANT_OF_NONE)
    //         }
    //     }
    // ));

    Ok(ret)
}

fn parse_discriminant_type (
    attrs: &'_ [Attribute],
    out_warnings: &mut TokenStream2,
) -> Result<(
        Quote![Option<&impl PhantomCType>],
        TokenStream2,
    )>
{
    let repr_attr =
        attrs
            .iter()
            .find(|attr| attr.path.is_ident("repr"))
            .ok_or(())
            .or_else(|()| bail!("missing `#[repr(…)]` annotation"))?
    ;
    let ref reprs = repr_attr.parse_args_with(
        Punctuated::<Ident, Token![,]>::parse_terminated,
    )?;
    if reprs.is_empty() {
        bail!("expected an integral `repr` specifier" => repr_attr);
    }
    let parsed_reprs = reprs.iter().try_vmap(Repr::try_from)?;
    let (c_type, repr) =
        match
            ::core::iter::zip(parsed_reprs, reprs)
                .find(|(parsed, _ident)| matches!(parsed, Repr::C).not())
        {
            | Some((_repr, ident)) => {
                let IntTy = quote!(
                    ::safer_ffi::ඞ::#ident
                );
                (
                    quote!(
                        ::safer_ffi::ඞ::Some(
                            &::safer_ffi::ඞ::marker::PhantomData::<#IntTy>
                        )
                    ),
                    IntTy,
                )
            },
            | None if reprs.iter().any(|repr| repr == "C") => {
                out_warnings.extend(utils::compile_warning(
                    reprs,
                    "\
                        `#[repr(C)]` enums are not well-defined in C; \
                        it is thus ill-advised to use them \
                        in a multi-compiler scenario such as FFI\
                    ",
                ));
                let IntTy = quote!(
                    ::safer_ffi::ඞ::os::raw::c_int
                );
                (
                    quote!(
                        ::safer_ffi::ඞ::None
                    ),
                    IntTy,
                )
            },
            | None => bail! {
                "expected an integral `repr` annotation"
            },
        }
    ;

    Ok((c_type, repr))
}

match_! {(
    C,
    u8, u16, u32, u64, u128,
    i8, i16, i32, i64, i128,
) {(
    $($repr:ident),* $(,)?
) => (
    enum Repr {
        $($repr),*
    }

    impl Repr {
        fn try_from (ident: &'_ Ident)
          -> Result<Self>
        {
            match &ident.to_string()[..] {
            $(
                | stringify!($repr) => Ok(Self::$repr),
            )*
                | _ => bail! {
                    "unsupported `repr` annotation" => ident,
                },
            }
        }
    }
)}}