(assert [exp] [?message]) macro

This commit is contained in:
2020-12-04 10:03:49 -07:00
parent 133ebfd7c6
commit c0dd21cfe1
3 changed files with 29 additions and 1 deletions

View File

@@ -122,6 +122,21 @@ class Macros {
arraySet(wholeExp, exps, k);
};
macros["assert"] = (wholeExp:ReaderExp, exps:Array<ReaderExp>, k:KissState) -> {
wholeExp.checkNumArgs(1, 2, "(assert [expression] [message])");
var expression = exps[0];
var basicMessage = 'Assertion ${expression.def.toString()} failed';
var messageExp = if (exps.length > 1) {
CallExp(Symbol("+").withPosOf(wholeExp), [StrExp(basicMessage + ": ").withPosOf(wholeExp), exps[1]]);
} else {
StrExp(basicMessage);
};
CallExp(Symbol("unless").withPosOf(wholeExp), [
expression,
CallExp(Symbol("throw").withPosOf(wholeExp), [messageExp.withPosOf(wholeExp)]).withPosOf(wholeExp)
]).withPosOf(wholeExp);
};
// Under the hood, (defmacrofun ...) defines a runtime function that accepts Quote arguments and a special form that quotes the arguments to macrofun calls
macros["defmacrofun"] = (wholeExp:ReaderExp, exps:Array<ReaderExp>, k:KissState) -> {
wholeExp.checkNumArgs(3, null, "(defmacrofun [name] [args] [body...])");

View File

@@ -217,4 +217,8 @@ class BasicTestCase extends Test {
function testBreakContinue() {
_testBreakContinue();
}
function testAssert() {
_testAssert();
}
}

View File

@@ -289,4 +289,13 @@
val)))]
(Assert.equals 2 a)
(Assert.equals 4 b)
(Assert.equals 6 c)))
(Assert.equals 6 c)))
(defun _testAssert []
(try
(assert false (+ "false " "should " "have " "been " "true"))
(catch [:String message]
(Assert.equals "Assertion false failed: false should have been true" message)))
(assert true)
(assert ![]))