compactly-derive 0.1.7

Derive macros for compactly crate
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
use std::collections::{BTreeSet, HashMap};

use proc_macro2::{Ident, Span};
use quote::{quote, ToTokens};
use syn::{Attribute, GenericParam, TraitBound};
use synstructure::{BindingInfo, VariantInfo};

#[derive(Debug, Clone)]
struct EncodingStrategy(syn::Type);
impl EncodingStrategy {
    fn parse_attrs(attrs: &[Attribute]) -> Vec<EncodingStrategy> {
        attrs
            .iter()
            .filter_map(|a| {
                if a.path().is_ident("compactly") {
                    let strategy: syn::Type = a.parse_args().expect("Unrecognize strategy");
                    Some(EncodingStrategy(strategy))
                } else {
                    None
                }
            })
            .collect::<Vec<_>>()
    }
    fn parse(binding: &BindingInfo) -> Option<EncodingStrategy> {
        match Self::parse_attrs(&binding.ast().attrs).as_slice() {
            [] => None,
            [s] => Some(s.clone()),
            _ => panic!("Cannot support multiple encoding strategies: {binding:?}"),
        }
    }
}

pub(crate) fn derive_compactly(mut s: synstructure::Structure) -> proc_macro2::TokenStream {
    let mut bound_names = BTreeSet::new();
    s.binding_name(|field, i| {
        if let Some(name) = &field.ident {
            if bound_names.contains(name) {
                for i in 0..10_000 {
                    let ident = Ident::new(&format!("{name}_{i}"), Span::call_site());
                    if !bound_names.contains(&ident) {
                        bound_names.insert(ident.clone());
                        return ident;
                    }
                }
                panic!("compactly does not currently support types with more than 10k identical field names");
            } else {
                bound_names.insert(name.clone());
                name.clone()
            }
        } else {
            let ident = {
                let ident = Ident::new(&format!("__binding_{i}"), Span::call_site());
            if bound_names.contains(&ident){
                crate::get_unique_name(&bound_names, "__binding_", 10000)
            }
            else {
                ident
            }
        };
            assert!(!bound_names.contains(&ident));
            bound_names.insert(ident.clone());
            ident
        }
    });

    let encode_trait = syn::parse_str::<TraitBound>("Encode").unwrap();
    let (_impl_generics, _ty_generics, where_clause) = s.ast().generics.split_for_impl();
    let mut where_clause = where_clause.cloned();
    s.add_trait_bounds(
        &encode_trait,
        &mut where_clause,
        synstructure::AddBounds::Generics,
    );

    let context_types = s
        .ast()
        .generics
        .params
        .iter()
        .filter_map(|param| {
            if let GenericParam::Type(ty) = param {
                Some(ty.ident.clone())
            } else {
                None
            }
        })
        .collect::<Vec<_>>();
    let context_generics = if context_types.is_empty() {
        quote! {}
    } else {
        quote! { <#(#context_types: Encode),*> }
    };
    let context_generics_without_bound = if context_types.is_empty() {
        quote! {}
    } else {
        quote! { <#(#context_types),*> }
    };
    let mut binding_strategies: HashMap<Ident, Option<EncodingStrategy>> = HashMap::new();
    let mut strategies = Vec::new();
    for binding in s
        .variants()
        .iter()
        .flat_map(|variant| variant.bindings().iter())
    {
        let strategy = EncodingStrategy::parse(binding);
        strategies.push(strategy.clone());
        binding_strategies.insert(binding.binding.clone(), strategy);
    }
    let context = s
        .variants()
        .iter()
        .flat_map(|variant| variant.bindings().iter())
        .zip(strategies.iter().cloned())
        .map(|(binding, strategy)| {
            let ty = &binding.ast().ty;
            let name = &binding.binding;
            if let Some(strategy) = strategy {
                let strategy = strategy.0;
                quote! {
                    #name: <#strategy as EncodingStrategy<#ty>>::Context
                }
            } else {
                quote! {
                    #name: <#ty as Encode>::Context
                }
            }
        })
        .collect::<Vec<_>>();
    let bindings = s
        .variants()
        .iter()
        .flat_map(|variant| variant.bindings().iter().map(|binding| &binding.binding))
        .collect::<Vec<_>>();

    let encode_fields = s.each(|binding| {
        let ty = &binding.ast().ty;
        let binding = &binding.binding;
        if let Some(Some(strategy)) = binding_strategies.get(binding) {
            let strategy = &strategy.0;
            quote! {
                <#strategy as EncodingStrategy<#ty>>::encode(&#binding, writer, &mut ctx.#binding);
            }
        } else {
            quote! {
                #binding.encode(writer, &mut ctx.#binding);
            }
        }
    });
    let num_variants = s.variants().len();
    let discriminant_type = quote! { compactly::v2::ULessThan<#num_variants> };
    let get_discriminant = |variant: &VariantInfo| -> usize {
        s.variants()
            .iter()
            .enumerate()
            .find(|(_, v)| v.ast().ident == variant.ast().ident)
            .map(|x| x.0)
            .expect("bug: invalid variant")
    };
    let encode_discriminant = s.each_variant(|variant| {
        let discriminant = get_discriminant(variant);
        quote! {
            compactly::v2::ULessThan::<#num_variants>::new(#discriminant).encode(writer, &mut ctx.discriminant);
        }
    });

    let decode_variants = s
        .variants()
        .iter()
        .enumerate()
        .map(|(_, variant)| {
            let decoding = variant
                .bindings()
                .iter()
                .map(|binding| {
                    if let Some(Some(strategy)) = binding_strategies.get(&binding.binding) {
                        let strategy = &strategy.0;
                        let ty = &binding.ast().ty;
                        quote! {
                            <#strategy as EncodingStrategy<#ty>>::decode(reader, &mut ctx.#binding)?
                        }
                    } else {
                        quote! {
                            Encode::decode(reader, &mut ctx.#binding)?
                        }
                    }
                })
                .collect::<Vec<_>>();
            variant.construct(|_, i| decoding[i].clone())
        })
        .collect::<Vec<_>>();
    let discriminants = 0..s.variants().len();
    let decode = quote! {
        Ok(match usize::from(discriminant) {
            #(#discriminants => #decode_variants,)*
            _ => return Err(std::io::Error::other("This discriminant should be impossible"))
        })
    };

    let strategies_to_impl = EncodingStrategy::parse_attrs(&s.ast().attrs);
    let impl_strategies = if strategies_to_impl.is_empty() {
        Vec::new()
    } else {
        let typename = s.ast().ident.clone();
        assert_eq!(num_variants, 1, "Cannot derive strategy for an enum");
        let bindings = s.variants()[0].bindings();
        assert_eq!(
            bindings.len(),
            1,
            "Can only derive strategy for newtype structs"
        );
        let binding = &bindings[0];
        strategies_to_impl
        .into_iter()
        .map(|EncodingStrategy(strategy)| {
            let ty = binding.ast().ty.clone();
            let field_name = binding.ast().ident.as_ref().map(|i| i.to_token_stream()).unwrap_or(quote! {0});
            let decoded = s.variants()[0].construct(|_, _| quote! { <#strategy as EncodingStrategy<#ty>>::decode(reader, ctx)? });
            quote! {
                impl EncodingStrategy<#typename> for #strategy {
                    type Context = <#strategy as EncodingStrategy<#ty>>::Context;
                    fn encode<E: EntropyCoder>(value: &#typename, writer: &mut E, ctx: &mut Self::Context) {
                        <#strategy as EncodingStrategy<#ty>>::encode(&value.#field_name, writer, ctx)
                    }
                    fn decode<D: EntropyDecoder>(reader: &mut D, ctx: &mut Self::Context) -> Result<#typename, std::io::Error> {
                        Ok(#decoded)
                    }
                }
            }
        })
        .collect::<Vec<_>>()
    };

    s.gen_impl(quote! {
        extern crate compactly;
        use compactly::v2::{Encode, EncodingStrategy, EntropyCoder, EntropyDecoder};
        use compactly::{Small, LowCardinality, Decimal, Compressible, Incompressible, Mapping, Normal, Sorted, Values};

        pub struct DerivedContext #context_generics {
            discriminant: <#discriminant_type as Encode>::Context,
            #(#context,)*
        }
        impl #context_generics Default for DerivedContext #context_generics_without_bound {
            fn default() -> Self {
                Self {
                    discriminant: Default::default(),
                    #(#bindings: Default::default(),)*
                }
            }
        }
        impl #context_generics Clone for DerivedContext #context_generics_without_bound {
            fn clone(&self) -> Self {
                Self {
                    discriminant: self.discriminant.clone(),
                    #(#bindings: self.#bindings.clone(),)*
                }
            }
        }

        #(#impl_strategies)*

        gen impl Encode for @Self {
            #![allow(unused_variables,non_shorthand_field_patterns)]
            type Context = DerivedContext #context_generics_without_bound;
            fn encode<E: EntropyCoder>(&self, writer: &mut E, ctx: &mut Self::Context) {
                match self { #encode_discriminant }
                match self { #encode_fields }
            }
            fn decode<D: EntropyDecoder>(
                reader: &mut D,
                ctx: &mut Self::Context,
            ) -> Result<Self, std::io::Error> {
                let discriminant: #discriminant_type = Encode::decode(reader, &mut ctx.discriminant)?;
                #decode
            }
        }
    })
}

#[cfg(test)]
fn pretty(tokens: proc_macro2::TokenStream) -> String {
    if let Ok(syntax_tree) = syn::parse2::<syn::File>(tokens.clone()) {
        prettyplease::unparse(&syntax_tree)
    } else {
        tokens.to_string()
    }
}

#[test]
fn impl_two_strategies() {
    let di: syn::DeriveInput = syn::parse_quote! {
        #[compactly(Small)]
        #[compactly(Sorted)]
        pub struct NewType(u32);
    };
    let s = synstructure::Structure::new(&di);

    expect_test::expect![[r#"
        const _: () = {
            extern crate compactly;
            use compactly::v2::{Encode, EncodingStrategy, EntropyCoder, EntropyDecoder};
            use compactly::{
                Small, LowCardinality, Decimal, Compressible, Incompressible, Mapping, Normal,
                Sorted, Values,
            };
            pub struct DerivedContext {
                discriminant: <compactly::v2::ULessThan<1usize> as Encode>::Context,
                __binding_0: <u32 as Encode>::Context,
            }
            impl Default for DerivedContext {
                fn default() -> Self {
                    Self {
                        discriminant: Default::default(),
                        __binding_0: Default::default(),
                    }
                }
            }
            impl Clone for DerivedContext {
                fn clone(&self) -> Self {
                    Self {
                        discriminant: self.discriminant.clone(),
                        __binding_0: self.__binding_0.clone(),
                    }
                }
            }
            impl EncodingStrategy<NewType> for Small {
                type Context = <Small as EncodingStrategy<u32>>::Context;
                fn encode<E: EntropyCoder>(
                    value: &NewType,
                    writer: &mut E,
                    ctx: &mut Self::Context,
                ) {
                    <Small as EncodingStrategy<u32>>::encode(&value.0, writer, ctx)
                }
                fn decode<D: EntropyDecoder>(
                    reader: &mut D,
                    ctx: &mut Self::Context,
                ) -> Result<NewType, std::io::Error> {
                    Ok(NewType(<Small as EncodingStrategy<u32>>::decode(reader, ctx)?))
                }
            }
            impl EncodingStrategy<NewType> for Sorted {
                type Context = <Sorted as EncodingStrategy<u32>>::Context;
                fn encode<E: EntropyCoder>(
                    value: &NewType,
                    writer: &mut E,
                    ctx: &mut Self::Context,
                ) {
                    <Sorted as EncodingStrategy<u32>>::encode(&value.0, writer, ctx)
                }
                fn decode<D: EntropyDecoder>(
                    reader: &mut D,
                    ctx: &mut Self::Context,
                ) -> Result<NewType, std::io::Error> {
                    Ok(NewType(<Sorted as EncodingStrategy<u32>>::decode(reader, ctx)?))
                }
            }
            impl Encode for NewType {
                #![allow(unused_variables, non_shorthand_field_patterns)]
                type Context = DerivedContext;
                fn encode<E: EntropyCoder>(&self, writer: &mut E, ctx: &mut Self::Context) {
                    match self {
                        NewType(ref __binding_0) => {
                            compactly::v2::ULessThan::<1usize>::new(0usize)
                                .encode(writer, &mut ctx.discriminant);
                        }
                    }
                    match self {
                        NewType(ref __binding_0) => {
                            __binding_0.encode(writer, &mut ctx.__binding_0);
                        }
                    }
                }
                fn decode<D: EntropyDecoder>(
                    reader: &mut D,
                    ctx: &mut Self::Context,
                ) -> Result<Self, std::io::Error> {
                    let discriminant: compactly::v2::ULessThan<1usize> = Encode::decode(
                        reader,
                        &mut ctx.discriminant,
                    )?;
                    Ok(
                        match usize::from(discriminant) {
                            0usize => NewType(Encode::decode(reader, &mut ctx.__binding_0)?),
                            _ => {
                                return Err(
                                    std::io::Error::other(
                                        "This discriminant should be impossible",
                                    ),
                                );
                            }
                        },
                    )
                }
            }
        };
    "#]]
    .assert_eq(&pretty(derive_compactly(s)));
}

#[test]
fn impl_strategies() {
    let di: syn::DeriveInput = syn::parse_quote! {
        #[compactly(Sorted)]
        pub struct NewType(u32);
    };
    let s = synstructure::Structure::new(&di);

    expect_test::expect![[r#"
        const _: () = {
            extern crate compactly;
            use compactly::v2::{Encode, EncodingStrategy, EntropyCoder, EntropyDecoder};
            use compactly::{
                Small, LowCardinality, Decimal, Compressible, Incompressible, Mapping, Normal,
                Sorted, Values,
            };
            pub struct DerivedContext {
                discriminant: <compactly::v2::ULessThan<1usize> as Encode>::Context,
                __binding_0: <u32 as Encode>::Context,
            }
            impl Default for DerivedContext {
                fn default() -> Self {
                    Self {
                        discriminant: Default::default(),
                        __binding_0: Default::default(),
                    }
                }
            }
            impl Clone for DerivedContext {
                fn clone(&self) -> Self {
                    Self {
                        discriminant: self.discriminant.clone(),
                        __binding_0: self.__binding_0.clone(),
                    }
                }
            }
            impl EncodingStrategy<NewType> for Sorted {
                type Context = <Sorted as EncodingStrategy<u32>>::Context;
                fn encode<E: EntropyCoder>(
                    value: &NewType,
                    writer: &mut E,
                    ctx: &mut Self::Context,
                ) {
                    <Sorted as EncodingStrategy<u32>>::encode(&value.0, writer, ctx)
                }
                fn decode<D: EntropyDecoder>(
                    reader: &mut D,
                    ctx: &mut Self::Context,
                ) -> Result<NewType, std::io::Error> {
                    Ok(NewType(<Sorted as EncodingStrategy<u32>>::decode(reader, ctx)?))
                }
            }
            impl Encode for NewType {
                #![allow(unused_variables, non_shorthand_field_patterns)]
                type Context = DerivedContext;
                fn encode<E: EntropyCoder>(&self, writer: &mut E, ctx: &mut Self::Context) {
                    match self {
                        NewType(ref __binding_0) => {
                            compactly::v2::ULessThan::<1usize>::new(0usize)
                                .encode(writer, &mut ctx.discriminant);
                        }
                    }
                    match self {
                        NewType(ref __binding_0) => {
                            __binding_0.encode(writer, &mut ctx.__binding_0);
                        }
                    }
                }
                fn decode<D: EntropyDecoder>(
                    reader: &mut D,
                    ctx: &mut Self::Context,
                ) -> Result<Self, std::io::Error> {
                    let discriminant: compactly::v2::ULessThan<1usize> = Encode::decode(
                        reader,
                        &mut ctx.discriminant,
                    )?;
                    Ok(
                        match usize::from(discriminant) {
                            0usize => NewType(Encode::decode(reader, &mut ctx.__binding_0)?),
                            _ => {
                                return Err(
                                    std::io::Error::other(
                                        "This discriminant should be impossible",
                                    ),
                                );
                            }
                        },
                    )
                }
            }
        };
    "#]]
    .assert_eq(&pretty(derive_compactly(s)));
}

#[test]
fn impl_newtype() {
    let di: syn::DeriveInput = syn::parse_quote! {
        pub struct NewType(u32);
    };
    let s = synstructure::Structure::new(&di);

    expect_test::expect![[r#"
        const _: () = {
            extern crate compactly;
            use compactly::v2::{Encode, EncodingStrategy, EntropyCoder, EntropyDecoder};
            use compactly::{
                Small, LowCardinality, Decimal, Compressible, Incompressible, Mapping, Normal,
                Sorted, Values,
            };
            pub struct DerivedContext {
                discriminant: <compactly::v2::ULessThan<1usize> as Encode>::Context,
                __binding_0: <u32 as Encode>::Context,
            }
            impl Default for DerivedContext {
                fn default() -> Self {
                    Self {
                        discriminant: Default::default(),
                        __binding_0: Default::default(),
                    }
                }
            }
            impl Clone for DerivedContext {
                fn clone(&self) -> Self {
                    Self {
                        discriminant: self.discriminant.clone(),
                        __binding_0: self.__binding_0.clone(),
                    }
                }
            }
            impl Encode for NewType {
                #![allow(unused_variables, non_shorthand_field_patterns)]
                type Context = DerivedContext;
                fn encode<E: EntropyCoder>(&self, writer: &mut E, ctx: &mut Self::Context) {
                    match self {
                        NewType(ref __binding_0) => {
                            compactly::v2::ULessThan::<1usize>::new(0usize)
                                .encode(writer, &mut ctx.discriminant);
                        }
                    }
                    match self {
                        NewType(ref __binding_0) => {
                            __binding_0.encode(writer, &mut ctx.__binding_0);
                        }
                    }
                }
                fn decode<D: EntropyDecoder>(
                    reader: &mut D,
                    ctx: &mut Self::Context,
                ) -> Result<Self, std::io::Error> {
                    let discriminant: compactly::v2::ULessThan<1usize> = Encode::decode(
                        reader,
                        &mut ctx.discriminant,
                    )?;
                    Ok(
                        match usize::from(discriminant) {
                            0usize => NewType(Encode::decode(reader, &mut ctx.__binding_0)?),
                            _ => {
                                return Err(
                                    std::io::Error::other(
                                        "This discriminant should be impossible",
                                    ),
                                );
                            }
                        },
                    )
                }
            }
        };
    "#]]
    .assert_eq(&pretty(derive_compactly(s)));
}