1 // run 2 3 // Copyright 2015 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 // Tests short circuiting. 8 9 package main 10 11 func and_ssa(arg1, arg2 bool) bool { 12 return arg1 && rightCall(arg2) 13 } 14 15 func or_ssa(arg1, arg2 bool) bool { 16 return arg1 || rightCall(arg2) 17 } 18 19 var rightCalled bool 20 21 //go:noinline 22 func rightCall(v bool) bool { 23 rightCalled = true 24 return v 25 panic("unreached") 26 } 27 28 func testAnd(arg1, arg2, wantRes bool) { testShortCircuit("AND", arg1, arg2, and_ssa, arg1, wantRes) } 29 func testOr(arg1, arg2, wantRes bool) { testShortCircuit("OR", arg1, arg2, or_ssa, !arg1, wantRes) } 30 31 func testShortCircuit(opName string, arg1, arg2 bool, fn func(bool, bool) bool, wantRightCall, wantRes bool) { 32 rightCalled = false 33 got := fn(arg1, arg2) 34 if rightCalled != wantRightCall { 35 println("failed for", arg1, opName, arg2, "; rightCalled=", rightCalled, "want=", wantRightCall) 36 failed = true 37 } 38 if wantRes != got { 39 println("failed for", arg1, opName, arg2, "; res=", got, "want=", wantRes) 40 failed = true 41 } 42 } 43 44 var failed = false 45 46 func main() { 47 testAnd(false, false, false) 48 testAnd(false, true, false) 49 testAnd(true, false, false) 50 testAnd(true, true, true) 51 52 testOr(false, false, false) 53 testOr(false, true, true) 54 testOr(true, false, true) 55 testOr(true, true, true) 56 57 if failed { 58 panic("failed") 59 } 60 } 61