vorant_gen 0.2.0

A proc-macro library for generating state machines
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
use proc_macro::TokenStream;
use syn::{ItemFn, parse_macro_input};

#[proc_macro_attribute]
pub fn machine(attr: TokenStream, item: TokenStream) -> TokenStream {
    let input_fn = parse_macro_input!(item as ItemFn);

    match machine_fn::machine(attr.into(), input_fn) {
        Ok(output) => output.into(),
        Err(err) => err.to_compile_error().into(),
    }
}

mod loop_points;
mod machine_fn;
mod save;
mod yield_points;
mod if_points;

#[cfg(test)]
mod tests {
    use proc_macro2::TokenStream;
    use quote::quote;
    use syn::{ItemFn, parse_quote};

    #[test]
    fn get_balances_at() {
        let input: ItemFn = parse_quote!(
            fn get_latest_at(
                now: Timestamp,
            ) -> Result<(Picture, Timestamp), Error> {
                #[vorant::save { now: Timestamp }]
                let last: Option<(Picture, Timestamp, bool)> = yield now as Timestamp;

                let (picture, range) = match last {
                    Some((picture, created_at, true)) => (picture, GetRange::Since(created_at..)),
                    Some((picture, created_at, false)) => (picture, GetRange::Between(created_at..=now)),
                    None => (Default::default, GetRange::Until(..=now)),
                };

                #[vorant::save { now: Timestamp }]
                let result: <Accumulator as Machine>::Out =
                    yield (Accumulator { picture }, range) as (Accumulator, GetRange);

                let result = match result {
                    Err(e) => Err(e),
                    Ok(picture) => Ok((picture, now)),
                };

                result
            }
        );
        let attr: TokenStream = syn::parse_quote!(GetLatestAt);

        let output = super::machine_fn::machine(attr, input).unwrap();

        assert_eq!(
            output.to_string(),
            quote! {
                enum GetLatestAt {
                    Yield0(get_latest_at::Yield0, ()),
                    Yield1(get_latest_at::Yield1, Timestamp),
                    Yield2(get_latest_at::Yield2, (Accumulator, GetRange))
                }

                mod get_latest_at {
                    use super::*;

                    impl GetLatestAt {
                        pub fn new(now: Timestamp) -> Self {
                            return GetLatestAt::Yield0(Yield0 { now }, ());
                        }
                    }

                    impl ::vorant::Machine for GetLatestAt {
                        type Out = Result<(Picture, Timestamp), Error>;
                    }

                    pub struct Yield0 {
                        now: Timestamp
                    }

                    impl Yield0 {
                        pub fn offer(self, _: ()) -> ::vorant::Step<GetLatestAt> {
                            let Self { now } = self;
                            return ::vorant::Step::Yield(GetLatestAt::Yield1(Yield1 { now }, now));
                        }
                    }

                    pub struct Yield1 {
                        now: Timestamp
                    }

                    impl Yield1 {
                        pub fn offer(
                            self,
                            last: Option<(Picture, Timestamp, bool)>
                        ) -> ::vorant::Step<GetLatestAt> {
                            let Self { now } = self;

                            let (picture, range) = match last {
                                Some((picture, created_at, true)) => (picture, GetRange::Since(created_at..)),
                                Some((picture, created_at, false)) => (picture, GetRange::Between(created_at..=now)),
                                None => (Default::default, GetRange::Until(..=now)),
                            };

                            return ::vorant::Step::Yield(GetLatestAt::Yield2(
                                Yield2 { now },
                                (Accumulator { picture }, range)
                            ));
                        }
                    }

                    pub struct Yield2 {
                        now: Timestamp
                    }

                    impl Yield2 {
                        pub fn offer(self, result: <Accumulator as Machine>::Out) -> ::vorant::Step<GetLatestAt> {
                            let Self { now } = self;

                            let result = match result {
                                Err(e) => Err(e),
                                Ok(picture) => Ok((picture, now)),
                            };

                            return ::vorant::Step::End(result);
                        }
                    }
                }
            }.to_string()
        );
    }

