Просмотр исходного кода

Merge pull request #12 from apsz3/main

Assert with message
BLUELOVETH 3 лет назад
Родитель
Сommit
794d0785a0
4 измененных файлов с 16 добавлено и 4 удалено
  1. 2 0
      src/compiler.h
  2. 3 2
      src/error.h
  3. 3 1
      src/vm.h
  4. 8 1
      tests/_exception.py

+ 2 - 0
src/compiler.h

@@ -871,6 +871,8 @@ __LISTCOMP:
             compile_try_except();
             compile_try_except();
         }else if(match(TK("assert"))){
         }else if(match(TK("assert"))){
             EXPR();
             EXPR();
+            if (match(TK(","))) EXPR();
+            else emit(OP_LOAD_CONST, co()->add_const(vm->PyStr("")));
             emit(OP_ASSERT);
             emit(OP_ASSERT);
             consume_end_stmt();
             consume_end_stmt();
         } else if(match(TK("with"))){
         } else if(match(TK("with"))){

+ 3 - 2
src/error.h

@@ -86,8 +86,9 @@ public:
         StrStream ss;
         StrStream ss;
         if(is_re) ss << "Traceback (most recent call last):\n";
         if(is_re) ss << "Traceback (most recent call last):\n";
         while(!st.empty()) { ss << st.top() << '\n'; st.pop(); }
         while(!st.empty()) { ss << st.top() << '\n'; st.pop(); }
-        ss << type << ": " << msg;
+        if (!msg.empty()) ss << type << ": " << msg;
+        else ss << type;
         return ss.str();
         return ss.str();
     }
     }
 };
 };
-}
+}

+ 3 - 1
src/vm.h

@@ -182,8 +182,10 @@ class VM {
             case OP_LOAD_ELLIPSIS: frame->push(Ellipsis); break;
             case OP_LOAD_ELLIPSIS: frame->push(Ellipsis); break;
             case OP_ASSERT:
             case OP_ASSERT:
                 {
                 {
+                    PyVar _msg = frame->pop_value(this);
+                    Str msg = PyStr_AS_C(asStr(_msg));
                     PyVar expr = frame->pop_value(this);
                     PyVar expr = frame->pop_value(this);
-                    if(asBool(expr) != True) _error("AssertionError", "");
+                    if(asBool(expr) != True) _error("AssertionError", msg);
                 } break;
                 } break;
             case OP_EXCEPTION_MATCH:
             case OP_EXCEPTION_MATCH:
                 {
                 {

+ 8 - 1
tests/_exception.py

@@ -41,4 +41,11 @@ def f1():
 try:
 try:
     f1()
     f1()
 except KeyError:
 except KeyError:
-    print("PASS 04")
+    print("PASS 04")
+
+
+assert True, "Msg"
+try:
+    assert False, "Msg"
+except AssertionError:
+    print("PASS 05")