...

Source file src/cmd/compile/internal/test/testdata/short_test.go

Documentation: cmd/compile/internal/test/testdata

     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  
     7  package main
     8  
     9  import "testing"
    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(t *testing.T, arg1, arg2, wantRes bool) {
    29  	testShortCircuit(t, "AND", arg1, arg2, and_ssa, arg1, wantRes)
    30  }
    31  func testOr(t *testing.T, arg1, arg2, wantRes bool) {
    32  	testShortCircuit(t, "OR", arg1, arg2, or_ssa, !arg1, wantRes)
    33  }
    34  
    35  func 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.
    47  func 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  

View as plain text