-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathllvm-expected.h
1502 lines (1298 loc) · 48.3 KB
/
llvm-expected.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines an API used to report recoverable errors.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_SUPPORT_ERROR_H
#define LLVM_SUPPORT_ERROR_H
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <memory>
#include <mutex>
#include <new>
#include <sstream>
#include <string>
#include <system_error>
#include <type_traits>
#include <utility>
#include <vector>
#if defined(_MSC_VER)
# include <io.h>
# include <fcntl.h>
# include <sal.h>
#else
# include <unistd.h>
#endif
#ifndef __has_feature
# define __has_feature(x) 0
#endif
#ifndef __has_extension
# define __has_extension(x) 0
#endif
#ifndef __has_attribute
# define __has_attribute(x) 0
#endif
#ifndef __has_cpp_attribute
# define __has_cpp_attribute(x) 0
#endif
#ifndef __has_builtin
# define __has_builtin(x) 0
#endif
/// \macro LLVM_GNUC_PREREQ
/// Extend the default __GNUC_PREREQ even if glibc's features.h isn't
/// available.
#ifndef LLVM_GNUC_PREREQ
# if defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__)
# define LLVM_GNUC_PREREQ(maj, min, patch) \
((__GNUC__ << 20) + (__GNUC_MINOR__ << 10) + __GNUC_PATCHLEVEL__ >= \
((maj) << 20) + ((min) << 10) + (patch))
# elif defined(__GNUC__) && defined(__GNUC_MINOR__)
# define LLVM_GNUC_PREREQ(maj, min, patch) \
((__GNUC__ << 20) + (__GNUC_MINOR__ << 10) >= ((maj) << 20) + ((min) << 10))
# else
# define LLVM_GNUC_PREREQ(maj, min, patch) 0
# endif
#endif
#ifdef __GNUC__
#define LLVM_ATTRIBUTE_NORETURN __attribute__((noreturn))
#elif defined(_MSC_VER)
#define LLVM_ATTRIBUTE_NORETURN __declspec(noreturn)
#else
#define LLVM_ATTRIBUTE_NORETURN
#endif
#if __has_builtin(__builtin_expect) || LLVM_GNUC_PREREQ(4, 0, 0)
#define LLVM_LIKELY(EXPR) __builtin_expect((bool)(EXPR), true)
#define LLVM_UNLIKELY(EXPR) __builtin_expect((bool)(EXPR), false)
#else
#define LLVM_LIKELY(EXPR) (EXPR)
#define LLVM_UNLIKELY(EXPR) (EXPR)
#endif
/// LLVM_ATTRIBUTE_NOINLINE - On compilers where we have a directive to do so,
/// mark a method "not for inlining".
#if __has_attribute(noinline) || LLVM_GNUC_PREREQ(3, 4, 0)
#define LLVM_ATTRIBUTE_NOINLINE __attribute__((noinline))
#elif defined(_MSC_VER)
#define LLVM_ATTRIBUTE_NOINLINE __declspec(noinline)
#else
#define LLVM_ATTRIBUTE_NOINLINE
#endif
/// LLVM_NODISCARD - Warn if a type or return value is discarded.
#if __cplusplus > 201402L && __has_cpp_attribute(nodiscard)
#define LLVM_NODISCARD [[nodiscard]]
#elif !__cplusplus
// Workaround for llvm.org/PR23435, since clang 3.6 and below emit a spurious
// error when __has_cpp_attribute is given a scoped attribute in C mode.
#define LLVM_NODISCARD
#elif __has_cpp_attribute(clang::warn_unused_result)
#define LLVM_NODISCARD [[clang::warn_unused_result]]
#else
#define LLVM_NODISCARD
#endif
/// LLVM_BUILTIN_UNREACHABLE - On compilers which support it, expands
/// to an expression which states that it is undefined behavior for the
/// compiler to reach this point. Otherwise is not defined.
#if __has_builtin(__builtin_unreachable) || LLVM_GNUC_PREREQ(4, 5, 0)
# define LLVM_BUILTIN_UNREACHABLE __builtin_unreachable()
#elif defined(_MSC_VER)
# define LLVM_BUILTIN_UNREACHABLE __assume(false)
#endif
namespace llvm {
/// \struct AlignedCharArray
/// Helper for building an aligned character array type.
///
/// This template is used to explicitly build up a collection of aligned
/// character array types. We have to build these up using a macro and explicit
/// specialization to cope with MSVC (at least till 2015) where only an
/// integer literal can be used to specify an alignment constraint. Once built
/// up here, we can then begin to indirect between these using normal C++
/// template parameters.
// MSVC requires special handling here.
#ifndef _MSC_VER
template<std::size_t Alignment, std::size_t Size>
struct AlignedCharArray {
alignas(Alignment) char buffer[Size];
};
#else // _MSC_VER
/// Create a type with an aligned char buffer.
template<std::size_t Alignment, std::size_t Size>
struct AlignedCharArray;
// We provide special variations of this template for the most common
// alignments because __declspec(align(...)) doesn't actually work when it is
// a member of a by-value function argument in MSVC, even if the alignment
// request is something reasonably like 8-byte or 16-byte. Note that we can't
// even include the declspec with the union that forces the alignment because
// MSVC warns on the existence of the declspec despite the union member forcing
// proper alignment.
template<std::size_t Size>
struct AlignedCharArray<1, Size> {
union {
char aligned;
char buffer[Size];
};
};
template<std::size_t Size>
struct AlignedCharArray<2, Size> {
union {
short aligned;
char buffer[Size];
};
};
template<std::size_t Size>
struct AlignedCharArray<4, Size> {
union {
int aligned;
char buffer[Size];
};
};
template<std::size_t Size>
struct AlignedCharArray<8, Size> {
union {
double aligned;
char buffer[Size];
};
};
// The rest of these are provided with a __declspec(align(...)) and we simply
// can't pass them by-value as function arguments on MSVC.
#define LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(x) \
template<std::size_t Size> \
struct AlignedCharArray<x, Size> { \
__declspec(align(x)) char buffer[Size]; \
};
LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(16)
LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(32)
LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(64)
LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT(128)
#undef LLVM_ALIGNEDCHARARRAY_TEMPLATE_ALIGNMENT
#endif // _MSC_VER
namespace detail {
template <typename T1,
typename T2 = char, typename T3 = char, typename T4 = char,
typename T5 = char, typename T6 = char, typename T7 = char,
typename T8 = char, typename T9 = char, typename T10 = char>
class AlignerImpl {
T1 t1; T2 t2; T3 t3; T4 t4; T5 t5; T6 t6; T7 t7; T8 t8; T9 t9; T10 t10;
AlignerImpl() = delete;
};
template <typename T1,
typename T2 = char, typename T3 = char, typename T4 = char,
typename T5 = char, typename T6 = char, typename T7 = char,
typename T8 = char, typename T9 = char, typename T10 = char>
union SizerImpl {
char arr1[sizeof(T1)], arr2[sizeof(T2)], arr3[sizeof(T3)], arr4[sizeof(T4)],
arr5[sizeof(T5)], arr6[sizeof(T6)], arr7[sizeof(T7)], arr8[sizeof(T8)],
arr9[sizeof(T9)], arr10[sizeof(T10)];
};
} // end namespace detail
/// This union template exposes a suitably aligned and sized character
/// array member which can hold elements of any of up to ten types.
///
/// These types may be arrays, structs, or any other types. The goal is to
/// expose a char array buffer member which can be used as suitable storage for
/// a placement new of any of these types. Support for more than ten types can
/// be added at the cost of more boilerplate.
template <typename T1,
typename T2 = char, typename T3 = char, typename T4 = char,
typename T5 = char, typename T6 = char, typename T7 = char,
typename T8 = char, typename T9 = char, typename T10 = char>
struct AlignedCharArrayUnion : llvm::AlignedCharArray<
alignof(llvm::detail::AlignerImpl<T1, T2, T3, T4, T5,
T6, T7, T8, T9, T10>),
sizeof(::llvm::detail::SizerImpl<T1, T2, T3, T4, T5,
T6, T7, T8, T9, T10>)> {
};
/// This function calls abort(), and prints the optional message to stderr.
/// Use the llvm_unreachable macro (that adds location info), instead of
/// calling this function directly.
LLVM_ATTRIBUTE_NORETURN inline void
llvm_unreachable_internal(const char *msg, const char *file, unsigned line) {
// This code intentionally doesn't call the ErrorHandler callback, because
// llvm_unreachable is intended to be used to indicate "impossible"
// situations, and not legitimate runtime errors.
if (msg)
std::cerr << msg << "\n";
std::cerr << "UNREACHABLE executed";
if (file)
std::cerr << " at " << file << ":" << line;
std::cerr << "!\n";
abort();
#ifdef LLVM_BUILTIN_UNREACHABLE
// Windows systems and possibly others don't declare abort() to be noreturn,
// so use the unreachable builtin to avoid a Clang self-host warning.
LLVM_BUILTIN_UNREACHABLE;
#endif
}
}
/// Marks that the current location is not supposed to be reachable.
/// In !NDEBUG builds, prints the message and location info to stderr.
/// In NDEBUG builds, becomes an optimizer hint that the current location
/// is not supposed to be reachable. On compilers that don't support
/// such hints, prints a reduced message instead.
///
/// Use this instead of assert(0). It conveys intent more clearly and
/// allows compilers to omit some unnecessary code.
#ifndef NDEBUG
#define llvm_unreachable(msg) \
::llvm::llvm_unreachable_internal(msg, __FILE__, __LINE__)
#elif defined(LLVM_BUILTIN_UNREACHABLE)
#define llvm_unreachable(msg) LLVM_BUILTIN_UNREACHABLE
#else
#define llvm_unreachable(msg) ::llvm::llvm_unreachable_internal()
#endif
namespace {
enum class ErrorErrorCode : int {
MultipleErrors = 1,
InconvertibleError
};
// FIXME: This class is only here to support the transition to llvm::Error. It
// will be removed once this transition is complete. Clients should prefer to
// deal with the Error value directly, rather than converting to error_code.
class ErrorErrorCategory : public std::error_category {
public:
const char *name() const noexcept override { return "Error"; }
std::string message(int condition) const override {
switch (static_cast<ErrorErrorCode>(condition)) {
case ErrorErrorCode::MultipleErrors:
return "Multiple errors";
case ErrorErrorCode::InconvertibleError:
return "Inconvertible error value. An error has occurred that could "
"not be converted to a known std::error_code. Please file a "
"bug.";
}
llvm_unreachable("Unhandled error code");
}
};
}
inline static const ErrorErrorCategory ErrorErrorCat;
namespace llvm {
class ErrorSuccess;
/// Base class for error info classes. Do not extend this directly: Extend
/// the ErrorInfo template subclass instead.
class ErrorInfoBase {
public:
virtual ~ErrorInfoBase() = default;
/// Print an error message to an output stream.
virtual void log(std::ostream &OS) const = 0;
/// Return the error message as a string.
virtual std::string message() const {
std::ostringstream OS;
log(OS);
return OS.str();
}
/// Convert this error to a std::error_code.
///
/// This is a temporary crutch to enable interaction with code still
/// using std::error_code. It will be removed in the future.
virtual std::error_code convertToErrorCode() const = 0;
// Returns the class ID for this type.
static const void *classID() { return &ID; }
// Returns the class ID for the dynamic type of this ErrorInfoBase instance.
virtual const void *dynamicClassID() const = 0;
// Check whether this instance is a subclass of the class identified by
// ClassID.
virtual bool isA(const void *const ClassID) const {
return ClassID == classID();
}
// Check whether this instance is a subclass of ErrorInfoT.
template <typename ErrorInfoT> bool isA() const {
return isA(ErrorInfoT::classID());
}
private:
inline static const char ID = 0;
};
/// Lightweight error class with error context and mandatory checking.
///
/// Instances of this class wrap a ErrorInfoBase pointer. Failure states
/// are represented by setting the pointer to a ErrorInfoBase subclass
/// instance containing information describing the failure. Success is
/// represented by a null pointer value.
///
/// Instances of Error also contains a 'Checked' flag, which must be set
/// before the destructor is called, otherwise the destructor will trigger a
/// runtime error. This enforces at runtime the requirement that all Error
/// instances be checked or returned to the caller.
///
/// There are two ways to set the checked flag, depending on what state the
/// Error instance is in. For Error instances indicating success, it
/// is sufficient to invoke the boolean conversion operator. E.g.:
///
/// @code{.cpp}
/// Error foo(<...>);
///
/// if (auto E = foo(<...>))
/// return E; // <- Return E if it is in the error state.
/// // We have verified that E was in the success state. It can now be safely
/// // destroyed.
/// @endcode
///
/// A success value *can not* be dropped. For example, just calling 'foo(<...>)'
/// without testing the return value will raise a runtime error, even if foo
/// returns success.
///
/// For Error instances representing failure, you must use either the
/// handleErrors or handleAllErrors function with a typed handler. E.g.:
///
/// @code{.cpp}
/// class MyErrorInfo : public ErrorInfo<MyErrorInfo> {
/// // Custom error info.
/// };
///
/// Error foo(<...>) { return make_error<MyErrorInfo>(...); }
///
/// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo.
/// auto NewE =
/// handleErrors(E,
/// [](const MyErrorInfo &M) {
/// // Deal with the error.
/// },
/// [](std::unique_ptr<OtherError> M) -> Error {
/// if (canHandle(*M)) {
/// // handle error.
/// return Error::success();
/// }
/// // Couldn't handle this error instance. Pass it up the stack.
/// return Error(std::move(M));
/// );
/// // Note - we must check or return NewE in case any of the handlers
/// // returned a new error.
/// @endcode
///
/// The handleAllErrors function is identical to handleErrors, except
/// that it has a void return type, and requires all errors to be handled and
/// no new errors be returned. It prevents errors (assuming they can all be
/// handled) from having to be bubbled all the way to the top-level.
///
/// *All* Error instances must be checked before destruction, even if
/// they're moved-assigned or constructed from Success values that have already
/// been checked. This enforces checking through all levels of the call stack.
class LLVM_NODISCARD Error {
// ErrorList needs to be able to yank ErrorInfoBase pointers out of this
// class to add to the error list.
friend class ErrorList;
// handleErrors needs to be able to set the Checked flag.
template <typename... HandlerTs>
friend Error handleErrors(Error E, HandlerTs &&... Handlers);
// Expected<T> needs to be able to steal the payload when constructed from an
// error.
template <typename T> friend class Expected;
protected:
/// Create a success value. Prefer using 'Error::success()' for readability
Error() {
setPtr(nullptr);
setChecked(false);
}
public:
/// Create a success value.
static ErrorSuccess success();
// Errors are not copy-constructable.
Error(const Error &Other) = delete;
/// Move-construct an error value. The newly constructed error is considered
/// unchecked, even if the source error had been checked. The original error
/// becomes a checked Success value, regardless of its original state.
Error(Error &&Other) {
setChecked(true);
*this = std::move(Other);
}
/// Create an error value. Prefer using the 'make_error' function, but
/// this constructor can be useful when "re-throwing" errors from handlers.
Error(std::unique_ptr<ErrorInfoBase> Payload) {
setPtr(Payload.release());
setChecked(false);
}
// Errors are not copy-assignable.
Error &operator=(const Error &Other) = delete;
/// Move-assign an error value. The current error must represent success, you
/// you cannot overwrite an unhandled error. The current error is then
/// considered unchecked. The source error becomes a checked success value,
/// regardless of its original state.
Error &operator=(Error &&Other) {
// Don't allow overwriting of unchecked values.
assertIsChecked();
setPtr(Other.getPtr());
// This Error is unchecked, even if the source error was checked.
setChecked(false);
// Null out Other's payload and set its checked bit.
Other.setPtr(nullptr);
Other.setChecked(true);
return *this;
}
/// Destroy a Error. Fails with a call to abort() if the error is
/// unchecked.
~Error() {
assertIsChecked();
delete getPtr();
}
/// Bool conversion. Returns true if this Error is in a failure state,
/// and false if it is in an accept state. If the error is in a Success state
/// it will be considered checked.
explicit operator bool() {
setChecked(getPtr() == nullptr);
return getPtr() != nullptr;
}
/// Check whether one error is a subclass of another.
template <typename ErrT> bool isA() const {
return getPtr() && getPtr()->isA(ErrT::classID());
}
/// Returns the dynamic class id of this error, or null if this is a success
/// value.
const void* dynamicClassID() const {
if (!getPtr())
return nullptr;
return getPtr()->dynamicClassID();
}
private:
#if !defined(NDEBUG)
// assertIsChecked() happens very frequently, but under normal circumstances
// is supposed to be a no-op. So we want it to be inlined, but having a bunch
// of debug prints can cause the function to be too large for inlining. So
// it's important that we define this function out of line so that it can't be
// inlined.
LLVM_ATTRIBUTE_NORETURN
void fatalUncheckedError() const {
std::cerr << "Program aborted due to an unhandled Error:\n";
if (getPtr())
getPtr()->log(std::cerr);
else
std::cerr << "Error value was Success. (Note: Success values must still be "
"checked prior to being destroyed).\n";
abort();
}
#endif
void assertIsChecked() {
#if !defined(NDEBUG)
if (LLVM_UNLIKELY(!getChecked() || getPtr()))
fatalUncheckedError();
#endif
}
ErrorInfoBase *getPtr() const {
return reinterpret_cast<ErrorInfoBase*>(
reinterpret_cast<uintptr_t>(Payload) &
~static_cast<uintptr_t>(0x1));
}
void setPtr(ErrorInfoBase *EI) {
#if !defined(NDEBUG)
Payload = reinterpret_cast<ErrorInfoBase*>(
(reinterpret_cast<uintptr_t>(EI) &
~static_cast<uintptr_t>(0x1)) |
(reinterpret_cast<uintptr_t>(Payload) & 0x1));
#else
Payload = EI;
#endif
}
bool getChecked() const {
#if !defined(NDEBUG)
return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0;
#else
return true;
#endif
}
void setChecked(bool V) {
Payload = reinterpret_cast<ErrorInfoBase*>(
(reinterpret_cast<uintptr_t>(Payload) &
~static_cast<uintptr_t>(0x1)) |
(V ? 0 : 1));
}
std::unique_ptr<ErrorInfoBase> takePayload() {
std::unique_ptr<ErrorInfoBase> Tmp(getPtr());
setPtr(nullptr);
setChecked(true);
return Tmp;
}
friend std::ostream &operator<<(std::ostream &OS, const Error &E) {
if (auto P = E.getPtr())
P->log(OS);
else
OS << "success";
return OS;
}
ErrorInfoBase *Payload = nullptr;
};
/// Subclass of Error for the sole purpose of identifying the success path in
/// the type system. This allows to catch invalid conversion to Expected<T> at
/// compile time.
class ErrorSuccess : public Error {};
inline ErrorSuccess Error::success() { return ErrorSuccess(); }
/// Make a Error instance representing failure using the given error info
/// type.
template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) {
return Error(std::make_unique<ErrT>(std::forward<ArgTs>(Args)...));
}
/// Base class for user error types. Users should declare their error types
/// like:
///
/// class MyError : public ErrorInfo<MyError> {
/// ....
/// };
///
/// This class provides an implementation of the ErrorInfoBase::kind
/// method, which is used by the Error RTTI system.
template <typename ThisErrT, typename ParentErrT = ErrorInfoBase>
class ErrorInfo : public ParentErrT {
public:
static const void *classID() { return &ThisErrT::ID; }
const void *dynamicClassID() const override { return &ThisErrT::ID; }
bool isA(const void *const ClassID) const override {
return ClassID == classID() || ParentErrT::isA(ClassID);
}
};
/// Special ErrorInfo subclass representing a list of ErrorInfos.
/// Instances of this class are constructed by joinError.
class ErrorList final : public ErrorInfo<ErrorList> {
// handleErrors needs to be able to iterate the payload list of an
// ErrorList.
template <typename... HandlerTs>
friend Error handleErrors(Error E, HandlerTs &&... Handlers);
// joinErrors is implemented in terms of join.
friend Error joinErrors(Error, Error);
public:
void log(std::ostream &OS) const override {
OS << "Multiple errors:\n";
for (auto &ErrPayload : Payloads) {
ErrPayload->log(OS);
OS << "\n";
}
}
std::error_code convertToErrorCode() const override {
return std::error_code(static_cast<int>(ErrorErrorCode::MultipleErrors),
ErrorErrorCat);
}
// Used by ErrorInfo::classID.
inline static const char ID = 0;
private:
ErrorList(std::unique_ptr<ErrorInfoBase> Payload1,
std::unique_ptr<ErrorInfoBase> Payload2) {
assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&
"ErrorList constructor payloads should be singleton errors");
Payloads.push_back(std::move(Payload1));
Payloads.push_back(std::move(Payload2));
}
static Error join(Error E1, Error E2) {
if (!E1)
return E2;
if (!E2)
return E1;
if (E1.isA<ErrorList>()) {
auto &E1List = static_cast<ErrorList &>(*E1.getPtr());
if (E2.isA<ErrorList>()) {
auto E2Payload = E2.takePayload();
auto &E2List = static_cast<ErrorList &>(*E2Payload);
for (auto &Payload : E2List.Payloads)
E1List.Payloads.push_back(std::move(Payload));
} else
E1List.Payloads.push_back(E2.takePayload());
return E1;
}
if (E2.isA<ErrorList>()) {
auto &E2List = static_cast<ErrorList &>(*E2.getPtr());
E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload());
return E2;
}
return Error(std::unique_ptr<ErrorList>(
new ErrorList(E1.takePayload(), E2.takePayload())));
}
std::vector<std::unique_ptr<ErrorInfoBase>> Payloads;
};
/// Concatenate errors. The resulting Error is unchecked, and contains the
/// ErrorInfo(s), if any, contained in E1, followed by the
/// ErrorInfo(s), if any, contained in E2.
inline Error joinErrors(Error E1, Error E2) {
return ErrorList::join(std::move(E1), std::move(E2));
}
/// Tagged union holding either a T or a Error.
///
/// This class parallels ErrorOr, but replaces error_code with Error. Since
/// Error cannot be copied, this class replaces getError() with
/// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the
/// error class type.
template <class T> class LLVM_NODISCARD Expected {
template <class T1> friend class ExpectedAsOutParameter;
template <class OtherT> friend class Expected;
static const bool isRef = std::is_reference<T>::value;
using wrap = std::reference_wrapper<typename std::remove_reference<T>::type>;
using error_type = std::unique_ptr<ErrorInfoBase>;
public:
using storage_type = typename std::conditional<isRef, wrap, T>::type;
using value_type = T;
private:
using reference = typename std::remove_reference<T>::type &;
using const_reference = const typename std::remove_reference<T>::type &;
using pointer = typename std::remove_reference<T>::type *;
using const_pointer = const typename std::remove_reference<T>::type *;
public:
/// Create an Expected<T> error value from the given Error.
Expected(Error Err)
: HasError(true)
#if !defined(NDEBUG)
// Expected is unchecked upon construction in Debug builds.
, Unchecked(true)
#endif
{
assert(Err && "Cannot create Expected<T> from Error success value.");
new (getErrorStorage()) error_type(Err.takePayload());
}
/// Forbid to convert from Error::success() implicitly, this avoids having
/// Expected<T> foo() { return Error::success(); } which compiles otherwise
/// but triggers the assertion above.
Expected(ErrorSuccess) = delete;
/// Create an Expected<T> success value from the given OtherT value, which
/// must be convertible to T.
template <typename OtherT>
Expected(OtherT &&Val,
typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
* = nullptr)
: HasError(false)
#if !defined(NDEBUG)
// Expected is unchecked upon construction in Debug builds.
, Unchecked(true)
#endif
{
new (getStorage()) storage_type(std::forward<OtherT>(Val));
}
/// Move construct an Expected<T> value.
Expected(Expected &&Other) { moveConstruct(std::move(Other)); }
/// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
/// must be convertible to T.
template <class OtherT>
Expected(Expected<OtherT> &&Other,
typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
* = nullptr) {
moveConstruct(std::move(Other));
}
/// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
/// isn't convertible to T.
template <class OtherT>
explicit Expected(
Expected<OtherT> &&Other,
typename std::enable_if<!std::is_convertible<OtherT, T>::value>::type * =
nullptr) {
moveConstruct(std::move(Other));
}
/// Move-assign from another Expected<T>.
Expected &operator=(Expected &&Other) {
moveAssign(std::move(Other));
return *this;
}
/// Destroy an Expected<T>.
~Expected() {
assertIsChecked();
if (!HasError)
getStorage()->~storage_type();
else
getErrorStorage()->~error_type();
}
/// Return false if there is an error.
explicit operator bool() {
#if !defined(NDEBUG)
Unchecked = HasError;
#endif
return !HasError;
}
/// Returns a reference to the stored T value.
reference get() {
assertIsChecked();
return *getStorage();
}
/// Returns a const reference to the stored T value.
const_reference get() const {
assertIsChecked();
return const_cast<Expected<T> *>(this)->get();
}
/// Check that this Expected<T> is an error of type ErrT.
template <typename ErrT> bool errorIsA() const {
return HasError && (*getErrorStorage())->template isA<ErrT>();
}
/// Take ownership of the stored error.
/// After calling this the Expected<T> is in an indeterminate state that can
/// only be safely destructed. No further calls (beside the destructor) should
/// be made on the Expected<T> vaule.
Error takeError() {
#if !defined(NDEBUG)
Unchecked = false;
#endif
return HasError ? Error(std::move(*getErrorStorage())) : Error::success();
}
/// Returns a pointer to the stored T value.
pointer operator->() {
assertIsChecked();
return toPointer(getStorage());
}
/// Returns a const pointer to the stored T value.
const_pointer operator->() const {
assertIsChecked();
return toPointer(getStorage());
}
/// Returns a reference to the stored T value.
reference operator*() {
assertIsChecked();
return *getStorage();
}
/// Returns a const reference to the stored T value.
const_reference operator*() const {
assertIsChecked();
return *getStorage();
}
private:
template <class T1>
static bool compareThisIfSameType(const T1 &a, const T1 &b) {
return &a == &b;
}
template <class T1, class T2>
static bool compareThisIfSameType(const T1 &a, const T2 &b) {
return false;
}
template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) {
HasError = Other.HasError;
#if !defined(NDEBUG)
Unchecked = true;
Other.Unchecked = false;
#endif
if (!HasError)
new (getStorage()) storage_type(std::move(*Other.getStorage()));
else
new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage()));
}
template <class OtherT> void moveAssign(Expected<OtherT> &&Other) {
assertIsChecked();
if (compareThisIfSameType(*this, Other))
return;
this->~Expected();
new (this) Expected(std::move(Other));
}
pointer toPointer(pointer Val) { return Val; }
const_pointer toPointer(const_pointer Val) const { return Val; }
pointer toPointer(wrap *Val) { return &Val->get(); }
const_pointer toPointer(const wrap *Val) const { return &Val->get(); }
storage_type *getStorage() {
assert(!HasError && "Cannot get value when an error exists!");
return reinterpret_cast<storage_type *>(TStorage.buffer);
}
const storage_type *getStorage() const {
assert(!HasError && "Cannot get value when an error exists!");
return reinterpret_cast<const storage_type *>(TStorage.buffer);
}
error_type *getErrorStorage() {
assert(HasError && "Cannot get error when a value exists!");
return reinterpret_cast<error_type *>(ErrorStorage.buffer);
}
const error_type *getErrorStorage() const {
assert(HasError && "Cannot get error when a value exists!");
return reinterpret_cast<const error_type *>(ErrorStorage.buffer);
}
// Used by ExpectedAsOutParameter to reset the checked flag.
void setUnchecked() {
#if !defined(NDEBUG)
Unchecked = true;
#endif
}
#if !defined(NDEBUG)
LLVM_ATTRIBUTE_NORETURN
LLVM_ATTRIBUTE_NOINLINE
void fatalUncheckedExpected() const {
std::cerr << "Expected<T> must be checked before access or destruction.\n";
if (HasError) {
std::cerr << "Unchecked Expected<T> contained error:\n";
(*getErrorStorage())->log(std::cerr);
} else
std::cerr << "Expected<T> value was in success state. (Note: Expected<T> "
"values in success mode must still be checked prior to being "
"destroyed).\n";
abort();
}
#endif
void assertIsChecked() {
#if !defined(NDEBUG)
if (LLVM_UNLIKELY(Unchecked))
fatalUncheckedExpected();
#endif
}
union {
AlignedCharArrayUnion<storage_type> TStorage;
AlignedCharArrayUnion<error_type> ErrorStorage;
};
bool HasError : 1;
#if !defined(NDEBUG)
bool Unchecked : 1;
#endif
};
/// Report a fatal error if Err is a failure value.
///
/// This function can be used to wrap calls to fallible functions ONLY when it
/// is known that the Error will always be a success value. E.g.
///
/// @code{.cpp}
/// // foo only attempts the fallible operation if DoFallibleOperation is
/// // true. If DoFallibleOperation is false then foo always returns
/// // Error::success().
/// Error foo(bool DoFallibleOperation);
///
/// cantFail(foo(false));
/// @endcode
inline void cantFail(Error Err, const char *Msg = nullptr) {
if (Err) {
if (!Msg)
Msg = "Failure value returned from cantFail wrapped call";
llvm_unreachable(Msg);
}
}
/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
/// returns the contained value.
///
/// This function can be used to wrap calls to fallible functions ONLY when it
/// is known that the Error will always be a success value. E.g.
///
/// @code{.cpp}
/// // foo only attempts the fallible operation if DoFallibleOperation is
/// // true. If DoFallibleOperation is false then foo always returns an int.
/// Expected<int> foo(bool DoFallibleOperation);
///
/// int X = cantFail(foo(false));
/// @endcode
template <typename T>