Fun 0.41.5
The programming language that makes you have fun!
Loading...
Searching...
No Matches
pow.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 pow.c
12 * @brief Implements the OP_POW opcode for exponentiation in the VM.
13 *
14 * This file handles the OP_POW instruction, which computes the power of two integer values.
15 * The values are popped from the stack, and the result is pushed back.
16 *
17 * Behavior:
18 * - Pops two integer values from the stack.
19 * - Computes the power of the first value raised to the second.
20 * - Pushes the result onto the stack.
21 *
22 * Error Handling:
23 * - Exits with an error if the operands are not integers.
24 *
25 * Example:
26 * - Bytecode: OP_POW
27 * - Stack before: [2, 3]
28 * - Stack after: [8]
29 */
30
31case OP_POW: {
32 Value b = pop_value(vm);
34 if (a.type != VAL_INT || b.type != VAL_INT) {
35 fprintf(stderr, "POW expects ints\n");
36 exit(1);
37 }
38 int64_t base = a.i;
39 int64_t exp = b.i;
40 int64_t res = 1;
41 if (exp < 0) {
42 res = 0;
43 } else {
44 while (exp > 0) {
45 if (exp & 1) res *= base;
46 base *= base;
47 exp >>= 1;
48 }
49 }
53 break;
54}
Value a
Definition add.c:37
uint32_t b
Definition band.c:32
@ OP_POW
Definition bytecode.h:125
const char * res
Definition get_string.c:38
int64_t exp
Definition pow.c:39
free_value(a)
int64_t base
Definition pow.c:38
Tagged union representing a Fun value.
Definition value.h:68
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
static void push_value(VM *vm, Value v)
Push a Value onto the VM operand stack.
Definition vm.c:564
#define fprintf
Definition vm.c:200
#define exit(code)
Definition vm.c:230