Skip to content

Commit

Permalink
Add debug.caller() (#390)
Browse files Browse the repository at this point in the history
* Add `debug.caller()`

* fix non-precompiled
  • Loading branch information
s-hadinger committed Jan 24, 2024
1 parent 0768dac commit 6152b0b
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
23 changes: 23 additions & 0 deletions src/be_debuglib.c
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
#include "be_debug.h"
#include "be_map.h"
#include "be_vm.h"
#include "be_exec.h"
#include <string.h>

#if BE_USE_DEBUG_MODULE
Expand Down Expand Up @@ -103,6 +104,26 @@ static int m_traceback(bvm *vm)
be_return_nil(vm);
}

static int m_caller(bvm *vm)
{
int depth = 1;
if (be_top(vm) >= 1 && be_isint(vm, 1)) {
depth = be_toint(vm, 1);
if (depth < 0) {
depth = -depth; /* take absolute value */
}
}
bcallframe *cf = (bcallframe*)be_stack_top(&vm->callstack) - depth;
bcallframe *base = be_stack_base(&vm->callstack);
if (cf >= base) {
bvalue *reg = be_incrtop(vm);
var_setval(reg, cf->func);
be_return(vm);
} else {
be_return_nil(vm);
}
}

#if BE_USE_DEBUG_HOOK
static int m_sethook(bvm *vm)
{
Expand Down Expand Up @@ -236,6 +257,7 @@ be_native_module_attr_table(debug) {
be_native_module_function("varname", m_varname),
be_native_module_function("upvname", m_upvname)
#endif
be_native_module_function("caller", m_caller),
be_native_module_function("gcdebug", m_gcdebug)
};

Expand All @@ -252,6 +274,7 @@ module debug (scope: global, depend: BE_USE_DEBUG_MODULE) {
top, func(m_top)
varname, func(m_varname), BE_DEBUG_VAR_INFO
upvname, func(m_upvname), BE_DEBUG_VAR_INFO
caller, func(m_caller)
// individual counters
allocs, func(m_allocs)
frees, func(m_frees)
Expand Down
27 changes: 26 additions & 1 deletion tests/debug.be
Original file line number Diff line number Diff line change
@@ -1,4 +1,29 @@
import debug

class A end
debug.attrdump(A) #- should not crash -#
debug.attrdump(A) #- should not crash -#

# debug.caller()
def caller_name_chain()
import debug
import introspect
var i = 1
var ret = []
var caller = debug.caller(i)
while caller
ret.push(introspect.name(caller))
i += 1
caller = debug.caller(i)
end
return ret
end
var chain = caller_name_chain()
assert(chain[0] == 'caller_name_chain')

def guess_my_name__()
return caller_name_chain()
end
chain = guess_my_name__()
print(chain)
assert(chain[0] == 'caller_name_chain')
assert(chain[1] == 'guess_my_name__')

0 comments on commit 6152b0b

Please sign in to comment.