rkyv_derive 0.8.16

Derive macro for rkyv
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
use proc_macro2::{Span, TokenStream, TokenTree};
use quote::{quote, ToTokens};
use syn::{
    meta::ParseNestedMeta, parenthesized, parse::Parse, parse_quote,
    punctuated::Punctuated, DeriveInput, Error, Field, Fields, Ident, Meta,
    Path, Token, Type, Variant, WherePredicate,
};

fn try_set_attribute<T: ToTokens>(
    attribute: &mut Option<T>,
    value: T,
    name: &'static str,
) -> Result<(), Error> {
    if attribute.is_none() {
        *attribute = Some(value);
        Ok(())
    } else {
        Err(Error::new_spanned(
            value,
            format!("{name} already specified"),
        ))
    }
}

#[derive(Default)]
pub struct Attributes {
    pub as_type: Option<Type>,
    pub archived: Option<Ident>,
    pub resolver: Option<Ident>,
    pub remote: Option<Path>,
    pub metas: Vec<Meta>,
    pub compares: Option<Punctuated<Path, Token![,]>>,
    pub archive_bounds: Option<Punctuated<WherePredicate, Token![,]>>,
    pub serialize_bounds: Option<Punctuated<WherePredicate, Token![,]>>,
    pub deserialize_bounds: Option<Punctuated<WherePredicate, Token![,]>>,
    pub bytecheck: Option<TokenStream>,
    pub crate_path: Option<Path>,
}

