diff --git a/internal/vm/arith.go b/internal/vm/arith.go index 258a59d7..793954b1 100644 --- a/internal/vm/arith.go +++ b/internal/vm/arith.go @@ -90,10 +90,11 @@ func binary(op bytecode.Op, a, b object.Value) object.Value { return matrixOp(op, a, b) } - // Time arithmetic: t + secs / t - secs (shift by a Duration) and t - other - // (the seconds between two instants) reach the operator fast path. - if at, ok := a.(*Time); ok { - return timeOp(op, at, b) + // Time reaches the VM-less path only for an operator other than + / - (those + // are intercepted in binaryOp, which has the VM needed for MRI's num_exact + // coercion). Every other arithmetic operator on a Time is undefined. + if _, ok := a.(*Time); ok { + return raise("NoMethodError", "undefined method '%s' for an instance of Time", arithOpName(op)) } // Date arithmetic: d + n / d - n (shift by a whole number of days) and @@ -399,6 +400,14 @@ func (vm *VM) binaryOp(op bytecode.Op, a, b object.Value) object.Value { if _, isSB := a.(*SafeBufferVal); isSB { return vm.send(a, arithOpName(op), []object.Value{b}, nil) } + // Time arithmetic (t + n / t - n, and t - other) needs a live VM: MRI's + // num_exact coercion of the shift amount (Integer/Rational kept exact, a + // Float taken through its exact #to_r, any other object via #to_r, while a + // String or nil is rejected) and the nanosecond-exact result both require + // dispatch the VM-less binary path cannot do. + if at, ok := a.(*Time); ok && (op == bytecode.OpAdd || op == bytecode.OpSub) { + return vm.timeArith(op, at, b) + } // Numeric coercion protocol: when a built-in number is combined with a // non-numeric object that answers #coerce, MRI calls other.coerce(self) // — expecting a [a2, b2] pair of same-type numbers — then re-runs the diff --git a/internal/vm/file_ops_internal_test.go b/internal/vm/file_ops_internal_test.go index 707c0101..895af2c9 100644 --- a/internal/vm/file_ops_internal_test.go +++ b/internal/vm/file_ops_internal_test.go @@ -27,9 +27,11 @@ func TestFileMetaOps(t *testing.T) { cases := []struct{ src, want string }{ // chmod returns the number of paths; multiple paths sum. {`p File.chmod(0o600, "` + f + `")`, "1\n"}, - // utime returns the count; accepts a Time and an Integer second count. + // utime returns the count; accepts a Time, and Integer/Float/Rational + // second counts (each coerced to whole Unix seconds). {`p File.utime(Time.now, Time.now, "` + f + `")`, "1\n"}, {`p File.utime(0, 0, "` + f + `")`, "1\n"}, + {`p File.utime(Rational(3, 2), 2.0, "` + f + `")`, "1\n"}, // chown with nil ids leaves them unchanged and still reports the count. {`p File.chown(nil, nil, "` + f + `")`, "1\n"}, {`p File.lchown(nil, nil, "` + f + `")`, "1\n"}, @@ -47,6 +49,10 @@ func TestFileMetaOps(t *testing.T) { t.Errorf("src=%q got=%q want=%q", c.src, got, c.want) } } + // A non-numeric utime second count is a TypeError (numFloat rejects it). + if got := runFSErr(t, `File.utime(:bad, 0, "`+f+`")`); got != "TypeError" { + t.Errorf("utime(:bad): got %q want TypeError", got) + } } // TestFileMetaOpsErrors drives the chmod/chown/lchown/utime error branches via diff --git a/internal/vm/time.go b/internal/vm/time.go index 09aabbe9..99f07cd6 100644 --- a/internal/vm/time.go +++ b/internal/vm/time.go @@ -2,6 +2,7 @@ package vm import ( "math/big" + "os" "regexp" "strconv" "strings" @@ -31,6 +32,55 @@ type Time struct { // was built with, or nil for a plain offset/UTC/local Time. When set, #zone // returns this object rather than the fixed-zone name. zoneObj object.Value + // frac carries the sub-nanosecond part of the sub-second, in seconds and in + // the range [0, 1e-9), that Go's nanosecond-resolution instant cannot hold — + // nil when the instant lands exactly on a nanosecond. MRI keeps a Time's + // sub-second as an exact Rational, so #subsec / #to_r (and the arithmetic that + // feeds them) must preserve digits past the ninth; the nanosecond-granular + // fields (#nsec, #usec, rendering) read only the whole-nanosecond part and are + // unaffected. + frac *big.Rat +} + +// subsecRat returns the Time's exact sub-second as a Rational number of seconds in +// [0, 1): the whole-nanosecond part plus any sub-nanosecond frac. +func (t *Time) subsecRat() *big.Rat { + r := big.NewRat(int64(t.t.Nanosecond()), 1e9) + if t.frac != nil { + r.Add(r, t.frac) + } + return r +} + +// newTimeExact builds a Time at an exact number of seconds since the epoch, +// flooring to the nanosecond for the backing instant and keeping any +// sub-nanosecond remainder in frac, in the given location with the given zone. +func newTimeExact(totalSec *big.Rat, loc *stdtime.Location, zoneObj object.Value) *Time { + nsRat := new(big.Rat).Mul(totalSec, big.NewRat(1e9, 1)) + fl := new(big.Int).Div(nsRat.Num(), nsRat.Denom()) // floor toward -inf + var frac *big.Rat + if rem := new(big.Rat).Sub(nsRat, new(big.Rat).SetInt(fl)); rem.Sign() != 0 { + frac = rem.Quo(rem, big.NewRat(1e9, 1)) // nanoseconds → seconds + } + sec := new(big.Int).Div(fl, big.NewInt(1e9)) + ns := new(big.Int).Sub(fl, new(big.Int).Mul(sec, big.NewInt(1e9))) + return &Time{t: stdtime.Unix(sec.Int64(), ns.Int64()).In(loc), zoneObj: zoneObj, frac: frac} +} + +// localLoc resolves the machine's current local timezone, honouring a TZ set at +// runtime — a spec's with_timezone helper assigns ENV['TZ'], which rbgo writes +// through to the process environment. An IANA name is loaded from Go's tzdata; an +// empty TZ keeps the process zone; and an unloadable name falls back to UTC, +// matching MRI's treatment of an unrecognised TZ as UTC. +func localLoc() *stdtime.Location { + tz := os.Getenv("TZ") + if tz == "" { + return stdtime.Local + } + if loc, err := stdtime.LoadLocation(tz); err == nil { + return loc + } + return stdtime.UTC } // unixTime builds a whole-second UTC Ruby Time from a Unix timestamp — the @@ -59,11 +109,10 @@ func (t *Time) fracString() string { // 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 { + if t.t.Nanosecond() == 0 && t.frac == nil { return object.IntValue(0) } - return &object.Rational{R: big.NewRat(int64(ns), 1e9)} + return &object.Rational{R: t.subsecRat()} } // zoneValue renders Time#zone: the Ruby timezone object when the Time carries @@ -223,7 +272,7 @@ func (vm *VM) registerTime() { vm.cTime.smethods["gm"] = utcM // Time.local / Time.mktime(...) → the same, in the local zone. localM := &Method{name: "local", owner: vm.cTime, native: func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { - return vm.timeFromCalendar(args, stdtime.Local) + return vm.timeFromCalendar(args, localLoc()) }} vm.cTime.smethods["local"] = localM vm.cTime.smethods["mktime"] = localM @@ -263,7 +312,9 @@ func (vm *VM) registerTime() { return object.Float(float64(self(v).t.UnixNano()) / 1e9) }) d("to_r", func(_ *VM, v object.Value, _ []object.Value, _ *Proc) object.Value { - return &object.Rational{R: big.NewRat(self(v).t.UnixNano(), 1e9)} + tt := self(v) + r := new(big.Rat).SetInt64(tt.t.Unix()) + return &object.Rational{R: r.Add(r, tt.subsecRat())} }) d("to_s", func(_ *VM, v object.Value, _ []object.Value, _ *Proc) object.Value { @@ -371,16 +422,18 @@ func (vm *VM) registerTime() { return v } d("utc", toUTC) - d("localtime", func(_ *VM, v object.Value, args []object.Value, _ *Proc) object.Value { - self(v).t = self(v).t.In(vm.localtimeLoc(args)) + d("localtime", func(vm *VM, v object.Value, args []object.Value, _ *Proc) object.Value { + local := vm.getlocalTime(self(v), args) + self(v).t = local.t + self(v).zoneObj = local.zoneObj return v }) getutc := func(_ *VM, v object.Value, _ []object.Value, _ *Proc) object.Value { return &Time{t: self(v).t.UTC()} } d("getutc", getutc) - d("getlocal", func(_ *VM, v object.Value, args []object.Value, _ *Proc) object.Value { - return &Time{t: self(v).t.In(vm.localtimeLoc(args))} + d("getlocal", func(vm *VM, v object.Value, args []object.Value, _ *Proc) object.Value { + return vm.getlocalTime(self(v), args) }) // round / floor / ceil to ndigits sub-second digits (default 0). @@ -439,11 +492,11 @@ func (vm *VM) registerTime() { }) // Arithmetic and ordering. - d("+", func(_ *VM, v object.Value, args []object.Value, _ *Proc) object.Value { - return timeOp(bytecode.OpAdd, self(v), args[0]) + d("+", func(vm *VM, v object.Value, args []object.Value, _ *Proc) object.Value { + return vm.timeArith(bytecode.OpAdd, self(v), args[0]) }) - d("-", func(_ *VM, v object.Value, args []object.Value, _ *Proc) object.Value { - return timeOp(bytecode.OpSub, self(v), args[0]) + d("-", func(vm *VM, v object.Value, args []object.Value, _ *Proc) object.Value { + return vm.timeArith(bytecode.OpSub, self(v), args[0]) }) d("<=>", func(vm *VM, v object.Value, args []object.Value, _ *Proc) object.Value { if other, ok := args[0].(*Time); ok { @@ -503,6 +556,16 @@ func (vm *VM) registerTime() { } } +// mixinTimeComparable adds Comparable to Time's ancestry so Time.include? +// (Comparable) is true (MRI mixes it in); Time's own #<=> already drives the +// comparison operators, and Comparable adds #between?/#clamp. Run after the +// prelude, which defines the Comparable module. +func (vm *VM) mixinTimeComparable() { + if cmp, ok := vm.consts["Comparable"].(*RClass); ok { + vm.cTime.includes = append(vm.cTime.includes, cmp) + } +} + // timeZoneKw pops a trailing keyword hash carrying in: off args, returning // the resolved location (nil when absent) and the remaining positional args. func timeZoneKw(args []object.Value) (object.Value, []object.Value) { @@ -516,12 +579,24 @@ func timeZoneKw(args []object.Value) (object.Value, []object.Value) { return nil, args } +// getlocalTime computes the local representation of recv used by Time#getlocal +// (and, mutating the receiver, Time#localtime): with no argument the machine's +// local zone, with a timezone object (one answering #utc_to_local) that zone — +// rendered through the object exactly as Time.at(in: zone) — and otherwise the +// same utc_offset forms Time.new accepts. +func (vm *VM) getlocalTime(recv *Time, args []object.Value) *Time { + if len(args) > 0 && vm.respondsToDynamic(args[0], "utc_to_local") { + return vm.timeInZoneObject(recv.t.Unix(), int64(recv.t.Nanosecond()), args[0]) + } + return &Time{t: recv.t.In(vm.localtimeLoc(args))} +} + // localtimeLoc resolves the optional offset argument of localtime / getlocal: // none → the local zone, else the same utc_offset forms Time.new accepts // (String or Integer seconds). func (vm *VM) localtimeLoc(args []object.Value) *stdtime.Location { if len(args) == 0 { - return stdtime.Local + return localLoc() } return vm.newTimeOffset(args[0]) } @@ -551,10 +626,37 @@ func (vm *VM) timeAt(args []object.Value) *Time { if hasZone { return vm.applyInstantZone(sec, ns, zone) } - // A numeric source with no zone keeps rbgo's deterministic UTC instant. + // A numeric source with no zone keeps rbgo's deterministic UTC instant. A lone + // Float/Rational argument is placed exactly so any sub-nanosecond part of the + // value survives (MRI keeps the sub-second as an exact Rational). + if r, ok := atExactSeconds(pos); ok { + return newTimeExact(r, stdtime.UTC, nil) + } return &Time{t: stdtime.Unix(sec, ns).UTC()} } +// atExactSeconds returns the exact seconds of Time.at's argument as a Rational +// (ok=true) for the lone-Float/Rational form that can carry sub-nanosecond +// precision; every other form (integer, coerced, or with an explicit subsecond +// argument) is nanosecond-granular and handled by the (sec, ns) path. A +// non-finite Float has no instant, so it raises FloatDomainError as MRI does. +func atExactSeconds(pos []object.Value) (*big.Rat, bool) { + if len(pos) != 1 { + return nil, false + } + switch n := pos[0].(type) { + case object.Float: + r := new(big.Rat).SetFloat64(float64(n)) + if r == nil { + raise("FloatDomainError", "%s", n.Inspect()) + } + return r, true + case *object.Rational: + return new(big.Rat).Set(n.R), true + } + return nil, false +} + // timeAtSeconds resolves Time.at's numeric first argument to whole seconds plus a // nanosecond remainder, keeping a Rational exact (so microsecond/nanosecond // round-trips are lossless) and coercing via #to_int or #to_r as MRI does. @@ -730,7 +832,7 @@ func (vm *VM) timeNew(args []object.Value) *Time { cal = pos[:6] } if zoneArg == nil { - return vm.buildTime(cal, 0, false, stdtime.Local) + return vm.buildTime(cal, 0, false, localLoc()) } if vm.respondsToDynamic(zoneArg, "local_to_utc") { return vm.buildTimeZoneObjectNew(cal, zoneArg) @@ -933,7 +1035,12 @@ func parseUtcOffset(s string) *stdtime.Location { if mm > 59 || ss > 59 { raiseBadOffset(s) } - return fixedOffsetLoc(sign * (hh*3600 + mm*60 + ss)) + total := sign * (hh*3600 + mm*60 + ss) + if total == 0 && sign < 0 { + // "-00:00" is RFC 3339's unknown-offset UTC: MRI reports its zone as "UTC". + return stdtime.UTC + } + return fixedOffsetLoc(total) } func raiseBadOffset(s string) { @@ -958,12 +1065,16 @@ func (vm *VM) timeNewFromString(s *object.String, kwZone, precision object.Value raise("ArgumentError", "time string should have ASCII compatible encoding") } str := s.Str() + // prec is the number of sub-second digits kept: 9 by default, an explicit + // non-negative count (which may exceed 9, landing in the sub-nanosecond frac), + // or "keep everything" for precision: nil or a negative count. prec := 9 - if hasPrec && !object.IsNil(precision) { - prec = vm.timeInt(precision) - } - if prec < 0 || prec > 9 { - prec = 9 + if hasPrec { + if object.IsNil(precision) { + prec = -1 + } else if prec = vm.timeInt(precision); prec < 0 { + prec = -1 + } } year, mon, day, hour, min, sec := 0, 1, 1, 0, 0, 0 @@ -1007,24 +1118,45 @@ func (vm *VM) timeNewFromString(s *object.String, kwZone, precision object.Value checkRange("min", min, 0, 59) checkRange("sec", sec, 0, 60) - // prec is clamped to [0, 9], so truncating to prec also bounds the fraction - // to the nanosecond resolution the backing instant can hold. - if len(fracDigits) > prec { + if prec >= 0 && len(fracDigits) > prec { fracDigits = fracDigits[:prec] } - ns := 0 - if fracDigits != "" { - ns = atoi(fracDigits + strings.Repeat("0", 9-len(fracDigits))) - } + ns, frac := splitFracDigits(fracDigits) - loc := stdtime.Local + loc := localLoc() switch { case strLoc != nil: loc = strLoc case kwZone != nil && !object.IsNil(kwZone): loc = vm.newTimeOffset(kwZone) } - return &Time{t: stdtime.Date(year, stdtime.Month(mon), day, hour, min, sec, ns, loc)} + return &Time{t: stdtime.Date(year, stdtime.Month(mon), day, hour, min, sec, ns, loc), frac: frac} +} + +// splitFracDigits converts a decimal sub-second digit string (e.g. "123456789876" +// for 0.123456789876 s) into the whole-nanosecond count and any sub-nanosecond +// remainder in seconds — nil when the string holds nine digits or fewer, or when +// the digits past the ninth are all zero. +func splitFracDigits(digits string) (int, *big.Rat) { + if digits == "" { + return 0, nil + } + nsPart := digits + if len(nsPart) > 9 { + nsPart = nsPart[:9] + } + ns := atoi(nsPart + strings.Repeat("0", 9-len(nsPart))) + if len(digits) <= 9 { + return ns, nil + } + extra := digits[9:] + num, _ := new(big.Int).SetString(extra, 10) + if num.Sign() == 0 { + return ns, nil + } + den := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(len(extra))), nil) + frac := new(big.Rat).SetFrac(num, den) // fraction of one nanosecond + return ns, frac.Quo(frac, big.NewRat(1e9, 1)) // → seconds } // timeCantParse raises MRI's ArgumentError for an unparseable Time.new String. @@ -1151,8 +1283,8 @@ func (vm *VM) timeSecParts(v object.Value) (int, int64) { case object.Float: return floatSecParts(float64(n)) case *object.Rational: - f, _ := n.R.Float64() - return floatSecParts(f) + s, ns := ratSecNs(n.R) + return int(s), ns case *object.String: return parseRubyInt(n.Str()), 0 } @@ -1163,8 +1295,8 @@ func (vm *VM) timeSecParts(v object.Value) (int, int64) { } if vm.isNumeric(v) && vm.respondsToDynamic(v, "to_r") { if r, ok := vm.send(v, "to_r", nil, nil).(*object.Rational); ok { - f, _ := r.R.Float64() - return floatSecParts(f) + s, ns := ratSecNs(r.R) + return int(s), ns } } raise("TypeError", "no implicit conversion of %s into Time", v.Inspect()) @@ -1311,33 +1443,79 @@ 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. -func timeOp(op bytecode.Op, a *Time, b object.Value) object.Value { - switch op { - case bytecode.OpAdd: - return timeShift(a, numFloat(b)) - case bytecode.OpSub: - if other, ok := b.(*Time); ok { - d := a.t.Sub(other.t) - return object.Float(d.Seconds()) +// timeArith implements Time#+ and Time#-. Subtracting another Time yields the +// Float number of seconds between the two instants; otherwise the operand is a +// shift amount, coerced to an exact Rational number of seconds (MRI's num_exact) +// and applied to the nanosecond, preserving the receiver's location and zone. +func (vm *VM) timeArith(op bytecode.Op, a *Time, b object.Value) object.Value { + if bt, ok := b.(*Time); ok { + if op == bytecode.OpSub { + return object.Float(a.t.Sub(bt.t).Seconds()) } - return timeShift(a, -numFloat(b)) + // Adding two Times is meaningless — MRI rejects it outright. + raise("TypeError", "time + time?") + } + delta := vm.timeDeltaRat(b) + if op == bytecode.OpSub { + delta = new(big.Rat).Neg(delta) } - return raise("NoMethodError", "undefined method '%s' for a Time", op) + return a.shiftByRat(delta) } -// timeShift shifts a Time forward by sec seconds (which may be fractional), -// 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), - zoneObj: t.zoneObj, +// timeDeltaRat coerces a Time#+/#- shift amount to an exact Rational number of +// seconds, following MRI's num_exact: an Integer/Bignum or Rational is exact, a +// Float is taken through its exact binary #to_r, and any other object is coerced +// via #to_r only when it *also* answers #to_int (else via #to_int alone), while a +// String or nil — and an object answering neither — is rejected outright. +func (vm *VM) timeDeltaRat(v object.Value) *big.Rat { + switch n := v.(type) { + case object.Float: + r := new(big.Rat).SetFloat64(float64(n)) + if r == nil { // NaN or ±Infinity has no exact rational + raise("FloatDomainError", "%s", n.Inspect()) + } + return r + case *object.Rational: + return new(big.Rat).Set(n.R) + case *object.String, object.Nil: + // Rejected before any coercion, matching MRI's num_exact. + default: + if bi, ok := object.BigOf(v); ok { // Integer or Bignum + return new(big.Rat).SetInt(bi) + } + if vm.respondsToDynamic(v, "to_int") { + if vm.respondsToDynamic(v, "to_r") { + return valueToRat(vm.send(v, "to_r", nil, nil)) + } + return valueToRat(vm.send(v, "to_int", nil, nil)) + } } + raise("TypeError", "can't convert %s into an exact number", vm.classOf(v).name) + return nil +} + +// valueToRat converts an Integer/Bignum/Rational (as returned by #to_r or +// #to_int) to a big.Rat, raising TypeError on any other result. +func valueToRat(v object.Value) *big.Rat { + if r, ok := v.(*object.Rational); ok { + return new(big.Rat).Set(r.R) + } + if bi, ok := object.BigOf(v); ok { + return new(big.Rat).SetInt(bi) + } + raise("TypeError", "can't convert into an exact number") + return nil +} + +// shiftByRat returns the Time advanced by delta seconds (which may carry a +// sub-nanosecond fraction), computed exactly from the receiver's own exact +// instant so precision beyond the nanosecond is preserved, with the receiver's +// location and Ruby timezone object carried onto the result. +func (t *Time) shiftByRat(delta *big.Rat) *Time { + cur := new(big.Rat).SetInt64(t.t.Unix()) + cur.Add(cur, t.subsecRat()) + cur.Add(cur, delta) + return newTimeExact(cur, t.t.Location(), t.zoneObj) } // timeCmp returns -1/0/1 ordering two Times. @@ -1631,13 +1809,11 @@ func zoneOffset(off, colons int) string { } } -// zoneName renders %Z: the zone's name, or its numeric offset when it is a bare -// fixed-offset zone. +// zoneName renders %Z: the zone's abbreviation, or the empty string for a bare +// fixed-offset zone — MRI's Time#strftime emits nothing for an offset-only zone +// (unlike #inspect, which shows the numeric offset). func zoneName(tm stdtime.Time) string { - name, off := tm.Zone() - if name == "" { - return signedOffset(off, ":") - } + name, _ := tm.Zone() return name } diff --git a/internal/vm/time_conformance_test.go b/internal/vm/time_conformance_test.go index 06421acd..025383db 100644 --- a/internal/vm/time_conformance_test.go +++ b/internal/vm/time_conformance_test.go @@ -186,8 +186,9 @@ func TestTimeStrftime(t *testing.T) { {base + `puts t.strftime("%Q")`, "%Q\n"}, {base + `puts t.strftime("done %")`, "done %\n"}, {base + `puts t.strftime("x%-")`, "x%-\n"}, - // %Z on a fixed-offset zone renders the numeric offset; %z sign both ways. - {`puts Time.new(2026,1,1,0,0,0,"+09:00").strftime("%Z")`, "+09:00\n"}, + // %Z is empty for a fixed-offset zone (MRI emits no abbreviation, unlike + // #inspect which shows the numeric offset). + {`p Time.new(2026,1,1,0,0,0,"+09:00").strftime("%Z")`, "\"\"\n"}, {`puts Time.new(2026,1,1,0,0,0,"-05:30").strftime("%z|%:z|%::z")`, "-0530|-05:30|-05:30:00\n"}, // hour12 wrap: midnight and noon both render 12. {`puts Time.utc(2026,1,1,0,0,0).strftime("%I %p")`, "12 AM\n"}, diff --git a/internal/vm/time_residuals_wave11_test.go b/internal/vm/time_residuals_wave11_test.go new file mode 100644 index 00000000..26cadbd2 --- /dev/null +++ b/internal/vm/time_residuals_wave11_test.go @@ -0,0 +1,250 @@ +package vm_test + +import ( + "strings" + "testing" +) + +// TestTimeArithExact pins Time#+ / Time#- to MRI 4.0.6: the shift amount is +// coerced with num_exact (Integer/Rational exact, Float via its exact #to_r) and +// applied to the nanosecond, so microsecond/nanosecond tracking is lossless and a +// negative Float truncates toward MRI's exact-binary result. Fixed instants only. +func TestTimeArithExact(t *testing.T) { + cases := []struct{ src, want string }{ + // Rational shift is exact: 1.1 + 0.9 == 2. + {`p((Time.at(Rational(11, 10)) + Rational(9, 10)) == Time.at(2))`, "true\n"}, + // Integer shift. + {`p (Time.utc(1970, 1, 1, 0, 0, 0) + 5).sec`, "5\n"}, + {`p (Time.utc(1970, 1, 1, 0, 0, 10) - 4).sec`, "6\n"}, + // A negative Float truncates to MRI's exact-binary microseconds. + {`p (Time.at(100) + -1.3).usec`, "699999\n"}, + {`p (Time.at(100) + -1.3).to_i`, "98\n"}, + // Microsecond / nanosecond tracking stays exact across repeated adds. + {`t = Time.at(0); t += Rational(123_456, 1_000_000); p t.usec`, "123456\n"}, + {`t = Time.at(0); t += Rational(123_456_789, 1_000_000_000); p t.nsec`, "123456789\n"}, + // Subtracting two Times yields the Float seconds between them. + {`p Time.utc(2020, 1, 1, 0, 0, 10) - Time.utc(2020, 1, 1, 0, 0, 0)`, "10.0\n"}, + // A Bignum shift. + {`p (Time.at(0) + (10 ** 18)).to_i`, "1000000000000000000\n"}, + } + for _, tc := range cases { + if got := eval(t, tc.src); got != tc.want { + t.Errorf("src=%q\n got=%q\nwant=%q", tc.src, got, tc.want) + } + } +} + +// TestTimeArithCoercion pins the num_exact object protocol: an object is coerced +// via #to_r only when it also answers #to_int (else via #to_int alone), while a +// String, nil, an object answering neither, and a #to_r returning a non-number +// are all rejected with TypeError — matching MRI 4.0.6. +func TestTimeArithCoercion(t *testing.T) { + // #to_r honoured when #to_int is present too. + if got := eval(t, `o = Object.new +def o.to_r; Rational(3, 2); end +def o.to_int; 1; end +p((Time.at(0) + o).subsec)`); got != "(1/2)\n" { + t.Errorf("to_r+to_int: got %q", got) + } + // #to_int alone is used when #to_r is absent. + if got := eval(t, `o = Object.new +def o.to_int; 5; end +p((Time.utc(1970, 1, 1, 0, 0, 0) + o).sec)`); got != "5\n" { + t.Errorf("to_int only: got %q", got) + } + // Rejections. + rejects := []string{ + `Time.now + "1"`, + `Time.now + nil`, + `Time.now + Object.new`, + `o = Object.new; def o.to_r; Rational(3, 2); end; Time.now + o`, // to_r but no to_int + `o = Object.new; def o.to_int; "x"; end; def o.to_r; "y"; end; Time.now + o`, // to_r returns non-number + } + for _, src := range rejects { + if err := runErr(t, src); err == nil || !strings.Contains(err.Error(), "TypeError") { + t.Errorf("expected TypeError for %q, got %v", src, err) + } + } + // Adding two Times is rejected. + if err := runErr(t, `Time.now + Time.now`); err == nil || !strings.Contains(err.Error(), "TypeError") { + t.Errorf("Time+Time: expected TypeError, got %v", err) + } + // A non-finite Float shift raises FloatDomainError. + if err := runErr(t, `Time.utc(2020) + (1.0 / 0.0)`); err == nil || !strings.Contains(err.Error(), "FloatDomainError") { + t.Errorf("Time+Infinity: expected FloatDomainError, got %v", err) + } + // Every other arithmetic operator on a Time is undefined. + if err := runErr(t, `Time.utc(2020) * 2`); err == nil || !strings.Contains(err.Error(), "NoMethodError") { + t.Errorf("Time*2: expected NoMethodError, got %v", err) + } +} + +// TestTimeExactRationalSeconds pins Time.utc/local's seconds field, when given as +// a Rational (or a Numeric coerced through #to_r), to MRI's exact conversion: no +// Float round-trip, so "25.02" is 20_000_000 ns, not 19_999_999. +func TestTimeExactRationalSeconds(t *testing.T) { + cases := []struct{ src, want string }{ + {`p Time.utc(2010, 3, 30, 5, 43, "25.02".to_r).nsec`, "20000000\n"}, + {`p Time.utc(2010, 3, 30, 5, 43, "25.0123456789".to_r).nsec`, "12345678\n"}, + // A Numeric subclass answering #to_r (but not #to_int) coerces exactly. + {`class MyNum < Numeric; def to_r; Rational(5, 2); end; end +p Time.utc(2010, 1, 1, 0, 0, MyNum.new).nsec`, "500000000\n"}, + } + for _, tc := range cases { + if got := eval(t, tc.src); got != tc.want { + t.Errorf("src=%q\n got=%q\nwant=%q", tc.src, got, tc.want) + } + } +} + +// TestTimeSubNanosecond pins MRI's exact sub-second: precision past the ninth +// digit, carried through Time.at and Time#+/#-, survives in #subsec and #to_r +// (while the nanosecond-granular #nsec/#usec are unchanged), and a non-finite +// Time.at Float raises FloatDomainError. +func TestTimeSubNanosecond(t *testing.T) { + cases := []struct{ src, want string }{ + // Addition keeps 15 significant sub-second digits. + {`p((Time.at(0) + Rational(8_999_999_999_999_999, 1_000_000_000_000_000)).subsec)`, + "(999999999999999/1000000000000000)\n"}, + {`p((Time.at(0) - Rational(1_000_000_000_000_001, 1_000_000_000_000_000)).subsec)`, + "(999999999999999/1000000000000000)\n"}, + // A Float base preserves its exact binary value through subtraction. + {`t = Time.at(0.777777); t -= 0.654321; p t.usec`, "123456\n"}, + // The whole-nanosecond fields ignore the sub-nanosecond part. + {`t = Time.at(0) + Rational(8_999_999_999_999_999, 1_000_000_000_000_000); p t.nsec`, "999999999\n"}, + {`t = Time.at(0) + Rational(8_999_999_999_999_999, 1_000_000_000_000_000); p t.usec`, "999999\n"}, + // A Rational within nanosecond resolution keeps subsec exact and adds no frac. + {`p Time.at(Rational(3, 2)).subsec`, "(1/2)\n"}, + {`p Time.at(Rational(11, 10)).to_r`, "(11/10)\n"}, + } + for _, tc := range cases { + if got := eval(t, tc.src); got != tc.want { + t.Errorf("src=%q\n got=%q\nwant=%q", tc.src, got, tc.want) + } + } + // A non-finite Float has no instant. + if err := runErr(t, `Time.at(Float::INFINITY)`); err == nil || !strings.Contains(err.Error(), "FloatDomainError") { + t.Errorf("Time.at(Infinity): expected FloatDomainError, got %v", err) + } +} + +// TestTimeIncludesComparable pins that Time mixes in Comparable (MRI does), so +// Time.include?(Comparable) is true and Comparable's #between?/#clamp work off +// Time's own #<=>. +func TestTimeIncludesComparable(t *testing.T) { + cases := []struct{ src, want string }{ + {`p Time.include?(Comparable)`, "true\n"}, + {`p Time.ancestors.include?(Comparable)`, "true\n"}, + {`p Time.utc(2020).between?(Time.utc(2019), Time.utc(2021))`, "true\n"}, + {`p Time.utc(2022).clamp(Time.utc(2019), Time.utc(2021)) == Time.utc(2021)`, "true\n"}, + } + for _, tc := range cases { + if got := eval(t, tc.src); got != tc.want { + t.Errorf("src=%q\n got=%q\nwant=%q", tc.src, got, tc.want) + } + } +} + +// TestTimeNewStringPrecision pins Time.new(String, precision:)'s sub-second +// truncation to MRI 4.0.6: the default keeps 9 digits, precision: nil or a +// negative count keeps every digit (into the sub-nanosecond frac), an explicit +// count truncates, and digits past the ninth that are all zero add no frac. +func TestTimeNewStringPrecision(t *testing.T) { + cases := []struct{ src, want string }{ + // Default precision keeps 9 digits. + {`p Time.new("2021-12-25 00:00:00.123456789876 +09:00").subsec`, "(123456789/1000000000)\n"}, + // precision: nil keeps all 12 digits. + {`p Time.new("2021-12-25 00:00:00.123456789876 +09:00", precision: nil).subsec`, + "(30864197469/250000000000)\n"}, + // A negative precision also keeps everything. + {`p Time.new("2021-12-25 00:00:00.123456789876 +09:00", precision: -1).subsec`, + "(30864197469/250000000000)\n"}, + // An explicit count truncates. + {`p Time.new("2021-12-25 00:00:00.123456789876 +09:00", precision: 3).subsec`, "(123/1000)\n"}, + {`p Time.new("2021-12-25 00:00:00 +09:00", precision: 0).subsec`, "0\n"}, + // Trailing zeros past the ninth digit add no sub-nanosecond frac. + {`p Time.new("2021-12-25 00:00:00.123456789000 +09:00", precision: nil).subsec`, + "(123456789/1000000000)\n"}, + // A whole-second string has no fraction at all. + {`p Time.new("2021-12-25 00:00:00 +09:00").subsec`, "0\n"}, + } + for _, tc := range cases { + if got := eval(t, tc.src); got != tc.want { + t.Errorf("src=%q\n got=%q\nwant=%q", tc.src, got, tc.want) + } + } +} + +// TestTimeGetlocalTimezoneObject pins Time#getlocal / Time#localtime with a +// timezone object (one answering #utc_to_local): the instant is rendered through +// that object exactly as Time.at(in: zone), the object becomes the result's zone, +// and the derived fixed offset is reported by #utc_offset — matching MRI 4.0.6. +func TestTimeGetlocalTimezoneObject(t *testing.T) { + // getlocal returns a fresh Time in the zone. + if got := eval(t, `z = Object.new +def z.utc_to_local(t); t + 3600; end +t = Time.utc(2000, 1, 1, 12, 0, 0).getlocal(z) +p t.utc_offset +p t.zone.equal?(z)`); got != "3600\ntrue\n" { + t.Errorf("getlocal(zone): got %q", got) + } + // localtime mutates the receiver into the zone. + if got := eval(t, `z = Object.new +def z.utc_to_local(t); t + 3600; end +t = Time.utc(2000, 1, 1, 12, 0, 0) +t.localtime(z) +p t.utc_offset +p t.zone.equal?(z)`); got != "3600\ntrue\n" { + t.Errorf("localtime(zone): got %q", got) + } + // A zone answering neither #utc_to_local nor a numeric/offset protocol is a + // TypeError, as MRI reports for an object it cannot read as an offset. + if err := runErr(t, `z = Object.new +def z.local_to_utc(t); t; end +Time.utc(2000, 1, 1, 12, 0, 0).getlocal(z)`); err == nil || !strings.Contains(err.Error(), "TypeError") { + t.Errorf("getlocal(bad zone): expected TypeError, got %v", err) + } +} + +// TestTimeLocalTimezoneEnv pins rbgo's local timezone resolution to the runtime +// TZ (as a spec's with_timezone sets via ENV['TZ']): an IANA name is honoured +// with DST, while an unloadable name defaults to UTC — the source restoring TZ so +// the process default (used by every other example) is unchanged. +func TestTimeLocalTimezoneEnv(t *testing.T) { + cases := []struct{ src, want string }{ + // IANA name, DST-aware: winter EST, summer EDT. + {`ENV["TZ"] = "America/New_York" +r = [Time.new(2001, 1, 1, 0, 0, 0).zone, Time.new(2001, 7, 1, 0, 0, 0).zone] +ENV.delete("TZ") +p r`, `["EST", "EDT"]` + "\n"}, + // An unloadable TZ falls back to UTC (offset 0), matching MRI. + {`ENV["TZ"] = "hello-foo" +r = Time.new(2001, 1, 1, 0, 0, 0).utc_offset +ENV.delete("TZ") +p r`, "0\n"}, + } + for _, tc := range cases { + if got := eval(t, tc.src); got != tc.want { + t.Errorf("src=%q\n got=%q\nwant=%q", tc.src, got, tc.want) + } + } +} + +// TestTimeZoneStrings pins Time#zone / strftime("%Z") for the UTC and +// fixed-offset string forms: "-00:00" is RFC 3339 unknown-offset UTC (zone +// "UTC"), a plain numeric offset has no zone name (nil / ""), matching MRI 4.0.6. +func TestTimeZoneStrings(t *testing.T) { + cases := []struct{ src, want string }{ + {`p Time.new(2022, 1, 1, 0, 0, 0, "-00:00").zone`, "\"UTC\"\n"}, + {`p Time.new(2022, 1, 1, 0, 0, 0, "UTC").zone`, "\"UTC\"\n"}, + {`p Time.new(2022, 1, 1, 0, 0, 0, 3600).zone`, "nil\n"}, + // strftime %Z is empty for an offset-only zone (unlike #inspect). + {`p Time.new(2000, 1, 1, 0, 0, 0, 42).strftime("%Z")`, "\"\"\n"}, + {`p Time.utc(2000).strftime("%Z")`, "\"UTC\"\n"}, + } + for _, tc := range cases { + if got := eval(t, tc.src); got != tc.want { + t.Errorf("src=%q\n got=%q\nwant=%q", tc.src, got, tc.want) + } + } +} diff --git a/internal/vm/time_whitebox_test.go b/internal/vm/time_whitebox_test.go index 5ec389cb..427f3062 100644 --- a/internal/vm/time_whitebox_test.go +++ b/internal/vm/time_whitebox_test.go @@ -2,8 +2,6 @@ package vm import ( "testing" - - "github.com/go-embedded-ruby/ruby/internal/bytecode" ) // TestTimeNowSeam pins the nowUnix seam so Time.now is deterministic in a test: @@ -19,15 +17,6 @@ func TestTimeNowSeam(t *testing.T) { } } -// TestTimeOpDefault covers timeOp's defensive default. Only the arithmetic -// opcodes (+, -) reach it through the interpreter, so a unit call with another -// opcode is the only way to exercise the fallthrough. -func TestTimeOpDefault(t *testing.T) { - wantRaise(t, "NoMethodError", func() { - timeOp(bytecode.OpMul, unixTime(0), unixTime(0)) - }) -} - // TestModNegative covers mod's Euclidean-positive branch for a negative // dividend — a defensive path the strftime callers (which only ever pass // non-negative operands) never reach through the interpreter. diff --git a/internal/vm/vm.go b/internal/vm/vm.go index 95e426b8..9e608721 100644 --- a/internal/vm/vm.go +++ b/internal/vm/vm.go @@ -853,6 +853,7 @@ func New(out io.Writer) *VM { vm.registerActiveSupport() // ActiveSupport::Inflector + core extensions (require "active_support" / "active_support/all"), backed by go-ruby-activesupport; after the prelude so the Enumerable module (which its core-ext extends) exists vm.registerActionView() // ActionView::Base view context (tag/url/form/text/number helpers + render) + FormBuilder + PartialIteration + ActiveSupport::SafeBuffer / String#html_safe (require "action_view"), backed by go-ruby-actionview; the URLFor (routes) and RenderTemplate seams wire to Ruby callables, the inline-render default evals ERB through the already-bound go-ruby-erb compiler; after registerActiveSupport (SafeBuffer nests under ActiveSupport) and after the bootstrap ERB/Erubi registration (escaping/compiler surface); #render stays a dispatchable method for a later actionpack/actionmailer binding vm.registerLazy() // after Enumerator (Enumerator::Lazy is built on it) + vm.mixinTimeComparable() // Time includes Comparable (its #<=> drives Comparable); after the prelude so the module exists vm.registerFileStat() // File::Stat / FileTest; after the prelude so File::Stat can mix in Comparable vm.registerIPAddr() // IPAddr (require "ipaddr"), backed by go-ruby-ipaddr; after the prelude so IPAddr can mix in Comparable vm.registerPathname() // Pathname lexical ops (cleanpath/relative_path_from/...), backed by go-ruby-pathname; after the prelude so it reopens the prelude-defined class