Fun 0.41.5
The programming language that makes you have fun!
Loading...
Searching...
No Matches
make_array.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 make_array.c
12 * @brief Implements the OP_MAKE_ARRAY opcode for creating arrays in the VM.
13 *
14 * This file handles the OP_MAKE_ARRAY instruction, which pops `n` values from the stack,
15 * creates an array from them, and pushes the resulting array back onto the stack.
16 *
17 * Behavior:
18 * - Validates the number of elements (`n`) to ensure it is non-negative and within stack bounds.
19 * - Allocates temporary storage for the array elements.
20 * - Constructs the array using `make_array_from_values`.
21 * - Frees temporary storage and pushes the array onto the stack.
22 *
23 * Error Handling:
24 * - Exits with an error if `n` is invalid or if memory allocation fails.
25 *
26 * Example:
27 * - Bytecode: OP_MAKE_ARRAY 3
28 * - Stack before: [1, 2, 3]
29 * - Stack after: [[1, 2, 3]]
30 */
31
33 int n = inst.operand;
34 if (n < 0 || vm->sp + 1 < n) {
35 fprintf(stderr, "Runtime error: invalid element count for MAKE_ARRAY\n");
36 exit(1);
37 }
38 /* pop n values into temp array preserving original order */
39 Value *vals = (Value *)malloc(sizeof(Value) * n);
40 if (!vals) {
41 fprintf(stderr, "Runtime error: OOM in MAKE_ARRAY\n");
42 exit(1);
43 }
44 for (int i = n - 1; i >= 0; --i) {
45 vals[i] = pop_value(vm); /* take ownership */
46 }
47 /* build array by copying values, then free originals */
49 for (int i = 0; i < n; ++i) {
50 free_value(vals[i]);
51 }
54 break;
55}
@ OP_MAKE_ARRAY
Definition bytecode.h:79
array_clear & arr
Definition clear.c:38
int n
Definition insert.c:41
push_value(vm, arr)
Value * vals
Definition make_array.c:39
free(vals)
Tagged union representing a Fun value.
Definition value.h:68
void free_value(Value v)
Free dynamic storage owned by a Value.
Definition value.c:517
Value make_array_from_values(const Value *vals, int count)
Create an array Value by copying items from an input span.
Definition value.c:142
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