Fun 0.41.5
The programming language that makes You have fun
Loading...
Searching...
No Matches
index_get.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
32
34 Value idx = pop_value(vm);
35 Value container = pop_value(vm);
36#ifdef FUN_DEBUG
37 fprintf(stderr, "DEBUG INDEX_GET: container.type=%d idx.type=%d\n",
38 container.type, idx.type);
39#endif
40 if (container.type == VAL_ARRAY) {
41 if (idx.type != VAL_INT) {
42 fprintf(stderr, "INDEX_GET index must be int for array\n");
43 exit(1);
44 }
45 Value elem;
46 if (!array_get_copy(&container, (int)idx.i, &elem)) {
47 fprintf(stderr, "Runtime error: index out of range\n");
48 exit(1);
49 }
52 push_value(vm, elem);
53 } else if (container.type == VAL_MAP) {
54 if (idx.type != VAL_STRING) {
55 fprintf(stderr, "INDEX_GET key must be string for map\n");
56 exit(1);
57 }
59 if (!map_get_copy(&container, idx.s ? idx.s : "", &out)) {
60 out = make_nil();
61 }
64 push_value(vm, out);
65 } else {
66 fprintf(stderr, "Runtime type error: INDEX_GET expects array or map (got container=%s, index=%s)\n",
67 value_type_name(container.type), value_type_name(idx.type));
68 exit(1);
69 }
70 break;
71}
Value out
Definition apop.c:38
@ OP_INDEX_GET
Definition bytecode.h:80
Value container
Definition index_get.c:35
int idx
Definition index_of.c:38
int map_get_copy(const Value *vm, const char *key, Value *out)
Look up a key and copy the stored value into out.
Definition map.c:112
Tagged union representing a Fun value.
Definition value.h:68
Value make_nil(void)
Construct a nil Value.
Definition value.c:126
void free_value(Value v)
Free dynamic storage owned by a Value.
Definition value.c:517
int array_get_copy(const Value *v, int index, Value *out)
Copy an array element into out.
Definition value.c:192
@ VAL_ARRAY
Definition value.h:55
@ VAL_MAP
Definition value.h:56
@ VAL_STRING
Definition value.h:53
@ VAL_INT
Definition value.h:51
#define fprintf
Definition vm.c:200
#define exit(code)
Definition vm.c:230