Skip to content

Commit bb5992d

Browse files
committed
chore: enhance runtime errors printing, add stack trace
1 parent a403c89 commit bb5992d

1 file changed

Lines changed: 27 additions & 19 deletions

File tree

src/vm.c

Lines changed: 27 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,20 @@ static void runtime_error(const char* format, ...)
2929
va_end(args);
3030
fputs("\n", stderr);
3131

32-
CallFrame* frame = &vm.frames[vm.frame_count - 1];
33-
size_t instruction = frame->ip - frame->function->chunk.code - 1;
34-
int line = frame->function->chunk.lines[instruction];
35-
fprintf(stderr, "[Line %d] in script\n", line);
32+
for (int i = vm.frame_count - 1; i >= 0; i--)
33+
{
34+
CallFrame* frame = &vm.frames[i];
35+
ObjFunction* function = frame->function;
36+
size_t instruction = frame->ip - function->chunk.code - 1;
3637

37-
reset_stack();
38+
fprintf(stderr, "[line %d] in ", function->chunk.lines[instruction]);
39+
if (function->name == NULL)
40+
fprintf(stderr, "script\n");
41+
else
42+
43+
fprintf(stderr, "%s()\n", function->name->chars);
44+
reset_stack();
45+
}
3846
}
3947

4048
void init_VM()
@@ -79,7 +87,7 @@ static bool call(ObjFunction* function, int arg_count)
7987
if (vm.frame_count == FRAMES_MAX)
8088
{
8189
// as Java developer i hate this exception,
82-
// but sorry there no way to increase stack size here like jvm does :Joy
90+
// but sorry there no way to increase stack size here like jvm does
8391
runtime_error("Stack Overflow");
8492
return false;
8593
}
@@ -92,22 +100,22 @@ static bool call(ObjFunction* function, int arg_count)
92100

93101
static bool call_value(Value callee, int arg_count)
94102
{
95-
if (!IS_OBJ(callee))
103+
if (IS_OBJ(callee))
96104
{
97-
runtime_error("Can only call functions and classes");
98-
return false;
105+
switch (OBJ_TYPE(callee))
106+
{
107+
case OBJ_FUNCTION:
108+
{
109+
return call(AS_FUNCTION(callee), arg_count);
110+
}
111+
default:
112+
// No callable shit
113+
break;
114+
}
99115
}
100116

101-
switch (OBJ_TYPE(callee))
102-
{
103-
case OBJ_FUNCTION:
104-
{
105-
return call(AS_FUNCTION(callee), arg_count);
106-
}
107-
default:
108-
// No callable shit
109-
break;
110-
}
117+
runtime_error("Can only call functions and classes");
118+
return false;
111119
}
112120

113121
static bool is_falsey(Value value)

0 commit comments

Comments
 (0)