Fun 0.41.5
The programming language that makes you have fun!
Loading...
Searching...
No Matches
find.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 find.c
12 * @brief Implements the OP_FIND opcode for finding substrings in the VM.
13 *
14 * This file handles the OP_FIND instruction, which finds the index of a substring
15 * within a string. The substring and string are popped from the stack, and the index
16 * (or -1) is pushed back.
17 *
18 * Behavior:
19 * - Pops the substring and string from the stack.
20 * - Finds the index of the substring within the string.
21 * - Pushes the index (or -1 if not found) onto the stack.
22 *
23 * Error Handling:
24 * - Exits with an error if the operands are not strings.
25 *
26 * Example:
27 * - Bytecode: OP_FIND
28 * - Stack before: ["world", "hello world"]
29 * - Stack after: [6]
30 */
31
32case OP_FIND: {
33 Value needle = pop_value(vm);
35 if (hay.type != VAL_STRING || needle.type != VAL_STRING) {
36 fprintf(stderr, "Runtime type error: FIND expects (string, string)\n");
37 exit(1);
38 }
39 int idx = bi_find(&hay, &needle);
41 free_value(needle);
43 break;
44}
@ OP_FIND
Definition bytecode.h:104
push_value(vm, make_int(idx))
free_value(hay)
Value hay
Definition find.c:34
int idx
Definition index_of.c:38
int bi_find(const Value *hay, const Value *needle)
Find the first occurrence of a needle inside a haystack string.
Definition string.c:96
Tagged union representing a Fun value.
Definition value.h:68
ValueType type
Definition value.h:69
Value make_int(int64_t v)
Construct a Value representing a 64-bit integer.
Definition value.c:51
@ VAL_STRING
Definition value.h:53
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