Fun 0.41.5
The programming language that makes you have fun!
Loading...
Searching...
No Matches
eq.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 eq.c
12 * @brief Implements the OP_EQ opcode for equality comparison in the VM.
13 *
14 * This file handles the OP_EQ instruction, which checks if two values are equal.
15 * The values are popped from the stack, and the result (1 or 0) is pushed back.
16 *
17 * Behavior:
18 * - Pops two values from the stack.
19 * - Checks if the values are equal.
20 * - Pushes 1 (true) or 0 (false) onto the stack.
21 *
22 * Error Handling:
23 * - Exits with an error if the operands are of incompatible types.
24 *
25 * Example:
26 * - Bytecode: OP_EQ
27 * - Stack before: [42, 42]
28 * - Stack after: [1]
29 */
30
31case OP_EQ: {
32 Value b = pop_value(vm);
34 int eq = 0;
35 if (a.type == b.type) {
36 switch (a.type) {
37 case VAL_INT:
38 eq = (a.i == b.i);
39 break;
40 case VAL_BOOL:
41 eq = ((a.i != 0) == (b.i != 0));
42 break;
43 case VAL_STRING:
44 eq = (a.s && b.s) ? (strcmp(a.s, b.s) == 0) : (a.s == b.s);
45 break;
46 case VAL_FUNCTION:
47 eq = (a.fn == b.fn);
48 break;
49 case VAL_NIL:
50 eq = 1;
51 break;
52 default:
53 eq = 0;
54 break;
55 }
56 } else {
57 /* interop: bool vs int (0/1) */
58 if ((a.type == VAL_BOOL && b.type == VAL_INT) || (a.type == VAL_INT && b.type == VAL_BOOL)) {
59 int ai = (a.type == VAL_BOOL) ? (a.i != 0) : (a.i != 0);
60 int bi = (b.type == VAL_BOOL) ? (b.i != 0) : (b.i != 0);
61 eq = (ai == bi);
62 } else {
63 eq = 0;
64 }
65 }
69 break;
70}
Value a
Definition add.c:37
uint32_t b
Definition band.c:32
@ OP_EQ
Definition bytecode.h:53
free_value(a)
int eq
Definition eq.c:34
Tagged union representing a Fun value.
Definition value.h:68
Value make_bool(int v)
Construct a boolean Value.
Definition value.c:79
@ VAL_BOOL
Definition value.h:52
@ VAL_STRING
Definition value.h:53
@ VAL_FUNCTION
Definition value.h:54
@ VAL_NIL
Definition value.h:57
@ VAL_INT
Definition value.h:51
static Value pop_value(VM *vm)
Pop a Value from the VM operand stack.
Definition vm.c:580
static void push_value(VM *vm, Value v)
Push a Value onto the VM operand stack.
Definition vm.c:564