93 lines
1.9 KiB
Rust
93 lines
1.9 KiB
Rust
use std::fmt::Display;
|
|
|
|
use crate::lexer::token;
|
|
|
|
pub enum UnaryOperator {
|
|
Minus,
|
|
Bang,
|
|
}
|
|
|
|
impl TryFrom<token::TokenType> for UnaryOperator {
|
|
type Error = EnumConvertError;
|
|
|
|
fn try_from(value: token::TokenType) -> Result<Self, Self::Error> {
|
|
Ok(match value {
|
|
token::TokenType::Bang => Self::Bang,
|
|
token::TokenType::Minus => Self::Minus,
|
|
_ => return Err(EnumConvertError),
|
|
})
|
|
}
|
|
}
|
|
|
|
impl Display for UnaryOperator {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
write!(
|
|
f,
|
|
"{}",
|
|
match *self {
|
|
UnaryOperator::Minus => "-",
|
|
UnaryOperator::Bang => "!",
|
|
}
|
|
)
|
|
}
|
|
}
|
|
|
|
pub enum Operator {
|
|
Minus,
|
|
Plus,
|
|
BangEqual,
|
|
EqualEqual,
|
|
Greater,
|
|
GreaterEqual,
|
|
Less,
|
|
LessEqual,
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
pub struct EnumConvertError;
|
|
impl std::fmt::Display for EnumConvertError {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
write!(f, "Couldn't convert between enums")
|
|
}
|
|
}
|
|
|
|
impl std::error::Error for EnumConvertError {}
|
|
|
|
impl TryFrom<token::TokenType> for Operator {
|
|
type Error = EnumConvertError;
|
|
|
|
fn try_from(value: token::TokenType) -> Result<Self, Self::Error> {
|
|
Ok(match value {
|
|
token::TokenType::Plus => Self::Plus,
|
|
token::TokenType::Minus => Self::Minus,
|
|
token::TokenType::BangEqual => Self::BangEqual,
|
|
token::TokenType::EqualEqual => Self::EqualEqual,
|
|
token::TokenType::Greater => Self::Greater,
|
|
token::TokenType::GreaterEqual => Self::GreaterEqual,
|
|
token::TokenType::Less => Self::Less,
|
|
token::TokenType::LessEqual => Self::LessEqual,
|
|
|
|
_ => return Err(EnumConvertError),
|
|
})
|
|
}
|
|
}
|
|
|
|
impl Display for Operator {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
write!(
|
|
f,
|
|
"{}",
|
|
match *self {
|
|
Operator::Plus => "+",
|
|
Operator::Minus => "-",
|
|
Operator::Less => "<",
|
|
Operator::Greater => ">",
|
|
Operator::BangEqual => "!=",
|
|
Operator::LessEqual => "<=",
|
|
Operator::EqualEqual => "==",
|
|
Operator::GreaterEqual => ">=",
|
|
}
|
|
)
|
|
}
|
|
}
|