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