Fun 0.41.5
The programming language that makes you have fun!
Loading...
Searching...
No Matches
call.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 call.c
12 * @brief Implements the OP_CALL opcode for function calls in the VM.
13 *
14 * This file handles the OP_CALL instruction, which calls a function with arguments.
15 *
16 * Behavior:
17 * - operand specifies number of arguments
18 * - Pops args and function from stack
19 * - Creates new frame with args in locals
20 * - Sets IP to start of function
21 *
22 * Error Handling:
23 * - Exits with error if not enough args
24 * - Exits if function isn't callable
25 */
26
27case OP_CALL: {
28 int argc = inst.operand;
29 if (argc < 0) argc = 0;
30 /* collect args in reverse (preserve order) */
31 Value *args = NULL;
32 if (argc > 0) {
33 args = (Value *)malloc(sizeof(Value) * argc);
34 /* pop args into array in reverse */
35 for (int i = argc - 1; i >= 0; --i) {
36 args[i] = pop_value(vm);
37 }
38 }
39 /* pop function value */
41 if (fnv.type != VAL_FUNCTION) {
42 fprintf(stderr, "Runtime type error: CALL expects function\n");
43 exit(1);
44 }
45 /* push new frame and transfer args */
46 vm_push_frame(vm, fnv.fn, argc, args);
47 /* free args array (locals moved), free fnv (no-op for function) */
49 /* note: fnv contains a pointer to the Bytecode, don't free here */
50 break;
51}
@ OP_CALL
Definition bytecode.h:60
Value * args
Definition call.c:31
Value fnv
Definition call.c:40
free(args)
vm_push_frame(vm, fnv.fn, argc, args)
Tagged union representing a Fun value.
Definition value.h:68
@ VAL_FUNCTION
Definition value.h:54
static Value pop_value(VM *vm)
Pop a Value from the VM operand stack.
Definition vm.c:580
#define fprintf
Definition vm.c:200
#define exit(code)
Definition vm.c:230