    #[test]
    fn accumulator() {
        let input: ItemFn = parse_quote!(
            fn accumulator(picture: Picture) -> Result<Picture, Error> {
                #[vorant::save { picture: Picture }]
                loop {
                    #[vorant::save { mut picture: Picture }]
                    let next: Option<Block> = yield () as ();

                    let Some(block) = next else {
                        return Ok(picture);
                    };

                    picture = match picture.apply_many(block.operations.into_iter()) {
                        Ok(picture) => picture,
                        Err(e) => return Err(e),
                    };
                }
            }
        );
        let attr: TokenStream = syn::parse_quote!(Accumulator);

        let output = super::machine_fn::machine(attr, input).unwrap();

        assert_eq!(
            output.to_string(),
            quote! {
                enum Accumulator {
                    Yield0(accumulator::Yield0, ()),
                    Yield1(accumulator::Yield1, ())
                }

                mod accumulator {
                    use super::*;

                    impl Accumulator {
                        pub fn new(picture: Picture) -> Self {
                            return Accumulator::Yield0(Yield0 { picture }, ());
                        }
                    }

                    impl ::vorant::Machine for Accumulator {
                        type Out = Result<Picture, Error>;
                    }

                    pub struct Yield0 {
                        picture: Picture
                    }

                    impl Yield0 {
                        pub fn offer(self, _: ()) -> ::vorant::Step<Accumulator> {
                            let Self { picture } = self;
                            return Loop0 { picture }.offer_start();
                        }
                    }

                    pub struct Loop0 {
                        picture: Picture
                    }

                    impl Loop0 {
                        pub fn offer_start(self) -> ::vorant::Step<Accumulator> {
                            let Self { picture } = self;
                            return ::vorant::Step::Yield(Accumulator::Yield1(Yield1 { picture }, ()));
                        }
                    }

                    pub struct Yield1 {
                        picture: Picture
                    }

                    impl Yield1 {
                        pub fn offer(self, next: Option<Block>) -> ::vorant::Step<Accumulator> {
                            let Self { mut picture } = self;

                            let Some(block) = next else {
                                return ::vorant::Step::End(Ok(picture));
                            };

                            picture = match picture.apply_many(block.operations.into_iter()) {
                                Ok(picture) => picture,
                                Err(e) => return ::vorant::Step::End(Err(e)),
                            };

                            return Loop0 { picture }.offer_start();
                        }
                    }
                }
            }
            .to_string()
        );
    }

    #[test]
    fn insert_block_at() {
        let input: ItemFn = parse_quote!(
            fn insert_block_at(
                block: Block,
                now: Timestamp,
                step_size: usize,
            ) -> Result<(), Error> {
                #[vorant::save { block: Block, now: Timestamp, step_size: usize }]
                let out: <GetLatestAt as Machine>::Out =
                    yield GetLatestAt::new(now) as GetLatestAt;

                let (balances, blocks_count) = match out {
                    Ok((balances, blocks_count)) => (balances, blocks_count),
                    Err(e) => return Err(e),
                };

                let balances = match balances.apply_many(block.into_iter()) {
                    Ok(balances) => balances,
                    Err(e) => return Err(e),
                };

                #[vorant::save {}]
                let result: Result<BalanceSet, Error> = yield (
                    BlocksRebuilder::new(balances, step_size, blocks_count.unwrap_or(0)),
                    now..,
                )
                    as (BlocksRebuilder, RangeFrom<Timestamp>);

                let _ = result?;

                Ok(())
            }
        );
        let attr: TokenStream = syn::parse_quote!(InsertBlockAt);

        let output = super::machine_fn::machine(attr, input).unwrap();

        assert_eq!(
            output.to_string(),
            quote! {
                enum InsertBlockAt {
                    Yield0(insert_block_at::Yield0, ()),
                    Yield1(insert_block_at::Yield1, GetLatestAt),
                    Yield2(
                        insert_block_at::Yield2,
                        (BlocksRebuilder, RangeFrom<Timestamp>)
                    )
                }

                mod insert_block_at {
                    use super::*;

                    impl InsertBlockAt {
                        pub fn new(block: Block, now: Timestamp, step_size: usize) -> Self {
                            return InsertBlockAt::Yield0(Yield0 { block, now, step_size }, ());
                        }
                    }

                    impl ::vorant::Machine for InsertBlockAt {
                        type Out = Result<(), Error>;
                    }

                    pub struct Yield0 {
                        block: Block,
                        now: Timestamp,
                        step_size: usize
                    }

                    impl Yield0 {
                        pub fn offer(self, _: ()) -> ::vorant::Step<InsertBlockAt> {
                            let Self { block, now, step_size } = self;
                            return ::vorant::Step::Yield(InsertBlockAt::Yield1(Yield1 { block, now, step_size }, GetLatestAt::new(now)));
                        }
                    }

                    pub struct Yield1 {
                        block: Block,
                        now: Timestamp,
                        step_size: usize
                    }

                    impl Yield1 {
                        pub fn offer(self, out: <GetLatestAt as Machine>::Out) -> ::vorant::Step<InsertBlockAt> {
                            let Self { block, now, step_size } = self;
                            let (balances, blocks_count) = match out {
                                Ok((balances, blocks_count)) => (balances, blocks_count),
                                Err(e) => return ::vorant::Step::End(Err(e)),
                            };
                            let balances = match balances.apply_many(block.into_iter()) {
                                Ok(balances) => balances,
                                Err(e) => return ::vorant::Step::End(Err(e)),
                            };

                            return ::vorant::Step::Yield(InsertBlockAt::Yield2(Yield2 {}, (BlocksRebuilder::new(balances, step_size, blocks_count.unwrap_or(0)), now..,)));
                        }
                    }

                    pub struct Yield2 {}
                    impl Yield2 {
                        pub fn offer(self, result: Result<BalanceSet, Error>) -> ::vorant::Step<InsertBlockAt> {
                            let Self {} = self;
                            let _ = result?;

                            return ::vorant::Step::End(Ok(()));
                        }
                    }
                }
            }.to_string()
        );
    }

