Skip to content

Commit

Permalink
refactor: simpler macros
Browse files Browse the repository at this point in the history
  • Loading branch information
caelansar committed Jun 25, 2024
1 parent 2fc74e3 commit a2dd287
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 19 deletions.
28 changes: 10 additions & 18 deletions src/eval/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,34 +4,26 @@ use crate::eval::object::{BOOL_OBJ_FALSE, BOOL_OBJ_TRUE};
#[allow(unused_macros)]
macro_rules! arithmetic_operator {
($l:expr, $r:expr, $op:tt, $($t:ident),*) => {
match $l {
match ($l, $r) {
$(
Object::$t(a) => {
if let Object::$t(b) = $r {
Object::$t(a $op b)
} else {
Object::Error(format!("type mismatch: {} {} {}", a, stringify!($op), $r))
}
}
(Object::$t(a), Object::$t(b)) => Object::$t(a $op b),
(Object::$t(a), b) => Object::Error(format!("type mismatch: {} {} {}", a, stringify!($op), b)),
(a, Object::$t(b)) => Object::Error(format!("type mismatch: {} {} {}", a, stringify!($op), b)),
)*
other => Object::Error(format!("unknown operator {} for {:?}", stringify!($op), other))
(a, b) => Object::Error(format!("unsupported operator: {} {} {}", a, stringify!($op), b))
}
};
}

macro_rules! arithmetic_operator_ref {
($l:expr, $r:expr, $op:tt, $($t:ident),*) => {
match $l {
match ($l, $r) {
$(
Object::$t(a) => {
if let Object::$t(ref b) = $r {
Object::$t(a $op b)
} else {
Object::Error(format!("type mismatch: {} {} {}", a, stringify!($op), $r))
}
}
(Object::$t(a), Object::$t(ref b)) => Object::$t(a $op b),
(Object::$t(a), b) => Object::Error(format!("type mismatch: {} {} {}", a, stringify!($op), b)),
(a, Object::$t(ref b)) => Object::Error(format!("type mismatch: {} {} {}", a, stringify!($op), b)),
)*
other => Object::Error(format!("unknown operator {} for {:?}", stringify!($op), other))
(a, b) => Object::Error(format!("unsupported operator: {} {} {}", a, stringify!($op), b))
}
};
}
Expand Down
2 changes: 1 addition & 1 deletion src/eval/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ fn object_arithmetic_should_work() {
&Object::String("1".into()) + &Object::String("2".into())
);
assert_eq!(
Object::Error("unknown operator + for Array([])".into()),
Object::Error("unsupported operator: [] + []".into()),
&Object::Array(Vec::new()) + &Object::Array(Vec::new())
);
assert_eq!(Object::Int(1), &Object::Int(1) % &Object::Int(2));
Expand Down

0 comments on commit a2dd287

Please sign in to comment.