okane_core/syntax/
expr.rs

1//! Defines value expression representation used in Ledger format.
2//! Note this is purely lexicographical and not always valid expression.
3
4use core::fmt;
5use std::borrow::Cow;
6
7use bounded_static::ToStatic;
8use pretty_decimal::PrettyDecimal;
9
10/// Amount, which is a single unit of value with a commodity.
11#[derive(Debug, PartialEq, Eq, Clone, ToStatic)]
12pub struct Amount<'i> {
13    pub value: PrettyDecimal,
14    pub commodity: Cow<'i, str>,
15}
16
17/// Defines value expression.
18/// Value expression is a valid expression when used in amount.
19/// It can be either amount literal or expression wrapped in `()`.
20#[derive(Debug, PartialEq, Eq, Clone, ToStatic)]
21pub enum ValueExpr<'i> {
22    Paren(Expr<'i>),
23    Amount(Amount<'i>),
24}
25
26impl<'i> From<Amount<'i>> for ValueExpr<'i> {
27    fn from(v: Amount<'i>) -> Self {
28        ValueExpr::Amount(v)
29    }
30}
31
32/// Generic expression.
33#[derive(Debug, PartialEq, Eq, Clone, ToStatic)]
34pub enum Expr<'i> {
35    Unary(UnaryOpExpr<'i>),
36    Binary(BinaryOpExpr<'i>),
37    Value(Box<ValueExpr<'i>>),
38}
39
40/// Represents unary operator.
41#[derive(Debug, PartialEq, Eq, Clone, Copy, ToStatic)]
42pub enum UnaryOp {
43    /// `-x`
44    Negate,
45}
46
47impl fmt::Display for UnaryOp {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        let op = match self {
50            UnaryOp::Negate => "-",
51        };
52        write!(f, "{}", op)
53    }
54}
55
56/// Unary operator expression.
57#[derive(Debug, PartialEq, Eq, Clone, ToStatic)]
58pub struct UnaryOpExpr<'i> {
59    pub op: UnaryOp,
60    pub expr: Box<Expr<'i>>,
61}
62
63/// Binary operator.
64#[derive(Debug, PartialEq, Eq, Clone, Copy, strum::EnumIter, ToStatic)]
65pub enum BinaryOp {
66    /// `+`
67    Add,
68    /// `-`
69    Sub,
70    /// `*`
71    Mul,
72    /// `/`
73    Div,
74}
75
76impl fmt::Display for BinaryOp {
77    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78        let op = match self {
79            BinaryOp::Add => "+",
80            BinaryOp::Sub => "-",
81            BinaryOp::Mul => "*",
82            BinaryOp::Div => "/",
83        };
84        write!(f, "{}", op)
85    }
86}
87
88/// Represents binary operator expression.
89#[derive(Debug, PartialEq, Eq, Clone, ToStatic)]
90pub struct BinaryOpExpr<'i> {
91    pub op: BinaryOp,
92    pub lhs: Box<Expr<'i>>,
93    pub rhs: Box<Expr<'i>>,
94}