1 // Regression: a typed constant built from a float-literal expression must fold
2 // EXACTLY, as Go's arbitrary-precision constant arithmetic does.
3 //
4 // Two losses made it wrong. ConvertConstLocal converted a float constant to an
5 // integer through cf.V (float64), and the declared type was applied late - when
6 // the SSA member was built, or at the use site - so the constant kept its
7 // untyped value and every later expression that used it was promoted to float by
8 // EvalBinaryLocal. src/time's
9 // absoluteToInternal int64 = -(absoluteYears*365.2425 + marchThruDecember) * secondsPerDay
10 // is exactly -9223371966606163200 and float64 rounds it to ...942944, so
11 // absoluteToUnix folded 256 too high and time.Date/time.Parse produced
12 // 4744828235076861952 and "33767811-02-01 18:05:52" instead of 1678806566 and
13 // "2023-03-14 15:09:26". Legacy (go/types) was always right, so this was a
14 // stage4-only wood-law divergence.
15 //
16 // Fixed in: pkg/types/tc_const.mx (ConvertConstLocal truncates the exact
17 // rational; ratTruncInt64), _mxc_stage4/ssa_builder.mx (localizeConstVal applies
18 // the declared type) and _mxc_stage4/ir_typecheck.mx (the declared type is
19 // applied when the constant is recorded, so later folds see a typed value).
20 21 package main
22 23 import "time"
24 25 // 2^53+1 is not representable in float64, so a float64 fold gives ...993 while
26 // the exact value is ...994.
27 const nearFloatEdge int64 = 9007199254740993 + 0.5*2
28 29 const absoluteYears = 292277022400
30 const marchThruDecember = 306
31 const secondsPerDay = 86400
32 33 const absoluteToInternal int64 = -(absoluteYears*365.2425 + marchThruDecember) * secondsPerDay
34 35 func chk(name string, got, want int64) {
36 if got != want {
37 println("FAIL: " | name | " got " | got.String() | " want " | want.String())
38 panic("mismatch")
39 }
40 }
41 42 func main() {
43 // Termination: a batch program must still be stoppable, so the entry
44 // handles the channel the runtime closes on SIGINT/SIGTERM.
45 select {
46 case <-shutdown:
47 return
48 default:
49 }
50 51 chk("nearFloatEdge", nearFloatEdge, 9007199254740994)
52 chk("absoluteToInternal", absoluteToInternal, -9223371966606163200)
53 54 t := time.Date(2023, 3, 14, 15, 9, 26, 0, time.UTC())
55 chk("date-unix", t.Unix(), 1678806566)
56 if t.Format("2006-01-02 15:04:05") != "2023-03-14 15:09:26" {
57 println("FAIL: date format " | t.Format("2006-01-02 15:04:05"))
58 panic("mismatch")
59 }
60 61 p, err := time.Parse("2006-01-02 15:04:05", "2023-03-14 15:09:26")
62 if err != nil {
63 panic("parse failed")
64 }
65 chk("parse-unix", p.Unix(), 1678806566)
66 67 println("ok")
68 }
69