stabby-macros 3.0.3-rc2

the macros that make working with stabby possible, you shouldn't add this crate to your dependencies, only `stabby`.
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//
// Copyright (c) 2023 ZettaScale Technology
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
//
// Contributors:
//   Pierre Avital, <pierre.avital@me.com>
//

use std::ops::Deref;

use proc_macro2::TokenStream;
use quote::quote;
use syn::{Attribute, DataEnum, Generics, Ident, Visibility};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Repr {
    Stabby,
    C,
    U8,
    U16,
    U32,
    U64,
    Usize,
    I8,
    I16,
    I32,
    I64,
    Isize,
}
impl syn::parse::Parse for Repr {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let id: syn::Ident = input.parse()?;
        match id.to_string().as_str() {
            "C" => Ok(Self::C),
            "u8" => Ok(Self::U8),
            "u16" => Ok(Self::U16),
            "u32" => Ok(Self::U32),
            "u64" => Ok(Self::U64),
            "usize" => Ok(Self::Usize),
            "i8" => Ok(Self::I8),
            "i16" => Ok(Self::I16),
            "i32" => Ok(Self::I32),
            "i64" => Ok(Self::I64),
            "isize" => Ok(Self::Isize),
            "stabby" => Ok(Self::Stabby),
            _ => Err(input.error("Unexpected repr, only `u*` and `stabby` are supported")),
        }
    }
}

pub fn stabby(
    attrs: Vec<Attribute>,
    vis: Visibility,
    ident: Ident,
    generics: Generics,
    data: DataEnum,
) -> TokenStream {
    let st = crate::tl_mod();
    let unbound_generics = &generics.params;
    let mut repr = None;
    let repr_ident = quote::format_ident!("repr");
    let mut new_attrs = Vec::with_capacity(attrs.len());
    for a in attrs {
        if a.path.is_ident(&repr_ident) {
            if repr.is_none() {
                repr = Some(a.parse_args().unwrap())
            } else {
                panic!("multiple reprs are forbidden")
            }
        } else {
            new_attrs.push(a)
        }
    }
    if data.variants.is_empty() {
        todo!("empty enums are not supported by stabby YET")
    }
    let mut layout = quote!(());
    let DataEnum { variants, .. } = &data;
    let mut has_non_empty_fields = false;
    let unit = syn::parse2(quote!(())).unwrap();
    let mut report = Vec::new();
    for variant in variants {
        match &variant.fields {
            syn::Fields::Named(_) => {
                panic!("stabby does not support named fields in enum variants")
            }
            syn::Fields::Unnamed(f) => {
                assert_eq!(
                    f.unnamed.len(),
                    1,
                    "stabby only supports one field per enum variant"
                );
                has_non_empty_fields = true;
                let f = f.unnamed.first().unwrap();
                let ty = &f.ty;
                layout = quote!(#st::Union<#layout, core::mem::ManuallyDrop<#ty>>);
                report.push((variant.ident.to_string(), ty));
            }
            syn::Fields::Unit => {
                report.push((variant.ident.to_string(), &unit));
            }
        }
    }
    let report = crate::report(&report);
    let repr = match repr {
        None | Some(Repr::Stabby) => {
            if !has_non_empty_fields {
                panic!("Your enum doesn't have any field with values: use #[repr(C)] or #[repr(u*)] instead")
            }
            return repr_stabby(
                &new_attrs,
                &vis,
                &ident,
                &generics,
                data,
                report,
                repr.is_none(),
            );
        }
        Some(Repr::C) => "u8",
        Some(Repr::U8) => "u8",
        Some(Repr::U16) => "u16",
        Some(Repr::U32) => "u32",
        Some(Repr::U64) => "u64",
        Some(Repr::Usize) => "usize",
        Some(Repr::I8) => "i8",
        Some(Repr::I16) => "i16",
        Some(Repr::I32) => "i32",
        Some(Repr::I64) => "i64",
        Some(Repr::Isize) => "isize",
    };
    let reprid = quote::format_ident!("{}", repr);
    layout = quote!(#st::Tuple<#reprid, #layout>);
    let sident = format!("{ident}");
    let (report, report_bounds) = report;
    quote! {
        #(#new_attrs)*
        #[repr(#reprid)]
        #vis enum #ident #generics {
            #variants
        }

        #[automatically_derived]
        unsafe impl #generics #st::IStable for #ident <#unbound_generics> where #report_bounds #layout: #st::IStable {
            type ForbiddenValues = <#layout as #st::IStable>::ForbiddenValues;
            type UnusedBits =<#layout as #st::IStable>::UnusedBits;
            type Size = <#layout as #st::IStable>::Size;
            type Align = <#layout as #st::IStable>::Align;
            type HasExactlyOneNiche = #st::B0;
            type ContainsIndirections = <#layout as #st::IStable>::ContainsIndirections;
            const REPORT: &'static #st::report::TypeReport = & #st::report::TypeReport {
                name: #st::str::Str::new(#sident),
                module: #st::str::Str::new(core::module_path!()),
                fields: unsafe {#st::StableLike::new(#report)},
                version: 0,
                tyty: #st::report::TyTy::Enum(#st::str::Str::new(#repr)),
            };
            const ID: u64 = #st::report::gen_id(Self::REPORT);
        }
    }
}

