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
//! Types for representing an [`Amount`]

use nom::{
    branch::alt,
    character::complete::{one_of, satisfy, space1},
    combinator::{map, not, opt, peek, recognize},
    multi::many_till,
    sequence::{pair, separated_pair},
    IResult,
};

#[cfg(all(test, feature = "unstable"))]
use crate::pest_parser::Pair;

pub use self::expression::{ConversionError, Expression, Value};

pub(crate) mod expression;

/// A beancount amount
///
/// The amount is the combination of an [`Expression`] and the currency.
#[derive(Debug, Clone, PartialEq)]
pub struct Amount<'a> {
    pub(crate) expression: Expression,
    pub(crate) currency: &'a str,
}

impl<'a> Amount<'a> {
    #[cfg(any(test))]
    pub(crate) fn new(value: impl Into<rust_decimal::Decimal>, currency: &'a str) -> Self {
        Self {
            expression: Expression::value(value),
            currency,
        }
    }

    /// Returns the [`Expression`] which may be inspected or evaluated
    #[must_use]
    pub fn expression(&self) -> &Expression {
        &self.expression
    }

    /// Evaluate the expression and returns the value
    #[must_use]
    pub fn value(&self) -> Value {
        self.expression.evaluate()
    }

    /// Returns the currency
    #[must_use]
    pub fn currency(&self) -> &'a str {
        self.currency
    }

    #[cfg(all(test, feature = "unstable"))]
    pub(crate) fn from_pair(pair: Pair<'_>) -> Amount<'_> {
        let mut inner = pair.into_inner();
        let expression = Expression::from_pair(inner.next().expect("no value in amount"));
        let currency = inner.next().expect("no currency in amount").as_str();
        Amount {
            expression,
            currency,
        }
    }
}

pub(crate) fn amount(input: &str) -> IResult<&str, Amount<'_>> {
    map(
        separated_pair(expression::parse, space1, currency),
        |(expression, currency)| Amount {
            expression,
            currency,
        },
    )(input)
}

fn current_first_char(input: &str) -> IResult<&str, char> {
    satisfy(|c: char| c.is_ascii_uppercase() && c.is_ascii_alphabetic())(input)
}

fn current_middle_char(input: &str) -> IResult<&str, char> {
    alt((
        satisfy(|c: char| c.is_ascii_uppercase() && c.is_ascii_alphabetic()),
        satisfy(char::is_numeric),
        one_of("'._-"),
    ))(input)
}

fn current_last_char(input: &str) -> IResult<&str, char> {
    alt((
        satisfy(|c: char| c.is_ascii_uppercase() && c.is_ascii_alphabetic()),
        satisfy(char::is_numeric),
    ))(input)
}

pub(crate) fn currency(input: &str) -> IResult<&str, &str> {
    recognize(pair(
        current_first_char,
        opt(pair(
            many_till(
                current_middle_char,
                peek(pair(current_last_char, not(current_middle_char))),
            ),
            current_last_char,
        )),
    ))(input)
}

#[cfg(test)]
mod tests {
    use super::*;

    use nom::combinator::all_consuming;

    #[test]
    fn parse_amount() {
        assert_eq!(
            amount("10 CHF"),
            Ok((
                "",
                Amount {
                    expression: Expression::value(10),
                    currency: "CHF"
                }
            ))
        );
    }

    #[test]
    fn invalid_amount() {
        assert!(amount("10 chf").is_err());
    }

    #[rstest]
    fn valid_currency(#[values("CHF", "X-A", "X_A", "X'A", "A", "AB", "A2", "R2D2")] input: &str) {
        assert_eq!(all_consuming(currency)(input), Ok(("", input)));
    }

    #[rstest]
    fn invalid_currency(#[values("CHF-", "X-a", "1A", "aA")] input: &str) {
        let p = all_consuming(currency)(input);
        assert!(p.is_err(), "Result was actually: {p:#?}");
    }
}