check_op.h 21 KB

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