1
0
Fork 0
forked from fun/fun

Added the Float type and many fixes. (0.24.0)

This commit is contained in:
Johannes Findeisen 2025-10-04 20:35:59 +02:00
commit 41fa946f1c
19 changed files with 432 additions and 69 deletions

View file

@ -34,22 +34,56 @@
case OP_TO_NUMBER: {
Value v = pop_value(vm);
if (v.type == VAL_INT) {
Value out = make_int(v.i);
push_value(vm, make_int(v.i));
free_value(v);
} else if (v.type == VAL_FLOAT) {
double d = v.d;
if (d >= (double)INT64_MIN && d <= (double)INT64_MAX) {
int64_t ii = (int64_t)d;
if ((double)ii == d) {
push_value(vm, make_int(ii));
} else {
push_value(vm, make_float(d));
}
} else {
push_value(vm, make_float(d));
}
free_value(v);
push_value(vm, out);
} else if (v.type == VAL_STRING) {
const char *s = v.s ? v.s : "";
const char *p = s;
while (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n') p++;
char *endp = NULL;
long long parsed = strtoll(p, &endp, 10);
/* Try float first to support decimals and scientific notation */
double dval = strtod(p, &endp);
while (endp && (*endp == ' ' || *endp == '\t' || *endp == '\r' || *endp == '\n')) endp++;
if (endp && *endp != '\0') {
push_value(vm, make_int(0));
if (!endp || *endp != '\0') {
/* Fallback to integer-only parse */
endp = NULL;
long long parsed = strtoll(p, &endp, 10);
while (endp && (*endp == ' ' || *endp == '\t' || *endp == '\r' || *endp == '\n')) endp++;
if (endp && *endp == '\0') {
push_value(vm, make_int((int64_t)parsed));
} else {
push_value(vm, make_int(0));
}
} else {
push_value(vm, make_int((int64_t)parsed));
/* Preserve int when exact; else float */
if (dval >= (double)INT64_MIN && dval <= (double)INT64_MAX) {
int64_t ii = (int64_t)dval;
if ((double)ii == dval) {
push_value(vm, make_int(ii));
} else {
push_value(vm, make_float(dval));
}
} else {
push_value(vm, make_float(dval));
}
}
free_value(v);
} else if (v.type == VAL_BOOL) {
push_value(vm, make_int(v.i ? 1 : 0));
free_value(v);
} else {
free_value(v);
push_value(vm, make_int(0));