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