1 //===----- unittests/ErrorTest.cpp - Error.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/Error.h"
11 
12 #include "llvm/ADT/Twine.h"
13 #include "llvm/Support/Errc.h"
14 #include "llvm/Support/ErrorHandling.h"
15 #include "gtest/gtest.h"
16 #include <memory>
17 
18 using namespace llvm;
19 
20 namespace {
21 
22 // Custom error class with a default base class and some random 'info' attached.
23 class CustomError : public ErrorInfo<CustomError> {
24 public:
25   // Create an error with some info attached.
26   CustomError(int Info) : Info(Info) {}
27 
28   // Get the info attached to this error.
29   int getInfo() const { return Info; }
30 
31   // Log this error to a stream.
32   void log(raw_ostream &OS) const override {
33     OS << "CustomError { " << getInfo() << "}";
34   }
35 
36   std::error_code convertToErrorCode() const override {
37     llvm_unreachable("CustomError doesn't support ECError conversion");
38   }
39 
40   // Used by ErrorInfo::classID.
41   static char ID;
42 
43 protected:
44   // This error is subclassed below, but we can't use inheriting constructors
45   // yet, so we can't propagate the constructors through ErrorInfo. Instead
46   // we have to have a default constructor and have the subclass initialize all
47   // fields.
48   CustomError() : Info(0) {}
49 
50   int Info;
51 };
52 
53 char CustomError::ID = 0;
54 
55 // Custom error class with a custom base class and some additional random
56 // 'info'.
57 class CustomSubError : public ErrorInfo<CustomSubError, CustomError> {
58 public:
59   // Create a sub-error with some info attached.
60   CustomSubError(int Info, int ExtraInfo) : ExtraInfo(ExtraInfo) {
61     this->Info = Info;
62   }
63 
64   // Get the extra info attached to this error.
65   int getExtraInfo() const { return ExtraInfo; }
66 
67   // Log this error to a stream.
68   void log(raw_ostream &OS) const override {
69     OS << "CustomSubError { " << getInfo() << ", " << getExtraInfo() << "}";
70   }
71 
72   std::error_code convertToErrorCode() const override {
73     llvm_unreachable("CustomSubError doesn't support ECError conversion");
74   }
75 
76   // Used by ErrorInfo::classID.
77   static char ID;
78 
79 protected:
80   int ExtraInfo;
81 };
82 
83 char CustomSubError::ID = 0;
84 
85 static Error handleCustomError(const CustomError &CE) { return Error(); }
86 
87 static void handleCustomErrorVoid(const CustomError &CE) {}
88 
89 static Error handleCustomErrorUP(std::unique_ptr<CustomError> CE) {
90   return Error();
91 }
92 
93 static void handleCustomErrorUPVoid(std::unique_ptr<CustomError> CE) {}
94 
95 // Test that success values implicitly convert to false, and don't cause crashes
96 // once they've been implicitly converted.
97 TEST(Error, CheckedSuccess) {
98   Error E;
99   EXPECT_FALSE(E) << "Unexpected error while testing Error 'Success'";
100 }
101 
102 // Test that unchecked succes values cause an abort.
103 #ifndef NDEBUG
104 TEST(Error, UncheckedSuccess) {
105   EXPECT_DEATH({ Error E; }, "Program aborted due to an unhandled Error:")
106       << "Unchecked Error Succes value did not cause abort()";
107 }
108 #endif
109 
110 // ErrorAsOutParameter tester.
111 void errAsOutParamHelper(Error &Err) {
112   ErrorAsOutParameter ErrAsOutParam(Err);
113   // Verify that checked flag is raised - assignment should not crash.
114   Err = Error::success();
115   // Raise the checked bit manually - caller should still have to test the
116   // error.
117   (void)!!Err;
118 }
119 
120 // Test that ErrorAsOutParameter sets the checked flag on construction.
121 TEST(Error, ErrorAsOutParameterChecked) {
122   Error E;
123   errAsOutParamHelper(E);
124   (void)!!E;
125 }
126 
127 // Test that ErrorAsOutParameter clears the checked flag on destruction.
128 #ifndef NDEBUG
129 TEST(Error, ErrorAsOutParameterUnchecked) {
130   EXPECT_DEATH({ Error E; errAsOutParamHelper(E); },
131                "Program aborted due to an unhandled Error:")
132       << "ErrorAsOutParameter did not clear the checked flag on destruction.";
133 }
134 #endif
135 
136 // Check that we abort on unhandled failure cases. (Force conversion to bool
137 // to make sure that we don't accidentally treat checked errors as handled).
138 // Test runs in debug mode only.
139 #ifndef NDEBUG
140 TEST(Error, UncheckedError) {
141   auto DropUnhandledError = []() {
142     Error E = make_error<CustomError>(42);
143     (void)!E;
144   };
145   EXPECT_DEATH(DropUnhandledError(),
146                "Program aborted due to an unhandled Error:")
147       << "Unhandled Error failure value did not cause abort()";
148 }
149 #endif
150 
151 // Check 'Error::isA<T>' method handling.
152 TEST(Error, IsAHandling) {
153   // Check 'isA' handling.
154   Error E = make_error<CustomError>(1);
155   Error F = make_error<CustomSubError>(1, 2);
156   Error G = Error::success();
157 
158   EXPECT_TRUE(E.isA<CustomError>());
159   EXPECT_FALSE(E.isA<CustomSubError>());
160   EXPECT_TRUE(F.isA<CustomError>());
161   EXPECT_TRUE(F.isA<CustomSubError>());
162   EXPECT_FALSE(G.isA<CustomError>());
163 
164   consumeError(std::move(E));
165   consumeError(std::move(F));
166   consumeError(std::move(G));
167 }
168 
169 // Check that we can handle a custom error.
170 TEST(Error, HandleCustomError) {
171   int CaughtErrorInfo = 0;
172   handleAllErrors(make_error<CustomError>(42), [&](const CustomError &CE) {
173     CaughtErrorInfo = CE.getInfo();
174   });
175 
176   EXPECT_TRUE(CaughtErrorInfo == 42) << "Wrong result from CustomError handler";
177 }
178 
179 // Check that handler type deduction also works for handlers
180 // of the following types:
181 // void (const Err&)
182 // Error (const Err&) mutable
183 // void (const Err&) mutable
184 // Error (Err&)
185 // void (Err&)
186 // Error (Err&) mutable
187 // void (Err&) mutable
188 // Error (unique_ptr<Err>)
189 // void (unique_ptr<Err>)
190 // Error (unique_ptr<Err>) mutable
191 // void (unique_ptr<Err>) mutable
192 TEST(Error, HandlerTypeDeduction) {
193 
194   handleAllErrors(make_error<CustomError>(42), [](const CustomError &CE) {});
195 
196   handleAllErrors(
197       make_error<CustomError>(42),
198       [](const CustomError &CE) mutable { return Error::success(); });
199 
200   handleAllErrors(make_error<CustomError>(42),
201                   [](const CustomError &CE) mutable {});
202 
203   handleAllErrors(make_error<CustomError>(42),
204                   [](CustomError &CE) { return Error::success(); });
205 
206   handleAllErrors(make_error<CustomError>(42), [](CustomError &CE) {});
207 
208   handleAllErrors(make_error<CustomError>(42),
209                   [](CustomError &CE) mutable { return Error::success(); });
210 
211   handleAllErrors(make_error<CustomError>(42), [](CustomError &CE) mutable {});
212 
213   handleAllErrors(
214       make_error<CustomError>(42),
215       [](std::unique_ptr<CustomError> CE) { return Error::success(); });
216 
217   handleAllErrors(make_error<CustomError>(42),
218                   [](std::unique_ptr<CustomError> CE) {});
219 
220   handleAllErrors(
221       make_error<CustomError>(42),
222       [](std::unique_ptr<CustomError> CE) mutable { return Error::success(); });
223 
224   handleAllErrors(make_error<CustomError>(42),
225                   [](std::unique_ptr<CustomError> CE) mutable {});
226 
227   // Check that named handlers of type 'Error (const Err&)' work.
228   handleAllErrors(make_error<CustomError>(42), handleCustomError);
229 
230   // Check that named handlers of type 'void (const Err&)' work.
231   handleAllErrors(make_error<CustomError>(42), handleCustomErrorVoid);
232 
233   // Check that named handlers of type 'Error (std::unique_ptr<Err>)' work.
234   handleAllErrors(make_error<CustomError>(42), handleCustomErrorUP);
235 
236   // Check that named handlers of type 'Error (std::unique_ptr<Err>)' work.
237   handleAllErrors(make_error<CustomError>(42), handleCustomErrorUPVoid);
238 }
239 
240 // Test that we can handle errors with custom base classes.
241 TEST(Error, HandleCustomErrorWithCustomBaseClass) {
242   int CaughtErrorInfo = 0;
243   int CaughtErrorExtraInfo = 0;
244   handleAllErrors(make_error<CustomSubError>(42, 7),
245                   [&](const CustomSubError &SE) {
246                     CaughtErrorInfo = SE.getInfo();
247                     CaughtErrorExtraInfo = SE.getExtraInfo();
248                   });
249 
250   EXPECT_TRUE(CaughtErrorInfo == 42 && CaughtErrorExtraInfo == 7)
251       << "Wrong result from CustomSubError handler";
252 }
253 
254 // Check that we trigger only the first handler that applies.
255 TEST(Error, FirstHandlerOnly) {
256   int DummyInfo = 0;
257   int CaughtErrorInfo = 0;
258   int CaughtErrorExtraInfo = 0;
259 
260   handleAllErrors(make_error<CustomSubError>(42, 7),
261                   [&](const CustomSubError &SE) {
262                     CaughtErrorInfo = SE.getInfo();
263                     CaughtErrorExtraInfo = SE.getExtraInfo();
264                   },
265                   [&](const CustomError &CE) { DummyInfo = CE.getInfo(); });
266 
267   EXPECT_TRUE(CaughtErrorInfo == 42 && CaughtErrorExtraInfo == 7 &&
268               DummyInfo == 0)
269       << "Activated the wrong Error handler(s)";
270 }
271 
272 // Check that general handlers shadow specific ones.
273 TEST(Error, HandlerShadowing) {
274   int CaughtErrorInfo = 0;
275   int DummyInfo = 0;
276   int DummyExtraInfo = 0;
277 
278   handleAllErrors(
279       make_error<CustomSubError>(42, 7),
280       [&](const CustomError &CE) { CaughtErrorInfo = CE.getInfo(); },
281       [&](const CustomSubError &SE) {
282         DummyInfo = SE.getInfo();
283         DummyExtraInfo = SE.getExtraInfo();
284       });
285 
286   EXPECT_TRUE(CaughtErrorInfo == 42 && DummyInfo == 0 && DummyExtraInfo == 0)
287       << "General Error handler did not shadow specific handler";
288 }
289 
290 // Test joinErrors.
291 TEST(Error, CheckJoinErrors) {
292   int CustomErrorInfo1 = 0;
293   int CustomErrorInfo2 = 0;
294   int CustomErrorExtraInfo = 0;
295   Error E =
296       joinErrors(make_error<CustomError>(7), make_error<CustomSubError>(42, 7));
297 
298   handleAllErrors(std::move(E),
299                   [&](const CustomSubError &SE) {
300                     CustomErrorInfo2 = SE.getInfo();
301                     CustomErrorExtraInfo = SE.getExtraInfo();
302                   },
303                   [&](const CustomError &CE) {
304                     // Assert that the CustomError instance above is handled
305                     // before the
306                     // CustomSubError - joinErrors should preserve error
307                     // ordering.
308                     EXPECT_EQ(CustomErrorInfo2, 0)
309                         << "CustomErrorInfo2 should be 0 here. "
310                            "joinErrors failed to preserve ordering.\n";
311                     CustomErrorInfo1 = CE.getInfo();
312                   });
313 
314   EXPECT_TRUE(CustomErrorInfo1 == 7 && CustomErrorInfo2 == 42 &&
315               CustomErrorExtraInfo == 7)
316       << "Failed handling compound Error.";
317 }
318 
319 // Test that we can consume success values.
320 TEST(Error, ConsumeSuccess) {
321   Error E;
322   consumeError(std::move(E));
323 }
324 
325 TEST(Error, ConsumeError) {
326   Error E = make_error<CustomError>(7);
327   consumeError(std::move(E));
328 }
329 
330 // Test that handleAllUnhandledErrors crashes if an error is not caught.
331 // Test runs in debug mode only.
332 #ifndef NDEBUG
333 TEST(Error, FailureToHandle) {
334   auto FailToHandle = []() {
335     handleAllErrors(make_error<CustomError>(7), [&](const CustomSubError &SE) {
336       errs() << "This should never be called";
337       exit(1);
338     });
339   };
340 
341   EXPECT_DEATH(FailToHandle(), "Program aborted due to an unhandled Error:")
342       << "Unhandled Error in handleAllErrors call did not cause an "
343          "abort()";
344 }
345 #endif
346 
347 // Test that handleAllUnhandledErrors crashes if an error is returned from a
348 // handler.
349 // Test runs in debug mode only.
350 #ifndef NDEBUG
351 TEST(Error, FailureFromHandler) {
352   auto ReturnErrorFromHandler = []() {
353     handleAllErrors(make_error<CustomError>(7),
354                     [&](std::unique_ptr<CustomSubError> SE) {
355                       return Error(std::move(SE));
356                     });
357   };
358 
359   EXPECT_DEATH(ReturnErrorFromHandler(),
360                "Program aborted due to an unhandled Error:")
361       << " Error returned from handler in handleAllErrors call did not "
362          "cause abort()";
363 }
364 #endif
365 
366 // Test that we can return values from handleErrors.
367 TEST(Error, CatchErrorFromHandler) {
368   int ErrorInfo = 0;
369 
370   Error E = handleErrors(
371       make_error<CustomError>(7),
372       [&](std::unique_ptr<CustomError> CE) { return Error(std::move(CE)); });
373 
374   handleAllErrors(std::move(E),
375                   [&](const CustomError &CE) { ErrorInfo = CE.getInfo(); });
376 
377   EXPECT_EQ(ErrorInfo, 7)
378       << "Failed to handle Error returned from handleErrors.";
379 }
380 
381 TEST(Error, StringError) {
382   std::string Msg;
383   raw_string_ostream S(Msg);
384   logAllUnhandledErrors(make_error<StringError>("foo" + Twine(42),
385                                                 inconvertibleErrorCode()),
386                         S, "");
387   EXPECT_EQ(S.str(), "foo42\n") << "Unexpected StringError log result";
388 
389   auto EC =
390     errorToErrorCode(make_error<StringError>("", errc::invalid_argument));
391   EXPECT_EQ(EC, errc::invalid_argument)
392     << "Failed to convert StringError to error_code.";
393 }
394 
395 // Test that the ExitOnError utility works as expected.
396 TEST(Error, ExitOnError) {
397   ExitOnError ExitOnErr;
398   ExitOnErr.setBanner("Error in tool:");
399   ExitOnErr.setExitCodeMapper([](const Error &E) {
400     if (E.isA<CustomSubError>())
401       return 2;
402     return 1;
403   });
404 
405   // Make sure we don't bail on success.
406   ExitOnErr(Error::success());
407   EXPECT_EQ(ExitOnErr(Expected<int>(7)), 7)
408       << "exitOnError returned an invalid value for Expected";
409 
410   int A = 7;
411   int &B = ExitOnErr(Expected<int&>(A));
412   EXPECT_EQ(&A, &B) << "ExitOnError failed to propagate reference";
413 
414   // Exit tests.
415   EXPECT_EXIT(ExitOnErr(make_error<CustomError>(7)),
416               ::testing::ExitedWithCode(1), "Error in tool:")
417       << "exitOnError returned an unexpected error result";
418 
419   EXPECT_EXIT(ExitOnErr(Expected<int>(make_error<CustomSubError>(0, 0))),
420               ::testing::ExitedWithCode(2), "Error in tool:")
421       << "exitOnError returned an unexpected error result";
422 }
423 
424 // Test Checked Expected<T> in success mode.
425 TEST(Error, CheckedExpectedInSuccessMode) {
426   Expected<int> A = 7;
427   EXPECT_TRUE(!!A) << "Expected with non-error value doesn't convert to 'true'";
428   // Access is safe in second test, since we checked the error in the first.
429   EXPECT_EQ(*A, 7) << "Incorrect Expected non-error value";
430 }
431 
432 // Test Expected with reference type.
433 TEST(Error, ExpectedWithReferenceType) {
434   int A = 7;
435   Expected<int&> B = A;
436   // 'Check' B.
437   (void)!!B;
438   int &C = *B;
439   EXPECT_EQ(&A, &C) << "Expected failed to propagate reference";
440 }
441 
442 // Test Unchecked Expected<T> in success mode.
443 // We expect this to blow up the same way Error would.
444 // Test runs in debug mode only.
445 #ifndef NDEBUG
446 TEST(Error, UncheckedExpectedInSuccessModeDestruction) {
447   EXPECT_DEATH({ Expected<int> A = 7; },
448                "Expected<T> must be checked before access or destruction.")
449     << "Unchecekd Expected<T> success value did not cause an abort().";
450 }
451 #endif
452 
453 // Test Unchecked Expected<T> in success mode.
454 // We expect this to blow up the same way Error would.
455 // Test runs in debug mode only.
456 #ifndef NDEBUG
457 TEST(Error, UncheckedExpectedInSuccessModeAccess) {
458   EXPECT_DEATH({ Expected<int> A = 7; *A; },
459                "Expected<T> must be checked before access or destruction.")
460     << "Unchecekd Expected<T> success value did not cause an abort().";
461 }
462 #endif
463 
464 // Test Unchecked Expected<T> in success mode.
465 // We expect this to blow up the same way Error would.
466 // Test runs in debug mode only.
467 #ifndef NDEBUG
468 TEST(Error, UncheckedExpectedInSuccessModeAssignment) {
469   EXPECT_DEATH({ Expected<int> A = 7; A = 7; },
470                "Expected<T> must be checked before access or destruction.")
471     << "Unchecekd Expected<T> success value did not cause an abort().";
472 }
473 #endif
474 
475 // Test Expected<T> in failure mode.
476 TEST(Error, ExpectedInFailureMode) {
477   Expected<int> A = make_error<CustomError>(42);
478   EXPECT_FALSE(!!A) << "Expected with error value doesn't convert to 'false'";
479   Error E = A.takeError();
480   EXPECT_TRUE(E.isA<CustomError>()) << "Incorrect Expected error value";
481   consumeError(std::move(E));
482 }
483 
484 // Check that an Expected instance with an error value doesn't allow access to
485 // operator*.
486 // Test runs in debug mode only.
487 #ifndef NDEBUG
488 TEST(Error, AccessExpectedInFailureMode) {
489   Expected<int> A = make_error<CustomError>(42);
490   EXPECT_DEATH(*A, "Expected<T> must be checked before access or destruction.")
491       << "Incorrect Expected error value";
492   consumeError(A.takeError());
493 }
494 #endif
495 
496 // Check that an Expected instance with an error triggers an abort if
497 // unhandled.
498 // Test runs in debug mode only.
499 #ifndef NDEBUG
500 TEST(Error, UnhandledExpectedInFailureMode) {
501   EXPECT_DEATH({ Expected<int> A = make_error<CustomError>(42); },
502                "Expected<T> must be checked before access or destruction.")
503       << "Unchecked Expected<T> failure value did not cause an abort()";
504 }
505 #endif
506 
507 // Test covariance of Expected.
508 TEST(Error, ExpectedCovariance) {
509   class B {};
510   class D : public B {};
511 
512   Expected<B *> A1(Expected<D *>(nullptr));
513   // Check A1 by converting to bool before assigning to it.
514   (void)!!A1;
515   A1 = Expected<D *>(nullptr);
516   // Check A1 again before destruction.
517   (void)!!A1;
518 
519   Expected<std::unique_ptr<B>> A2(Expected<std::unique_ptr<D>>(nullptr));
520   // Check A2 by converting to bool before assigning to it.
521   (void)!!A2;
522   A2 = Expected<std::unique_ptr<D>>(nullptr);
523   // Check A2 again before destruction.
524   (void)!!A2;
525 }
526 
527 TEST(Error, ErrorCodeConversions) {
528   // Round-trip a success value to check that it converts correctly.
529   EXPECT_EQ(errorToErrorCode(errorCodeToError(std::error_code())),
530             std::error_code())
531       << "std::error_code() should round-trip via Error conversions";
532 
533   // Round-trip an error value to check that it converts correctly.
534   EXPECT_EQ(errorToErrorCode(errorCodeToError(errc::invalid_argument)),
535             errc::invalid_argument)
536       << "std::error_code error value should round-trip via Error "
537          "conversions";
538 
539   // Round-trip a success value through ErrorOr/Expected to check that it
540   // converts correctly.
541   {
542     auto Orig = ErrorOr<int>(42);
543     auto RoundTripped =
544       expectedToErrorOr(errorOrToExpected(ErrorOr<int>(42)));
545     EXPECT_EQ(*Orig, *RoundTripped)
546       << "ErrorOr<T> success value should round-trip via Expected<T> "
547          "conversions.";
548   }
549 
550   // Round-trip a failure value through ErrorOr/Expected to check that it
551   // converts correctly.
552   {
553     auto Orig = ErrorOr<int>(errc::invalid_argument);
554     auto RoundTripped =
555       expectedToErrorOr(
556           errorOrToExpected(ErrorOr<int>(errc::invalid_argument)));
557     EXPECT_EQ(Orig.getError(), RoundTripped.getError())
558       << "ErrorOr<T> failure value should round-trip via Expected<T> "
559          "conversions.";
560   }
561 }
562 
563 // Test that error messages work.
564 TEST(Error, ErrorMessage) {
565   EXPECT_EQ(toString(Error::success()).compare(""), 0);
566 
567   Error E1 = make_error<CustomError>(0);
568   EXPECT_EQ(toString(std::move(E1)).compare("CustomError { 0}"), 0);
569 
570   Error E2 = make_error<CustomError>(0);
571   handleAllErrors(std::move(E2), [](const CustomError &CE) {
572     EXPECT_EQ(CE.message().compare("CustomError { 0}"), 0);
573   });
574 
575   Error E3 = joinErrors(make_error<CustomError>(0), make_error<CustomError>(1));
576   EXPECT_EQ(toString(std::move(E3))
577                 .compare("CustomError { 0}\n"
578                          "CustomError { 1}"),
579             0);
580 }
581 
582 } // end anon namespace
583