/Users/alexjokela/projects/lattice/src/type_ops.c
Line | Count | Source |
1 | | #include "type_ops.h" |
2 | | #include <stdlib.h> |
3 | | #include <string.h> |
4 | | #include <errno.h> |
5 | | #include <ctype.h> |
6 | | |
7 | | /* ── to_int ── */ |
8 | | |
9 | 0 | LatValue type_to_int(const LatValue *v, char **err) { |
10 | 0 | switch (v->type) { |
11 | 0 | case VAL_INT: |
12 | 0 | return value_int(v->as.int_val); |
13 | | |
14 | 0 | case VAL_FLOAT: |
15 | 0 | return value_int((int64_t)v->as.float_val); |
16 | | |
17 | 0 | case VAL_BOOL: |
18 | 0 | return value_int(v->as.bool_val ? 1 : 0); |
19 | | |
20 | 0 | case VAL_STR: { |
21 | 0 | const char *s = v->as.str_val; |
22 | 0 | char *endptr = NULL; |
23 | 0 | errno = 0; |
24 | 0 | int64_t result = strtoll(s, &endptr, 10); |
25 | | /* skip trailing whitespace */ |
26 | 0 | while (*endptr && isspace((unsigned char)*endptr)) endptr++; |
27 | 0 | if (endptr == s || *endptr != '\0' || errno == ERANGE) { |
28 | 0 | *err = strdup("to_int(): invalid string"); |
29 | 0 | return value_unit(); |
30 | 0 | } |
31 | 0 | return value_int(result); |
32 | 0 | } |
33 | | |
34 | 0 | default: |
35 | 0 | *err = strdup("to_int(): cannot convert this type to Int"); |
36 | 0 | return value_unit(); |
37 | 0 | } |
38 | 0 | } |
39 | | |
40 | | /* ── to_float ── */ |
41 | | |
42 | 0 | LatValue type_to_float(const LatValue *v, char **err) { |
43 | 0 | switch (v->type) { |
44 | 0 | case VAL_FLOAT: |
45 | 0 | return value_float(v->as.float_val); |
46 | | |
47 | 0 | case VAL_INT: |
48 | 0 | return value_float((double)v->as.int_val); |
49 | | |
50 | 0 | case VAL_BOOL: |
51 | 0 | return value_float(v->as.bool_val ? 1.0 : 0.0); |
52 | | |
53 | 0 | case VAL_STR: { |
54 | 0 | const char *s = v->as.str_val; |
55 | 0 | char *endptr = NULL; |
56 | 0 | errno = 0; |
57 | 0 | double result = strtod(s, &endptr); |
58 | | /* skip trailing whitespace */ |
59 | 0 | while (*endptr && isspace((unsigned char)*endptr)) endptr++; |
60 | 0 | if (endptr == s || *endptr != '\0' || errno == ERANGE) { |
61 | 0 | *err = strdup("to_float(): invalid string"); |
62 | 0 | return value_unit(); |
63 | 0 | } |
64 | 0 | return value_float(result); |
65 | 0 | } |
66 | | |
67 | 0 | default: |
68 | 0 | *err = strdup("to_float(): cannot convert this type to Float"); |
69 | 0 | return value_unit(); |
70 | 0 | } |
71 | 0 | } |