Fun
0.41.5
The programming language that makes you have fun!
Main Page
Data Structures
Files
File List
Globals
Loading...
Searching...
No Matches
src
vm
arrays
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
32
case
OP_SLICE
: {
33
Value
end =
pop_value
(vm);
34
Value
start
=
pop_value
(vm);
35
Value
arr
=
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
);
41
free_value
(
arr
);
42
free_value
(
start
);
43
free_value
(end);
44
push_value
(vm,
out
);
45
break
;
46
}
out
Value out
Definition
apop.c:38
OP_SLICE
@ OP_SLICE
Definition
bytecode.h:90
arr
array_clear & arr
Definition
clear.c:38
start
Value start
Definition
slice.c:34
free_value
free_value(arr)
push_value
push_value(vm, out)
Value
Tagged union representing a Fun value.
Definition
value.h:68
Value::i
int64_t i
Definition
value.h:71
Value::type
ValueType type
Definition
value.h:69
array_slice
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
@ VAL_ARRAY
Definition
value.h:55
VAL_INT
@ VAL_INT
Definition
value.h:51
pop_value
static Value pop_value(VM *vm)
Pop a Value from the VM operand stack.
Definition
vm.c:580
fprintf
#define fprintf
Definition
vm.c:200
exit
#define exit(code)
Definition
vm.c:230
Generated on
for Fun by
1.16.1