Add assert function

This commit is contained in:
Laurenz 2021-10-05 19:37:38 +02:00
parent 58d1cc68d9
commit 0a23bfbc23
3 changed files with 34 additions and 2 deletions

View File

@ -57,6 +57,7 @@ pub fn new() -> Scope {
std.def_func("circle", circle);
// Utility.
std.def_func("assert", assert);
std.def_func("type", type_);
std.def_func("repr", repr);
std.def_func("join", join);

View File

@ -4,6 +4,17 @@ use std::str::FromStr;
use super::*;
use crate::color::{Color, RgbaColor};
/// `assert`: Ensure that a condition is fulfilled.
pub fn assert(_: &mut EvalContext, args: &mut Args) -> TypResult<Value> {
let Spanned { v, span } = args.expect("condition")?;
match v {
Value::Bool(true) => {}
Value::Bool(false) => bail!(span, "assertion failed"),
v => bail!(span, "expected boolean, found {}", v.type_name()),
}
Ok(Value::None)
}
/// `type`: The name of a value's type.
pub fn type_(_: &mut EvalContext, args: &mut Args) -> TypResult<Value> {
Ok(args.expect::<Value>("value")?.type_name().into())
@ -86,7 +97,7 @@ pub fn abs(_: &mut EvalContext, args: &mut Args) -> TypResult<Value> {
Value::Relative(v) => Value::Relative(v.abs()),
Value::Fractional(v) => Value::Fractional(v.abs()),
Value::Linear(_) => bail!(span, "cannot take absolute value of a linear"),
_ => bail!(span, "expected numeric value"),
v => bail!(span, "expected numeric value, found {}", v.type_name()),
})
}
@ -157,7 +168,11 @@ pub fn len(_: &mut EvalContext, args: &mut Args) -> TypResult<Value> {
Value::Str(v) => v.len(),
Value::Array(v) => v.len(),
Value::Dict(v) => v.len(),
_ => bail!(span, "expected string, array or dictionary"),
v => bail!(
span,
"expected string, array or dictionary, found {}",
v.type_name(),
),
}))
}

View File

@ -1,6 +1,22 @@
// Test basic functions.
// Ref: false
---
// Test the `assert` function.
#assert(1 + 1 == 2)
#assert(2..5 == (2, 3, 4))
#assert(not false)
---
// Test failing assertions.
// Error: 9-15 assertion failed
#assert(1 == 2)
---
// Test failing assertions.
// Error: 9-15 expected boolean, found string
#assert("true")
---
// Test the `type` function.
#test(type(1), "integer")