Fun 0.41.5
The programming language that makes you have fun!
Loading...
Searching...
No Matches
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
33case OP_SUBSTR: {
34 Value lenv = 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);
46 break;
47}
Value out
Definition apop.c:38
@ OP_SUBSTR
Definition bytecode.h:103
Value str
Definition regex_match.c:42
Value bi_substr(const Value *str, int start, int len)
Extract a substring from a string Value.
Definition string.c:77
Tagged union representing a Fun value.
Definition value.h:68
int64_t i
Definition value.h:71
ValueType type
Definition value.h:69
Value startv
Definition substr.c:35
free_value(str)
push_value(vm, out)
@ VAL_STRING
Definition value.h:53
@ 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