dust/tests/functions.rs

135 lines
2.4 KiB
Rust
Raw Normal View History

2024-02-01 00:35:27 +00:00
use dust_lang::{error::ValidationError, *};
2024-01-06 07:18:30 +00:00
#[test]
fn function_call() {
assert_eq!(
interpret(
"
2024-02-16 18:23:58 +00:00
foobar = (message <str>) <str> { message }
foobar('Hiya')
",
2024-01-06 07:18:30 +00:00
),
Ok(Value::string("Hiya".to_string()))
);
}
#[test]
fn call_empty_function() {
assert_eq!(
interpret(
"
2024-02-16 18:23:58 +00:00
foobar = (message <str>) <none> {}
foobar('Hiya')
",
2024-01-06 07:18:30 +00:00
),
Ok(Value::none())
);
}
#[test]
fn callback() {
assert_eq!(
interpret(
"
foobar = (cb <() -> str>) <str> {
cb()
}
foobar(() <str> { 'Hiya' })
",
),
Ok(Value::string("Hiya".to_string()))
);
}
#[test]
fn built_in_function_call() {
2024-02-15 15:33:25 +00:00
assert_eq!(interpret("output('Hiya')"), Ok(Value::none()));
2024-01-06 07:18:30 +00:00
}
#[test]
fn function_context_does_not_capture_normal_values() {
2024-02-01 00:35:27 +00:00
assert_eq!(
interpret(
"
2024-01-06 07:18:30 +00:00
x = 1
foo = () <any> { x }
"
2024-02-01 00:35:27 +00:00
),
Err(Error::Validation(
2024-02-15 21:02:27 +00:00
ValidationError::VariableIdentifierNotFound(Identifier::new("x"))
2024-02-01 00:35:27 +00:00
))
);
2024-01-06 07:18:30 +00:00
assert_eq!(
interpret(
"
x = 1
foo = (x <int>) <int> { x }
foo(2)
"
),
Ok(Value::Integer(2))
);
2024-01-10 01:38:40 +00:00
}
2024-01-06 07:18:30 +00:00
2024-01-10 01:38:40 +00:00
#[test]
fn function_context_captures_functions() {
2024-01-06 07:18:30 +00:00
assert_eq!(
interpret(
"
bar = () <int> { 2 }
foo = () <int> { bar() }
foo()
"
),
Ok(Value::Integer(2))
);
}
#[test]
fn function_context_captures_structure_definitions() {
2024-02-15 05:53:43 +00:00
let mut map = Map::new();
2024-01-06 07:18:30 +00:00
2024-02-15 21:02:27 +00:00
map.set(Identifier::new("name"), Value::string("bob"));
2024-01-06 07:18:30 +00:00
assert_eq!(
interpret(
"
2024-02-16 18:23:58 +00:00
struct User {
2024-01-06 07:18:30 +00:00
name <str>
}
bob = () <User> {
new User {
name = 'bob'
}
}
bob()
"
),
2024-02-16 18:31:35 +00:00
Ok(Value::Struct(StructInstance::new("User".into(), map)))
2024-01-06 07:18:30 +00:00
);
}
#[test]
fn recursion() {
assert_eq!(
interpret(
"
fib = (i <int>) <int> {
if i <= 1 {
1
} else {
2024-01-28 23:42:27 +00:00
fib(i - 1) + fib(i - 2)
}
}
2024-01-28 23:42:27 +00:00
fib(8)
"
),
2024-01-28 23:42:27 +00:00
Ok(Value::Integer(34))
);
}