Skip to content

Commit 32a63ca

Browse files
gh-155: Make THROW concatenate args.
Fix tests passing/throw-empty-message.pre.
1 parent b0957d7 commit 32a63ca

2 files changed

Lines changed: 50 additions & 6 deletions

File tree

src/builtins.c

Lines changed: 48 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6226,12 +6226,56 @@ static Value builtin_assert(Interpreter* interp, Value* args, int argc, Expr** a
62266226
static Value builtin_throw(Interpreter* interp, Value* args, int argc, Expr** arg_nodes, Env* env, int line, int col) {
62276227
(void)arg_nodes; (void)env;
62286228

6229-
if (argc >= 1) {
6230-
if (args[0].type == VAL_STR) {
6231-
RUNTIME_ERROR(interp, args[0].as.s, line, col);
6229+
if (argc == 0) {
6230+
RUNTIME_ERROR(interp, "Exception thrown", line, col);
6231+
}
6232+
6233+
/* Build error message by concatenating rendered args (same rules as PRINT),
6234+
* but do not append a trailing newline. Ownership of the resulting buffer
6235+
* is transferred to interp->error (it will be freed by interpreter cleanup).
6236+
*/
6237+
JsonBuf jb;
6238+
jb_init(&jb);
6239+
6240+
for (int i = 0; i < argc; i++) {
6241+
switch (args[i].type) {
6242+
case VAL_BOOL:
6243+
jb_append_str(&jb, args[i].as.boolean ? "TRUE" : "FALSE");
6244+
break;
6245+
case VAL_INT: {
6246+
char* s = int_to_base_prefixed_str(args[i].as.i, numeric_base_of(args[i]));
6247+
jb_append_str(&jb, s);
6248+
free(s);
6249+
break;
6250+
}
6251+
case VAL_FLT: {
6252+
char* s = flt_to_base_prefixed_str(args[i].as.f, numeric_base_of(args[i]), args[i].num_base_nan);
6253+
jb_append_str(&jb, s);
6254+
free(s);
6255+
break;
6256+
}
6257+
case VAL_STR:
6258+
jb_append_str(&jb, args[i].as.s ? args[i].as.s : "");
6259+
break;
6260+
case VAL_FUNC:
6261+
jb_append_fmt(&jb, "<func %p>", (void*)args[i].as.func);
6262+
break;
6263+
default:
6264+
jb_append_str(&jb, "<null>");
6265+
break;
62326266
}
62336267
}
6234-
RUNTIME_ERROR(interp, "Exception thrown", line, col);
6268+
6269+
if (jb.data && jb.len > 0) {
6270+
/* Transfer ownership of jb.data to interp->error */
6271+
interp->error = jb.data;
6272+
} else {
6273+
if (jb.data) free(jb.data);
6274+
interp->error = strdup("Exception thrown");
6275+
}
6276+
interp->error_line = line;
6277+
interp->error_col = col;
6278+
return value_null();
62356279
}
62366280

62376281
// ============ Type checking ============

tests/cases/passing/throw-empty-message.pre

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@ TRY{
44
THROW('')
55
} CATCH(err) {
66
caught = TRUE
7-
ASSERT(EQ(err, ''))
8-
ASSERT(EQ(SLEN(err), 0d0))
7+
ASSERT(EQ(err, 'Exception thrown'))
8+
ASSERT(EQ(SLEN(err), 0d16))
99
}
1010

1111
ASSERT(caught)

0 commit comments

Comments
 (0)