Refactor builtin function declaration

This commit is contained in:
ConnorSkees 2020-02-03 07:11:35 -05:00
parent efc62a2433
commit 8eb9620a1a
3 changed files with 32 additions and 33 deletions

View File

@ -4,17 +4,14 @@ use super::Builtin;
use crate::value::Value;
pub(crate) fn register(f: &mut BTreeMap<String, Builtin>) {
f.insert(
"if".to_owned(),
Box::new(|args| {
let cond: &Value = arg!(args, 0, "condition");
let if_true = arg!(args, 1, "if-true").clone();
let if_false = arg!(args, 2, "if-false").clone();
if cond.is_true() {
Some(if_true)
} else {
Some(if_false)
}
}),
);
decl!(f "if", |args| {
let cond: &Value = arg!(args, 0, "condition");
let if_true = arg!(args, 1, "if-true").clone();
let if_false = arg!(args, 2, "if-false").clone();
if cond.is_true() {
Some(if_true)
} else {
Some(if_false)
}
});
}

View File

@ -4,26 +4,8 @@ use std::collections::BTreeMap;
use crate::args::CallArgs;
use crate::value::Value;
macro_rules! arg {
($args:ident, $idx:literal, $name:literal) => {
match $args.get(stringify!($idx)) {
Some(v) => v,
None => match $args.get($name) {
Some(v) => v,
None => panic!("missing variable"),
},
};
};
($args:ident, $idx:literal, $name:literal, $default:literal) => {
match $args.get(stringify!($idx)) {
Some(v) => v,
None => match $args.get($name) {
Some(v) => v,
None => $default,
},
};
};
}
#[macro_use]
mod macros;
mod color;

20
tests/meta.rs Normal file
View File

@ -0,0 +1,20 @@
#![cfg(test)]
#[macro_use]
mod macros;
test!(
if_true,
"a {\n color: if(true, 1, 2)\n}\n",
"a {\n color: 1;\n}\n"
);
test!(
if_named_args,
"a {\n color: if($condition: true, $if-true: 1, $if-false: 2)\n}\n",
"a {\n color: 1;\n}\n"
);
test!(
if_false,
"a {\n color: if(false, 1, 2);\n}\n",
"a {\n color: 2;\n}\n"
);