beancount-parser-lima-python 0.9.0

Proof of concept Python bindings for beancount-parser-lima
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
use std::{cmp::Ordering, collections::HashMap};

use crate::types::*;
use beancount_parser_lima as lima;
use pyo3::{
    prelude::*,
    types::{PyDate, PyDateAccess, PyDict, PyList, PySet, PyString},
};
use string_interner::{symbol::SymbolU32, DefaultStringInterner, StringInterner, Symbol};
use strum::IntoEnumIterator;
use time::Date;

/// Convert from Rust to Python while interning strings, dates, Subaccount lists.
///
/// While PyO3 does seem to support string interning, there's a comment there that
/// every string interning request results in creation of a temporary Python String
/// object, which we choose to avoid.
pub(crate) struct Converter {
    string: StringFactory,
    date: DateFactory,
}

impl Converter {
    pub(crate) fn new() -> Self {
        Converter {
            string: StringFactory::new(),
            date: DateFactory::new(),
        }
    }

    pub(crate) fn directive(
        &mut self,
        py: Python<'_>,
        date: &Date,
        metadata: &lima::Metadata,
    ) -> PyResult<Directive> {
        Ok(Directive {
            date: self.date.create_or_reuse(py, date),
            metadata: self.metadata(py, metadata)?,
        })
    }

    pub(crate) fn transaction(
        &mut self,
        py: Python<'_>,
        date: &Date,
        metadata: &lima::Metadata,
        x: &lima::Transaction<'_>,
    ) -> PyResult<Py<PyAny>> {
        let flag = self.flag(py, x.flag().item());
        let payee = x
            .payee()
            .map(|payee| self.string.create_or_reuse(py, payee.item()));
        let narration = x
            .narration()
            .map(|narration| self.string.create_or_reuse(py, narration.item()));
        let postings = x
            .postings()
            .map(|p| self.posting(py, p))
            .collect::<PyResult<Vec<_>>>()?;

        Ok(Py::new(
            py,
            (
                Transaction {
                    flag,
                    payee,
                    narration,
                    postings,
                },
                self.directive(py, date, metadata)?,
            ),
        )?
        .into_any())
    }

    pub(crate) fn posting(&mut self, py: Python<'_>, x: &lima::Posting<'_>) -> PyResult<Posting> {
        let flag = x.flag().map(|flag| self.flag(py, flag.item()));
        let account = self.string.create_or_reuse(py, x.account().item().as_ref());
        let amount = x.amount().map(|amount| amount.value());
        let currency = x
            .currency()
            .map(|currency| self.string.create_or_reuse(py, currency.item().as_ref()));
        let cost_spec = x
            .cost_spec()
            .map(|cost_spec| self.cost_spec(py, cost_spec.item()));
        let price_annotation = x
            .price_annotation()
            .map(|price_annotation| self.price_spec(py, price_annotation.item()));
        let metadata = self.metadata(py, x.metadata())?;

        Ok(Posting {
            flag,
            account,
            amount,
            currency,
            cost_spec,
            price_annotation,
            metadata,
        })
    }

    pub(crate) fn price(
        &mut self,
        py: Python<'_>,
        date: &Date,
        metadata: &lima::Metadata,
        x: &lima::Price<'_>,
    ) -> PyResult<Py<PyAny>> {
        let currency = self
            .string
            .create_or_reuse(py, x.currency().item().as_ref());
        let amount = self.amount(py, x.amount().item());

        Ok(Py::new(
            py,
            (
                Price { currency, amount },
                self.directive(py, date, metadata)?,
            ),
        )?
        .into_any())
    }

    pub(crate) fn balance(
        &mut self,
        py: Python<'_>,
        date: &Date,
        metadata: &lima::Metadata,
        x: &lima::Balance<'_>,
    ) -> PyResult<Py<PyAny>> {
        let account = self.string.create_or_reuse(py, x.account().item().as_ref());
        let atol = self.amount_with_tolerance(py, x.atol());

        Ok(Py::new(
            py,
            (
                Balance { account, atol },
                self.directive(py, date, metadata)?,
            ),
        )?
        .into_any())
    }

