• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- llvm/unittest/ADT/FunctionRefTest.cpp - function_ref unit tests ----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/ADT/STLExtras.h"
10 #include "gtest/gtest.h"
11 
12 using namespace llvm;
13 
14 namespace {
15 
16 // Ensure that there is a default constructor and we can test for a null
17 // function_ref.
TEST(FunctionRefTest,Null)18 TEST(FunctionRefTest, Null) {
19   function_ref<int()> F;
20   EXPECT_FALSE(F);
21 
22   auto L = [] { return 1; };
23   F = L;
24   EXPECT_TRUE(F);
25 
26   F = {};
27   EXPECT_FALSE(F);
28 }
29 
30 // Ensure that copies of a function_ref copy the underlying state rather than
31 // causing one function_ref to chain to the next.
TEST(FunctionRefTest,Copy)32 TEST(FunctionRefTest, Copy) {
33   auto A = [] { return 1; };
34   auto B = [] { return 2; };
35   function_ref<int()> X = A;
36   function_ref<int()> Y = X;
37   X = B;
38   EXPECT_EQ(1, Y());
39 }
40 
TEST(FunctionRefTest,BadCopy)41 TEST(FunctionRefTest, BadCopy) {
42   auto A = [] { return 1; };
43   function_ref<int()> X;
44   function_ref<int()> Y = A;
45   function_ref<int()> Z = static_cast<const function_ref<int()> &&>(Y);
46   X = Z;
47   Y = nullptr;
48   ASSERT_EQ(1, X());
49 }
50 
51 // Test that overloads on function_refs are resolved as expected.
returns(StringRef)52 std::string returns(StringRef) { return "not a function"; }
returns(function_ref<double ()> F)53 std::string returns(function_ref<double()> F) { return "number"; }
returns(function_ref<StringRef ()> F)54 std::string returns(function_ref<StringRef()> F) { return "string"; }
55 
TEST(FunctionRefTest,SFINAE)56 TEST(FunctionRefTest, SFINAE) {
57   EXPECT_EQ("not a function", returns("boo!"));
58   EXPECT_EQ("number", returns([] { return 42; }));
59   EXPECT_EQ("string", returns([] { return "hello"; }));
60 }
61 
62 } // namespace
63