struct Variant {
    ident: Ident,
    field: Option<syn::Field>,
    attrs: Vec<Attribute>,
}
impl From<&syn::Variant> for Variant {
    fn from(value: &syn::Variant) -> Self {
        let syn::Variant {
            ident,
            fields,
            discriminant: None,
            attrs,
            ..
        } = value.clone()
        else {
            panic!("#[repr(stabby)] enums do not support explicit discriminants")
        };
        let field = match fields {
            syn::Fields::Unit => None,
            syn::Fields::Unnamed(mut f) => {
                let field = f.unnamed.pop().map(|f| f.into_value());
                assert!(f.unnamed.is_empty());
                field
            }
            syn::Fields::Named(_) => unreachable!(),
        };
        Variant {
            ident,
            field,
            attrs,
        }
    }
}
struct Variants {
    variants: Vec<Variant>,
}
impl Deref for Variants {
    type Target = Vec<Variant>;
    fn deref(&self) -> &Self::Target {
        &self.variants
    }
}
impl<'a> FromIterator<&'a syn::Variant> for Variants {
    fn from_iter<T: IntoIterator<Item = &'a syn::Variant>>(iter: T) -> Self {
        Self {
            variants: Vec::from_iter(iter.into_iter().map(Into::into)),
        }
    }
}
impl Variants {
    fn recursion<'a, U, LeafFn: FnMut(&'a Variant) -> U, JoinFn: FnMut(U, U) -> U>(
        variants: &'a [Variant],
        leaf: &mut LeafFn,
        join: &mut JoinFn,
    ) -> U {
        if variants.len() > 1 {
            let (left, right) = variants.split_at(variants.len() / 2);
            let left = Self::recursion(left, leaf, join);
            let right = Self::recursion(right, leaf, join);
            join(left, right)
        } else {
            leaf(&variants[0])
        }
    }
    fn map<'a, U, LeafFn: FnMut(&'a Variant) -> U, JoinFn: FnMut(U, U) -> U>(
        &'a self,
        mut leaf: LeafFn,
        mut join: JoinFn,
    ) -> U {
        Self::recursion(&self.variants, &mut leaf, &mut join)
    }
    fn map_with_finalizer<
        'a,
        U,
        V,
        LeafFn: FnMut(&'a Variant) -> U,
        JoinFn: FnMut(U, U) -> U,
        FinalJoinFn: FnOnce(U, U) -> V,
    >(
        &'a self,
        mut leaf: LeafFn,
        mut join: JoinFn,
        final_join: FinalJoinFn,
    ) -> V {
        let (left, right) = self.variants.split_at(self.variants.len() / 2);
        let left = Self::recursion(left, &mut leaf, &mut join);
        let right = Self::recursion(right, &mut leaf, &mut join);
        final_join(left, right)
    }
}

