1
0
dust/dust-lang/tests/functions.rs

128 lines
2.4 KiB
Rust
Raw Normal View History

2024-03-24 13:10:49 +00:00
use std::rc::Rc;
2024-03-09 03:34:17 +00:00
use dust_lang::{
abstract_tree::Identifier,
error::{Error, ValidationError},
*,
};
#[test]
fn function_call() {
assert_eq!(
interpret(
2024-03-24 13:10:49 +00:00
Rc::new("test".to_string()),
2024-03-09 03:34:17 +00:00
"
2024-03-24 13:10:49 +00:00
foobar = (message : str) str { message }
2024-03-09 03:34:17 +00:00
foobar('Hiya')
",
),
Ok(Some(Value::string("Hiya".to_string())))
);
}
#[test]
fn call_empty_function() {
assert_eq!(
interpret(
2024-03-24 13:10:49 +00:00
Rc::new("test".to_string()),
2024-03-09 03:34:17 +00:00
"
2024-03-24 13:10:49 +00:00
foobar = (message : str) none {}
2024-03-09 03:34:17 +00:00
foobar('Hiya')
",
),
Ok(None)
);
}
#[test]
fn callback() {
assert_eq!(
interpret(
2024-03-24 13:10:49 +00:00
Rc::new("test".to_string()),
2024-03-09 03:34:17 +00:00
"
2024-03-24 13:10:49 +00:00
foobar = (cb: fn() -> str) str {
2024-03-09 03:34:17 +00:00
cb()
}
2024-03-24 13:10:49 +00:00
foobar(() str { 'Hiya' })
2024-03-09 03:34:17 +00:00
",
),
Ok(Some(Value::string("Hiya".to_string())))
);
}
#[test]
fn built_in_function_call() {
2024-03-24 13:10:49 +00:00
assert_eq!(
interpret(Rc::new("test".to_string()), "io.write_line('Hiya')"),
Ok(None)
);
2024-03-09 03:34:17 +00:00
}
#[test]
fn function_context_does_not_capture_values() {
assert_eq!(
interpret(
2024-03-24 13:10:49 +00:00
Rc::new("test".to_string()),
2024-03-09 03:34:17 +00:00
"
x = 1
2024-03-24 13:10:49 +00:00
foo = () any { x }
2024-03-09 03:34:17 +00:00
"
2024-03-24 13:10:49 +00:00
)
.unwrap_err()
.errors(),
&vec![Error::Validation {
2024-03-09 03:34:17 +00:00
error: ValidationError::VariableNotFound(Identifier::new("x")),
2024-03-24 13:10:49 +00:00
position: (32, 50).into()
}]
2024-03-09 03:34:17 +00:00
);
assert_eq!(
interpret(
2024-03-24 13:10:49 +00:00
Rc::new("test".to_string()),
2024-03-09 03:34:17 +00:00
"
x = 1
2024-03-24 13:10:49 +00:00
foo = (x: int) int { x }
2024-03-09 03:34:17 +00:00
foo(2)
"
),
Ok(Some(Value::integer(2)))
);
}
#[test]
fn function_context_captures_functions() {
assert_eq!(
interpret(
2024-03-24 13:10:49 +00:00
Rc::new("test".to_string()),
2024-03-09 03:34:17 +00:00
"
2024-03-24 13:10:49 +00:00
bar = () int { 2 }
foo = () int { bar() }
2024-03-09 03:34:17 +00:00
foo()
"
),
Ok(Some(Value::integer(2)))
);
}
#[test]
fn recursion() {
assert_eq!(
interpret(
2024-03-24 13:10:49 +00:00
Rc::new("test".to_string()),
2024-03-09 03:34:17 +00:00
"
2024-03-24 13:10:49 +00:00
fib = (i: int) int {
2024-03-09 03:34:17 +00:00
if i <= 1 {
1
} else {
fib(i - 1) + fib(i - 2)
}
}
fib(8)
"
),
Ok(Some(Value::integer(34)))
);
}