    pub(crate) fn open(
        &mut self,
        py: Python<'_>,
        date: &Date,
        metadata: &lima::Metadata,
        x: &lima::Open<'_>,
    ) -> PyResult<Py<PyAny>> {
        let account = self.string.create_or_reuse(py, x.account().item().as_ref());

        let currencies = PyList::new(
            py,
            x.currencies()
                .map(|currency| self.string.create_or_reuse(py, currency.item().as_ref())),
        )?
        .into();

        let booking = x
            .booking()
            .map(|booking| self.string.create_or_reuse(py, booking.item().as_ref()));

        Ok(Py::new(
            py,
            (
                Open {
                    account,
                    currencies,
                    booking,
                },
                self.directive(py, date, metadata)?,
            ),
        )?
        .into_any())
    }

    pub(crate) fn close(
        &mut self,
        py: Python<'_>,
        date: &Date,
        metadata: &lima::Metadata,
        x: &lima::Close<'_>,
    ) -> PyResult<Py<PyAny>> {
        let account = self.string.create_or_reuse(py, x.account().item().as_ref());

        Ok(Py::new(py, (Close { account }, self.directive(py, date, metadata)?))?.into_any())
    }

    pub(crate) fn commodity(
        &mut self,
        py: Python<'_>,
        date: &Date,
        metadata: &lima::Metadata,
        x: &lima::Commodity<'_>,
    ) -> PyResult<Py<PyAny>> {
        let currency = self
            .string
            .create_or_reuse(py, x.currency().item().as_ref());

        Ok(Py::new(
            py,
            (Commodity { currency }, self.directive(py, date, metadata)?),
        )?
        .into_any())
    }

    pub(crate) fn pad(
        &mut self,
        py: Python<'_>,
        date: &Date,
        metadata: &lima::Metadata,
        x: &lima::Pad<'_>,
    ) -> PyResult<Py<PyAny>> {
        let account = self.string.create_or_reuse(py, x.account().item().as_ref());
        let source = self.string.create_or_reuse(py, x.source().item().as_ref());

        Ok(Py::new(
            py,
            (Pad { account, source }, self.directive(py, date, metadata)?),
        )?
        .into_any())
    }

    pub(crate) fn document(
        &mut self,
        py: Python<'_>,
        date: &Date,
        metadata: &lima::Metadata,
        x: &lima::Document<'_>,
    ) -> PyResult<Py<PyAny>> {
        let account = self.string.create_or_reuse(py, x.account().item().as_ref());
        let path = self.string.create_or_reuse(py, x.path().item().as_ref());

        Ok(Py::new(
            py,
            (
                Document { account, path },
                self.directive(py, date, metadata)?,
            ),
        )?
        .into_any())
    }

    pub(crate) fn note(
        &mut self,
        py: Python<'_>,
        date: &Date,
        metadata: &lima::Metadata,
        x: &lima::Note<'_>,
    ) -> PyResult<Py<PyAny>> {
        let account = self.string.create_or_reuse(py, x.account().item().as_ref());
        let comment = self.string.create_or_reuse(py, x.comment().item().as_ref());

        Ok(Py::new(
            py,
            (
                Note { account, comment },
                self.directive(py, date, metadata)?,
            ),
        )?
        .into_any())
    }

    pub(crate) fn event(
        &mut self,
        py: Python<'_>,
        date: &Date,
        metadata: &lima::Metadata,
        x: &lima::Event<'_>,
    ) -> PyResult<Py<PyAny>> {
        let event_type = self
            .string
            .create_or_reuse(py, x.event_type().item().as_ref());
        let description = self
            .string
            .create_or_reuse(py, x.description().item().as_ref());

        Ok(Py::new(
            py,
            (
                Event {
                    event_type,
                    description,
                },
                self.directive(py, date, metadata)?,
            ),
        )?
        .into_any())
    }

    pub(crate) fn query(
        &mut self,
        py: Python<'_>,
        date: &Date,
        metadata: &lima::Metadata,
        x: &lima::Query<'_>,
    ) -> PyResult<Py<PyAny>> {
        let name = self.string.create_or_reuse(py, x.name().item().as_ref());
        let content = self.string.create_or_reuse(py, x.content().item().as_ref());

        Ok(Py::new(
            py,
            (Query { name, content }, self.directive(py, date, metadata)?),
        )?
        .into_any())
    }

