github.com/filosottile/go@v0.0.0-20170906193555-dbed9972d994/test/mergemul.go (about) 1 // runoutput 2 3 // Copyright 2017 The Go Authors. All rights reserved. 4 // Use of this source code is governed by a BSD-style 5 // license that can be found in the LICENSE file. 6 7 package main 8 9 import "fmt" 10 11 // Check that expressions like (c*n + d*(n+k)) get correctly merged by 12 // the compiler into (c+d)*n + d*k (with c+d and d*k computed at 13 // compile time). 14 // 15 // The merging is performed by a combination of the multiplication 16 // merge rules 17 // (c*n + d*n) -> (c+d)*n 18 // and the distributive multiplication rules 19 // c * (d+x) -> c*d + c*x 20 21 // Generate a MergeTest that looks like this: 22 // 23 // a8, b8 = m1*n8 + m2*(n8+k), (m1+m2)*n8 + m2*k 24 // if a8 != b8 { 25 // // print error msg and panic 26 // } 27 func makeMergeTest(m1, m2, k int, size string) string { 28 29 model := " a" + size + ", b" + size 30 model += fmt.Sprintf(" = %%d*n%s + %%d*(n%s+%%d), (%%d+%%d)*n%s + (%%d*%%d)", size, size, size) 31 32 test := fmt.Sprintf(model, m1, m2, k, m1, m2, m2, k) 33 test += fmt.Sprintf(` 34 if a%s != b%s { 35 fmt.Printf("MergeTest(%d, %d, %d, %s) failed\n") 36 fmt.Printf("%%d != %%d\n", a%s, b%s) 37 panic("FAIL") 38 } 39 `, size, size, m1, m2, k, size, size, size) 40 return test + "\n" 41 } 42 43 func makeAllSizes(m1, m2, k int) string { 44 var tests string 45 tests += makeMergeTest(m1, m2, k, "8") 46 tests += makeMergeTest(m1, m2, k, "16") 47 tests += makeMergeTest(m1, m2, k, "32") 48 tests += makeMergeTest(m1, m2, k, "64") 49 tests += "\n" 50 return tests 51 } 52 53 func main() { 54 fmt.Println(`package main 55 56 import "fmt" 57 58 var n8 int8 = 42 59 var n16 int16 = 42 60 var n32 int32 = 42 61 var n64 int64 = 42 62 63 func main() { 64 var a8, b8 int8 65 var a16, b16 int16 66 var a32, b32 int32 67 var a64, b64 int64 68 `) 69 70 fmt.Println(makeAllSizes(03, 05, 0)) // 3*n + 5*n 71 fmt.Println(makeAllSizes(17, 33, 0)) 72 fmt.Println(makeAllSizes(80, 45, 0)) 73 fmt.Println(makeAllSizes(32, 64, 0)) 74 75 fmt.Println(makeAllSizes(7, 11, +1)) // 7*n + 11*(n+1) 76 fmt.Println(makeAllSizes(9, 13, +2)) 77 fmt.Println(makeAllSizes(11, 16, -1)) 78 fmt.Println(makeAllSizes(17, 9, -2)) 79 80 fmt.Println("}") 81 }