gtest-printers.h 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  1. // Copyright 2007, Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. //
  30. // Author: wan@google.com (Zhanyong Wan)
  31. // Google Test - The Google C++ Testing Framework
  32. //
  33. // This file implements a universal value printer that can print a
  34. // value of any type T:
  35. //
  36. // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
  37. //
  38. // A user can teach this function how to print a class type T by
  39. // defining either operator<<() or PrintTo() in the namespace that
  40. // defines T. More specifically, the FIRST defined function in the
  41. // following list will be used (assuming T is defined in namespace
  42. // foo):
  43. //
  44. // 1. foo::PrintTo(const T&, ostream*)
  45. // 2. operator<<(ostream&, const T&) defined in either foo or the
  46. // global namespace.
  47. //
  48. // However if T is an STL-style container then it is printed element-wise
  49. // unless foo::PrintTo(const T&, ostream*) is defined. Note that
  50. // operator<<() is ignored for container types.
  51. //
  52. // If none of the above is defined, it will print the debug string of
  53. // the value if it is a protocol buffer, or print the raw bytes in the
  54. // value otherwise.
  55. //
  56. // To aid debugging: when T is a reference type, the address of the
  57. // value is also printed; when T is a (const) char pointer, both the
  58. // pointer value and the NUL-terminated string it points to are
  59. // printed.
  60. //
  61. // We also provide some convenient wrappers:
  62. //
  63. // // Prints a value to a string. For a (const or not) char
  64. // // pointer, the NUL-terminated string (but not the pointer) is
  65. // // printed.
  66. // std::string ::testing::PrintToString(const T& value);
  67. //
  68. // // Prints a value tersely: for a reference type, the referenced
  69. // // value (but not the address) is printed; for a (const or not) char
  70. // // pointer, the NUL-terminated string (but not the pointer) is
  71. // // printed.
  72. // void ::testing::internal::UniversalTersePrint(const T& value, ostream*);
  73. //
  74. // // Prints value using the type inferred by the compiler. The difference
  75. // // from UniversalTersePrint() is that this function prints both the
  76. // // pointer and the NUL-terminated string for a (const or not) char pointer.
  77. // void ::testing::internal::UniversalPrint(const T& value, ostream*);
  78. //
  79. // // Prints the fields of a tuple tersely to a string vector, one
  80. // // element for each field. Tuple support must be enabled in
  81. // // gtest-port.h.
  82. // std::vector<string> UniversalTersePrintTupleFieldsToStrings(
  83. // const Tuple& value);
  84. //
  85. // Known limitation:
  86. //
  87. // The print primitives print the elements of an STL-style container
  88. // using the compiler-inferred type of *iter where iter is a
  89. // const_iterator of the container. When const_iterator is an input
  90. // iterator but not a forward iterator, this inferred type may not
  91. // match value_type, and the print output may be incorrect. In
  92. // practice, this is rarely a problem as for most containers
  93. // const_iterator is a forward iterator. We'll fix this if there's an
  94. // actual need for it. Note that this fix cannot rely on value_type
  95. // being defined as many user-defined container types don't have
  96. // value_type.
  97. #ifndef GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
  98. #define GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
  99. #include <ostream> // NOLINT
  100. #include <sstream>
  101. #include <string>
  102. #include <utility>
  103. #include <vector>
  104. #include "gtest/internal/gtest-port.h"
  105. #include "gtest/internal/gtest-internal.h"
  106. #if GTEST_HAS_STD_TUPLE_
  107. # include <tuple>
  108. #endif
  109. #if GTEST_HAS_ABSL
  110. #include "absl/strings/string_view.h"
  111. #include "absl/types/optional.h"
  112. #endif // GTEST_HAS_ABSL
  113. namespace testing {
  114. // Definitions in the 'internal' and 'internal2' name spaces are
  115. // subject to change without notice. DO NOT USE THEM IN USER CODE!
  116. namespace internal2 {
  117. // Prints the given number of bytes in the given object to the given
  118. // ostream.
  119. GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
  120. size_t count,
  121. ::std::ostream* os);
  122. // For selecting which printer to use when a given type has neither <<
  123. // nor PrintTo().
  124. enum TypeKind {
  125. kProtobuf, // a protobuf type
  126. kConvertibleToInteger, // a type implicitly convertible to BiggestInt
  127. // (e.g. a named or unnamed enum type)
  128. #if GTEST_HAS_ABSL
  129. kConvertibleToStringView, // a type implicitly convertible to
  130. // absl::string_view
  131. #endif
  132. kOtherType // anything else
  133. };
  134. // TypeWithoutFormatter<T, kTypeKind>::PrintValue(value, os) is called
  135. // by the universal printer to print a value of type T when neither
  136. // operator<< nor PrintTo() is defined for T, where kTypeKind is the
  137. // "kind" of T as defined by enum TypeKind.
  138. template <typename T, TypeKind kTypeKind>
  139. class TypeWithoutFormatter {
  140. public:
  141. // This default version is called when kTypeKind is kOtherType.
  142. static void PrintValue(const T& value, ::std::ostream* os) {
  143. PrintBytesInObjectTo(static_cast<const unsigned char*>(
  144. reinterpret_cast<const void*>(&value)),
  145. sizeof(value), os);
  146. }
  147. };
  148. // We print a protobuf using its ShortDebugString() when the string
  149. // doesn't exceed this many characters; otherwise we print it using
  150. // DebugString() for better readability.
  151. const size_t kProtobufOneLinerMaxLength = 50;
  152. template <typename T>
  153. class TypeWithoutFormatter<T, kProtobuf> {
  154. public:
  155. static void PrintValue(const T& value, ::std::ostream* os) {
  156. std::string pretty_str = value.ShortDebugString();
  157. if (pretty_str.length() > kProtobufOneLinerMaxLength) {
  158. pretty_str = "\n" + value.DebugString();
  159. }
  160. *os << ("<" + pretty_str + ">");
  161. }
  162. };
  163. template <typename T>
  164. class TypeWithoutFormatter<T, kConvertibleToInteger> {
  165. public:
  166. // Since T has no << operator or PrintTo() but can be implicitly
  167. // converted to BiggestInt, we print it as a BiggestInt.
  168. //
  169. // Most likely T is an enum type (either named or unnamed), in which
  170. // case printing it as an integer is the desired behavior. In case
  171. // T is not an enum, printing it as an integer is the best we can do
  172. // given that it has no user-defined printer.
  173. static void PrintValue(const T& value, ::std::ostream* os) {
  174. const internal::BiggestInt kBigInt = value;
  175. *os << kBigInt;
  176. }
  177. };
  178. #if GTEST_HAS_ABSL
  179. template <typename T>
  180. class TypeWithoutFormatter<T, kConvertibleToStringView> {
  181. public:
  182. // Since T has neither operator<< nor PrintTo() but can be implicitly
  183. // converted to absl::string_view, we print it as a absl::string_view.
  184. //
  185. // Note: the implementation is further below, as it depends on
  186. // internal::PrintTo symbol which is defined later in the file.
  187. static void PrintValue(const T& value, ::std::ostream* os);
  188. };
  189. #endif
  190. // Prints the given value to the given ostream. If the value is a
  191. // protocol message, its debug string is printed; if it's an enum or
  192. // of a type implicitly convertible to BiggestInt, it's printed as an
  193. // integer; otherwise the bytes in the value are printed. This is
  194. // what UniversalPrinter<T>::Print() does when it knows nothing about
  195. // type T and T has neither << operator nor PrintTo().
  196. //
  197. // A user can override this behavior for a class type Foo by defining
  198. // a << operator in the namespace where Foo is defined.
  199. //
  200. // We put this operator in namespace 'internal2' instead of 'internal'
  201. // to simplify the implementation, as much code in 'internal' needs to
  202. // use << in STL, which would conflict with our own << were it defined
  203. // in 'internal'.
  204. //
  205. // Note that this operator<< takes a generic std::basic_ostream<Char,
  206. // CharTraits> type instead of the more restricted std::ostream. If
  207. // we define it to take an std::ostream instead, we'll get an
  208. // "ambiguous overloads" compiler error when trying to print a type
  209. // Foo that supports streaming to std::basic_ostream<Char,
  210. // CharTraits>, as the compiler cannot tell whether
  211. // operator<<(std::ostream&, const T&) or
  212. // operator<<(std::basic_stream<Char, CharTraits>, const Foo&) is more
  213. // specific.
  214. template <typename Char, typename CharTraits, typename T>
  215. ::std::basic_ostream<Char, CharTraits>& operator<<(
  216. ::std::basic_ostream<Char, CharTraits>& os, const T& x) {
  217. TypeWithoutFormatter<T, (internal::IsAProtocolMessage<T>::value
  218. ? kProtobuf
  219. : internal::ImplicitlyConvertible<
  220. const T&, internal::BiggestInt>::value
  221. ? kConvertibleToInteger
  222. :
  223. #if GTEST_HAS_ABSL
  224. internal::ImplicitlyConvertible<
  225. const T&, absl::string_view>::value
  226. ? kConvertibleToStringView
  227. :
  228. #endif
  229. kOtherType)>::PrintValue(x, &os);
  230. return os;
  231. }
  232. } // namespace internal2
  233. } // namespace testing
  234. // This namespace MUST NOT BE NESTED IN ::testing, or the name look-up
  235. // magic needed for implementing UniversalPrinter won't work.
  236. namespace testing_internal {
  237. // Used to print a value that is not an STL-style container when the
  238. // user doesn't define PrintTo() for it.
  239. template <typename T>
  240. void DefaultPrintNonContainerTo(const T& value, ::std::ostream* os) {
  241. // With the following statement, during unqualified name lookup,
  242. // testing::internal2::operator<< appears as if it was declared in
  243. // the nearest enclosing namespace that contains both
  244. // ::testing_internal and ::testing::internal2, i.e. the global
  245. // namespace. For more details, refer to the C++ Standard section
  246. // 7.3.4-1 [namespace.udir]. This allows us to fall back onto
  247. // testing::internal2::operator<< in case T doesn't come with a <<
  248. // operator.
  249. //
  250. // We cannot write 'using ::testing::internal2::operator<<;', which
  251. // gcc 3.3 fails to compile due to a compiler bug.
  252. using namespace ::testing::internal2; // NOLINT
  253. // Assuming T is defined in namespace foo, in the next statement,
  254. // the compiler will consider all of:
  255. //
  256. // 1. foo::operator<< (thanks to Koenig look-up),
  257. // 2. ::operator<< (as the current namespace is enclosed in ::),
  258. // 3. testing::internal2::operator<< (thanks to the using statement above).
  259. //
  260. // The operator<< whose type matches T best will be picked.
  261. //
  262. // We deliberately allow #2 to be a candidate, as sometimes it's
  263. // impossible to define #1 (e.g. when foo is ::std, defining
  264. // anything in it is undefined behavior unless you are a compiler
  265. // vendor.).
  266. *os << value;
  267. }
  268. } // namespace testing_internal
  269. namespace testing {
  270. namespace internal {
  271. // FormatForComparison<ToPrint, OtherOperand>::Format(value) formats a
  272. // value of type ToPrint that is an operand of a comparison assertion
  273. // (e.g. ASSERT_EQ). OtherOperand is the type of the other operand in
  274. // the comparison, and is used to help determine the best way to
  275. // format the value. In particular, when the value is a C string
  276. // (char pointer) and the other operand is an STL string object, we
  277. // want to format the C string as a string, since we know it is
  278. // compared by value with the string object. If the value is a char
  279. // pointer but the other operand is not an STL string object, we don't
  280. // know whether the pointer is supposed to point to a NUL-terminated
  281. // string, and thus want to print it as a pointer to be safe.
  282. //
  283. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  284. // The default case.
  285. template <typename ToPrint, typename OtherOperand>
  286. class FormatForComparison {
  287. public:
  288. static ::std::string Format(const ToPrint& value) {
  289. return ::testing::PrintToString(value);
  290. }
  291. };
  292. // Array.
  293. template <typename ToPrint, size_t N, typename OtherOperand>
  294. class FormatForComparison<ToPrint[N], OtherOperand> {
  295. public:
  296. static ::std::string Format(const ToPrint* value) {
  297. return FormatForComparison<const ToPrint*, OtherOperand>::Format(value);
  298. }
  299. };
  300. // By default, print C string as pointers to be safe, as we don't know
  301. // whether they actually point to a NUL-terminated string.
  302. #define GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(CharType) \
  303. template <typename OtherOperand> \
  304. class FormatForComparison<CharType*, OtherOperand> { \
  305. public: \
  306. static ::std::string Format(CharType* value) { \
  307. return ::testing::PrintToString(static_cast<const void*>(value)); \
  308. } \
  309. }
  310. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char);
  311. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char);
  312. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t);
  313. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);
  314. #undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_
  315. // If a C string is compared with an STL string object, we know it's meant
  316. // to point to a NUL-terminated string, and thus can print it as a string.
  317. #define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \
  318. template <> \
  319. class FormatForComparison<CharType*, OtherStringType> { \
  320. public: \
  321. static ::std::string Format(CharType* value) { \
  322. return ::testing::PrintToString(value); \
  323. } \
  324. }
  325. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);
  326. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string);
  327. #if GTEST_HAS_GLOBAL_STRING
  328. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::string);
  329. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::string);
  330. #endif
  331. #if GTEST_HAS_GLOBAL_WSTRING
  332. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::wstring);
  333. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::wstring);
  334. #endif
  335. #if GTEST_HAS_STD_WSTRING
  336. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring);
  337. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring);
  338. #endif
  339. #undef GTEST_IMPL_FORMAT_C_STRING_AS_STRING_
  340. // Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc)
  341. // operand to be used in a failure message. The type (but not value)
  342. // of the other operand may affect the format. This allows us to
  343. // print a char* as a raw pointer when it is compared against another
  344. // char* or void*, and print it as a C string when it is compared
  345. // against an std::string object, for example.
  346. //
  347. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  348. template <typename T1, typename T2>
  349. std::string FormatForComparisonFailureMessage(
  350. const T1& value, const T2& /* other_operand */) {
  351. return FormatForComparison<T1, T2>::Format(value);
  352. }
  353. // UniversalPrinter<T>::Print(value, ostream_ptr) prints the given
  354. // value to the given ostream. The caller must ensure that
  355. // 'ostream_ptr' is not NULL, or the behavior is undefined.
  356. //
  357. // We define UniversalPrinter as a class template (as opposed to a
  358. // function template), as we need to partially specialize it for
  359. // reference types, which cannot be done with function templates.
  360. template <typename T>
  361. class UniversalPrinter;
  362. template <typename T>
  363. void UniversalPrint(const T& value, ::std::ostream* os);
  364. enum DefaultPrinterType {
  365. kPrintContainer,
  366. kPrintPointer,
  367. kPrintFunctionPointer,
  368. kPrintOther,
  369. };
  370. template <DefaultPrinterType type> struct WrapPrinterType {};
  371. // Used to print an STL-style container when the user doesn't define
  372. // a PrintTo() for it.
  373. template <typename C>
  374. void DefaultPrintTo(WrapPrinterType<kPrintContainer> /* dummy */,
  375. const C& container, ::std::ostream* os) {
  376. const size_t kMaxCount = 32; // The maximum number of elements to print.
  377. *os << '{';
  378. size_t count = 0;
  379. for (typename C::const_iterator it = container.begin();
  380. it != container.end(); ++it, ++count) {
  381. if (count > 0) {
  382. *os << ',';
  383. if (count == kMaxCount) { // Enough has been printed.
  384. *os << " ...";
  385. break;
  386. }
  387. }
  388. *os << ' ';
  389. // We cannot call PrintTo(*it, os) here as PrintTo() doesn't
  390. // handle *it being a native array.
  391. internal::UniversalPrint(*it, os);
  392. }
  393. if (count > 0) {
  394. *os << ' ';
  395. }
  396. *os << '}';
  397. }
  398. // Used to print a pointer that is neither a char pointer nor a member
  399. // pointer, when the user doesn't define PrintTo() for it. (A member
  400. // variable pointer or member function pointer doesn't really point to
  401. // a location in the address space. Their representation is
  402. // implementation-defined. Therefore they will be printed as raw
  403. // bytes.)
  404. template <typename T>
  405. void DefaultPrintTo(WrapPrinterType<kPrintPointer> /* dummy */,
  406. T* p, ::std::ostream* os) {
  407. if (p == NULL) {
  408. *os << "NULL";
  409. } else {
  410. // T is not a function type. We just call << to print p,
  411. // relying on ADL to pick up user-defined << for their pointer
  412. // types, if any.
  413. *os << p;
  414. }
  415. }
  416. template <typename T>
  417. void DefaultPrintTo(WrapPrinterType<kPrintFunctionPointer> /* dummy */,
  418. T* p, ::std::ostream* os) {
  419. if (p == NULL) {
  420. *os << "NULL";
  421. } else {
  422. // T is a function type, so '*os << p' doesn't do what we want
  423. // (it just prints p as bool). We want to print p as a const
  424. // void*.
  425. *os << reinterpret_cast<const void*>(p);
  426. }
  427. }
  428. // Used to print a non-container, non-pointer value when the user
  429. // doesn't define PrintTo() for it.
  430. template <typename T>
  431. void DefaultPrintTo(WrapPrinterType<kPrintOther> /* dummy */,
  432. const T& value, ::std::ostream* os) {
  433. ::testing_internal::DefaultPrintNonContainerTo(value, os);
  434. }
  435. // Prints the given value using the << operator if it has one;
  436. // otherwise prints the bytes in it. This is what
  437. // UniversalPrinter<T>::Print() does when PrintTo() is not specialized
  438. // or overloaded for type T.
  439. //
  440. // A user can override this behavior for a class type Foo by defining
  441. // an overload of PrintTo() in the namespace where Foo is defined. We
  442. // give the user this option as sometimes defining a << operator for
  443. // Foo is not desirable (e.g. the coding style may prevent doing it,
  444. // or there is already a << operator but it doesn't do what the user
  445. // wants).
  446. template <typename T>
  447. void PrintTo(const T& value, ::std::ostream* os) {
  448. // DefaultPrintTo() is overloaded. The type of its first argument
  449. // determines which version will be picked.
  450. //
  451. // Note that we check for container types here, prior to we check
  452. // for protocol message types in our operator<<. The rationale is:
  453. //
  454. // For protocol messages, we want to give people a chance to
  455. // override Google Mock's format by defining a PrintTo() or
  456. // operator<<. For STL containers, other formats can be
  457. // incompatible with Google Mock's format for the container
  458. // elements; therefore we check for container types here to ensure
  459. // that our format is used.
  460. //
  461. // Note that MSVC and clang-cl do allow an implicit conversion from
  462. // pointer-to-function to pointer-to-object, but clang-cl warns on it.
  463. // So don't use ImplicitlyConvertible if it can be helped since it will
  464. // cause this warning, and use a separate overload of DefaultPrintTo for
  465. // function pointers so that the `*os << p` in the object pointer overload
  466. // doesn't cause that warning either.
  467. DefaultPrintTo(
  468. WrapPrinterType <
  469. (sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) &&
  470. !IsRecursiveContainer<T>::value
  471. ? kPrintContainer
  472. : !is_pointer<T>::value
  473. ? kPrintOther
  474. #if GTEST_LANG_CXX11
  475. : std::is_function<typename std::remove_pointer<T>::type>::value
  476. #else
  477. : !internal::ImplicitlyConvertible<T, const void*>::value
  478. #endif
  479. ? kPrintFunctionPointer
  480. : kPrintPointer > (),
  481. value, os);
  482. }
  483. // The following list of PrintTo() overloads tells
  484. // UniversalPrinter<T>::Print() how to print standard types (built-in
  485. // types, strings, plain arrays, and pointers).
  486. // Overloads for various char types.
  487. GTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os);
  488. GTEST_API_ void PrintTo(signed char c, ::std::ostream* os);
  489. inline void PrintTo(char c, ::std::ostream* os) {
  490. // When printing a plain char, we always treat it as unsigned. This
  491. // way, the output won't be affected by whether the compiler thinks
  492. // char is signed or not.
  493. PrintTo(static_cast<unsigned char>(c), os);
  494. }
  495. // Overloads for other simple built-in types.
  496. inline void PrintTo(bool x, ::std::ostream* os) {
  497. *os << (x ? "true" : "false");
  498. }
  499. // Overload for wchar_t type.
  500. // Prints a wchar_t as a symbol if it is printable or as its internal
  501. // code otherwise and also as its decimal code (except for L'\0').
  502. // The L'\0' char is printed as "L'\\0'". The decimal code is printed
  503. // as signed integer when wchar_t is implemented by the compiler
  504. // as a signed type and is printed as an unsigned integer when wchar_t
  505. // is implemented as an unsigned type.
  506. GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os);
  507. // Overloads for C strings.
  508. GTEST_API_ void PrintTo(const char* s, ::std::ostream* os);
  509. inline void PrintTo(char* s, ::std::ostream* os) {
  510. PrintTo(ImplicitCast_<const char*>(s), os);
  511. }
  512. // signed/unsigned char is often used for representing binary data, so
  513. // we print pointers to it as void* to be safe.
  514. inline void PrintTo(const signed char* s, ::std::ostream* os) {
  515. PrintTo(ImplicitCast_<const void*>(s), os);
  516. }
  517. inline void PrintTo(signed char* s, ::std::ostream* os) {
  518. PrintTo(ImplicitCast_<const void*>(s), os);
  519. }
  520. inline void PrintTo(const unsigned char* s, ::std::ostream* os) {
  521. PrintTo(ImplicitCast_<const void*>(s), os);
  522. }
  523. inline void PrintTo(unsigned char* s, ::std::ostream* os) {
  524. PrintTo(ImplicitCast_<const void*>(s), os);
  525. }
  526. // MSVC can be configured to define wchar_t as a typedef of unsigned
  527. // short. It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native
  528. // type. When wchar_t is a typedef, defining an overload for const
  529. // wchar_t* would cause unsigned short* be printed as a wide string,
  530. // possibly causing invalid memory accesses.
  531. #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
  532. // Overloads for wide C strings
  533. GTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os);
  534. inline void PrintTo(wchar_t* s, ::std::ostream* os) {
  535. PrintTo(ImplicitCast_<const wchar_t*>(s), os);
  536. }
  537. #endif
  538. // Overload for C arrays. Multi-dimensional arrays are printed
  539. // properly.
  540. // Prints the given number of elements in an array, without printing
  541. // the curly braces.
  542. template <typename T>
  543. void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) {
  544. UniversalPrint(a[0], os);
  545. for (size_t i = 1; i != count; i++) {
  546. *os << ", ";
  547. UniversalPrint(a[i], os);
  548. }
  549. }
  550. // Overloads for ::string and ::std::string.
  551. #if GTEST_HAS_GLOBAL_STRING
  552. GTEST_API_ void PrintStringTo(const ::string&s, ::std::ostream* os);
  553. inline void PrintTo(const ::string& s, ::std::ostream* os) {
  554. PrintStringTo(s, os);
  555. }
  556. #endif // GTEST_HAS_GLOBAL_STRING
  557. GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os);
  558. inline void PrintTo(const ::std::string& s, ::std::ostream* os) {
  559. PrintStringTo(s, os);
  560. }
  561. // Overloads for ::wstring and ::std::wstring.
  562. #if GTEST_HAS_GLOBAL_WSTRING
  563. GTEST_API_ void PrintWideStringTo(const ::wstring&s, ::std::ostream* os);
  564. inline void PrintTo(const ::wstring& s, ::std::ostream* os) {
  565. PrintWideStringTo(s, os);
  566. }
  567. #endif // GTEST_HAS_GLOBAL_WSTRING
  568. #if GTEST_HAS_STD_WSTRING
  569. GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os);
  570. inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
  571. PrintWideStringTo(s, os);
  572. }
  573. #endif // GTEST_HAS_STD_WSTRING
  574. #if GTEST_HAS_ABSL
  575. // Overload for absl::string_view.
  576. inline void PrintTo(absl::string_view sp, ::std::ostream* os) {
  577. PrintTo(::std::string(sp), os);
  578. }
  579. #endif // GTEST_HAS_ABSL
  580. #if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_
  581. // Helper function for printing a tuple. T must be instantiated with
  582. // a tuple type.
  583. template <typename T>
  584. void PrintTupleTo(const T& t, ::std::ostream* os);
  585. #endif // GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_
  586. #if GTEST_HAS_TR1_TUPLE
  587. // Overload for ::std::tr1::tuple. Needed for printing function arguments,
  588. // which are packed as tuples.
  589. // Overloaded PrintTo() for tuples of various arities. We support
  590. // tuples of up-to 10 fields. The following implementation works
  591. // regardless of whether tr1::tuple is implemented using the
  592. // non-standard variadic template feature or not.
  593. inline void PrintTo(const ::std::tr1::tuple<>& t, ::std::ostream* os) {
  594. PrintTupleTo(t, os);
  595. }
  596. template <typename T1>
  597. void PrintTo(const ::std::tr1::tuple<T1>& t, ::std::ostream* os) {
  598. PrintTupleTo(t, os);
  599. }
  600. template <typename T1, typename T2>
  601. void PrintTo(const ::std::tr1::tuple<T1, T2>& t, ::std::ostream* os) {
  602. PrintTupleTo(t, os);
  603. }
  604. template <typename T1, typename T2, typename T3>
  605. void PrintTo(const ::std::tr1::tuple<T1, T2, T3>& t, ::std::ostream* os) {
  606. PrintTupleTo(t, os);
  607. }
  608. template <typename T1, typename T2, typename T3, typename T4>
  609. void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4>& t, ::std::ostream* os) {
  610. PrintTupleTo(t, os);
  611. }
  612. template <typename T1, typename T2, typename T3, typename T4, typename T5>
  613. void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5>& t,
  614. ::std::ostream* os) {
  615. PrintTupleTo(t, os);
  616. }
  617. template <typename T1, typename T2, typename T3, typename T4, typename T5,
  618. typename T6>
  619. void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6>& t,
  620. ::std::ostream* os) {
  621. PrintTupleTo(t, os);
  622. }
  623. template <typename T1, typename T2, typename T3, typename T4, typename T5,
  624. typename T6, typename T7>
  625. void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7>& t,
  626. ::std::ostream* os) {
  627. PrintTupleTo(t, os);
  628. }
  629. template <typename T1, typename T2, typename T3, typename T4, typename T5,
  630. typename T6, typename T7, typename T8>
  631. void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8>& t,
  632. ::std::ostream* os) {
  633. PrintTupleTo(t, os);
  634. }
  635. template <typename T1, typename T2, typename T3, typename T4, typename T5,
  636. typename T6, typename T7, typename T8, typename T9>
  637. void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9>& t,
  638. ::std::ostream* os) {
  639. PrintTupleTo(t, os);
  640. }
  641. template <typename T1, typename T2, typename T3, typename T4, typename T5,
  642. typename T6, typename T7, typename T8, typename T9, typename T10>
  643. void PrintTo(
  644. const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>& t,
  645. ::std::ostream* os) {
  646. PrintTupleTo(t, os);
  647. }
  648. #endif // GTEST_HAS_TR1_TUPLE
  649. #if GTEST_HAS_STD_TUPLE_
  650. template <typename... Types>
  651. void PrintTo(const ::std::tuple<Types...>& t, ::std::ostream* os) {
  652. PrintTupleTo(t, os);
  653. }
  654. #endif // GTEST_HAS_STD_TUPLE_
  655. // Overload for std::pair.
  656. template <typename T1, typename T2>
  657. void PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) {
  658. *os << '(';
  659. // We cannot use UniversalPrint(value.first, os) here, as T1 may be
  660. // a reference type. The same for printing value.second.
  661. UniversalPrinter<T1>::Print(value.first, os);
  662. *os << ", ";
  663. UniversalPrinter<T2>::Print(value.second, os);
  664. *os << ')';
  665. }
  666. // Implements printing a non-reference type T by letting the compiler
  667. // pick the right overload of PrintTo() for T.
  668. template <typename T>
  669. class UniversalPrinter {
  670. public:
  671. // MSVC warns about adding const to a function type, so we want to
  672. // disable the warning.
  673. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
  674. // Note: we deliberately don't call this PrintTo(), as that name
  675. // conflicts with ::testing::internal::PrintTo in the body of the
  676. // function.
  677. static void Print(const T& value, ::std::ostream* os) {
  678. // By default, ::testing::internal::PrintTo() is used for printing
  679. // the value.
  680. //
  681. // Thanks to Koenig look-up, if T is a class and has its own
  682. // PrintTo() function defined in its namespace, that function will
  683. // be visible here. Since it is more specific than the generic ones
  684. // in ::testing::internal, it will be picked by the compiler in the
  685. // following statement - exactly what we want.
  686. PrintTo(value, os);
  687. }
  688. GTEST_DISABLE_MSC_WARNINGS_POP_()
  689. };
  690. #if GTEST_HAS_ABSL
  691. // Printer for absl::optional
  692. template <typename T>
  693. class UniversalPrinter<::absl::optional<T>> {
  694. public:
  695. static void Print(const ::absl::optional<T>& value, ::std::ostream* os) {
  696. *os << '(';
  697. if (!value) {
  698. *os << "nullopt";
  699. } else {
  700. UniversalPrint(*value, os);
  701. }
  702. *os << ')';
  703. }
  704. };
  705. #endif // GTEST_HAS_ABSL
  706. // UniversalPrintArray(begin, len, os) prints an array of 'len'
  707. // elements, starting at address 'begin'.
  708. template <typename T>
  709. void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
  710. if (len == 0) {
  711. *os << "{}";
  712. } else {
  713. *os << "{ ";
  714. const size_t kThreshold = 18;
  715. const size_t kChunkSize = 8;
  716. // If the array has more than kThreshold elements, we'll have to
  717. // omit some details by printing only the first and the last
  718. // kChunkSize elements.
  719. // TODO(wan@google.com): let the user control the threshold using a flag.
  720. if (len <= kThreshold) {
  721. PrintRawArrayTo(begin, len, os);
  722. } else {
  723. PrintRawArrayTo(begin, kChunkSize, os);
  724. *os << ", ..., ";
  725. PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os);
  726. }
  727. *os << " }";
  728. }
  729. }
  730. // This overload prints a (const) char array compactly.
  731. GTEST_API_ void UniversalPrintArray(
  732. const char* begin, size_t len, ::std::ostream* os);
  733. // This overload prints a (const) wchar_t array compactly.
  734. GTEST_API_ void UniversalPrintArray(
  735. const wchar_t* begin, size_t len, ::std::ostream* os);
  736. // Implements printing an array type T[N].
  737. template <typename T, size_t N>
  738. class UniversalPrinter<T[N]> {
  739. public:
  740. // Prints the given array, omitting some elements when there are too
  741. // many.
  742. static void Print(const T (&a)[N], ::std::ostream* os) {
  743. UniversalPrintArray(a, N, os);
  744. }
  745. };
  746. // Implements printing a reference type T&.
  747. template <typename T>
  748. class UniversalPrinter<T&> {
  749. public:
  750. // MSVC warns about adding const to a function type, so we want to
  751. // disable the warning.
  752. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
  753. static void Print(const T& value, ::std::ostream* os) {
  754. // Prints the address of the value. We use reinterpret_cast here
  755. // as static_cast doesn't compile when T is a function type.
  756. *os << "@" << reinterpret_cast<const void*>(&value) << " ";
  757. // Then prints the value itself.
  758. UniversalPrint(value, os);
  759. }
  760. GTEST_DISABLE_MSC_WARNINGS_POP_()
  761. };
  762. // Prints a value tersely: for a reference type, the referenced value
  763. // (but not the address) is printed; for a (const) char pointer, the
  764. // NUL-terminated string (but not the pointer) is printed.
  765. template <typename T>
  766. class UniversalTersePrinter {
  767. public:
  768. static void Print(const T& value, ::std::ostream* os) {
  769. UniversalPrint(value, os);
  770. }
  771. };
  772. template <typename T>
  773. class UniversalTersePrinter<T&> {
  774. public:
  775. static void Print(const T& value, ::std::ostream* os) {
  776. UniversalPrint(value, os);
  777. }
  778. };
  779. template <typename T, size_t N>
  780. class UniversalTersePrinter<T[N]> {
  781. public:
  782. static void Print(const T (&value)[N], ::std::ostream* os) {
  783. UniversalPrinter<T[N]>::Print(value, os);
  784. }
  785. };
  786. template <>
  787. class UniversalTersePrinter<const char*> {
  788. public:
  789. static void Print(const char* str, ::std::ostream* os) {
  790. if (str == NULL) {
  791. *os << "NULL";
  792. } else {
  793. UniversalPrint(std::string(str), os);
  794. }
  795. }
  796. };
  797. template <>
  798. class UniversalTersePrinter<char*> {
  799. public:
  800. static void Print(char* str, ::std::ostream* os) {
  801. UniversalTersePrinter<const char*>::Print(str, os);
  802. }
  803. };
  804. #if GTEST_HAS_STD_WSTRING
  805. template <>
  806. class UniversalTersePrinter<const wchar_t*> {
  807. public:
  808. static void Print(const wchar_t* str, ::std::ostream* os) {
  809. if (str == NULL) {
  810. *os << "NULL";
  811. } else {
  812. UniversalPrint(::std::wstring(str), os);
  813. }
  814. }
  815. };
  816. #endif
  817. template <>
  818. class UniversalTersePrinter<wchar_t*> {
  819. public:
  820. static void Print(wchar_t* str, ::std::ostream* os) {
  821. UniversalTersePrinter<const wchar_t*>::Print(str, os);
  822. }
  823. };
  824. template <typename T>
  825. void UniversalTersePrint(const T& value, ::std::ostream* os) {
  826. UniversalTersePrinter<T>::Print(value, os);
  827. }
  828. // Prints a value using the type inferred by the compiler. The
  829. // difference between this and UniversalTersePrint() is that for a
  830. // (const) char pointer, this prints both the pointer and the
  831. // NUL-terminated string.
  832. template <typename T>
  833. void UniversalPrint(const T& value, ::std::ostream* os) {
  834. // A workarond for the bug in VC++ 7.1 that prevents us from instantiating
  835. // UniversalPrinter with T directly.
  836. typedef T T1;
  837. UniversalPrinter<T1>::Print(value, os);
  838. }
  839. typedef ::std::vector< ::std::string> Strings;
  840. // TuplePolicy<TupleT> must provide:
  841. // - tuple_size
  842. // size of tuple TupleT.
  843. // - get<size_t I>(const TupleT& t)
  844. // static function extracting element I of tuple TupleT.
  845. // - tuple_element<size_t I>::type
  846. // type of element I of tuple TupleT.
  847. template <typename TupleT>
  848. struct TuplePolicy;
  849. #if GTEST_HAS_TR1_TUPLE
  850. template <typename TupleT>
  851. struct TuplePolicy {
  852. typedef TupleT Tuple;
  853. static const size_t tuple_size = ::std::tr1::tuple_size<Tuple>::value;
  854. template <size_t I>
  855. struct tuple_element : ::std::tr1::tuple_element<I, Tuple> {};
  856. template <size_t I>
  857. static typename AddReference<
  858. const typename ::std::tr1::tuple_element<I, Tuple>::type>::type get(
  859. const Tuple& tuple) {
  860. return ::std::tr1::get<I>(tuple);
  861. }
  862. };
  863. template <typename TupleT>
  864. const size_t TuplePolicy<TupleT>::tuple_size;
  865. #endif // GTEST_HAS_TR1_TUPLE
  866. #if GTEST_HAS_STD_TUPLE_
  867. template <typename... Types>
  868. struct TuplePolicy< ::std::tuple<Types...> > {
  869. typedef ::std::tuple<Types...> Tuple;
  870. static const size_t tuple_size = ::std::tuple_size<Tuple>::value;
  871. template <size_t I>
  872. struct tuple_element : ::std::tuple_element<I, Tuple> {};
  873. template <size_t I>
  874. static const typename ::std::tuple_element<I, Tuple>::type& get(
  875. const Tuple& tuple) {
  876. return ::std::get<I>(tuple);
  877. }
  878. };
  879. template <typename... Types>
  880. const size_t TuplePolicy< ::std::tuple<Types...> >::tuple_size;
  881. #endif // GTEST_HAS_STD_TUPLE_
  882. #if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_
  883. // This helper template allows PrintTo() for tuples and
  884. // UniversalTersePrintTupleFieldsToStrings() to be defined by
  885. // induction on the number of tuple fields. The idea is that
  886. // TuplePrefixPrinter<N>::PrintPrefixTo(t, os) prints the first N
  887. // fields in tuple t, and can be defined in terms of
  888. // TuplePrefixPrinter<N - 1>.
  889. //
  890. // The inductive case.
  891. template <size_t N>
  892. struct TuplePrefixPrinter {
  893. // Prints the first N fields of a tuple.
  894. template <typename Tuple>
  895. static void PrintPrefixTo(const Tuple& t, ::std::ostream* os) {
  896. TuplePrefixPrinter<N - 1>::PrintPrefixTo(t, os);
  897. GTEST_INTENTIONAL_CONST_COND_PUSH_()
  898. if (N > 1) {
  899. GTEST_INTENTIONAL_CONST_COND_POP_()
  900. *os << ", ";
  901. }
  902. UniversalPrinter<
  903. typename TuplePolicy<Tuple>::template tuple_element<N - 1>::type>
  904. ::Print(TuplePolicy<Tuple>::template get<N - 1>(t), os);
  905. }
  906. // Tersely prints the first N fields of a tuple to a string vector,
  907. // one element for each field.
  908. template <typename Tuple>
  909. static void TersePrintPrefixToStrings(const Tuple& t, Strings* strings) {
  910. TuplePrefixPrinter<N - 1>::TersePrintPrefixToStrings(t, strings);
  911. ::std::stringstream ss;
  912. UniversalTersePrint(TuplePolicy<Tuple>::template get<N - 1>(t), &ss);
  913. strings->push_back(ss.str());
  914. }
  915. };
  916. // Base case.
  917. template <>
  918. struct TuplePrefixPrinter<0> {
  919. template <typename Tuple>
  920. static void PrintPrefixTo(const Tuple&, ::std::ostream*) {}
  921. template <typename Tuple>
  922. static void TersePrintPrefixToStrings(const Tuple&, Strings*) {}
  923. };
  924. // Helper function for printing a tuple.
  925. // Tuple must be either std::tr1::tuple or std::tuple type.
  926. template <typename Tuple>
  927. void PrintTupleTo(const Tuple& t, ::std::ostream* os) {
  928. *os << "(";
  929. TuplePrefixPrinter<TuplePolicy<Tuple>::tuple_size>::PrintPrefixTo(t, os);
  930. *os << ")";
  931. }
  932. // Prints the fields of a tuple tersely to a string vector, one
  933. // element for each field. See the comment before
  934. // UniversalTersePrint() for how we define "tersely".
  935. template <typename Tuple>
  936. Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {
  937. Strings result;
  938. TuplePrefixPrinter<TuplePolicy<Tuple>::tuple_size>::
  939. TersePrintPrefixToStrings(value, &result);
  940. return result;
  941. }
  942. #endif // GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_
  943. } // namespace internal
  944. #if GTEST_HAS_ABSL
  945. namespace internal2 {
  946. template <typename T>
  947. void TypeWithoutFormatter<T, kConvertibleToStringView>::PrintValue(
  948. const T& value, ::std::ostream* os) {
  949. internal::PrintTo(absl::string_view(value), os);
  950. }
  951. } // namespace internal2
  952. #endif
  953. template <typename T>
  954. ::std::string PrintToString(const T& value) {
  955. ::std::stringstream ss;
  956. internal::UniversalTersePrinter<T>::Print(value, &ss);
  957. return ss.str();
  958. }
  959. } // namespace testing
  960. // Include any custom printer added by the local installation.
  961. // We must include this header at the end to make sure it can use the
  962. // declarations from this file.
  963. #include "gtest/internal/custom/gtest-printers.h"
  964. #endif // GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_