Fun 0.41.5
The programming language that makes you have fun!
Loading...
Searching...
No Matches
sqrt.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 2026 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 sqrt.c
12 * @brief Implements the OP_SQRT opcode using C99 math.h sqrt().
13 *
14 * Behavior:
15 * - Pops one numeric operand (int or float).
16 * - If x < 0, pushes NaN; else pushes sqrt(x).
17 * - Returns VAL_INT when the result fits exactly in int64, otherwise VAL_FLOAT.
18 *
19 * Stack effect:
20 * - Pop: x
21 * - Push: sqrt(x) | NaN
22 */
23
24#include <math.h>
25
26case OP_SQRT: {
27 Value v = pop_value(vm);
28 if (v.type == VAL_INT || v.type == VAL_FLOAT) {
29 double x = (v.type == VAL_FLOAT) ? v.d : (double)v.i;
30 if (x < 0.0) {
31 push_value(vm, make_float(NAN));
32 } else {
33 double r = sqrt(x);
34 /* preserve int if exactly integral */
35 if (r >= (double)INT64_MIN && r <= (double)INT64_MAX) {
36 int64_t ii = (int64_t)r;
37 if ((double)ii == r) {
38 push_value(vm, make_int(ii));
39 } else {
41 }
42 } else {
44 }
45 }
47 } else {
48 fprintf(stderr, "Runtime type error: SQRT expects number, got %s\n", value_type_name(v.type));
49 exit(1);
50 }
51 break;
52}
uint32_t r
Definition band.c:33
@ OP_SQRT
Definition bytecode.h:265
Value v
Definition cast.c:22
Value x
Definition clamp.c:29
Tagged union representing a Fun value.
Definition value.h:68
void free_value(Value v)
Free dynamic storage owned by a Value.
Definition value.c:517
Value make_float(double v)
Construct a Value representing a double-precision float.
Definition value.c:64
Value make_int(int64_t v)
Construct a Value representing a 64-bit integer.
Definition value.c:51
@ VAL_INT
Definition value.h:51
@ VAL_FLOAT
Definition value.h:58
static Value pop_value(VM *vm)
Pop a Value from the VM operand stack.
Definition vm.c:580
static const char * value_type_name(ValueType t)
Get a human-readable name for a ValueType.
Definition vm.c:318
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