Fun 0.41.5
The programming language that makes you have fun!
Loading...
Searching...
No Matches
index_set.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 index_set.c
12 * @brief Implements the OP_INDEX_SET opcode for array and map assignment in the VM.
13 *
14 * This file handles the OP_INDEX_SET instruction, which assigns a value to an
15 * element in an array or a key in a map.
16 *
17 * Behavior:
18 * - Pops the value, index/key, and container from the stack.
19 * - For arrays, assigns the value to the specified index.
20 * - For maps, assigns the value to the specified key.
21 *
22 * Error Handling:
23 * - Exits with an error if the container is not an array or map, if the index/key
24 * is of the wrong type, or if the index is out of bounds.
25 *
26 * Example:
27 * - Bytecode: OP_INDEX_SET
28 * - Stack before: [42, 1, [10, 20, 30]]
29 * - Stack after: [[10, 42, 30]]
30 */
31
33 Value v = pop_value(vm);
36#ifdef FUN_DEBUG
37 fprintf(stderr, "DEBUG INDEX_SET: container.type=%d idx.type=%d value.type=%d\n",
38 container.type, idx.type, v.type);
39#endif
40 if (container.type == VAL_ARRAY) {
41 if (idx.type != VAL_INT) {
42 fprintf(stderr, "INDEX_SET index must be int for array\n");
43 exit(1);
44 }
45 if (!array_set(&container, (int)idx.i, v)) {
46 fprintf(stderr, "Runtime error: index out of range\n");
47 exit(1);
48 }
51 } else if (container.type == VAL_MAP) {
52 if (idx.type != VAL_STRING) {
53 fprintf(stderr, "INDEX_SET key must be string for map\n");
54 exit(1);
55 }
56 if (!map_set(&container, idx.s ? idx.s : "", v)) {
57 fprintf(stderr, "Runtime error: map set failed\n");
58 exit(1);
59 }
62 } else {
63 fprintf(stderr, "Runtime type error: INDEX_SET expects array or map\n");
64 exit(1);
65 }
66 break;
67}
@ OP_INDEX_SET
Definition bytecode.h:81
Value v
Definition cast.c:22
Value container
Definition index_get.c:35
int idx
Definition index_of.c:38
int map_set(Value *vm, const char *key, Value v)
Insert or replace a key in the map.
Definition map.c:79
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
int array_set(Value *v, int index, Value newElem)
Replace an element of an array with a new Value.
Definition value.c:210
@ VAL_ARRAY
Definition value.h:55
@ VAL_MAP
Definition value.h:56
@ VAL_STRING
Definition value.h:53
@ VAL_INT
Definition value.h:51
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