Fun 0.41.5
The programming language that makes you have fun!
Loading...
Searching...
No Matches
len.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 len.c
12 * @brief Implements the OP_LEN opcode for getting the length of arrays or strings in the VM.
13 *
14 * This file handles the OP_LEN instruction, which retrieves the length of an array or string.
15 * The array or string is popped from the stack, and the length is pushed back.
16 *
17 * Behavior:
18 * - Pops the array or string from the stack.
19 * - Retrieves the length of the array or string.
20 * - Pushes the length onto the stack.
21 *
22 * Error Handling:
23 * - Exits with an error if the operand is not an array or string.
24 *
25 * Example:
26 * - Bytecode: OP_LEN
27 * - Stack before: ["hello"]
28 * - Stack after: [5]
29 */
30
31case OP_LEN: {
32 Value a = pop_value(vm);
33 int len = 0;
34 if (a.type == VAL_STRING) {
35 len = (int)(a.s ? (int)strlen(a.s) : 0);
36 } else if (a.type == VAL_ARRAY) {
37 len = array_length(&a);
38 if (len < 0) len = 0;
39 } else {
40 /* Be lenient: for non-array/non-string, treat length as 0 */
41 push_value(vm, make_int(0));
42 }
45 break;
46}
Value a
Definition add.c:37
@ OP_LEN
Definition bytecode.h:84
size_t len
Definition input_line.c:102
free_value(a)
push_value(vm, make_int(len))
Tagged union representing a Fun value.
Definition value.h:68
int array_length(const Value *v)
Get the element count of an array Value.
Definition value.c:176
Value make_int(int64_t v)
Construct a Value representing a 64-bit integer.
Definition value.c:51
@ VAL_ARRAY
Definition value.h:55
@ VAL_STRING
Definition value.h:53
static Value pop_value(VM *vm)
Pop a Value from the VM operand stack.
Definition vm.c:580