1 | //===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===// |
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 | // This file defines an API used to report recoverable errors. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #ifndef LLVM_SUPPORT_ERROR_H |
14 | #define LLVM_SUPPORT_ERROR_H |
15 | |
16 | #include "llvm-c/Error.h" |
17 | #include "llvm/ADT/Twine.h" |
18 | #include "llvm/Config/abi-breaking.h" |
19 | #include "llvm/Support/AlignOf.h" |
20 | #include "llvm/Support/Compiler.h" |
21 | #include "llvm/Support/Debug.h" |
22 | #include "llvm/Support/ErrorHandling.h" |
23 | #include "llvm/Support/ErrorOr.h" |
24 | #include "llvm/Support/Format.h" |
25 | #include "llvm/Support/raw_ostream.h" |
26 | #include <cassert> |
27 | #include <cstdint> |
28 | #include <cstdlib> |
29 | #include <functional> |
30 | #include <memory> |
31 | #include <new> |
32 | #include <optional> |
33 | #include <string> |
34 | #include <system_error> |
35 | #include <type_traits> |
36 | #include <utility> |
37 | #include <vector> |
38 | |
39 | namespace llvm { |
40 | |
41 | class ErrorSuccess; |
42 | |
43 | /// Base class for error info classes. Do not extend this directly: Extend |
44 | /// the ErrorInfo template subclass instead. |
45 | class ErrorInfoBase { |
46 | public: |
47 | virtual ~ErrorInfoBase() = default; |
48 | |
49 | /// Print an error message to an output stream. |
50 | virtual void log(raw_ostream &OS) const = 0; |
51 | |
52 | /// Return the error message as a string. |
53 | virtual std::string message() const { |
54 | std::string Msg; |
55 | raw_string_ostream OS(Msg); |
56 | log(OS); |
57 | return OS.str(); |
58 | } |
59 | |
60 | /// Convert this error to a std::error_code. |
61 | /// |
62 | /// This is a temporary crutch to enable interaction with code still |
63 | /// using std::error_code. It will be removed in the future. |
64 | virtual std::error_code convertToErrorCode() const = 0; |
65 | |
66 | // Returns the class ID for this type. |
67 | static const void *classID() { return &ID; } |
68 | |
69 | // Returns the class ID for the dynamic type of this ErrorInfoBase instance. |
70 | virtual const void *dynamicClassID() const = 0; |
71 | |
72 | // Check whether this instance is a subclass of the class identified by |
73 | // ClassID. |
74 | virtual bool isA(const void *const ClassID) const { |
75 | return ClassID == classID(); |
76 | } |
77 | |
78 | // Check whether this instance is a subclass of ErrorInfoT. |
79 | template <typename ErrorInfoT> bool isA() const { |
80 | return isA(ErrorInfoT::classID()); |
81 | } |
82 | |
83 | private: |
84 | virtual void anchor(); |
85 | |
86 | static char ID; |
87 | }; |
88 | |
89 | /// Lightweight error class with error context and mandatory checking. |
90 | /// |
91 | /// Instances of this class wrap a ErrorInfoBase pointer. Failure states |
92 | /// are represented by setting the pointer to a ErrorInfoBase subclass |
93 | /// instance containing information describing the failure. Success is |
94 | /// represented by a null pointer value. |
95 | /// |
96 | /// Instances of Error also contains a 'Checked' flag, which must be set |
97 | /// before the destructor is called, otherwise the destructor will trigger a |
98 | /// runtime error. This enforces at runtime the requirement that all Error |
99 | /// instances be checked or returned to the caller. |
100 | /// |
101 | /// There are two ways to set the checked flag, depending on what state the |
102 | /// Error instance is in. For Error instances indicating success, it |
103 | /// is sufficient to invoke the boolean conversion operator. E.g.: |
104 | /// |
105 | /// @code{.cpp} |
106 | /// Error foo(<...>); |
107 | /// |
108 | /// if (auto E = foo(<...>)) |
109 | /// return E; // <- Return E if it is in the error state. |
110 | /// // We have verified that E was in the success state. It can now be safely |
111 | /// // destroyed. |
112 | /// @endcode |
113 | /// |
114 | /// A success value *can not* be dropped. For example, just calling 'foo(<...>)' |
115 | /// without testing the return value will raise a runtime error, even if foo |
116 | /// returns success. |
117 | /// |
118 | /// For Error instances representing failure, you must use either the |
119 | /// handleErrors or handleAllErrors function with a typed handler. E.g.: |
120 | /// |
121 | /// @code{.cpp} |
122 | /// class MyErrorInfo : public ErrorInfo<MyErrorInfo> { |
123 | /// // Custom error info. |
124 | /// }; |
125 | /// |
126 | /// Error foo(<...>) { return make_error<MyErrorInfo>(...); } |
127 | /// |
128 | /// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo. |
129 | /// auto NewE = |
130 | /// handleErrors(E, |
131 | /// [](const MyErrorInfo &M) { |
132 | /// // Deal with the error. |
133 | /// }, |
134 | /// [](std::unique_ptr<OtherError> M) -> Error { |
135 | /// if (canHandle(*M)) { |
136 | /// // handle error. |
137 | /// return Error::success(); |
138 | /// } |
139 | /// // Couldn't handle this error instance. Pass it up the stack. |
140 | /// return Error(std::move(M)); |
141 | /// ); |
142 | /// // Note - we must check or return NewE in case any of the handlers |
143 | /// // returned a new error. |
144 | /// @endcode |
145 | /// |
146 | /// The handleAllErrors function is identical to handleErrors, except |
147 | /// that it has a void return type, and requires all errors to be handled and |
148 | /// no new errors be returned. It prevents errors (assuming they can all be |
149 | /// handled) from having to be bubbled all the way to the top-level. |
150 | /// |
151 | /// *All* Error instances must be checked before destruction, even if |
152 | /// they're moved-assigned or constructed from Success values that have already |
153 | /// been checked. This enforces checking through all levels of the call stack. |
154 | class [[nodiscard]] Error { |
155 | // ErrorList needs to be able to yank ErrorInfoBase pointers out of Errors |
156 | // to add to the error list. It can't rely on handleErrors for this, since |
157 | // handleErrors does not support ErrorList handlers. |
158 | friend class ErrorList; |
159 | |
160 | // handleErrors needs to be able to set the Checked flag. |
161 | template <typename... HandlerTs> |
162 | friend Error handleErrors(Error E, HandlerTs &&... Handlers); |
163 | |
164 | // Expected<T> needs to be able to steal the payload when constructed from an |
165 | // error. |
166 | template <typename T> friend class Expected; |
167 | |
168 | // wrap needs to be able to steal the payload. |
169 | friend LLVMErrorRef wrap(Error); |
170 | |
171 | protected: |
172 | /// Create a success value. Prefer using 'Error::success()' for readability |
173 | Error() { |
174 | setPtr(nullptr); |
175 | setChecked(false); |
176 | } |
177 | |
178 | public: |
179 | /// Create a success value. |
180 | static ErrorSuccess success(); |
181 | |
182 | // Errors are not copy-constructable. |
183 | Error(const Error &Other) = delete; |
184 | |
185 | /// Move-construct an error value. The newly constructed error is considered |
186 | /// unchecked, even if the source error had been checked. The original error |
187 | /// becomes a checked Success value, regardless of its original state. |
188 | Error(Error &&Other) { |
189 | setChecked(true); |
190 | *this = std::move(Other); |
191 | } |
192 | |
193 | /// Create an error value. Prefer using the 'make_error' function, but |
194 | /// this constructor can be useful when "re-throwing" errors from handlers. |
195 | Error(std::unique_ptr<ErrorInfoBase> Payload) { |
196 | setPtr(Payload.release()); |
197 | setChecked(false); |
198 | } |
199 | |
200 | // Errors are not copy-assignable. |
201 | Error &operator=(const Error &Other) = delete; |
202 | |
203 | /// Move-assign an error value. The current error must represent success, you |
204 | /// you cannot overwrite an unhandled error. The current error is then |
205 | /// considered unchecked. The source error becomes a checked success value, |
206 | /// regardless of its original state. |
207 | Error &operator=(Error &&Other) { |
208 | // Don't allow overwriting of unchecked values. |
209 | assertIsChecked(); |
210 | setPtr(Other.getPtr()); |
211 | |
212 | // This Error is unchecked, even if the source error was checked. |
213 | setChecked(false); |
214 | |
215 | // Null out Other's payload and set its checked bit. |
216 | Other.setPtr(nullptr); |
217 | Other.setChecked(true); |
218 | |
219 | return *this; |
220 | } |
221 | |
222 | /// Destroy a Error. Fails with a call to abort() if the error is |
223 | /// unchecked. |
224 | ~Error() { |
225 | assertIsChecked(); |
226 | delete getPtr(); |
227 | } |
228 | |
229 | /// Bool conversion. Returns true if this Error is in a failure state, |
230 | /// and false if it is in an accept state. If the error is in a Success state |
231 | /// it will be considered checked. |
232 | explicit operator bool() { |
233 | setChecked(getPtr() == nullptr); |
234 | return getPtr() != nullptr; |
235 | } |
236 | |
237 | /// Check whether one error is a subclass of another. |
238 | template <typename ErrT> bool isA() const { |
239 | return getPtr() && getPtr()->isA(ErrT::classID()); |
240 | } |
241 | |
242 | /// Returns the dynamic class id of this error, or null if this is a success |
243 | /// value. |
244 | const void* dynamicClassID() const { |
245 | if (!getPtr()) |
246 | return nullptr; |
247 | return getPtr()->dynamicClassID(); |
248 | } |
249 | |
250 | private: |
251 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS |
252 | // assertIsChecked() happens very frequently, but under normal circumstances |
253 | // is supposed to be a no-op. So we want it to be inlined, but having a bunch |
254 | // of debug prints can cause the function to be too large for inlining. So |
255 | // it's important that we define this function out of line so that it can't be |
256 | // inlined. |
257 | [[noreturn]] void fatalUncheckedError() const; |
258 | #endif |
259 | |
260 | void assertIsChecked() { |
261 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS |
262 | if (LLVM_UNLIKELY(!getChecked() || getPtr())) |
263 | fatalUncheckedError(); |
264 | #endif |
265 | } |
266 | |
267 | ErrorInfoBase *getPtr() const { |
268 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS |
269 | return reinterpret_cast<ErrorInfoBase*>( |
270 | reinterpret_cast<uintptr_t>(Payload) & |
271 | ~static_cast<uintptr_t>(0x1)); |
272 | #else |
273 | return Payload; |
274 | #endif |
275 | } |
276 | |
277 | void setPtr(ErrorInfoBase *EI) { |
278 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS |
279 | Payload = reinterpret_cast<ErrorInfoBase*>( |
280 | (reinterpret_cast<uintptr_t>(EI) & |
281 | ~static_cast<uintptr_t>(0x1)) | |
282 | (reinterpret_cast<uintptr_t>(Payload) & 0x1)); |
283 | #else |
284 | Payload = EI; |
285 | #endif |
286 | } |
287 | |
288 | bool getChecked() const { |
289 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS |
290 | return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0; |
291 | #else |
292 | return true; |
293 | #endif |
294 | } |
295 | |
296 | void setChecked(bool V) { |
297 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS |
298 | Payload = reinterpret_cast<ErrorInfoBase*>( |
299 | (reinterpret_cast<uintptr_t>(Payload) & |
300 | ~static_cast<uintptr_t>(0x1)) | |
301 | (V ? 0 : 1)); |
302 | #endif |
303 | } |
304 | |
305 | std::unique_ptr<ErrorInfoBase> takePayload() { |
306 | std::unique_ptr<ErrorInfoBase> Tmp(getPtr()); |
307 | setPtr(nullptr); |
308 | setChecked(true); |
309 | return Tmp; |
310 | } |
311 | |
312 | friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) { |
313 | if (auto *P = E.getPtr()) |
314 | P->log(OS); |
315 | else |
316 | OS << "success" ; |
317 | return OS; |
318 | } |
319 | |
320 | ErrorInfoBase *Payload = nullptr; |
321 | }; |
322 | |
323 | /// Subclass of Error for the sole purpose of identifying the success path in |
324 | /// the type system. This allows to catch invalid conversion to Expected<T> at |
325 | /// compile time. |
326 | class ErrorSuccess final : public Error {}; |
327 | |
328 | inline ErrorSuccess Error::success() { return ErrorSuccess(); } |
329 | |
330 | /// Make a Error instance representing failure using the given error info |
331 | /// type. |
332 | template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) { |
333 | return Error(std::make_unique<ErrT>(std::forward<ArgTs>(Args)...)); |
334 | } |
335 | |
336 | /// Base class for user error types. Users should declare their error types |
337 | /// like: |
338 | /// |
339 | /// class MyError : public ErrorInfo<MyError> { |
340 | /// .... |
341 | /// }; |
342 | /// |
343 | /// This class provides an implementation of the ErrorInfoBase::kind |
344 | /// method, which is used by the Error RTTI system. |
345 | template <typename ThisErrT, typename ParentErrT = ErrorInfoBase> |
346 | class ErrorInfo : public ParentErrT { |
347 | public: |
348 | using ParentErrT::ParentErrT; // inherit constructors |
349 | |
350 | static const void *classID() { return &ThisErrT::ID; } |
351 | |
352 | const void *dynamicClassID() const override { return &ThisErrT::ID; } |
353 | |
354 | bool isA(const void *const ClassID) const override { |
355 | return ClassID == classID() || ParentErrT::isA(ClassID); |
356 | } |
357 | }; |
358 | |
359 | /// Special ErrorInfo subclass representing a list of ErrorInfos. |
360 | /// Instances of this class are constructed by joinError. |
361 | class ErrorList final : public ErrorInfo<ErrorList> { |
362 | // handleErrors needs to be able to iterate the payload list of an |
363 | // ErrorList. |
364 | template <typename... HandlerTs> |
365 | friend Error handleErrors(Error E, HandlerTs &&... Handlers); |
366 | |
367 | // joinErrors is implemented in terms of join. |
368 | friend Error joinErrors(Error, Error); |
369 | |
370 | public: |
371 | void log(raw_ostream &OS) const override { |
372 | OS << "Multiple errors:\n" ; |
373 | for (const auto &ErrPayload : Payloads) { |
374 | ErrPayload->log(OS); |
375 | OS << "\n" ; |
376 | } |
377 | } |
378 | |
379 | std::error_code convertToErrorCode() const override; |
380 | |
381 | // Used by ErrorInfo::classID. |
382 | static char ID; |
383 | |
384 | private: |
385 | ErrorList(std::unique_ptr<ErrorInfoBase> Payload1, |
386 | std::unique_ptr<ErrorInfoBase> Payload2) { |
387 | assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && |
388 | "ErrorList constructor payloads should be singleton errors" ); |
389 | Payloads.push_back(x: std::move(Payload1)); |
390 | Payloads.push_back(x: std::move(Payload2)); |
391 | } |
392 | |
393 | static Error join(Error E1, Error E2) { |
394 | if (!E1) |
395 | return E2; |
396 | if (!E2) |
397 | return E1; |
398 | if (E1.isA<ErrorList>()) { |
399 | auto &E1List = static_cast<ErrorList &>(*E1.getPtr()); |
400 | if (E2.isA<ErrorList>()) { |
401 | auto E2Payload = E2.takePayload(); |
402 | auto &E2List = static_cast<ErrorList &>(*E2Payload); |
403 | for (auto &Payload : E2List.Payloads) |
404 | E1List.Payloads.push_back(x: std::move(Payload)); |
405 | } else |
406 | E1List.Payloads.push_back(x: E2.takePayload()); |
407 | |
408 | return E1; |
409 | } |
410 | if (E2.isA<ErrorList>()) { |
411 | auto &E2List = static_cast<ErrorList &>(*E2.getPtr()); |
412 | E2List.Payloads.insert(position: E2List.Payloads.begin(), x: E1.takePayload()); |
413 | return E2; |
414 | } |
415 | return Error(std::unique_ptr<ErrorList>( |
416 | new ErrorList(E1.takePayload(), E2.takePayload()))); |
417 | } |
418 | |
419 | std::vector<std::unique_ptr<ErrorInfoBase>> Payloads; |
420 | }; |
421 | |
422 | /// Concatenate errors. The resulting Error is unchecked, and contains the |
423 | /// ErrorInfo(s), if any, contained in E1, followed by the |
424 | /// ErrorInfo(s), if any, contained in E2. |
425 | inline Error joinErrors(Error E1, Error E2) { |
426 | return ErrorList::join(E1: std::move(E1), E2: std::move(E2)); |
427 | } |
428 | |
429 | /// Tagged union holding either a T or a Error. |
430 | /// |
431 | /// This class parallels ErrorOr, but replaces error_code with Error. Since |
432 | /// Error cannot be copied, this class replaces getError() with |
433 | /// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the |
434 | /// error class type. |
435 | /// |
436 | /// Example usage of 'Expected<T>' as a function return type: |
437 | /// |
438 | /// @code{.cpp} |
439 | /// Expected<int> myDivide(int A, int B) { |
440 | /// if (B == 0) { |
441 | /// // return an Error |
442 | /// return createStringError(inconvertibleErrorCode(), |
443 | /// "B must not be zero!"); |
444 | /// } |
445 | /// // return an integer |
446 | /// return A / B; |
447 | /// } |
448 | /// @endcode |
449 | /// |
450 | /// Checking the results of to a function returning 'Expected<T>': |
451 | /// @code{.cpp} |
452 | /// if (auto E = Result.takeError()) { |
453 | /// // We must consume the error. Typically one of: |
454 | /// // - return the error to our caller |
455 | /// // - toString(), when logging |
456 | /// // - consumeError(), to silently swallow the error |
457 | /// // - handleErrors(), to distinguish error types |
458 | /// errs() << "Problem with division " << toString(std::move(E)) << "\n"; |
459 | /// return; |
460 | /// } |
461 | /// // use the result |
462 | /// outs() << "The answer is " << *Result << "\n"; |
463 | /// @endcode |
464 | /// |
465 | /// For unit-testing a function returning an 'Expected<T>', see the |
466 | /// 'EXPECT_THAT_EXPECTED' macros in llvm/Testing/Support/Error.h |
467 | |
468 | template <class T> class [[nodiscard]] Expected { |
469 | template <class T1> friend class ExpectedAsOutParameter; |
470 | template <class OtherT> friend class Expected; |
471 | |
472 | static constexpr bool isRef = std::is_reference_v<T>; |
473 | |
474 | using wrap = std::reference_wrapper<std::remove_reference_t<T>>; |
475 | |
476 | using error_type = std::unique_ptr<ErrorInfoBase>; |
477 | |
478 | public: |
479 | using storage_type = std::conditional_t<isRef, wrap, T>; |
480 | using value_type = T; |
481 | |
482 | private: |
483 | using reference = std::remove_reference_t<T> &; |
484 | using const_reference = const std::remove_reference_t<T> &; |
485 | using pointer = std::remove_reference_t<T> *; |
486 | using const_pointer = const std::remove_reference_t<T> *; |
487 | |
488 | public: |
489 | /// Create an Expected<T> error value from the given Error. |
490 | Expected(Error Err) |
491 | : HasError(true) |
492 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS |
493 | // Expected is unchecked upon construction in Debug builds. |
494 | , Unchecked(true) |
495 | #endif |
496 | { |
497 | assert(Err && "Cannot create Expected<T> from Error success value." ); |
498 | new (getErrorStorage()) error_type(Err.takePayload()); |
499 | } |
500 | |
501 | /// Forbid to convert from Error::success() implicitly, this avoids having |
502 | /// Expected<T> foo() { return Error::success(); } which compiles otherwise |
503 | /// but triggers the assertion above. |
504 | Expected(ErrorSuccess) = delete; |
505 | |
506 | /// Create an Expected<T> success value from the given OtherT value, which |
507 | /// must be convertible to T. |
508 | template <typename OtherT> |
509 | Expected(OtherT &&Val, |
510 | std::enable_if_t<std::is_convertible_v<OtherT, T>> * = nullptr) |
511 | : HasError(false) |
512 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS |
513 | // Expected is unchecked upon construction in Debug builds. |
514 | , |
515 | Unchecked(true) |
516 | #endif |
517 | { |
518 | new (getStorage()) storage_type(std::forward<OtherT>(Val)); |
519 | } |
520 | |
521 | /// Move construct an Expected<T> value. |
522 | Expected(Expected &&Other) { moveConstruct(std::move(Other)); } |
523 | |
524 | /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT |
525 | /// must be convertible to T. |
526 | template <class OtherT> |
527 | Expected(Expected<OtherT> &&Other, |
528 | std::enable_if_t<std::is_convertible_v<OtherT, T>> * = nullptr) { |
529 | moveConstruct(std::move(Other)); |
530 | } |
531 | |
532 | /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT |
533 | /// isn't convertible to T. |
534 | template <class OtherT> |
535 | explicit Expected( |
536 | Expected<OtherT> &&Other, |
537 | std::enable_if_t<!std::is_convertible_v<OtherT, T>> * = nullptr) { |
538 | moveConstruct(std::move(Other)); |
539 | } |
540 | |
541 | /// Move-assign from another Expected<T>. |
542 | Expected &operator=(Expected &&Other) { |
543 | moveAssign(std::move(Other)); |
544 | return *this; |
545 | } |
546 | |
547 | /// Destroy an Expected<T>. |
548 | ~Expected() { |
549 | assertIsChecked(); |
550 | if (!HasError) |
551 | getStorage()->~storage_type(); |
552 | else |
553 | getErrorStorage()->~error_type(); |
554 | } |
555 | |
556 | /// Return false if there is an error. |
557 | explicit operator bool() { |
558 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS |
559 | Unchecked = HasError; |
560 | #endif |
561 | return !HasError; |
562 | } |
563 | |
564 | /// Returns a reference to the stored T value. |
565 | reference get() { |
566 | assertIsChecked(); |
567 | return *getStorage(); |
568 | } |
569 | |
570 | /// Returns a const reference to the stored T value. |
571 | const_reference get() const { |
572 | assertIsChecked(); |
573 | return const_cast<Expected<T> *>(this)->get(); |
574 | } |
575 | |
576 | /// Returns \a takeError() after moving the held T (if any) into \p V. |
577 | template <class OtherT> |
578 | Error moveInto( |
579 | OtherT &Value, |
580 | std::enable_if_t<std::is_assignable_v<OtherT &, T &&>> * = nullptr) && { |
581 | if (*this) |
582 | Value = std::move(get()); |
583 | return takeError(); |
584 | } |
585 | |
586 | /// Check that this Expected<T> is an error of type ErrT. |
587 | template <typename ErrT> bool errorIsA() const { |
588 | return HasError && (*getErrorStorage())->template isA<ErrT>(); |
589 | } |
590 | |
591 | /// Take ownership of the stored error. |
592 | /// After calling this the Expected<T> is in an indeterminate state that can |
593 | /// only be safely destructed. No further calls (beside the destructor) should |
594 | /// be made on the Expected<T> value. |
595 | Error takeError() { |
596 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS |
597 | Unchecked = false; |
598 | #endif |
599 | return HasError ? Error(std::move(*getErrorStorage())) : Error::success(); |
600 | } |
601 | |
602 | /// Returns a pointer to the stored T value. |
603 | pointer operator->() { |
604 | assertIsChecked(); |
605 | return toPointer(getStorage()); |
606 | } |
607 | |
608 | /// Returns a const pointer to the stored T value. |
609 | const_pointer operator->() const { |
610 | assertIsChecked(); |
611 | return toPointer(getStorage()); |
612 | } |
613 | |
614 | /// Returns a reference to the stored T value. |
615 | reference operator*() { |
616 | assertIsChecked(); |
617 | return *getStorage(); |
618 | } |
619 | |
620 | /// Returns a const reference to the stored T value. |
621 | const_reference operator*() const { |
622 | assertIsChecked(); |
623 | return *getStorage(); |
624 | } |
625 | |
626 | private: |
627 | template <class T1> |
628 | static bool compareThisIfSameType(const T1 &a, const T1 &b) { |
629 | return &a == &b; |
630 | } |
631 | |
632 | template <class T1, class T2> |
633 | static bool compareThisIfSameType(const T1 &, const T2 &) { |
634 | return false; |
635 | } |
636 | |
637 | template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) { |
638 | HasError = Other.HasError; |
639 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS |
640 | Unchecked = true; |
641 | Other.Unchecked = false; |
642 | #endif |
643 | |
644 | if (!HasError) |
645 | new (getStorage()) storage_type(std::move(*Other.getStorage())); |
646 | else |
647 | new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage())); |
648 | } |
649 | |
650 | template <class OtherT> void moveAssign(Expected<OtherT> &&Other) { |
651 | assertIsChecked(); |
652 | |
653 | if (compareThisIfSameType(*this, Other)) |
654 | return; |
655 | |
656 | this->~Expected(); |
657 | new (this) Expected(std::move(Other)); |
658 | } |
659 | |
660 | pointer toPointer(pointer Val) { return Val; } |
661 | |
662 | const_pointer toPointer(const_pointer Val) const { return Val; } |
663 | |
664 | pointer toPointer(wrap *Val) { return &Val->get(); } |
665 | |
666 | const_pointer toPointer(const wrap *Val) const { return &Val->get(); } |
667 | |
668 | storage_type *getStorage() { |
669 | assert(!HasError && "Cannot get value when an error exists!" ); |
670 | return reinterpret_cast<storage_type *>(&TStorage); |
671 | } |
672 | |
673 | const storage_type *getStorage() const { |
674 | assert(!HasError && "Cannot get value when an error exists!" ); |
675 | return reinterpret_cast<const storage_type *>(&TStorage); |
676 | } |
677 | |
678 | error_type *getErrorStorage() { |
679 | assert(HasError && "Cannot get error when a value exists!" ); |
680 | return reinterpret_cast<error_type *>(&ErrorStorage); |
681 | } |
682 | |
683 | const error_type *getErrorStorage() const { |
684 | assert(HasError && "Cannot get error when a value exists!" ); |
685 | return reinterpret_cast<const error_type *>(&ErrorStorage); |
686 | } |
687 | |
688 | // Used by ExpectedAsOutParameter to reset the checked flag. |
689 | void setUnchecked() { |
690 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS |
691 | Unchecked = true; |
692 | #endif |
693 | } |
694 | |
695 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS |
696 | [[noreturn]] LLVM_ATTRIBUTE_NOINLINE void fatalUncheckedExpected() const { |
697 | dbgs() << "Expected<T> must be checked before access or destruction.\n" ; |
698 | if (HasError) { |
699 | dbgs() << "Unchecked Expected<T> contained error:\n" ; |
700 | (*getErrorStorage())->log(dbgs()); |
701 | } else |
702 | dbgs() << "Expected<T> value was in success state. (Note: Expected<T> " |
703 | "values in success mode must still be checked prior to being " |
704 | "destroyed).\n" ; |
705 | abort(); |
706 | } |
707 | #endif |
708 | |
709 | void assertIsChecked() const { |
710 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS |
711 | if (LLVM_UNLIKELY(Unchecked)) |
712 | fatalUncheckedExpected(); |
713 | #endif |
714 | } |
715 | |
716 | union { |
717 | AlignedCharArrayUnion<storage_type> TStorage; |
718 | AlignedCharArrayUnion<error_type> ErrorStorage; |
719 | }; |
720 | bool HasError : 1; |
721 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS |
722 | bool Unchecked : 1; |
723 | #endif |
724 | }; |
725 | |
726 | /// Report a serious error, calling any installed error handler. See |
727 | /// ErrorHandling.h. |
728 | [[noreturn]] void report_fatal_error(Error Err, bool gen_crash_diag = true); |
729 | |
730 | /// Report a fatal error if Err is a failure value. |
731 | /// |
732 | /// This function can be used to wrap calls to fallible functions ONLY when it |
733 | /// is known that the Error will always be a success value. E.g. |
734 | /// |
735 | /// @code{.cpp} |
736 | /// // foo only attempts the fallible operation if DoFallibleOperation is |
737 | /// // true. If DoFallibleOperation is false then foo always returns |
738 | /// // Error::success(). |
739 | /// Error foo(bool DoFallibleOperation); |
740 | /// |
741 | /// cantFail(foo(false)); |
742 | /// @endcode |
743 | inline void cantFail(Error Err, const char *Msg = nullptr) { |
744 | if (Err) { |
745 | if (!Msg) |
746 | Msg = "Failure value returned from cantFail wrapped call" ; |
747 | #ifndef NDEBUG |
748 | std::string Str; |
749 | raw_string_ostream OS(Str); |
750 | OS << Msg << "\n" << Err; |
751 | Msg = OS.str().c_str(); |
752 | #endif |
753 | llvm_unreachable(Msg); |
754 | } |
755 | } |
756 | |
757 | /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and |
758 | /// returns the contained value. |
759 | /// |
760 | /// This function can be used to wrap calls to fallible functions ONLY when it |
761 | /// is known that the Error will always be a success value. E.g. |
762 | /// |
763 | /// @code{.cpp} |
764 | /// // foo only attempts the fallible operation if DoFallibleOperation is |
765 | /// // true. If DoFallibleOperation is false then foo always returns an int. |
766 | /// Expected<int> foo(bool DoFallibleOperation); |
767 | /// |
768 | /// int X = cantFail(foo(false)); |
769 | /// @endcode |
770 | template <typename T> |
771 | T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) { |
772 | if (ValOrErr) |
773 | return std::move(*ValOrErr); |
774 | else { |
775 | if (!Msg) |
776 | Msg = "Failure value returned from cantFail wrapped call" ; |
777 | #ifndef NDEBUG |
778 | std::string Str; |
779 | raw_string_ostream OS(Str); |
780 | auto E = ValOrErr.takeError(); |
781 | OS << Msg << "\n" << E; |
782 | Msg = OS.str().c_str(); |
783 | #endif |
784 | llvm_unreachable(Msg); |
785 | } |
786 | } |
787 | |
788 | /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and |
789 | /// returns the contained reference. |
790 | /// |
791 | /// This function can be used to wrap calls to fallible functions ONLY when it |
792 | /// is known that the Error will always be a success value. E.g. |
793 | /// |
794 | /// @code{.cpp} |
795 | /// // foo only attempts the fallible operation if DoFallibleOperation is |
796 | /// // true. If DoFallibleOperation is false then foo always returns a Bar&. |
797 | /// Expected<Bar&> foo(bool DoFallibleOperation); |
798 | /// |
799 | /// Bar &X = cantFail(foo(false)); |
800 | /// @endcode |
801 | template <typename T> |
802 | T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) { |
803 | if (ValOrErr) |
804 | return *ValOrErr; |
805 | else { |
806 | if (!Msg) |
807 | Msg = "Failure value returned from cantFail wrapped call" ; |
808 | #ifndef NDEBUG |
809 | std::string Str; |
810 | raw_string_ostream OS(Str); |
811 | auto E = ValOrErr.takeError(); |
812 | OS << Msg << "\n" << E; |
813 | Msg = OS.str().c_str(); |
814 | #endif |
815 | llvm_unreachable(Msg); |
816 | } |
817 | } |
818 | |
819 | /// Helper for testing applicability of, and applying, handlers for |
820 | /// ErrorInfo types. |
821 | template <typename HandlerT> |
822 | class ErrorHandlerTraits |
823 | : public ErrorHandlerTraits< |
824 | decltype(&std::remove_reference_t<HandlerT>::operator())> {}; |
825 | |
826 | // Specialization functions of the form 'Error (const ErrT&)'. |
827 | template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> { |
828 | public: |
829 | static bool appliesTo(const ErrorInfoBase &E) { |
830 | return E.template isA<ErrT>(); |
831 | } |
832 | |
833 | template <typename HandlerT> |
834 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { |
835 | assert(appliesTo(*E) && "Applying incorrect handler" ); |
836 | return H(static_cast<ErrT &>(*E)); |
837 | } |
838 | }; |
839 | |
840 | // Specialization functions of the form 'void (const ErrT&)'. |
841 | template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> { |
842 | public: |
843 | static bool appliesTo(const ErrorInfoBase &E) { |
844 | return E.template isA<ErrT>(); |
845 | } |
846 | |
847 | template <typename HandlerT> |
848 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { |
849 | assert(appliesTo(*E) && "Applying incorrect handler" ); |
850 | H(static_cast<ErrT &>(*E)); |
851 | return Error::success(); |
852 | } |
853 | }; |
854 | |
855 | /// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'. |
856 | template <typename ErrT> |
857 | class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> { |
858 | public: |
859 | static bool appliesTo(const ErrorInfoBase &E) { |
860 | return E.template isA<ErrT>(); |
861 | } |
862 | |
863 | template <typename HandlerT> |
864 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { |
865 | assert(appliesTo(*E) && "Applying incorrect handler" ); |
866 | std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release())); |
867 | return H(std::move(SubE)); |
868 | } |
869 | }; |
870 | |
871 | /// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'. |
872 | template <typename ErrT> |
873 | class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> { |
874 | public: |
875 | static bool appliesTo(const ErrorInfoBase &E) { |
876 | return E.template isA<ErrT>(); |
877 | } |
878 | |
879 | template <typename HandlerT> |
880 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { |
881 | assert(appliesTo(*E) && "Applying incorrect handler" ); |
882 | std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release())); |
883 | H(std::move(SubE)); |
884 | return Error::success(); |
885 | } |
886 | }; |
887 | |
888 | // Specialization for member functions of the form 'RetT (const ErrT&)'. |
889 | template <typename C, typename RetT, typename ErrT> |
890 | class ErrorHandlerTraits<RetT (C::*)(ErrT &)> |
891 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; |
892 | |
893 | // Specialization for member functions of the form 'RetT (const ErrT&) const'. |
894 | template <typename C, typename RetT, typename ErrT> |
895 | class ErrorHandlerTraits<RetT (C::*)(ErrT &) const> |
896 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; |
897 | |
898 | // Specialization for member functions of the form 'RetT (const ErrT&)'. |
899 | template <typename C, typename RetT, typename ErrT> |
900 | class ErrorHandlerTraits<RetT (C::*)(const ErrT &)> |
901 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; |
902 | |
903 | // Specialization for member functions of the form 'RetT (const ErrT&) const'. |
904 | template <typename C, typename RetT, typename ErrT> |
905 | class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const> |
906 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; |
907 | |
908 | /// Specialization for member functions of the form |
909 | /// 'RetT (std::unique_ptr<ErrT>)'. |
910 | template <typename C, typename RetT, typename ErrT> |
911 | class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)> |
912 | : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {}; |
913 | |
914 | /// Specialization for member functions of the form |
915 | /// 'RetT (std::unique_ptr<ErrT>) const'. |
916 | template <typename C, typename RetT, typename ErrT> |
917 | class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const> |
918 | : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {}; |
919 | |
920 | inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) { |
921 | return Error(std::move(Payload)); |
922 | } |
923 | |
924 | template <typename HandlerT, typename... HandlerTs> |
925 | Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload, |
926 | HandlerT &&Handler, HandlerTs &&... Handlers) { |
927 | if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload)) |
928 | return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler), |
929 | std::move(Payload)); |
930 | return handleErrorImpl(std::move(Payload), |
931 | std::forward<HandlerTs>(Handlers)...); |
932 | } |
933 | |
934 | /// Pass the ErrorInfo(s) contained in E to their respective handlers. Any |
935 | /// unhandled errors (or Errors returned by handlers) are re-concatenated and |
936 | /// returned. |
937 | /// Because this function returns an error, its result must also be checked |
938 | /// or returned. If you intend to handle all errors use handleAllErrors |
939 | /// (which returns void, and will abort() on unhandled errors) instead. |
940 | template <typename... HandlerTs> |
941 | Error handleErrors(Error E, HandlerTs &&... Hs) { |
942 | if (!E) |
943 | return Error::success(); |
944 | |
945 | std::unique_ptr<ErrorInfoBase> Payload = E.takePayload(); |
946 | |
947 | if (Payload->isA<ErrorList>()) { |
948 | ErrorList &List = static_cast<ErrorList &>(*Payload); |
949 | Error R; |
950 | for (auto &P : List.Payloads) |
951 | R = ErrorList::join( |
952 | E1: std::move(R), |
953 | E2: handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...)); |
954 | return R; |
955 | } |
956 | |
957 | return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...); |
958 | } |
959 | |
960 | /// Behaves the same as handleErrors, except that by contract all errors |
961 | /// *must* be handled by the given handlers (i.e. there must be no remaining |
962 | /// errors after running the handlers, or llvm_unreachable is called). |
963 | template <typename... HandlerTs> |
964 | void handleAllErrors(Error E, HandlerTs &&... Handlers) { |
965 | cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...)); |
966 | } |
967 | |
968 | /// Check that E is a non-error, then drop it. |
969 | /// If E is an error, llvm_unreachable will be called. |
970 | inline void handleAllErrors(Error E) { |
971 | cantFail(Err: std::move(E)); |
972 | } |
973 | |
974 | /// Handle any errors (if present) in an Expected<T>, then try a recovery path. |
975 | /// |
976 | /// If the incoming value is a success value it is returned unmodified. If it |
977 | /// is a failure value then it the contained error is passed to handleErrors. |
978 | /// If handleErrors is able to handle the error then the RecoveryPath functor |
979 | /// is called to supply the final result. If handleErrors is not able to |
980 | /// handle all errors then the unhandled errors are returned. |
981 | /// |
982 | /// This utility enables the follow pattern: |
983 | /// |
984 | /// @code{.cpp} |
985 | /// enum FooStrategy { Aggressive, Conservative }; |
986 | /// Expected<Foo> foo(FooStrategy S); |
987 | /// |
988 | /// auto ResultOrErr = |
989 | /// handleExpected( |
990 | /// foo(Aggressive), |
991 | /// []() { return foo(Conservative); }, |
992 | /// [](AggressiveStrategyError&) { |
993 | /// // Implicitly conusme this - we'll recover by using a conservative |
994 | /// // strategy. |
995 | /// }); |
996 | /// |
997 | /// @endcode |
998 | template <typename T, typename RecoveryFtor, typename... HandlerTs> |
999 | Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath, |
1000 | HandlerTs &&... Handlers) { |
1001 | if (ValOrErr) |
1002 | return ValOrErr; |
1003 | |
1004 | if (auto Err = handleErrors(ValOrErr.takeError(), |
1005 | std::forward<HandlerTs>(Handlers)...)) |
1006 | return std::move(Err); |
1007 | |
1008 | return RecoveryPath(); |
1009 | } |
1010 | |
1011 | /// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner |
1012 | /// will be printed before the first one is logged. A newline will be printed |
1013 | /// after each error. |
1014 | /// |
1015 | /// This function is compatible with the helpers from Support/WithColor.h. You |
1016 | /// can pass any of them as the OS. Please consider using them instead of |
1017 | /// including 'error: ' in the ErrorBanner. |
1018 | /// |
1019 | /// This is useful in the base level of your program to allow clean termination |
1020 | /// (allowing clean deallocation of resources, etc.), while reporting error |
1021 | /// information to the user. |
1022 | void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner = {}); |
1023 | |
1024 | /// Write all error messages (if any) in E to a string. The newline character |
1025 | /// is used to separate error messages. |
1026 | std::string toString(Error E); |
1027 | |
1028 | /// Consume a Error without doing anything. This method should be used |
1029 | /// only where an error can be considered a reasonable and expected return |
1030 | /// value. |
1031 | /// |
1032 | /// Uses of this method are potentially indicative of design problems: If it's |
1033 | /// legitimate to do nothing while processing an "error", the error-producer |
1034 | /// might be more clearly refactored to return an std::optional<T>. |
1035 | inline void consumeError(Error Err) { |
1036 | handleAllErrors(E: std::move(Err), Handlers: [](const ErrorInfoBase &) {}); |
1037 | } |
1038 | |
1039 | /// Convert an Expected to an Optional without doing anything. This method |
1040 | /// should be used only where an error can be considered a reasonable and |
1041 | /// expected return value. |
1042 | /// |
1043 | /// Uses of this method are potentially indicative of problems: perhaps the |
1044 | /// error should be propagated further, or the error-producer should just |
1045 | /// return an Optional in the first place. |
1046 | template <typename T> std::optional<T> expectedToOptional(Expected<T> &&E) { |
1047 | if (E) |
1048 | return std::move(*E); |
1049 | consumeError(E.takeError()); |
1050 | return std::nullopt; |
1051 | } |
1052 | |
1053 | template <typename T> std::optional<T> expectedToStdOptional(Expected<T> &&E) { |
1054 | if (E) |
1055 | return std::move(*E); |
1056 | consumeError(E.takeError()); |
1057 | return std::nullopt; |
1058 | } |
1059 | |
1060 | /// Helper for converting an Error to a bool. |
1061 | /// |
1062 | /// This method returns true if Err is in an error state, or false if it is |
1063 | /// in a success state. Puts Err in a checked state in both cases (unlike |
1064 | /// Error::operator bool(), which only does this for success states). |
1065 | inline bool errorToBool(Error Err) { |
1066 | bool IsError = static_cast<bool>(Err); |
1067 | if (IsError) |
1068 | consumeError(Err: std::move(Err)); |
1069 | return IsError; |
1070 | } |
1071 | |
1072 | /// Helper for Errors used as out-parameters. |
1073 | /// |
1074 | /// This helper is for use with the Error-as-out-parameter idiom, where an error |
1075 | /// is passed to a function or method by reference, rather than being returned. |
1076 | /// In such cases it is helpful to set the checked bit on entry to the function |
1077 | /// so that the error can be written to (unchecked Errors abort on assignment) |
1078 | /// and clear the checked bit on exit so that clients cannot accidentally forget |
1079 | /// to check the result. This helper performs these actions automatically using |
1080 | /// RAII: |
1081 | /// |
1082 | /// @code{.cpp} |
1083 | /// Result foo(Error &Err) { |
1084 | /// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set |
1085 | /// // <body of foo> |
1086 | /// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed. |
1087 | /// } |
1088 | /// @endcode |
1089 | /// |
1090 | /// ErrorAsOutParameter takes an Error* rather than Error& so that it can be |
1091 | /// used with optional Errors (Error pointers that are allowed to be null). If |
1092 | /// ErrorAsOutParameter took an Error reference, an instance would have to be |
1093 | /// created inside every condition that verified that Error was non-null. By |
1094 | /// taking an Error pointer we can just create one instance at the top of the |
1095 | /// function. |
1096 | class ErrorAsOutParameter { |
1097 | public: |
1098 | ErrorAsOutParameter(Error *Err) : Err(Err) { |
1099 | // Raise the checked bit if Err is success. |
1100 | if (Err) |
1101 | (void)!!*Err; |
1102 | } |
1103 | |
1104 | ~ErrorAsOutParameter() { |
1105 | // Clear the checked bit. |
1106 | if (Err && !*Err) |
1107 | *Err = Error::success(); |
1108 | } |
1109 | |
1110 | private: |
1111 | Error *Err; |
1112 | }; |
1113 | |
1114 | /// Helper for Expected<T>s used as out-parameters. |
1115 | /// |
1116 | /// See ErrorAsOutParameter. |
1117 | template <typename T> |
1118 | class ExpectedAsOutParameter { |
1119 | public: |
1120 | ExpectedAsOutParameter(Expected<T> *ValOrErr) |
1121 | : ValOrErr(ValOrErr) { |
1122 | if (ValOrErr) |
1123 | (void)!!*ValOrErr; |
1124 | } |
1125 | |
1126 | ~ExpectedAsOutParameter() { |
1127 | if (ValOrErr) |
1128 | ValOrErr->setUnchecked(); |
1129 | } |
1130 | |
1131 | private: |
1132 | Expected<T> *ValOrErr; |
1133 | }; |
1134 | |
1135 | /// This class wraps a std::error_code in a Error. |
1136 | /// |
1137 | /// This is useful if you're writing an interface that returns a Error |
1138 | /// (or Expected) and you want to call code that still returns |
1139 | /// std::error_codes. |
1140 | class ECError : public ErrorInfo<ECError> { |
1141 | friend Error errorCodeToError(std::error_code); |
1142 | |
1143 | void anchor() override; |
1144 | |
1145 | public: |
1146 | void setErrorCode(std::error_code EC) { this->EC = EC; } |
1147 | std::error_code convertToErrorCode() const override { return EC; } |
1148 | void log(raw_ostream &OS) const override { OS << EC.message(); } |
1149 | |
1150 | // Used by ErrorInfo::classID. |
1151 | static char ID; |
1152 | |
1153 | protected: |
1154 | ECError() = default; |
1155 | ECError(std::error_code EC) : EC(EC) {} |
1156 | |
1157 | std::error_code EC; |
1158 | }; |
1159 | |
1160 | /// The value returned by this function can be returned from convertToErrorCode |
1161 | /// for Error values where no sensible translation to std::error_code exists. |
1162 | /// It should only be used in this situation, and should never be used where a |
1163 | /// sensible conversion to std::error_code is available, as attempts to convert |
1164 | /// to/from this error will result in a fatal error. (i.e. it is a programmatic |
1165 | /// error to try to convert such a value). |
1166 | std::error_code inconvertibleErrorCode(); |
1167 | |
1168 | /// Helper for converting an std::error_code to a Error. |
1169 | Error errorCodeToError(std::error_code EC); |
1170 | |
1171 | /// Helper for converting an ECError to a std::error_code. |
1172 | /// |
1173 | /// This method requires that Err be Error() or an ECError, otherwise it |
1174 | /// will trigger a call to abort(). |
1175 | std::error_code errorToErrorCode(Error Err); |
1176 | |
1177 | /// Convert an ErrorOr<T> to an Expected<T>. |
1178 | template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) { |
1179 | if (auto EC = EO.getError()) |
1180 | return errorCodeToError(EC); |
1181 | return std::move(*EO); |
1182 | } |
1183 | |
1184 | /// Convert an Expected<T> to an ErrorOr<T>. |
1185 | template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) { |
1186 | if (auto Err = E.takeError()) |
1187 | return errorToErrorCode(std::move(Err)); |
1188 | return std::move(*E); |
1189 | } |
1190 | |
1191 | /// This class wraps a string in an Error. |
1192 | /// |
1193 | /// StringError is useful in cases where the client is not expected to be able |
1194 | /// to consume the specific error message programmatically (for example, if the |
1195 | /// error message is to be presented to the user). |
1196 | /// |
1197 | /// StringError can also be used when additional information is to be printed |
1198 | /// along with a error_code message. Depending on the constructor called, this |
1199 | /// class can either display: |
1200 | /// 1. the error_code message (ECError behavior) |
1201 | /// 2. a string |
1202 | /// 3. the error_code message and a string |
1203 | /// |
1204 | /// These behaviors are useful when subtyping is required; for example, when a |
1205 | /// specific library needs an explicit error type. In the example below, |
1206 | /// PDBError is derived from StringError: |
1207 | /// |
1208 | /// @code{.cpp} |
1209 | /// Expected<int> foo() { |
1210 | /// return llvm::make_error<PDBError>(pdb_error_code::dia_failed_loading, |
1211 | /// "Additional information"); |
1212 | /// } |
1213 | /// @endcode |
1214 | /// |
1215 | class StringError : public ErrorInfo<StringError> { |
1216 | public: |
1217 | static char ID; |
1218 | |
1219 | // Prints EC + S and converts to EC |
1220 | StringError(std::error_code EC, const Twine &S = Twine()); |
1221 | |
1222 | // Prints S and converts to EC |
1223 | StringError(const Twine &S, std::error_code EC); |
1224 | |
1225 | void log(raw_ostream &OS) const override; |
1226 | std::error_code convertToErrorCode() const override; |
1227 | |
1228 | const std::string &getMessage() const { return Msg; } |
1229 | |
1230 | private: |
1231 | std::string Msg; |
1232 | std::error_code EC; |
1233 | const bool PrintMsgOnly = false; |
1234 | }; |
1235 | |
1236 | /// Create formatted StringError object. |
1237 | template <typename... Ts> |
1238 | inline Error createStringError(std::error_code EC, char const *Fmt, |
1239 | const Ts &... Vals) { |
1240 | std::string Buffer; |
1241 | raw_string_ostream Stream(Buffer); |
1242 | Stream << format(Fmt, Vals...); |
1243 | return make_error<StringError>(Args&: Stream.str(), Args&: EC); |
1244 | } |
1245 | |
1246 | Error createStringError(std::error_code EC, char const *Msg); |
1247 | |
1248 | inline Error createStringError(std::error_code EC, const Twine &S) { |
1249 | return createStringError(EC, Msg: S.str().c_str()); |
1250 | } |
1251 | |
1252 | template <typename... Ts> |
1253 | inline Error createStringError(std::errc EC, char const *Fmt, |
1254 | const Ts &... Vals) { |
1255 | return createStringError(std::make_error_code(e: EC), Fmt, Vals...); |
1256 | } |
1257 | |
1258 | /// This class wraps a filename and another Error. |
1259 | /// |
1260 | /// In some cases, an error needs to live along a 'source' name, in order to |
1261 | /// show more detailed information to the user. |
1262 | class FileError final : public ErrorInfo<FileError> { |
1263 | |
1264 | friend Error createFileError(const Twine &, Error); |
1265 | friend Error createFileError(const Twine &, size_t, Error); |
1266 | |
1267 | public: |
1268 | void log(raw_ostream &OS) const override { |
1269 | assert(Err && "Trying to log after takeError()." ); |
1270 | OS << "'" << FileName << "': " ; |
1271 | if (Line) |
1272 | OS << "line " << *Line << ": " ; |
1273 | Err->log(OS); |
1274 | } |
1275 | |
1276 | std::string messageWithoutFileInfo() const { |
1277 | std::string Msg; |
1278 | raw_string_ostream OS(Msg); |
1279 | Err->log(OS); |
1280 | return OS.str(); |
1281 | } |
1282 | |
1283 | StringRef getFileName() const { return FileName; } |
1284 | |
1285 | Error takeError() { return Error(std::move(Err)); } |
1286 | |
1287 | std::error_code convertToErrorCode() const override; |
1288 | |
1289 | // Used by ErrorInfo::classID. |
1290 | static char ID; |
1291 | |
1292 | private: |
1293 | FileError(const Twine &F, std::optional<size_t> LineNum, |
1294 | std::unique_ptr<ErrorInfoBase> E) { |
1295 | assert(E && "Cannot create FileError from Error success value." ); |
1296 | FileName = F.str(); |
1297 | Err = std::move(E); |
1298 | Line = std::move(LineNum); |
1299 | } |
1300 | |
1301 | static Error build(const Twine &F, std::optional<size_t> Line, Error E) { |
1302 | std::unique_ptr<ErrorInfoBase> Payload; |
1303 | handleAllErrors(E: std::move(E), |
1304 | Handlers: [&](std::unique_ptr<ErrorInfoBase> EIB) -> Error { |
1305 | Payload = std::move(EIB); |
1306 | return Error::success(); |
1307 | }); |
1308 | return Error( |
1309 | std::unique_ptr<FileError>(new FileError(F, Line, std::move(Payload)))); |
1310 | } |
1311 | |
1312 | std::string FileName; |
1313 | std::optional<size_t> Line; |
1314 | std::unique_ptr<ErrorInfoBase> Err; |
1315 | }; |
1316 | |
1317 | /// Concatenate a source file path and/or name with an Error. The resulting |
1318 | /// Error is unchecked. |
1319 | inline Error createFileError(const Twine &F, Error E) { |
1320 | return FileError::build(F, Line: std::optional<size_t>(), E: std::move(E)); |
1321 | } |
1322 | |
1323 | /// Concatenate a source file path and/or name with line number and an Error. |
1324 | /// The resulting Error is unchecked. |
1325 | inline Error createFileError(const Twine &F, size_t Line, Error E) { |
1326 | return FileError::build(F, Line: std::optional<size_t>(Line), E: std::move(E)); |
1327 | } |
1328 | |
1329 | /// Concatenate a source file path and/or name with a std::error_code |
1330 | /// to form an Error object. |
1331 | inline Error createFileError(const Twine &F, std::error_code EC) { |
1332 | return createFileError(F, E: errorCodeToError(EC)); |
1333 | } |
1334 | |
1335 | /// Concatenate a source file path and/or name with line number and |
1336 | /// std::error_code to form an Error object. |
1337 | inline Error createFileError(const Twine &F, size_t Line, std::error_code EC) { |
1338 | return createFileError(F, Line, E: errorCodeToError(EC)); |
1339 | } |
1340 | |
1341 | Error createFileError(const Twine &F, ErrorSuccess) = delete; |
1342 | |
1343 | /// Helper for check-and-exit error handling. |
1344 | /// |
1345 | /// For tool use only. NOT FOR USE IN LIBRARY CODE. |
1346 | /// |
1347 | class ExitOnError { |
1348 | public: |
1349 | /// Create an error on exit helper. |
1350 | ExitOnError(std::string Banner = "" , int DefaultErrorExitCode = 1) |
1351 | : Banner(std::move(Banner)), |
1352 | GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {} |
1353 | |
1354 | /// Set the banner string for any errors caught by operator(). |
1355 | void setBanner(std::string Banner) { this->Banner = std::move(Banner); } |
1356 | |
1357 | /// Set the exit-code mapper function. |
1358 | void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) { |
1359 | this->GetExitCode = std::move(GetExitCode); |
1360 | } |
1361 | |
1362 | /// Check Err. If it's in a failure state log the error(s) and exit. |
1363 | void operator()(Error Err) const { checkError(Err: std::move(Err)); } |
1364 | |
1365 | /// Check E. If it's in a success state then return the contained value. If |
1366 | /// it's in a failure state log the error(s) and exit. |
1367 | template <typename T> T operator()(Expected<T> &&E) const { |
1368 | checkError(Err: E.takeError()); |
1369 | return std::move(*E); |
1370 | } |
1371 | |
1372 | /// Check E. If it's in a success state then return the contained reference. If |
1373 | /// it's in a failure state log the error(s) and exit. |
1374 | template <typename T> T& operator()(Expected<T&> &&E) const { |
1375 | checkError(Err: E.takeError()); |
1376 | return *E; |
1377 | } |
1378 | |
1379 | private: |
1380 | void checkError(Error Err) const { |
1381 | if (Err) { |
1382 | int ExitCode = GetExitCode(Err); |
1383 | logAllUnhandledErrors(E: std::move(Err), OS&: errs(), ErrorBanner: Banner); |
1384 | exit(status: ExitCode); |
1385 | } |
1386 | } |
1387 | |
1388 | std::string Banner; |
1389 | std::function<int(const Error &)> GetExitCode; |
1390 | }; |
1391 | |
1392 | /// Conversion from Error to LLVMErrorRef for C error bindings. |
1393 | inline LLVMErrorRef wrap(Error Err) { |
1394 | return reinterpret_cast<LLVMErrorRef>(Err.takePayload().release()); |
1395 | } |
1396 | |
1397 | /// Conversion from LLVMErrorRef to Error for C error bindings. |
1398 | inline Error unwrap(LLVMErrorRef ErrRef) { |
1399 | return Error(std::unique_ptr<ErrorInfoBase>( |
1400 | reinterpret_cast<ErrorInfoBase *>(ErrRef))); |
1401 | } |
1402 | |
1403 | } // end namespace llvm |
1404 | |
1405 | #endif // LLVM_SUPPORT_ERROR_H |
1406 | |