-
Notifications
You must be signed in to change notification settings - Fork 267
Expand file tree
/
Copy pathcpp2util.h
More file actions
2141 lines (1884 loc) · 81.9 KB
/
cpp2util.h
File metadata and controls
2141 lines (1884 loc) · 81.9 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
// There are two kinds of entities in this file.
//
// 1) Entities in namespace cpp2:: itself, and documented at /cppfront/docs
//
// These are intended for programs to use directly, to the extent
// described in the documentation. Using any parts not described in the
// documentation is not supported.
//
// 2) Entities in namespace cpp2::impl::, and macros
//
// These should not be used by the program. They form the language
// support library intended to be called only from generated code.
//
// For example, if a Cpp2 function leaves a local variable
// uninitialized, cppfront will generate uses of impl::deferred_init<>
// under the covers and guarantee it is constructed exactly once, so
// the implementation here doesn't need to check for double construction
// because it can't happen; using the name impl::deferred_init directly
// from program code is not supported.
//
//===========================================================================
#ifndef CPP2_UTIL_H
#define CPP2_UTIL_H
// If this implementation doesn't support source_location yet, disable it
#include <version>
#if !defined(_MSC_VER) && !defined(__cpp_lib_source_location)
#undef CPP2_USE_SOURCE_LOCATION
#endif
// If the user requested making the entire C++ standard library available
// via module import (incl. via -pure-cpp2) or header include, do that
#if defined(CPP2_IMPORT_STD) || defined(CPP2_INCLUDE_STD)
// If C++23 'import std;' was requested but isn't available, fall back
// to the 'include std' path
#if defined(CPP2_IMPORT_STD) && defined(__cpp_lib_modules)
import std.compat;
// If 'include std' was requested, include all standard headers.
// This list tracks the current draft standard, so as of this
// writing includes draft C++26 headers like <debugging>.
// Use a feature test #ifdef for each header that isn't supported
// by all of { VS 2022, g++-10, clang++-12 }
#else
#ifdef _MSC_VER
#include "intrin.h"
#endif
#include <algorithm>
#include <any>
#include <array>
#include <atomic>
#ifdef __cpp_lib_barrier
#include <barrier>
#endif
#include <bit>
#include <bitset>
#include <cassert>
#include <cctype>
#include <cerrno>
#include <cfenv>
#include <cfloat>
#include <charconv>
#include <chrono>
#include <cinttypes>
#include <climits>
#include <clocale>
#include <cmath>
#include <codecvt>
#include <compare>
#include <complex>
#include <concepts>
#include <condition_variable>
#ifdef __cpp_lib_coroutine
#include <coroutine>
#endif
#include <csetjmp>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#if __has_include(<cuchar>)
#include <cuchar>
#endif
#include <cwchar>
#include <cwctype>
#ifdef __cpp_lib_debugging
#include <debugging>
#endif
#include <deque>
#ifndef CPP2_NO_EXCEPTIONS
#include <exception>
#endif
// 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>
#ifdef __cpp_lib_expected
#include <expected>
#endif
#include <filesystem>
#if defined(__cpp_lib_format) || (defined(_MSC_VER) && _MSC_VER >= 1929)
#include <format>
#endif
#ifdef __cpp_lib_flat_map
#include <flat_map>
#endif
#ifdef __cpp_lib_flat_set
#include <flat_set>
#endif
#include <forward_list>
#include <fstream>
#include <functional>
#include <future>
#ifdef __cpp_lib_generator
#include <generator>
#endif
#ifdef __cpp_lib_hazard_pointer
#include <hazard_pointer>
#endif
#include <initializer_list>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <iso646.h>
#include <istream>
#include <iterator>
#ifdef __cpp_lib_latch
#include <latch>
#endif
#include <limits>
#ifdef __cpp_lib_linalg
#include <linalg>
#endif
#include <list>
#include <locale>
#include <map>
#ifdef __cpp_lib_mdspan
#include <mdspan>
#endif
#include <memory>
#ifdef __cpp_lib_memory_resource
#include <memory_resource>
#endif
#include <mutex>
#include <new>
#include <numbers>
#include <numeric>
#include <optional>
#include <ostream>
#ifdef __cpp_lib_print
#include <print>
#endif
#include <queue>
#include <random>
#include <ranges>
#include <ratio>
#ifdef __cpp_lib_rcu
#include <rcu>
#endif
#include <regex>
#include <scoped_allocator>
#ifdef __cpp_lib_semaphore
#include <semaphore>
#endif
#include <set>
#include <shared_mutex>
#ifdef __cpp_lib_source_location
#include <source_location>
#endif
#include <span>
#ifdef __cpp_lib_spanstream
#include <spanstream>
#endif
#include <sstream>
#include <stack>
#ifdef __cpp_lib_stacktrace
#include <stacktrace>
#endif
#ifdef __cpp_lib_stdatomic_h
#include <stdatomic.h>
#endif
#include <stdexcept>
#if __has_include(<stdfloat>)
#if !defined(_MSC_VER) || _HAS_CXX23
#include <stdfloat>
#endif
#endif
#ifdef __cpp_lib_jthread
#include <stop_token>
#endif
#include <streambuf>
#include <string>
#include <string_view>
#ifdef __cpp_lib_syncbuf
#include <syncstream>
#endif
#include <system_error>
#ifdef __cpp_lib_text_encoding
#include <text_encoding>
#endif
#include <thread>
#include <tuple>
#include <type_traits>
#include <typeindex>
#ifndef CPP2_NO_RTTI
#include <typeinfo>
#endif
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <valarray>
#include <variant>
#include <vector>
#endif
// Otherwise, just #include the facilities used in this header
#else
#ifdef _MSC_VER
#include "intrin.h"
#endif
#include <algorithm>
#include <any>
#include <compare>
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#ifndef CPP2_NO_EXCEPTIONS
#include <exception>
#endif
#ifdef __cpp_lib_expected
#include <expected>
#endif
#if defined(__cpp_lib_format) || (defined(_MSC_VER) && _MSC_VER >= 1929)
#include <format>
#endif
#include <functional>
#include <iostream>
#include <iterator>
#include <limits>
#include <memory>
#include <new>
#include <random>
#include <optional>
#if defined(CPP2_USE_SOURCE_LOCATION)
#include <source_location>
#endif
#include <span>
#include <string>
#include <string_view>
#include <system_error>
#include <tuple>
#include <type_traits>
#ifndef CPP2_NO_RTTI
#include <typeinfo>
#endif
#include <utility>
#include <variant>
#include <vector>
#endif
//-----------------------------------------------------------------------
//
// Macros
//
//-----------------------------------------------------------------------
//
#define CPP2_TYPEOF(x) std::remove_cvref_t<decltype(x)>
#if __cplusplus >= 202302L && \
( \
(defined(__clang_major__) && __clang_major__ >= 15) \
|| (defined(__GNUC__) && __GNUC__ >= 12) \
)
#define CPP2_COPY(x) auto(x)
#else
#define CPP2_COPY(x) CPP2_TYPEOF(x)(x)
#endif
#define CPP2_FORWARD(x) std::forward<decltype(x)>(x)
#define CPP2_PACK_EMPTY(x) (sizeof...(x) == 0)
#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
#if defined(_MSC_VER)
// MSVC can't handle 'inline constexpr' yet in all cases
#define CPP2_CONSTEXPR const
#else
#define CPP2_CONSTEXPR constexpr
#endif
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 uint = unsigned int;
// long
using ulong = unsigned 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
//
//-----------------------------------------------------------------------
//
template <typename T>
requires (std::is_copy_constructible_v<std::remove_cvref_t<T>>)
auto move(T&& t) -> decltype(auto) {
return std::move(t);
}
template <typename T>
requires (!std::is_copy_constructible_v<std::remove_cvref_t<T>>)
auto move(T&& t) -> decltype(auto) {
return std::forward<T>(t);
}
inline constexpr auto max(auto... values) {
return std::max( { values... } );
}
template <class T, class... Ts>
inline constexpr auto is_any = std::disjunction_v<std::is_same<T, Ts>...>;
template <std::size_t Len, std::size_t Align>
struct aligned_storage {
alignas(Align) unsigned char data[Len];
};
template <typename T>
requires requires { *std::declval<T&>(); }
using deref_t = decltype(*std::declval<T&>());
//-----------------------------------------------------------------------
//
// 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*
#define CPP2_CONTRACT_MSG cpp2::message_to_cstr_adapter
inline auto message_to_cstr_adapter( CPP2_MESSAGE_PARAM msg ) -> CPP2_MESSAGE_PARAM { return msg ? msg : ""; }
inline auto message_to_cstr_adapter( std::string const& msg ) -> CPP2_MESSAGE_PARAM { return msg.c_str(); }
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 = {}) { reporter = h; }
constexpr auto is_active () const -> bool { return reporter != handler{}; }
constexpr auto enforce(bool b, CPP2_MESSAGE_PARAM msg = "" CPP2_SOURCE_LOCATION_PARAM_WITH_DEFAULT)
-> void { if (!b) report_violation(msg CPP2_SOURCE_LOCATION_ARG); }
constexpr auto report_violation(CPP2_MESSAGE_PARAM msg = "" CPP2_SOURCE_LOCATION_PARAM_WITH_DEFAULT)
-> void { if (reporter) 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 && msg[0] != '\0') {
std::cerr << ": " << msg;
}
std::cerr << "\n";
std::terminate();
}
auto inline cpp2_default = contract_group(
[](CPP2_MESSAGE_PARAM msg CPP2_SOURCE_LOCATION_PARAM)noexcept {
report_and_terminate("Contract", msg CPP2_SOURCE_LOCATION_ARG);
}
);
auto inline bounds_safety = contract_group(
[](CPP2_MESSAGE_PARAM msg CPP2_SOURCE_LOCATION_PARAM)noexcept {
report_and_terminate("Bounds safety", msg CPP2_SOURCE_LOCATION_ARG);
}
);
auto inline null_safety = contract_group(
[](CPP2_MESSAGE_PARAM msg CPP2_SOURCE_LOCATION_PARAM)noexcept {
report_and_terminate("Null safety", msg CPP2_SOURCE_LOCATION_ARG);
}
);
auto inline type_safety = 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);
}
);
namespace impl {
//-----------------------------------------------------------------------
//
// Check for invalid dereference or indirection which would result in undefined behavior.
//
// - Null pointer
// - std::unique_ptr that owns nothing
// - std::shared_ptr with no managed object
// - std::optional with no value
// - std::expected containing an unexpected value
//
// Note: For naming simplicity we consider all the above cases to be "null" states so that
// we can write: `*assert_not_null(object)`.
//
template<typename T>
concept UniquePtr = std::is_same_v<T, std::unique_ptr<typename T::element_type, typename T::deleter_type>>;
template<typename T>
concept SharedPtr = std::is_same_v<T, std::shared_ptr<typename T::element_type>>;
template<typename T>
concept Optional = std::is_same_v<T, std::optional<typename T::value_type>>;
#ifdef __cpp_lib_expected
template<typename T>
concept Expected = std::is_same_v<T, std::expected<typename T::value_type, typename T::error_type>>;
#endif
auto assert_not_null(auto&& arg 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(arg)>) {
if (arg == CPP2_TYPEOF(arg){}) {
null_safety.report_violation("dynamic null dereference attempt detected" CPP2_SOURCE_LOCATION_ARG);
};
}
else if constexpr (UniquePtr<CPP2_TYPEOF(arg)>) {
if (!arg) {
null_safety.report_violation("std::unique_ptr is empty" CPP2_SOURCE_LOCATION_ARG);
}
}
else if constexpr (SharedPtr<CPP2_TYPEOF(arg)>) {
if (!arg) {
null_safety.report_violation("std::shared_ptr is empty" CPP2_SOURCE_LOCATION_ARG);
}
}
else if constexpr (Optional<CPP2_TYPEOF(arg)>) {
if (!arg.has_value()) {
null_safety.report_violation("std::optional does not contain a value" CPP2_SOURCE_LOCATION_ARG);
}
}
#ifdef __cpp_lib_expected
else if constexpr (Expected<CPP2_TYPEOF(arg)>) {
if (!arg.has_value()) {
null_safety.report_violation("std::expected has an unexpected value" CPP2_SOURCE_LOCATION_ARG);
}
}
#endif
return CPP2_FORWARD(arg);
}
// Subscript bounds checking
//
#define CPP2_ASSERT_IN_BOUNDS_IMPL \
requires (std::is_integral_v<CPP2_TYPEOF(arg)> && \
requires { std::size(x); std::ssize(x); x[arg]; std::begin(x) + 2; }) \
{ \
auto max = [&]() -> auto { \
if constexpr (std::is_signed_v<CPP2_TYPEOF(arg)>) { return std::ssize(x); } \
else { return std::size(x); } \
}; \
auto msg = "out of bounds access attempt detected - attempted access at index " + std::to_string(arg) + ", "; \
if (max() > 0 ) { \
msg += "[min,max] range is [0," + std::to_string(max()-1) + "]"; \
} \
else { \
msg += "but container is empty"; \
} \
if (!(0 <= arg && arg < max())) { \
bounds_safety.report_violation(msg.c_str() CPP2_SOURCE_LOCATION_ARG); \
} \
return CPP2_FORWARD(x) [ arg ]; \
}
template<auto arg>
auto assert_in_bounds(auto&& x CPP2_SOURCE_LOCATION_PARAM_WITH_DEFAULT) -> decltype(auto)
CPP2_ASSERT_IN_BOUNDS_IMPL
auto assert_in_bounds(auto&& x, auto&& arg CPP2_SOURCE_LOCATION_PARAM_WITH_DEFAULT) -> decltype(auto)
CPP2_ASSERT_IN_BOUNDS_IMPL
template<auto arg>
auto assert_in_bounds(auto&& x CPP2_SOURCE_LOCATION_PARAM_WITH_DEFAULT) -> decltype(auto)
{
return CPP2_FORWARD(x) [ arg ];
}
auto assert_in_bounds(auto&& x, auto&& arg CPP2_SOURCE_LOCATION_PARAM_WITH_DEFAULT) -> decltype(auto)
{
return CPP2_FORWARD(x) [ CPP2_FORWARD(arg) ];
}
#define CPP2_ASSERT_IN_BOUNDS(x,arg) (cpp2::impl::assert_in_bounds((x),(arg)))
#define CPP2_ASSERT_IN_BOUNDS_LITERAL(x,arg) (cpp2::impl::assert_in_bounds<(arg)>(x))
//-----------------------------------------------------------------------
//
// 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
auto err = std::string{"exceptions are disabled with -fno-exceptions - attempted to throw exception with type \"" + typeid(decltype(x)).name() + "\""};
if (msg) {
err += " and the message \"" + msg + "\"";
}
type_safety.report_violation( err );
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_safety.report_violation( "'as' dynamic casting is disabled with -fno-rtti" );
return nullptr;
#else
return dynamic_cast<T>(CPP2_FORWARD(x));
#endif
}
template<typename T>
auto Typeid() -> decltype(auto) {
#ifdef CPP2_NO_RTTI
type_safety.report_violation( "'any' dynamic casting is disabled with -fno-rtti" );
#else
return typeid(T);
#endif
}
auto Typeid( [[maybe_unused]] auto&& x ) -> decltype(auto) {
#ifdef CPP2_NO_RTTI
type_safety.report_violation( "'typeid' is disabled with -fno-rtti" );
#else
return typeid(CPP2_FORWARD(x));
#endif
}
} // impl
//-----------------------------------------------------------------------
//
// 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> {
// Prefer { } to ( ) so that initializing a vector<int> with
// (10), (10, 20), and (10, 20, 30) is consistent
if constexpr (requires { T{CPP2_FORWARD(args)...}; }) {
// This is because apparently make_unique can't deal with list
// initialization of aggregates, even after P0960
return std::unique_ptr<T>( new T{CPP2_FORWARD(args)...} );
}
else {
return std::make_unique<T>(CPP2_FORWARD(args)...);
}
}
} inline unique;
[[maybe_unused]] struct {
template<typename T>
[[nodiscard]] auto cpp2_new(auto&& ...args) const -> std::shared_ptr<T> {
// Prefer { } to ( ) as noted for unique.new
//
// Note this does mean we don't get the make_shared optimization a lot
// of the time -- we can restore that as soon as make_shared improves to
// allow list initialization. But the make_shared optimization isn't a
// huge deal anyway: it saves one allocation, but most of the cost of
// shared_ptrs is copying them and the allocation cost saving is probably
// outweighed by just a couple of shared_ptr copies; also, the make_shared
// optimization has the potential downside of keeping the raw storage
// alive longer when there are weak_ptrs. So, yes, we can and should
// restore the make_shared optimization as soon as make_shared supports
// list init, but I don't think it's all that important AFAIK
if constexpr (requires { T{CPP2_FORWARD(args)...}; }) {
// Why this calls 'unique.new': The workaround to use { } initialization
// requires calling naked 'new' to allocate the object separately anyway,
// so reuse the unique.new path that already does that (less code
// duplication, plus encapsulate the naked 'new' in one place)
return unique.cpp2_new<T>(CPP2_FORWARD(args)...);
}
else {
return std::make_shared<T>(CPP2_FORWARD(args)...);
}
}
} inline shared;
template<typename T>
[[nodiscard]] auto cpp2_new(auto&& ...args) -> std::unique_ptr<T> {
return unique.cpp2_new<T>(CPP2_FORWARD(args)...);
}
namespace impl {
//-----------------------------------------------------------------------
//
// 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)];
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& { cpp2_default.enforce(init); return t(); }
auto construct(auto&& ...args) -> void { cpp2_default.enforce(!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} { cpp2_default.enforce( t); }
out(deferred_init<T>* dt_) noexcept : dt{dt_}, has_t{false} { cpp2_default.enforce(dt); }
out(out<T>* ot_) noexcept : ot{ot_}, has_t{ot_->has_t} { cpp2_default.enforce(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()) {
cpp2_default.enforce(!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)...); }) {
cpp2_default.enforce( t );
*t = T(CPP2_FORWARD(args)...);
}
else {
cpp2_default.report_violation("attempted to copy assign, but copy assignment is not available");
}
}
else {
cpp2_default.enforce( dt );
if (dt->init) {
if constexpr (requires { *t = T(CPP2_FORWARD(args)...); }) {
dt->value() = T(CPP2_FORWARD(args)...);
}
else {
cpp2_default.report_violation("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) {
cpp2_default.enforce( t );
return *t;
}
else {
cpp2_default.enforce( dt );
return dt->value();
}
}
};
//-----------------------------------------------------------------------
//
// CPP2_UFCS: Variadic macro generating a variadic lamba, oh my...
//
//-----------------------------------------------------------------------
//
// Workaround <https://github.com/llvm/llvm-project/issues/70556>.
#define CPP2_FORCE_INLINE_LAMBDA_CLANG /* empty */
#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))
#if defined(__clang__)
#define CPP2_FORCE_INLINE_LAMBDA /* empty */
#undef CPP2_FORCE_INLINE_LAMBDA_CLANG
#define CPP2_FORCE_INLINE_LAMBDA_CLANG __attribute__((always_inline))
#else
#define CPP2_FORCE_INLINE_LAMBDA __attribute__((always_inline))
#endif
#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
#define CPP2_UFCS_EMPTY(...)
#define CPP2_UFCS_IDENTITY(...) __VA_ARGS__
#define CPP2_UFCS_REMPARENS(...) __VA_ARGS__
// Ideally, the expression `CPP2_UFCS_IS_NOTHROW` expands to
// is in the _noexcept-specifier_ of the UFCS lambda, but without 'std::declval'.
// To workaround [GCC bug 101043](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=101043),
// we instead make it a template parameter of the UFCS lambda.
// But using a template parameter, Clang also ICEs on an application.
// So we use these `NOTHROW` macros to fall back to the ideal for when not using GCC.
#define CPP2_UFCS_IS_NOTHROW(MVFWD,QUALID,TEMPKW,...) \
requires { requires requires { std::declval<Obj>().CPP2_UFCS_REMPARENS QUALID TEMPKW __VA_ARGS__(std::declval<Params>()...); }; \
requires noexcept(std::declval<Obj>().CPP2_UFCS_REMPARENS QUALID TEMPKW __VA_ARGS__(std::declval<Params>()...)); } \
|| requires { requires !requires { std::declval<Obj>().CPP2_UFCS_REMPARENS QUALID TEMPKW __VA_ARGS__(std::declval<Params>()...); }; \
requires noexcept(MVFWD(CPP2_UFCS_REMPARENS QUALID __VA_ARGS__)(std::declval<Obj>(), std::declval<Params>()...)); }
#define CPP2_UFCS_IS_NOTHROW_PARAM(...) /*empty*/
#define CPP2_UFCS_IS_NOTHROW_ARG(MVFWD,QUALID,TEMPKW,...) CPP2_UFCS_IS_NOTHROW(MVFWD,QUALID,TEMPKW,__VA_ARGS__)
#if defined(__GNUC__) && !defined(__clang__)
#undef CPP2_UFCS_IS_NOTHROW_PARAM
#undef CPP2_UFCS_IS_NOTHROW_ARG
#define CPP2_UFCS_IS_NOTHROW_PARAM(MVFWD,QUALID,TEMPKW,...) , bool IsNothrow = CPP2_UFCS_IS_NOTHROW(MVFWD,QUALID,TEMPKW,__VA_ARGS__)
#define CPP2_UFCS_IS_NOTHROW_ARG(...) IsNothrow
#if __GNUC__ < 11
#undef CPP2_UFCS_IS_NOTHROW_PARAM
#undef CPP2_UFCS_IS_NOTHROW_ARG
#define CPP2_UFCS_IS_NOTHROW_PARAM(...) /*empty*/
#define CPP2_UFCS_IS_NOTHROW_ARG(...) false // GCC 10 UFCS is always potentially-throwing.
#endif
#endif
// Ideally, the expression `CPP2_UFCS_CONSTRAINT_ARG` expands to
// is in the _requires-clause_ of the UFCS lambda.
// To workaround an MSVC bug within a member function 'F' where UFCS is also for 'F'
// (<https://github.com/hsutter/cppfront/pull/506#issuecomment-1826086952>),
// we instead make it a template parameter of the UFCS lambda.
// But using a template parameter, Clang also ICEs and GCC rejects a local 'F'.
// Also, Clang rejects the SFINAE test case when using 'std::declval'.
// So we use these `CONSTRAINT` macros to fall back to the ideal for when not using MSVC.
#define CPP2_UFCS_CONSTRAINT_PARAM(...) /*empty*/
#define CPP2_UFCS_CONSTRAINT_ARG(MVFWD,QUALID,TEMPKW,...) \
requires { CPP2_FORWARD(obj).CPP2_UFCS_REMPARENS QUALID TEMPKW __VA_ARGS__(CPP2_FORWARD(params)...); } \
|| requires { MVFWD(CPP2_UFCS_REMPARENS QUALID __VA_ARGS__)(CPP2_FORWARD(obj), CPP2_FORWARD(params)...); }
#if defined(_MSC_VER)
#undef CPP2_UFCS_CONSTRAINT_PARAM
#undef CPP2_UFCS_CONSTRAINT_ARG
#define CPP2_UFCS_CONSTRAINT_PARAM(MVFWD,QUALID,TEMPKW,...) , bool IsViable = \
requires { std::declval<Obj>().CPP2_UFCS_REMPARENS QUALID TEMPKW __VA_ARGS__(std::declval<Params>()...); } \
|| requires { MVFWD(CPP2_UFCS_REMPARENS QUALID __VA_ARGS__)(std::declval<Obj>(), std::declval<Params>()...); }
#define CPP2_UFCS_CONSTRAINT_ARG(...) IsViable
#endif
template <class T> struct dependent_false : std::false_type {};
#define CPP2_UFCS_(LAMBDADEFCAPT,SFINAE,MVFWD,QUALID,TEMPKW,...) \
[LAMBDADEFCAPT]< \
typename Obj, typename... Params \
CPP2_UFCS_IS_NOTHROW_PARAM(MVFWD,QUALID,TEMPKW,__VA_ARGS__) \
CPP2_UFCS_CONSTRAINT_PARAM(MVFWD,QUALID,TEMPKW,__VA_ARGS__) \
> \
CPP2_LAMBDA_NO_DISCARD (Obj&& obj, Params&& ...params) CPP2_FORCE_INLINE_LAMBDA_CLANG \
noexcept(CPP2_UFCS_IS_NOTHROW_ARG(MVFWD,QUALID,TEMPKW,__VA_ARGS__)) CPP2_FORCE_INLINE_LAMBDA -> decltype(auto) \
SFINAE( requires CPP2_UFCS_CONSTRAINT_ARG(MVFWD,QUALID,TEMPKW,__VA_ARGS__) ) \
{ \
if constexpr (requires{ CPP2_FORWARD(obj).CPP2_UFCS_REMPARENS QUALID TEMPKW __VA_ARGS__(CPP2_FORWARD(params)...); }) { \
return CPP2_FORWARD(obj).CPP2_UFCS_REMPARENS QUALID TEMPKW __VA_ARGS__(CPP2_FORWARD(params)...); \
} \
else if constexpr (requires{ MVFWD(CPP2_UFCS_REMPARENS QUALID __VA_ARGS__)(CPP2_FORWARD(obj), CPP2_FORWARD(params)...); }) { \
return MVFWD(CPP2_UFCS_REMPARENS QUALID __VA_ARGS__)(CPP2_FORWARD(obj), CPP2_FORWARD(params)...); \
} \
else if constexpr (requires{ obj.CPP2_UFCS_REMPARENS QUALID TEMPKW __VA_ARGS__(CPP2_FORWARD(params)...); }) { \
static_assert( cpp2::impl::dependent_false<Obj>::value, "error: implicit discard of an object's modified value is not allowed - this function call modifies 'obj', but 'obj' is never used again in the function so the new value is never used - if that's what you intended, add another line '_ = obj;' afterward to explicitly discard the new value of the object" ); \
CPP2_FORWARD(obj).CPP2_UFCS_REMPARENS QUALID TEMPKW __VA_ARGS__(CPP2_FORWARD(params)...); \
MVFWD(CPP2_UFCS_REMPARENS QUALID __VA_ARGS__)(CPP2_FORWARD(obj), CPP2_FORWARD(params)...); \
} \
else if constexpr (requires{ MVFWD(CPP2_UFCS_REMPARENS QUALID __VA_ARGS__)(obj, CPP2_FORWARD(params)...); }) { \
static_assert( cpp2::impl::dependent_false<Obj>::value, "error: implicit discard of an object's modified value is not allowed - this function call modifies 'obj', but 'obj' is never used again in the function so the new value is never used - if that's what you intended, add another line '_ = obj;' afterward to explicitly discard the new value of the object" ); \
CPP2_FORWARD(obj).CPP2_UFCS_REMPARENS QUALID TEMPKW __VA_ARGS__(CPP2_FORWARD(params)...); \
MVFWD(CPP2_UFCS_REMPARENS QUALID __VA_ARGS__)(CPP2_FORWARD(obj), CPP2_FORWARD(params)...); \
} \
else { \
static_assert( cpp2::impl::dependent_false<Obj>::value, "this function call syntax tries 'obj.func(...)', then 'func(obj,...);', but both failed - if this function call is passing a local variable that will be modified by the function, but that variable is never used again in the function so the new value is never used, that's likely the problem - if that's what you intended, add another line '_ = obj;' afterward to explicitly discard the new value of the object" ); \
CPP2_FORWARD(obj).CPP2_UFCS_REMPARENS QUALID TEMPKW __VA_ARGS__(CPP2_FORWARD(params)...); \
MVFWD(CPP2_UFCS_REMPARENS QUALID __VA_ARGS__)(CPP2_FORWARD(obj), CPP2_FORWARD(params)...); \
} \
}
#define CPP2_UFCS(...) CPP2_UFCS_(&,CPP2_UFCS_EMPTY,CPP2_UFCS_IDENTITY,(),,__VA_ARGS__)
#define CPP2_UFCS_MOVE(...) CPP2_UFCS_(&,CPP2_UFCS_EMPTY,std::move,(),,__VA_ARGS__)
#define CPP2_UFCS_FORWARD(...) CPP2_UFCS_(&,CPP2_UFCS_EMPTY,CPP2_FORWARD,(),,__VA_ARGS__)
#define CPP2_UFCS_TEMPLATE(...) CPP2_UFCS_(&,CPP2_UFCS_EMPTY,CPP2_UFCS_IDENTITY,(),template,__VA_ARGS__)
#define CPP2_UFCS_QUALIFIED_TEMPLATE(QUALID,...) CPP2_UFCS_(&,CPP2_UFCS_EMPTY,CPP2_UFCS_IDENTITY,QUALID,template,__VA_ARGS__)
#define CPP2_UFCS_NONLOCAL(...) CPP2_UFCS_(,CPP2_UFCS_IDENTITY,CPP2_UFCS_IDENTITY,(),,__VA_ARGS__)
#define CPP2_UFCS_TEMPLATE_NONLOCAL(...) CPP2_UFCS_(,CPP2_UFCS_IDENTITY,CPP2_UFCS_IDENTITY,(),template,__VA_ARGS__)
#define CPP2_UFCS_QUALIFIED_TEMPLATE_NONLOCAL(QUALID,...) CPP2_UFCS_(,CPP2_UFCS_IDENTITY,CPP2_UFCS_IDENTITY,QUALID,template,__VA_ARGS__)
} // impl