Fun 0.41.5
The programming language that makes You have fun
Loading...
Searching...
No Matches
to_number.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
33
35 Value v = pop_value(vm);
36 if (v.type == VAL_INT) {
37 push_value(vm, make_int(v.i));
39 } else if (v.type == VAL_FLOAT) {
40 double d = v.d;
41 if (d >= (double)INT64_MIN && d <= (double)INT64_MAX) {
42 int64_t ii = (int64_t)d;
43 if ((double)ii == d) {
44 push_value(vm, make_int(ii));
45 } else {
47 }
48 } else {
50 }
52 } else if (v.type == VAL_STRING) {
53 const char *s = v.s ? v.s : "";
54 const char *p = s;
55 while (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n')
56 p++;
57 char *endp = NULL;
58 /* Try float first to support decimals and scientific notation */
59 double dval = strtod(p, &endp);
60 while (endp && (*endp == ' ' || *endp == '\t' || *endp == '\r' || *endp == '\n'))
61 endp++;
62 if (!endp || *endp != '\0') {
63 /* Fallback to integer-only parse */
64 endp = NULL;
65 long long parsed = strtoll(p, &endp, 10);
66 while (endp && (*endp == ' ' || *endp == '\t' || *endp == '\r' || *endp == '\n'))
67 endp++;
68 if (endp && *endp == '\0') {
69 push_value(vm, make_int((int64_t)parsed));
70 } else {
71 push_value(vm, make_int(0));
72 }
73 } else {
74 /* Preserve int when exact; else float */
75 if (dval >= (double)INT64_MIN && dval <= (double)INT64_MAX) {
76 int64_t ii = (int64_t)dval;
77 if ((double)ii == dval) {
78 push_value(vm, make_int(ii));
79 } else {
80 push_value(vm, make_float(dval));
81 }
82 } else {
83 push_value(vm, make_float(dval));
84 }
85 }
87 } else if (v.type == VAL_BOOL) {
88 push_value(vm, make_int(v.i ? 1 : 0));
90 } else {
93 }
94 break;
95}
@ OP_TO_NUMBER
Definition bytecode.h:93
Value v
Definition cast.c:22
const char * p
Definition read_file.c:37
uint32_t s
Definition rol.c:31
Tagged union representing a Fun value.
Definition value.h:68
push_value(vm, make_int(0))
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_BOOL
Definition value.h:52
@ VAL_STRING
Definition value.h:53
@ VAL_INT
Definition value.h:51
@ VAL_FLOAT
Definition value.h:58