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
strings
substr.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 substr.c
12
* @brief Implements the OP_SUBSTR opcode for extracting substrings in the VM.
13
*
14
* This file handles the OP_SUBSTR instruction, which extracts a substring from a string
15
* using a start index and length. The length, start index, and string are popped from the stack,
16
* and the resulting substring is pushed back.
17
*
18
* Behavior:
19
* - Pops the length, start index, and string from the stack.
20
* - Extracts the substring from the string.
21
* - Pushes the resulting substring onto the stack.
22
*
23
* Error Handling:
24
* - Exits with an error if the operands are not integers or strings.
25
* - Exits with an error if the start index or length is out of bounds.
26
*
27
* Example:
28
* - Bytecode: OP_SUBSTR
29
* - Stack before: [5, 6, "hello world"]
30
* - Stack after: ["world"]
31
*/
32
33
case
OP_SUBSTR
: {
34
Value
lenv =
pop_value
(vm);
35
Value
startv
=
pop_value
(vm);
36
Value
str
=
pop_value
(vm);
37
if
(
str
.type !=
VAL_STRING
||
startv
.type !=
VAL_INT
|| lenv.
type
!=
VAL_INT
) {
38
fprintf
(stderr,
"Runtime type error: SUBSTR expects (string, int, int)\n"
);
39
exit
(1);
40
}
41
Value
out
=
bi_substr
(&
str
, (
int
)
startv
.i, (
int
)lenv.
i
);
42
free_value
(
str
);
43
free_value
(
startv
);
44
free_value
(lenv);
45
push_value
(vm,
out
);
46
break
;
47
}
out
Value out
Definition
apop.c:38
OP_SUBSTR
@ OP_SUBSTR
Definition
bytecode.h:103
str
Value str
Definition
regex_match.c:42
bi_substr
Value bi_substr(const Value *str, int start, int len)
Extract a substring from a string Value.
Definition
string.c:77
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
startv
Value startv
Definition
substr.c:35
free_value
free_value(str)
push_value
push_value(vm, out)
VAL_STRING
@ VAL_STRING
Definition
value.h:53
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