    pub(crate) fn metadata(
        &mut self,
        py: Python<'_>,
        x: &lima::Metadata<'_>,
    ) -> Result<Option<Metadata>, PyErr> {
        let key_values = x.key_values();
        let tags = x.tags();
        let links = x.links();

        if key_values.len() == 0 && tags.len() == 0 && links.len() == 0 {
            Ok(None)
        } else {
            let key_values = if key_values.len() == 0 {
                None
            } else {
                let key_value_dict = PyDict::new(py);
                for (k, v) in key_values {
                    key_value_dict.set_item(
                        self.string.create_or_reuse(py, k.item().as_ref()),
                        self.meta_value(py, v.item())?,
                    )?
                }
                Some(key_value_dict.into())
            };

            let tags = if tags.len() == 0 {
                None
            } else {
                Some(
                    PyList::new(
                        py,
                        tags.map(|tag| self.string.create_or_reuse(py, tag.item().as_ref())),
                    )?
                    .into(),
                )
            };

            let links = if links.len() == 0 {
                None
            } else {
                Some(
                    PyList::new(
                        py,
                        links.map(|link| self.string.create_or_reuse(py, link.item().as_ref())),
                    )?
                    .into(),
                )
            };

            Ok(Some(Metadata {
                key_values,
                tags,
                links,
            }))
        }
    }

    pub(crate) fn meta_value(
        &mut self,
        py: Python<'_>,
        x: &lima::MetaValue<'_>,
    ) -> PyResult<Py<PyAny>> {
        use lima::MetaValue::*;
        use lima::SimpleValue::*;

        let meta_value = MetaValue {};

        match x {
            Simple(String(x)) => {
                let value = self.string.create_or_reuse(py, x);
                Ok(Py::new(py, (MetaValueString { value }, meta_value))?.into_any())
            }

            Simple(Currency(x)) => {
                let value = self.string.create_or_reuse(py, x.as_ref());
                Ok(Py::new(py, (MetaValueCurrency { value }, meta_value))?.into_any())
            }

            Simple(Account(x)) => {
                let value = self.string.create_or_reuse(py, x.as_ref());
                Ok(Py::new(py, (MetaValueAccount { value }, meta_value))?.into_any())
            }

            Simple(Tag(x)) => {
                let value = self.string.create_or_reuse(py, x.as_ref());
                Ok(Py::new(py, (MetaValueTag { value }, meta_value))?.into_any())
            }

            Simple(Link(x)) => {
                let value = self.string.create_or_reuse(py, x.as_ref());
                Ok(Py::new(py, (MetaValueLink { value }, meta_value))?.into_any())
            }

            Simple(Date(x)) => {
                let value = self.date.create_or_reuse(py, x);
                Ok(Py::new(py, (MetaValueDate { value }, meta_value))?.into_any())
            }

            Simple(Bool(x)) => {
                let value = *x;
                Ok(Py::new(py, (MetaValueBool { value }, meta_value))?.into_any())
            }

            Simple(None) => Ok(Py::new(py, (MetaValueNone, meta_value))?.into_any()),

            Simple(Expr(x)) => {
                let value = x.value();
                Ok(Py::new(py, (MetaValueExpr { value }, meta_value))?.into_any())
            }

            Amount(x) => {
                let value = self.amount(py, x);
                Ok(Py::new(py, (MetaValueAmount { value }, meta_value))?.into_any())
            }
        }
    }

    pub(crate) fn flag(&mut self, py: Python<'_>, x: &lima::Flag) -> Py<PyString> {
        use lima::Flag::*;

        let mut buf = [0; 8]; // two unicode characters, more than we need for an ASCII flag mpoe.g. 'A
        let s = match x {
            Asterisk => '*'.encode_utf8(&mut buf),
            Exclamation => '*'.encode_utf8(&mut buf),
            Ampersand => '*'.encode_utf8(&mut buf),
            Hash => '*'.encode_utf8(&mut buf),
            Question => '*'.encode_utf8(&mut buf),
            Percent => '*'.encode_utf8(&mut buf),
            Letter(x) => {
                let quote_len = '\''.encode_utf8(&mut buf).len();
                let char_len = x.char().encode_utf8(&mut buf[quote_len..]).len();
                std::str::from_utf8(&buf[..quote_len + char_len]).unwrap()
            }
        };
        self.string.create_or_reuse(py, s)
    }

    pub(crate) fn amount(&mut self, py: Python<'_>, x: &lima::Amount) -> Amount {
        let number = x.number().item().value();
        let currency = self
            .string
            .create_or_reuse(py, x.currency().item().as_ref());
        Amount { number, currency }
    }

