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