From 2563f64670211edf8e9dea4637981d72b7b02723 Mon Sep 17 00:00:00 2001 From: aps <62445385+apsz3@users.noreply.github.com> Date: Fri, 10 Feb 2023 22:34:44 -0500 Subject: [PATCH 1/3] Assert takes optional message --- src/compiler.h | 2 ++ src/error.h | 3 ++- src/vm.h | 4 +++- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/compiler.h b/src/compiler.h index a737e7ff..f6b47495 100644 --- a/src/compiler.h +++ b/src/compiler.h @@ -887,6 +887,8 @@ __LISTCOMP: compile_try_except(); }else if(match(TK("assert"))){ EXPR(); + if (match(TK(","))) EXPR(); + else emit(OP_LOAD_CONST, co()->add_const(vm->PyStr(""))); emit(OP_ASSERT); consume_end_stmt(); } else if(match(TK("with"))){ diff --git a/src/error.h b/src/error.h index 2e55d385..f557dc79 100644 --- a/src/error.h +++ b/src/error.h @@ -86,7 +86,8 @@ public: StrStream ss; if(is_re) ss << "Traceback (most recent call last):\n"; while(!st.empty()) { ss << st.top() << '\n'; st.pop(); } - ss << type << ": " << msg; + if (msg.compare("") != 0) ss << type << ": " << msg; + else ss << type; return ss.str(); } }; diff --git a/src/vm.h b/src/vm.h index 966e9208..31db29c5 100644 --- a/src/vm.h +++ b/src/vm.h @@ -186,8 +186,10 @@ class VM { case OP_LOAD_ELLIPSIS: frame->push(Ellipsis); break; case OP_ASSERT: { + PyVar _msg = frame->pop_value(this); + Str msg = PyStr_AS_C(asStr(_msg)); PyVar expr = frame->pop_value(this); - if(asBool(expr) != True) _error("AssertionError", ""); + if(asBool(expr) != True) _error("AssertionError", msg); } break; case OP_EXCEPTION_MATCH: { From ac9640f73e30e700a1bf8ad554ff23999b0fc57f Mon Sep 17 00:00:00 2001 From: aps <62445385+apsz3@users.noreply.github.com> Date: Fri, 10 Feb 2023 22:41:27 -0500 Subject: [PATCH 2/3] Add sample test for assertions with messages --- tests/_exception.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/tests/_exception.py b/tests/_exception.py index 84423b10..4e77ac35 100644 --- a/tests/_exception.py +++ b/tests/_exception.py @@ -41,4 +41,11 @@ def f1(): try: f1() except KeyError: - print("PASS 04") \ No newline at end of file + print("PASS 04") + + +assert True, "Msg" +try: + assert False, "Msg" +except AssertionError: + print("PASS 05") From e02429365e1af10bdcb0ea7882cb8e5e0d25a561 Mon Sep 17 00:00:00 2001 From: BLUELOVETH Date: Sat, 11 Feb 2023 19:59:28 +0800 Subject: [PATCH 3/3] Update error.h --- src/error.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/error.h b/src/error.h index f557dc79..9fc76949 100644 --- a/src/error.h +++ b/src/error.h @@ -86,9 +86,9 @@ public: StrStream ss; if(is_re) ss << "Traceback (most recent call last):\n"; while(!st.empty()) { ss << st.top() << '\n'; st.pop(); } - if (msg.compare("") != 0) ss << type << ": " << msg; + if (!msg.empty()) ss << type << ": " << msg; else ss << type; return ss.str(); } }; -} \ No newline at end of file +}