Fun 0.41.5
The programming language that makes you have fun!
Loading...
Searching...
No Matches
throw.c
Go to the documentation of this file.
1/*
2 * This file is part of the Fun programming language.
3 * https://fun-lang.xyz/
4 *
5 * Copyright 2025 Johannes Findeisen <you@hanez.org>
6 * Licensed under the terms of the Apache-2.0 license.
7 * https://opensource.org/license/apache-2-0
8 */
9
10/**
11 * @file throw.c
12 * @brief Implements the OP_THROW opcode for raising exceptions in the VM.
13 *
14 * This file handles the OP_THROW instruction, which raises an exception. If a
15 * matching TRY handler exists in the current frame (pushed via OP_TRY_PUSH),
16 * control flow jumps to the handler location and the error value is made
17 * available to the catch block via the stack. If no handler is present in the
18 * current frame, the error is printed and the VM terminates execution by
19 * clearing the frame stack.
20 *
21 * Behavior:
22 * - Pops the error `Value` from the stack.
23 * - If the current frame has a pending TRY handler (f->try_sp >= 0):
24 * - Retrieves the handler target IP from the TRY instruction's operand.
25 * - Pushes the error back on the stack for the catch block to consume.
26 * - Sets the instruction pointer (IP) to the handler target.
27 * - Otherwise (no handler):
28 * - Prints the error in a human-readable form.
29 * - Frees the error value and clears all frames (vm->fp = -1) to stop the VM.
30 *
31 * Errors:
32 * - None explicitly thrown here; if unhandled, the VM stops after printing the
33 * error message.
34 */
35
36case OP_THROW: {
37 Value err = pop_value(vm);
38 /* if there is a handler in this frame, jump to it and push err for catch */
39 if (f->try_sp >= 0) {
40 int try_idx = f->try_stack[f->try_sp--];
41 int target = f->fn->instructions[try_idx].operand;
42 /* push error for catch block */
43 push_value(vm, err); /* transfer ownership to stack */
44 f->ip = target;
45 break;
46 }
47 /* Unhandled: print error and terminate */
48 char *s = value_to_string_alloc(&err);
49 if (s) {
50 fprintf(stdout, "%s\n", s);
51 free(s);
52 } else {
53 fprintf(stdout, "<error>\n");
54 }
56 /* clear frames to stop execution */
57 vm->fp = -1;
58 break;
59}
@ OP_THROW
Definition bytecode.h:250
char target[32]
Definition cast.c:28
free(vals)
FILE * f
Definition read_file.c:38
uint32_t s
Definition rol.c:31
Tagged union representing a Fun value.
Definition value.h:68
free_value(err)
char * value_to_string_alloc(const Value *v)
Allocate a printable C string for a Value.
Definition value.c:641
static Value pop_value(VM *vm)
Pop a Value from the VM operand stack.
Definition vm.c:580
static void push_value(VM *vm, Value v)
Push a Value onto the VM operand stack.
Definition vm.c:564
#define fprintf
Definition vm.c:200