y_lang/ast/
prefix_op.rs

1use std::{fmt::Display, str::FromStr};
2
3use super::Rule;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
6pub enum PrefixOp {
7    UnaryMinus,
8    Not,
9}
10
11#[derive(Debug)]
12pub struct UndefinedPrefixOpError(String);
13
14impl FromStr for PrefixOp {
15    type Err = UndefinedPrefixOpError;
16
17    fn from_str(s: &str) -> Result<Self, Self::Err> {
18        match s {
19            "-" => Ok(PrefixOp::UnaryMinus),
20            "!" => Ok(PrefixOp::Not),
21            _ => Err(UndefinedPrefixOpError(format!(
22                "Unexpected prefix op '{s}'"
23            ))),
24        }
25    }
26}
27
28impl Display for PrefixOp {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        f.write_str(match self {
31            PrefixOp::UnaryMinus => "-",
32            PrefixOp::Not => "!",
33        })
34    }
35}
36
37impl From<Rule> for PrefixOp {
38    fn from(rule: Rule) -> Self {
39        match rule {
40            Rule::unaryMinus => PrefixOp::UnaryMinus,
41            Rule::not => PrefixOp::Not,
42            _ => unreachable!("Unexpected rule {:?}", rule),
43        }
44    }
45}