1//===- unittests/ErrorOrTest.cpp - ErrorOr.h tests ------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "llvm/Support/ErrorOr.h"
11
12#include "gtest/gtest.h"
13
14#include <memory>
15
16using namespace llvm;
17
18namespace {
19
20ErrorOr<int> t1() {return 1;}
21ErrorOr<int> t2() { return errc::invalid_argument; }
22
23TEST(ErrorOr, SimpleValue) {
24  ErrorOr<int> a = t1();
25  EXPECT_TRUE(a);
26  EXPECT_EQ(1, *a);
27
28  a = t2();
29  EXPECT_FALSE(a);
30  EXPECT_EQ(errc::invalid_argument, a);
31#ifdef EXPECT_DEBUG_DEATH
32  EXPECT_DEBUG_DEATH(*a, "Cannot get value when an error exists");
33#endif
34}
35
36#if LLVM_HAS_CXX11_STDLIB
37ErrorOr<std::unique_ptr<int> > t3() {
38  return std::unique_ptr<int>(new int(3));
39}
40#endif
41
42TEST(ErrorOr, Types) {
43  int x;
44  ErrorOr<int&> a(x);
45  *a = 42;
46  EXPECT_EQ(42, x);
47
48  EXPECT_FALSE(ErrorOr<void>(errc::broken_pipe));
49  EXPECT_TRUE(ErrorOr<void>(errc::success));
50
51#if LLVM_HAS_CXX11_STDLIB
52  // Move only types.
53  EXPECT_EQ(3, **t3());
54#endif
55}
56
57struct B {};
58struct D : B {};
59
60TEST(ErrorOr, Covariant) {
61  ErrorOr<B*> b(ErrorOr<D*>(0));
62  b = ErrorOr<D*>(0);
63
64#if LLVM_HAS_CXX11_STDLIB
65  ErrorOr<std::unique_ptr<B> > b1(ErrorOr<std::unique_ptr<D> >(0));
66  b1 = ErrorOr<std::unique_ptr<D> >(0);
67#endif
68}
69} // end anon namespace
70
71struct InvalidArgError {
72  InvalidArgError() {}
73  InvalidArgError(std::string S) : ArgName(S) {}
74  std::string ArgName;
75};
76
77namespace llvm {
78template<>
79struct ErrorOrUserDataTraits<InvalidArgError> : true_type {
80  static error_code error() {
81    return make_error_code(errc::invalid_argument);
82  }
83};
84} // end namespace llvm
85
86ErrorOr<int> t4() {
87  return InvalidArgError("adena");
88}
89
90ErrorOr<void> t5() {
91  return InvalidArgError("pie");
92}
93
94namespace {
95TEST(ErrorOr, UserErrorData) {
96  ErrorOr<int> a = t4();
97  EXPECT_EQ(errc::invalid_argument, a);
98  EXPECT_EQ("adena", t4().getError<InvalidArgError>().ArgName);
99
100  ErrorOr<void> b = t5();
101  EXPECT_EQ(errc::invalid_argument, b);
102  EXPECT_EQ("pie", b.getError<InvalidArgError>().ArgName);
103}
104} // end anon namespace
105