-
Notifications
You must be signed in to change notification settings - Fork 267
Expand file tree
/
Copy pathcpp2util.h
More file actions
1828 lines (1586 loc) · 68.2 KB
/
cpp2util.h
File metadata and controls
1828 lines (1586 loc) · 68.2 KB
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
// Copyright (c) Herb Sutter
// SPDX-License-Identifier: CC-BY-NC-ND-4.0
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//===========================================================================
// Cpp2 utilities:
// Language support implementations
// #include'd by generated Cpp1 code
//===========================================================================
#ifndef __CPP2_UTIL
#define __CPP2_UTIL
// If this implementation doesn't support source_location yet, disable it
// TODO: technically this test should have <version> included first, but GEFN
#if !defined(_MSC_VER) && !defined(__cpp_lib_source_location)
#undef CPP2_USE_SOURCE_LOCATION
#endif
// If the cppfront user requested -pure-cpp2, this will be set
// and we should be using modules only
#ifdef CPP2_USE_MODULES
// If we have real modules, use those the best we can
// as implementations are still underway
#ifdef __cpp_modules
#ifndef _MSC_VER
// This is the ideal -- note that we just voted "import std;"
// into draft C++23 in late July 2022, so implementers haven't
// had time to catch up yet. As of this writing (September 2022)
// no compiler will take this path yet, but they're on the way...
import std;
#else // MSVC
// Note: When C++23 "import std;" is available, we will switch to that here
// In the meantime, this is what works on MSVC which is the only compiler
// I've been able to get access to that implements modules enough to demo
// (but we'll have more full-C++20 compilers soon!)
import std.core;
import std.regex;
import std.filesystem;
import std.memory;
import std.threading;
// Suppress spurious MSVC modules warning
#pragma warning(disable:5050)
#endif
// Otherwise, "fake it till you make it"... include (nearly) all the
// standard headers, with a feature test #ifdef for each header that
// isn't yet supported by all of { VS 2022, g++-10, clang++-12 }
// ... this should approximate "import std;" on those compilers
#else
#include <version>
#include <concepts>
#ifdef __cpp_lib_coroutine
#include <coroutine>
#endif
#include <any>
#include <bitset>
#include <chrono>
#include <compare>
#include <csetjmp>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdlib>
#include <ctime>
#include <functional>
#include <initializer_list>
#include <optional>
#ifdef __cpp_lib_source_location
#include <source_location>
#endif
#include <tuple>
#include <type_traits>
#include <typeindex>
#ifndef CPP2_NO_RTTI
#include <typeinfo>
#endif
#include <utility>
#include <variant>
#include <memory>
#ifdef __cpp_lib_memory_resource
#include <memory_resource>
#endif
#include <new>
#include <scoped_allocator>
#include <cfloat>
#include <cinttypes>
#include <climits>
#include <cstdint>
#include <limits>
#include <cassert>
#include <cerrno>
#ifndef CPP2_NO_EXCEPTIONS
#include <exception>
#endif
#include <stdexcept>
#include <system_error>
#include <cctype>
#include <charconv>
#include <cstring>
#if __has_include(<cuchar>)
#include <cuchar>
#endif
#include <cwchar>
#include <cwctype>
#ifdef __cpp_lib_format
#include <format>
#endif
#include <string>
#include <string_view>
#include <array>
#include <deque>
#include <forward_list>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <span>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <iterator>
#include <ranges>
#include <algorithm>
#include <bit>
#include <cfenv>
#include <cmath>
#include <complex>
#include <numbers>
#include <numeric>
#include <random>
#include <ratio>
#include <valarray>
#include <clocale>
#include <codecvt>
#include <locale>
#include <cstdio>
#include <fstream>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <ostream>
#ifdef __cpp_lib_spanstream
#include <spanstream>
#endif
#include <sstream>
#include <streambuf>
#ifdef __cpp_lib_syncstream
#include <syncstream>
#endif
#include <filesystem>
#include <regex>
#include <atomic>
#ifdef __cpp_lib_barrier
#include <barrier>
#endif
#include <condition_variable>
#include <future>
#ifdef __cpp_lib_latch
#include <latch>
#endif
#include <mutex>
#ifdef __cpp_lib_semaphore
#include <semaphore>
#endif
#include <shared_mutex>
#ifdef __cpp_lib_jthread
#include <stop_token>
#endif
#include <thread>
#include <iso646.h>
// libstdc++ currently has a dependency on linking TBB if <execution> is
// included, and TBB seems to be not automatically installed and linkable
// on some GCC installations, so let's not pull in that little-used header
// in our -pure-cpp2 "import std;" simulation mode... if you need this,
// use mixed mode (not -pure-cpp2) and #include all the headers you need
// including this one
//
// #include <execution>
#endif
// Otherwise, we're not in -pure-cpp2 and so just #include
// what we need in this header to make this self-contained
#else
#include <type_traits>
#include <new>
#include <memory>
#include <random>
#include <tuple>
#include <string>
#include <string_view>
#include <vector>
#include <span>
#include <iostream>
#include <variant>
#include <any>
#include <optional>
#include <cstddef>
#include <utility>
#include <cstdio>
#include <cstdint>
#include <algorithm>
#include <compare>
#include <iterator>
#include <concepts>
#include <system_error>
#include <limits>
#ifndef CPP2_NO_EXCEPTIONS
#include <exception>
#endif
#ifndef CPP2_NO_RTTI
#include <typeinfo>
#endif
#if defined(CPP2_USE_SOURCE_LOCATION)
#include <source_location>
#endif
#endif
#define CPP2_TYPEOF(x) std::remove_cvref_t<decltype(x)>
#define CPP2_FORWARD(x) std::forward<decltype(x)>(x)
#define CPP2_CONTINUE_BREAK(NAME) goto CONTINUE_##NAME; CONTINUE_##NAME: continue; goto BREAK_##NAME; BREAK_##NAME: break;
// these redundant goto's to avoid 'unused label' warnings
namespace cpp2 {
//-----------------------------------------------------------------------
//
// Convenience names for fundamental types
//
// Note: De jure, some of these are optional per the C and C++ standards
// De facto, all of these are supported in all implementations I know of
//
//-----------------------------------------------------------------------
//
// Encouraged by default: Fixed-precision names
using i8 = std::int8_t ;
using i16 = std::int16_t ;
using i32 = std::int32_t ;
using i64 = std::int64_t ;
using u8 = std::uint8_t ;
using u16 = std::uint16_t ;
using u32 = std::uint32_t ;
using u64 = std::uint64_t ;
// Discouraged: Variable precision names
// short
using ushort = unsigned short;
// int
using ulong = unsigned long;
// long
using longlong = long long;
using ulonglong = unsigned long long;
using longdouble = long double;
// Strongly discouraged, for compatibility/interop only
using __schar = signed char; // normally use i8 instead
using __uchar = unsigned char; // normally use u8 instead
//-----------------------------------------------------------------------
//
// General helpers
//
//-----------------------------------------------------------------------
//
constexpr auto max(auto... values) {
return std::max( { values... } );
}
//-----------------------------------------------------------------------
//
// String: A helper workaround for passing a string literal as a
// template argument
//
//-----------------------------------------------------------------------
//
template<std::size_t N>
struct String
{
constexpr String(const char (&str)[N])
{
std::copy_n(str, N, value);
}
auto operator<=>(String const&) const = default;
char value[N] = {};
};
//-----------------------------------------------------------------------
//
// contract_group
//
//-----------------------------------------------------------------------
//
#ifdef CPP2_USE_SOURCE_LOCATION
#define CPP2_SOURCE_LOCATION_PARAM , std::source_location where
#define CPP2_SOURCE_LOCATION_PARAM_WITH_DEFAULT , std::source_location where = std::source_location::current()
#define CPP2_SOURCE_LOCATION_PARAM_SOLO std::source_location where
#define CPP2_SOURCE_LOCATION_ARG , where
#else
#define CPP2_SOURCE_LOCATION_PARAM
#define CPP2_SOURCE_LOCATION_PARAM_WITH_DEFAULT
#define CPP2_SOURCE_LOCATION_PARAM_SOLO
#define CPP2_SOURCE_LOCATION_ARG
#endif
// For C++23: make this std::string_view and drop the macro
// Before C++23 std::string_view was not guaranteed to be trivially copyable,
// and so in<T> will pass it by const& and really it should be by value
#define CPP2_MESSAGE_PARAM char const*
class contract_group {
public:
using handler = void (*)(CPP2_MESSAGE_PARAM msg CPP2_SOURCE_LOCATION_PARAM);
constexpr contract_group (handler h = {}) : reporter(h) { }
constexpr auto set_handler(handler h);
constexpr auto get_handler() const -> handler { return reporter; }
constexpr auto expects (bool b, CPP2_MESSAGE_PARAM msg = "" CPP2_SOURCE_LOCATION_PARAM_WITH_DEFAULT)
-> void { if (!b) reporter(msg CPP2_SOURCE_LOCATION_ARG); }
private:
handler reporter;
};
[[noreturn]] inline auto report_and_terminate(std::string_view group, CPP2_MESSAGE_PARAM msg = "" CPP2_SOURCE_LOCATION_PARAM_WITH_DEFAULT) noexcept -> void {
std::cerr
#ifdef CPP2_USE_SOURCE_LOCATION
<< where.file_name() << "("
<< where.line() << ") "
<< where.function_name() << ": "
#endif
<< group << " violation";
if (msg[0] != '\0') {
std::cerr << ": " << msg;
}
std::cerr << "\n";
std::terminate();
}
auto inline Default = contract_group(
[](CPP2_MESSAGE_PARAM msg CPP2_SOURCE_LOCATION_PARAM)noexcept {
report_and_terminate("Contract", msg CPP2_SOURCE_LOCATION_ARG);
}
);
auto inline Bounds = contract_group(
[](CPP2_MESSAGE_PARAM msg CPP2_SOURCE_LOCATION_PARAM)noexcept {
report_and_terminate("Bounds safety", msg CPP2_SOURCE_LOCATION_ARG);
}
);
auto inline Null = contract_group(
[](CPP2_MESSAGE_PARAM msg CPP2_SOURCE_LOCATION_PARAM)noexcept {
report_and_terminate("Null safety", msg CPP2_SOURCE_LOCATION_ARG);
}
);
auto inline Type = contract_group(
[](CPP2_MESSAGE_PARAM msg CPP2_SOURCE_LOCATION_PARAM)noexcept {
report_and_terminate("Type safety", msg CPP2_SOURCE_LOCATION_ARG);
}
);
auto inline Testing = contract_group(
[](CPP2_MESSAGE_PARAM msg CPP2_SOURCE_LOCATION_PARAM)noexcept {
report_and_terminate("Testing", msg CPP2_SOURCE_LOCATION_ARG);
}
);
constexpr auto contract_group::set_handler(handler h) {
Default.expects(h);
reporter = h;
}
// Null pointer deref checking
//
auto assert_not_null(auto&& p CPP2_SOURCE_LOCATION_PARAM_WITH_DEFAULT) -> decltype(auto)
{
// NOTE: This "!= T{}" test may or may not work for STL iterators. The standard
// doesn't guarantee that using == and != will reliably report whether an
// STL iterator has the default-constructed value. So use it only for raw *...
if constexpr (std::is_pointer_v<CPP2_TYPEOF(p)>) {
Null.expects(p != CPP2_TYPEOF(p){}, "dynamic null dereference attempt detected" CPP2_SOURCE_LOCATION_ARG);
}
return CPP2_FORWARD(p);
}
// Subscript bounds checking
//
auto assert_in_bounds(auto&& x, auto&& arg CPP2_SOURCE_LOCATION_PARAM_WITH_DEFAULT) -> decltype(auto)
requires (std::is_integral_v<CPP2_TYPEOF(arg)> &&
requires { std::size(x); std::ssize(x); x[arg]; std::begin(x) + 2; })
{
Bounds.expects(0 <= arg && arg < [&]() -> auto {
if constexpr (std::is_signed_v<CPP2_TYPEOF(arg)>) { return std::ssize(x); }
else { return std::size(x); }
}(), "out of bounds access attempt detected" CPP2_SOURCE_LOCATION_ARG);
return CPP2_FORWARD(x) [ CPP2_FORWARD(arg) ];
}
auto assert_in_bounds(auto&& x, auto&& arg CPP2_SOURCE_LOCATION_PARAM_WITH_DEFAULT) -> decltype(auto)
{
return CPP2_FORWARD(x) [ CPP2_FORWARD(arg) ];
}
//-----------------------------------------------------------------------
//
// Support wrappers that unblock using this file in environments that
// disable EH or RTTI
//
// Note: This is not endorsing disabling those features, it's just
// recognizing that disabling them is popular (e.g., games, WASM)
// and so we should remove a potential adoption blocker... only a
// few features in this file depend on EH or RTTI anyway, and
// wouldn't be exercised in such an environment anyway so there
// is no real net loss here
//
//-----------------------------------------------------------------------
//
[[noreturn]] auto Throw(auto&& x, [[maybe_unused]] char const* msg) -> void {
#ifdef CPP2_NO_EXCEPTIONS
Type.expects(
!"exceptions are disabled with -fno-exceptions",
msg
);
std::terminate();
#else
throw CPP2_FORWARD(x);
#endif
}
inline auto Uncaught_exceptions() -> int {
#ifdef CPP2_NO_EXCEPTIONS
return 0;
#else
return std::uncaught_exceptions();
#endif
}
template<typename T>
auto Dynamic_cast( [[maybe_unused]] auto&& x ) -> decltype(auto) {
#ifdef CPP2_NO_RTTI
Type.expects(
!"'as' dynamic casting is disabled with -fno-rtti", // more likely to appear on console
"'as' dynamic casting is disabled with -fno-rtti" // make message available to hooked handlers
);
return nullptr;
#else
return dynamic_cast<T>(CPP2_FORWARD(x));
#endif
}
template<typename T>
auto Typeid() -> decltype(auto) {
#ifdef CPP2_NO_RTTI
Type.expects(
!"'any' dynamic casting is disabled with -fno-rtti", // more likely to appear on console
"'any' dynamic casting is disabled with -fno-rtti" // make message available to hooked handlers
);
#else
return typeid(T);
#endif
}
// We don't need typeid(expr) yet -- uncomment this if/when we need it
//auto Typeid( [[maybe_unused]] auto&& x ) -> decltype(auto) {
//#ifdef CPP2_NO_RTTI
// Type.expects(
// !"<write appropriate error message here>"
// );
//#else
// return typeid(CPP2_FORWARD(x));
//#endif
//}
//-----------------------------------------------------------------------
//
// Arena objects for std::allocators
//
// Note: cppfront translates "new" to "cpp2_new", so in Cpp2 code
// these are invoked by simply "unique.new<T>" etc.
//
//-----------------------------------------------------------------------
//
struct {
template<typename T>
[[nodiscard]] auto cpp2_new(auto&& ...args) const -> std::unique_ptr<T> {
return std::make_unique<T>(CPP2_FORWARD(args)...);
}
} unique;
[[maybe_unused]] struct {
template<typename T>
[[nodiscard]] auto cpp2_new(auto&& ...args) const -> std::shared_ptr<T> {
return std::make_shared<T>(CPP2_FORWARD(args)...);
}
} shared;
template<typename T>
[[nodiscard]] auto cpp2_new(auto&& ...args) -> std::unique_ptr<T> {
return unique.cpp2_new<T>(CPP2_FORWARD(args)...);
}
//-----------------------------------------------------------------------
//
// in<T> For "in" parameter
//
//-----------------------------------------------------------------------
//
template<typename T>
constexpr bool prefer_pass_by_value =
sizeof(T) <= 2*sizeof(void*)
&& std::is_trivially_copy_constructible_v<T>;
template<typename T>
requires std::is_class_v<T> || std::is_union_v<T> || std::is_array_v<T> || std::is_function_v<T>
constexpr bool prefer_pass_by_value<T> = false;
template<typename T>
requires (!std::is_void_v<T>)
using in =
std::conditional_t <
prefer_pass_by_value<T>,
T const,
T const&
>;
//-----------------------------------------------------------------------
//
// Initialization: These are closely related...
//
// deferred_init<T> For deferred-initialized local object
//
// out<T> For out parameter
//
//-----------------------------------------------------------------------
//
template<typename T>
class deferred_init {
alignas(T) std::byte data[sizeof(T)]; // or: std::aligned_storage_t<sizeof(T), alignof(T)> data
bool init = false;
auto t() -> T& { return *std::launder(reinterpret_cast<T*>(&data)); }
template<typename U>
friend class out;
auto destroy() -> void { if (init) { t().~T(); } init = false; }
public:
deferred_init() noexcept { }
~deferred_init() noexcept { destroy(); }
auto value() noexcept -> T& { Default.expects(init); return t(); }
auto construct(auto&& ...args) -> void { Default.expects(!init); new (&data) T{CPP2_FORWARD(args)...}; init = true; }
};
template<typename T>
class out {
// Not going to bother with std::variant here
union {
T* t;
deferred_init<T>* dt;
};
out<T>* ot = {};
bool has_t;
// Each out in a chain contains its own uncaught_count ...
int uncaught_count = Uncaught_exceptions();
// ... but all in a chain share the topmost called_construct_
bool called_construct_ = false;
public:
out(T* t_) noexcept : t{ t_}, has_t{true} { Default.expects( t); }
out(deferred_init<T>* dt_) noexcept : dt{dt_}, has_t{false} { Default.expects(dt); }
out(out<T>* ot_) noexcept : ot{ot_}, has_t{ot_->has_t} { Default.expects(ot);
if (has_t) { t = ot->t; }
else { dt = ot->dt; }
}
auto called_construct() -> bool& {
if (ot) { return ot->called_construct(); }
else { return called_construct_; }
}
// In the case of an exception, if the parameter was uninitialized
// then leave it in the same state on exit (strong guarantee)
~out() {
if (called_construct() && uncaught_count != Uncaught_exceptions()) {
Default.expects(!has_t);
dt->destroy();
called_construct() = false;
}
}
auto construct(auto&& ...args) -> void {
if (has_t || called_construct()) {
if constexpr (requires { *t = T(CPP2_FORWARD(args)...); }) {
Default.expects( t );
*t = T(CPP2_FORWARD(args)...);
}
else {
Default.expects(false, "attempted to copy assign, but copy assignment is not available");
}
}
else {
Default.expects( dt );
if (dt->init) {
if constexpr (requires { *t = T(CPP2_FORWARD(args)...); }) {
dt->value() = T(CPP2_FORWARD(args)...);
}
else {
Default.expects(false, "attempted to copy assign, but copy assignment is not available");
}
}
else {
dt->construct(CPP2_FORWARD(args)...);
called_construct() = true;
}
}
}
auto value() noexcept -> T& {
if (has_t) {
Default.expects( t );
return *t;
}
else {
Default.expects( dt );
return dt->value();
}
}
};
//-----------------------------------------------------------------------
//
// CPP2_UFCS: Variadic macro generating a variadic lamba, oh my...
//
//-----------------------------------------------------------------------
//
#if defined(_MSC_VER) && !defined(__clang_major__)
#define CPP2_FORCE_INLINE __forceinline
#define CPP2_FORCE_INLINE_LAMBDA [[msvc::forceinline]]
#define CPP2_LAMBDA_NO_DISCARD
#else
#define CPP2_FORCE_INLINE __attribute__((always_inline))
#define CPP2_FORCE_INLINE_LAMBDA __attribute__((always_inline))
#if defined(__clang_major__)
// Also check __cplusplus, only to satisfy Clang -pedantic-errors
#if __cplusplus >= 202302L && (__clang_major__ > 13 || (__clang_major__ == 13 && __clang_minor__ >= 2))
#define CPP2_LAMBDA_NO_DISCARD [[nodiscard]]
#else
#define CPP2_LAMBDA_NO_DISCARD
#endif
#elif defined(__GNUC__)
#if __GNUC__ >= 9
#define CPP2_LAMBDA_NO_DISCARD [[nodiscard]]
#else
#define CPP2_LAMBDA_NO_DISCARD
#endif
#if ((__GNUC__ * 100) + __GNUC_MINOR__) < 1003
// GCC 10.2 doesn't support this feature (10.3 is fine)
#undef CPP2_FORCE_INLINE_LAMBDA
#define CPP2_FORCE_INLINE_LAMBDA
#endif
#else
#define CPP2_LAMBDA_NO_DISCARD
#endif
#endif
// Note: [&] is because a nested UFCS might be viewed as trying to capture 'this'
#define CPP2_UFCS(FUNCNAME,PARAM1,...) \
[&] CPP2_LAMBDA_NO_DISCARD (auto&& obj, auto&& ...params) CPP2_FORCE_INLINE_LAMBDA -> decltype(auto) { \
if constexpr (requires{ CPP2_FORWARD(obj).FUNCNAME(CPP2_FORWARD(params)...); }) { \
return CPP2_FORWARD(obj).FUNCNAME(CPP2_FORWARD(params)...); \
} else { \
return FUNCNAME(CPP2_FORWARD(obj), CPP2_FORWARD(params)...); \
} \
}(PARAM1, __VA_ARGS__)
#define CPP2_UFCS_0(FUNCNAME,PARAM1) \
[&] CPP2_LAMBDA_NO_DISCARD (auto&& obj) CPP2_FORCE_INLINE_LAMBDA -> decltype(auto) { \
if constexpr (requires{ CPP2_FORWARD(obj).FUNCNAME(); }) { \
return CPP2_FORWARD(obj).FUNCNAME(); \
} else { \
return FUNCNAME(CPP2_FORWARD(obj)); \
} \
}(PARAM1)
#define CPP2_UFCS_REMPARENS(...) __VA_ARGS__
#define CPP2_UFCS_TEMPLATE(FUNCNAME,TEMPARGS,PARAM1,...) \
[&] CPP2_LAMBDA_NO_DISCARD (auto&& obj, auto&& ...params) CPP2_FORCE_INLINE_LAMBDA -> decltype(auto) { \
if constexpr (requires{ CPP2_FORWARD(obj).template FUNCNAME CPP2_UFCS_REMPARENS TEMPARGS (CPP2_FORWARD(params)...); }) { \
return CPP2_FORWARD(obj).template FUNCNAME CPP2_UFCS_REMPARENS TEMPARGS (CPP2_FORWARD(params)...); \
} else { \
return FUNCNAME CPP2_UFCS_REMPARENS TEMPARGS (CPP2_FORWARD(obj), CPP2_FORWARD(params)...); \
} \
}(PARAM1, __VA_ARGS__)
#define CPP2_UFCS_TEMPLATE_0(FUNCNAME,TEMPARGS,PARAM1) \
[&] CPP2_LAMBDA_NO_DISCARD (auto&& obj) CPP2_FORCE_INLINE_LAMBDA -> decltype(auto) { \
if constexpr (requires{ CPP2_FORWARD(obj).template FUNCNAME CPP2_UFCS_REMPARENS TEMPARGS (); }) { \
return CPP2_FORWARD(obj).template FUNCNAME CPP2_UFCS_REMPARENS TEMPARGS (); \
} else { \
return FUNCNAME CPP2_UFCS_REMPARENS TEMPARGS (CPP2_FORWARD(obj)); \
} \
}(PARAM1)
// But for non-local lambdas [&] is not allowed
#define CPP2_UFCS_NONLOCAL(FUNCNAME,PARAM1,...) \
[] CPP2_LAMBDA_NO_DISCARD (auto&& obj, auto&& ...params) CPP2_FORCE_INLINE_LAMBDA -> decltype(auto) { \
if constexpr (requires{ CPP2_FORWARD(obj).FUNCNAME(CPP2_FORWARD(params)...); }) { \
return CPP2_FORWARD(obj).FUNCNAME(CPP2_FORWARD(params)...); \
} else { \
return FUNCNAME(CPP2_FORWARD(obj), CPP2_FORWARD(params)...); \
} \
}(PARAM1, __VA_ARGS__)
#define CPP2_UFCS_0_NONLOCAL(FUNCNAME,PARAM1) \
[] CPP2_LAMBDA_NO_DISCARD (auto&& obj) CPP2_FORCE_INLINE_LAMBDA -> decltype(auto) { \
if constexpr (requires{ CPP2_FORWARD(obj).FUNCNAME(); }) { \
return CPP2_FORWARD(obj).FUNCNAME(); \
} else { \
return FUNCNAME(CPP2_FORWARD(obj)); \
} \
}(PARAM1)
#define CPP2_UFCS_TEMPLATE_NONLOCAL(FUNCNAME,TEMPARGS,PARAM1,...) \
[] CPP2_LAMBDA_NO_DISCARD (auto&& obj, auto&& ...params) CPP2_FORCE_INLINE_LAMBDA -> decltype(auto) { \
if constexpr (requires{ CPP2_FORWARD(obj).template FUNCNAME CPP2_UFCS_REMPARENS TEMPARGS (CPP2_FORWARD(params)...); }) { \
return CPP2_FORWARD(obj).template FUNCNAME CPP2_UFCS_REMPARENS TEMPARGS (CPP2_FORWARD(params)...); \
} else { \
return FUNCNAME CPP2_UFCS_REMPARENS TEMPARGS (CPP2_FORWARD(obj), CPP2_FORWARD(params)...); \
} \
}(PARAM1, __VA_ARGS__)
#define CPP2_UFCS_TEMPLATE_0_NONLOCAL(FUNCNAME,TEMPARGS,PARAM1) \
[] CPP2_LAMBDA_NO_DISCARD (auto&& obj) CPP2_FORCE_INLINE_LAMBDA -> decltype(auto) { \
if constexpr (requires{ CPP2_FORWARD(obj).template FUNCNAME CPP2_UFCS_REMPARENS TEMPARGS (); }) { \
return CPP2_FORWARD(obj).template FUNCNAME CPP2_UFCS_REMPARENS TEMPARGS (); \
} else { \
return FUNCNAME CPP2_UFCS_REMPARENS TEMPARGS (CPP2_FORWARD(obj)); \
} \
}(PARAM1)
//-----------------------------------------------------------------------
//
// is and as
//
//-----------------------------------------------------------------------
//
//-------------------------------------------------------------------------------------------------------------
// Built-in is
//
// For designating "holds no value" -- used only with is, not as
// TODO: Does this really warrant a new synonym? Perhaps "is void" is enough
using empty = void;
// Templates
//
template <template <typename...> class C, typename... Ts>
constexpr auto is(C< Ts...> const& ) -> bool {
return true;
}
#if defined(_MSC_VER)
template <template <typename, typename...> class C, typename T>
constexpr auto is( T const& ) -> bool {
return false;
}
#else
template <template <typename...> class C, typename T>
constexpr auto is( T const& ) -> bool {
return false;
}
#endif
template <template <typename,auto> class C, typename T, auto V>
constexpr auto is( C<T, V> const& ) -> bool {
return true;
}
template <template <typename,auto> class C, typename T>
constexpr auto is( T const& ) -> bool {
return false;
}
// Types
//
template< typename C, typename X >
auto is( X const& ) -> bool {
return false;
}
template< typename C, typename X >
requires std::is_same_v<C, X>
auto is( X const& ) -> bool {
return true;
}
template< typename C, typename X >
requires (std::is_base_of_v<C, X> && !std::is_same_v<C,X>)
auto is( X const& ) -> bool {
return true;
}
template< typename C, typename X >
requires (
( std::is_base_of_v<X, C> ||
( std::is_polymorphic_v<C> && std::is_polymorphic_v<X>)
) && !std::is_same_v<C,X>)
auto is( X const& x ) -> bool {
return Dynamic_cast<C const*>(&x) != nullptr;
}
template< typename C, typename X >
requires (
( std::is_base_of_v<X, C> ||
( std::is_polymorphic_v<C> && std::is_polymorphic_v<X>)
) && !std::is_same_v<C,X>)
auto is( X const* x ) -> bool {
return Dynamic_cast<C const*>(x) != nullptr;
}
template< typename C, typename X >
requires (requires (X x) { *x; X(); } && std::is_same_v<C, empty>)
auto is( X const& x ) -> bool {
return x == X();
}
// Values
//
inline constexpr auto is( auto const& x, auto const& value ) -> bool
{
// Value with customized operator_is case
if constexpr (requires{ x.op_is(value); }) {
return x.op_is(value);
}
// Predicate case
else if constexpr (requires{ bool{ value(x) }; }) {
return value(x);
}
else if constexpr (std::is_function_v<decltype(value)> || requires{ &value.operator(); }) {
return false;
}
// Value equality case
else if constexpr (requires{ bool{x == value}; }) {
return x == value;
}
return false;
}
//-------------------------------------------------------------------------------------------------------------
// Built-in as
//
// For use when returning "no such thing", such as
// when customizing "as" for std::variant
struct nonesuch_ {
auto operator==(auto const&) -> bool { return false; }
};
constexpr static nonesuch_ nonesuch;
// The 'as' cast functions are <To, From> so use that order here
// If it's confusing, we can switch this to <From, To>
template< typename To, typename From >
inline constexpr auto is_narrowing_v =
// [dcl.init.list] 7.1
(std::is_floating_point_v<From> && std::is_integral_v<To>) ||
// [dcl.init.list] 7.2
(std::is_floating_point_v<From> && std::is_floating_point_v<To> && sizeof(From) > sizeof(To)) ||
// [dcl.init.list] 7.3
(std::is_integral_v<From> && std::is_floating_point_v<To>) ||
(std::is_enum_v<From> && std::is_floating_point_v<To>) ||
// [dcl.init.list] 7.4
(std::is_integral_v<From> && std::is_integral_v<To> && sizeof(From) > sizeof(To)) ||
(std::is_enum_v<From> && std::is_integral_v<To> && sizeof(From) > sizeof(To)) ||
// [dcl.init.list] 7.5
(std::is_pointer_v<From> && std::is_same_v<To, bool>);
template <typename... Ts>
inline constexpr auto program_violates_type_safety_guarantee = sizeof...(Ts) < 0;
// For literals we can check for safe 'narrowing' at a compile time (e.g., 1 as std::size_t)
template< typename C, auto x >
inline constexpr bool is_castable_v =
std::is_integral_v<C> &&
std::is_integral_v<CPP2_TYPEOF(x)> &&
!(static_cast<CPP2_TYPEOF(x)>(static_cast<C>(x)) != x ||
(
(std::is_signed_v<C> != std::is_signed_v<CPP2_TYPEOF(x)>) &&
((static_cast<C>(x) < C{}) != (x < CPP2_TYPEOF(x){}))
)
);
// As
//
template< typename C >
auto as(auto const&) -> auto {
return nonesuch;
}
template< typename C, auto x >
requires (std::is_arithmetic_v<C> && std::is_arithmetic_v<CPP2_TYPEOF(x)>)
inline constexpr auto as() -> auto
{
if constexpr ( is_castable_v<C, x> ) {
return static_cast<C>(x);
} else {
return nonesuch;
}
}
template< typename C >
inline constexpr auto as(auto const& x) -> auto
requires (
std::is_floating_point_v<C> &&
std::is_floating_point_v<CPP2_TYPEOF(x)> &&
sizeof(CPP2_TYPEOF(x)) > sizeof(C)
)
{
return nonesuch;
}
// Signed/unsigned conversions to a not-smaller type are handled as a precondition,
// and trying to cast from a value that is in the half of the value space that isn't
// representable in the target type C is flagged as a Type safety contract violation
template< typename C >
inline constexpr auto as(auto const& x CPP2_SOURCE_LOCATION_PARAM_WITH_DEFAULT) -> auto
requires (
std::is_integral_v<C> &&
std::is_integral_v<CPP2_TYPEOF(x)> &&
std::is_signed_v<CPP2_TYPEOF(x)> != std::is_signed_v<C> &&
sizeof(CPP2_TYPEOF(x)) <= sizeof(C)
)
{
const C c = static_cast<C>(x);
Type.expects( // precondition check: must be round-trippable => not lossy
static_cast<CPP2_TYPEOF(x)>(c) == x && (c < C{}) == (x < CPP2_TYPEOF(x){}),
"dynamic lossy narrowing conversion attempt detected" CPP2_SOURCE_LOCATION_ARG
);
return c;
}
template< typename C, typename X >
requires std::is_same_v<C, X>
auto as( X const& x ) -> decltype(auto) {
return x;
}
template< typename C, typename X >
requires std::is_same_v<C, X>
auto as( X& x ) -> decltype(auto) {
return x;