    pub(crate) fn amount_with_tolerance(
        &mut self,
        py: Python<'_>,
        x: &lima::AmountWithTolerance,
    ) -> AmountWithTolerance {
        let amount = self.amount(py, x.amount());
        let tolerance = x.tolerance().map(|tolerance| *tolerance.item());
        AmountWithTolerance { amount, tolerance }
    }

    pub(crate) fn cost_spec(&mut self, py: Python<'_>, x: &lima::CostSpec<'_>) -> CostSpec {
        let per_unit = x.per_unit().map(|per_unit| per_unit.item().value());
        let total = x.total().map(|total| total.item().value());
        let currency = x
            .currency()
            .map(|currency| self.string.create_or_reuse(py, currency.item().as_ref()));
        let date = x.date().map(|date| self.date.create_or_reuse(py, date));

        let label = x
            .label()
            .map(|label| self.string.create_or_reuse(py, label.item().as_ref()));
        let merge = x.merge();

        CostSpec {
            per_unit,
            total,
            currency,
            date,
            label,
            merge,
        }
    }

    pub(crate) fn price_spec(&mut self, py: Python<'_>, x: &lima::PriceSpec<'_>) -> PriceSpec {
        use lima::PriceSpec::*;
        use lima::ScopedExprValue::*;

        let per_unit = match x {
            BareAmount(PerUnit(expr)) => Some(expr.value()),
            CurrencyAmount(PerUnit(expr), _) => Some(expr.value()),
            _ => None,
        };

        let total = match x {
            BareAmount(Total(expr)) => Some(expr.value()),
            CurrencyAmount(Total(expr), _) => Some(expr.value()),
            _ => None,
        };

        let currency = match x {
            BareCurrency(currency) => Some(*currency),
            CurrencyAmount(_, currency) => Some(*currency),
            _ => None,
        }
        .map(|currency| self.string.create_or_reuse(py, currency.as_ref()));

        PriceSpec {
            per_unit,
            total,
            currency,
        }
    }

    pub(crate) fn options(&mut self, py: Python<'_>, x: &lima::Options<'_>) -> PyResult<Options> {
        let title = self.string.create_or_reuse(py, x.title());
        let account_previous_balances = self
            .string
            .create_or_reuse(py, x.account_previous_balances().as_ref());
        let account_previous_earnings = self
            .string
            .create_or_reuse(py, x.account_previous_earnings().as_ref());
        let account_previous_conversions = self
            .string
            .create_or_reuse(py, x.account_previous_conversions().as_ref());
        let account_current_earnings = self
            .string
            .create_or_reuse(py, x.account_current_earnings().as_ref());
        let account_current_conversions = self
            .string
            .create_or_reuse(py, x.account_current_conversions().as_ref());
        let account_unrealized_gains = self
            .string
            .create_or_reuse(py, x.account_unrealized_gains().as_ref());
        let account_rounding = x
            .account_rounding()
            .map(|account_rounding| self.string.create_or_reuse(py, account_rounding.as_ref()));
        let conversion_currency = self
            .string
            .create_or_reuse(py, x.conversion_currency().as_ref());

        let inferred_tolerance_default = PyDict::new(py);
        for (c, d) in x.inferred_tolerance_defaults() {
            // let c = match c {
            //     Some(c) => (Some(self.string.create_or_reuse(py, c.as_ref())), d),
            //     None => (None, d),
            // };
            // inferred_tolerance_default.set_item(c, d)?;
            inferred_tolerance_default
                .set_item(c.map(|c| self.string.create_or_reuse(py, c.as_ref())), d)?
        }
        let inferred_tolerance_default = inferred_tolerance_default.into();

        let inferred_tolerance_multiplier = x.inferred_tolerance_multiplier();
        let infer_tolerance_from_cost = x.infer_tolerance_from_cost();

        let documents = PySet::new(
            py,
            x.documents()
                .map(|p| {
                    self.string
                        .create_or_reuse(py, p.to_string_lossy().as_ref())
                })
                .collect::<Vec<Py<PyString>>>()
                .iter(),
        )
        .unwrap()
        .into();

        let operating_currency = PySet::new(
            py,
            x.operating_currency()
                .map(|c| self.string.create_or_reuse(py, c.as_ref()))
                .collect::<Vec<_>>()
                .iter(),
        )
        .unwrap()
        .into();
        let render_commas = x.render_commas();
        let booking_method = self.string.create_or_reuse(py, x.booking_method().as_ref());
        let plugin_processing_mode = self
            .string
            .create_or_reuse(py, x.plugin_processing_mode().into());

        let account_type_name = lima::AccountType::iter()
            .map(|t| (t, x.account_type_name(t)))
            .collect::<HashMap<lima::AccountType, &lima::AccountTypeName>>();

        let account_name_by_type = PyDict::new(py);
        let account_type_by_name = PyDict::new(py);
        for (t, n) in account_type_name {
            account_name_by_type.set_item(
                self.string.create_or_reuse(py, t.as_ref()),
                self.string.create_or_reuse(py, n.as_ref()),
            )?;
            account_type_by_name.set_item(
                self.string.create_or_reuse(py, n.as_ref()),
                self.string.create_or_reuse(py, t.as_ref()),
            )?;
        }
        let account_name_by_type = account_name_by_type.into();
        let account_type_by_name = account_type_by_name.into();

        let long_string_maxlines = x.long_string_maxlines();

        Ok(Options {
            title,
            account_previous_balances,
            account_previous_earnings,
            account_previous_conversions,
            account_current_earnings,
            account_current_conversions,
            account_unrealized_gains,
            account_rounding,
            conversion_currency,
            inferred_tolerance_default,
            inferred_tolerance_multiplier,
            infer_tolerance_from_cost,
            documents,
            operating_currency,
            render_commas,
            booking_method,
            plugin_processing_mode,
            account_name_by_type,
            account_type_by_name,
            long_string_maxlines,
        })
    }

