1f7f6d3e9SLang Hames //===----- unittests/ErrorTest.cpp - Error.h tests ------------------------===//
2f7f6d3e9SLang Hames //
3f7f6d3e9SLang Hames //                     The LLVM Compiler Infrastructure
4f7f6d3e9SLang Hames //
5f7f6d3e9SLang Hames // This file is distributed under the University of Illinois Open Source
6f7f6d3e9SLang Hames // License. See LICENSE.TXT for details.
7f7f6d3e9SLang Hames //
8f7f6d3e9SLang Hames //===----------------------------------------------------------------------===//
9f7f6d3e9SLang Hames 
10f7f6d3e9SLang Hames #include "llvm/Support/Error.h"
11*c5e0bbd7SLang Hames 
12*c5e0bbd7SLang Hames #include "llvm/ADT/Twine.h"
13f7f6d3e9SLang Hames #include "llvm/Support/Errc.h"
14e7aad357SLang Hames #include "llvm/Support/ErrorHandling.h"
15f7f6d3e9SLang Hames #include "gtest/gtest.h"
16f7f6d3e9SLang Hames #include <memory>
17f7f6d3e9SLang Hames 
18f7f6d3e9SLang Hames using namespace llvm;
19f7f6d3e9SLang Hames 
20f7f6d3e9SLang Hames namespace {
21f7f6d3e9SLang Hames 
22f7f6d3e9SLang Hames // Custom error class with a default base class and some random 'info' attached.
23f7f6d3e9SLang Hames class CustomError : public ErrorInfo<CustomError> {
24f7f6d3e9SLang Hames public:
25f7f6d3e9SLang Hames   // Create an error with some info attached.
26f7f6d3e9SLang Hames   CustomError(int Info) : Info(Info) {}
27f7f6d3e9SLang Hames 
28f7f6d3e9SLang Hames   // Get the info attached to this error.
29f7f6d3e9SLang Hames   int getInfo() const { return Info; }
30f7f6d3e9SLang Hames 
31f7f6d3e9SLang Hames   // Log this error to a stream.
32f7f6d3e9SLang Hames   void log(raw_ostream &OS) const override {
33f7f6d3e9SLang Hames     OS << "CustomError { " << getInfo() << "}";
34f7f6d3e9SLang Hames   }
35f7f6d3e9SLang Hames 
36e7aad357SLang Hames   std::error_code convertToErrorCode() const override {
37e7aad357SLang Hames     llvm_unreachable("CustomError doesn't support ECError conversion");
38e7aad357SLang Hames   }
39e7aad357SLang Hames 
40a15b76b3SReid Kleckner   // Used by ErrorInfo::classID.
41a15b76b3SReid Kleckner   static char ID;
42a15b76b3SReid Kleckner 
43f7f6d3e9SLang Hames protected:
44f7f6d3e9SLang Hames   // This error is subclassed below, but we can't use inheriting constructors
45f7f6d3e9SLang Hames   // yet, so we can't propagate the constructors through ErrorInfo. Instead
46f7f6d3e9SLang Hames   // we have to have a default constructor and have the subclass initialize all
47f7f6d3e9SLang Hames   // fields.
48f7f6d3e9SLang Hames   CustomError() : Info(0) {}
49f7f6d3e9SLang Hames 
50f7f6d3e9SLang Hames   int Info;
51f7f6d3e9SLang Hames };
52f7f6d3e9SLang Hames 
53a15b76b3SReid Kleckner char CustomError::ID = 0;
54a15b76b3SReid Kleckner 
55f7f6d3e9SLang Hames // Custom error class with a custom base class and some additional random
56f7f6d3e9SLang Hames // 'info'.
57f7f6d3e9SLang Hames class CustomSubError : public ErrorInfo<CustomSubError, CustomError> {
58f7f6d3e9SLang Hames public:
59f7f6d3e9SLang Hames   // Create a sub-error with some info attached.
60f7f6d3e9SLang Hames   CustomSubError(int Info, int ExtraInfo) : ExtraInfo(ExtraInfo) {
61f7f6d3e9SLang Hames     this->Info = Info;
62f7f6d3e9SLang Hames   }
63f7f6d3e9SLang Hames 
64f7f6d3e9SLang Hames   // Get the extra info attached to this error.
65f7f6d3e9SLang Hames   int getExtraInfo() const { return ExtraInfo; }
66f7f6d3e9SLang Hames 
67f7f6d3e9SLang Hames   // Log this error to a stream.
68f7f6d3e9SLang Hames   void log(raw_ostream &OS) const override {
69f7f6d3e9SLang Hames     OS << "CustomSubError { " << getInfo() << ", " << getExtraInfo() << "}";
70f7f6d3e9SLang Hames   }
71f7f6d3e9SLang Hames 
72e7aad357SLang Hames   std::error_code convertToErrorCode() const override {
73e7aad357SLang Hames     llvm_unreachable("CustomSubError doesn't support ECError conversion");
74e7aad357SLang Hames   }
75e7aad357SLang Hames 
76a15b76b3SReid Kleckner   // Used by ErrorInfo::classID.
77a15b76b3SReid Kleckner   static char ID;
78a15b76b3SReid Kleckner 
79f7f6d3e9SLang Hames protected:
80f7f6d3e9SLang Hames   int ExtraInfo;
81f7f6d3e9SLang Hames };
82f7f6d3e9SLang Hames 
83a15b76b3SReid Kleckner char CustomSubError::ID = 0;
84a15b76b3SReid Kleckner 
85f7f6d3e9SLang Hames static Error handleCustomError(const CustomError &CE) { return Error(); }
86f7f6d3e9SLang Hames 
87f7f6d3e9SLang Hames static void handleCustomErrorVoid(const CustomError &CE) {}
88f7f6d3e9SLang Hames 
89f7f6d3e9SLang Hames static Error handleCustomErrorUP(std::unique_ptr<CustomError> CE) {
90f7f6d3e9SLang Hames   return Error();
91f7f6d3e9SLang Hames }
92f7f6d3e9SLang Hames 
93f7f6d3e9SLang Hames static void handleCustomErrorUPVoid(std::unique_ptr<CustomError> CE) {}
94f7f6d3e9SLang Hames 
9501864a2dSLang Hames // Test that success values implicitly convert to false, and don't cause crashes
9601864a2dSLang Hames // once they've been implicitly converted.
9701864a2dSLang Hames TEST(Error, CheckedSuccess) {
9801864a2dSLang Hames   Error E;
9901864a2dSLang Hames   EXPECT_FALSE(E) << "Unexpected error while testing Error 'Success'";
10001864a2dSLang Hames }
10101864a2dSLang Hames 
10201864a2dSLang Hames // Test that unchecked succes values cause an abort.
10301864a2dSLang Hames #ifndef NDEBUG
10401864a2dSLang Hames TEST(Error, UncheckedSuccess) {
10501864a2dSLang Hames   EXPECT_DEATH({ Error E; }, "Program aborted due to an unhandled Error:")
10601864a2dSLang Hames       << "Unchecked Error Succes value did not cause abort()";
10701864a2dSLang Hames }
10801864a2dSLang Hames #endif
10901864a2dSLang Hames 
110d1af8fceSLang Hames // ErrorAsOutParameter tester.
111d1af8fceSLang Hames void errAsOutParamHelper(Error &Err) {
112d1af8fceSLang Hames   ErrorAsOutParameter ErrAsOutParam(Err);
113d1af8fceSLang Hames   // Verify that checked flag is raised - assignment should not crash.
114d1af8fceSLang Hames   Err = Error::success();
115d1af8fceSLang Hames   // Raise the checked bit manually - caller should still have to test the
116d1af8fceSLang Hames   // error.
117d1af8fceSLang Hames   (void)!!Err;
118d0ac31a7SLang Hames }
119d0ac31a7SLang Hames 
120d1af8fceSLang Hames // Test that ErrorAsOutParameter sets the checked flag on construction.
121d1af8fceSLang Hames TEST(Error, ErrorAsOutParameterChecked) {
122d1af8fceSLang Hames   Error E;
123d1af8fceSLang Hames   errAsOutParamHelper(E);
124d1af8fceSLang Hames   (void)!!E;
125d1af8fceSLang Hames }
126d1af8fceSLang Hames 
127d1af8fceSLang Hames // Test that ErrorAsOutParameter clears the checked flag on destruction.
128d1af8fceSLang Hames #ifndef NDEBUG
129d1af8fceSLang Hames TEST(Error, ErrorAsOutParameterUnchecked) {
130d1af8fceSLang Hames   EXPECT_DEATH({ Error E; errAsOutParamHelper(E); },
131d1af8fceSLang Hames                "Program aborted due to an unhandled Error:")
132d1af8fceSLang Hames       << "ErrorAsOutParameter did not clear the checked flag on destruction.";
133d1af8fceSLang Hames }
134d1af8fceSLang Hames #endif
135d1af8fceSLang Hames 
136f7f6d3e9SLang Hames // Check that we abort on unhandled failure cases. (Force conversion to bool
137f7f6d3e9SLang Hames // to make sure that we don't accidentally treat checked errors as handled).
138f7f6d3e9SLang Hames // Test runs in debug mode only.
139f7f6d3e9SLang Hames #ifndef NDEBUG
14001864a2dSLang Hames TEST(Error, UncheckedError) {
141f7f6d3e9SLang Hames   auto DropUnhandledError = []() {
142f7f6d3e9SLang Hames     Error E = make_error<CustomError>(42);
143f7f6d3e9SLang Hames     (void)!E;
144f7f6d3e9SLang Hames   };
145f7f6d3e9SLang Hames   EXPECT_DEATH(DropUnhandledError(),
146f7f6d3e9SLang Hames                "Program aborted due to an unhandled Error:")
147f7f6d3e9SLang Hames       << "Unhandled Error failure value did not cause abort()";
148f7f6d3e9SLang Hames }
149f7f6d3e9SLang Hames #endif
150f7f6d3e9SLang Hames 
15101864a2dSLang Hames // Check 'Error::isA<T>' method handling.
15201864a2dSLang Hames TEST(Error, IsAHandling) {
153f7f6d3e9SLang Hames   // Check 'isA' handling.
154f7f6d3e9SLang Hames   Error E = make_error<CustomError>(1);
155f7f6d3e9SLang Hames   Error F = make_error<CustomSubError>(1, 2);
15601a3cf4dSLang Hames   Error G = Error::success();
157f7f6d3e9SLang Hames 
158f7f6d3e9SLang Hames   EXPECT_TRUE(E.isA<CustomError>());
159f7f6d3e9SLang Hames   EXPECT_FALSE(E.isA<CustomSubError>());
160f7f6d3e9SLang Hames   EXPECT_TRUE(F.isA<CustomError>());
161f7f6d3e9SLang Hames   EXPECT_TRUE(F.isA<CustomSubError>());
16201a3cf4dSLang Hames   EXPECT_FALSE(G.isA<CustomError>());
163f7f6d3e9SLang Hames 
164f7f6d3e9SLang Hames   consumeError(std::move(E));
165f7f6d3e9SLang Hames   consumeError(std::move(F));
16601a3cf4dSLang Hames   consumeError(std::move(G));
167f7f6d3e9SLang Hames }
168f7f6d3e9SLang Hames 
169f7f6d3e9SLang Hames // Check that we can handle a custom error.
17001864a2dSLang Hames TEST(Error, HandleCustomError) {
171f7f6d3e9SLang Hames   int CaughtErrorInfo = 0;
172f7f6d3e9SLang Hames   handleAllErrors(make_error<CustomError>(42), [&](const CustomError &CE) {
173f7f6d3e9SLang Hames     CaughtErrorInfo = CE.getInfo();
174f7f6d3e9SLang Hames   });
175f7f6d3e9SLang Hames 
17601864a2dSLang Hames   EXPECT_TRUE(CaughtErrorInfo == 42) << "Wrong result from CustomError handler";
177f7f6d3e9SLang Hames }
178f7f6d3e9SLang Hames 
179f7f6d3e9SLang Hames // Check that handler type deduction also works for handlers
180f7f6d3e9SLang Hames // of the following types:
181f7f6d3e9SLang Hames // void (const Err&)
182f7f6d3e9SLang Hames // Error (const Err&) mutable
183f7f6d3e9SLang Hames // void (const Err&) mutable
184f7f6d3e9SLang Hames // Error (Err&)
185f7f6d3e9SLang Hames // void (Err&)
186f7f6d3e9SLang Hames // Error (Err&) mutable
187f7f6d3e9SLang Hames // void (Err&) mutable
188f7f6d3e9SLang Hames // Error (unique_ptr<Err>)
189f7f6d3e9SLang Hames // void (unique_ptr<Err>)
190f7f6d3e9SLang Hames // Error (unique_ptr<Err>) mutable
191f7f6d3e9SLang Hames // void (unique_ptr<Err>) mutable
19201864a2dSLang Hames TEST(Error, HandlerTypeDeduction) {
193f7f6d3e9SLang Hames 
194f7f6d3e9SLang Hames   handleAllErrors(make_error<CustomError>(42), [](const CustomError &CE) {});
195f7f6d3e9SLang Hames 
196f7f6d3e9SLang Hames   handleAllErrors(
197f7f6d3e9SLang Hames       make_error<CustomError>(42),
198f7f6d3e9SLang Hames       [](const CustomError &CE) mutable { return Error::success(); });
199f7f6d3e9SLang Hames 
200f7f6d3e9SLang Hames   handleAllErrors(make_error<CustomError>(42),
201f7f6d3e9SLang Hames                   [](const CustomError &CE) mutable {});
202f7f6d3e9SLang Hames 
203f7f6d3e9SLang Hames   handleAllErrors(make_error<CustomError>(42),
204f7f6d3e9SLang Hames                   [](CustomError &CE) { return Error::success(); });
205f7f6d3e9SLang Hames 
206f7f6d3e9SLang Hames   handleAllErrors(make_error<CustomError>(42), [](CustomError &CE) {});
207f7f6d3e9SLang Hames 
208f7f6d3e9SLang Hames   handleAllErrors(make_error<CustomError>(42),
209f7f6d3e9SLang Hames                   [](CustomError &CE) mutable { return Error::success(); });
210f7f6d3e9SLang Hames 
211f7f6d3e9SLang Hames   handleAllErrors(make_error<CustomError>(42), [](CustomError &CE) mutable {});
212f7f6d3e9SLang Hames 
213f7f6d3e9SLang Hames   handleAllErrors(
214f7f6d3e9SLang Hames       make_error<CustomError>(42),
215f7f6d3e9SLang Hames       [](std::unique_ptr<CustomError> CE) { return Error::success(); });
216f7f6d3e9SLang Hames 
217f7f6d3e9SLang Hames   handleAllErrors(make_error<CustomError>(42),
218f7f6d3e9SLang Hames                   [](std::unique_ptr<CustomError> CE) {});
219f7f6d3e9SLang Hames 
220f7f6d3e9SLang Hames   handleAllErrors(
221f7f6d3e9SLang Hames       make_error<CustomError>(42),
222f7f6d3e9SLang Hames       [](std::unique_ptr<CustomError> CE) mutable { return Error::success(); });
223f7f6d3e9SLang Hames 
224f7f6d3e9SLang Hames   handleAllErrors(make_error<CustomError>(42),
225f7f6d3e9SLang Hames                   [](std::unique_ptr<CustomError> CE) mutable {});
226f7f6d3e9SLang Hames 
227f7f6d3e9SLang Hames   // Check that named handlers of type 'Error (const Err&)' work.
228f7f6d3e9SLang Hames   handleAllErrors(make_error<CustomError>(42), handleCustomError);
229f7f6d3e9SLang Hames 
230f7f6d3e9SLang Hames   // Check that named handlers of type 'void (const Err&)' work.
231f7f6d3e9SLang Hames   handleAllErrors(make_error<CustomError>(42), handleCustomErrorVoid);
232f7f6d3e9SLang Hames 
233f7f6d3e9SLang Hames   // Check that named handlers of type 'Error (std::unique_ptr<Err>)' work.
234f7f6d3e9SLang Hames   handleAllErrors(make_error<CustomError>(42), handleCustomErrorUP);
235f7f6d3e9SLang Hames 
236f7f6d3e9SLang Hames   // Check that named handlers of type 'Error (std::unique_ptr<Err>)' work.
237f7f6d3e9SLang Hames   handleAllErrors(make_error<CustomError>(42), handleCustomErrorUPVoid);
23801864a2dSLang Hames }
239f7f6d3e9SLang Hames 
24001864a2dSLang Hames // Test that we can handle errors with custom base classes.
24101864a2dSLang Hames TEST(Error, HandleCustomErrorWithCustomBaseClass) {
242f7f6d3e9SLang Hames   int CaughtErrorInfo = 0;
243f7f6d3e9SLang Hames   int CaughtErrorExtraInfo = 0;
244f7f6d3e9SLang Hames   handleAllErrors(make_error<CustomSubError>(42, 7),
245f7f6d3e9SLang Hames                   [&](const CustomSubError &SE) {
246f7f6d3e9SLang Hames                     CaughtErrorInfo = SE.getInfo();
247f7f6d3e9SLang Hames                     CaughtErrorExtraInfo = SE.getExtraInfo();
248f7f6d3e9SLang Hames                   });
249f7f6d3e9SLang Hames 
250f7f6d3e9SLang Hames   EXPECT_TRUE(CaughtErrorInfo == 42 && CaughtErrorExtraInfo == 7)
251f7f6d3e9SLang Hames       << "Wrong result from CustomSubError handler";
252f7f6d3e9SLang Hames }
253f7f6d3e9SLang Hames 
254f7f6d3e9SLang Hames // Check that we trigger only the first handler that applies.
25501864a2dSLang Hames TEST(Error, FirstHandlerOnly) {
256f7f6d3e9SLang Hames   int DummyInfo = 0;
257f7f6d3e9SLang Hames   int CaughtErrorInfo = 0;
258f7f6d3e9SLang Hames   int CaughtErrorExtraInfo = 0;
259f7f6d3e9SLang Hames 
260f7f6d3e9SLang Hames   handleAllErrors(make_error<CustomSubError>(42, 7),
261f7f6d3e9SLang Hames                   [&](const CustomSubError &SE) {
262f7f6d3e9SLang Hames                     CaughtErrorInfo = SE.getInfo();
263f7f6d3e9SLang Hames                     CaughtErrorExtraInfo = SE.getExtraInfo();
264f7f6d3e9SLang Hames                   },
265f7f6d3e9SLang Hames                   [&](const CustomError &CE) { DummyInfo = CE.getInfo(); });
266f7f6d3e9SLang Hames 
267f7f6d3e9SLang Hames   EXPECT_TRUE(CaughtErrorInfo == 42 && CaughtErrorExtraInfo == 7 &&
268f7f6d3e9SLang Hames               DummyInfo == 0)
269f7f6d3e9SLang Hames       << "Activated the wrong Error handler(s)";
270f7f6d3e9SLang Hames }
271f7f6d3e9SLang Hames 
272f7f6d3e9SLang Hames // Check that general handlers shadow specific ones.
27301864a2dSLang Hames TEST(Error, HandlerShadowing) {
274f7f6d3e9SLang Hames   int CaughtErrorInfo = 0;
275f7f6d3e9SLang Hames   int DummyInfo = 0;
276f7f6d3e9SLang Hames   int DummyExtraInfo = 0;
277f7f6d3e9SLang Hames 
278f7f6d3e9SLang Hames   handleAllErrors(
279f7f6d3e9SLang Hames       make_error<CustomSubError>(42, 7),
280f7f6d3e9SLang Hames       [&](const CustomError &CE) { CaughtErrorInfo = CE.getInfo(); },
281f7f6d3e9SLang Hames       [&](const CustomSubError &SE) {
282f7f6d3e9SLang Hames         DummyInfo = SE.getInfo();
283f7f6d3e9SLang Hames         DummyExtraInfo = SE.getExtraInfo();
284f7f6d3e9SLang Hames       });
285f7f6d3e9SLang Hames 
286b2cef64bSNAKAMURA Takumi   EXPECT_TRUE(CaughtErrorInfo == 42 && DummyInfo == 0 && DummyExtraInfo == 0)
287f7f6d3e9SLang Hames       << "General Error handler did not shadow specific handler";
288f7f6d3e9SLang Hames }
289f7f6d3e9SLang Hames 
29001864a2dSLang Hames // Test joinErrors.
29101864a2dSLang Hames TEST(Error, CheckJoinErrors) {
292f7f6d3e9SLang Hames   int CustomErrorInfo1 = 0;
293f7f6d3e9SLang Hames   int CustomErrorInfo2 = 0;
294f7f6d3e9SLang Hames   int CustomErrorExtraInfo = 0;
29501864a2dSLang Hames   Error E =
29601864a2dSLang Hames       joinErrors(make_error<CustomError>(7), make_error<CustomSubError>(42, 7));
297f7f6d3e9SLang Hames 
298f7f6d3e9SLang Hames   handleAllErrors(std::move(E),
299f7f6d3e9SLang Hames                   [&](const CustomSubError &SE) {
300f7f6d3e9SLang Hames                     CustomErrorInfo2 = SE.getInfo();
301f7f6d3e9SLang Hames                     CustomErrorExtraInfo = SE.getExtraInfo();
302f7f6d3e9SLang Hames                   },
303f7f6d3e9SLang Hames                   [&](const CustomError &CE) {
304f7f6d3e9SLang Hames                     // Assert that the CustomError instance above is handled
305f7f6d3e9SLang Hames                     // before the
306f7f6d3e9SLang Hames                     // CustomSubError - joinErrors should preserve error
307f7f6d3e9SLang Hames                     // ordering.
308f7f6d3e9SLang Hames                     EXPECT_EQ(CustomErrorInfo2, 0)
309f7f6d3e9SLang Hames                         << "CustomErrorInfo2 should be 0 here. "
310f7f6d3e9SLang Hames                            "joinErrors failed to preserve ordering.\n";
311f7f6d3e9SLang Hames                     CustomErrorInfo1 = CE.getInfo();
312f7f6d3e9SLang Hames                   });
313f7f6d3e9SLang Hames 
314f7f6d3e9SLang Hames   EXPECT_TRUE(CustomErrorInfo1 == 7 && CustomErrorInfo2 == 42 &&
315f7f6d3e9SLang Hames               CustomErrorExtraInfo == 7)
316f7f6d3e9SLang Hames       << "Failed handling compound Error.";
317f7f6d3e9SLang Hames }
318f7f6d3e9SLang Hames 
31901864a2dSLang Hames // Test that we can consume success values.
32001864a2dSLang Hames TEST(Error, ConsumeSuccess) {
321f7f6d3e9SLang Hames   Error E;
322f7f6d3e9SLang Hames   consumeError(std::move(E));
323f7f6d3e9SLang Hames }
32401864a2dSLang Hames 
32501864a2dSLang Hames TEST(Error, ConsumeError) {
326f7f6d3e9SLang Hames   Error E = make_error<CustomError>(7);
327f7f6d3e9SLang Hames   consumeError(std::move(E));
328f7f6d3e9SLang Hames }
329f7f6d3e9SLang Hames 
330f7f6d3e9SLang Hames // Test that handleAllUnhandledErrors crashes if an error is not caught.
331f7f6d3e9SLang Hames // Test runs in debug mode only.
332f7f6d3e9SLang Hames #ifndef NDEBUG
33301864a2dSLang Hames TEST(Error, FailureToHandle) {
334f7f6d3e9SLang Hames   auto FailToHandle = []() {
33501864a2dSLang Hames     handleAllErrors(make_error<CustomError>(7), [&](const CustomSubError &SE) {
336f7f6d3e9SLang Hames       errs() << "This should never be called";
337f7f6d3e9SLang Hames       exit(1);
338f7f6d3e9SLang Hames     });
339f7f6d3e9SLang Hames   };
340f7f6d3e9SLang Hames 
341f7f6d3e9SLang Hames   EXPECT_DEATH(FailToHandle(), "Program aborted due to an unhandled Error:")
342f7f6d3e9SLang Hames       << "Unhandled Error in handleAllErrors call did not cause an "
343f7f6d3e9SLang Hames          "abort()";
344f7f6d3e9SLang Hames }
345f7f6d3e9SLang Hames #endif
346f7f6d3e9SLang Hames 
347f7f6d3e9SLang Hames // Test that handleAllUnhandledErrors crashes if an error is returned from a
348f7f6d3e9SLang Hames // handler.
349f7f6d3e9SLang Hames // Test runs in debug mode only.
350f7f6d3e9SLang Hames #ifndef NDEBUG
35101864a2dSLang Hames TEST(Error, FailureFromHandler) {
352f7f6d3e9SLang Hames   auto ReturnErrorFromHandler = []() {
353f7f6d3e9SLang Hames     handleAllErrors(make_error<CustomError>(7),
354f7f6d3e9SLang Hames                     [&](std::unique_ptr<CustomSubError> SE) {
355f7f6d3e9SLang Hames                       return Error(std::move(SE));
356f7f6d3e9SLang Hames                     });
357f7f6d3e9SLang Hames   };
358f7f6d3e9SLang Hames 
359f7f6d3e9SLang Hames   EXPECT_DEATH(ReturnErrorFromHandler(),
360f7f6d3e9SLang Hames                "Program aborted due to an unhandled Error:")
361f7f6d3e9SLang Hames       << " Error returned from handler in handleAllErrors call did not "
362f7f6d3e9SLang Hames          "cause abort()";
363f7f6d3e9SLang Hames }
364f7f6d3e9SLang Hames #endif
365f7f6d3e9SLang Hames 
366f7f6d3e9SLang Hames // Test that we can return values from handleErrors.
36701864a2dSLang Hames TEST(Error, CatchErrorFromHandler) {
368f7f6d3e9SLang Hames   int ErrorInfo = 0;
369f7f6d3e9SLang Hames 
370f7f6d3e9SLang Hames   Error E = handleErrors(
371f7f6d3e9SLang Hames       make_error<CustomError>(7),
372f7f6d3e9SLang Hames       [&](std::unique_ptr<CustomError> CE) { return Error(std::move(CE)); });
373f7f6d3e9SLang Hames 
374f7f6d3e9SLang Hames   handleAllErrors(std::move(E),
375f7f6d3e9SLang Hames                   [&](const CustomError &CE) { ErrorInfo = CE.getInfo(); });
376f7f6d3e9SLang Hames 
377f7f6d3e9SLang Hames   EXPECT_EQ(ErrorInfo, 7)
378f7f6d3e9SLang Hames       << "Failed to handle Error returned from handleErrors.";
379f7f6d3e9SLang Hames }
3806935c2d3SLang Hames 
381*c5e0bbd7SLang Hames TEST(Error, StringError) {
382*c5e0bbd7SLang Hames   std::string Msg;
383*c5e0bbd7SLang Hames   raw_string_ostream S(Msg);
384*c5e0bbd7SLang Hames   logAllUnhandledErrors(make_error<StringError>("foo" + Twine(42),
385*c5e0bbd7SLang Hames                                                 unconvertibleErrorCode()),
386*c5e0bbd7SLang Hames                         S, "");
387*c5e0bbd7SLang Hames   EXPECT_EQ(S.str(), "foo42\n") << "Unexpected StringError log result";
388*c5e0bbd7SLang Hames 
389*c5e0bbd7SLang Hames   auto EC =
390*c5e0bbd7SLang Hames     errorToErrorCode(make_error<StringError>("", errc::invalid_argument));
391*c5e0bbd7SLang Hames   EXPECT_EQ(EC, errc::invalid_argument)
392*c5e0bbd7SLang Hames     << "Failed to convert StringError to error_code.";
393*c5e0bbd7SLang Hames }
394*c5e0bbd7SLang Hames 
39501864a2dSLang Hames // Test that the ExitOnError utility works as expected.
39601864a2dSLang Hames TEST(Error, ExitOnError) {
3976935c2d3SLang Hames   ExitOnError ExitOnErr;
3986935c2d3SLang Hames   ExitOnErr.setBanner("Error in tool:");
39901864a2dSLang Hames   ExitOnErr.setExitCodeMapper([](const Error &E) {
4006935c2d3SLang Hames     if (E.isA<CustomSubError>())
4016935c2d3SLang Hames       return 2;
4026935c2d3SLang Hames     return 1;
4036935c2d3SLang Hames   });
4046935c2d3SLang Hames 
4056935c2d3SLang Hames   // Make sure we don't bail on success.
4066935c2d3SLang Hames   ExitOnErr(Error::success());
4076935c2d3SLang Hames   EXPECT_EQ(ExitOnErr(Expected<int>(7)), 7)
4086935c2d3SLang Hames       << "exitOnError returned an invalid value for Expected";
4096935c2d3SLang Hames 
410285639f8SLang Hames   int A = 7;
411285639f8SLang Hames   int &B = ExitOnErr(Expected<int&>(A));
412285639f8SLang Hames   EXPECT_EQ(&A, &B) << "ExitOnError failed to propagate reference";
413285639f8SLang Hames 
4146935c2d3SLang Hames   // Exit tests.
4156935c2d3SLang Hames   EXPECT_EXIT(ExitOnErr(make_error<CustomError>(7)),
4166935c2d3SLang Hames               ::testing::ExitedWithCode(1), "Error in tool:")
4176935c2d3SLang Hames       << "exitOnError returned an unexpected error result";
4186935c2d3SLang Hames 
4196935c2d3SLang Hames   EXPECT_EXIT(ExitOnErr(Expected<int>(make_error<CustomSubError>(0, 0))),
4206935c2d3SLang Hames               ::testing::ExitedWithCode(2), "Error in tool:")
4216935c2d3SLang Hames       << "exitOnError returned an unexpected error result";
4226935c2d3SLang Hames }
423f7f6d3e9SLang Hames 
424580ca237SLang Hames // Test Checked Expected<T> in success mode.
425580ca237SLang Hames TEST(Error, CheckedExpectedInSuccessMode) {
426f7f6d3e9SLang Hames   Expected<int> A = 7;
42701864a2dSLang Hames   EXPECT_TRUE(!!A) << "Expected with non-error value doesn't convert to 'true'";
428580ca237SLang Hames   // Access is safe in second test, since we checked the error in the first.
429f7f6d3e9SLang Hames   EXPECT_EQ(*A, 7) << "Incorrect Expected non-error value";
430f7f6d3e9SLang Hames }
431f7f6d3e9SLang Hames 
432285639f8SLang Hames // Test Expected with reference type.
433285639f8SLang Hames TEST(Error, ExpectedWithReferenceType) {
434285639f8SLang Hames   int A = 7;
435285639f8SLang Hames   Expected<int&> B = A;
436285639f8SLang Hames   // 'Check' B.
437285639f8SLang Hames   (void)!!B;
438285639f8SLang Hames   int &C = *B;
439285639f8SLang Hames   EXPECT_EQ(&A, &C) << "Expected failed to propagate reference";
440285639f8SLang Hames }
441285639f8SLang Hames 
442580ca237SLang Hames // Test Unchecked Expected<T> in success mode.
443580ca237SLang Hames // We expect this to blow up the same way Error would.
444580ca237SLang Hames // Test runs in debug mode only.
445580ca237SLang Hames #ifndef NDEBUG
446580ca237SLang Hames TEST(Error, UncheckedExpectedInSuccessModeDestruction) {
447580ca237SLang Hames   EXPECT_DEATH({ Expected<int> A = 7; },
448580ca237SLang Hames                "Expected<T> must be checked before access or destruction.")
449580ca237SLang Hames     << "Unchecekd Expected<T> success value did not cause an abort().";
450580ca237SLang Hames }
451580ca237SLang Hames #endif
452580ca237SLang Hames 
453580ca237SLang Hames // Test Unchecked Expected<T> in success mode.
454580ca237SLang Hames // We expect this to blow up the same way Error would.
455580ca237SLang Hames // Test runs in debug mode only.
456580ca237SLang Hames #ifndef NDEBUG
457580ca237SLang Hames TEST(Error, UncheckedExpectedInSuccessModeAccess) {
458580ca237SLang Hames   EXPECT_DEATH({ Expected<int> A = 7; *A; },
459580ca237SLang Hames                "Expected<T> must be checked before access or destruction.")
460580ca237SLang Hames     << "Unchecekd Expected<T> success value did not cause an abort().";
461580ca237SLang Hames }
462580ca237SLang Hames #endif
463580ca237SLang Hames 
464580ca237SLang Hames // Test Unchecked Expected<T> in success mode.
465580ca237SLang Hames // We expect this to blow up the same way Error would.
466580ca237SLang Hames // Test runs in debug mode only.
467580ca237SLang Hames #ifndef NDEBUG
468580ca237SLang Hames TEST(Error, UncheckedExpectedInSuccessModeAssignment) {
469580ca237SLang Hames   EXPECT_DEATH({ Expected<int> A = 7; A = 7; },
470580ca237SLang Hames                "Expected<T> must be checked before access or destruction.")
471580ca237SLang Hames     << "Unchecekd Expected<T> success value did not cause an abort().";
472580ca237SLang Hames }
473580ca237SLang Hames #endif
474580ca237SLang Hames 
47501864a2dSLang Hames // Test Expected<T> in failure mode.
47601864a2dSLang Hames TEST(Error, ExpectedInFailureMode) {
477f7f6d3e9SLang Hames   Expected<int> A = make_error<CustomError>(42);
478f7f6d3e9SLang Hames   EXPECT_FALSE(!!A) << "Expected with error value doesn't convert to 'false'";
479f7f6d3e9SLang Hames   Error E = A.takeError();
480f7f6d3e9SLang Hames   EXPECT_TRUE(E.isA<CustomError>()) << "Incorrect Expected error value";
481f7f6d3e9SLang Hames   consumeError(std::move(E));
482f7f6d3e9SLang Hames }
483f7f6d3e9SLang Hames 
484f7f6d3e9SLang Hames // Check that an Expected instance with an error value doesn't allow access to
485f7f6d3e9SLang Hames // operator*.
486f7f6d3e9SLang Hames // Test runs in debug mode only.
487f7f6d3e9SLang Hames #ifndef NDEBUG
48801864a2dSLang Hames TEST(Error, AccessExpectedInFailureMode) {
489f7f6d3e9SLang Hames   Expected<int> A = make_error<CustomError>(42);
490580ca237SLang Hames   EXPECT_DEATH(*A, "Expected<T> must be checked before access or destruction.")
491f7f6d3e9SLang Hames       << "Incorrect Expected error value";
492f7f6d3e9SLang Hames   consumeError(A.takeError());
493f7f6d3e9SLang Hames }
494f7f6d3e9SLang Hames #endif
495f7f6d3e9SLang Hames 
496f7f6d3e9SLang Hames // Check that an Expected instance with an error triggers an abort if
497f7f6d3e9SLang Hames // unhandled.
498f7f6d3e9SLang Hames // Test runs in debug mode only.
499f7f6d3e9SLang Hames #ifndef NDEBUG
50001864a2dSLang Hames TEST(Error, UnhandledExpectedInFailureMode) {
501f7f6d3e9SLang Hames   EXPECT_DEATH({ Expected<int> A = make_error<CustomError>(42); },
502580ca237SLang Hames                "Expected<T> must be checked before access or destruction.")
503f7f6d3e9SLang Hames       << "Unchecked Expected<T> failure value did not cause an abort()";
50401864a2dSLang Hames }
505f7f6d3e9SLang Hames #endif
506f7f6d3e9SLang Hames 
507f7f6d3e9SLang Hames // Test covariance of Expected.
50801864a2dSLang Hames TEST(Error, ExpectedCovariance) {
509f7f6d3e9SLang Hames   class B {};
510f7f6d3e9SLang Hames   class D : public B {};
511f7f6d3e9SLang Hames 
512f7f6d3e9SLang Hames   Expected<B *> A1(Expected<D *>(nullptr));
513580ca237SLang Hames   // Check A1 by converting to bool before assigning to it.
514580ca237SLang Hames   (void)!!A1;
515f7f6d3e9SLang Hames   A1 = Expected<D *>(nullptr);
516580ca237SLang Hames   // Check A1 again before destruction.
517580ca237SLang Hames   (void)!!A1;
518f7f6d3e9SLang Hames 
519f7f6d3e9SLang Hames   Expected<std::unique_ptr<B>> A2(Expected<std::unique_ptr<D>>(nullptr));
520580ca237SLang Hames   // Check A2 by converting to bool before assigning to it.
521580ca237SLang Hames   (void)!!A2;
522f7f6d3e9SLang Hames   A2 = Expected<std::unique_ptr<D>>(nullptr);
523580ca237SLang Hames   // Check A2 again before destruction.
524580ca237SLang Hames   (void)!!A2;
525f7f6d3e9SLang Hames }
526f7f6d3e9SLang Hames 
527d21a535bSLang Hames TEST(Error, ErrorCodeConversions) {
528f7f6d3e9SLang Hames   // Round-trip a success value to check that it converts correctly.
529f7f6d3e9SLang Hames   EXPECT_EQ(errorToErrorCode(errorCodeToError(std::error_code())),
530f7f6d3e9SLang Hames             std::error_code())
531f7f6d3e9SLang Hames       << "std::error_code() should round-trip via Error conversions";
532f7f6d3e9SLang Hames 
533f7f6d3e9SLang Hames   // Round-trip an error value to check that it converts correctly.
534f7f6d3e9SLang Hames   EXPECT_EQ(errorToErrorCode(errorCodeToError(errc::invalid_argument)),
535f7f6d3e9SLang Hames             errc::invalid_argument)
536f7f6d3e9SLang Hames       << "std::error_code error value should round-trip via Error "
537f7f6d3e9SLang Hames          "conversions";
538d21a535bSLang Hames 
539d21a535bSLang Hames   // Round-trip a success value through ErrorOr/Expected to check that it
540d21a535bSLang Hames   // converts correctly.
541d21a535bSLang Hames   {
542d21a535bSLang Hames     auto Orig = ErrorOr<int>(42);
543d21a535bSLang Hames     auto RoundTripped =
544d21a535bSLang Hames       expectedToErrorOr(errorOrToExpected(ErrorOr<int>(42)));
545d21a535bSLang Hames     EXPECT_EQ(*Orig, *RoundTripped)
546d21a535bSLang Hames       << "ErrorOr<T> success value should round-trip via Expected<T> "
547d21a535bSLang Hames          "conversions.";
548d21a535bSLang Hames   }
549d21a535bSLang Hames 
550d21a535bSLang Hames   // Round-trip a failure value through ErrorOr/Expected to check that it
551d21a535bSLang Hames   // converts correctly.
552d21a535bSLang Hames   {
553d21a535bSLang Hames     auto Orig = ErrorOr<int>(errc::invalid_argument);
554d21a535bSLang Hames     auto RoundTripped =
555d21a535bSLang Hames       expectedToErrorOr(
556d21a535bSLang Hames           errorOrToExpected(ErrorOr<int>(errc::invalid_argument)));
557d21a535bSLang Hames     EXPECT_EQ(Orig.getError(), RoundTripped.getError())
558d21a535bSLang Hames       << "ErrorOr<T> failure value should round-trip via Expected<T> "
559d21a535bSLang Hames          "conversions.";
560d21a535bSLang Hames   }
561f7f6d3e9SLang Hames }
562f7f6d3e9SLang Hames 
56327370a09SVedant Kumar // Test that error messages work.
56427370a09SVedant Kumar TEST(Error, ErrorMessage) {
56527370a09SVedant Kumar   EXPECT_EQ(toString(Error::success()).compare(""), 0);
56627370a09SVedant Kumar 
56727370a09SVedant Kumar   Error E1 = make_error<CustomError>(0);
56827370a09SVedant Kumar   EXPECT_EQ(toString(std::move(E1)).compare("CustomError { 0}"), 0);
56927370a09SVedant Kumar 
57027370a09SVedant Kumar   Error E2 = make_error<CustomError>(0);
57127370a09SVedant Kumar   handleAllErrors(std::move(E2), [](const CustomError &CE) {
57227370a09SVedant Kumar     EXPECT_EQ(CE.message().compare("CustomError { 0}"), 0);
57327370a09SVedant Kumar   });
57427370a09SVedant Kumar 
57527370a09SVedant Kumar   Error E3 = joinErrors(make_error<CustomError>(0), make_error<CustomError>(1));
57627370a09SVedant Kumar   EXPECT_EQ(toString(std::move(E3))
57727370a09SVedant Kumar                 .compare("CustomError { 0}\n"
57827370a09SVedant Kumar                          "CustomError { 1}"),
57927370a09SVedant Kumar             0);
58027370a09SVedant Kumar }
58127370a09SVedant Kumar 
582f7f6d3e9SLang Hames } // end anon namespace
583