Fun 0.41.5
The programming language that makes you have fun!
Loading...
Searching...
No Matches
floor.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 floor.c
12 * @brief Implements the OP_FLOOR opcode using C99 math.h floor().
13 *
14 * VM opcode snippet included by vm.c. Provides numeric floor operation.
15 *
16 * Behavior:
17 * - Pops one numeric operand (int or float) from the stack.
18 * - Applies floor(x) in double precision.
19 * - If the result is an exact 64-bit integer, pushes VAL_INT; otherwise VAL_FLOAT.
20 *
21 * Stack effect:
22 * - Pop: x
23 * - Push: floor(x)
24 *
25 * Types:
26 * - Accepts VAL_INT and VAL_FLOAT.
27 * - Other types cause a runtime error.
28 *
29 * Errors:
30 * - Exits with an error message if the operand is not a number.
31 *
32 * Example:
33 * - Input stack: [2.9] → Output stack: [2]
34 * - Input stack: [-2.1] → Output stack: [-3]
35 */
36
37#include <math.h>
38
39case OP_FLOOR: {
40 Value v = pop_value(vm);
41 if (v.type == VAL_INT) {
42 /* floor(n) == n for integers */
43 push_value(vm, make_int(v.i));
45 } else if (v.type == VAL_FLOAT) {
46 double r = floor(v.d);
47 if (r >= (double)INT64_MIN && r <= (double)INT64_MAX) {
48 int64_t ii = (int64_t)r;
49 if ((double)ii == r) {
50 push_value(vm, make_int(ii));
51 } else {
53 }
54 } else {
56 }
58 } else {
59 fprintf(stderr, "Runtime type error: FLOOR expects number, got %s\n", value_type_name(v.type));
60 exit(1);
61 }
62 break;
63}
uint32_t r
Definition band.c:33
@ OP_FLOOR
Definition bytecode.h:253
Value v
Definition cast.c:22
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