    pub(crate) fn plugin(&mut self, py: Python<'_>, x: &lima::Plugin<'_>) -> PyResult<Plugin> {
        let module_name = self.string.create_or_reuse(py, x.module_name());
        let config = x
            .config()
            .as_ref()
            .map(|config| self.string.create_or_reuse(py, config.item()));

        Ok(Plugin {
            module_name,
            config,
        })
    }
}

struct StringFactory {
    string_interner: DefaultStringInterner,
    py_strings: Vec<Py<PyString>>,
}

impl StringFactory {
    fn new() -> Self {
        StringFactory {
            string_interner: StringInterner::new(),
            py_strings: Vec::new(),
        }
    }

    // either create a new string or reuse an existing one if we've already seen this string before
    fn create_or_reuse(&mut self, py: Python<'_>, x: &str) -> Py<PyString> {
        let sym = self.create_or_lookup_symbol(py, x);
        self.reuse(py, sym)
    }

    // reuse a string we have in our symbol table
    fn reuse(&mut self, py: Python<'_>, sym: SymbolU32) -> Py<PyString> {
        self.py_strings[sym.to_usize()].clone_ref(py)
    }

    fn create_or_lookup_symbol(&mut self, py: Python<'_>, x: &str) -> SymbolU32 {
        use Ordering::*;

        let sym = self.string_interner.get_or_intern(x);
        let i_sym = sym.to_usize();

        // allocate a new PyString if we don't already have it
        match i_sym.cmp(&self.py_strings.len()) {
            Less => (),
            Equal => {
                self.py_strings.push(PyString::new(py, x).into());
            }
            Greater => {
                // impossible
                panic!(
                    "unexpected symbol {:?} with index {} from string_interner with vec len {}",
                    sym,
                    i_sym,
                    self.py_strings.len()
                );
            }
        }

        sym
    }
}

struct DateFactory {
    cached_date: Option<Py<PyDate>>,
}

impl DateFactory {
    pub(crate) fn new() -> Self {
        DateFactory { cached_date: None }
    }

    // reuse the cached date if it matches, otherwise discard and create a new one.
    fn create_or_reuse(&mut self, py: Python<'_>, x: &Date) -> Py<PyDate> {
        let cached_date = self.cached_date.take();

        self.cached_date = match cached_date {
            Some(cached_date) => {
                let py_date = cached_date.bind(py);
                if py_date.get_year() == x.year()
                    && py_date.get_month() == x.month() as u8
                    && py_date.get_day() == x.day()
                {
                    Some(cached_date)
                } else {
                    Some(create_date(py, x))
                }
            }
            None => Some(create_date(py, x)),
        };

        self.cached_date.as_ref().unwrap().clone_ref(py)
    }
}

fn create_date(py: Python<'_>, x: &Date) -> Py<PyDate> {
    PyDate::new(py, x.year(), x.month() as u8, x.day())
        .unwrap()
        .into()
}