Skip to main content

beancount_parser/
metadata.rs

1//! Types to represent [beancount metadata](https://beancount.github.io/docs/beancount_language_syntax.html#metadata)
2//!
3//! # Example
4//!
5//! ```
6//! # use beancount_parser::BeancountFile;
7//! use beancount_parser::metadata::Value;
8//! let input = r#"
9//! 2023-05-27 commodity CHF
10//!     title: "Swiss Franc"
11//! "#;
12//! let beancount: BeancountFile<f64> = input.parse().unwrap();
13//! let directive_metadata = &beancount.directives[0].metadata;
14//! assert_eq!(directive_metadata.get("title"), Some(&Value::String("Swiss Franc".into())));
15//! ```
16
17use std::{
18    borrow::Borrow,
19    collections::HashMap,
20    fmt::{Debug, Display, Formatter},
21    str::FromStr,
22    sync::Arc,
23};
24
25use nom::{
26    branch::alt,
27    bytes::complete::take_while,
28    character::complete::{char, satisfy, space1},
29    combinator::{all_consuming, iterator, map, recognize},
30    sequence::preceded,
31    Parser,
32};
33
34use crate::{amount, empty_line, end_of_line, string, Currency, Decimal, IResult, Span};
35
36/// Metadata map
37///
38/// See the [`metadata`](crate::metadata) module for an example
39pub type Map<D> = HashMap<Key, Value<D>>;
40
41/// Metadata key
42///
43/// See the [`metadata`](crate::metadata) module for an example
44#[derive(Debug, Clone, Eq, PartialEq, Hash)]
45pub struct Key(Arc<str>);
46
47impl Display for Key {
48    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
49        Display::fmt(&self.0, f)
50    }
51}
52
53impl AsRef<str> for Key {
54    fn as_ref(&self) -> &str {
55        self.0.as_ref()
56    }
57}
58
59impl Borrow<str> for Key {
60    fn borrow(&self) -> &str {
61        self.0.borrow()
62    }
63}
64
65impl FromStr for Key {
66    type Err = crate::Error;
67    fn from_str(s: &str) -> Result<Self, Self::Err> {
68        let span = Span::new(s);
69        match all_consuming(key).parse(span) {
70            Ok((_, key)) => Ok(key),
71            Err(_) => Err(crate::Error::new(s, span)),
72        }
73    }
74}
75
76/// Metadata value
77///
78/// See the [`metadata`](crate::metadata) module for an example
79#[derive(Debug, Clone, PartialEq)]
80#[non_exhaustive]
81pub enum Value<D> {
82    /// String value
83    String(String),
84    /// A number or number expression
85    Number(D),
86    /// A [`Currency`]
87    Currency(Currency),
88}
89
90pub(crate) fn parse<D: Decimal>(input: Span<'_>) -> IResult<'_, Map<D>> {
91    let mut iter = iterator(input, alt((entry.map(Some), empty_line.map(|()| None))));
92    let map: HashMap<_, _> = iter.by_ref().flatten().collect();
93    let (input, ()) = iter.finish()?;
94    Ok((input, map))
95}
96
97fn entry<D: Decimal>(input: Span<'_>) -> IResult<'_, (Key, Value<D>)> {
98    let (input, _) = space1(input)?;
99    let (input, key) = key(input)?;
100    let (input, _) = char(':')(input)?;
101    let (input, _) = space1(input)?;
102    let (input, value) = alt((
103        string.map(Value::String),
104        amount::expression.map(Value::Number),
105        amount::currency.map(Value::Currency),
106    ))
107    .parse(input)?;
108    let (input, ()) = end_of_line(input)?;
109    Ok((input, (key, value)))
110}
111
112fn key(input: Span<'_>) -> IResult<'_, Key> {
113    map(
114        recognize(preceded(
115            satisfy(char::is_lowercase),
116            take_while(|c: char| c.is_alphanumeric() || c == '-' || c == '_'),
117        )),
118        |s: Span<'_>| Key((*s.fragment()).into()),
119    )
120    .parse(input)
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126
127    use rstest::rstest;
128
129    #[rstest]
130    fn key_from_str_should_parse_key() {
131        let key: Key = "foo".parse().unwrap();
132        assert_eq!(key.as_ref(), "foo");
133    }
134
135    #[rstest]
136    fn key_from_str_should_not_parse_invalid_key() {
137        let key: Result<Key, _> = "foo bar".parse();
138        assert!(key.is_err(), "{key:?}");
139    }
140}