Fun 0.41.5
The programming language that makes you have fun!
Loading...
Searching...
No Matches
random_int.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 random_int.c
12 * @brief Implements the OP_RANDOM_INT opcode for generating random integers in the VM.
13 *
14 * This file handles the OP_RANDOM_INT instruction, which generates a random integer
15 * within a specified range. The range bounds are popped from the stack, and the result
16 * is pushed back.
17 *
18 * Behavior:
19 * - Pops the upper and lower bounds from the stack.
20 * - Generates a random integer within the range.
21 * - Pushes the result onto the stack.
22 *
23 * Error Handling:
24 * - Exits with an error if the bounds are not integers.
25 * - Exits with an error if the lower bound is greater than the upper bound.
26 *
27 * Example:
28 * - Bytecode: OP_RANDOM_INT
29 * - Stack before: [10, 1]
30 * - Stack after: [7]
31 */
32
34 Value hi = pop_value(vm);
36 if (lo.type != VAL_INT || hi.type != VAL_INT) {
37 fprintf(stderr, "RANDOM_INT expects (int, int)\n");
38 exit(1);
39 }
40 int64_t a = lo.i, b = hi.i;
41 if (b <= a) {
42 push_value(vm, make_int((int64_t)a));
44 free_value(hi);
45 break;
46 }
47 int64_t span = b - a;
48 int64_t r = (int64_t)(rand() % (span));
52 break;
53}
Value a
Definition add.c:37
uint32_t b
Definition band.c:32
uint32_t r
Definition band.c:33
@ OP_RANDOM_INT
Definition bytecode.h:127
Value lo
Definition clamp.c:28
int64_t span
Definition random_int.c:47
free_value(lo)
push_value(vm, make_int(a+r))
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