y_lang/ast/
binary_op.rs

1use std::{fmt::Display, str::FromStr};
2
3use super::Rule;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
6pub enum BinaryOp {
7    GreaterThan,
8    LessThan,
9    Equal,
10    Plus,
11    Minus,
12    Times,
13    DividedBy,
14}
15
16#[derive(Debug)]
17pub struct UndefinedOpError(String);
18
19impl FromStr for BinaryOp {
20    type Err = UndefinedOpError;
21
22    fn from_str(s: &str) -> Result<Self, Self::Err> {
23        match s {
24            ">" => Ok(BinaryOp::GreaterThan),
25            "<" => Ok(BinaryOp::LessThan),
26            "==" => Ok(BinaryOp::Equal),
27            "+" => Ok(BinaryOp::Plus),
28            "-" => Ok(BinaryOp::Minus),
29            "*" => Ok(BinaryOp::Times),
30            "/" => Ok(BinaryOp::DividedBy),
31            _ => Err(UndefinedOpError(format!("Unexpected binary op '{s}'"))),
32        }
33    }
34}
35
36impl Display for BinaryOp {
37    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38        f.write_str(match self {
39            BinaryOp::GreaterThan => ">",
40            BinaryOp::LessThan => "<",
41            BinaryOp::Equal => "==",
42            BinaryOp::Plus => "+",
43            BinaryOp::Minus => "-",
44            BinaryOp::Times => "*",
45            BinaryOp::DividedBy => "/",
46        })
47    }
48}
49
50impl From<Rule> for BinaryOp {
51    fn from(rule: Rule) -> Self {
52        match rule {
53            Rule::greaterThan => BinaryOp::GreaterThan,
54            Rule::lessThan => BinaryOp::LessThan,
55            Rule::equal => BinaryOp::Equal,
56            Rule::plus => BinaryOp::Plus,
57            Rule::minus => BinaryOp::Minus,
58            Rule::times => BinaryOp::Times,
59            Rule::dividedBy => BinaryOp::DividedBy,
60            _ => unreachable!("Unexpected rule {:?}", rule),
61        }
62    }
63}