Commit df7954c5

df7954c5bed6Merged

Tomoyuki INOUE <[email protected]> · 6 months ago · 4 files · ~4 modified

Description

feat(codegen): restore sp_Time struct, fix Time.at dispatch

d78149b made Time.now return mrb_float so Time.now.to_f * 1000 would yield millisecond precision, but as a side effect dropped sp_Time / Time.at along with the SPINEL_TYPE_TIME entry in the type system. Reproducer:

puts Time.at(1234567890).to_i

emitted "cannot resolve call to 'at' on int" at compile time and printed 0 at runtime instead of 1234567890.

Restore sp_Time as a value-typed struct in lib/sp_runtime.h, route Time.now / Time.at(int|float) through sp_time_now / sp_time_at_int / sp_time_at_float, and inline tv_sec / tv_nsec at every Time#to_i / Time#to_f / Time#- call site. d78149b's sub-second precision is preserved because the inlined to_f expansion is exactly what the original Time.now lowering already emitted -- just hoisted behind the type system instead of returned bare.

The ecfea5d Time.now.to_i special-case becomes redundant: the new to_i lowering reads tv_sec directly, with no float roundtrip.

Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]

Details

Commit
df7954c5bed6
Parent
3b24523ba11b

lib/sp_runtime.hmodifiedView file

@@ -85,6 +85,32 @@
8585 typedef struct{mrb_int first;mrb_int last;}sp_Range;
8686 static sp_Range sp_range_new(mrb_int f,mrb_int l){sp_Range r;r.first=f;r.last=l;return r;}
8787
88+/* ---- Time runtime ---- */
89+/* sp_Time keeps Time.now / Time.at as value-typed structs. d78149b's
90+ sub-second precision is preserved by inlining tv_sec + tv_nsec/1e9
91+ at every Time#to_f / Time#- call site (see spinel_codegen.rb). */
92+typedef struct { int64_t tv_sec; int32_t tv_nsec; } sp_Time;
93+static inline sp_Time sp_time_now(void) {
94+ struct timespec ts;
95+ clock_gettime(CLOCK_REALTIME, &ts);
96+ return (sp_Time){ ts.tv_sec, (int32_t)ts.tv_nsec };
97+}
98+static inline sp_Time sp_time_at_int(mrb_int sec) {
99+ return (sp_Time){ (int64_t)sec, 0 };
100+}
101+/* POSIX convention: keep tv_nsec in [0, 1e9). For negative epoch with a
102+ non-integer fractional part, decrement tv_sec and roll the fraction
103+ into the positive nsec range — so Time.at(-0.5).to_i returns -1, not 0. */
104+static inline sp_Time sp_time_at_float(mrb_float epoch) {
105+ int64_t sec = (int64_t)epoch;
106+ mrb_float frac = epoch - (mrb_float)sec;
107+ if (frac < 0.0) {
108+ sec -= 1;
109+ frac += 1.0;
110+ }
111+ return (sp_Time){ sec, (int32_t)(frac * 1e9) };
112+}
113+
88114 typedef struct sp_gc_hdr { struct sp_gc_hdr *next; void (*finalize)(void *); void (*scan)(void *); size_t size; unsigned marked : 1; } sp_gc_hdr;
89115 static sp_gc_hdr *sp_gc_heap = NULL; static size_t sp_gc_bytes = 0; static size_t sp_gc_threshold = 256*1024;
90116