1// Copyright 2015 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5// Tests short circuiting.
6
7package main
8
9import "testing"
10
11func and_ssa(arg1, arg2 bool) bool {
12	return arg1 && rightCall(arg2)
13}
14
15func or_ssa(arg1, arg2 bool) bool {
16	return arg1 || rightCall(arg2)
17}
18
19var rightCalled bool
20
21//go:noinline
22func rightCall(v bool) bool {
23	rightCalled = true
24	return v
25	panic("unreached")
26}
27
28func testAnd(t *testing.T, arg1, arg2, wantRes bool) {
29	testShortCircuit(t, "AND", arg1, arg2, and_ssa, arg1, wantRes)
30}
31func testOr(t *testing.T, arg1, arg2, wantRes bool) {
32	testShortCircuit(t, "OR", arg1, arg2, or_ssa, !arg1, wantRes)
33}
34
35func testShortCircuit(t *testing.T, opName string, arg1, arg2 bool, fn func(bool, bool) bool, wantRightCall, wantRes bool) {
36	rightCalled = false
37	got := fn(arg1, arg2)
38	if rightCalled != wantRightCall {
39		t.Errorf("failed for %t %s %t; rightCalled=%t want=%t", arg1, opName, arg2, rightCalled, wantRightCall)
40	}
41	if wantRes != got {
42		t.Errorf("failed for %t %s %t; res=%t want=%t", arg1, opName, arg2, got, wantRes)
43	}
44}
45
46// TestShortCircuit tests OANDAND and OOROR expressions and short circuiting.
47func TestShortCircuit(t *testing.T) {
48	testAnd(t, false, false, false)
49	testAnd(t, false, true, false)
50	testAnd(t, true, false, false)
51	testAnd(t, true, true, true)
52
53	testOr(t, false, false, false)
54	testOr(t, false, true, true)
55	testOr(t, true, false, true)
56	testOr(t, true, true, true)
57}
58