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