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 Mock - a framework for writing C++ mock classes.
32//
33// This file defines some utilities useful for implementing Google
34// Mock.  They are subject to change without notice, so please DO NOT
35// USE THEM IN USER CODE.
36
37// GOOGLETEST_CM0002 DO NOT DELETE
38
39#ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
40#define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
41
42#include <stdio.h>
43#include <ostream>  // NOLINT
44#include <string>
45#include "gmock/internal/gmock-generated-internal-utils.h"
46#include "gmock/internal/gmock-port.h"
47#include "gtest/gtest.h"
48
49namespace testing {
50namespace internal {
51
52// Silence MSVC C4100 (unreferenced formal parameter) and
53// C4805('==': unsafe mix of type 'const int' and type 'const bool')
54#ifdef _MSC_VER
55# pragma warning(push)
56# pragma warning(disable:4100)
57# pragma warning(disable:4805)
58#endif
59
60// Joins a vector of strings as if they are fields of a tuple; returns
61// the joined string.
62GTEST_API_ std::string JoinAsTuple(const Strings& fields);
63
64// Converts an identifier name to a space-separated list of lower-case
65// words.  Each maximum substring of the form [A-Za-z][a-z]*|\d+ is
66// treated as one word.  For example, both "FooBar123" and
67// "foo_bar_123" are converted to "foo bar 123".
68GTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name);
69
70// PointeeOf<Pointer>::type is the type of a value pointed to by a
71// Pointer, which can be either a smart pointer or a raw pointer.  The
72// following default implementation is for the case where Pointer is a
73// smart pointer.
74template <typename Pointer>
75struct PointeeOf {
76  // Smart pointer classes define type element_type as the type of
77  // their pointees.
78  typedef typename Pointer::element_type type;
79};
80// This specialization is for the raw pointer case.
81template <typename T>
82struct PointeeOf<T*> { typedef T type; };  // NOLINT
83
84// GetRawPointer(p) returns the raw pointer underlying p when p is a
85// smart pointer, or returns p itself when p is already a raw pointer.
86// The following default implementation is for the smart pointer case.
87template <typename Pointer>
88inline const typename Pointer::element_type* GetRawPointer(const Pointer& p) {
89  return p.get();
90}
91// This overloaded version is for the raw pointer case.
92template <typename Element>
93inline Element* GetRawPointer(Element* p) { return p; }
94
95// This comparator allows linked_ptr to be stored in sets.
96template <typename T>
97struct LinkedPtrLessThan {
98  bool operator()(const ::testing::internal::linked_ptr<T>& lhs,
99                  const ::testing::internal::linked_ptr<T>& rhs) const {
100    return lhs.get() < rhs.get();
101  }
102};
103
104// Symbian compilation can be done with wchar_t being either a native
105// type or a typedef.  Using Google Mock with OpenC without wchar_t
106// should require the definition of _STLP_NO_WCHAR_T.
107//
108// MSVC treats wchar_t as a native type usually, but treats it as the
109// same as unsigned short when the compiler option /Zc:wchar_t- is
110// specified.  It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t
111// is a native type.
112#if (GTEST_OS_SYMBIAN && defined(_STLP_NO_WCHAR_T)) || \
113    (defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED))
114// wchar_t is a typedef.
115#else
116# define GMOCK_WCHAR_T_IS_NATIVE_ 1
117#endif
118
119// signed wchar_t and unsigned wchar_t are NOT in the C++ standard.
120// Using them is a bad practice and not portable.  So DON'T use them.
121//
122// Still, Google Mock is designed to work even if the user uses signed
123// wchar_t or unsigned wchar_t (obviously, assuming the compiler
124// supports them).
125//
126// To gcc,
127//   wchar_t == signed wchar_t != unsigned wchar_t == unsigned int
128//
129// gcc-9 appears to treat signed/unsigned wchar_t as ill-formed
130// regardless of the signage of its underlying type.
131#ifdef __GNUC__
132#if !defined(__WCHAR_UNSIGNED__) && (__GNUC__ < 9)
133// signed/unsigned wchar_t are valid types.
134# define GMOCK_HAS_SIGNED_WCHAR_T_ 1
135#endif
136#endif
137
138// In what follows, we use the term "kind" to indicate whether a type
139// is bool, an integer type (excluding bool), a floating-point type,
140// or none of them.  This categorization is useful for determining
141// when a matcher argument type can be safely converted to another
142// type in the implementation of SafeMatcherCast.
143enum TypeKind {
144  kBool, kInteger, kFloatingPoint, kOther
145};
146
147// KindOf<T>::value is the kind of type T.
148template <typename T> struct KindOf {
149  enum { value = kOther };  // The default kind.
150};
151
152// This macro declares that the kind of 'type' is 'kind'.
153#define GMOCK_DECLARE_KIND_(type, kind) \
154  template <> struct KindOf<type> { enum { value = kind }; }
155
156GMOCK_DECLARE_KIND_(bool, kBool);
157
158// All standard integer types.
159GMOCK_DECLARE_KIND_(char, kInteger);
160GMOCK_DECLARE_KIND_(signed char, kInteger);
161GMOCK_DECLARE_KIND_(unsigned char, kInteger);
162GMOCK_DECLARE_KIND_(short, kInteger);  // NOLINT
163GMOCK_DECLARE_KIND_(unsigned short, kInteger);  // NOLINT
164GMOCK_DECLARE_KIND_(int, kInteger);
165GMOCK_DECLARE_KIND_(unsigned int, kInteger);
166GMOCK_DECLARE_KIND_(long, kInteger);  // NOLINT
167GMOCK_DECLARE_KIND_(unsigned long, kInteger);  // NOLINT
168
169#if GMOCK_WCHAR_T_IS_NATIVE_
170GMOCK_DECLARE_KIND_(wchar_t, kInteger);
171#endif
172
173// Non-standard integer types.
174GMOCK_DECLARE_KIND_(Int64, kInteger);
175GMOCK_DECLARE_KIND_(UInt64, kInteger);
176
177// All standard floating-point types.
178GMOCK_DECLARE_KIND_(float, kFloatingPoint);
179GMOCK_DECLARE_KIND_(double, kFloatingPoint);
180GMOCK_DECLARE_KIND_(long double, kFloatingPoint);
181
182#undef GMOCK_DECLARE_KIND_
183
184// Evaluates to the kind of 'type'.
185#define GMOCK_KIND_OF_(type) \
186  static_cast< ::testing::internal::TypeKind>( \
187      ::testing::internal::KindOf<type>::value)
188
189// Evaluates to true iff integer type T is signed.
190#define GMOCK_IS_SIGNED_(T) (static_cast<T>(-1) < 0)
191
192// LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value
193// is true iff arithmetic type From can be losslessly converted to
194// arithmetic type To.
195//
196// It's the user's responsibility to ensure that both From and To are
197// raw (i.e. has no CV modifier, is not a pointer, and is not a
198// reference) built-in arithmetic types, kFromKind is the kind of
199// From, and kToKind is the kind of To; the value is
200// implementation-defined when the above pre-condition is violated.
201template <TypeKind kFromKind, typename From, TypeKind kToKind, typename To>
202struct LosslessArithmeticConvertibleImpl : public false_type {};
203
204// Converting bool to bool is lossless.
205template <>
206struct LosslessArithmeticConvertibleImpl<kBool, bool, kBool, bool>
207    : public true_type {};  // NOLINT
208
209// Converting bool to any integer type is lossless.
210template <typename To>
211struct LosslessArithmeticConvertibleImpl<kBool, bool, kInteger, To>
212    : public true_type {};  // NOLINT
213
214// Converting bool to any floating-point type is lossless.
215template <typename To>
216struct LosslessArithmeticConvertibleImpl<kBool, bool, kFloatingPoint, To>
217    : public true_type {};  // NOLINT
218
219// Converting an integer to bool is lossy.
220template <typename From>
221struct LosslessArithmeticConvertibleImpl<kInteger, From, kBool, bool>
222    : public false_type {};  // NOLINT
223
224// Converting an integer to another non-bool integer is lossless iff
225// the target type's range encloses the source type's range.
226template <typename From, typename To>
227struct LosslessArithmeticConvertibleImpl<kInteger, From, kInteger, To>
228    : public bool_constant<
229      // When converting from a smaller size to a larger size, we are
230      // fine as long as we are not converting from signed to unsigned.
231      ((sizeof(From) < sizeof(To)) &&
232       (!GMOCK_IS_SIGNED_(From) || GMOCK_IS_SIGNED_(To))) ||
233      // When converting between the same size, the signedness must match.
234      ((sizeof(From) == sizeof(To)) &&
235       (GMOCK_IS_SIGNED_(From) == GMOCK_IS_SIGNED_(To)))> {};  // NOLINT
236
237#undef GMOCK_IS_SIGNED_
238
239// Converting an integer to a floating-point type may be lossy, since
240// the format of a floating-point number is implementation-defined.
241template <typename From, typename To>
242struct LosslessArithmeticConvertibleImpl<kInteger, From, kFloatingPoint, To>
243    : public false_type {};  // NOLINT
244
245// Converting a floating-point to bool is lossy.
246template <typename From>
247struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kBool, bool>
248    : public false_type {};  // NOLINT
249
250// Converting a floating-point to an integer is lossy.
251template <typename From, typename To>
252struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kInteger, To>
253    : public false_type {};  // NOLINT
254
255// Converting a floating-point to another floating-point is lossless
256// iff the target type is at least as big as the source type.
257template <typename From, typename To>
258struct LosslessArithmeticConvertibleImpl<
259  kFloatingPoint, From, kFloatingPoint, To>
260    : public bool_constant<sizeof(From) <= sizeof(To)> {};  // NOLINT
261
262// LosslessArithmeticConvertible<From, To>::value is true iff arithmetic
263// type From can be losslessly converted to arithmetic type To.
264//
265// It's the user's responsibility to ensure that both From and To are
266// raw (i.e. has no CV modifier, is not a pointer, and is not a
267// reference) built-in arithmetic types; the value is
268// implementation-defined when the above pre-condition is violated.
269template <typename From, typename To>
270struct LosslessArithmeticConvertible
271    : public LosslessArithmeticConvertibleImpl<
272  GMOCK_KIND_OF_(From), From, GMOCK_KIND_OF_(To), To> {};  // NOLINT
273
274// This interface knows how to report a Google Mock failure (either
275// non-fatal or fatal).
276class FailureReporterInterface {
277 public:
278  // The type of a failure (either non-fatal or fatal).
279  enum FailureType {
280    kNonfatal, kFatal
281  };
282
283  virtual ~FailureReporterInterface() {}
284
285  // Reports a failure that occurred at the given source file location.
286  virtual void ReportFailure(FailureType type, const char* file, int line,
287                             const std::string& message) = 0;
288};
289
290// Returns the failure reporter used by Google Mock.
291GTEST_API_ FailureReporterInterface* GetFailureReporter();
292
293// Asserts that condition is true; aborts the process with the given
294// message if condition is false.  We cannot use LOG(FATAL) or CHECK()
295// as Google Mock might be used to mock the log sink itself.  We
296// inline this function to prevent it from showing up in the stack
297// trace.
298inline void Assert(bool condition, const char* file, int line,
299                   const std::string& msg) {
300  if (!condition) {
301    GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal,
302                                        file, line, msg);
303  }
304}
305inline void Assert(bool condition, const char* file, int line) {
306  Assert(condition, file, line, "Assertion failed.");
307}
308
309// Verifies that condition is true; generates a non-fatal failure if
310// condition is false.
311inline void Expect(bool condition, const char* file, int line,
312                   const std::string& msg) {
313  if (!condition) {
314    GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal,
315                                        file, line, msg);
316  }
317}
318inline void Expect(bool condition, const char* file, int line) {
319  Expect(condition, file, line, "Expectation failed.");
320}
321
322// Severity level of a log.
323enum LogSeverity {
324  kInfo = 0,
325  kWarning = 1
326};
327
328// Valid values for the --gmock_verbose flag.
329
330// All logs (informational and warnings) are printed.
331const char kInfoVerbosity[] = "info";
332// Only warnings are printed.
333const char kWarningVerbosity[] = "warning";
334// No logs are printed.
335const char kErrorVerbosity[] = "error";
336
337// Returns true iff a log with the given severity is visible according
338// to the --gmock_verbose flag.
339GTEST_API_ bool LogIsVisible(LogSeverity severity);
340
341// Prints the given message to stdout iff 'severity' >= the level
342// specified by the --gmock_verbose flag.  If stack_frames_to_skip >=
343// 0, also prints the stack trace excluding the top
344// stack_frames_to_skip frames.  In opt mode, any positive
345// stack_frames_to_skip is treated as 0, since we don't know which
346// function calls will be inlined by the compiler and need to be
347// conservative.
348GTEST_API_ void Log(LogSeverity severity, const std::string& message,
349                    int stack_frames_to_skip);
350
351// A marker class that is used to resolve parameterless expectations to the
352// correct overload. This must not be instantiable, to prevent client code from
353// accidentally resolving to the overload; for example:
354//
355//    ON_CALL(mock, Method({}, nullptr))...
356//
357class WithoutMatchers {
358 private:
359  WithoutMatchers() {}
360  friend GTEST_API_ WithoutMatchers GetWithoutMatchers();
361};
362
363// Internal use only: access the singleton instance of WithoutMatchers.
364GTEST_API_ WithoutMatchers GetWithoutMatchers();
365
366// FIXME: group all type utilities together.
367
368// Type traits.
369
370// is_reference<T>::value is non-zero iff T is a reference type.
371template <typename T> struct is_reference : public false_type {};
372template <typename T> struct is_reference<T&> : public true_type {};
373
374// type_equals<T1, T2>::value is non-zero iff T1 and T2 are the same type.
375template <typename T1, typename T2> struct type_equals : public false_type {};
376template <typename T> struct type_equals<T, T> : public true_type {};
377
378// remove_reference<T>::type removes the reference from type T, if any.
379template <typename T> struct remove_reference { typedef T type; };  // NOLINT
380template <typename T> struct remove_reference<T&> { typedef T type; }; // NOLINT
381
382// DecayArray<T>::type turns an array type U[N] to const U* and preserves
383// other types.  Useful for saving a copy of a function argument.
384template <typename T> struct DecayArray { typedef T type; };  // NOLINT
385template <typename T, size_t N> struct DecayArray<T[N]> {
386  typedef const T* type;
387};
388// Sometimes people use arrays whose size is not available at the use site
389// (e.g. extern const char kNamePrefix[]).  This specialization covers that
390// case.
391template <typename T> struct DecayArray<T[]> {
392  typedef const T* type;
393};
394
395// Disable MSVC warnings for infinite recursion, since in this case the
396// the recursion is unreachable.
397#ifdef _MSC_VER
398# pragma warning(push)
399# pragma warning(disable:4717)
400#endif
401
402// Invalid<T>() is usable as an expression of type T, but will terminate
403// the program with an assertion failure if actually run.  This is useful
404// when a value of type T is needed for compilation, but the statement
405// will not really be executed (or we don't care if the statement
406// crashes).
407template <typename T>
408inline T Invalid() {
409  Assert(false, "", -1, "Internal error: attempt to return invalid value");
410  // This statement is unreachable, and would never terminate even if it
411  // could be reached. It is provided only to placate compiler warnings
412  // about missing return statements.
413  return Invalid<T>();
414}
415
416#ifdef _MSC_VER
417# pragma warning(pop)
418#endif
419
420// Given a raw type (i.e. having no top-level reference or const
421// modifier) RawContainer that's either an STL-style container or a
422// native array, class StlContainerView<RawContainer> has the
423// following members:
424//
425//   - type is a type that provides an STL-style container view to
426//     (i.e. implements the STL container concept for) RawContainer;
427//   - const_reference is a type that provides a reference to a const
428//     RawContainer;
429//   - ConstReference(raw_container) returns a const reference to an STL-style
430//     container view to raw_container, which is a RawContainer.
431//   - Copy(raw_container) returns an STL-style container view of a
432//     copy of raw_container, which is a RawContainer.
433//
434// This generic version is used when RawContainer itself is already an
435// STL-style container.
436template <class RawContainer>
437class StlContainerView {
438 public:
439  typedef RawContainer type;
440  typedef const type& const_reference;
441
442  static const_reference ConstReference(const RawContainer& container) {
443    // Ensures that RawContainer is not a const type.
444    testing::StaticAssertTypeEq<RawContainer,
445        GTEST_REMOVE_CONST_(RawContainer)>();
446    return container;
447  }
448  static type Copy(const RawContainer& container) { return container; }
449};
450
451// This specialization is used when RawContainer is a native array type.
452template <typename Element, size_t N>
453class StlContainerView<Element[N]> {
454 public:
455  typedef GTEST_REMOVE_CONST_(Element) RawElement;
456  typedef internal::NativeArray<RawElement> type;
457  // NativeArray<T> can represent a native array either by value or by
458  // reference (selected by a constructor argument), so 'const type'
459  // can be used to reference a const native array.  We cannot
460  // 'typedef const type& const_reference' here, as that would mean
461  // ConstReference() has to return a reference to a local variable.
462  typedef const type const_reference;
463
464  static const_reference ConstReference(const Element (&array)[N]) {
465    // Ensures that Element is not a const type.
466    testing::StaticAssertTypeEq<Element, RawElement>();
467#if GTEST_OS_SYMBIAN
468    // The Nokia Symbian compiler confuses itself in template instantiation
469    // for this call without the cast to Element*:
470    // function call '[testing::internal::NativeArray<char *>].NativeArray(
471    //     {lval} const char *[4], long, testing::internal::RelationToSource)'
472    //     does not match
473    // 'testing::internal::NativeArray<char *>::NativeArray(
474    //     char *const *, unsigned int, testing::internal::RelationToSource)'
475    // (instantiating: 'testing::internal::ContainsMatcherImpl
476    //     <const char * (&)[4]>::Matches(const char * (&)[4]) const')
477    // (instantiating: 'testing::internal::StlContainerView<char *[4]>::
478    //     ConstReference(const char * (&)[4])')
479    // (and though the N parameter type is mismatched in the above explicit
480    // conversion of it doesn't help - only the conversion of the array).
481    return type(const_cast<Element*>(&array[0]), N,
482                RelationToSourceReference());
483#else
484    return type(array, N, RelationToSourceReference());
485#endif  // GTEST_OS_SYMBIAN
486  }
487  static type Copy(const Element (&array)[N]) {
488#if GTEST_OS_SYMBIAN
489    return type(const_cast<Element*>(&array[0]), N, RelationToSourceCopy());
490#else
491    return type(array, N, RelationToSourceCopy());
492#endif  // GTEST_OS_SYMBIAN
493  }
494};
495
496// This specialization is used when RawContainer is a native array
497// represented as a (pointer, size) tuple.
498template <typename ElementPointer, typename Size>
499class StlContainerView< ::testing::tuple<ElementPointer, Size> > {
500 public:
501  typedef GTEST_REMOVE_CONST_(
502      typename internal::PointeeOf<ElementPointer>::type) RawElement;
503  typedef internal::NativeArray<RawElement> type;
504  typedef const type const_reference;
505
506  static const_reference ConstReference(
507      const ::testing::tuple<ElementPointer, Size>& array) {
508    return type(get<0>(array), get<1>(array), RelationToSourceReference());
509  }
510  static type Copy(const ::testing::tuple<ElementPointer, Size>& array) {
511    return type(get<0>(array), get<1>(array), RelationToSourceCopy());
512  }
513};
514
515// The following specialization prevents the user from instantiating
516// StlContainer with a reference type.
517template <typename T> class StlContainerView<T&>;
518
519// A type transform to remove constness from the first part of a pair.
520// Pairs like that are used as the value_type of associative containers,
521// and this transform produces a similar but assignable pair.
522template <typename T>
523struct RemoveConstFromKey {
524  typedef T type;
525};
526
527// Partially specialized to remove constness from std::pair<const K, V>.
528template <typename K, typename V>
529struct RemoveConstFromKey<std::pair<const K, V> > {
530  typedef std::pair<K, V> type;
531};
532
533// Mapping from booleans to types. Similar to boost::bool_<kValue> and
534// std::integral_constant<bool, kValue>.
535template <bool kValue>
536struct BooleanConstant {};
537
538// Emit an assertion failure due to incorrect DoDefault() usage. Out-of-lined to
539// reduce code size.
540GTEST_API_ void IllegalDoDefault(const char* file, int line);
541
542#if GTEST_LANG_CXX11
543// Helper types for Apply() below.
544template <size_t... Is> struct int_pack { typedef int_pack type; };
545
546template <class Pack, size_t I> struct append;
547template <size_t... Is, size_t I>
548struct append<int_pack<Is...>, I> : int_pack<Is..., I> {};
549
550template <size_t C>
551struct make_int_pack : append<typename make_int_pack<C - 1>::type, C - 1> {};
552template <> struct make_int_pack<0> : int_pack<> {};
553
554template <typename F, typename Tuple, size_t... Idx>
555auto ApplyImpl(F&& f, Tuple&& args, int_pack<Idx...>) -> decltype(
556    std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...)) {
557  return std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...);
558}
559
560// Apply the function to a tuple of arguments.
561template <typename F, typename Tuple>
562auto Apply(F&& f, Tuple&& args)
563    -> decltype(ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
564                          make_int_pack<std::tuple_size<Tuple>::value>())) {
565  return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),
566                   make_int_pack<std::tuple_size<Tuple>::value>());
567}
568#endif
569
570
571#ifdef _MSC_VER
572# pragma warning(pop)
573#endif
574
575}  // namespace internal
576}  // namespace testing
577
578#endif  // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
579