pub fn repr_stabby(
    attrs: &Vec<Attribute>,
    vis: &Visibility,
    ident: &Ident,
    generics: &Generics,
    data: DataEnum,
    report: (TokenStream, TokenStream),
    check: bool,
) -> TokenStream {
    let st = crate::tl_mod();
    let unbound_generics = crate::utils::unbound_generics(&generics.params);
    let generics_without_defaults = crate::utils::generics_without_defaults(&generics.params);
    let data_variants = data.variants;
    if data_variants.len() < 2 {
        panic!("#[repr(stabby)] doesn't support single-member enums");
    }
    let variants = data_variants.iter().collect::<Variants>();
    let vty = variants
        .iter()
        .map(|v| v.field.as_ref().map(|f| &f.ty))
        .collect::<Vec<_>>();
    let vtyref = vty
        .iter()
        .map(|v| v.map(|ty| quote!(&'st_lt #ty)))
        .collect::<Vec<_>>();
    let vtymut = vty
        .iter()
        .map(|v| v.map(|ty| quote!(&'st_lt mut #ty)))
        .collect::<Vec<_>>();
    let vid = variants.iter().map(|v| &v.ident).collect::<Vec<_>>();
    let vattrs = variants.iter().map(|v| &v.attrs);
    let fnvid = vid
        .iter()
        .map(|i| quote::format_ident!("{i}Fn"))
        .collect::<Vec<_>>();
    let (result, bounds) = variants.map(
        |Variant { field, .. }| match field.as_ref() {
            Some(syn::Field { ty, .. }) => (quote!(#ty), quote!()),
            None => (quote!(()), quote!()),
        },
        |(aty, abound), (bty, bbound)| {
            (
                quote!(#st::Result<#aty, #bty>),
                quote!(#aty: #st::IDeterminantProvider<#bty>, #bty: #st::IStable, #abound #bbound),
            )
        },
    );
    let mut cparams = Vec::new();
    let constructors = variants.map(
        |v| {
            let ovid = match &v.field {
                Some(syn::Field { ty, .. }) => {
                    cparams.push(quote!(value: #ty));
                    quote!(value)
                }
                None => {
                    cparams.push(quote!());
                    quote!(())
                }
            };
            vec![ovid]
        },
        |a, b| {
            let mut r = Vec::with_capacity(a.len() + b.len());
            for v in a {
                r.push(quote!(#st::Result::Ok(#v)))
            }
            for v in b {
                r.push(quote!(#st::Result::Err(#v)))
            }
            r
        },
    );
    let matcher = |matcher| {
        variants.map_with_finalizer(
            |Variant { ident, field, .. }| match field {
                Some(_) => quote!(#ident),
                None => quote!(|_| #ident()),
            },
            |a, b| quote!(move |this| this.#matcher(#a, #b)),
            |a, b| quote!(self.0.#matcher(#a, #b)),
        )
    };
    let matcher_ctx = |matcher| {
        variants.map_with_finalizer(
            |Variant { ident, field, .. }| match field {
                Some(_) => quote!(#ident),
                None => quote!(|stabby_ctx, _| #ident(stabby_ctx)),
            },
            |a, b| quote!(move |stabby_ctx, this| this.#matcher(stabby_ctx, #a, #b)),
            |a, b| quote!(self.0.#matcher(stabby_ctx, #a, #b)),
        )
    };
    let owned_matcher = matcher(quote!(match_owned));
    let ref_matcher = matcher(quote!(match_ref));
    let mut_matcher = matcher(quote!(match_mut));
    let owned_matcher_ctx = matcher_ctx(quote!(match_owned_ctx));
    let ref_matcher_ctx = matcher_ctx(quote!(match_ref_ctx));
    let mut_matcher_ctx = matcher_ctx(quote!(match_mut_ctx));
    let layout = &result;

    let bounds2 = generics.where_clause.as_ref().map(|c| &c.predicates);
    let bounds = quote!(#bounds #bounds2);

    let sident = format!("{ident}");
    let (report, report_bounds) = report;
    let enum_as_struct = quote! {
        #(#attrs)*
        #vis struct #ident #generics (#result) where #report_bounds #bounds;
    };
    let check = check.then(|| {
        let opt_id = quote::format_ident!("ReprCLayoutFor{ident}");
        let optdoc = format!("Returns true if the layout for [`{ident}`] is smaller than what `#[repr(C)]` would have generated for it.");
        quote! {
            #[allow(dead_code)]
            #[repr(u8)]
            enum #opt_id <#generics_without_defaults> where #bounds {
                #data_variants
            }
            impl<#generics_without_defaults> #ident <#unbound_generics> where #report_bounds #bounds #layout: #st::IStable  {
                #[doc = #optdoc]
                pub const fn has_optimal_layout() -> bool {
                    core::mem::size_of::<Self>() < core::mem::size_of::<#opt_id<#unbound_generics>>()
                }
            }
        }
    });
    let assertions= generics.params.is_empty().then(||{
        let check = check.is_some().then(||{
            let sub_optimal_message = format!(
                "{ident}'s layout is sub-optimal, reorder fields or use `#[repr(stabby)]` to silence this error."
            );
            quote!(
                if !<#ident>::has_optimal_layout() {
                    panic!(#sub_optimal_message)
                })
        });
        let size_bug = format!(
            "{ident}'s size was mis-evaluated by stabby, this is a definitely a bug and may cause UB, please fill an issue"
        );
        let align_bug = format!(
            "{ident}'s align was mis-evaluated by stabby, this is a definitely a bug and may cause UB, please fill an issue"
        );
        quote! {
            const _: () = {
                #check
                if core::mem::size_of::<#ident>() != <<#ident as #st::IStable>::Size as #st::Unsigned>::USIZE {
                    panic!(#size_bug)
                }
                if core::mem::align_of::<#ident>() != <<#ident as #st::IStable>::Align as #st::Unsigned>::USIZE {
                    panic!(#align_bug)
                }
            };
        }
    });
    quote! {
        #enum_as_struct
        #check
        #assertions
        #[automatically_derived]
        unsafe impl <#generics_without_defaults> #st::IStable for #ident < #unbound_generics > where #report_bounds #bounds #layout: #st::IStable {
            type ForbiddenValues = <#layout as #st::IStable>::ForbiddenValues;
            type UnusedBits =<#layout as #st::IStable>::UnusedBits;
            type Size = <#layout as #st::IStable>::Size;
            type Align = <#layout as #st::IStable>::Align;
            type HasExactlyOneNiche = #st::B0;
            type ContainsIndirections = <#layout as #st::IStable>::ContainsIndirections;
            const REPORT: &'static #st::report::TypeReport = & #st::report::TypeReport {
                name: #st::str::Str::new(#sident),
                module: #st::str::Str::new(core::module_path!()),
                fields: unsafe {#st::StableLike::new(#report)},
                version: 0,
                tyty: #st::report::TyTy::Enum(#st::str::Str::new("stabby")),
            };
            const ID: u64 = #st::report::gen_id(Self::REPORT);
        }
        #[automatically_derived]
        impl #generics #ident < #unbound_generics > where #report_bounds #bounds {
            #(
                #[allow(non_snake_case)]
                #(#vattrs)*
                pub fn #vid(#cparams) -> Self {
                    Self (#constructors)
                }
            )*
            #[allow(non_snake_case)]
            /// Equivalent to `match self`.
            pub fn match_owned<StabbyOut, #(#fnvid: FnOnce(#vty) -> StabbyOut,)*>(self, #(#vid: #fnvid,)*) -> StabbyOut {
                #owned_matcher
            }
            #[allow(non_snake_case)]
            /// Equivalent to `match &self`.
            pub fn match_ref<'st_lt, StabbyOut, #(#fnvid: FnOnce(#vtyref) -> StabbyOut,)*>(&'st_lt self, #(#vid: #fnvid,)*) -> StabbyOut {
                #ref_matcher
            }
            #[allow(non_snake_case)]
            /// Equivalent to `match &mut self`.
            pub fn match_mut<'st_lt, StabbyOut, #(#fnvid: FnOnce(#vtymut) -> StabbyOut,)*>(&'st_lt mut self, #(#vid: #fnvid,)*) -> StabbyOut {
                #mut_matcher
            }
            #[allow(non_snake_case)]
            /// Equivalent to `match self`, but allows you to pass common arguments to all closures to make the borrow checker happy.
            pub fn match_owned_ctx<StabbyOut, StabbyCtx, #(#fnvid: FnOnce(StabbyCtx, #vty) -> StabbyOut,)*>(self, stabby_ctx: StabbyCtx, #(#vid: #fnvid,)*) -> StabbyOut {
                #owned_matcher_ctx
            }
            #[allow(non_snake_case)]
            /// Equivalent to `match &self`, but allows you to pass common arguments to all closures to make the borrow checker happy.
            pub fn match_ref_ctx<'st_lt, StabbyCtx, StabbyOut, #(#fnvid: FnOnce(StabbyCtx, #vtyref) -> StabbyOut,)*>(&'st_lt self, stabby_ctx: StabbyCtx, #(#vid: #fnvid,)*) -> StabbyOut {
                #ref_matcher_ctx
            }
            #[allow(non_snake_case)]
            /// Equivalent to `match &mut self`, but allows you to pass common arguments to all closures to make the borrow checker happy.
            pub fn match_mut_ctx<'st_lt, StabbyCtx, StabbyOut, #(#fnvid: FnOnce(StabbyCtx, #vtymut) -> StabbyOut,)*>(&'st_lt mut self, stabby_ctx: StabbyCtx, #(#vid: #fnvid,)*) -> StabbyOut {
                #mut_matcher_ctx
            }
        }
    }
}