    #[test]
    fn blocks_rebuilder() {
        let input: ItemFn = parse_quote!(
            fn blocks_rebuilder(balances: Picture, step_size: usize) -> Result<(), Error> {
                let acc = Accumulator::new(balances);
                let mut i = 0;

                #[vorant::save { acc: Accumulator, step_size: usize, i: usize }]
                loop {
                    #[vorant::save { mut acc: Accumulator, step_size: usize, mut i: usize }]
                    let next: Option<(BlockId, Block)> = yield () as ();

                    let Some((id, block)) = next else {
                        return Ok(());
                    };

                    let Accumulator::Yield0(acc) = acc;

                    acc = match acc.offer(Some(block)) {
                        ::vorant::Step::End(out) => return out.map(|_| ()),
                        ::vorant::Step::Yield(acc) => acc,
                    };

                    i += 1;

                    #[vorant::save { acc: Accumulator, step_size: usize, i: usize }]
                    if i >= step_size {
                        total_blocks += i;

                        let snapshot = Snapshot {
                            balances: acc.balances,
                            blocks_count: total_blocks,
                            at_block_id: id,
                        };

                        #[vorant::save { step_size: usize }]
                        let balances: Picture = yield snapshot as Snapshot;

                        let i = 0;
                        let acc = Accumulator::new(balances);
                    }
                }
            }
        );
        let attr: TokenStream = syn::parse_quote!(BlocksRebuilder);

        let output = super::machine_fn::machine(attr, input).unwrap();

        assert_eq!(
            output.to_string(),
            quote! {
                enum BlocksRebuilder {
                    Yield0(blocks_rebuilder::Yield0, ()),
                    Yield1(blocks_rebuilder::Yield1, ()),
                    Yield2(blocks_rebuilder::Yield2, Snapshot)
                }

                mod blocks_rebuilder {
                    use super::*;

                    impl BlocksRebuilder {
                        pub fn new(balances: Picture, step_size: usize) -> Self {
                            return BlocksRebuilder::Yield0(Yield0 { balances, step_size }, ());
                        }
                    }

                    impl ::vorant::Machine for BlocksRebuilder {
                        type Out = Result<(), Error>;
                    }

                    pub struct Yield0 {
                        balances: Picture,
                        step_size: usize
                    }

                    impl Yield0 {
                        pub fn offer(self, _: ()) -> ::vorant::Step<BlocksRebuilder> {
                            let Self { balances, step_size } = self;

                            let acc = Accumulator::new(balances);
                            let mut i = 0;

                            return Loop0 { acc, step_size, i }.offer_start();
                        }
                    }

                    pub struct Loop0 {
                        acc: Accumulator,
                        step_size: usize,
                        i: usize
                    }

                    impl Loop0 {
                        pub fn offer_start(self) -> ::vorant::Step<BlocksRebuilder> {
                            let Self { acc, step_size, i } = self;

                            return ::vorant::Step::Yield(BlocksRebuilder::Yield1(
                                Yield1 { acc, step_size, i },
                                ()
                            ));
                        }
                    }

                    pub struct Yield1 {
                        acc: Accumulator,
                        step_size: usize,
                        i: usize
                    }

                    impl Yield1 {
                        pub fn offer(self, next: Option<(BlockId, Block)>) -> ::vorant::Step<BlocksRebuilder> {
                            let Self { mut acc, step_size, mut i } = self;

                            let Some((id, block)) = next else {
                                return ::vorant::Step::End(Ok(()));
                            };

                            let Accumulator::Yield0(acc) = acc;

                            acc = match acc.offer(Some(block)) {
                                ::vorant::Step::End(out) => return ::vorant::Step::End(out.map(|_| ())),
                                ::vorant::Step::Yield(acc) => acc,
                            };

                            i += 1;

                            if i >= step_size {
                                total_blocks += i;

                                let snapshot = Snapshot {
                                    balances: acc.balances,
                                    blocks_count: total_blocks,
                                    at_block_id: id,
                                };

                                return ::vorant::Step::Yield(BlocksRebuilder::Yield2(
                                    Yield2 { step_size },
                                    snapshot
                                ));
                            }

                            return If0 { acc, step_size, i }.offer_after();
                        }
                    }

                    pub struct If0 {
                        acc: Accumulator,
                        step_size: usize,
                        i: usize
                    }

                    pub struct Yield2 {
                        step_size: usize
                    }

                    impl Yield2 {
                        pub fn offer(self, balances: Picture) -> ::vorant::Step<BlocksRebuilder> {
                            let Self { step_size } = self;

                            let i = 0;
                            let acc = Accumulator::new(balances);

                            return If0 { acc, step_size, i }.offer_after();
                        }
                    }

                    impl If0 {
                        pub fn offer_after(self) -> ::vorant::Step<BlocksRebuilder> {
                            let Self { acc, step_size, i } = self;

                            return Loop0 { acc, step_size, i }.offer_start();
                        }
                    }
                }
            }.to_string()
        );
    }
}