Fun 0.41.5
The programming language that makes you have fun!
Loading...
Searching...
No Matches
make_map.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_map.c
12 * @brief Implements the OP_MAKE_MAP opcode for creating maps in the VM.
13 *
14 * This file handles the OP_MAKE_MAP instruction, which pops `pairs` key-value pairs
15 * from the stack, creates a map from them, and pushes the resulting map back onto the stack.
16 *
17 * Behavior:
18 * - Validates the number of pairs to ensure it is non-negative.
19 * - Ensures that map keys are strings.
20 * - Constructs the map using `make_map_empty` and `map_set`.
21 * - Pushes the map onto the stack.
22 *
23 * Error Handling:
24 * - Exits with an error if the number of pairs is invalid, if keys are not strings,
25 * or if map construction fails.
26 *
27 * Example:
28 * - Bytecode: OP_MAKE_MAP 2
29 * - Stack before: ["key1", 1, "key2", 2]
30 * - Stack after: [{"key1": 1, "key2": 2}]
31 */
32
34 int pairs = inst.operand;
35 if (pairs < 0) {
36 fprintf(stderr, "MAKE_MAP invalid pair count\n");
37 exit(1);
38 }
40 for (int i = 0; i < pairs; ++i) {
41 Value val = pop_value(vm);
42 Value key = pop_value(vm);
43 if (key.type != VAL_STRING) {
44 fprintf(stderr, "Map literal keys must be strings\n");
45 exit(1);
46 }
47 if (!map_set(&m, key.s ? key.s : "", val)) {
48 fprintf(stderr, "Map literal set failed\n");
49 exit(1);
50 }
52 }
54 break;
55}
@ OP_MAKE_MAP
Definition bytecode.h:130
const char * key
Definition get_bool.c:40
Value m
Definition has_key.c:27
Value val
Definition load_local.c:36
push_value(vm, m)
int map_set(Value *vm, const char *key, Value v)
Insert or replace a key in the map.
Definition map.c:79
Value make_map_empty(void)
Construct a new empty map Value.
Definition map.c:35
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
@ VAL_STRING
Definition value.h:53
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