impl Attributes {
    fn parse_meta(&mut self, meta: ParseNestedMeta<'_>) -> Result<(), Error> {
        if meta.path.is_ident("bytecheck") {
            let tokens = meta.input.step(|cursor| {
                if let Some((TokenTree::Group(group), rest)) =
                    cursor.token_tree()
                {
                    Ok((group.stream(), rest))
                } else {
                    Err(cursor.error("expected bytecheck attributes"))
                }
            })?;

            if cfg!(feature = "bytecheck") {
                try_set_attribute(&mut self.bytecheck, tokens, "bytecheck")?;
            }

            Ok(())
        } else if meta.path.is_ident("compare") {
            let traits;
            parenthesized!(traits in meta.input);
            let traits = traits.parse_terminated(Path::parse, Token![,])?;
            try_set_attribute(&mut self.compares, traits, "compare")
        } else if meta.path.is_ident("archive_bounds") {
            let bounds;
            parenthesized!(bounds in meta.input);
            let clauses =
                bounds.parse_terminated(WherePredicate::parse, Token![,])?;
            try_set_attribute(
                &mut self.archive_bounds,
                clauses,
                "archive_bounds",
            )
        } else if meta.path.is_ident("serialize_bounds") {
            let bounds;
            parenthesized!(bounds in meta.input);
            let clauses =
                bounds.parse_terminated(WherePredicate::parse, Token![,])?;
            try_set_attribute(
                &mut self.serialize_bounds,
                clauses,
                "serialize_bounds",
            )
        } else if meta.path.is_ident("deserialize_bounds") {
            let bounds;
            parenthesized!(bounds in meta.input);
            let clauses =
                bounds.parse_terminated(WherePredicate::parse, Token![,])?;
            try_set_attribute(
                &mut self.deserialize_bounds,
                clauses,
                "deserialize_bounds",
            )
        } else if meta.path.is_ident("archived") {
            try_set_attribute(
                &mut self.archived,
                meta.value()?.parse()?,
                "archived",
            )
        } else if meta.path.is_ident("resolver") {
            try_set_attribute(
                &mut self.resolver,
                meta.value()?.parse()?,
                "resolver",
            )
        } else if meta.path.is_ident("as") {
            meta.input.parse::<Token![=]>()?;
            try_set_attribute(
                &mut self.as_type,
                meta.input.parse::<Type>()?,
                "as",
            )
        } else if meta.path.is_ident("crate") {
            if meta.input.parse::<Token![=]>().is_ok() {
                let path = meta.input.parse::<Path>()?;
                try_set_attribute(&mut self.crate_path, path, "crate")
            } else if meta.input.is_empty() || meta.input.peek(Token![,]) {
                try_set_attribute(
                    &mut self.crate_path,
                    parse_quote! { crate },
                    "crate",
                )
            } else {
                Err(meta.error("expected `crate` or `crate = ...`"))
            }
        } else if meta.path.is_ident("derive") {
            let metas;
            parenthesized!(metas in meta.input);
            self.metas.extend(
                metas
                    .parse_terminated(Meta::parse, Token![,])?
                    .into_iter()
                    .map(|meta| parse_quote! { derive(#meta) }),
            );
            Ok(())
        } else if meta.path.is_ident("attr") {
            let metas;
            parenthesized!(metas in meta.input);
            self.metas
                .extend(metas.parse_terminated(Meta::parse, Token![,])?);
            Ok(())
        } else if meta.path.is_ident("remote") {
            try_set_attribute(
                &mut self.remote,
                meta.value()?.parse()?,
                "remote",
            )
        } else {
            Err(meta.error("unrecognized rkyv argument"))
        }
    }

    pub fn parse(input: &DeriveInput) -> Result<Self, Error> {
        let mut result = Self::default();

        for attr in input.attrs.iter() {
            if attr.path().is_ident("rkyv") {
                attr.parse_nested_meta(|meta| result.parse_meta(meta))?;
            }
        }

        if result.as_type.is_some() {
            if let Some(ref ident) = result.archived {
                return Err(Error::new_spanned(
                    ident,
                    "`archived = ...` may not be used with `as = ...` because \
                     no type is generated",
                ));
            }

            if let Some(first) = result.metas.first() {
                return Err(Error::new_spanned(
                    first,
                    "attributes may not be used with `as = ...`; place \
                     attributes on the archived type instead",
                ));
            }

            if let Some(bytecheck) = &result.bytecheck {
                return Err(Error::new_spanned(
                    bytecheck,
                    "cannot generate a `CheckBytes` impl because `as = ...` \
                     does not generate an archived type",
                ));
            }
        }

        Ok(result)
    }

    pub fn crate_path(&self) -> Path {
        self.crate_path
            .clone()
            .unwrap_or_else(|| parse_quote! { ::rkyv })
    }
}

#[derive(Default)]
pub struct FieldAttributes {
    pub attrs: Punctuated<Meta, Token![,]>,
    pub omit_bounds: Option<Path>,
    pub with: Option<Type>,
    pub getter: Option<Path>,
    pub niches: Vec<Niche>,
}

impl FieldAttributes {
    fn parse_meta(&mut self, meta: ParseNestedMeta<'_>) -> Result<(), Error> {
        if meta.path.is_ident("attr") {
            let content;
            parenthesized!(content in meta.input);
            self.attrs = content.parse_terminated(Meta::parse, Token![,])?;
            Ok(())
        } else if meta.path.is_ident("omit_bounds") {
            self.omit_bounds = Some(meta.path);
            Ok(())
        } else if meta.path.is_ident("with") {
            meta.input.parse::<Token![=]>()?;
            self.with = Some(meta.input.parse::<Type>()?);
            Ok(())
        } else if meta.path.is_ident("getter") {
            meta.input.parse::<Token![=]>()?;
            self.getter = Some(meta.input.parse::<Path>()?);
            Ok(())
        } else if meta.path.is_ident("niche") {
            let niche = if meta.input.is_empty() {
                Niche::Default
            } else {
                meta.input.parse::<Token![=]>()?;

                Niche::Type(Box::new(meta.input.parse::<Type>()?))
            };

            self.niches.push(niche);

            Ok(())
        } else {
            Err(meta.error("unrecognized rkyv arguments"))
        }
    }

    pub fn parse(
        attributes: &Attributes,
        input: &Field,
    ) -> Result<Self, Error> {
        let mut result = Self::default();

        for attr in input.attrs.iter() {
            if attr.path().is_ident("rkyv") {
                attr.parse_nested_meta(|meta| result.parse_meta(meta))?;
            }
        }

        if result.getter.is_some() && attributes.remote.is_none() {
            return Err(Error::new_spanned(
                result.getter,
                "getters may only be used with remote derive",
            ));
        }

        Ok(result)
    }

    pub fn archive_bound(
        &self,
        rkyv_path: &Path,
        field: &Field,
    ) -> Option<WherePredicate> {
        if self.omit_bounds.is_some() {
            return None;
        }

        let ty = &field.ty;
        if let Some(with) = &self.with {
            Some(parse_quote! {
                #with: #rkyv_path::with::ArchiveWith<#ty>
            })
        } else {
            Some(parse_quote! {
                #ty: #rkyv_path::Archive
            })
        }
    }

    pub fn serialize_bound(
        &self,
        rkyv_path: &Path,
        field: &Field,
    ) -> Option<WherePredicate> {
        if self.omit_bounds.is_some() {
            return None;
        }

        let ty = &field.ty;
        if let Some(with) = &self.with {
            Some(parse_quote! {
                #with: #rkyv_path::with::SerializeWith<#ty, __S>
            })
        } else {
            Some(parse_quote! {
                #ty: #rkyv_path::Serialize<__S>
            })
        }
    }

    pub fn deserialize_bound(
        &self,
        rkyv_path: &Path,
        field: &Field,
    ) -> Option<WherePredicate> {
        if self.omit_bounds.is_some() {
            return None;
        }

        let archived = self.archived(rkyv_path, field);

        let ty = &field.ty;
        if let Some(with) = &self.with {
            Some(parse_quote! {
                #with: #rkyv_path::with::DeserializeWith<#archived, #ty, __D>
            })
        } else {
            Some(parse_quote! {
                #archived: #rkyv_path::Deserialize<#ty, __D>
            })
        }
    }

    fn archive_item(
        &self,
        rkyv_path: &Path,
        field: &Field,
        name: &str,
        with_name: &str,
    ) -> TokenStream {
        let ty = &field.ty;
        if let Some(with) = &self.with {
            let ident = Ident::new(with_name, Span::call_site());
            quote! {
                <#with as #rkyv_path::with::ArchiveWith<#ty>>::#ident
            }
        } else {
            let ident = Ident::new(name, Span::call_site());
            quote! {
                <#ty as #rkyv_path::Archive>::#ident
            }
        }
    }

    pub fn archived(&self, rkyv_path: &Path, field: &Field) -> TokenStream {
        self.archive_item(rkyv_path, field, "Archived", "Archived")
    }

    pub fn resolver(&self, rkyv_path: &Path, field: &Field) -> TokenStream {
        self.archive_item(rkyv_path, field, "Resolver", "Resolver")
    }

    pub fn resolve(&self, rkyv_path: &Path, field: &Field) -> TokenStream {
        self.archive_item(rkyv_path, field, "resolve", "resolve_with")
    }

    pub fn serialize(&self, rkyv_path: &Path, field: &Field) -> TokenStream {
        let ty = &field.ty;
        if let Some(with) = &self.with {
            quote! {
                <
                    #with as #rkyv_path::with::SerializeWith<#ty, __S>
                >::serialize_with
            }
        } else {
            quote! {
                <#ty as #rkyv_path::Serialize<__S>>::serialize
            }
        }
    }

    pub fn deserialize(&self, rkyv_path: &Path, field: &Field) -> TokenStream {
        let ty = &field.ty;
        let archived = self.archived(rkyv_path, field);

        if let Some(with) = &self.with {
            quote! {
                <
                    #with as #rkyv_path::with::DeserializeWith<
                        #archived,
                        #ty,
                        __D,
                    >
                >::deserialize_with
            }
        } else {
            quote! {
                <#archived as #rkyv_path::Deserialize<#ty, __D>>::deserialize
            }
        }
    }

    pub fn access_field(
        &self,
        this: &Ident,
        member: &impl ToTokens,
    ) -> TokenStream {
        if let Some(ref getter) = self.getter {
            quote! { ::core::borrow::Borrow::borrow(&#getter(#this)) }
        } else {
            quote! { &#this.#member }
        }
    }

    pub fn metas(&self) -> TokenStream {
        let mut result = TokenStream::new();

        #[cfg(feature = "bytecheck")]
        if self.omit_bounds.is_some() {
            result.extend(quote! { #[bytecheck(omit_bounds)] });
        }

        for attr in self.attrs.iter() {
            result.extend(quote! { #[#attr] });
        }

        result
    }
}

#[derive(Default)]
pub struct VariantAttributes {
    pub other: Option<Path>,
}

impl VariantAttributes {
    fn parse_meta(&mut self, meta: ParseNestedMeta<'_>) -> Result<(), Error> {
        if meta.path.is_ident("other") {
            self.other = Some(meta.path);
            Ok(())
        } else {
            Err(meta.error("unrecognized rkyv arguments"))
        }
    }

    pub fn parse(
        attributes: &Attributes,
        input: &Variant,
    ) -> Result<Self, Error> {
        let mut result = Self::default();

        for attr in input.attrs.iter() {
            if attr.path().is_ident("rkyv") {
                attr.parse_nested_meta(|meta| result.parse_meta(meta))?;
            }
        }

        if result.other.is_some() {
            if attributes.remote.is_none() {
                return Err(Error::new_spanned(
                    result.other,
                    "`#[rkyv(other)]` may only be used with remote derive",
                ));
            } else if !matches!(input.fields, Fields::Unit) {
                return Err(Error::new_spanned(
                    result.other,
                    "`#[rkyv(other)]` may only be used on unit variants",
                ));
            }
        }

        Ok(result)
    }
}

pub enum Niche {
    Type(Box<Type>),
    Default,
}

impl Niche {
    pub fn to_tokens(&self, rkyv_path: &Path) -> TokenStream {
        match self {
            Niche::Type(ty) => quote!(#ty),
            Niche::Default => quote! {
                #rkyv_path::niche::niching::DefaultNiche
            },
        }
    }
}

impl PartialEq for Niche {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Niche::Type(ty1), Niche::Type(ty2)) => {
                if let (Type::Path(ty1), Type::Path(ty2)) = (&**ty1, &**ty2) {
                    ty1.path.get_ident() == ty2.path.get_ident()
                } else {
                    false
                }
            }
            (Niche::Type(ty), Niche::Default)
            | (Niche::Default, Niche::Type(ty)) => {
                if let Type::Path(ty) = &**ty {
                    match ty.path.get_ident() {
                        Some(ident) => ident == "DefaultNiche",
                        None => false,
                    }
                } else {
                    false
                }
            }
            (Niche::Default, Niche::Default) => true,
        }
    }
}