forked from jeremy-rifkin/libassert
-
Notifications
You must be signed in to change notification settings - Fork 0
/
assert.hpp
1324 lines (1205 loc) · 57.5 KB
/
assert.hpp
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
#ifndef LIBASSERT_HPP
#define LIBASSERT_HPP
// Copyright (c) 2021-2022 Jeremy Rifkin under the MIT license
// https://github.com/jeremy-rifkin/libassert
#include <cstdio>
#include <cstring>
#include <sstream>
#include <string_view>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
#include <system_error>
#ifdef __cpp_lib_expected
#include <expected>
#endif
#if defined(_MSVC_LANG) && _MSVC_LANG < 201703L
#error "libassert requires C++17 or newer"
#elif !defined(_MSVC_LANG) && __cplusplus < 201703L
#pragma error "libassert requires C++17 or newer"
#endif
#if __cplusplus >= 202002L || _MSVC_LANG >= 202002L
#include <compare>
#endif
#ifdef ASSERT_USE_MAGIC_ENUM
// this is a temporary hack to make testing thing in compiler explorer quicker (it disallows simple relative includes)
#include \
"../third_party/magic_enum.hpp"
#endif
#if defined(__clang__)
#define LIBASSERT_IS_CLANG 1
#elif defined(__GNUC__) || defined(__GNUG__)
#define LIBASSERT_IS_GCC 1
#elif defined(_MSC_VER)
#define LIBASSERT_IS_MSVC 1
#include <iso646.h> // alternative operator tokens are standard but msvc requires the include or /permissive- or /Za
#else
#error "Unsupported compiler"
#endif
#if LIBASSERT_IS_CLANG || LIBASSERT_IS_GCC
#define LIBASSERT_PFUNC __extension__ __PRETTY_FUNCTION__
#define LIBASSERT_ATTR_COLD [[gnu::cold]]
#define LIBASSERT_ATTR_NOINLINE [[gnu::noinline]]
#define LIBASSERT_UNREACHABLE __builtin_unreachable()
#else
#define LIBASSERT_PFUNC __FUNCSIG__
#define LIBASSERT_ATTR_COLD
#define LIBASSERT_ATTR_NOINLINE __declspec(noinline)
#define LIBASSERT_UNREACHABLE __assume(false)
#endif
#if LIBASSERT_IS_MSVC
#define LIBASSERT_STRONG_EXPECT(expr, value) (expr)
#elif defined(__clang__) && __clang_major__ >= 11 || __GNUC__ >= 9
#define LIBASSERT_STRONG_EXPECT(expr, value) __builtin_expect_with_probability((expr), (value), 1)
#else
#define LIBASSERT_STRONG_EXPECT(expr, value) __builtin_expect((expr), (value))
#endif
namespace libassert {
enum class ASSERTION {
NONFATAL, FATAL
};
enum class assert_type {
debug_assertion,
assertion,
assumption,
verification
};
class assertion_printer;
}
#ifndef ASSERT_FAIL
#define ASSERT_FAIL libassert_default_fail_action
#endif
void ASSERT_FAIL(libassert::assert_type type, libassert::ASSERTION fatal, const libassert::assertion_printer& printer);
// always_false is just convenient to use here
#define LIBASSERT_PHONY_USE(E) ((void)libassert::detail::always_false<decltype(E)>)
/*
* Internal mechanisms
*
* Macros exposed: LIBASSERT_PRIMITIVE_ASSERT
*/
namespace libassert::detail {
// Lightweight helper, eventually may use C++20 std::source_location if this library no longer
// targets C++17. Note: __builtin_FUNCTION only returns the name, so __PRETTY_FUNCTION__ is
// still needed.
struct source_location {
const char* const file;
//const char* const function; // disabled for now due to static constexpr restrictions
const int line;
constexpr source_location(
//const char* _function /*= __builtin_FUNCTION()*/,
const char* _file = __builtin_FILE(),
int _line = __builtin_LINE()
) : file(_file), /*function(_function),*/ line(_line) {}
};
// bootstrap with primitive implementations
void primitive_assert_impl(
bool condition,
bool verify,
const char* expression,
const char* signature,
source_location location,
const char* message = nullptr
);
#ifndef NDEBUG
#define LIBASSERT_PRIMITIVE_ASSERT(c, ...) \
libassert::detail::primitive_assert_impl(c, false, #c, LIBASSERT_PFUNC, {}, ##__VA_ARGS__)
#else
#define LIBASSERT_PRIMITIVE_ASSERT(c, ...) LIBASSERT_PHONY_USE(c)
#endif
/*
* String utilities
*/
[[nodiscard]] std::string bstringf(const char* format, ...);
/*
* System wrappers
*/
[[nodiscard]] std::string strerror_wrapper(int err); // stupid C stuff, stupid microsoft stuff
/*
* Stacktrace implementation
*/
// All in the .cpp
void* get_stacktrace_opaque();
/*
* metaprogramming utilities
*/
struct nothing {};
template<typename T> inline constexpr bool is_nothing = std::is_same_v<T, nothing>;
// Hack to get around static_assert(false); being evaluated before any instantiation, even under
// an if-constexpr branch
// Also used for PHONY_USE
template<typename T> inline constexpr bool always_false = false;
template<typename T> using strip = std::remove_cv_t<std::remove_reference_t<T>>;
// intentionally not stripping B
template<typename A, typename B> inline constexpr bool isa = std::is_same_v<strip<A>, B>;
// Is integral but not boolean
template<typename T> inline constexpr bool is_integral_and_not_bool = std::is_integral_v<strip<T>> && !isa<T, bool>;
template<typename T> inline constexpr bool is_arith_not_bool_char =
std::is_arithmetic_v<strip<T>> && !isa<T, bool> && !isa<T, char>;
template<typename T> inline constexpr bool is_c_string =
isa<std::decay_t<strip<T>>, char*> // <- covers literals (i.e. const char(&)[N]) too
|| isa<std::decay_t<strip<T>>, const char*>;
template<typename T> inline constexpr bool is_string_type =
isa<T, std::string>
|| isa<T, std::string_view>
|| is_c_string<T>;
template<typename T> typename std::add_lvalue_reference<T>::type decllval() noexcept;
/*
* expression decomposition
*/
// Lots of boilerplate
// Using int comparison functions here to support proper signed comparisons. Need to make sure
// assert(map.count(1) == 2) doesn't produce a warning. It wouldn't under normal circumstances
// but it would in this library due to the parameters being forwarded down a long chain.
// And we want to provide as much robustness as possible anyways.
// Copied and pasted from https://en.cppreference.com/w/cpp/utility/intcmp
// Not using std:: versions because library is targetting C++17
template<typename T, typename U>
[[nodiscard]] constexpr bool cmp_equal(T t, U u) {
using UT = std::make_unsigned_t<T>;
using UU = std::make_unsigned_t<U>;
if constexpr(std::is_signed_v<T> == std::is_signed_v<U>) {
return t == u;
} else if constexpr(std::is_signed_v<T>) {
return t >= 0 && UT(t) == u;
} else {
return u >= 0 && t == UU(u);
}
}
template<typename T, typename U>
[[nodiscard]] constexpr bool cmp_not_equal(T t, U u) {
return !cmp_equal(t, u);
}
template<typename T, typename U>
[[nodiscard]] constexpr bool cmp_less(T t, U u) {
using UT = std::make_unsigned_t<T>;
using UU = std::make_unsigned_t<U>;
if constexpr(std::is_signed_v<T> == std::is_signed_v<U>) {
return t < u;
} else if constexpr(std::is_signed_v<T>) {
return t < 0 || UT(t) < u;
} else {
return u >= 0 && t < UU(u);
}
}
template<typename T, typename U>
[[nodiscard]] constexpr bool cmp_greater(T t, U u) {
return cmp_less(u, t);
}
template<typename T, typename U>
[[nodiscard]] constexpr bool cmp_less_equal(T t, U u) {
return !cmp_less(u, t);
}
template<typename T, typename U>
[[nodiscard]] constexpr bool cmp_greater_equal(T t, U u) {
return !cmp_less(t, u);
}
// Lots of boilerplate
// std:: implementations don't allow two separate types for lhs/rhs
// Note: is this macro potentially bad when it comes to debugging(?)
namespace ops {
#define LIBASSERT_GEN_OP_BOILERPLATE(name, op) struct name { \
static constexpr std::string_view op_string = #op; \
template<typename A, typename B> \
LIBASSERT_ATTR_COLD [[nodiscard]] \
constexpr decltype(auto) operator()(A&& lhs, B&& rhs) const { /* no need to forward ints */ \
return std::forward<A>(lhs) op std::forward<B>(rhs); \
} \
}
#define LIBASSERT_GEN_OP_BOILERPLATE_SPECIAL(name, op, cmp) struct name { \
static constexpr std::string_view op_string = #op; \
template<typename A, typename B> \
LIBASSERT_ATTR_COLD [[nodiscard]] \
constexpr decltype(auto) operator()(A&& lhs, B&& rhs) const { /* no need to forward ints */ \
if constexpr(is_integral_and_not_bool<A> && is_integral_and_not_bool<B>) return cmp(lhs, rhs); \
else return std::forward<A>(lhs) op std::forward<B>(rhs); \
} \
}
LIBASSERT_GEN_OP_BOILERPLATE(shl, <<);
LIBASSERT_GEN_OP_BOILERPLATE(shr, >>);
#if __cplusplus >= 202002L
LIBASSERT_GEN_OP_BOILERPLATE(spaceship, <=>);
#endif
LIBASSERT_GEN_OP_BOILERPLATE_SPECIAL(eq, ==, cmp_equal);
LIBASSERT_GEN_OP_BOILERPLATE_SPECIAL(neq, !=, cmp_not_equal);
LIBASSERT_GEN_OP_BOILERPLATE_SPECIAL(gt, >, cmp_greater);
LIBASSERT_GEN_OP_BOILERPLATE_SPECIAL(lt, <, cmp_less);
LIBASSERT_GEN_OP_BOILERPLATE_SPECIAL(gteq, >=, cmp_greater_equal);
LIBASSERT_GEN_OP_BOILERPLATE_SPECIAL(lteq, <=, cmp_less_equal);
LIBASSERT_GEN_OP_BOILERPLATE(band, &);
LIBASSERT_GEN_OP_BOILERPLATE(bxor, ^);
LIBASSERT_GEN_OP_BOILERPLATE(bor, |);
#ifdef ASSERT_DECOMPOSE_BINARY_LOGICAL
LIBASSERT_GEN_OP_BOILERPLATE(land, &&);
LIBASSERT_GEN_OP_BOILERPLATE(lor, ||);
#endif
LIBASSERT_GEN_OP_BOILERPLATE(assign, =);
LIBASSERT_GEN_OP_BOILERPLATE(add_assign, +=);
LIBASSERT_GEN_OP_BOILERPLATE(sub_assign, -=);
LIBASSERT_GEN_OP_BOILERPLATE(mul_assign, *=);
LIBASSERT_GEN_OP_BOILERPLATE(div_assign, /=);
LIBASSERT_GEN_OP_BOILERPLATE(mod_assign, %=);
LIBASSERT_GEN_OP_BOILERPLATE(shl_assign, <<=);
LIBASSERT_GEN_OP_BOILERPLATE(shr_assign, >>=);
LIBASSERT_GEN_OP_BOILERPLATE(band_assign, &=);
LIBASSERT_GEN_OP_BOILERPLATE(bxor_assign, ^=);
LIBASSERT_GEN_OP_BOILERPLATE(bor_assign, |=);
#undef LIBASSERT_GEN_OP_BOILERPLATE
#undef LIBASSERT_GEN_OP_BOILERPLATE_SPECIAL
}
// I learned this automatic expression decomposition trick from lest:
// https://github.com/martinmoene/lest/blob/master/include/lest/lest.hpp#L829-L853
//
// I have improved upon the trick by supporting more operators and generally improving
// functionality.
//
// Some cases to test and consider:
//
// Expression Parsed as
// Basic:
// false << false
// a == b (<< a) == b
//
// Equal precedence following:
// a << b (<< a) << b
// a << b << c ((<< a) << b) << c
// a << b + c (<< a) << (b + c)
// a << b < c ((<< a) << b) < c // edge case
//
// Higher precedence following:
// a + b << (a + b)
// a + b + c << ((a + b) + c)
// a + b * c << (a + (b * c))
// a + b < c (<< (a + b)) < c
//
// Lower precedence following:
// a < b (<< a) < b
// a < b < c ((<< a) < b) < c
// a < b + c (<< a) < (b + c)
// a < b == c ((<< a) < b) == c // edge case
template<typename A = nothing, typename B = nothing, typename C = nothing>
struct expression_decomposer {
A a;
B b;
explicit constexpr expression_decomposer() = default;
compl expression_decomposer() = default;
// not copyable
constexpr expression_decomposer(const expression_decomposer&) = delete;
constexpr expression_decomposer& operator=(const expression_decomposer&) = delete;
// allow move construction
constexpr expression_decomposer(expression_decomposer&&)
#if !LIBASSERT_IS_GCC || __GNUC__ >= 10 // gcc 9 has some issue with the move constructor being noexcept
noexcept
#endif
= default;
constexpr expression_decomposer& operator=(expression_decomposer&&) = delete;
// value constructors
template<typename U>
// NOLINTNEXTLINE(bugprone-forwarding-reference-overload) // TODO
explicit constexpr expression_decomposer(U&& _a) : a(std::forward<U>(_a)) {}
template<typename U, typename V>
explicit constexpr expression_decomposer(U&& _a, V&& _b) : a(std::forward<U>(_a)), b(std::forward<V>(_b)) {}
/* Ownership logic:
* One of two things can happen to this class
* - Either it is composed with another operation
* + The value of the subexpression represented by this is computed (either get_value()
* or operator bool), either A& or C()(a, b)
* + Or, just the lhs is moved B is nothing
* - Or this class represents the whole expression
* + The value is computed (either A& or C()(a, b))
* + a and b are referenced freely
* + Either the value is taken or a is moved out
* Ensuring the value is only computed once is left to the assert handler
*/
[[nodiscard]]
constexpr decltype(auto) get_value() {
if constexpr(is_nothing<C>) {
static_assert(is_nothing<B> && !is_nothing<A>);
return (((((((((((((((((((a)))))))))))))))))));
} else {
return C()(a, b);
}
}
[[nodiscard]]
constexpr operator bool() { // for ternary support
return (bool)get_value();
}
// return true if the lhs should be returned, false if full computed value should be
[[nodiscard]]
constexpr bool ret_lhs() {
static_assert(!is_nothing<A>);
static_assert(is_nothing<B> == is_nothing<C>);
if constexpr(is_nothing<C>) {
// if there is no top-level binary operation, A is the only thing that can be returned
return true;
} else {
// return LHS for the following types;
return C::op_string == "=="
|| C::op_string == "!="
|| C::op_string == "<"
|| C::op_string == ">"
|| C::op_string == "<="
|| C::op_string == ">="
|| C::op_string == "&&"
|| C::op_string == "||";
// don't return LHS for << >> & ^ | and all assignments
}
}
[[nodiscard]]
constexpr A take_lhs() { // should only be called if ret_lhs() == true
if constexpr(std::is_lvalue_reference<A>::value) {
return ((((a))));
} else {
return std::move(a);
}
}
// Need overloads for operators with precedence <= bitshift
// TODO: spaceship operator?
// Note: Could decompose more than just comparison and boolean operators, but it would take
// a lot of work and I don't think it's beneficial for this library.
template<typename O> [[nodiscard]] constexpr auto operator<<(O&& operand) && {
using Q = std::conditional_t<std::is_rvalue_reference_v<O>, std::remove_reference_t<O>, O>;
if constexpr(is_nothing<A>) {
static_assert(is_nothing<B> && is_nothing<C>);
return expression_decomposer<Q, nothing, nothing>(std::forward<O>(operand));
} else if constexpr(is_nothing<B>) {
static_assert(is_nothing<C>);
return expression_decomposer<A, Q, ops::shl>(std::forward<A>(a), std::forward<O>(operand));
} else {
static_assert(!is_nothing<C>);
return expression_decomposer<decltype(get_value()), O, ops::shl>(
std::forward<A>(get_value()),
std::forward<O>(operand)
);
}
}
#define LIBASSERT_GEN_OP_BOILERPLATE(functor, op) \
template<typename O> [[nodiscard]] constexpr auto operator op(O&& operand) && { \
static_assert(!is_nothing<A>); \
using Q = std::conditional_t<std::is_rvalue_reference_v<O>, std::remove_reference_t<O>, O>; \
if constexpr(is_nothing<B>) { \
static_assert(is_nothing<C>); \
return expression_decomposer<A, Q, functor>(std::forward<A>(a), std::forward<O>(operand)); \
} else { \
static_assert(!is_nothing<C>); \
using V = decltype(get_value()); \
return expression_decomposer<V, Q, functor>(std::forward<V>(get_value()), std::forward<O>(operand)); \
} \
}
LIBASSERT_GEN_OP_BOILERPLATE(ops::shr, >>)
#if __cplusplus >= 202002L
LIBASSERT_GEN_OP_BOILERPLATE(ops::spaceship, <=>)
#endif
LIBASSERT_GEN_OP_BOILERPLATE(ops::eq, ==)
LIBASSERT_GEN_OP_BOILERPLATE(ops::neq, !=)
LIBASSERT_GEN_OP_BOILERPLATE(ops::gt, >)
LIBASSERT_GEN_OP_BOILERPLATE(ops::lt, <)
LIBASSERT_GEN_OP_BOILERPLATE(ops::gteq, >=)
LIBASSERT_GEN_OP_BOILERPLATE(ops::lteq, <=)
LIBASSERT_GEN_OP_BOILERPLATE(ops::band, &)
LIBASSERT_GEN_OP_BOILERPLATE(ops::bxor, ^)
LIBASSERT_GEN_OP_BOILERPLATE(ops::bor, |)
#ifdef ASSERT_DECOMPOSE_BINARY_LOGICAL
LIBASSERT_GEN_OP_BOILERPLATE(ops::land, &&)
LIBASSERT_GEN_OP_BOILERPLATE(ops::lor, ||)
#endif
LIBASSERT_GEN_OP_BOILERPLATE(ops::assign, =) // NOLINT(cppcoreguidelines-c-copy-assignment-signature, misc-unconventional-assign-operator)
LIBASSERT_GEN_OP_BOILERPLATE(ops::add_assign, +=)
LIBASSERT_GEN_OP_BOILERPLATE(ops::sub_assign, -=)
LIBASSERT_GEN_OP_BOILERPLATE(ops::mul_assign, *=)
LIBASSERT_GEN_OP_BOILERPLATE(ops::div_assign, /=)
LIBASSERT_GEN_OP_BOILERPLATE(ops::mod_assign, %=)
LIBASSERT_GEN_OP_BOILERPLATE(ops::shl_assign, <<=)
LIBASSERT_GEN_OP_BOILERPLATE(ops::shr_assign, >>=)
LIBASSERT_GEN_OP_BOILERPLATE(ops::band_assign, &=)
LIBASSERT_GEN_OP_BOILERPLATE(ops::bxor_assign, ^=)
LIBASSERT_GEN_OP_BOILERPLATE(ops::bor_assign, |=)
#undef LIBASSERT_GEN_OP_BOILERPLATE
};
// for ternary support
template<typename U> expression_decomposer(U&&)
-> expression_decomposer<std::conditional_t<std::is_rvalue_reference_v<U>, std::remove_reference_t<U>, U>>;
/*
* C++ syntax analysis logic
*/
enum class literal_format {
character,
dec,
hex,
octal,
binary,
none // needs to be at the end for sorting reasons
};
[[nodiscard]] std::string prettify_type(std::string type);
[[nodiscard]] literal_format get_literal_format(const std::string& expression);
[[nodiscard]] bool is_bitwise(std::string_view op);
[[nodiscard]] std::pair<std::string, std::string> decompose_expression(
const std::string& expression,
std::string_view target_op
);
/*
* stringification
*/
LIBASSERT_ATTR_COLD [[nodiscard]]
constexpr std::string_view substring_bounded_by(
std::string_view sig,
std::string_view l,
std::string_view r
) noexcept {
auto i = sig.find(l) + l.length();
return sig.substr(i, sig.rfind(r) - i);
}
template<typename T>
LIBASSERT_ATTR_COLD [[nodiscard]]
constexpr std::string_view type_name() noexcept {
// Cases to handle:
// gcc: constexpr std::string_view ns::type_name() [with T = int; std::string_view = std::basic_string_view<char>]
// clang: std::string_view ns::type_name() [T = int]
// msvc: class std::basic_string_view<char,struct std::char_traits<char> > __cdecl ns::type_name<int>(void)
#if LIBASSERT_IS_CLANG
return substring_bounded_by(LIBASSERT_PFUNC, "[T = ", "]");
#elif LIBASSERT_IS_GCC
return substring_bounded_by(LIBASSERT_PFUNC, "[with T = ", "; std::string_view = ");
#elif LIBASSERT_IS_MSVC
return substring_bounded_by(LIBASSERT_PFUNC, "type_name<", ">(void)");
#else
static_assert(false, "unsupported compiler");
#endif
}
namespace stringification {
[[nodiscard]] std::string stringify(const std::string&, literal_format = literal_format::none);
[[nodiscard]] std::string stringify(const std::string_view&, literal_format = literal_format::none);
// without nullptr_t overload msvc (without /permissive-) will call stringify(bool) and mingw
[[nodiscard]] std::string stringify(std::nullptr_t, literal_format = literal_format::none);
[[nodiscard]] std::string stringify(char, literal_format = literal_format::none);
[[nodiscard]] std::string stringify(bool, literal_format = literal_format::none);
[[nodiscard]] std::string stringify(short, literal_format = literal_format::none);
[[nodiscard]] std::string stringify(int, literal_format = literal_format::none);
[[nodiscard]] std::string stringify(long, literal_format = literal_format::none);
[[nodiscard]] std::string stringify(long long, literal_format = literal_format::none);
[[nodiscard]] std::string stringify(unsigned short, literal_format = literal_format::none);
[[nodiscard]] std::string stringify(unsigned int, literal_format = literal_format::none);
[[nodiscard]] std::string stringify(unsigned long, literal_format = literal_format::none);
[[nodiscard]] std::string stringify(unsigned long long, literal_format = literal_format::none);
[[nodiscard]] std::string stringify(float, literal_format = literal_format::none);
[[nodiscard]] std::string stringify(double, literal_format = literal_format::none);
[[nodiscard]] std::string stringify(long double, literal_format = literal_format::none);
[[nodiscard]] std::string stringify(std::error_code ec, literal_format = literal_format::none);
[[nodiscard]] std::string stringify(std::error_condition ec, literal_format = literal_format::none);
#if __cplusplus >= 202002L
[[nodiscard]] std::string stringify(std::strong_ordering, literal_format = literal_format::none);
[[nodiscard]] std::string stringify(std::weak_ordering, literal_format = literal_format::none);
[[nodiscard]] std::string stringify(std::partial_ordering, literal_format = literal_format::none);
#endif
#ifdef __cpp_lib_expected
template<typename E>
[[nodiscard]] std::string stringify(const std::unexpected<E>& x, literal_format fmt = literal_format::none) {
return "unexpected " + stringify(x.error(), fmt == literal_format::none ? literal_format::dec : fmt);
}
template<typename T, typename E>
[[nodiscard]] std::string stringify(const std::expected<T, E>& x, literal_format fmt = literal_format::none) {
if(x.has_value()) {
if constexpr(std::is_void_v<T>) {
return "expected void";
} else {
return "expected " + stringify(*x, fmt == literal_format::none ? literal_format::dec : fmt);
}
} else {
return "unexpected " + stringify(x.error(), fmt == literal_format::none ? literal_format::dec : fmt);
}
}
#endif
[[nodiscard]] std::string stringify_ptr(const void*, literal_format = literal_format::none);
template<typename T, typename = void> class can_basic_stringify : public std::false_type {};
template<typename T> class can_basic_stringify<
T,
std::void_t<decltype(stringify(std::declval<T>()))>
> : public std::true_type {};
template<typename T, typename = void> class has_stream_overload : public std::false_type {};
template<typename T> class has_stream_overload<
T,
std::void_t<decltype(std::declval<std::ostringstream>() << std::declval<T>())>
> : public std::true_type {};
template<typename T, typename = void> class is_tuple_like : public std::false_type {};
template<typename T> class is_tuple_like<
T,
std::void_t<
typename std::tuple_size<T>::type,
decltype(std::get<0>(std::declval<T>()))
>
> : public std::true_type {};
namespace adl {
using std::size, std::begin, std::end; // ADL
template<typename T, typename = void> class is_printable_container : public std::false_type {};
template<typename T> class is_printable_container<
T,
std::void_t<
decltype(size(decllval<T>())),
decltype(begin(decllval<T>())),
decltype(end(decllval<T>())),
typename std::enable_if< // can stringify (and not just "instance of")
has_stream_overload<decltype(*begin(decllval<T>()))>::value
|| std::is_enum<strip<decltype(*begin(decllval<T>()))>>::value
|| is_printable_container<strip<decltype(*begin(decllval<T>()))>>::value
|| is_tuple_like<strip<decltype(*begin(decllval<T>()))>>::value,
void>::type
>
> : public std::true_type {};
}
template<typename T, size_t... I> std::string stringify_tuple_like(const T&, std::index_sequence<I...>);
template<typename T> std::string stringify_tuple_like(const T& t) {
return stringify_tuple_like(t, std::make_index_sequence<std::tuple_size<T>::value - 1>{});
}
template<typename T, typename std::enable_if<std::is_pointer<strip<typename std::decay<T>::type>>::value
|| std::is_function<strip<T>>::value
|| !can_basic_stringify<T>::value, int>::type = 0>
LIBASSERT_ATTR_COLD [[nodiscard]]
std::string stringify(const T& t, [[maybe_unused]] literal_format fmt = literal_format::none) {
if constexpr(
has_stream_overload<T>::value && !is_string_type<T>
&& !std::is_pointer<strip<typename std::decay<T>::type>>::value
) {
std::ostringstream oss;
oss<<t;
return std::move(oss).str();
} else if constexpr(adl::is_printable_container<T>::value && !is_c_string<T>) {
using std::begin, std::end; // ADL
std::string str = "[";
const auto begin_it = begin(t);
for(auto it = begin_it; it != end(t); it++) {
if(it != begin_it) {
str += ", ";
}
str += stringify(*it, literal_format::dec);
}
str += "]";
return str;
} else if constexpr(
std::is_pointer<strip<typename std::decay<T>::type>>::value
|| std::is_function<strip<T>>::value
) {
if constexpr(isa<typename std::remove_pointer<typename std::decay<T>::type>::type, char>) { // strings
const void* v = t; // circumvent -Wnonnull-compare
if(v != nullptr) {
return stringify(std::string_view(t)); // not printing type for now, TODO: reconsider?
}
}
return prettify_type(std::string(type_name<T>())) + ": "
+ stringify_ptr(reinterpret_cast<const void*>(t), fmt);
} else if constexpr(is_tuple_like<T>::value) {
return stringify_tuple_like(t);
}
#ifdef ASSERT_USE_MAGIC_ENUM
else if constexpr(std::is_enum<strip<T>>::value) {
std::string_view name = magic_enum::enum_name(t);
if(!name.empty()) {
return std::string(name);
} else {
return bstringf("<instance of %s>", prettify_type(std::string(type_name<T>())).c_str());
}
}
#endif
else {
return bstringf("<instance of %s>", prettify_type(std::string(type_name<T>())).c_str());
}
}
// I'm going to assume at least one index because is_tuple_like requires index 0 to exist
template<typename T, size_t... I> std::string stringify_tuple_like(const T& t, std::index_sequence<I...>) {
using lf = literal_format;
using stringification::stringify; // ADL
return "["
+ (stringify(std::get<0>(t), lf::dec) + ... + (", " + stringify(std::get<I + 1>(t), lf::dec)))
+ "]";
}
}
/*
* assert diagnostics generation
*/
constexpr size_t format_arr_length = 5;
// TODO: Not yet happy with the naming of this function / how it's used
template<typename T>
LIBASSERT_ATTR_COLD [[nodiscard]]
std::string generate_stringification(const T& v, literal_format fmt = literal_format::none) {
using stringification::stringify; // ADL
if constexpr((stringification::adl::is_printable_container<T>::value && !is_string_type<T>)) {
using std::size; // ADL
return prettify_type(std::string(type_name<T>()))
+ " [size: " + std::to_string(size(v)) + "]: " + stringify(v, fmt);
} else if constexpr(stringification::is_tuple_like<T>::value) {
return prettify_type(std::string(type_name<T>())) + ": " + stringify(v, fmt);
} else {
return stringify(v, fmt);
}
}
template<typename T>
LIBASSERT_ATTR_COLD [[nodiscard]]
std::vector<std::string> generate_stringifications(const T& v, const literal_format (&formats)[format_arr_length]) {
if constexpr((std::is_arithmetic<strip<T>>::value || std::is_enum<strip<T>>::value) && !isa<T, bool>) {
std::vector<std::string> vec;
for(literal_format fmt : formats) {
if(fmt == literal_format::none) { break; }
using stringification::stringify; // ADL
// TODO: consider pushing empty fillers to keep columns aligned later on? Does not
// matter at the moment because floats only have decimal and hex literals but could
// if more formats are added.
vec.push_back(stringify(v, fmt));
}
return vec;
} else {
return { generate_stringification(v) };
}
}
struct binary_diagnostics_descriptor {
std::vector<std::string> lstrings;
std::vector<std::string> rstrings;
std::string a_str;
std::string b_str;
bool multiple_formats;
bool present = false;
binary_diagnostics_descriptor(); // = default; in the .cpp
binary_diagnostics_descriptor(
std::vector<std::string>& lstrings,
std::vector<std::string>& rstrings,
std::string a_str,
std::string b_str,
bool multiple_formats
);
compl binary_diagnostics_descriptor(); // = default; in the .cpp
binary_diagnostics_descriptor(const binary_diagnostics_descriptor&) = delete;
binary_diagnostics_descriptor(binary_diagnostics_descriptor&&) noexcept; // = default; in the .cpp
binary_diagnostics_descriptor& operator=(const binary_diagnostics_descriptor&) = delete;
binary_diagnostics_descriptor& operator=(binary_diagnostics_descriptor&&) noexcept; // = default; in the .cpp
};
void sort_and_dedup(literal_format(&)[format_arr_length]);
template<typename A, typename B>
LIBASSERT_ATTR_COLD [[nodiscard]]
binary_diagnostics_descriptor generate_binary_diagnostic(
const A& a,
const B& b,
const char* a_str,
const char* b_str,
std::string_view op
) {
using lf = literal_format;
// Note: op
// figure out what information we need to print in the where clause
// find all literal formats involved (literal_format::dec included for everything)
auto lformat = get_literal_format(a_str);
auto rformat = get_literal_format(b_str);
// formerly used std::set here, now using array + sorting, `none` entries will be at the end and ignored
constexpr bool either_is_character = isa<A, char> || isa<B, char>;
constexpr bool either_is_arithmetic = is_arith_not_bool_char<A> || is_arith_not_bool_char<B>;
lf formats[format_arr_length] = {
either_is_arithmetic ? lf::dec : lf::none,
lformat, rformat, // ↓ always display binary for bitwise
is_bitwise(op) ? lf::binary : lf::none,
either_is_character ? lf::character : lf::none
};
sort_and_dedup(formats); // print in specific order, avoid duplicates
if(formats[0] == lf::none) {
formats[0] = lf::dec; // if no formats apply just print everything default, TODO this is a bit of a hack
}
// generate raw strings for given formats, without highlighting
std::vector<std::string> lstrings = generate_stringifications(a, formats);
std::vector<std::string> rstrings = generate_stringifications(b, formats);
return binary_diagnostics_descriptor { lstrings, rstrings, a_str, b_str, formats[1] != lf::none };
}
#define LIBASSERT_X(x) #x
#define LIBASSERT_Y(x) LIBASSERT_X(x)
constexpr const std::string_view errno_expansion = LIBASSERT_Y(errno);
#undef LIBASSERT_Y
#undef LIBASSERT_X
struct extra_diagnostics {
ASSERTION fatality = ASSERTION::FATAL;
std::string message;
std::vector<std::pair<std::string, std::string>> entries;
const char* pretty_function = "<error>";
extra_diagnostics();
compl extra_diagnostics();
extra_diagnostics(const extra_diagnostics&) = delete;
extra_diagnostics(extra_diagnostics&&) noexcept; // = default; in the .cpp
extra_diagnostics& operator=(const extra_diagnostics&) = delete;
extra_diagnostics& operator=(extra_diagnostics&&) = delete;
};
struct pretty_function_name_wrapper {
const char* pretty_function;
};
template<typename T>
LIBASSERT_ATTR_COLD
void process_arg(extra_diagnostics& entry, size_t i, const char* const* const args_strings, const T& t) {
if constexpr(isa<T, ASSERTION>) {
entry.fatality = t;
} else if constexpr(isa<T, pretty_function_name_wrapper>) {
entry.pretty_function = t.pretty_function;
} else {
// three cases to handle: assert message, errno, and regular diagnostics
#if LIBASSERT_IS_MSVC
#pragma warning(push)
#pragma warning(disable: 4127) // MSVC thinks constexpr should be used here. It should not.
#endif
if(isa<T, strip<decltype(errno)>> && args_strings[i] == errno_expansion) {
#if LIBASSERT_IS_MSVC
#pragma warning(pop)
#endif
// this is redundant and useless but the body for errno handling needs to be in an
// if constexpr wrapper
if constexpr(isa<T, strip<decltype(errno)>>) {
// errno will expand to something hideous like (*__errno_location()),
// may as well replace it with "errno"
entry.entries.push_back({ "errno", bstringf("%2d \"%s\"", t, strerror_wrapper(t).c_str()) });
}
} else {
if constexpr(is_string_type<T>) {
if(i == 0) {
if constexpr(std::is_pointer<T>::value) {
if(t == nullptr) {
entry.message = "(nullptr)";
return;
}
}
entry.message = t;
return;
}
}
entry.entries.push_back({ args_strings[i], generate_stringification(t, literal_format::dec) });
}
}
}
template<typename... Args>
LIBASSERT_ATTR_COLD [[nodiscard]]
extra_diagnostics process_args(const char* const* const args_strings, Args&... args) {
extra_diagnostics entry;
size_t i = 0;
(process_arg(entry, i++, args_strings, args), ...);
(void)args_strings;
return entry;
}
/*
* actual assertion handling, finally
*/
struct lock {
lock();
compl lock();
lock(const lock&) = delete;
lock(lock&&) = delete;
lock& operator=(const lock&) = delete;
lock& operator=(lock&&) = delete;
};
// collection of assertion data that can be put in static storage and all passed by a single pointer
struct assert_static_parameters {
const char* name;
assert_type type;
const char* expr_str;
source_location location;
const char* const* args_strings;
};
}
/*
* Public constructs
*/
namespace libassert {
struct verification_failure : std::exception {
// I must just this once
// NOLINTNEXTLINE(cppcoreguidelines-explicit-virtual-functions,modernize-use-override)
[[nodiscard]] virtual const char* what() const noexcept final override;
};
class assertion_printer {
const detail::assert_static_parameters* params;
const detail::extra_diagnostics& processed_args;
detail::binary_diagnostics_descriptor& binary_diagnostics;
void* raw_trace;
size_t sizeof_args;
public:
assertion_printer() = delete;
assertion_printer(
const detail::assert_static_parameters* params,
const detail::extra_diagnostics& processed_args,
detail::binary_diagnostics_descriptor& binary_diagnostics,
void* raw_trace, size_t sizeof_args
);
compl assertion_printer();
assertion_printer(const assertion_printer&) = delete;
assertion_printer(assertion_printer&&) = delete;
assertion_printer& operator=(const assertion_printer&) = delete;
assertion_printer& operator=(assertion_printer&&) = delete;
[[nodiscard]] std::string operator()(int width) const;
// filename, line, function, message
[[nodiscard]] std::tuple<const char*, int, std::string, const char*> get_assertion_info() const;
};
}
/*
* Public utilities
*/
namespace libassert::utility {
// strip ansi escape sequences from a string
[[nodiscard]] std::string strip_colors(const std::string& str);
// replace 24-bit rgb ansi color sequences with traditional color sequences
[[nodiscard]] std::string replace_rgb(std::string str);
// returns the width of the terminal represented by fd, will be 0 on error
[[nodiscard]] int terminal_width(int fd);
// generates a stack trace, formats to the given width
[[nodiscard]] std::string stacktrace(int width);
// returns the type name of T
template<typename T>
[[nodiscard]] std::string_view type_name() noexcept {
return detail::type_name<T>();
}
// returns the prettified type name for T
template<typename T>
[[nodiscard]] std::string pretty_type_name() noexcept {
return detail::prettify_type(std::string(detail::type_name<T>()));
}
// returns a debug stringification of t
template<typename T>
[[nodiscard]] std::string stringify(const T& t) {
using detail::stringification::stringify; // ADL
using lf = detail::literal_format;
return stringify(t, detail::isa<T, char> ? lf::character : lf::dec);
}
}
/*
* Configuration
*/
namespace libassert::config {
// configures whether the default assertion handler prints in color or not to tty devices
void set_color_output(bool);
// configure whether to use 24-bit rgb ansi color sequences or traditional ansi color sequences
void set_rgb_output(bool);
}
/*
* Actual top-level assertion processing
*/
namespace libassert::detail {
size_t count_args_strings(const char* const*);
template<typename A, typename B, typename C, typename... Args>
LIBASSERT_ATTR_COLD LIBASSERT_ATTR_NOINLINE
void process_assert_fail(
expression_decomposer<A, B, C>& decomposer,
const assert_static_parameters* params,
Args&&... args
) {
lock l;
const auto* args_strings = params->args_strings;
size_t args_strings_count = count_args_strings(args_strings);
size_t sizeof_extra_diagnostics = sizeof...(args) - 1; // - 1 for pretty function signature
LIBASSERT_PRIMITIVE_ASSERT(
(sizeof...(args) == 1 && args_strings_count == 2) || args_strings_count == sizeof_extra_diagnostics + 1
);
// process_args needs to be called as soon as possible in case errno needs to be read
const auto processed_args = process_args(args_strings, args...);
const auto fatal = processed_args.fatality;
void* raw_trace = get_stacktrace_opaque();
// generate header
std::string output;
binary_diagnostics_descriptor binary_diagnostics;
// generate binary diagnostics
if constexpr(is_nothing<C>) {
static_assert(is_nothing<B> && !is_nothing<A>);
if constexpr(isa<A, bool>) {
(void)decomposer; // suppress warning in msvc
} else {