byten_derive 0.0.13

Procedural macros for deriving binary codec traits (internal use by byten)
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
use proc_macro2::{Span, TokenStream};
use quote::quote;
use syn::{
    Attribute, Expr, Ident, Meta, Token, Type,
    parse::{ParseStream, Parser},
    parse_quote,
    spanned::Spanned,
    token::{Brace, Bracket, Paren},
};

use super::{BinarySchema, DecodeContext, EncodeContext, MeasureContext};

struct CodecSchema {
    expr: Expr,
}

impl BinarySchema for CodecSchema {
    fn decode(&self, ctx: &DecodeContext) -> syn::Result<proc_macro2::TokenStream> {
        let expr = &self.expr;
        let encoded = &ctx.encoded;
        let offset = &ctx.offset;
        Ok(quote! { ::byten::Decoder::decode(&#expr, #encoded, #offset)? })
    }

    fn encode(&self, ctx: &EncodeContext) -> syn::Result<proc_macro2::TokenStream> {
        let expr = &self.expr;
        let decoded = &ctx.decoded;
        let encoded = &ctx.encoded;
        let offset = &ctx.offset;
        Ok(quote! { ::byten::Encoder::encode(&#expr, #decoded, #encoded, #offset)? })
    }

    fn measure_fixed(&self) -> syn::Result<proc_macro2::TokenStream> {
        let expr = &self.expr;
        Ok(quote! { ::byten::FixedMeasurer::measure_fixed(&#expr) })
    }

    fn measure(&self, ctx: &MeasureContext) -> syn::Result<proc_macro2::TokenStream> {
        let expr = &self.expr;
        let decoded = &ctx.decoded;
        Ok(quote! { ::byten::Measurer::measure(&#expr, #decoded)? })
    }
}

trait Operand {
    fn span(&self) -> Span;
    fn codec(&self) -> Expr;
    fn typ(&self) -> syn::Result<Type> {
        Err(syn::Error::new(
            self.span(),
            "Operand does not support type extraction",
        ))
    }
}

struct DefaultOperand {
    span: Span,
}

impl Operand for DefaultOperand {
    fn span(&self) -> Span {
        self.span
    }

    fn codec(&self) -> Expr {
        parse_quote! { ::byten::DefaultCodec::default_codec() }
    }
}

struct TypeOperand {
    span: Span,
    typ: Type,
}

impl Operand for TypeOperand {
    fn span(&self) -> Span {
        self.span
    }

    fn codec(&self) -> Expr {
        let ty = &self.typ;
        parse_quote! { <#ty as ::byten::DefaultCodec>::default_codec() }
    }

    fn typ(&self) -> syn::Result<Type> {
        Ok(self.typ.clone())
    }
}

enum EndianOperand {
    Big(Span, Type),
    Little(Span, Type),
}

impl Operand for EndianOperand {
    fn span(&self) -> Span {
        match self {
            EndianOperand::Big(span, _) => *span,
            EndianOperand::Little(span, _) => *span,
        }
    }

    fn codec(&self) -> Expr {
        match self {
            EndianOperand::Big(_, ty) => {
                parse_quote! { ::byten::EndianCodec::<#ty>::new(::byten::Endianness::Big) }
            }
            EndianOperand::Little(_, ty) => {
                parse_quote! { ::byten::EndianCodec::<#ty>::new(::byten::Endianness::Little) }
            }
        }
    }
}

struct OwnOperand {
    span: Span,
    base: Box<dyn Operand>,
}

impl Operand for OwnOperand {
    fn span(&self) -> Span {
        self.span
    }

    fn codec(&self) -> Expr {
        let base = self.base.codec();
        parse_quote! { ::byten::OwnedCodec::new(#base) }
    }
}

struct OptOperand {
    span: Span,
    base: Box<dyn Operand>,
}

impl Operand for OptOperand {
    fn span(&self) -> Span {
        self.span
    }

    fn codec(&self) -> Expr {
        let base = self.base.codec();
        parse_quote! { ::byten::OptionCodec::new(#base) }
    }
}

struct UTF8Operand {
    span: Span,
    base: Box<dyn Operand>,
}

impl Operand for UTF8Operand {
    fn span(&self) -> Span {
        self.span
    }

    fn codec(&self) -> Expr {
        let base = self.base.codec();
        parse_quote! { ::byten::UTF8Codec::new(#base) }
    }
}

struct CodecOperand {
    span: Span,
    codec: Expr,
}

impl Operand for CodecOperand {
    fn span(&self) -> Span {
        self.span
    }

    fn codec(&self) -> Expr {
        self.codec.clone()
    }
}

struct UVarBEOperand {
    span: Span,
    typ: Type,
}

impl Operand for UVarBEOperand {
    fn span(&self) -> Span {
        self.span
    }

    fn codec(&self) -> Expr {
        let ty = &self.typ;
        parse_quote! { ::byten::UVarBECodec::<#ty>::new() }
    }
}

struct BytesOperand {
    span: Span,
    length: Box<dyn Operand>,
}

impl Operand for BytesOperand {
    fn span(&self) -> Span {
        self.span
    }

    fn codec(&self) -> Expr {
        let length_codec = self.length.codec();
        parse_quote! { ::byten::BytesCodec::new(#length_codec) }
    }
}

struct RemainingOperand {
    span: Span,
}

impl Operand for RemainingOperand {
    fn span(&self) -> Span {
        self.span
    }
    fn codec(&self) -> Expr {
        parse_quote! { ::byten::RemainingCodec::new() }
    }
}

struct ArrOperand {
    span: Span,
    item: Box<dyn Operand>,
}

impl Operand for ArrOperand {
    fn span(&self) -> Span {
        self.span
    }

    fn codec(&self) -> Expr {
        let item_codec = self.item.codec();
        parse_quote! { ::byten::ArrayCodec::new(#item_codec) }
    }
}

struct PhantomOperand {
    span: Span,
    value: Expr,
}

impl Operand for PhantomOperand {
    fn span(&self) -> Span {
        self.span
    }

    fn codec(&self) -> Expr {
        let value = &self.value;
        parse_quote! { ::byten::PhantomCodec::new(#value) }
    }
}

struct BoxOperand {
    span: Span,
    base: Box<dyn Operand>,
}

impl Operand for BoxOperand {
    fn span(&self) -> Span {
        self.span
    }

    fn codec(&self) -> Expr {
        let base = self.base.codec();
        parse_quote! { ::byten::BoxCodec::new(#base) }
    }
}

struct ForOperand {
    span: Span,
    item: Box<dyn Operand>,
    length: Box<dyn Operand>,
}

impl Operand for ForOperand {
    fn span(&self) -> Span {
        self.span
    }

    fn codec(&self) -> Expr {
        let item_codec = self.item.codec();
        let length_codec = self.length.codec();
        parse_quote! { ::byten::PrefixedCodec::new(#length_codec, #item_codec) }
    }
}

struct TupleOperand {
    span: Span,
    items: Vec<Box<dyn Operand>>,
}

impl Operand for TupleOperand {
    fn span(&self) -> Span {
        self.span
    }

    fn codec(&self) -> Expr {
        let item_codecs: Vec<Expr> = self.items.iter().map(|item| item.codec()).collect();
        let codec_name = Ident::new(&format!("Tuple{}Codec", item_codecs.len()), self.span);
        parse_quote! { ::byten::#codec_name::new( #( #item_codecs ),* ) }
    }
}

pub fn build_codec_expr(tokens: TokenStream) -> syn::Result<Expr> {
    let span = tokens.span();
    let operand = Parser::parse2(
        move |stream: ParseStream<'_>| {
            build_codec_pipeline(stream, Box::new(DefaultOperand { span }))
        },
        tokens,
    )?;

    Ok(operand.codec())
}

pub fn build_codec_schema(
    attr: &Vec<Attribute>,
    typ: Option<&Type>,
) -> syn::Result<Box<dyn BinarySchema>> {
    let mut operand: Box<dyn Operand> = match typ {
        Some(typ) => Box::new(TypeOperand {
            span: typ.span(),
            typ: typ.clone(),
        }),
        None => Box::new(DefaultOperand {
            span: Span::call_site(),
        }),
    };

    for attribute in attr {
        if !attribute.path().is_ident("byten") {
            continue;
        }
        match &attribute.meta {
            Meta::List(meta) => {
                let tokens = meta.tokens.clone();
                operand = Parser::parse2(
                    move |stream: ParseStream<'_>| build_codec_pipeline(stream, operand),
                    tokens,
                )?;
            }
            _ => {
                return Err(syn::Error::new(
                    attribute.span(),
                    "Invalid byten attribute format",
                ));
            }
        }
    }

    Ok(Box::new(CodecSchema {
        expr: operand.codec(),
    }))
}

fn build_codec_pipeline(
    stream: ParseStream,
    mut operand: Box<dyn Operand>,
) -> Result<Box<dyn Operand>, syn::Error> {
    loop {
        operand = build_codec(stream, operand)?;
        if stream.is_empty() || stream.peek(Token![,]) {
            break Ok(operand);
        }
    }
}

fn build_codec(
    stream: ParseStream,
    operand: Box<dyn Operand>,
) -> Result<Box<dyn Operand>, syn::Error> {
    if stream.peek(Paren) {
        let content;
        syn::parenthesized!(content in stream);
        let operands = content.parse_terminated(
            |s: ParseStream<'_>| {
                build_codec_pipeline(s, Box::new(DefaultOperand { span: s.span() }))
            },
            Token![,],
        )?;
        if operands.len() == 1 && !operands.trailing_punct() {
            return Err(syn::Error::new(
                content.span(),
                "Single element tuples require a trailing comma.",
            ));
        }
        let items: Vec<Box<dyn Operand>> = operands.into_iter().collect();
        return Ok(Box::new(TupleOperand {
            span: content.span(),
            items,
        }));
    }

    if stream.peek(Brace) {
        let content;
        syn::braced!(content in stream);
        let expr: Expr = content.parse()?;
        return Ok(Box::new(CodecOperand {
            span: content.span(),
            codec: expr,
        }));
    }

    if stream.peek(Bracket) {
        let content;
        syn::bracketed!(content in stream);
        if !content.is_empty() {
            return Err(syn::Error::new(
                content.span(),
                "Array codec does not support length specification here. Consider using 'for' modifier.",
            ));
        }
        return Ok(Box::new(ArrOperand {
            span: content.span(),
            item: operand,
        }));
    }

    if stream.peek(Token![..]) {
        let _dots: Token![..] = stream.parse()?;
        return Ok(Box::new(RemainingOperand { span: _dots.span() }));
    }

    if stream.peek(Token![=]) {
        let eq_token: Token![=] = stream.parse()?;
        let value: Expr = stream.parse()?;
        return Ok(Box::new(PhantomOperand {
            span: eq_token.span(),
            value,
        }));
    }

    if stream.peek(Token![box]) {
        let box_token: Token![box] = stream.parse()?;
        return Ok(Box::new(BoxOperand {
            span: box_token.span(),
            base: operand,
        }));
    }

    if stream.peek(Token![?]) {
        let opt_token: Token![?] = stream.parse()?;
        return Ok(Box::new(OptOperand {
            span: opt_token.span(),
            base: operand,
        }));
    }

    if stream.peek(Token![for]) {
        let for_token: Token![for] = stream.parse()?;
        let content;
        syn::bracketed!(content in stream);
        let length = build_codec_pipeline(
            &content,
            Box::new(DefaultOperand {
                span: for_token.span(),
            }),
        )?;
        return Ok(Box::new(ForOperand {
            span: for_token.span(),
            item: operand,
            length,
        }));
    }

    if stream.peek(Token![$]) {
        let _dollar: Token![$] = stream.parse()?;
        let ident: Ident = stream.parse()?;
        return match ident.to_string().as_str() {
            "own" => Ok(Box::new(OwnOperand {
                span: ident.span(),
                base: operand,
            })),
            "be" => Ok(Box::new(EndianOperand::Big(ident.span(), operand.typ()?))),
            "le" => Ok(Box::new(EndianOperand::Little(
                ident.span(),
                operand.typ()?,
            ))),
            "uvarbe" => Ok(Box::new(UVarBEOperand {
                span: ident.span(),
                typ: operand.typ()?,
            })),
            "bytes" => {
                let content;
                syn::bracketed!(content in stream);
                let length = build_codec_pipeline(
                    &content,
                    Box::new(DefaultOperand { span: ident.span() }),
                )?;
                Ok(Box::new(BytesOperand {
                    span: ident.span(),
                    length,
                }))
            }
            "utf8" => Ok(Box::new(UTF8Operand {
                span: ident.span(),
                base: operand,
            })),
            _ => Err(syn::Error::new(
                ident.span(),
                format!("Unknown codec modifier: {}", ident),
            )),
        };
    }

    let typ: Type = stream.parse()?;
    Ok(Box::new(TypeOperand {
        span: stream.span(),
        typ,
    }))
}