Fun 0.41.5
The programming language that makes you have fun!
Loading...
Searching...
No Matches
slice.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 slice.c
12 * @brief Implements the OP_SLICE opcode for array slicing in the VM.
13 *
14 * This file handles the OP_SLICE instruction, which creates a new array containing
15 * elements from the original array between specified start and end indices.
16 *
17 * Behavior:
18 * - Pops end index, start index, and array from the stack
19 * - Creates a new array containing elements from start to end-1
20 * - Pushes the new array onto the stack
21 *
22 * Error Handling:
23 * - Exits with error if arguments are wrong types
24 * - Handles negative indices and out-of-bounds cases gracefully
25 *
26 * Example:
27 * - Bytecode: OP_SLICE
28 * - Stack before: [3, 1, [10,20,30,40]]
29 * - Stack after: [[20,30]]
30 */
31
32case OP_SLICE: {
33 Value end = pop_value(vm);
36 if (arr.type != VAL_ARRAY || start.type != VAL_INT || end.type != VAL_INT) {
37 fprintf(stderr, "Runtime type error: SLICE expects (array, int, int)\n");
38 exit(1);
39 }
40 Value out = array_slice(&arr, (int)start.i, (int)end.i);
45 break;
46}
Value out
Definition apop.c:38
@ OP_SLICE
Definition bytecode.h:90
array_clear & arr
Definition clear.c:38
Value start
Definition slice.c:34
free_value(arr)
push_value(vm, out)
Tagged union representing a Fun value.
Definition value.h:68
int64_t i
Definition value.h:71
ValueType type
Definition value.h:69
Value array_slice(const Value *v, int start, int end)
Create a shallow-copied slice of an array Value.
Definition value.c:362
@ VAL_ARRAY
Definition value.h:55
@ 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