diff --git a/library/src/compute/foundations.rs b/library/src/compute/foundations.rs index 82270dd31..f17af2198 100644 --- a/library/src/compute/foundations.rs +++ b/library/src/compute/foundations.rs @@ -56,6 +56,29 @@ pub fn repr(args: &mut Args) -> SourceResult { Ok(args.expect::("value")?.repr().into()) } +/// # Panic +/// Fail with an error. +/// +/// ## Example +/// The code below produces the error `panicked at: "this is wrong"`. +/// ```typ +/// #panic("this is wrong") +/// ``` +/// +/// ## Parameters +/// - payload: `Value` (positional) +/// The value (or message) to panic with. +/// +/// ## Category +/// foundations +#[func] +pub fn panic(args: &mut Args) -> SourceResult { + match args.eat::()? { + Some(v) => bail!(args.span, "panicked with: {}", v.repr()), + None => bail!(args.span, "panicked"), + } +} + /// # Assert /// Ensure that a condition is fulfilled. /// @@ -64,24 +87,26 @@ pub fn repr(args: &mut Args) -> SourceResult { /// /// ## Example /// ```example -/// #assert(1 < 2) +/// #assert(1 < 2, message: "one is") /// ``` /// /// ## Parameters /// - condition: `bool` (positional, required) /// The condition that must be true for the assertion to pass. +/// - message: `EcoString` (named) +/// The error message when the assertion fails. /// /// ## Category /// foundations #[func] pub fn assert(args: &mut Args) -> SourceResult { - let Spanned { v, span } = args.expect::>("condition")?; + let check = args.expect::("condition")?; let message = args.named::("message")?; - if !v { + if !check { if let Some(message) = message { - bail!(span, "assertion failed: {}", message); + bail!(args.span, "assertion failed: {}", message); } else { - bail!(span, "assertion failed"); + bail!(args.span, "assertion failed"); } } Ok(Value::None) diff --git a/library/src/lib.rs b/library/src/lib.rs index 8a2315319..31da5b71f 100644 --- a/library/src/lib.rs +++ b/library/src/lib.rs @@ -96,6 +96,7 @@ fn global(math: Module, calc: Module) -> Module { // Compute. global.def_func::("type"); global.def_func::("repr"); + global.def_func::("panic"); global.def_func::("assert"); global.def_func::("eval"); global.def_func::("int"); diff --git a/tests/typ/compute/foundations.typ b/tests/typ/compute/foundations.typ index 83cda65fb..eb3e7e35c 100644 --- a/tests/typ/compute/foundations.typ +++ b/tests/typ/compute/foundations.typ @@ -10,11 +10,31 @@ #test(repr(ltr), "ltr") #test(repr((1, 2, false, )), "(1, 2, false)") +--- +// Test panic. +// Error: 7-9 panicked +#panic() + +--- +// Test panic. +// Error: 7-12 panicked with: 123 +#panic(123) + +--- +// Test panic. +// Error: 7-24 panicked with: "this is wrong" +#panic("this is wrong") + --- // Test failing assertions. -// Error: 9-15 assertion failed +// Error: 8-16 assertion failed #assert(1 == 2) +--- +// Test failing assertions. +// Error: 8-51 assertion failed: two is smaller than one +#assert(2 < 1, message: "two is smaller than one") + --- // Test failing assertions. // Error: 9-15 expected boolean, found string