Fun 0.41.5
The programming language that makes you have fun!
Loading...
Searching...
No Matches
clamp.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 clamp.c
12 * @brief Implements the OP_CLAMP opcode for value clamping in the VM.
13 *
14 * This file handles the OP_CLAMP instruction, which clamps a value between
15 * a minimum and maximum.
16 *
17 * Behavior:
18 * - Pops x, lo, hi from stack
19 * - Pushes x clamped to [lo,hi]
20 *
21 * Error Handling:
22 * - Exits if arguments wrong types
23 * - Handles hi < lo case
24 */
25
26case OP_CLAMP: {
27 Value hi = pop_value(vm);
30 if (x.type != VAL_INT || lo.type != VAL_INT || hi.type != VAL_INT) {
31 fprintf(stderr, "CLAMP expects ints\n");
32 exit(1);
33 }
34 int64_t v = x.i;
35 if (v < lo.i) v = lo.i;
36 if (v > hi.i) v = hi.i;
41 break;
42}
@ OP_CLAMP
Definition bytecode.h:123
Value v
Definition cast.c:22
Value x
Definition clamp.c:29
free_value(x)
Value lo
Definition clamp.c:28
push_value(vm, make_int(v))
Tagged union representing a Fun value.
Definition value.h:68
int64_t i
Definition value.h:71
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_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