1 // Copyright 2022 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15 // -----------------------------------------------------------------------------
16 // File: log/internal/check_op.h
17 // -----------------------------------------------------------------------------
18 //
19 // This file declares helpers routines and macros used to implement `CHECK`
20 // macros.
21
22 #ifndef ABSL_LOG_INTERNAL_CHECK_OP_H_
23 #define ABSL_LOG_INTERNAL_CHECK_OP_H_
24
25 #include <stdint.h>
26
27 #include <ostream>
28 #include <sstream>
29 #include <string>
30 #include <utility>
31
32 #include "absl/base/attributes.h"
33 #include "absl/base/config.h"
34 #include "absl/base/optimization.h"
35 #include "absl/log/internal/nullguard.h"
36 #include "absl/log/internal/nullstream.h"
37 #include "absl/log/internal/strip.h"
38
39 // `ABSL_LOG_INTERNAL_STRIP_STRING_LITERAL` wraps string literals that
40 // should be stripped when `ABSL_MIN_LOG_LEVEL` exceeds `kFatal`.
41 #ifdef ABSL_MIN_LOG_LEVEL
42 #define ABSL_LOG_INTERNAL_STRIP_STRING_LITERAL(literal) \
43 (::absl::LogSeverity::kFatal >= \
44 static_cast<::absl::LogSeverity>(ABSL_MIN_LOG_LEVEL) \
45 ? (literal) \
46 : "")
47 #else
48 #define ABSL_LOG_INTERNAL_STRIP_STRING_LITERAL(literal) (literal)
49 #endif
50
51 #ifdef NDEBUG
52 // `NDEBUG` is defined, so `DCHECK_EQ(x, y)` and so on do nothing. However, we
53 // still want the compiler to parse `x` and `y`, because we don't want to lose
54 // potentially useful errors and warnings.
55 #define ABSL_LOG_INTERNAL_DCHECK_NOP(x, y) \
56 while (false && ((void)(x), (void)(y), 0)) \
57 ::absl::log_internal::NullStream().InternalStream()
58 #endif
59
60 #define ABSL_LOG_INTERNAL_CHECK_OP(name, op, val1, val1_text, val2, val2_text) \
61 while ( \
62 ::std::string* absl_log_internal_check_op_result ABSL_ATTRIBUTE_UNUSED = \
63 ::absl::log_internal::name##Impl( \
64 ::absl::log_internal::GetReferenceableValue(val1), \
65 ::absl::log_internal::GetReferenceableValue(val2), \
66 ABSL_LOG_INTERNAL_STRIP_STRING_LITERAL(val1_text \
67 " " #op " " val2_text))) \
68 ABSL_LOG_INTERNAL_CONDITION_FATAL(STATELESS, true) \
69 ABSL_LOG_INTERNAL_CHECK(*absl_log_internal_check_op_result).InternalStream()
70 #define ABSL_LOG_INTERNAL_QCHECK_OP(name, op, val1, val1_text, val2, \
71 val2_text) \
72 while (::std::string* absl_log_internal_qcheck_op_result = \
73 ::absl::log_internal::name##Impl( \
74 ::absl::log_internal::GetReferenceableValue(val1), \
75 ::absl::log_internal::GetReferenceableValue(val2), \
76 ABSL_LOG_INTERNAL_STRIP_STRING_LITERAL( \
77 val1_text " " #op " " val2_text))) \
78 ABSL_LOG_INTERNAL_CONDITION_QFATAL(STATELESS, true) \
79 ABSL_LOG_INTERNAL_QCHECK(*absl_log_internal_qcheck_op_result).InternalStream()
80 #define ABSL_LOG_INTERNAL_CHECK_STROP(func, op, expected, s1, s1_text, s2, \
81 s2_text) \
82 while (::std::string* absl_log_internal_check_strop_result = \
83 ::absl::log_internal::Check##func##expected##Impl( \
84 (s1), (s2), \
85 ABSL_LOG_INTERNAL_STRIP_STRING_LITERAL(s1_text " " #op \
86 " " s2_text))) \
87 ABSL_LOG_INTERNAL_CONDITION_FATAL(STATELESS, true) \
88 ABSL_LOG_INTERNAL_CHECK(*absl_log_internal_check_strop_result) \
89 .InternalStream()
90 #define ABSL_LOG_INTERNAL_QCHECK_STROP(func, op, expected, s1, s1_text, s2, \
91 s2_text) \
92 while (::std::string* absl_log_internal_qcheck_strop_result = \
93 ::absl::log_internal::Check##func##expected##Impl( \
94 (s1), (s2), \
95 ABSL_LOG_INTERNAL_STRIP_STRING_LITERAL(s1_text " " #op \
96 " " s2_text))) \
97 ABSL_LOG_INTERNAL_CONDITION_QFATAL(STATELESS, true) \
98 ABSL_LOG_INTERNAL_QCHECK(*absl_log_internal_qcheck_strop_result) \
99 .InternalStream()
100 // This one is tricky:
101 // * We must evaluate `val` exactly once, yet we need to do two things with it:
102 // evaluate `.ok()` and (sometimes) `.ToString()`.
103 // * `val` might be an `absl::Status` or some `absl::StatusOr<T>`.
104 // * `val` might be e.g. `ATemporary().GetStatus()`, which may return a
105 // reference to a member of `ATemporary` that is only valid until the end of
106 // the full expression.
107 // * We don't want this file to depend on `absl::Status` `#include`s or linkage,
108 // nor do we want to move the definition to status and introduce a dependency
109 // in the other direction. We can be assured that callers must already have a
110 // `Status` and the necessary `#include`s and linkage.
111 // * Callsites should be small and fast (at least when `val.ok()`): one branch,
112 // minimal stack footprint.
113 // * In particular, the string concat stuff should be out-of-line and emitted
114 // in only one TU to save linker input size
115 // * We want the `val.ok()` check inline so static analyzers and optimizers can
116 // see it.
117 // * As usual, no braces so we can stream into the expansion with `operator<<`.
118 // * Also as usual, it must expand to a single (partial) statement with no
119 // ambiguous-else problems.
120 // * When stripped by `ABSL_MIN_LOG_LEVEL`, we must discard the `<expr> is OK`
121 // string literal and abort without doing any streaming. We don't need to
122 // strip the call to stringify the non-ok `Status` as long as we don't log it;
123 // dropping the `Status`'s message text is out of scope.
124 #define ABSL_LOG_INTERNAL_CHECK_OK(val, val_text) \
125 for (::std::pair<const ::absl::Status*, ::std::string*> \
126 absl_log_internal_check_ok_goo; \
127 absl_log_internal_check_ok_goo.first = \
128 ::absl::log_internal::AsStatus(val), \
129 absl_log_internal_check_ok_goo.second = \
130 ABSL_PREDICT_TRUE(absl_log_internal_check_ok_goo.first->ok()) \
131 ? nullptr \
132 : ::absl::status_internal::MakeCheckFailString( \
133 absl_log_internal_check_ok_goo.first, \
134 ABSL_LOG_INTERNAL_STRIP_STRING_LITERAL(val_text \
135 " is OK")), \
136 !ABSL_PREDICT_TRUE(absl_log_internal_check_ok_goo.first->ok());) \
137 ABSL_LOG_INTERNAL_CONDITION_FATAL(STATELESS, true) \
138 ABSL_LOG_INTERNAL_CHECK(*absl_log_internal_check_ok_goo.second) \
139 .InternalStream()
140 #define ABSL_LOG_INTERNAL_QCHECK_OK(val, val_text) \
141 for (::std::pair<const ::absl::Status*, ::std::string*> \
142 absl_log_internal_qcheck_ok_goo; \
143 absl_log_internal_qcheck_ok_goo.first = \
144 ::absl::log_internal::AsStatus(val), \
145 absl_log_internal_qcheck_ok_goo.second = \
146 ABSL_PREDICT_TRUE(absl_log_internal_qcheck_ok_goo.first->ok()) \
147 ? nullptr \
148 : ::absl::status_internal::MakeCheckFailString( \
149 absl_log_internal_qcheck_ok_goo.first, \
150 ABSL_LOG_INTERNAL_STRIP_STRING_LITERAL(val_text \
151 " is OK")), \
152 !ABSL_PREDICT_TRUE(absl_log_internal_qcheck_ok_goo.first->ok());) \
153 ABSL_LOG_INTERNAL_CONDITION_QFATAL(STATELESS, true) \
154 ABSL_LOG_INTERNAL_QCHECK(*absl_log_internal_qcheck_ok_goo.second) \
155 .InternalStream()
156
157 namespace absl {
158 ABSL_NAMESPACE_BEGIN
159
160 class Status;
161 template <typename T>
162 class StatusOr;
163
164 namespace status_internal {
165 ABSL_ATTRIBUTE_PURE_FUNCTION std::string* MakeCheckFailString(
166 const absl::Status* status, const char* prefix);
167 } // namespace status_internal
168
169 namespace log_internal {
170
171 // Convert a Status or a StatusOr to its underlying status value.
172 //
173 // (This implementation does not require a dep on absl::Status to work.)
AsStatus(const absl::Status & s)174 inline const absl::Status* AsStatus(const absl::Status& s) { return &s; }
175 template <typename T>
AsStatus(const absl::StatusOr<T> & s)176 const absl::Status* AsStatus(const absl::StatusOr<T>& s) {
177 return &s.status();
178 }
179
180 // A helper class for formatting `expr (V1 vs. V2)` in a `CHECK_XX` statement.
181 // See `MakeCheckOpString` for sample usage.
182 class CheckOpMessageBuilder final {
183 public:
184 // Inserts `exprtext` and ` (` to the stream.
185 explicit CheckOpMessageBuilder(const char* exprtext);
186 ~CheckOpMessageBuilder() = default;
187 // For inserting the first variable.
ForVar1()188 std::ostream& ForVar1() { return stream_; }
189 // For inserting the second variable (adds an intermediate ` vs. `).
190 std::ostream& ForVar2();
191 // Get the result (inserts the closing `)`).
192 std::string* NewString();
193
194 private:
195 std::ostringstream stream_;
196 };
197
198 // This formats a value for a failing `CHECK_XX` statement. Ordinarily, it uses
199 // the definition for `operator<<`, with a few special cases below.
200 template <typename T>
MakeCheckOpValueString(std::ostream & os,const T & v)201 inline void MakeCheckOpValueString(std::ostream& os, const T& v) {
202 os << log_internal::NullGuard<T>::Guard(v);
203 }
204
205 // Overloads for char types provide readable values for unprintable characters.
206 void MakeCheckOpValueString(std::ostream& os, char v);
207 void MakeCheckOpValueString(std::ostream& os, signed char v);
208 void MakeCheckOpValueString(std::ostream& os, unsigned char v);
209 void MakeCheckOpValueString(std::ostream& os, const void* p);
210
211 namespace detect_specialization {
212
213 // MakeCheckOpString is being specialized for every T and U pair that is being
214 // passed to the CHECK_op macros. However, there is a lot of redundancy in these
215 // specializations that creates unnecessary library and binary bloat.
216 // The number of instantiations tends to be O(n^2) because we have two
217 // independent inputs. This technique works by reducing `n`.
218 //
219 // Most user-defined types being passed to CHECK_op end up being printed as a
220 // builtin type. For example, enums tend to be implicitly converted to its
221 // underlying type when calling operator<<, and pointers are printed with the
222 // `const void*` overload.
223 // To reduce the number of instantiations we coerce these values before calling
224 // MakeCheckOpString instead of inside it.
225 //
226 // To detect if this coercion is needed, we duplicate all the relevant
227 // operator<< overloads as specified in the standard, just in a different
228 // namespace. If the call to `stream << value` becomes ambiguous, it means that
229 // one of these overloads is the one selected by overload resolution. We then
230 // do overload resolution again just with our overload set to see which one gets
231 // selected. That tells us which type to coerce to.
232 // If the augmented call was not ambiguous, it means that none of these were
233 // selected and we can't coerce the input.
234 //
235 // As a secondary step to reduce code duplication, we promote integral types to
236 // their 64-bit variant. This does not change the printed value, but reduces the
237 // number of instantiations even further. Promoting an integer is very cheap at
238 // the call site.
239 int64_t operator<<(std::ostream&, short value); // NOLINT
240 int64_t operator<<(std::ostream&, unsigned short value); // NOLINT
241 int64_t operator<<(std::ostream&, int value);
242 int64_t operator<<(std::ostream&, unsigned int value);
243 int64_t operator<<(std::ostream&, long value); // NOLINT
244 uint64_t operator<<(std::ostream&, unsigned long value); // NOLINT
245 int64_t operator<<(std::ostream&, long long value); // NOLINT
246 uint64_t operator<<(std::ostream&, unsigned long long value); // NOLINT
247 float operator<<(std::ostream&, float value);
248 double operator<<(std::ostream&, double value);
249 long double operator<<(std::ostream&, long double value);
250 bool operator<<(std::ostream&, bool value);
251 const void* operator<<(std::ostream&, const void* value);
252 const void* operator<<(std::ostream&, std::nullptr_t);
253
254 // These `char` overloads are specified like this in the standard, so we have to
255 // write them exactly the same to ensure the call is ambiguous.
256 // If we wrote it in a different way (eg taking std::ostream instead of the
257 // template) then one call might have a higher rank than the other and it would
258 // not be ambiguous.
259 template <typename Traits>
260 char operator<<(std::basic_ostream<char, Traits>&, char);
261 template <typename Traits>
262 signed char operator<<(std::basic_ostream<char, Traits>&, signed char);
263 template <typename Traits>
264 unsigned char operator<<(std::basic_ostream<char, Traits>&, unsigned char);
265 template <typename Traits>
266 const char* operator<<(std::basic_ostream<char, Traits>&, const char*);
267 template <typename Traits>
268 const signed char* operator<<(std::basic_ostream<char, Traits>&,
269 const signed char*);
270 template <typename Traits>
271 const unsigned char* operator<<(std::basic_ostream<char, Traits>&,
272 const unsigned char*);
273
274 // This overload triggers when the call is not ambiguous.
275 // It means that T is being printed with some overload not on this list.
276 // We keep the value as `const T&`.
277 template <typename T, typename = decltype(std::declval<std::ostream&>()
278 << std::declval<const T&>())>
279 const T& Detect(int);
280
281 // This overload triggers when the call is ambiguous.
282 // It means that T is either one from this list or printed as one from this
283 // list. Eg an enum that decays to `int` for printing.
284 // We ask the overload set to give us the type we want to convert it to.
285 template <typename T>
286 decltype(detect_specialization::operator<<(std::declval<std::ostream&>(),
287 std::declval<const T&>()))
288 Detect(char);
289
290 } // namespace detect_specialization
291
292 template <typename T>
293 using CheckOpStreamType = decltype(detect_specialization::Detect<T>(0));
294
295 // Build the error message string. Specify no inlining for code size.
296 template <typename T1, typename T2>
297 ABSL_ATTRIBUTE_RETURNS_NONNULL std::string* MakeCheckOpString(
298 T1 v1, T2 v2, const char* exprtext) ABSL_ATTRIBUTE_NOINLINE;
299
300 template <typename T1, typename T2>
MakeCheckOpString(T1 v1,T2 v2,const char * exprtext)301 std::string* MakeCheckOpString(T1 v1, T2 v2, const char* exprtext) {
302 CheckOpMessageBuilder comb(exprtext);
303 MakeCheckOpValueString(comb.ForVar1(), v1);
304 MakeCheckOpValueString(comb.ForVar2(), v2);
305 return comb.NewString();
306 }
307
308 // Add a few commonly used instantiations as extern to reduce size of objects
309 // files.
310 #define ABSL_LOG_INTERNAL_DEFINE_MAKE_CHECK_OP_STRING_EXTERN(x) \
311 extern template std::string* MakeCheckOpString(x, x, const char*)
312 ABSL_LOG_INTERNAL_DEFINE_MAKE_CHECK_OP_STRING_EXTERN(bool);
313 ABSL_LOG_INTERNAL_DEFINE_MAKE_CHECK_OP_STRING_EXTERN(int64_t);
314 ABSL_LOG_INTERNAL_DEFINE_MAKE_CHECK_OP_STRING_EXTERN(uint64_t);
315 ABSL_LOG_INTERNAL_DEFINE_MAKE_CHECK_OP_STRING_EXTERN(float);
316 ABSL_LOG_INTERNAL_DEFINE_MAKE_CHECK_OP_STRING_EXTERN(double);
317 ABSL_LOG_INTERNAL_DEFINE_MAKE_CHECK_OP_STRING_EXTERN(char);
318 ABSL_LOG_INTERNAL_DEFINE_MAKE_CHECK_OP_STRING_EXTERN(unsigned char);
319 ABSL_LOG_INTERNAL_DEFINE_MAKE_CHECK_OP_STRING_EXTERN(const std::string&);
320 ABSL_LOG_INTERNAL_DEFINE_MAKE_CHECK_OP_STRING_EXTERN(const absl::string_view&);
321 ABSL_LOG_INTERNAL_DEFINE_MAKE_CHECK_OP_STRING_EXTERN(const char*);
322 ABSL_LOG_INTERNAL_DEFINE_MAKE_CHECK_OP_STRING_EXTERN(const signed char*);
323 ABSL_LOG_INTERNAL_DEFINE_MAKE_CHECK_OP_STRING_EXTERN(const unsigned char*);
324 ABSL_LOG_INTERNAL_DEFINE_MAKE_CHECK_OP_STRING_EXTERN(const void*);
325 #undef ABSL_LOG_INTERNAL_DEFINE_MAKE_CHECK_OP_STRING_EXTERN
326
327 // `ABSL_LOG_INTERNAL_CHECK_OP_IMPL_RESULT` skips formatting the Check_OP result
328 // string iff `ABSL_MIN_LOG_LEVEL` exceeds `kFatal`, instead returning an empty
329 // string.
330 #ifdef ABSL_MIN_LOG_LEVEL
331 #define ABSL_LOG_INTERNAL_CHECK_OP_IMPL_RESULT(U1, U2, v1, v2, exprtext) \
332 ((::absl::LogSeverity::kFatal >= \
333 static_cast<::absl::LogSeverity>(ABSL_MIN_LOG_LEVEL)) \
334 ? MakeCheckOpString<U1, U2>(v1, v2, exprtext) \
335 : new std::string())
336 #else
337 #define ABSL_LOG_INTERNAL_CHECK_OP_IMPL_RESULT(U1, U2, v1, v2, exprtext) \
338 MakeCheckOpString<U1, U2>(v1, v2, exprtext)
339 #endif
340
341 // Helper functions for `ABSL_LOG_INTERNAL_CHECK_OP` macro family. The
342 // `(int, int)` override works around the issue that the compiler will not
343 // instantiate the template version of the function on values of unnamed enum
344 // type.
345 #define ABSL_LOG_INTERNAL_CHECK_OP_IMPL(name, op) \
346 template <typename T1, typename T2> \
347 inline constexpr ::std::string* name##Impl(const T1& v1, const T2& v2, \
348 const char* exprtext) { \
349 using U1 = CheckOpStreamType<T1>; \
350 using U2 = CheckOpStreamType<T2>; \
351 return ABSL_PREDICT_TRUE(v1 op v2) \
352 ? nullptr \
353 : ABSL_LOG_INTERNAL_CHECK_OP_IMPL_RESULT(U1, U2, v1, v2, \
354 exprtext); \
355 } \
356 inline constexpr ::std::string* name##Impl(int v1, int v2, \
357 const char* exprtext) { \
358 return name##Impl<int, int>(v1, v2, exprtext); \
359 }
360
361 ABSL_LOG_INTERNAL_CHECK_OP_IMPL(Check_EQ, ==)
362 ABSL_LOG_INTERNAL_CHECK_OP_IMPL(Check_NE, !=)
363 ABSL_LOG_INTERNAL_CHECK_OP_IMPL(Check_LE, <=)
364 ABSL_LOG_INTERNAL_CHECK_OP_IMPL(Check_LT, <)
365 ABSL_LOG_INTERNAL_CHECK_OP_IMPL(Check_GE, >=)
366 ABSL_LOG_INTERNAL_CHECK_OP_IMPL(Check_GT, >)
367 #undef ABSL_LOG_INTERNAL_CHECK_OP_IMPL_RESULT
368 #undef ABSL_LOG_INTERNAL_CHECK_OP_IMPL
369
370 std::string* CheckstrcmptrueImpl(const char* s1, const char* s2,
371 const char* exprtext);
372 std::string* CheckstrcmpfalseImpl(const char* s1, const char* s2,
373 const char* exprtext);
374 std::string* CheckstrcasecmptrueImpl(const char* s1, const char* s2,
375 const char* exprtext);
376 std::string* CheckstrcasecmpfalseImpl(const char* s1, const char* s2,
377 const char* exprtext);
378
379 // `CHECK_EQ` and friends want to pass their arguments by reference, however
380 // this winds up exposing lots of cases where people have defined and
381 // initialized static const data members but never declared them (i.e. in a .cc
382 // file), meaning they are not referenceable. This function avoids that problem
383 // for integers (the most common cases) by overloading for every primitive
384 // integer type, even the ones we discourage, and returning them by value.
385 template <typename T>
GetReferenceableValue(const T & t)386 inline constexpr const T& GetReferenceableValue(const T& t) {
387 return t;
388 }
GetReferenceableValue(char t)389 inline constexpr char GetReferenceableValue(char t) { return t; }
GetReferenceableValue(unsigned char t)390 inline constexpr unsigned char GetReferenceableValue(unsigned char t) {
391 return t;
392 }
GetReferenceableValue(signed char t)393 inline constexpr signed char GetReferenceableValue(signed char t) { return t; }
GetReferenceableValue(short t)394 inline constexpr short GetReferenceableValue(short t) { return t; } // NOLINT
GetReferenceableValue(unsigned short t)395 inline constexpr unsigned short GetReferenceableValue( // NOLINT
396 unsigned short t) { // NOLINT
397 return t;
398 }
GetReferenceableValue(int t)399 inline constexpr int GetReferenceableValue(int t) { return t; }
GetReferenceableValue(unsigned int t)400 inline constexpr unsigned int GetReferenceableValue(unsigned int t) {
401 return t;
402 }
GetReferenceableValue(long t)403 inline constexpr long GetReferenceableValue(long t) { return t; } // NOLINT
GetReferenceableValue(unsigned long t)404 inline constexpr unsigned long GetReferenceableValue( // NOLINT
405 unsigned long t) { // NOLINT
406 return t;
407 }
GetReferenceableValue(long long t)408 inline constexpr long long GetReferenceableValue(long long t) { // NOLINT
409 return t;
410 }
GetReferenceableValue(unsigned long long t)411 inline constexpr unsigned long long GetReferenceableValue( // NOLINT
412 unsigned long long t) { // NOLINT
413 return t;
414 }
415
416 } // namespace log_internal
417 ABSL_NAMESPACE_END
418 } // namespace absl
419
420 #endif // ABSL_LOG_INTERNAL_CHECK_OP_H_
421