xref: /llvm-project/llvm/unittests/Support/ErrorTest.cpp (revision b5f6cc9eb4f661816ef264ad41cb703004380636)
1 //===----- unittests/ErrorTest.cpp - Error.h 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/Support/Error.h"
10 #include "llvm-c/Error.h"
11 
12 #include "llvm/ADT/Twine.h"
13 #include "llvm/Support/Errc.h"
14 #include "llvm/Support/ErrorHandling.h"
15 #include "llvm/Testing/Support/Error.h"
16 #include "gmock/gmock.h"
17 #include "gtest/gtest-spi.h"
18 #include "gtest/gtest.h"
19 #include <memory>
20 
21 using namespace llvm;
22 
23 namespace {
24 
25 // Custom error class with a default base class and some random 'info' attached.
26 class CustomError : public ErrorInfo<CustomError> {
27 public:
28   // Create an error with some info attached.
29   CustomError(int Info) : Info(Info) {}
30 
31   // Get the info attached to this error.
32   int getInfo() const { return Info; }
33 
34   // Log this error to a stream.
35   void log(raw_ostream &OS) const override {
36     OS << "CustomError {" << getInfo() << "}";
37   }
38 
39   std::error_code convertToErrorCode() const override {
40     llvm_unreachable("CustomError doesn't support ECError conversion");
41   }
42 
43   // Used by ErrorInfo::classID.
44   static char ID;
45 
46 protected:
47   // This error is subclassed below, but we can't use inheriting constructors
48   // yet, so we can't propagate the constructors through ErrorInfo. Instead
49   // we have to have a default constructor and have the subclass initialize all
50   // fields.
51   CustomError() : Info(0) {}
52 
53   int Info;
54 };
55 
56 char CustomError::ID = 0;
57 
58 // Custom error class with a custom base class and some additional random
59 // 'info'.
60 class CustomSubError : public ErrorInfo<CustomSubError, CustomError> {
61 public:
62   // Create a sub-error with some info attached.
63   CustomSubError(int Info, int ExtraInfo) : ExtraInfo(ExtraInfo) {
64     this->Info = Info;
65   }
66 
67   // Get the extra info attached to this error.
68   int getExtraInfo() const { return ExtraInfo; }
69 
70   // Log this error to a stream.
71   void log(raw_ostream &OS) const override {
72     OS << "CustomSubError { " << getInfo() << ", " << getExtraInfo() << "}";
73   }
74 
75   std::error_code convertToErrorCode() const override {
76     llvm_unreachable("CustomSubError doesn't support ECError conversion");
77   }
78 
79   // Used by ErrorInfo::classID.
80   static char ID;
81 
82 protected:
83   int ExtraInfo;
84 };
85 
86 char CustomSubError::ID = 0;
87 
88 static Error handleCustomError(const CustomError &CE) {
89   return Error::success();
90 }
91 
92 static void handleCustomErrorVoid(const CustomError &CE) {}
93 
94 static Error handleCustomErrorUP(std::unique_ptr<CustomError> CE) {
95   return Error::success();
96 }
97 
98 static void handleCustomErrorUPVoid(std::unique_ptr<CustomError> CE) {}
99 
100 // Test that success values implicitly convert to false, and don't cause crashes
101 // once they've been implicitly converted.
102 TEST(Error, CheckedSuccess) {
103   Error E = Error::success();
104   EXPECT_FALSE(E) << "Unexpected error while testing Error 'Success'";
105 }
106 
107 // Test that unchecked success values cause an abort.
108 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
109 TEST(Error, UncheckedSuccess) {
110   EXPECT_DEATH({ Error E = Error::success(); },
111                "Program aborted due to an unhandled Error:")
112       << "Unchecked Error Succes value did not cause abort()";
113 }
114 #endif
115 
116 // ErrorAsOutParameter tester.
117 void errAsOutParamHelper(Error &Err) {
118   ErrorAsOutParameter ErrAsOutParam(&Err);
119   // Verify that checked flag is raised - assignment should not crash.
120   Err = Error::success();
121   // Raise the checked bit manually - caller should still have to test the
122   // error.
123   (void)!!Err;
124 }
125 
126 // Test that ErrorAsOutParameter sets the checked flag on construction.
127 TEST(Error, ErrorAsOutParameterChecked) {
128   Error E = Error::success();
129   errAsOutParamHelper(E);
130   (void)!!E;
131 }
132 
133 // Test that ErrorAsOutParameter clears the checked flag on destruction.
134 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
135 TEST(Error, ErrorAsOutParameterUnchecked) {
136   EXPECT_DEATH({ Error E = Error::success(); errAsOutParamHelper(E); },
137                "Program aborted due to an unhandled Error:")
138       << "ErrorAsOutParameter did not clear the checked flag on destruction.";
139 }
140 #endif
141 
142 // Check that we abort on unhandled failure cases. (Force conversion to bool
143 // to make sure that we don't accidentally treat checked errors as handled).
144 // Test runs in debug mode only.
145 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
146 TEST(Error, UncheckedError) {
147   auto DropUnhandledError = []() {
148     Error E = make_error<CustomError>(42);
149     (void)!E;
150   };
151   EXPECT_DEATH(DropUnhandledError(),
152                "Program aborted due to an unhandled Error:")
153       << "Unhandled Error failure value did not cause abort()";
154 }
155 #endif
156 
157 // Check 'Error::isA<T>' method handling.
158 TEST(Error, IsAHandling) {
159   // Check 'isA' handling.
160   Error E = make_error<CustomError>(1);
161   Error F = make_error<CustomSubError>(1, 2);
162   Error G = Error::success();
163 
164   EXPECT_TRUE(E.isA<CustomError>());
165   EXPECT_FALSE(E.isA<CustomSubError>());
166   EXPECT_TRUE(F.isA<CustomError>());
167   EXPECT_TRUE(F.isA<CustomSubError>());
168   EXPECT_FALSE(G.isA<CustomError>());
169 
170   consumeError(std::move(E));
171   consumeError(std::move(F));
172   consumeError(std::move(G));
173 }
174 
175 // Check that we can handle a custom error.
176 TEST(Error, HandleCustomError) {
177   int CaughtErrorInfo = 0;
178   handleAllErrors(make_error<CustomError>(42), [&](const CustomError &CE) {
179     CaughtErrorInfo = CE.getInfo();
180   });
181 
182   EXPECT_EQ(CaughtErrorInfo, 42) << "Wrong result from CustomError handler";
183 }
184 
185 // Check that handler type deduction also works for handlers
186 // of the following types:
187 // void (const Err&)
188 // Error (const Err&) mutable
189 // void (const Err&) mutable
190 // Error (Err&)
191 // void (Err&)
192 // Error (Err&) mutable
193 // void (Err&) mutable
194 // Error (unique_ptr<Err>)
195 // void (unique_ptr<Err>)
196 // Error (unique_ptr<Err>) mutable
197 // void (unique_ptr<Err>) mutable
198 TEST(Error, HandlerTypeDeduction) {
199 
200   handleAllErrors(make_error<CustomError>(42), [](const CustomError &CE) {});
201 
202   handleAllErrors(
203       make_error<CustomError>(42),
204       [](const CustomError &CE) mutable  -> Error { return Error::success(); });
205 
206   handleAllErrors(make_error<CustomError>(42),
207                   [](const CustomError &CE) mutable {});
208 
209   handleAllErrors(make_error<CustomError>(42),
210                   [](CustomError &CE) -> Error { return Error::success(); });
211 
212   handleAllErrors(make_error<CustomError>(42), [](CustomError &CE) {});
213 
214   handleAllErrors(make_error<CustomError>(42),
215                   [](CustomError &CE) mutable -> Error { return Error::success(); });
216 
217   handleAllErrors(make_error<CustomError>(42), [](CustomError &CE) mutable {});
218 
219   handleAllErrors(
220       make_error<CustomError>(42),
221       [](std::unique_ptr<CustomError> CE) -> Error { return Error::success(); });
222 
223   handleAllErrors(make_error<CustomError>(42),
224                   [](std::unique_ptr<CustomError> CE) {});
225 
226   handleAllErrors(
227       make_error<CustomError>(42),
228       [](std::unique_ptr<CustomError> CE) mutable -> Error { return Error::success(); });
229 
230   handleAllErrors(make_error<CustomError>(42),
231                   [](std::unique_ptr<CustomError> CE) mutable {});
232 
233   // Check that named handlers of type 'Error (const Err&)' work.
234   handleAllErrors(make_error<CustomError>(42), handleCustomError);
235 
236   // Check that named handlers of type 'void (const Err&)' work.
237   handleAllErrors(make_error<CustomError>(42), handleCustomErrorVoid);
238 
239   // Check that named handlers of type 'Error (std::unique_ptr<Err>)' work.
240   handleAllErrors(make_error<CustomError>(42), handleCustomErrorUP);
241 
242   // Check that named handlers of type 'Error (std::unique_ptr<Err>)' work.
243   handleAllErrors(make_error<CustomError>(42), handleCustomErrorUPVoid);
244 }
245 
246 // Test that we can handle errors with custom base classes.
247 TEST(Error, HandleCustomErrorWithCustomBaseClass) {
248   int CaughtErrorInfo = 0;
249   int CaughtErrorExtraInfo = 0;
250   handleAllErrors(make_error<CustomSubError>(42, 7),
251                   [&](const CustomSubError &SE) {
252                     CaughtErrorInfo = SE.getInfo();
253                     CaughtErrorExtraInfo = SE.getExtraInfo();
254                   });
255 
256   EXPECT_EQ(CaughtErrorInfo, 42) << "Wrong result from CustomSubError handler";
257   EXPECT_EQ(CaughtErrorExtraInfo, 7)
258       << "Wrong result from CustomSubError handler";
259 }
260 
261 // Check that we trigger only the first handler that applies.
262 TEST(Error, FirstHandlerOnly) {
263   int DummyInfo = 0;
264   int CaughtErrorInfo = 0;
265   int CaughtErrorExtraInfo = 0;
266 
267   handleAllErrors(make_error<CustomSubError>(42, 7),
268                   [&](const CustomSubError &SE) {
269                     CaughtErrorInfo = SE.getInfo();
270                     CaughtErrorExtraInfo = SE.getExtraInfo();
271                   },
272                   [&](const CustomError &CE) { DummyInfo = CE.getInfo(); });
273 
274   EXPECT_EQ(CaughtErrorInfo, 42) << "Activated the wrong Error handler(s)";
275   EXPECT_EQ(CaughtErrorExtraInfo, 7) << "Activated the wrong Error handler(s)";
276   EXPECT_EQ(DummyInfo, 0) << "Activated the wrong Error handler(s)";
277 }
278 
279 // Check that general handlers shadow specific ones.
280 TEST(Error, HandlerShadowing) {
281   int CaughtErrorInfo = 0;
282   int DummyInfo = 0;
283   int DummyExtraInfo = 0;
284 
285   handleAllErrors(
286       make_error<CustomSubError>(42, 7),
287       [&](const CustomError &CE) { CaughtErrorInfo = CE.getInfo(); },
288       [&](const CustomSubError &SE) {
289         DummyInfo = SE.getInfo();
290         DummyExtraInfo = SE.getExtraInfo();
291       });
292 
293   EXPECT_EQ(CaughtErrorInfo, 42)
294       << "General Error handler did not shadow specific handler";
295   EXPECT_EQ(DummyInfo, 0)
296       << "General Error handler did not shadow specific handler";
297   EXPECT_EQ(DummyExtraInfo, 0)
298       << "General Error handler did not shadow specific handler";
299 }
300 
301 // Test joinErrors.
302 TEST(Error, CheckJoinErrors) {
303   int CustomErrorInfo1 = 0;
304   int CustomErrorInfo2 = 0;
305   int CustomErrorExtraInfo = 0;
306   Error E =
307       joinErrors(make_error<CustomError>(7), make_error<CustomSubError>(42, 7));
308 
309   handleAllErrors(std::move(E),
310                   [&](const CustomSubError &SE) {
311                     CustomErrorInfo2 = SE.getInfo();
312                     CustomErrorExtraInfo = SE.getExtraInfo();
313                   },
314                   [&](const CustomError &CE) {
315                     // Assert that the CustomError instance above is handled
316                     // before the
317                     // CustomSubError - joinErrors should preserve error
318                     // ordering.
319                     EXPECT_EQ(CustomErrorInfo2, 0)
320                         << "CustomErrorInfo2 should be 0 here. "
321                            "joinErrors failed to preserve ordering.\n";
322                     CustomErrorInfo1 = CE.getInfo();
323                   });
324 
325   EXPECT_EQ(CustomErrorInfo1, 7) << "Failed handling compound Error.";
326   EXPECT_EQ(CustomErrorInfo2, 42) << "Failed handling compound Error.";
327   EXPECT_EQ(CustomErrorExtraInfo, 7) << "Failed handling compound Error.";
328 
329   // Test appending a single item to a list.
330   {
331     int Sum = 0;
332     handleAllErrors(
333         joinErrors(
334             joinErrors(make_error<CustomError>(7),
335                        make_error<CustomError>(7)),
336             make_error<CustomError>(7)),
337         [&](const CustomError &CE) {
338           Sum += CE.getInfo();
339         });
340     EXPECT_EQ(Sum, 21) << "Failed to correctly append error to error list.";
341   }
342 
343   // Test prepending a single item to a list.
344   {
345     int Sum = 0;
346     handleAllErrors(
347         joinErrors(
348             make_error<CustomError>(7),
349             joinErrors(make_error<CustomError>(7),
350                        make_error<CustomError>(7))),
351         [&](const CustomError &CE) {
352           Sum += CE.getInfo();
353         });
354     EXPECT_EQ(Sum, 21) << "Failed to correctly prepend error to error list.";
355   }
356 
357   // Test concatenating two error lists.
358   {
359     int Sum = 0;
360     handleAllErrors(
361         joinErrors(
362             joinErrors(
363                 make_error<CustomError>(7),
364                 make_error<CustomError>(7)),
365             joinErrors(
366                 make_error<CustomError>(7),
367                 make_error<CustomError>(7))),
368         [&](const CustomError &CE) {
369           Sum += CE.getInfo();
370         });
371     EXPECT_EQ(Sum, 28) << "Failed to correctly concatenate error lists.";
372   }
373 }
374 
375 // Test that we can consume success values.
376 TEST(Error, ConsumeSuccess) {
377   Error E = Error::success();
378   consumeError(std::move(E));
379 }
380 
381 TEST(Error, ConsumeError) {
382   Error E = make_error<CustomError>(7);
383   consumeError(std::move(E));
384 }
385 
386 // Test that handleAllUnhandledErrors crashes if an error is not caught.
387 // Test runs in debug mode only.
388 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
389 TEST(Error, FailureToHandle) {
390   auto FailToHandle = []() {
391     handleAllErrors(make_error<CustomError>(7), [&](const CustomSubError &SE) {
392       errs() << "This should never be called";
393       exit(1);
394     });
395   };
396 
397   EXPECT_DEATH(FailToHandle(),
398                "Failure value returned from cantFail wrapped call\n"
399                "CustomError \\{7\\}")
400       << "Unhandled Error in handleAllErrors call did not cause an "
401          "abort()";
402 }
403 #endif
404 
405 // Test that handleAllUnhandledErrors crashes if an error is returned from a
406 // handler.
407 // Test runs in debug mode only.
408 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
409 TEST(Error, FailureFromHandler) {
410   auto ReturnErrorFromHandler = []() {
411     handleAllErrors(make_error<CustomError>(7),
412                     [&](std::unique_ptr<CustomSubError> SE) {
413                       return Error(std::move(SE));
414                     });
415   };
416 
417   EXPECT_DEATH(ReturnErrorFromHandler(),
418                "Failure value returned from cantFail wrapped call\n"
419                "CustomError \\{7\\}")
420       << " Error returned from handler in handleAllErrors call did not "
421          "cause abort()";
422 }
423 #endif
424 
425 // Test that we can return values from handleErrors.
426 TEST(Error, CatchErrorFromHandler) {
427   int ErrorInfo = 0;
428 
429   Error E = handleErrors(
430       make_error<CustomError>(7),
431       [&](std::unique_ptr<CustomError> CE) { return Error(std::move(CE)); });
432 
433   handleAllErrors(std::move(E),
434                   [&](const CustomError &CE) { ErrorInfo = CE.getInfo(); });
435 
436   EXPECT_EQ(ErrorInfo, 7)
437       << "Failed to handle Error returned from handleErrors.";
438 }
439 
440 TEST(Error, StringError) {
441   std::string Msg;
442   raw_string_ostream S(Msg);
443   logAllUnhandledErrors(
444       make_error<StringError>("foo" + Twine(42), inconvertibleErrorCode()), S);
445   EXPECT_EQ(S.str(), "foo42\n") << "Unexpected StringError log result";
446 
447   auto EC =
448     errorToErrorCode(make_error<StringError>("", errc::invalid_argument));
449   EXPECT_EQ(EC, errc::invalid_argument)
450     << "Failed to convert StringError to error_code.";
451 }
452 
453 TEST(Error, createStringError) {
454   static const char *Bar = "bar";
455   static const std::error_code EC = errc::invalid_argument;
456   std::string Msg;
457   raw_string_ostream S(Msg);
458   logAllUnhandledErrors(createStringError(EC, "foo%s%d0x%" PRIx8, Bar, 1, 0xff),
459                         S);
460   EXPECT_EQ(S.str(), "foobar10xff\n")
461     << "Unexpected createStringError() log result";
462 
463   S.flush();
464   Msg.clear();
465   logAllUnhandledErrors(createStringError(EC, Bar), S);
466   EXPECT_EQ(S.str(), "bar\n")
467     << "Unexpected createStringError() (overloaded) log result";
468 
469   S.flush();
470   Msg.clear();
471   auto Res = errorToErrorCode(createStringError(EC, "foo%s", Bar));
472   EXPECT_EQ(Res, EC)
473     << "Failed to convert createStringError() result to error_code.";
474 }
475 
476 // Test that the ExitOnError utility works as expected.
477 TEST(ErrorDeathTest, ExitOnError) {
478   ExitOnError ExitOnErr;
479   ExitOnErr.setBanner("Error in tool:");
480   ExitOnErr.setExitCodeMapper([](const Error &E) {
481     if (E.isA<CustomSubError>())
482       return 2;
483     return 1;
484   });
485 
486   // Make sure we don't bail on success.
487   ExitOnErr(Error::success());
488   EXPECT_EQ(ExitOnErr(Expected<int>(7)), 7)
489       << "exitOnError returned an invalid value for Expected";
490 
491   int A = 7;
492   int &B = ExitOnErr(Expected<int&>(A));
493   EXPECT_EQ(&A, &B) << "ExitOnError failed to propagate reference";
494 
495   // Exit tests.
496   EXPECT_EXIT(ExitOnErr(make_error<CustomError>(7)),
497               ::testing::ExitedWithCode(1), "Error in tool:")
498       << "exitOnError returned an unexpected error result";
499 
500   EXPECT_EXIT(ExitOnErr(Expected<int>(make_error<CustomSubError>(0, 0))),
501               ::testing::ExitedWithCode(2), "Error in tool:")
502       << "exitOnError returned an unexpected error result";
503 }
504 
505 // Test that the ExitOnError utility works as expected.
506 TEST(Error, CantFailSuccess) {
507   cantFail(Error::success());
508 
509   int X = cantFail(Expected<int>(42));
510   EXPECT_EQ(X, 42) << "Expected value modified by cantFail";
511 
512   int Dummy = 42;
513   int &Y = cantFail(Expected<int&>(Dummy));
514   EXPECT_EQ(&Dummy, &Y) << "Reference mangled by cantFail";
515 }
516 
517 // Test that cantFail results in a crash if you pass it a failure value.
518 #if LLVM_ENABLE_ABI_BREAKING_CHECKS && !defined(NDEBUG)
519 TEST(Error, CantFailDeath) {
520   EXPECT_DEATH(cantFail(make_error<StringError>("Original error message",
521                                                 inconvertibleErrorCode()),
522                         "Cantfail call failed"),
523                "Cantfail call failed\n"
524                "Original error message")
525       << "cantFail(Error) did not cause an abort for failure value";
526 
527   EXPECT_DEATH(
528       {
529         auto IEC = inconvertibleErrorCode();
530         int X = cantFail(Expected<int>(make_error<StringError>("foo", IEC)));
531         (void)X;
532       },
533       "Failure value returned from cantFail wrapped call")
534     << "cantFail(Expected<int>) did not cause an abort for failure value";
535 }
536 #endif
537 
538 
539 // Test Checked Expected<T> in success mode.
540 TEST(Error, CheckedExpectedInSuccessMode) {
541   Expected<int> A = 7;
542   EXPECT_TRUE(!!A) << "Expected with non-error value doesn't convert to 'true'";
543   // Access is safe in second test, since we checked the error in the first.
544   EXPECT_EQ(*A, 7) << "Incorrect Expected non-error value";
545 }
546 
547 // Test Expected with reference type.
548 TEST(Error, ExpectedWithReferenceType) {
549   int A = 7;
550   Expected<int&> B = A;
551   // 'Check' B.
552   (void)!!B;
553   int &C = *B;
554   EXPECT_EQ(&A, &C) << "Expected failed to propagate reference";
555 }
556 
557 // Test Unchecked Expected<T> in success mode.
558 // We expect this to blow up the same way Error would.
559 // Test runs in debug mode only.
560 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
561 TEST(Error, UncheckedExpectedInSuccessModeDestruction) {
562   EXPECT_DEATH({ Expected<int> A = 7; },
563                "Expected<T> must be checked before access or destruction.")
564       << "Unchecked Expected<T> success value did not cause an abort().";
565 }
566 #endif
567 
568 // Test Unchecked Expected<T> in success mode.
569 // We expect this to blow up the same way Error would.
570 // Test runs in debug mode only.
571 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
572 TEST(Error, UncheckedExpectedInSuccessModeAccess) {
573   EXPECT_DEATH(
574       {
575         const Expected<int> A = 7;
576         *A;
577       },
578       "Expected<T> must be checked before access or destruction.")
579       << "Unchecked Expected<T> success value did not cause an abort().";
580 }
581 #endif
582 
583 // Test Unchecked Expected<T> in success mode.
584 // We expect this to blow up the same way Error would.
585 // Test runs in debug mode only.
586 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
587 TEST(Error, UncheckedExpectedInSuccessModeAssignment) {
588   EXPECT_DEATH(
589       {
590         Expected<int> A = 7;
591         A = 7;
592       },
593       "Expected<T> must be checked before access or destruction.")
594       << "Unchecked Expected<T> success value did not cause an abort().";
595 }
596 #endif
597 
598 // Test Expected<T> in failure mode.
599 TEST(Error, ExpectedInFailureMode) {
600   Expected<int> A = make_error<CustomError>(42);
601   EXPECT_FALSE(!!A) << "Expected with error value doesn't convert to 'false'";
602   Error E = A.takeError();
603   EXPECT_TRUE(E.isA<CustomError>()) << "Incorrect Expected error value";
604   consumeError(std::move(E));
605 }
606 
607 // Check that an Expected instance with an error value doesn't allow access to
608 // operator*.
609 // Test runs in debug mode only.
610 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
611 TEST(Error, AccessExpectedInFailureMode) {
612   Expected<int> A = make_error<CustomError>(42);
613   EXPECT_DEATH(*A, "Expected<T> must be checked before access or destruction.")
614       << "Incorrect Expected error value";
615   consumeError(A.takeError());
616 }
617 #endif
618 
619 // Check that an Expected instance with an error triggers an abort if
620 // unhandled.
621 // Test runs in debug mode only.
622 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
623 TEST(Error, UnhandledExpectedInFailureMode) {
624   EXPECT_DEATH({ Expected<int> A = make_error<CustomError>(42); },
625                "Expected<T> must be checked before access or destruction.")
626       << "Unchecked Expected<T> failure value did not cause an abort()";
627 }
628 #endif
629 
630 // Test covariance of Expected.
631 TEST(Error, ExpectedCovariance) {
632   class B {};
633   class D : public B {};
634 
635   Expected<B *> A1(Expected<D *>(nullptr));
636   // Check A1 by converting to bool before assigning to it.
637   (void)!!A1;
638   A1 = Expected<D *>(nullptr);
639   // Check A1 again before destruction.
640   (void)!!A1;
641 
642   Expected<std::unique_ptr<B>> A2(Expected<std::unique_ptr<D>>(nullptr));
643   // Check A2 by converting to bool before assigning to it.
644   (void)!!A2;
645   A2 = Expected<std::unique_ptr<D>>(nullptr);
646   // Check A2 again before destruction.
647   (void)!!A2;
648 }
649 
650 // Test that handleExpected just returns success values.
651 TEST(Error, HandleExpectedSuccess) {
652   auto ValOrErr =
653     handleExpected(Expected<int>(42),
654                    []() { return Expected<int>(43); });
655   EXPECT_TRUE(!!ValOrErr)
656     << "handleExpected should have returned a success value here";
657   EXPECT_EQ(*ValOrErr, 42)
658     << "handleExpected should have returned the original success value here";
659 }
660 
661 enum FooStrategy { Aggressive, Conservative };
662 
663 static Expected<int> foo(FooStrategy S) {
664   if (S == Aggressive)
665     return make_error<CustomError>(7);
666   return 42;
667 }
668 
669 // Test that handleExpected invokes the error path if errors are not handled.
670 TEST(Error, HandleExpectedUnhandledError) {
671   // foo(Aggressive) should return a CustomError which should pass through as
672   // there is no handler for CustomError.
673   auto ValOrErr =
674     handleExpected(
675       foo(Aggressive),
676       []() { return foo(Conservative); });
677 
678   EXPECT_FALSE(!!ValOrErr)
679     << "handleExpected should have returned an error here";
680   auto Err = ValOrErr.takeError();
681   EXPECT_TRUE(Err.isA<CustomError>())
682     << "handleExpected should have returned the CustomError generated by "
683     "foo(Aggressive) here";
684   consumeError(std::move(Err));
685 }
686 
687 // Test that handleExpected invokes the fallback path if errors are handled.
688 TEST(Error, HandleExpectedHandledError) {
689   // foo(Aggressive) should return a CustomError which should handle triggering
690   // the fallback path.
691   auto ValOrErr =
692     handleExpected(
693       foo(Aggressive),
694       []() { return foo(Conservative); },
695       [](const CustomError&) { /* do nothing */ });
696 
697   EXPECT_TRUE(!!ValOrErr)
698     << "handleExpected should have returned a success value here";
699   EXPECT_EQ(*ValOrErr, 42)
700     << "handleExpected returned the wrong success value";
701 }
702 
703 TEST(Error, ErrorCodeConversions) {
704   // Round-trip a success value to check that it converts correctly.
705   EXPECT_EQ(errorToErrorCode(errorCodeToError(std::error_code())),
706             std::error_code())
707       << "std::error_code() should round-trip via Error conversions";
708 
709   // Round-trip an error value to check that it converts correctly.
710   EXPECT_EQ(errorToErrorCode(errorCodeToError(errc::invalid_argument)),
711             errc::invalid_argument)
712       << "std::error_code error value should round-trip via Error "
713          "conversions";
714 
715   // Round-trip a success value through ErrorOr/Expected to check that it
716   // converts correctly.
717   {
718     auto Orig = ErrorOr<int>(42);
719     auto RoundTripped =
720       expectedToErrorOr(errorOrToExpected(ErrorOr<int>(42)));
721     EXPECT_EQ(*Orig, *RoundTripped)
722       << "ErrorOr<T> success value should round-trip via Expected<T> "
723          "conversions.";
724   }
725 
726   // Round-trip a failure value through ErrorOr/Expected to check that it
727   // converts correctly.
728   {
729     auto Orig = ErrorOr<int>(errc::invalid_argument);
730     auto RoundTripped =
731       expectedToErrorOr(
732           errorOrToExpected(ErrorOr<int>(errc::invalid_argument)));
733     EXPECT_EQ(Orig.getError(), RoundTripped.getError())
734       << "ErrorOr<T> failure value should round-trip via Expected<T> "
735          "conversions.";
736   }
737 }
738 
739 // Test that error messages work.
740 TEST(Error, ErrorMessage) {
741   EXPECT_EQ(toString(Error::success()), "");
742 
743   Error E1 = make_error<CustomError>(0);
744   EXPECT_EQ(toString(std::move(E1)), "CustomError {0}");
745 
746   Error E2 = make_error<CustomError>(0);
747   handleAllErrors(std::move(E2), [](const CustomError &CE) {
748     EXPECT_EQ(CE.message(), "CustomError {0}");
749   });
750 
751   Error E3 = joinErrors(make_error<CustomError>(0), make_error<CustomError>(1));
752   EXPECT_EQ(toString(std::move(E3)), "CustomError {0}\n"
753                                      "CustomError {1}");
754 }
755 
756 TEST(Error, Stream) {
757   {
758     Error OK = Error::success();
759     std::string Buf;
760     llvm::raw_string_ostream S(Buf);
761     S << OK;
762     EXPECT_EQ("success", S.str());
763     consumeError(std::move(OK));
764   }
765   {
766     Error E1 = make_error<CustomError>(0);
767     std::string Buf;
768     llvm::raw_string_ostream S(Buf);
769     S << E1;
770     EXPECT_EQ("CustomError {0}", S.str());
771     consumeError(std::move(E1));
772   }
773 }
774 
775 TEST(Error, SucceededMatcher) {
776   EXPECT_THAT_ERROR(Error::success(), Succeeded());
777   EXPECT_NONFATAL_FAILURE(
778       EXPECT_THAT_ERROR(make_error<CustomError>(0), Succeeded()),
779       "Expected: succeeded\n  Actual: failed  (CustomError {0})");
780 
781   EXPECT_THAT_EXPECTED(Expected<int>(0), Succeeded());
782   EXPECT_NONFATAL_FAILURE(
783       EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)),
784                            Succeeded()),
785       "Expected: succeeded\n  Actual: failed  (CustomError {0})");
786   int a = 1;
787   EXPECT_THAT_EXPECTED(Expected<int &>(a), Succeeded());
788 }
789 
790 TEST(Error, FailedMatcher) {
791   EXPECT_THAT_ERROR(make_error<CustomError>(0), Failed());
792   EXPECT_NONFATAL_FAILURE(EXPECT_THAT_ERROR(Error::success(), Failed()),
793                           "Expected: failed\n  Actual: succeeded");
794 
795   EXPECT_THAT_ERROR(make_error<CustomError>(0), Failed<CustomError>());
796   EXPECT_NONFATAL_FAILURE(
797       EXPECT_THAT_ERROR(Error::success(), Failed<CustomError>()),
798       "Expected: failed with Error of given type\n  Actual: succeeded");
799   EXPECT_NONFATAL_FAILURE(
800       EXPECT_THAT_ERROR(make_error<CustomError>(0), Failed<CustomSubError>()),
801       "Error was not of given type");
802   EXPECT_NONFATAL_FAILURE(
803       EXPECT_THAT_ERROR(
804           joinErrors(make_error<CustomError>(0), make_error<CustomError>(1)),
805           Failed<CustomError>()),
806       "multiple errors");
807 
808   EXPECT_THAT_ERROR(
809       make_error<CustomError>(0),
810       Failed<CustomError>(testing::Property(&CustomError::getInfo, 0)));
811   EXPECT_NONFATAL_FAILURE(
812       EXPECT_THAT_ERROR(
813           make_error<CustomError>(0),
814           Failed<CustomError>(testing::Property(&CustomError::getInfo, 1))),
815       "Expected: failed with Error of given type and the error is an object "
816       "whose given property is equal to 1\n"
817       "  Actual: failed  (CustomError {0})");
818   EXPECT_THAT_ERROR(make_error<CustomError>(0), Failed<ErrorInfoBase>());
819 
820   EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)), Failed());
821   EXPECT_NONFATAL_FAILURE(
822       EXPECT_THAT_EXPECTED(Expected<int>(0), Failed()),
823       "Expected: failed\n  Actual: succeeded with value 0");
824   EXPECT_THAT_EXPECTED(Expected<int &>(make_error<CustomError>(0)), Failed());
825 }
826 
827 TEST(Error, HasValueMatcher) {
828   EXPECT_THAT_EXPECTED(Expected<int>(0), HasValue(0));
829   EXPECT_NONFATAL_FAILURE(
830       EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)),
831                            HasValue(0)),
832       "Expected: succeeded with value (is equal to 0)\n"
833       "  Actual: failed  (CustomError {0})");
834   EXPECT_NONFATAL_FAILURE(
835       EXPECT_THAT_EXPECTED(Expected<int>(1), HasValue(0)),
836       "Expected: succeeded with value (is equal to 0)\n"
837       "  Actual: succeeded with value 1, (isn't equal to 0)");
838 
839   int a = 1;
840   EXPECT_THAT_EXPECTED(Expected<int &>(a), HasValue(testing::Eq(1)));
841 
842   EXPECT_THAT_EXPECTED(Expected<int>(1), HasValue(testing::Gt(0)));
843   EXPECT_NONFATAL_FAILURE(
844       EXPECT_THAT_EXPECTED(Expected<int>(0), HasValue(testing::Gt(1))),
845       "Expected: succeeded with value (is > 1)\n"
846       "  Actual: succeeded with value 0, (isn't > 1)");
847   EXPECT_NONFATAL_FAILURE(
848       EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)),
849                            HasValue(testing::Gt(1))),
850       "Expected: succeeded with value (is > 1)\n"
851       "  Actual: failed  (CustomError {0})");
852 }
853 
854 TEST(Error, FailedWithMessageMatcher) {
855   EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)),
856                        FailedWithMessage("CustomError {0}"));
857 
858   EXPECT_NONFATAL_FAILURE(
859       EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(1)),
860                            FailedWithMessage("CustomError {0}")),
861       "Expected: failed with Error whose message has 1 element that is equal "
862       "to \"CustomError {0}\"\n"
863       "  Actual: failed  (CustomError {1})");
864 
865   EXPECT_NONFATAL_FAILURE(
866       EXPECT_THAT_EXPECTED(Expected<int>(0),
867                            FailedWithMessage("CustomError {0}")),
868       "Expected: failed with Error whose message has 1 element that is equal "
869       "to \"CustomError {0}\"\n"
870       "  Actual: succeeded with value 0");
871 
872   EXPECT_NONFATAL_FAILURE(
873       EXPECT_THAT_EXPECTED(Expected<int>(make_error<CustomError>(0)),
874                            FailedWithMessage("CustomError {0}", "CustomError {0}")),
875       "Expected: failed with Error whose message has 2 elements where\n"
876       "element #0 is equal to \"CustomError {0}\",\n"
877       "element #1 is equal to \"CustomError {0}\"\n"
878       "  Actual: failed  (CustomError {0}), which has 1 element");
879 
880   EXPECT_NONFATAL_FAILURE(
881       EXPECT_THAT_EXPECTED(
882           Expected<int>(joinErrors(make_error<CustomError>(0),
883                                    make_error<CustomError>(0))),
884           FailedWithMessage("CustomError {0}")),
885       "Expected: failed with Error whose message has 1 element that is equal "
886       "to \"CustomError {0}\"\n"
887       "  Actual: failed  (CustomError {0}; CustomError {0}), which has 2 elements");
888 
889   EXPECT_THAT_ERROR(
890       joinErrors(make_error<CustomError>(0), make_error<CustomError>(0)),
891       FailedWithMessageArray(testing::SizeIs(2)));
892 }
893 
894 TEST(Error, C_API) {
895   EXPECT_THAT_ERROR(unwrap(wrap(Error::success())), Succeeded())
896       << "Failed to round-trip Error success value via C API";
897   EXPECT_THAT_ERROR(unwrap(wrap(make_error<CustomError>(0))),
898                     Failed<CustomError>())
899       << "Failed to round-trip Error failure value via C API";
900 
901   auto Err =
902       wrap(make_error<StringError>("test message", inconvertibleErrorCode()));
903   EXPECT_EQ(LLVMGetErrorTypeId(Err), LLVMGetStringErrorTypeId())
904       << "Failed to match error type ids via C API";
905   char *ErrMsg = LLVMGetErrorMessage(Err);
906   EXPECT_STREQ(ErrMsg, "test message")
907       << "Failed to roundtrip StringError error message via C API";
908   LLVMDisposeErrorMessage(ErrMsg);
909 
910   bool GotCSE = false;
911   bool GotCE = false;
912   handleAllErrors(
913     unwrap(wrap(joinErrors(make_error<CustomSubError>(42, 7),
914                            make_error<CustomError>(42)))),
915     [&](CustomSubError &CSE) {
916       GotCSE = true;
917     },
918     [&](CustomError &CE) {
919       GotCE = true;
920     });
921   EXPECT_TRUE(GotCSE) << "Failed to round-trip ErrorList via C API";
922   EXPECT_TRUE(GotCE) << "Failed to round-trip ErrorList via C API";
923 }
924 
925 TEST(Error, FileErrorTest) {
926 #if !defined(NDEBUG) && GTEST_HAS_DEATH_TEST
927     EXPECT_DEATH(
928       {
929         Error S = Error::success();
930         consumeError(createFileError("file.bin", std::move(S)));
931       },
932       "");
933 #endif
934   // Not allowed, would fail at compile-time
935   //consumeError(createFileError("file.bin", ErrorSuccess()));
936 
937   Error E1 = make_error<CustomError>(1);
938   Error FE1 = createFileError("file.bin", std::move(E1));
939   EXPECT_EQ(toString(std::move(FE1)), "'file.bin': CustomError {1}");
940 
941   Error E2 = make_error<CustomError>(2);
942   Error FE2 = createFileError("file.bin", std::move(E2));
943   handleAllErrors(std::move(FE2), [](const FileError &F) {
944     EXPECT_EQ(F.message(), "'file.bin': CustomError {2}");
945   });
946 
947   Error E3 = make_error<CustomError>(3);
948   Error FE3 = createFileError("file.bin", std::move(E3));
949   auto E31 = handleErrors(std::move(FE3), [](std::unique_ptr<FileError> F) {
950     return F->takeError();
951   });
952   handleAllErrors(std::move(E31), [](const CustomError &C) {
953     EXPECT_EQ(C.message(), "CustomError {3}");
954   });
955 
956   Error FE4 =
957       joinErrors(createFileError("file.bin", make_error<CustomError>(41)),
958                  createFileError("file2.bin", make_error<CustomError>(42)));
959   EXPECT_EQ(toString(std::move(FE4)), "'file.bin': CustomError {41}\n"
960                                       "'file2.bin': CustomError {42}");
961 
962   Error FE5 = createFileError("", make_error<CustomError>(5));
963   EXPECT_EQ(toString(std::move(FE5)), "'': CustomError {5}");
964 
965   Error FE6 = createFileError("unused", make_error<CustomError>(6));
966   handleAllErrors(std::move(FE6), [](std::unique_ptr<FileError> F) {
967     EXPECT_EQ(F->messageWithoutFileInfo(), "CustomError {6}");
968   });
969 }
970 
971 TEST(Error, FileErrorErrorCode) {
972   for (std::error_code EC : {
973            make_error_code(std::errc::not_supported),
974            make_error_code(std::errc::invalid_argument),
975            make_error_code(std::errc::no_such_file_or_directory),
976        }) {
977     EXPECT_EQ(EC, errorToErrorCode(
978                       createFileError("file.bin", EC)));
979     EXPECT_EQ(EC, errorToErrorCode(
980                       createFileError("file.bin", /*Line=*/5, EC)));
981     EXPECT_EQ(EC, errorToErrorCode(
982                       createFileError("file.bin", errorCodeToError(EC))));
983     EXPECT_EQ(EC, errorToErrorCode(
984                       createFileError("file.bin", /*Line=*/5, errorCodeToError(EC))));
985   }
986 
987   // inconvertibleErrorCode() should be wrapped to avoid a fatal error.
988   EXPECT_EQ(
989       "A file error occurred.",
990       errorToErrorCode(createFileError("file.bin", inconvertibleErrorCode()))
991           .message());
992   EXPECT_EQ(
993       "A file error occurred.",
994       errorToErrorCode(createFileError("file.bin", /*Line=*/5, inconvertibleErrorCode()))
995           .message());
996 }
997 
998 enum class test_error_code {
999   unspecified = 1,
1000   error_1,
1001   error_2,
1002 };
1003 
1004 } // end anon namespace
1005 
1006 namespace std {
1007     template <>
1008     struct is_error_code_enum<test_error_code> : std::true_type {};
1009 } // namespace std
1010 
1011 namespace {
1012 
1013 const std::error_category &TErrorCategory();
1014 
1015 inline std::error_code make_error_code(test_error_code E) {
1016     return std::error_code(static_cast<int>(E), TErrorCategory());
1017 }
1018 
1019 class TestDebugError : public ErrorInfo<TestDebugError, StringError> {
1020 public:
1021     using ErrorInfo<TestDebugError, StringError >::ErrorInfo; // inherit constructors
1022     TestDebugError(const Twine &S) : ErrorInfo(S, test_error_code::unspecified) {}
1023     static char ID;
1024 };
1025 
1026 class TestErrorCategory : public std::error_category {
1027 public:
1028   const char *name() const noexcept override { return "error"; }
1029   std::string message(int Condition) const override {
1030     switch (static_cast<test_error_code>(Condition)) {
1031     case test_error_code::unspecified:
1032       return "An unknown error has occurred.";
1033     case test_error_code::error_1:
1034       return "Error 1.";
1035     case test_error_code::error_2:
1036       return "Error 2.";
1037     }
1038     llvm_unreachable("Unrecognized test_error_code");
1039   }
1040 };
1041 
1042 const std::error_category &TErrorCategory() {
1043   static TestErrorCategory TestErrCategory;
1044   return TestErrCategory;
1045 }
1046 
1047 char TestDebugError::ID;
1048 
1049 TEST(Error, SubtypeStringErrorTest) {
1050   auto E1 = make_error<TestDebugError>(test_error_code::error_1);
1051   EXPECT_EQ(toString(std::move(E1)), "Error 1.");
1052 
1053   auto E2 = make_error<TestDebugError>(test_error_code::error_1,
1054                                        "Detailed information");
1055   EXPECT_EQ(toString(std::move(E2)), "Error 1. Detailed information");
1056 
1057   auto E3 = make_error<TestDebugError>(test_error_code::error_2);
1058   handleAllErrors(std::move(E3), [](const TestDebugError &F) {
1059     EXPECT_EQ(F.message(), "Error 2.");
1060   });
1061 
1062   auto E4 = joinErrors(make_error<TestDebugError>(test_error_code::error_1,
1063                                                   "Detailed information"),
1064                        make_error<TestDebugError>(test_error_code::error_2));
1065   EXPECT_EQ(toString(std::move(E4)), "Error 1. Detailed information\n"
1066                                      "Error 2.");
1067 }
1068 
1069 static Error createAnyError() {
1070   return errorCodeToError(test_error_code::unspecified);
1071 }
1072 
1073 struct MoveOnlyBox {
1074   std::optional<int> Box;
1075 
1076   explicit MoveOnlyBox(int I) : Box(I) {}
1077   MoveOnlyBox() = default;
1078   MoveOnlyBox(MoveOnlyBox &&) = default;
1079   MoveOnlyBox &operator=(MoveOnlyBox &&) = default;
1080 
1081   MoveOnlyBox(const MoveOnlyBox &) = delete;
1082   MoveOnlyBox &operator=(const MoveOnlyBox &) = delete;
1083 
1084   bool operator==(const MoveOnlyBox &RHS) const {
1085     if (bool(Box) != bool(RHS.Box))
1086       return false;
1087     return Box ? *Box == *RHS.Box : false;
1088   }
1089 };
1090 
1091 TEST(Error, moveInto) {
1092   // Use MoveOnlyBox as the T in Expected<T>.
1093   auto make = [](int I) -> Expected<MoveOnlyBox> { return MoveOnlyBox(I); };
1094   auto makeFailure = []() -> Expected<MoveOnlyBox> { return createAnyError(); };
1095 
1096   {
1097     MoveOnlyBox V;
1098 
1099     // Failure with no prior value.
1100     EXPECT_THAT_ERROR(makeFailure().moveInto(V), Failed());
1101     EXPECT_EQ(std::nullopt, V.Box);
1102 
1103     // Success with no prior value.
1104     EXPECT_THAT_ERROR(make(5).moveInto(V), Succeeded());
1105     EXPECT_EQ(5, V.Box);
1106 
1107     // Success with an existing value.
1108     EXPECT_THAT_ERROR(make(7).moveInto(V), Succeeded());
1109     EXPECT_EQ(7, V.Box);
1110 
1111     // Failure with an existing value. Might be nice to assign a
1112     // default-constructed value in this case, but for now it's being left
1113     // alone.
1114     EXPECT_THAT_ERROR(makeFailure().moveInto(V), Failed());
1115     EXPECT_EQ(7, V.Box);
1116   }
1117 
1118   // Check that this works with optionals too.
1119   {
1120     // Same cases as above.
1121     std::optional<MoveOnlyBox> MaybeV;
1122     EXPECT_THAT_ERROR(makeFailure().moveInto(MaybeV), Failed());
1123     EXPECT_EQ(std::nullopt, MaybeV);
1124 
1125     EXPECT_THAT_ERROR(make(5).moveInto(MaybeV), Succeeded());
1126     EXPECT_EQ(MoveOnlyBox(5), MaybeV);
1127 
1128     EXPECT_THAT_ERROR(make(7).moveInto(MaybeV), Succeeded());
1129     EXPECT_EQ(MoveOnlyBox(7), MaybeV);
1130 
1131     EXPECT_THAT_ERROR(makeFailure().moveInto(MaybeV), Failed());
1132     EXPECT_EQ(MoveOnlyBox(7), MaybeV);
1133   }
1134 }
1135 
1136 TEST(Error, FatalBadAllocErrorHandlersInteraction) {
1137   auto ErrorHandler = [](void *Data, const char *, bool) {};
1138   install_fatal_error_handler(ErrorHandler, nullptr);
1139   // The following call should not crash; previously, a bug in
1140   // install_bad_alloc_error_handler asserted that no fatal-error handler is
1141   // installed already.
1142   install_bad_alloc_error_handler(ErrorHandler, nullptr);
1143 
1144   // Don't interfere with other tests.
1145   remove_fatal_error_handler();
1146   remove_bad_alloc_error_handler();
1147 }
1148 
1149 TEST(Error, BadAllocFatalErrorHandlersInteraction) {
1150   auto ErrorHandler = [](void *Data, const char *, bool) {};
1151   install_bad_alloc_error_handler(ErrorHandler, nullptr);
1152   // The following call should not crash; related to
1153   // FatalBadAllocErrorHandlersInteraction: Ensure that the error does not occur
1154   // in the other direction.
1155   install_fatal_error_handler(ErrorHandler, nullptr);
1156 
1157   // Don't interfere with other tests.
1158   remove_fatal_error_handler();
1159   remove_bad_alloc_error_handler();
1160 }
1161 
1162 TEST(Error, ForwardToExpected) {
1163   auto ErrorReturningFct = [](bool Fail) {
1164     return Fail ? make_error<StringError>(llvm::errc::invalid_argument,
1165                                           "Some Error")
1166                 : Error::success();
1167   };
1168   auto ExpectedReturningFct = [&](bool Fail) -> Expected<int> {
1169     auto Err = ErrorReturningFct(Fail);
1170     if (Err)
1171       return Err;
1172     return 42;
1173   };
1174   std::optional<int> MaybeV;
1175   EXPECT_THAT_ERROR(ExpectedReturningFct(true).moveInto(MaybeV), Failed());
1176   EXPECT_THAT_ERROR(ExpectedReturningFct(false).moveInto(MaybeV), Succeeded());
1177   EXPECT_EQ(*MaybeV, 42);
1178 }
1179 } // namespace
1180