From bf5d027bc28c730e13ee3451b2e3c207cde15135 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Mon, 31 Aug 2026 20:48:30 +0200 Subject: [PATCH 1/5] Time: share one Method record for documented aliases (MRI 4.0.6) Time#mon, #mday, #tv_sec, #tv_usec, #tv_nsec, #gmt_offset, #gmtoff, #gmt?, #isdst, #gmtime, #getgm, #ctime and #xmlschema are documented aliases in MRI: Time.instance_method(:alias) equals Time.instance_method(:canonical). Previously each was defined with its own native body, so the reflected UnboundMethods compared unequal. Assign the canonical Method record under the alias name (as complex.go already does) so the entries are identity-equal, flipping 13 core/time rubyspec files green with no behavior change. Co-Authored-By: Claude Opus 4.8 --- internal/vm/time.go | 38 ++++++++++------------- internal/vm/time_residuals_test.go | 48 ++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 23 deletions(-) create mode 100644 internal/vm/time_residuals_test.go diff --git a/internal/vm/time.go b/internal/vm/time.go index 978c15da..9b3ce0ae 100644 --- a/internal/vm/time.go +++ b/internal/vm/time.go @@ -211,9 +211,6 @@ func (vm *VM) registerTime() { d("strftime", func(_ *VM, v object.Value, args []object.Value, _ *Proc) object.Value { return object.NewString(strftime(self(v), strArg(args[0]))) }) - d("ctime", func(_ *VM, v object.Value, _ []object.Value, _ *Proc) object.Value { - return object.NewString(strftime(self(v), "%a %b %e %H:%M:%S %Y")) - }) d("asctime", func(_ *VM, v object.Value, _ []object.Value, _ *Proc) object.Value { return object.NewString(strftime(self(v), "%a %b %e %H:%M:%S %Y")) }) @@ -224,7 +221,6 @@ func (vm *VM) registerTime() { return object.NewString(self(v).iso8601Str(int(intArgOr(args, 0)))) } d("iso8601", iso) - d("xmlschema", iso) rfc2822 := func(_ *VM, v object.Value, _ []object.Value, _ *Proc) object.Value { return object.NewString(self(v).rfc2822Str()) } @@ -242,12 +238,10 @@ func (vm *VM) registerTime() { return object.IntValue(int64(self(v).t.Month())) } d("month", monthFn) - d("mon", monthFn) dayFn := func(_ *VM, v object.Value, _ []object.Value, _ *Proc) object.Value { return object.IntValue(int64(self(v).t.Day())) } d("day", dayFn) - d("mday", dayFn) d("hour", func(_ *VM, v object.Value, _ []object.Value, _ *Proc) object.Value { return object.IntValue(int64(self(v).t.Hour())) }) @@ -277,17 +271,6 @@ func (vm *VM) registerTime() { return object.IntValue(int64(self(v).t.Weekday())) }) - // POSIX time-value accessors. - d("tv_sec", func(_ *VM, v object.Value, _ []object.Value, _ *Proc) object.Value { - return object.IntValue(self(v).t.Unix()) - }) - d("tv_usec", func(_ *VM, v object.Value, _ []object.Value, _ *Proc) object.Value { - return object.IntValue(int64(self(v).t.Nanosecond() / 1000)) - }) - d("tv_nsec", func(_ *VM, v object.Value, _ []object.Value, _ *Proc) object.Value { - return object.IntValue(int64(self(v).t.Nanosecond())) - }) - // Weekday predicates. weekdayPred := func(want stdtime.Weekday) NativeFn { return func(_ *VM, v object.Value, _ []object.Value, _ *Proc) object.Value { @@ -318,18 +301,14 @@ func (vm *VM) registerTime() { return object.IntValue(int64(off)) } d("utc_offset", offsetFn) - d("gmt_offset", offsetFn) - d("gmtoff", offsetFn) utcPred := func(_ *VM, v object.Value, _ []object.Value, _ *Proc) object.Value { return object.Bool(self(v).t.Location() == stdtime.UTC) } d("utc?", utcPred) - d("gmt?", utcPred) dstFn := func(_ *VM, v object.Value, _ []object.Value, _ *Proc) object.Value { return object.Bool(self(v).t.IsDST()) } d("dst?", dstFn) - d("isdst", dstFn) // Conversions. utc/gmtime/localtime mutate the receiver and return it (MRI); // getutc/getlocal return a new Time. @@ -338,7 +317,6 @@ func (vm *VM) registerTime() { return v } d("utc", toUTC) - d("gmtime", toUTC) d("localtime", func(_ *VM, v object.Value, args []object.Value, _ *Proc) object.Value { self(v).t = self(v).t.In(vm.localtimeLoc(args)) return v @@ -347,7 +325,6 @@ func (vm *VM) registerTime() { return &Time{t: self(v).t.UTC()} } d("getutc", getutc) - d("getgm", getutc) d("getlocal", func(_ *VM, v object.Value, args []object.Value, _ *Proc) object.Value { return &Time{t: self(v).t.In(vm.localtimeLoc(args))} }) @@ -409,6 +386,21 @@ func (vm *VM) registerTime() { d("hash", func(_ *VM, v object.Value, _ []object.Value, _ *Proc) object.Value { return object.IntValue(self(v).t.UnixNano()) }) + + // True aliases share one Method record so Time.instance_method(:mon) == + // Time.instance_method(:month), matching MRI 4.0.6 (Time#mday, #tv_sec, + // #gmt_offset, #gmtoff, #gmt?, #isdst, #gmtime, #getgm, #ctime and + // #xmlschema are all documented aliases). + for _, pair := range [][2]string{ + {"mon", "month"}, {"mday", "day"}, + {"tv_sec", "to_i"}, {"tv_usec", "usec"}, {"tv_nsec", "nsec"}, + {"gmt_offset", "utc_offset"}, {"gmtoff", "utc_offset"}, + {"gmt?", "utc?"}, {"isdst", "dst?"}, + {"gmtime", "utc"}, {"getgm", "getutc"}, + {"ctime", "asctime"}, {"xmlschema", "iso8601"}, + } { + vm.cTime.methods[pair[0]] = vm.cTime.methods[pair[1]] + } } // timeZoneKw pops a trailing keyword hash carrying in: off args, returning diff --git a/internal/vm/time_residuals_test.go b/internal/vm/time_residuals_test.go new file mode 100644 index 00000000..85788d94 --- /dev/null +++ b/internal/vm/time_residuals_test.go @@ -0,0 +1,48 @@ +package vm_test + +import "testing" + +// TestTimeAliasIdentity pins the documented Time method aliases as sharing a +// single method entry, exactly as MRI 4.0.6 does: Time.instance_method(:alias) +// == Time.instance_method(:canonical). rubyspec asserts this for #mon, #mday, +// #tv_sec, #tv_usec, #tv_nsec, #gmt_offset, #gmtoff, #gmt?, #isdst, #gmtime, +// #getgm, #ctime and #xmlschema. +func TestTimeAliasIdentity(t *testing.T) { + pairs := []struct{ a, b string }{ + {"mon", "month"}, {"mday", "day"}, + {"tv_sec", "to_i"}, {"tv_usec", "usec"}, {"tv_nsec", "nsec"}, + {"gmt_offset", "utc_offset"}, {"gmtoff", "utc_offset"}, + {"gmt?", "utc?"}, {"isdst", "dst?"}, + {"gmtime", "utc"}, {"getgm", "getutc"}, + {"ctime", "asctime"}, {"xmlschema", "iso8601"}, + } + for _, p := range pairs { + src := "p Time.instance_method(:" + p.a + ") == Time.instance_method(:" + p.b + ")" + if got := eval(t, src); got != "true\n" { + t.Errorf("alias %s->%s: got=%q want=%q", p.a, p.b, got, "true\n") + } + } +} + +// TestTimeAliasBehavior confirms the aliases still compute the right value once +// they share the canonical body (a shared record must not lose behavior). +func TestTimeAliasBehavior(t *testing.T) { + cases := []struct{ src, want string }{ + {`p Time.utc(2020, 3, 1, 12, 0, 0).mon`, "3\n"}, + {`p Time.utc(2020, 3, 5, 12, 0, 0).mday`, "5\n"}, + {`p Time.utc(2020, 3, 1, 12, 0, 0).tv_sec`, "1583064000\n"}, + {`p Time.utc(2020, 3, 1, 12, 0, 0, 123456).tv_usec`, "123456\n"}, + {`p Time.utc(2020, 3, 1, 12, 0, 0, 123456).tv_nsec`, "123456000\n"}, + {`p Time.utc(2020, 3, 1, 12, 0, 0).gmt_offset`, "0\n"}, + {`p Time.utc(2020, 3, 1, 12, 0, 0).gmtoff`, "0\n"}, + {`p Time.utc(2020, 3, 1, 12, 0, 0).gmt?`, "true\n"}, + {`p Time.utc(2020, 3, 1, 12, 0, 0).getgm.utc?`, "true\n"}, + {`p Time.utc(2020, 3, 1, 12, 0, 0).ctime`, "\"Sun Mar 1 12:00:00 2020\"\n"}, + {`p Time.utc(2020, 3, 1, 12, 0, 0).xmlschema`, "\"2020-03-01T12:00:00Z\"\n"}, + } + for _, c := range cases { + if got := eval(t, c.src); got != c.want { + t.Errorf("src=%q\n got=%q\nwant=%q", c.src, got, c.want) + } + } +} From 04e3d0442fbe236a19dc27459128535ae0350fe3 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Mon, 31 Aug 2026 21:03:19 +0200 Subject: [PATCH 2/5] Time#+/#-: preserve the receiver's timezone object across a shift MRI keeps a Time's zone through arithmetic: (t + n).zone and (t - n).zone report the zone t was built with. timeShift dropped the Ruby timezone object (zoneObj) when it built the shifted Time, so a Time.new(..., tz) lost its zone on the first +/-. Carry zoneObj onto the result, flipping the "preserves time zone" example in both core/time/plus_spec and core/time/minus_spec green (the Go location was already preserved by time.Time.Add). Co-Authored-By: Claude Opus 4.8 --- internal/vm/time.go | 10 +++++++--- internal/vm/time_residuals_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/internal/vm/time.go b/internal/vm/time.go index 9b3ce0ae..04bc4477 100644 --- a/internal/vm/time.go +++ b/internal/vm/time.go @@ -1214,7 +1214,7 @@ func roundFn(add func(z, x, y *big.Int) *big.Int, half bool) NativeFn { // timeOp implements the Time operator fast path reached from binary(): t + secs // shifts forward, t - secs shifts back, and t - other yields the Float seconds // between the two instants. A non-Time, non-numeric right operand raises via -// numFloat / timeSeconds. +// numFloat. func timeOp(op bytecode.Op, a *Time, b object.Value) object.Value { switch op { case bytecode.OpAdd: @@ -1230,10 +1230,14 @@ func timeOp(op bytecode.Op, a *Time, b object.Value) object.Value { } // timeShift shifts a Time forward by sec seconds (which may be fractional), -// preserving its location. +// preserving both its location and its Ruby timezone object so that, per MRI, +// (t + n).zone keeps the zone t was built with. func timeShift(t *Time, sec float64) object.Value { whole, ns := splitSeconds(sec) - return &Time{t: t.t.Add(stdtime.Duration(whole)*stdtime.Second + stdtime.Duration(ns)*stdtime.Nanosecond)} + return &Time{ + t: t.t.Add(stdtime.Duration(whole)*stdtime.Second + stdtime.Duration(ns)*stdtime.Nanosecond), + zoneObj: t.zoneObj, + } } // timeCmp returns -1/0/1 ordering two Times. diff --git a/internal/vm/time_residuals_test.go b/internal/vm/time_residuals_test.go index 85788d94..2ce16034 100644 --- a/internal/vm/time_residuals_test.go +++ b/internal/vm/time_residuals_test.go @@ -36,6 +36,7 @@ func TestTimeAliasBehavior(t *testing.T) { {`p Time.utc(2020, 3, 1, 12, 0, 0).gmt_offset`, "0\n"}, {`p Time.utc(2020, 3, 1, 12, 0, 0).gmtoff`, "0\n"}, {`p Time.utc(2020, 3, 1, 12, 0, 0).gmt?`, "true\n"}, + {`p Time.utc(2020, 3, 1, 12, 0, 0).isdst`, "false\n"}, {`p Time.utc(2020, 3, 1, 12, 0, 0).getgm.utc?`, "true\n"}, {`p Time.utc(2020, 3, 1, 12, 0, 0).ctime`, "\"Sun Mar 1 12:00:00 2020\"\n"}, {`p Time.utc(2020, 3, 1, 12, 0, 0).xmlschema`, "\"2020-03-01T12:00:00Z\"\n"}, @@ -46,3 +47,32 @@ func TestTimeAliasBehavior(t *testing.T) { } } } + +// TestTimeShiftPreservesZone covers timeShift: Time#+ and Time#- keep both the +// receiver's UTC-ness / fixed offset and its Ruby timezone object, as MRI does. +func TestTimeShiftPreservesZone(t *testing.T) { + cases := []struct{ src, want string }{ + // A UTC receiver stays UTC after a shift. + {`p (Time.utc(2020, 3, 1, 12, 0, 0) + 10).utc?`, "true\n"}, + {`p (Time.utc(2020, 3, 1, 12, 0, 0) - 10).utc?`, "true\n"}, + // A fixed-offset receiver keeps its offset. + {`p (Time.at(0).getlocal("+05:00") + 1).utc_offset`, "18000\n"}, + {`p (Time.at(0).getlocal("-07:00") - 1).utc_offset`, "-25200\n"}, + // A Rational shift via the explicit method call is lossless to the second. + {`p Time.at(0).+(Rational(3, 2)).usec`, "500000\n"}, + // A timezone object rides along through +/-. + {` +class TZ + def utc_to_local(t) t end + def local_to_utc(t) t end + def name; "TZ"; end +end +t = Time.new(2020, 3, 1, 12, 0, 0, TZ.new) +p [(t + 10).zone.name, (t - 10).zone.name]`, "[\"TZ\", \"TZ\"]\n"}, + } + for _, c := range cases { + if got := eval(t, c.src); got != c.want { + t.Errorf("src=%q\n got=%q\nwant=%q", c.src, got, c.want) + } + } +} From 3703c94dd1329122fd79714c1418114623bf6b52 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Mon, 31 Aug 2026 21:06:53 +0200 Subject: [PATCH 3/5] Time#strftime: add %g and %v, apply flags through alias directives Three MRI 4.0.6 strftime gaps in core/time/strftime_spec: - %g (the commercial/ISO week year modulo 100) was unhandled and passed through verbatim; add it beside %G. - %v (the VMS/Oracle date " 3-FEB-2001", an alias of %e-%^b-%Y) was missing; add it to the expansion table. - An alias/composite directive discarded the parsed flags and width, so %^h rendered "Feb" not "FEB" and %10h did not pad. Route the expansion result through applyFlags so the GNU modifiers (^ upcase, _/0 pad, - no-pad, width) compose over %h and friends. Flag-less expansions are unchanged (applyFlags is a no-op with no flags and no width), so the existing %F/%T/%D/%R/%r/%X cases keep their output. Co-Authored-By: Claude Opus 4.8 --- internal/vm/time.go | 9 ++++++++- internal/vm/time_residuals_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/internal/vm/time.go b/internal/vm/time.go index 04bc4477..413bd972 100644 --- a/internal/vm/time.go +++ b/internal/vm/time.go @@ -1292,6 +1292,7 @@ var strftimeExpand = map[byte]string{ 'T': "%H:%M:%S", 'X': "%H:%M:%S", 'h': "%b", + 'v': "%e-%^b-%Y", // VMS/Oracle date, e.g. " 3-FEB-2001" } // strftime formats a Time per Ruby's strftime directive set: flags (-_0^#), @@ -1325,7 +1326,10 @@ func strftime(t *Time, format string) string { } dir := format[j] if exp, ok := strftimeExpand[dir]; ok { - b.WriteString(strftime(t, exp)) + // A composite/alias directive expands to a sub-format; the parsed + // flags and explicit width still apply to its rendered result, so + // `%^h` upcases (%b → FEB) and `%10h` right-pads to width 10. + b.WriteString(applyFlags(strftime(t, exp), flags, 0, ' ', width)) i = j continue } @@ -1419,6 +1423,9 @@ func strftimeField(t *Time, dir byte, colons, width int) (field, bool) { case 'G': y, _ := tm.ISOWeek() return num(int64(y), 4), true + case 'g': + y, _ := tm.ISOWeek() + return num(int64(mod(y, 100)), 2), true case 'V': _, wk := tm.ISOWeek() return num(int64(wk), 2), true diff --git a/internal/vm/time_residuals_test.go b/internal/vm/time_residuals_test.go index 2ce16034..23b73627 100644 --- a/internal/vm/time_residuals_test.go +++ b/internal/vm/time_residuals_test.go @@ -48,6 +48,33 @@ func TestTimeAliasBehavior(t *testing.T) { } } +// TestTimeStrftimeDirectives covers the strftime additions: %g (two-digit +// commercial/ISO week year), %v (the VMS/Oracle date, an alias of %e-%^b-%Y), +// and the GNU flag modifiers applying through an alias directive (%^h upcases +// %b, with width and pad flags composing), all matched against MRI 4.0.6. +func TestTimeStrftimeDirectives(t *testing.T) { + // A fixed UTC instant keeps the assertions zone-independent. + base := `t = Time.utc(2001, 2, 3, 4, 5, 6); ` + cases := []struct{ src, want string }{ + {base + `p t.strftime("%g")`, "\"01\"\n"}, + {base + `p Time.utc(2000, 4, 6).strftime("%g")`, "\"00\"\n"}, + {base + `p t.strftime("%v")`, "\" 3-FEB-2001\"\n"}, + {base + `p t.strftime("%v") == t.strftime("%e-%^b-%Y")`, "true\n"}, + {base + `p t.strftime("%^h")`, "\"FEB\"\n"}, + {base + `p t.strftime("%^_5h")`, "\" FEB\"\n"}, + {base + `p t.strftime("%0^5h")`, "\"00FEB\"\n"}, + {base + `p t.strftime("%0-^5h")`, "\"FEB\"\n"}, + {base + `p t.strftime("%^ha")`, "\"FEBa\"\n"}, + {base + `p t.strftime("%10h")`, "\" Feb\"\n"}, + {base + `p t.strftime("%_010h")`, "\"0000000Feb\"\n"}, + } + for _, c := range cases { + if got := eval(t, c.src); got != c.want { + t.Errorf("src=%q\n got=%q\nwant=%q", c.src, got, c.want) + } + } +} + // TestTimeShiftPreservesZone covers timeShift: Time#+ and Time#- keep both the // receiver's UTC-ness / fixed offset and its Ruby timezone object, as MRI does. func TestTimeShiftPreservesZone(t *testing.T) { From bb617c9124368e129a558416d5ed88e0d0a2c97f Mon Sep 17 00:00:00 2001 From: tannevaled Date: Mon, 31 Aug 2026 21:18:57 +0200 Subject: [PATCH 4/5] Time: UTC "UTC" label, reverse #<=>, and #deconstruct_keys MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three MRI 4.0.6 conformance fixes in core/time: - #to_s / #inspect label a UTC instant's zone "UTC" rather than the "+0000" offset (repr), since rbgo's UTC-location Times already answer utc? true and #zone "UTC". Fixes inspect_spec (4) and to_s_spec (1), and helped _load_spec (+2). Existing unit tests that pinned the old "+0000" for Time.utc/Time.at outputs are updated to "UTC". - #<=> with a non-Time argument reverses the comparison (other <=> self) and inverts the sign, returning nil when that is nil, dispatching the sign test through the result's own #>/#< — fixes comparison_spec (5). - #deconstruct_keys(keys) is added for pattern matching: nil returns the whole field hash (year..zone), an Array returns the requested Symbol fields (ignoring non-Symbol and unknown keys), and a non-Array/non-nil argument raises TypeError — fixes deconstruct_keys_spec (7). The subsec and zone readers are factored into shared helpers it reuses. Co-Authored-By: Claude Opus 4.8 --- internal/vm/time.go | 138 +++++++++++++++++++++++---- internal/vm/time_conformance_test.go | 26 ++--- internal/vm/time_residuals_test.go | 82 +++++++++++++++- internal/vm/time_test.go | 11 ++- 4 files changed, 219 insertions(+), 38 deletions(-) diff --git a/internal/vm/time.go b/internal/vm/time.go index 413bd972..09aabbe9 100644 --- a/internal/vm/time.go +++ b/internal/vm/time.go @@ -56,15 +56,80 @@ func (t *Time) fracString() string { return "." + s } +// subsecValue renders Time#subsec: the exact fraction of a second as a Rational, +// or the Integer 0 on a whole second (MRI keeps 0 an Integer, not 0/1). +func (t *Time) subsecValue() object.Value { + ns := t.t.Nanosecond() + if ns == 0 { + return object.IntValue(0) + } + return &object.Rational{R: big.NewRat(int64(ns), 1e9)} +} + +// zoneValue renders Time#zone: the Ruby timezone object when the Time carries +// one, else the fixed/named zone abbreviation, or nil when the zone is unnamed. +func (t *Time) zoneValue() object.Value { + if z := t.zoneObj; z != nil { + return z + } + name, _ := t.t.Zone() + if name == "" { + return object.NilV + } + return object.NewString(name) +} + +// timeDeconstructKeys is the field set Time#deconstruct_keys(nil) returns, in +// MRI's order. +var timeDeconstructKeys = []string{ + "year", "month", "day", "yday", "wday", "hour", "min", "sec", "subsec", "dst", "zone", +} + +// fieldValue resolves one Time#deconstruct_keys field name to its value, with ok +// false for a name that is not a field. +func (t *Time) fieldValue(key string) (object.Value, bool) { + tm := t.t + switch key { + case "year": + return object.IntValue(int64(tm.Year())), true + case "month": + return object.IntValue(int64(tm.Month())), true + case "day": + return object.IntValue(int64(tm.Day())), true + case "yday": + return object.IntValue(int64(tm.YearDay())), true + case "wday": + return object.IntValue(int64(tm.Weekday())), true + case "hour": + return object.IntValue(int64(tm.Hour())), true + case "min": + return object.IntValue(int64(tm.Minute())), true + case "sec": + return object.IntValue(int64(tm.Second())), true + case "subsec": + return t.subsecValue(), true + case "dst": + return object.Bool(tm.IsDST()), true + case "zone": + return t.zoneValue(), true + } + return nil, false +} + // repr renders MRI's "2026-06-21 12:34:56 +0000"; when withFrac the sub-second -// fraction is included (inspect, not to_s). +// fraction is included (inspect, not to_s). A UTC instant reports the zone as +// "UTC" rather than the "+0000" offset, matching MRI's to_s / inspect. func (t *Time) repr(withFrac bool) string { base := t.t.Format("2006-01-02 15:04:05") frac := "" if withFrac { frac = t.fracString() } - return base + frac + " " + t.offsetString() + zone := t.offsetString() + if t.t.Location() == stdtime.UTC { + zone = "UTC" + } + return base + frac + " " + zone } func (t *Time) ToS() string { return t.repr(false) } @@ -258,11 +323,7 @@ func (vm *VM) registerTime() { return object.IntValue(int64(self(v).t.Nanosecond())) }) d("subsec", func(_ *VM, v object.Value, _ []object.Value, _ *Proc) object.Value { - ns := self(v).t.Nanosecond() - if ns == 0 { - return object.IntValue(0) - } - return &object.Rational{R: big.NewRat(int64(ns), 1e9)} + return self(v).subsecValue() }) d("yday", func(_ *VM, v object.Value, _ []object.Value, _ *Proc) object.Value { return object.IntValue(int64(self(v).t.YearDay())) @@ -287,14 +348,7 @@ func (vm *VM) registerTime() { // Zone queries. d("zone", func(_ *VM, v object.Value, _ []object.Value, _ *Proc) object.Value { - if z := self(v).zoneObj; z != nil { - return z - } - name, _ := self(v).t.Zone() - if name == "" { - return object.NilV - } - return object.NewString(name) + return self(v).zoneValue() }) offsetFn := func(_ *VM, v object.Value, _ []object.Value, _ *Proc) object.Value { _, off := self(v).t.Zone() @@ -351,6 +405,39 @@ func (vm *VM) registerTime() { ) }) + // deconstruct_keys(keys) backs pattern matching (MRI 4.0): nil returns the + // whole field hash; an Array returns just the requested Symbol keys that name + // a field, ignoring (not raising on) non-Symbol or unknown keys; any other + // argument raises TypeError. + d("deconstruct_keys", func(vm *VM, v object.Value, args []object.Value, _ *Proc) object.Value { + if len(args) != 1 { + raise("ArgumentError", "wrong number of arguments (given %d, expected 1)", len(args)) + } + t := self(v) + h := object.NewHash() + if object.IsNil(args[0]) { + for _, k := range timeDeconstructKeys { + val, _ := t.fieldValue(k) + h.Set(object.Symbol(k), val) + } + return h + } + arr, ok := args[0].(*object.Array) + if !ok { + raise("TypeError", "wrong argument type %s (expected Array or nil)", vm.classOf(args[0]).name) + } + for _, k := range arr.Elems { + sym, ok := k.(object.Symbol) + if !ok { + continue // a non-Symbol key is ignored, not an error + } + if val, ok := t.fieldValue(string(sym)); ok { + h.Set(sym, val) + } + } + return h + }) + // Arithmetic and ordering. d("+", func(_ *VM, v object.Value, args []object.Value, _ *Proc) object.Value { return timeOp(bytecode.OpAdd, self(v), args[0]) @@ -358,12 +445,25 @@ func (vm *VM) registerTime() { d("-", func(_ *VM, v object.Value, args []object.Value, _ *Proc) object.Value { return timeOp(bytecode.OpSub, self(v), args[0]) }) - d("<=>", func(_ *VM, v object.Value, args []object.Value, _ *Proc) object.Value { - other, ok := args[0].(*Time) - if !ok { + d("<=>", func(vm *VM, v object.Value, args []object.Value, _ *Proc) object.Value { + if other, ok := args[0].(*Time); ok { + return object.IntValue(timeCmp(self(v), other)) + } + // A non-Time argument: MRI reverses the comparison — it asks the other + // object for `other <=> self` and inverts the sign of the answer (nil + // stays nil), dispatching the sign test through the result's own #>/#<. + r := vm.send(args[0], "<=>", []object.Value{v}, nil) + if object.IsNil(r) { return object.NilV } - return object.IntValue(timeCmp(self(v), other)) + switch { + case vm.send(r, ">", []object.Value{object.IntValue(0)}, nil).Truthy(): + return object.IntValue(-1) + case vm.send(r, "<", []object.Value{object.IntValue(0)}, nil).Truthy(): + return object.IntValue(1) + default: + return object.IntValue(0) + } }) d("<", func(_ *VM, v object.Value, args []object.Value, _ *Proc) object.Value { return object.Bool(self(v).t.Before(timeArg(args[0]).t)) diff --git a/internal/vm/time_conformance_test.go b/internal/vm/time_conformance_test.go index b1e8b7bd..06421acd 100644 --- a/internal/vm/time_conformance_test.go +++ b/internal/vm/time_conformance_test.go @@ -18,13 +18,13 @@ func TestTimeConstructors(t *testing.T) { // Time.utc / Time.gm — a whole UTC instant and its parts. {`p Time.utc(2026,6,21,12,34,56).to_i`, "1782045296\n"}, {`p Time.gm(2026,6,21,12,34,56).to_i`, "1782045296\n"}, - {`puts Time.utc(2026,6,21,12,34,56)`, "2026-06-21 12:34:56 +0000\n"}, - // Defaulted trailing parts. - {`puts Time.utc(2026)`, "2026-01-01 00:00:00 +0000\n"}, - {`puts Time.utc(2026,6)`, "2026-06-01 00:00:00 +0000\n"}, - {`puts Time.utc(2026,6,21)`, "2026-06-21 00:00:00 +0000\n"}, - {`puts Time.utc(2026,6,21,12)`, "2026-06-21 12:00:00 +0000\n"}, - {`puts Time.utc(2026,6,21,12,34)`, "2026-06-21 12:34:00 +0000\n"}, + {`puts Time.utc(2026,6,21,12,34,56)`, "2026-06-21 12:34:56 UTC\n"}, + // Defaulted trailing parts. A UTC instant labels its zone "UTC" (MRI). + {`puts Time.utc(2026)`, "2026-01-01 00:00:00 UTC\n"}, + {`puts Time.utc(2026,6)`, "2026-06-01 00:00:00 UTC\n"}, + {`puts Time.utc(2026,6,21)`, "2026-06-21 00:00:00 UTC\n"}, + {`puts Time.utc(2026,6,21,12)`, "2026-06-21 12:00:00 UTC\n"}, + {`puts Time.utc(2026,6,21,12,34)`, "2026-06-21 12:34:00 UTC\n"}, // 7th arg to utc/local is microseconds (Float sub-usec allowed). {`p Time.utc(2026,6,21,12,34,56,789012.5).nsec`, "789012500\n"}, {`p Time.utc(2026,6,21,12,34,56,500).usec`, "500\n"}, @@ -32,9 +32,9 @@ func TestTimeConstructors(t *testing.T) { {`p Time.utc(2026,6.9,1).mon`, "6\n"}, {`p Time.utc(2026,6,1,5.7).hour`, "5\n"}, // Overflow normalises the way MRI (and Go) do. - {`puts Time.utc(2026,2,30)`, "2026-03-02 00:00:00 +0000\n"}, - {`puts Time.utc(2026,1,1,24)`, "2026-01-02 00:00:00 +0000\n"}, - {`puts Time.utc(2026,1,1,0,0,60)`, "2026-01-01 00:01:00 +0000\n"}, + {`puts Time.utc(2026,2,30)`, "2026-03-02 00:00:00 UTC\n"}, + {`puts Time.utc(2026,1,1,24)`, "2026-01-02 00:00:00 UTC\n"}, + {`puts Time.utc(2026,1,1,0,0,60)`, "2026-01-01 00:01:00 UTC\n"}, // Time.local / Time.mktime — local zone (assert only TZ-independent facts). {`p Time.local(2026,6,21).year`, "2026\n"}, {`p Time.mktime(2026,6,21).mon`, "6\n"}, @@ -194,9 +194,9 @@ func TestTimeStrftime(t *testing.T) { {`puts Time.utc(2026,1,1,13,0,0).strftime("%I %l %P")`, "01 1 pm\n"}, // inspect includes the sub-second fraction (trailing zeros trimmed); to_s // does not. - {base + `p t.inspect`, "\"2026-06-21 12:34:56 +0000\"\n"}, - {`p Time.utc(2026,6,21,12,34,56,789012.5).inspect`, "\"2026-06-21 12:34:56.7890125 +0000\"\n"}, - {`p Time.utc(2026,6,21,12,34,56,789012.5).to_s`, "\"2026-06-21 12:34:56 +0000\"\n"}, + {base + `p t.inspect`, "\"2026-06-21 12:34:56 UTC\"\n"}, + {`p Time.utc(2026,6,21,12,34,56,789012.5).inspect`, "\"2026-06-21 12:34:56.7890125 UTC\"\n"}, + {`p Time.utc(2026,6,21,12,34,56,789012.5).to_s`, "\"2026-06-21 12:34:56 UTC\"\n"}, // ctime / asctime. {base + `puts t.ctime`, "Sun Jun 21 12:34:56 2026\n"}, {base + `puts t.asctime`, "Sun Jun 21 12:34:56 2026\n"}, diff --git a/internal/vm/time_residuals_test.go b/internal/vm/time_residuals_test.go index 23b73627..a948d4f6 100644 --- a/internal/vm/time_residuals_test.go +++ b/internal/vm/time_residuals_test.go @@ -1,6 +1,9 @@ package vm_test -import "testing" +import ( + "strings" + "testing" +) // TestTimeAliasIdentity pins the documented Time method aliases as sharing a // single method entry, exactly as MRI 4.0.6 does: Time.instance_method(:alias) @@ -75,6 +78,83 @@ func TestTimeStrftimeDirectives(t *testing.T) { } } +// TestTimeDeconstructKeys covers Time#deconstruct_keys (MRI 4.0 pattern +// matching): nil yields the whole field hash; an Array yields the requested +// Symbol fields, ignoring non-Symbol and unknown keys; a non-Array/non-nil +// argument is a TypeError and a missing argument an ArgumentError. +func TestTimeDeconstructKeys(t *testing.T) { + cases := []struct{ src, want string }{ + {`p Time.utc(2022, 10, 5, 13, 30).deconstruct_keys(nil)`, + "{year: 2022, month: 10, day: 5, yday: 278, wday: 3, hour: 13, min: 30, sec: 0, subsec: 0, dst: false, zone: \"UTC\"}\n"}, + {`p Time.utc(2022, 10, 5, 13, 39).deconstruct_keys([:zone, :subsec])`, "{zone: \"UTC\", subsec: 0}\n"}, + {`p Time.utc(2022, 10, 5, 13, 30).deconstruct_keys([])`, "{}\n"}, + // Non-Symbol keys are ignored. + {`p Time.utc(2022, 10, 5, 13, 30).deconstruct_keys(['year', []])`, "{}\n"}, + // Unknown Symbol keys are skipped, processing continues past them. + {`p Time.utc(2022, 10, 5, 13, 30).deconstruct_keys([:year, :a, :month, :b, :day])`, "{year: 2022, month: 10, day: 5}\n"}, + // A sub-second time reports a Rational subsec. + {`p Time.utc(2022, 10, 5, 13, 30, 0, 500000).deconstruct_keys([:subsec])`, "{subsec: (1/2)}\n"}, + } + for _, c := range cases { + if got := eval(t, c.src); got != c.want { + t.Errorf("src=%q\n got=%q\nwant=%q", c.src, got, c.want) + } + } + errCases := []struct{ src, want string }{ + {`Time.utc(2022, 10, 5).deconstruct_keys`, "ArgumentError"}, + {`Time.utc(2022, 10, 5).deconstruct_keys(1)`, "TypeError"}, + {`Time.utc(2022, 10, 5).deconstruct_keys("x")`, "TypeError"}, + {`Time.utc(2022, 10, 5).deconstruct_keys(:x)`, "TypeError"}, + } + for _, c := range errCases { + err := runErr(t, c.src) + if err == nil || !strings.Contains(err.Error(), c.want) { + t.Errorf("src=%q: got err=%v, want containing %q", c.src, err, c.want) + } + } +} + +// TestTimeInspectUTCZone covers repr: a UTC-location Time labels its zone "UTC" +// (not the "+0000" offset) in both #to_s and #inspect, while a fixed-offset Time +// keeps the numeric offset — matching MRI 4.0.6. +func TestTimeInspectUTCZone(t *testing.T) { + cases := []struct{ src, want string }{ + {`p Time.utc(2000, 1, 1, 20, 15, 1).to_s`, "\"2000-01-01 20:15:01 UTC\"\n"}, + {`p Time.utc(2000, 1, 1, 20, 15, 1).inspect`, "\"2000-01-01 20:15:01 UTC\"\n"}, + {`p Time.utc(2007, 11, 1, 15, 25, 0, 123456).inspect`, "\"2007-11-01 15:25:00.123456 UTC\"\n"}, + // A fixed-offset instant keeps its numeric offset in both forms. + {`p Time.at(0).getlocal("+00:00").to_s`, "\"1970-01-01 00:00:00 +0000\"\n"}, + {`p Time.at(0).getlocal("+05:30").inspect`, "\"1970-01-01 05:30:00 +0530\"\n"}, + } + for _, c := range cases { + if got := eval(t, c.src); got != c.want { + t.Errorf("src=%q\n got=%q\nwant=%q", c.src, got, c.want) + } + } +} + +// TestTimeSpaceshipNonTime covers Time#<=> with a non-Time argument: MRI reverses +// the comparison (other <=> self) and inverts the sign, returning nil when that +// yields nil. +func TestTimeSpaceshipNonTime(t *testing.T) { + cases := []struct{ src, want string }{ + // A Comparable-ish object whose reverse <=> is positive/negative/zero. + {` +class C + def initialize(r) @r = r end + def <=>(o) @r end +end +t = Time.utc(2020, 1, 1) +p [t <=> C.new(1), t <=> C.new(-1), t <=> C.new(0), t <=> C.new(nil)]`, + "[-1, 1, 0, nil]\n"}, + } + for _, c := range cases { + if got := eval(t, c.src); got != c.want { + t.Errorf("src=%q\n got=%q\nwant=%q", c.src, got, c.want) + } + } +} + // TestTimeShiftPreservesZone covers timeShift: Time#+ and Time#- keep both the // receiver's UTC-ness / fixed offset and its Ruby timezone object, as MRI does. func TestTimeShiftPreservesZone(t *testing.T) { diff --git a/internal/vm/time_test.go b/internal/vm/time_test.go index 3a2e9ad9..3fe32099 100644 --- a/internal/vm/time_test.go +++ b/internal/vm/time_test.go @@ -16,11 +16,12 @@ func TestTime(t *testing.T) { {`p Time.at(1000).to_i`, "1000\n"}, {`p Time.at(1000.9).to_i`, "1000\n"}, // Float seconds truncate {`p Time.at(0).to_f`, "0.0\n"}, - // to_s / inspect (RFC-ish, UTC offset). - {`puts Time.at(0)`, "1970-01-01 00:00:00 +0000\n"}, - {`p Time.at(0).to_s`, "\"1970-01-01 00:00:00 +0000\"\n"}, - {`p Time.at(0).inspect`, "\"1970-01-01 00:00:00 +0000\"\n"}, - {`p [Time.at(0)]`, "[1970-01-01 00:00:00 +0000]\n"}, // Go-level Inspect, via Array#inspect + // to_s / inspect. rbgo's Time.at is a deterministic UTC instant (utc? is + // true, #zone is "UTC"), so MRI labels the zone "UTC", not "+0000". + {`puts Time.at(0)`, "1970-01-01 00:00:00 UTC\n"}, + {`p Time.at(0).to_s`, "\"1970-01-01 00:00:00 UTC\"\n"}, + {`p Time.at(0).inspect`, "\"1970-01-01 00:00:00 UTC\"\n"}, + {`p [Time.at(0)]`, "[1970-01-01 00:00:00 UTC]\n"}, // Go-level Inspect, via Array#inspect // strftime. {`puts Time.at(0).strftime("%Y-%m-%d %H:%M:%S")`, "1970-01-01 00:00:00\n"}, {`puts Time.at(0).strftime("%Y/%m/%d")`, "1970/01/01\n"}, From 494a6724923e82faef73b0f164e24b0511843886 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Mon, 31 Aug 2026 21:32:14 +0200 Subject: [PATCH 5/5] test: update drytypes/mysql UTC Time expectations to the "UTC" label Follow-up to the repr change: TestDryFromGo (dry-types Go time.Time conversion) and TestMySQLValueTypes (MySQL DATETIME value) each render a UTC-location Time, whose #to_s / #inspect now labels the zone "UTC" rather than "+0000", matching MRI. These are the only two non-time_* test files that print a UTC Time; the remaining "+0000" occurrences in the suite are rfc2822/input strings and Date#rfc2822 output, unaffected. Co-Authored-By: Claude Opus 4.8 --- internal/vm/drytypes_test.go | 2 +- internal/vm/mysql_test.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/vm/drytypes_test.go b/internal/vm/drytypes_test.go index 73c24ac9..7febbfe9 100644 --- a/internal/vm/drytypes_test.go +++ b/internal/vm/drytypes_test.go @@ -219,7 +219,7 @@ func TestDryFromGo(t *testing.T) { check(drytypes.Symbol("s"), ":s") check([]any{int64(1)}, "[1]") check(drytypes.Date{Year: 2026, Month: 6, Day: 30}, "\"2026-06-30\"") - check(stdtime.Unix(1_700_000_000, 0), "2023-11-14 22:13:20 +0000") + check(stdtime.Unix(1_700_000_000, 0), "2023-11-14 22:13:20 UTC") check(drytypes.Undefined, "nil") // An unmapped value falls through to nil. check(struct{}{}, "nil") diff --git a/internal/vm/mysql_test.go b/internal/vm/mysql_test.go index 73654287..01ad560f 100644 --- a/internal/vm/mysql_test.go +++ b/internal/vm/mysql_test.go @@ -133,7 +133,7 @@ p row["nb"]` "1", "18446744073709551615", "2.5", "BigDecimal", `"0.314e1"`, "Date", `"2026-01-02"`, - "Time", `"2026-01-02 03:04:05 +0000"`, + "Time", `"2026-01-02 03:04:05 UTC"`, `"10:20:30"`, `"hi"`, `"AB"`, "nil", }, "\n") + "\n" if got := eval(t, mysqlSrc(port, body)); got != want {