From 4df6d4fdb1689734064c94b3e9ee9ae8b88fab15 Mon Sep 17 00:00:00 2001 From: blueloveTH Date: Sun, 8 Oct 2023 01:36:11 +0800 Subject: [PATCH] fix a bug of `traceback` --- src/ceval.cpp | 6 ------ src/vm.cpp | 18 +++++++++++++----- tests/80_traceback.py | 8 ++++++-- 3 files changed, 19 insertions(+), 13 deletions(-) diff --git a/src/ceval.cpp b/src/ceval.cpp index e867f2cd..bd867b2b 100644 --- a/src/ceval.cpp +++ b/src/ceval.cpp @@ -760,12 +760,6 @@ __NEXT_STEP:; PK_UNUSED(e); PyObject* obj = POPX(); Exception& _e = CAST(Exception&, obj); - int actual_ip = frame->_ip; - if(_e._ip_on_error >= 0 && _e._code_on_error == (void*)frame->co) actual_ip = _e._ip_on_error; - int current_line = frame->co->lines[actual_ip]; // current line - auto current_f_name = frame->co->name.sv(); // current function name - if(frame->_callable == nullptr) current_f_name = ""; // not in a function - _e.st_push(frame->co->src->snapshot(current_line, nullptr, current_f_name)); _pop_frame(); if(callstack.empty()){ #if PK_DEBUG_FULL_EXCEPTION diff --git a/src/vm.cpp b/src/vm.cpp index 5a016938..5ee9913d 100644 --- a/src/vm.cpp +++ b/src/vm.cpp @@ -1082,13 +1082,21 @@ void VM::_error(Exception e){ } void VM::_raise(bool re_raise){ - Frame* top = top_frame().get(); + Frame* frame = top_frame().get(); + Exception& e = PK_OBJ_GET(Exception, s_data.top()); if(!re_raise){ - Exception& e = PK_OBJ_GET(Exception, s_data.top()); - e._ip_on_error = top->_ip; - e._code_on_error = (void*)top->co; + e._ip_on_error = frame->_ip; + e._code_on_error = (void*)frame->co; } - bool ok = top->jump_to_exception_handler(); + bool ok = frame->jump_to_exception_handler(); + + int actual_ip = frame->_ip; + if(e._ip_on_error >= 0 && e._code_on_error == (void*)frame->co) actual_ip = e._ip_on_error; + int current_line = frame->co->lines[actual_ip]; // current line + auto current_f_name = frame->co->name.sv(); // current function name + if(frame->_callable == nullptr) current_f_name = ""; // not in a function + e.st_push(frame->co->src->snapshot(current_line, nullptr, current_f_name)); + if(ok) throw HandledException(); else throw UnhandledException(); } diff --git a/tests/80_traceback.py b/tests/80_traceback.py index 25fbfec7..b1df66fd 100644 --- a/tests/80_traceback.py +++ b/tests/80_traceback.py @@ -6,5 +6,9 @@ try: except KeyError: s = traceback.format_exc() -assert s == r'''Traceback (most recent call last): -KeyError: 6''' \ No newline at end of file +ok = s == '''Traceback (most recent call last): + File "80_traceback.py", line 5 + b = a[6] +KeyError: 6''' + +assert ok, s \ No newline at end of file